controller.cc 23 KB

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