controller.cc 25 KB

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