controller.cc 25 KB

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