controller.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. extern "C" {
  2. #include <event2/listener.h>
  3. #include <event2/bufferevent.h>
  4. #include <event2/buffer.h>
  5. }
  6. #include <NTL/vec_ZZ.h>
  7. #include <NTL/ZZ.h>
  8. #include <NTL/ZZ_p.h>
  9. #include <sys/socket.h>
  10. #include <netinet/in.h>
  11. #include <arpa/inet.h>
  12. #include <sys/time.h>
  13. #include <fstream>
  14. #include <vector>
  15. #include <set>
  16. #include <map>
  17. #include <string.h>
  18. #include "evutils.h"
  19. #include "subproblem.h"
  20. #include "controller.h"
  21. NTL_CLIENT
  22. // #undef VERBOSE
  23. struct SubproblemProgress;
  24. typedef std::set<struct bufferevent *> BESet;
  25. typedef std::map<struct bufferevent *, SubproblemProgress *> BEMap;
  26. static void besetdump(const BESet &bes, ostream &os)
  27. {
  28. BESet::const_iterator besit;
  29. os << hex << " ";
  30. for (besit = bes.begin(); besit != bes.end(); ++besit) {
  31. os << *besit << " ";
  32. }
  33. os << dec << "\n";
  34. }
  35. static void besetfree(BESet &bes)
  36. {
  37. BESet::iterator besit;
  38. for (besit = bes.begin(); besit != bes.end(); ++besit) {
  39. bufferevent_free(*besit);
  40. }
  41. bes.clear();
  42. }
  43. static void bemapdump(const BEMap &bem, ostream &os)
  44. {
  45. BEMap::const_iterator bemit;
  46. os << hex << " ";
  47. for (bemit = bem.begin(); bemit != bem.end(); ++bemit) {
  48. os << bemit->first << "->" << bemit->second << " ";
  49. }
  50. os << dec << "\n";
  51. }
  52. static void bemapfree(BEMap &bem)
  53. {
  54. BEMap::iterator bemit;
  55. for (bemit = bem.begin(); bemit != bem.end(); ++bemit) {
  56. bufferevent_free(bemit->first);
  57. }
  58. bem.clear();
  59. }
  60. struct Statuses {
  61. BESet idle;
  62. BEMap working;
  63. // Dump the state for debug purposes
  64. void dump(ostream &os) const {
  65. os << " idle (" << idle.size() << "):\n";
  66. besetdump(idle, os);
  67. os << " working (" << working.size() << "):\n";
  68. bemapdump(working, os);
  69. }
  70. void free(void) {
  71. besetfree(idle);
  72. bemapfree(working);
  73. }
  74. };
  75. struct FactorDecomp {
  76. ZZ factor;
  77. vec_ZZ fvec;
  78. };
  79. static void vsppdump(const vector<SubproblemProgress> &spv, ostream &os);
  80. static struct ControllerState {
  81. ZZ rho;
  82. FactorDecomp p, q;
  83. ZZ base, target;
  84. bool working;
  85. struct timeval started_working;
  86. vector<SubproblemProgress> subproblems_p, subproblems_q;
  87. Statuses dpnodes, workers;
  88. unsigned int num_unsolved_subproblems;
  89. Worklist worklist;
  90. struct evconnlistener *listener;
  91. ControllerState() : working(false), num_unsolved_subproblems(0),
  92. listener(NULL) {}
  93. // Reset the state for a new problem with the same modulus
  94. void reset(void) {
  95. base = 0;
  96. target = 0;
  97. working = false;
  98. subproblems_p.clear();
  99. subproblems_q.clear();
  100. num_unsolved_subproblems = 0;
  101. started_working.tv_sec = 0;
  102. started_working.tv_usec = 0;
  103. }
  104. // Dump the state for debug purposes
  105. void dump(ostream &os) const {
  106. if (!working) {
  107. os << "Not working\n";
  108. return;
  109. }
  110. os << "P:\n";
  111. vsppdump(subproblems_p, os);
  112. os << "Q:\n";
  113. vsppdump(subproblems_q, os);
  114. os << "dpnodes:\n";
  115. dpnodes.dump(os);
  116. os << "workers:\n";
  117. workers.dump(os);
  118. }
  119. } ctrlstate;
  120. struct IPPort {
  121. unsigned char ipport[6];
  122. IPPort(unsigned char *ipp) {
  123. memmove(ipport, ipp, 6);
  124. }
  125. void dump(ostream &os) const {
  126. os << int(ipport[0]) << "." << int(ipport[1]) << "." <<
  127. int(ipport[2]) << "." << int(ipport[3]) << ":" <<
  128. ((ipport[4] << 8) + ipport[5]) << " ";
  129. }
  130. };
  131. typedef vector<IPPort> IPPortSet;
  132. static void ipportsetdump(const IPPortSet &ipps, ostream &os)
  133. {
  134. IPPortSet::const_iterator ippsit;
  135. os << " ";
  136. for (ippsit = ipps.begin(); ippsit != ipps.end(); ++ippsit) {
  137. ippsit->dump(os);
  138. }
  139. os << "\n";
  140. }
  141. void desired_resources(const ZZ &order, unsigned short &desired_dpnodes,
  142. unsigned int &max_workers, unsigned int &dpfreq);
  143. struct SubproblemProgress : Subproblem {
  144. // The sets of dpnodes and workers currently working on this subproblem
  145. BESet dpnodes, workers;
  146. // The dpnode IPPorts registered for this subproblem
  147. IPPortSet ipports;
  148. // The desired number of DPnodes for this subproblem
  149. unsigned short desired_dpnodes;
  150. // The maximum number of workers useful for this subproblem
  151. unsigned int max_workers;
  152. // Have we found a solution?
  153. bool solved;
  154. // The solution, if found.
  155. ZZ solution;
  156. SubproblemProgress(unsigned short id, const ZZ &b, const ZZ &t,
  157. const ZZ &m, const ZZ &o) :
  158. // By default, 1 in 1000 points are distinguihed points. The
  159. // number in the next line is 2^32/1000
  160. Subproblem(id, b, t, m, o, 4294967), solved(false) {
  161. desired_resources(order, desired_dpnodes, max_workers, dpfreq);
  162. // We need to update the binary description of the subproblem,
  163. // as we may have just changed dpfreq.
  164. updatedesc();
  165. }
  166. // Stop all dpnodes and workers
  167. void stop(void) {
  168. BESet::iterator iter;
  169. unsigned char stopcmd[1] = { 'S' };
  170. for (BESet::iterator iter = dpnodes.begin(); iter != dpnodes.end();
  171. ++iter) {
  172. bufferevent_write(*iter, stopcmd, 1);
  173. ctrlstate.dpnodes.working.erase(*iter);
  174. ctrlstate.dpnodes.idle.insert(*iter);
  175. }
  176. for (BESet::iterator iter = workers.begin(); iter != workers.end();
  177. ++iter) {
  178. bufferevent_write(*iter, stopcmd, 1);
  179. ctrlstate.workers.working.erase(*iter);
  180. ctrlstate.workers.idle.insert(*iter);
  181. }
  182. dpnodes.clear();
  183. workers.clear();
  184. ipports.clear();
  185. }
  186. // Dump for debugging purposes
  187. void dump(ostream &os) const {
  188. os << " Subproblem " << problemid << "\n";
  189. os << " dpnodes (" << dpnodes.size() << "):\n";
  190. besetdump(dpnodes, os);
  191. os << " workers (" << workers.size() << "):\n";
  192. besetdump(workers, os);
  193. os << " ipports (" << ipports.size() << "):\n";
  194. ipportsetdump(ipports, os);
  195. if (solved) {
  196. os << " solution: " << solution << "\n\n";
  197. }
  198. }
  199. void worker_write(struct bufferevent *bev) {
  200. bev_write(bev);
  201. unsigned short num_ipports = ipports.size();
  202. bufferevent_write(bev, &num_ipports, 2);
  203. for (unsigned short i = 0; i < num_ipports; ++i) {
  204. bufferevent_write(bev, ipports[i].ipport, 6);
  205. }
  206. #ifdef VERBOSE
  207. cerr << "Added worker " << bev << " to subproblem "
  208. << problemid << "\n";
  209. #endif
  210. }
  211. };
  212. // Dump the state for debug purposes
  213. static void vsppdump(const vector<SubproblemProgress> &spv, ostream &os)
  214. {
  215. vector<SubproblemProgress>::const_iterator spiter;
  216. int count = 0;
  217. for (spiter = spv.begin(); spiter != spv.end(); ++spiter) {
  218. ++count;
  219. os << " " << count << ":\n";
  220. spiter->dump(os);
  221. }
  222. os << "\n";
  223. }
  224. // Find a subproblem in the given vector that could use another DPnode,
  225. // and give it one of the idle ones. Only allocate it to a subproblem
  226. // with no current DPnodes if consider_empty is true.
  227. static void find_subproblem_for_dpnode(vector<SubproblemProgress> &spv,
  228. bool consider_empty)
  229. {
  230. vector<SubproblemProgress>::iterator spiter;
  231. for (spiter = spv.begin(); spiter != spv.end(); ++spiter) {
  232. if (spiter->solved) continue;
  233. if (spiter->dpnodes.size() == 0 && consider_empty == false) continue;
  234. // How many DPnodes would we like to have for this subproblem?
  235. while (spiter->dpnodes.size() < spiter->desired_dpnodes &&
  236. ctrlstate.dpnodes.idle.size() > 0) {
  237. // Get the first idle DPnode
  238. BESet::iterator beviter = ctrlstate.dpnodes.idle.begin();
  239. struct bufferevent *firstbev = *beviter;
  240. // Allocate it to the subproblem
  241. spiter->dpnodes.insert(firstbev);
  242. ctrlstate.dpnodes.working[firstbev] = &(*spiter);
  243. ctrlstate.dpnodes.idle.erase(firstbev);
  244. // Tell it to start listening for DPs
  245. spiter->bev_write(firstbev);
  246. }
  247. }
  248. }
  249. // Find a subproblem in the given vector that has all of its DPnodes and
  250. // could use another worker, and give it one of the idle ones.
  251. static void find_subproblem_for_worker(vector<SubproblemProgress> &spv)
  252. {
  253. vector<SubproblemProgress>::iterator spiter;
  254. for (spiter = spv.begin(); spiter != spv.end(); ++spiter) {
  255. if (spiter->solved) continue;
  256. while (spiter->ipports.size() == spiter->desired_dpnodes &&
  257. spiter->workers.size() < spiter->max_workers &&
  258. ctrlstate.workers.idle.size() > 0) {
  259. // Get the first idle worker
  260. BESet::iterator beviter = ctrlstate.workers.idle.begin();
  261. struct bufferevent *firstbev = *beviter;
  262. // Allocate it to the subproblem
  263. spiter->workers.insert(firstbev);
  264. ctrlstate.workers.working[firstbev] = &(*spiter);
  265. ctrlstate.workers.idle.erase(firstbev);
  266. // Tell it to start working on the subproblem
  267. spiter->worker_write(firstbev);
  268. }
  269. }
  270. }
  271. // See if there are any idle DPnodes or workers we can put to use
  272. static void schedule(void)
  273. {
  274. // Check the DPnodes
  275. // Iterate through the subproblems, looking for one that can use
  276. // another DPnode. First look for subproblems that already have
  277. // some, but not all, of their DPnodes
  278. if (ctrlstate.dpnodes.idle.size() > 0) {
  279. find_subproblem_for_dpnode(ctrlstate.subproblems_p, false);
  280. }
  281. if (ctrlstate.dpnodes.idle.size() > 0) {
  282. find_subproblem_for_dpnode(ctrlstate.subproblems_q, false);
  283. }
  284. // If there are still more dpnodes to place, start assigning them to
  285. // subproblems with no current dpnodes
  286. if (ctrlstate.dpnodes.idle.size() > 0) {
  287. find_subproblem_for_dpnode(ctrlstate.subproblems_p, true);
  288. }
  289. if (ctrlstate.dpnodes.idle.size() > 0) {
  290. find_subproblem_for_dpnode(ctrlstate.subproblems_q, true);
  291. }
  292. // Check the workers
  293. // Iterate through the subproblems, looking for one that can use
  294. // another worker.
  295. if (ctrlstate.workers.idle.size() > 0) {
  296. find_subproblem_for_worker(ctrlstate.subproblems_p);
  297. }
  298. if (ctrlstate.workers.idle.size() > 0) {
  299. find_subproblem_for_worker(ctrlstate.subproblems_q);
  300. }
  301. // cerr << "After schedule:\n"; ctrlstate.dump(cerr);
  302. }
  303. static ZZ computation_complete_p(const vector<SubproblemProgress> &v)
  304. {
  305. ZZ curmodulus, curexp;
  306. curmodulus = 2;
  307. curexp = 0;
  308. vector<SubproblemProgress>::const_iterator vit;
  309. for(vit = v.begin(); vit != v.end(); ++vit) {
  310. CRT(curexp, curmodulus, vit->solution, vit->order);
  311. }
  312. if (curexp < 0) {
  313. curexp += curmodulus;
  314. }
  315. return curexp;
  316. }
  317. // All subproblems are solved. Combine the results.
  318. static void computation_complete(void)
  319. {
  320. ZZ exp_p = computation_complete_p(ctrlstate.subproblems_p);
  321. ZZ exp_q = computation_complete_p(ctrlstate.subproblems_q);
  322. ZZ pm1 = (ctrlstate.p.factor - 1)/2;
  323. ZZ qm1 = (ctrlstate.q.factor - 1)/2;
  324. CRT(exp_p, pm1, exp_q, qm1);
  325. if (exp_p < 0) {
  326. exp_p += pm1;
  327. }
  328. ZZ& expon = exp_p;
  329. struct timeval ended_working;
  330. gettimeofday(&ended_working, NULL);
  331. unsigned long long computation_length_ms =
  332. (ended_working.tv_sec - ctrlstate.started_working.tv_sec) * 1000 +
  333. (ended_working.tv_usec - ctrlstate.started_working.tv_usec) / 1000;
  334. char length_buf[50];
  335. sprintf(length_buf, "%lld.%03lld s", computation_length_ms / 1000,
  336. computation_length_ms % 1000);
  337. cout << "expon = " << expon << "\n";
  338. cout << ctrlstate.worklist[0].first << " ";
  339. ZZ base_exp = PowerMod(ctrlstate.base, expon, ctrlstate.rho);
  340. if (base_exp == ctrlstate.target) {
  341. cout << "CORRECT in " << length_buf << "\n";
  342. } else {
  343. cout << "INCORRECT in " << length_buf << ":\n";
  344. cout << "base^exp = " << base_exp << "\n";
  345. cout << "target = " << ctrlstate.target << "\n";
  346. }
  347. cout.flush();
  348. ctrlstate.reset();
  349. }
  350. static unsigned short curproblemid = 0;
  351. // Take base and target mod f.factor, then decompose that into small
  352. // subproblems given our knowledge of the factors of phi(f.factor)
  353. static vector<SubproblemProgress> decomp(const ZZ_p &base, const ZZ_p &target,
  354. const FactorDecomp &f)
  355. {
  356. vector<SubproblemProgress> ret;
  357. // Compute phi(factor)
  358. const int fveclen = f.fvec.length();
  359. ZZ phi = to_ZZ(2);
  360. for (int i = 0; i < fveclen; ++i) {
  361. phi *= f.fvec[i];
  362. }
  363. ZZ_p::init(f.factor);
  364. for (int i = 0; i < fveclen; ++i) {
  365. const ZZ& order = f.fvec[i];
  366. ZZ quotient = phi / order;
  367. ZZ_p subgroup_base = to_ZZ_p(rep(base));
  368. subgroup_base = power(subgroup_base, quotient);
  369. ZZ_p subgroup_target = to_ZZ_p(rep(target));
  370. subgroup_target = power(subgroup_target, quotient);
  371. if (subgroup_base == 1) {
  372. // The original base wasn't a generator of the whole group
  373. if (subgroup_target == 1) {
  374. // But the target is in the subgroup. Lucky us.
  375. continue;
  376. } else {
  377. ret.clear();
  378. return ret;
  379. }
  380. }
  381. ++curproblemid;
  382. ret.push_back(SubproblemProgress(curproblemid, rep(subgroup_base),
  383. rep(subgroup_target), f.factor, order));
  384. }
  385. return ret;
  386. }
  387. // Read the modulus (and the factorization of the modulus and its
  388. // totient) from the given file. "-" means cin. Returns true if
  389. // successful.
  390. static bool read_modulus(const char *filename)
  391. {
  392. if (strcmp(filename, "-")) {
  393. ifstream ins(filename);
  394. if (!ins.good()) return false;
  395. ins >> ctrlstate.rho >> ctrlstate.p.factor >> ctrlstate.p.fvec >>
  396. ctrlstate.q.factor >> ctrlstate.q.fvec;
  397. ins.close();
  398. } else {
  399. cin >> ctrlstate.rho >> ctrlstate.p.factor >> ctrlstate.p.fvec >>
  400. ctrlstate.q.factor >> ctrlstate.q.fvec;
  401. }
  402. return true;
  403. }
  404. static int generate_problem(struct event_base *evbase)
  405. {
  406. while (ctrlstate.worklist[0].second == 0) {
  407. ctrlstate.worklist.erase(ctrlstate.worklist.begin());
  408. if (ctrlstate.worklist.size() > 0) {
  409. read_modulus(ctrlstate.worklist[0].first);
  410. } else {
  411. break;
  412. }
  413. }
  414. // If there are no more problems to generate, close the listener
  415. if (ctrlstate.worklist.size() == 0) {
  416. evconnlistener_free(ctrlstate.listener);
  417. ctrlstate.dpnodes.free();
  418. ctrlstate.workers.free();
  419. return -1;
  420. }
  421. // If there's already a problem on the go, don't generate another one
  422. if (ctrlstate.working == true) {
  423. return -1;
  424. }
  425. ctrlstate.working = true;
  426. int num_subproblems_p = 0;
  427. int num_subproblems_q = 0;
  428. // Generate a DLP mod rho (in the large odd-order subgroup)
  429. ZZ_p::init(ctrlstate.rho);
  430. do {
  431. ZZ_p base = power(random_ZZ_p(), 2);
  432. ZZ_p target = power(random_ZZ_p(), 2);
  433. gettimeofday(&ctrlstate.started_working, NULL);
  434. ctrlstate.base = rep(base);
  435. ctrlstate.target = rep(target);
  436. // Decompose it mod p and mod q
  437. ctrlstate.subproblems_p = decomp(base, target, ctrlstate.p);
  438. ctrlstate.subproblems_q = decomp(base, target, ctrlstate.q);
  439. num_subproblems_p = ctrlstate.subproblems_p.size();
  440. num_subproblems_q = ctrlstate.subproblems_q.size();
  441. } while (num_subproblems_p == 0 || num_subproblems_q == 0);
  442. ctrlstate.num_unsolved_subproblems =
  443. num_subproblems_p + num_subproblems_q;
  444. schedule();
  445. --(ctrlstate.worklist[0].second);
  446. return 0;
  447. }
  448. typedef enum {
  449. CCSTATE_START,
  450. CCSTATE_DPWAITRESP,
  451. CCSTATE_DPLISTENING,
  452. CCSTATE_DPEXPON,
  453. CCSTATE_END
  454. } CCState;
  455. struct ControllerConnInfo {
  456. CCState state;
  457. ControllerConnInfo() : state(CCSTATE_DPWAITRESP) {}
  458. };
  459. static void controller_dpnode_reader(struct bufferevent *bev, void *ctx)
  460. {
  461. struct evbuffer *input = bufferevent_get_input(bev);
  462. ControllerConnInfo *info = (ControllerConnInfo *)ctx;
  463. unsigned char cmd[1];
  464. ZZ expon;
  465. while(1) {
  466. size_t len = evbuffer_get_length(input);
  467. switch (info->state) {
  468. case CCSTATE_START:
  469. case CCSTATE_DPWAITRESP:
  470. if (len < 1) return;
  471. bufferevent_read(bev, cmd, 1);
  472. switch (cmd[0]) {
  473. case 'L':
  474. info->state = CCSTATE_DPLISTENING;
  475. break;
  476. case 'E':
  477. info->state = CCSTATE_DPEXPON;
  478. break;
  479. default:
  480. /* Unknown DPnode command received */
  481. fprintf(stderr, "Unknown command in "
  482. "controller_dpnode_reader: "
  483. "%c\n", cmd[0]);
  484. info->state = CCSTATE_END;
  485. break;
  486. }
  487. break;
  488. case CCSTATE_DPLISTENING:
  489. // Read 6 bytes
  490. if (len < 6) return;
  491. unsigned char ipport[6];
  492. unsigned int DPip;
  493. unsigned short DPport;
  494. bufferevent_read(bev, ipport, 6);
  495. memmove(&DPip, ipport, 4);
  496. memmove(&DPport, ipport+4, 2);
  497. {
  498. #ifdef VERBOSE
  499. struct in_addr DPaddr = { DPip };
  500. fprintf(stderr, "DP node at %s:%d\n", inet_ntoa(DPaddr), ntohs(DPport));
  501. #endif
  502. if (ctrlstate.dpnodes.working.count(bev) > 0) {
  503. ctrlstate.dpnodes.working[bev]->ipports.push_back(
  504. IPPort(ipport));
  505. schedule();
  506. }
  507. }
  508. info->state = CCSTATE_DPWAITRESP;
  509. break;
  510. case CCSTATE_DPEXPON:
  511. // Read the subproblemid and the answer to the subproblem
  512. if (len < 2 + 3*sizeof(unsigned int)) return;
  513. unsigned char exponbytes[2 + 3*sizeof(unsigned int)];
  514. unsigned short problemid;
  515. bufferevent_read(bev, exponbytes, 2 + 3*sizeof(unsigned int));
  516. memmove(&problemid, exponbytes, 2);
  517. ZZFromBytes(expon, exponbytes+2, 3*sizeof(unsigned int));
  518. // Find the subproblem and check the answer
  519. if (ctrlstate.dpnodes.working.count(bev) > 0) {
  520. SubproblemProgress *spp = ctrlstate.dpnodes.working[bev];
  521. if (spp->problemid == problemid &&
  522. spp->solved == false &&
  523. spp->target ==
  524. PowerMod(spp->base, expon, spp->modulus)) {
  525. // Subproblem solved!
  526. spp->solution = expon;
  527. spp->solved = true;
  528. spp->stop();
  529. ctrlstate.num_unsolved_subproblems--;
  530. if (ctrlstate.num_unsolved_subproblems == 0) {
  531. computation_complete();
  532. generate_problem(bufferevent_get_base(bev));
  533. }
  534. schedule();
  535. }
  536. }
  537. info->state = CCSTATE_DPWAITRESP;
  538. break;
  539. case CCSTATE_END:
  540. // Shut down the connection
  541. delete info;
  542. bufferevent_free(bev);
  543. return;
  544. }
  545. }
  546. }
  547. static void controller_dpnode_event_cb(struct bufferevent *bev, short events,
  548. void *ctx)
  549. {
  550. if (events & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  551. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  552. fprintf(stderr, "Closing dpnode connection\n");
  553. if (ctrlstate.dpnodes.working.count(bev)) {
  554. // If we lose a dpnode from an active computation, the
  555. // computation is useless.
  556. SubproblemProgress *spp = ctrlstate.dpnodes.working[bev];
  557. ctrlstate.dpnodes.working.erase(bev);
  558. spp->dpnodes.erase(bev);
  559. spp->stop();
  560. } else {
  561. ctrlstate.dpnodes.idle.erase(bev);
  562. }
  563. delete info;
  564. bufferevent_free(bev);
  565. schedule();
  566. }
  567. }
  568. static void controller_worker_event_cb(struct bufferevent *bev, short events,
  569. void *ctx)
  570. {
  571. if (events & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  572. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  573. fprintf(stderr, "Closing worker connection\n");
  574. if (ctrlstate.workers.working.count(bev)) {
  575. SubproblemProgress *spp = ctrlstate.workers.working[bev];
  576. ctrlstate.workers.working.erase(bev);
  577. spp->workers.erase(bev);
  578. } else {
  579. ctrlstate.workers.idle.erase(bev);
  580. }
  581. delete info;
  582. bufferevent_free(bev);
  583. schedule();
  584. }
  585. }
  586. static void controller_event_cb(struct bufferevent *bev, short events,
  587. void *ctx)
  588. {
  589. if (events & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  590. fprintf(stderr, "Closing connection\n");
  591. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  592. delete info;
  593. bufferevent_free(bev);
  594. }
  595. }
  596. // We're just going to read a single byte that will tell us whether the
  597. // peer is a DPnode or a Worker
  598. static void controller_master_reader(struct bufferevent *bev, void *ctx)
  599. {
  600. struct evbuffer *input = bufferevent_get_input(bev);
  601. size_t len = evbuffer_get_length(input);
  602. if (len < 1) return;
  603. char indata[1];
  604. bufferevent_read(bev, indata, 1);
  605. switch(indata[0]) {
  606. case 'D':
  607. /* Add this DPnode to the list of available ones */
  608. ctrlstate.dpnodes.idle.insert(bev);
  609. bufferevent_setcb(bev, controller_dpnode_reader, NULL,
  610. controller_dpnode_event_cb, ctx);
  611. controller_dpnode_reader(bev, ctx);
  612. schedule();
  613. return;
  614. case 'W':
  615. ctrlstate.workers.idle.insert(bev);
  616. // We don't actually read anything from workers
  617. bufferevent_enable(bev, EV_WRITE);
  618. bufferevent_setcb(bev, NULL, NULL,
  619. controller_worker_event_cb, ctx);
  620. schedule();
  621. return;
  622. default:
  623. fprintf(stderr, "Unknown command in controller_master_reader: "
  624. "%c\n", indata[0]);
  625. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  626. delete info;
  627. bufferevent_free(bev);
  628. return;
  629. }
  630. }
  631. static void controller_accept_cb(struct evconnlistener *listener,
  632. evutil_socket_t fd, struct sockaddr *address, int socklen,
  633. void *ctx)
  634. {
  635. // Create the state of the new connection
  636. ControllerConnInfo *info = new ControllerConnInfo();
  637. // Create a bufferevent for the new connection
  638. struct event_base *base = evconnlistener_get_base(listener);
  639. struct bufferevent *bev = bufferevent_socket_new(
  640. base, fd, BEV_OPT_CLOSE_ON_FREE);
  641. bufferevent_setcb(bev, controller_master_reader, NULL,
  642. controller_event_cb, info);
  643. bufferevent_enable(bev, EV_READ|EV_WRITE);
  644. }
  645. // Create a new controller socket. bindport is the port to bind to (in
  646. // host byte order), or 0 if any port will do. ip and boundport are set
  647. // to the IP and port of the socket, in network byte order.
  648. static struct evconnlistener *controller_create(struct event_base *evbase,
  649. unsigned short bindport, unsigned int *ip, unsigned short *boundport)
  650. {
  651. return listener_create(evbase, bindport, controller_accept_cb, NULL,
  652. ip, boundport, false);
  653. }
  654. int controller_parse_args(int argc, char **argv, unsigned short &bindport,
  655. Worklist &worklist, unsigned short &total_nodes,
  656. unsigned short &GB_mem_per_node)
  657. {
  658. bindport = 0;
  659. total_nodes = 1;
  660. GB_mem_per_node = 1;
  661. int reps = 1;
  662. while (argc > 2 && argv[1][0] == '-') {
  663. if (!strncmp(argv[1], "-p", 2)) {
  664. // A port number was specified
  665. bindport = strtoul(argv[2], NULL, 10);
  666. argc -= 2;
  667. argv += 2;
  668. } else if (!strncmp(argv[1], "-n", 2)) {
  669. total_nodes = strtoul(argv[2], NULL, 10);
  670. argc -= 2;
  671. argv += 2;
  672. } else if (!strncmp(argv[1], "-m", 2)) {
  673. GB_mem_per_node = strtoul(argv[2], NULL, 10);
  674. argc -= 2;
  675. argv += 2;
  676. } else if (!strncmp(argv[1], "-r", 2)) {
  677. reps = strtoul(argv[2], NULL, 10);
  678. argc -= 2;
  679. argv += 2;
  680. }
  681. }
  682. if (argc < 3 || (argc % 2 == 0)) {
  683. return 1;
  684. }
  685. for (int r=0;r<reps;++r) {
  686. for (int i=1;i<argc;i+=2) {
  687. worklist.push_back(
  688. Workentry(argv[i], strtoul(argv[i+1], NULL, 10)));
  689. }
  690. }
  691. return 0;
  692. }
  693. int controller_main(const Worklist &worklist, unsigned short bindport,
  694. void (*boundcb)(const char *boundaddr, unsigned short boundport))
  695. {
  696. // Initialize the prng with some randomness from the kernel
  697. unsigned char randbuf[1024];
  698. ifstream urand("/dev/urandom");
  699. urand.read((char *)randbuf, sizeof(randbuf));
  700. urand.close();
  701. ZZ randzz = ZZFromBytes(randbuf, sizeof(randbuf));
  702. SetSeed(randzz);
  703. if (worklist.size() == 0) {
  704. return 0;
  705. }
  706. ctrlstate.worklist = worklist;
  707. // Read the modulus and the factorization of its totient from the
  708. // specified file
  709. if (!read_modulus(worklist[0].first)) {
  710. cerr << "Unable to read file " << worklist[0].first << "\n";
  711. return 1;
  712. }
  713. struct event_base *evbase = event_base_new();
  714. unsigned int myip;
  715. unsigned short myport;
  716. ctrlstate.listener = controller_create(evbase, bindport, &myip, &myport);
  717. if (ctrlstate.listener && boundcb) {
  718. struct in_addr myaddr = { myip };
  719. boundcb(inet_ntoa(myaddr), ntohs(myport));
  720. }
  721. // Kick off the first problem to solve
  722. generate_problem(evbase);
  723. event_base_dispatch(evbase);
  724. return 0;
  725. }