controller.cc 25 KB

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