controller.cc 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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. unsigned int attempt = 0;
  453. do {
  454. ZZ_p base;
  455. ZZ_p target;
  456. {
  457. #ifdef DERANDOMIZE
  458. RandomStreamPush push_seed;
  459. // the seed will be reset to its original value
  460. // once we exit this scope
  461. SetSeed(ctrlstate.rho*ctrlstate.p.factor*ctrlstate.q.factor+attempt);
  462. #endif
  463. base = power(random_ZZ_p(), 2);
  464. target = power(random_ZZ_p(), 2);
  465. }
  466. gettimeofday(&ctrlstate.started_working, NULL);
  467. ctrlstate.base = rep(base);
  468. ctrlstate.target = rep(target);
  469. // Decompose it mod p and mod q
  470. ctrlstate.subproblems_p = decomp(base, target, ctrlstate.p);
  471. ctrlstate.subproblems_q = decomp(base, target, ctrlstate.q);
  472. num_subproblems_p = ctrlstate.subproblems_p.size();
  473. num_subproblems_q = ctrlstate.subproblems_q.size();
  474. attempt++;
  475. } while (num_subproblems_p == 0 || num_subproblems_q == 0);
  476. ctrlstate.num_unsolved_subproblems =
  477. num_subproblems_p + num_subproblems_q;
  478. schedule();
  479. --(ctrlstate.worklist[0].second);
  480. return 0;
  481. }
  482. typedef enum {
  483. CCSTATE_START,
  484. CCSTATE_DPWAITRESP,
  485. CCSTATE_DPLISTENING,
  486. CCSTATE_DPEXPON,
  487. CCSTATE_END
  488. } CCState;
  489. struct ControllerConnInfo {
  490. CCState state;
  491. ControllerConnInfo() : state(CCSTATE_DPWAITRESP) {}
  492. };
  493. static void controller_dpnode_reader(struct bufferevent *bev, void *ctx)
  494. {
  495. struct evbuffer *input = bufferevent_get_input(bev);
  496. ControllerConnInfo *info = (ControllerConnInfo *)ctx;
  497. unsigned char cmd[1];
  498. ZZ expon;
  499. while(1) {
  500. size_t len = evbuffer_get_length(input);
  501. switch (info->state) {
  502. case CCSTATE_START:
  503. case CCSTATE_DPWAITRESP:
  504. if (len < 1) return;
  505. bufferevent_read(bev, cmd, 1);
  506. switch (cmd[0]) {
  507. case 'L':
  508. info->state = CCSTATE_DPLISTENING;
  509. break;
  510. case 'E':
  511. info->state = CCSTATE_DPEXPON;
  512. break;
  513. default:
  514. /* Unknown DPnode command received */
  515. fprintf(stderr, "Unknown command in "
  516. "controller_dpnode_reader: "
  517. "%c\n", cmd[0]);
  518. info->state = CCSTATE_END;
  519. break;
  520. }
  521. break;
  522. case CCSTATE_DPLISTENING:
  523. // Read 6 bytes
  524. if (len < 6) return;
  525. unsigned char ipport[6];
  526. unsigned int DPip;
  527. unsigned short DPport;
  528. bufferevent_read(bev, ipport, 6);
  529. memmove(&DPip, ipport, 4);
  530. memmove(&DPport, ipport+4, 2);
  531. {
  532. #ifdef VERBOSE
  533. struct in_addr DPaddr = { DPip };
  534. fprintf(stderr, "DP node at %s:%d\n", inet_ntoa(DPaddr), ntohs(DPport));
  535. #endif
  536. if (ctrlstate.dpnodes.working.count(bev) > 0) {
  537. ctrlstate.dpnodes.working[bev]->ipports.push_back(
  538. IPPort(ipport));
  539. schedule();
  540. }
  541. }
  542. info->state = CCSTATE_DPWAITRESP;
  543. break;
  544. case CCSTATE_DPEXPON:
  545. // Read the subproblemid and the answer to the subproblem
  546. if (len < 2 + 3*sizeof(unsigned int)) return;
  547. unsigned char exponbytes[2 + 3*sizeof(unsigned int)];
  548. unsigned short problemid;
  549. bufferevent_read(bev, exponbytes, 2 + 3*sizeof(unsigned int));
  550. memmove(&problemid, exponbytes, 2);
  551. ZZFromBytes(expon, exponbytes+2, 3*sizeof(unsigned int));
  552. // Find the subproblem and check the answer
  553. if (ctrlstate.dpnodes.working.count(bev) > 0) {
  554. SubproblemProgress *spp = ctrlstate.dpnodes.working[bev];
  555. if (spp->problemid == problemid &&
  556. spp->solved == false &&
  557. spp->target ==
  558. PowerMod(spp->base, expon, spp->modulus)) {
  559. // Subproblem solved!
  560. ctrlstate.num_unsolved_subproblems--;
  561. spp->solution = expon;
  562. spp->solved = true;
  563. spp->stop();
  564. schedule();
  565. }
  566. }
  567. info->state = CCSTATE_DPWAITRESP;
  568. break;
  569. case CCSTATE_END:
  570. // Shut down the connection
  571. delete info;
  572. bufferevent_free(bev);
  573. return;
  574. }
  575. }
  576. }
  577. static void controller_worker_reader(struct bufferevent *bev, void *ctx)
  578. {
  579. struct evbuffer *input = bufferevent_get_input(bev);
  580. ControllerConnInfo *info = (ControllerConnInfo *)ctx;
  581. while(1) {
  582. unsigned int kernel_launch_count = 0;
  583. size_t len = evbuffer_get_length(input);
  584. if (len < sizeof(kernel_launch_count)) return;
  585. bufferevent_read(bev, &kernel_launch_count, sizeof(kernel_launch_count));
  586. // this assumes that workers never leave a subproblem (never crash or get re-assigned)
  587. // otherwise we'll miss out on the kernel_launch_count for some workers
  588. SubproblemProgress *spp = ctrlstate.workers.working[bev];
  589. spp->kernel_launch_count += kernel_launch_count;
  590. spp->num_workers_replied += 1;
  591. if (spp->num_workers_replied == spp->workers.size()) {
  592. cout << "Timing (name, problemid, subproblemid, launches): "
  593. << ctrlstate.worklist[0].first << ", "
  594. << ctrlstate.problemid << ", "
  595. << spp->problemid << ", "
  596. << spp->kernel_launch_count << "\n";
  597. cout.flush();
  598. spp->reset();
  599. schedule();
  600. }
  601. if (ctrlstate.num_unsolved_subproblems == 0 && ctrlstate.workers.working.size() == 0) {
  602. computation_complete();
  603. generate_problem();
  604. }
  605. }
  606. }
  607. static void controller_dpnode_event_cb(struct bufferevent *bev, short events,
  608. void *ctx)
  609. {
  610. if (events & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  611. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  612. fprintf(stderr, "Closing dpnode connection\n");
  613. if (ctrlstate.dpnodes.working.count(bev)) {
  614. // If we lose a dpnode from an active computation, the
  615. // computation is useless.
  616. SubproblemProgress *spp = ctrlstate.dpnodes.working[bev];
  617. ctrlstate.dpnodes.working.erase(bev);
  618. spp->dpnodes.erase(bev);
  619. spp->stop();
  620. spp->reset();
  621. } else {
  622. ctrlstate.dpnodes.idle.erase(bev);
  623. }
  624. delete info;
  625. bufferevent_free(bev);
  626. schedule();
  627. }
  628. }
  629. static void controller_worker_event_cb(struct bufferevent *bev, short events,
  630. void *ctx)
  631. {
  632. if (events & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  633. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  634. fprintf(stderr, "Closing worker connection\n");
  635. if (ctrlstate.workers.working.count(bev)) {
  636. SubproblemProgress *spp = ctrlstate.workers.working[bev];
  637. ctrlstate.workers.working.erase(bev);
  638. spp->workers.erase(bev);
  639. } else {
  640. ctrlstate.workers.idle.erase(bev);
  641. }
  642. delete info;
  643. bufferevent_free(bev);
  644. schedule();
  645. }
  646. }
  647. static void controller_event_cb(struct bufferevent *bev, short events,
  648. void *ctx)
  649. {
  650. if (events & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  651. fprintf(stderr, "Closing connection\n");
  652. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  653. delete info;
  654. bufferevent_free(bev);
  655. }
  656. }
  657. // We're just going to read a single byte that will tell us whether the
  658. // peer is a DPnode or a Worker
  659. static void controller_master_reader(struct bufferevent *bev, void *ctx)
  660. {
  661. struct evbuffer *input = bufferevent_get_input(bev);
  662. size_t len = evbuffer_get_length(input);
  663. if (len < 1) return;
  664. char indata[1];
  665. bufferevent_read(bev, indata, 1);
  666. switch(indata[0]) {
  667. case 'D':
  668. /* Add this DPnode to the list of available ones */
  669. ctrlstate.dpnodes.idle.insert(bev);
  670. bufferevent_setcb(bev, controller_dpnode_reader, NULL,
  671. controller_dpnode_event_cb, ctx);
  672. controller_dpnode_reader(bev, ctx);
  673. schedule();
  674. return;
  675. case 'W':
  676. ctrlstate.workers.idle.insert(bev);
  677. bufferevent_enable(bev, EV_WRITE);
  678. bufferevent_setcb(bev, controller_worker_reader, NULL,
  679. controller_worker_event_cb, ctx);
  680. controller_worker_reader(bev, ctx);
  681. schedule();
  682. return;
  683. default:
  684. fprintf(stderr, "Unknown command in controller_master_reader: "
  685. "%c\n", indata[0]);
  686. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  687. delete info;
  688. bufferevent_free(bev);
  689. return;
  690. }
  691. }
  692. static void controller_accept_cb(struct evconnlistener *listener,
  693. evutil_socket_t fd, struct sockaddr *address, int socklen,
  694. void *ctx)
  695. {
  696. // Create the state of the new connection
  697. ControllerConnInfo *info = new ControllerConnInfo();
  698. // Create a bufferevent for the new connection
  699. struct event_base *base = evconnlistener_get_base(listener);
  700. struct bufferevent *bev = bufferevent_socket_new(
  701. base, fd, BEV_OPT_CLOSE_ON_FREE);
  702. bufferevent_setcb(bev, controller_master_reader, NULL,
  703. controller_event_cb, info);
  704. bufferevent_enable(bev, EV_READ|EV_WRITE);
  705. }
  706. // Create a new controller socket. bindport is the port to bind to (in
  707. // host byte order), or 0 if any port will do. ip and boundport are set
  708. // to the IP and port of the socket, in network byte order.
  709. static struct evconnlistener *controller_create(struct event_base *evbase,
  710. unsigned short bindport, unsigned int *ip, unsigned short *boundport)
  711. {
  712. return listener_create(evbase, bindport, controller_accept_cb, NULL,
  713. ip, boundport, false);
  714. }
  715. int controller_parse_args(int argc, char **argv, unsigned short &bindport,
  716. Worklist &worklist, unsigned short &total_nodes,
  717. unsigned short &GB_mem_per_node)
  718. {
  719. bindport = 0;
  720. total_nodes = 1;
  721. GB_mem_per_node = 1;
  722. int reps = 1;
  723. while (argc > 2 && argv[1][0] == '-') {
  724. if (!strncmp(argv[1], "-p", 2)) {
  725. // A port number was specified
  726. bindport = strtoul(argv[2], NULL, 10);
  727. argc -= 2;
  728. argv += 2;
  729. } else if (!strncmp(argv[1], "-n", 2)) {
  730. total_nodes = strtoul(argv[2], NULL, 10);
  731. argc -= 2;
  732. argv += 2;
  733. } else if (!strncmp(argv[1], "-m", 2)) {
  734. GB_mem_per_node = strtoul(argv[2], NULL, 10);
  735. argc -= 2;
  736. argv += 2;
  737. } else if (!strncmp(argv[1], "-r", 2)) {
  738. reps = strtoul(argv[2], NULL, 10);
  739. argc -= 2;
  740. argv += 2;
  741. }
  742. }
  743. if (argc < 3 || (argc % 2 == 0)) {
  744. return 1;
  745. }
  746. for (int r=0;r<reps;++r) {
  747. for (int i=1;i<argc;i+=2) {
  748. worklist.push_back(
  749. Workentry(argv[i], strtoul(argv[i+1], NULL, 10)));
  750. }
  751. }
  752. return 0;
  753. }
  754. int controller_main(const Worklist &worklist, unsigned short bindport,
  755. void (*boundcb)(const char *boundaddr, unsigned short boundport))
  756. {
  757. // Initialize the prng with some randomness from the kernel
  758. unsigned char randbuf[1024];
  759. ifstream urand("/dev/urandom");
  760. urand.read((char *)randbuf, sizeof(randbuf));
  761. urand.close();
  762. ZZ randzz = ZZFromBytes(randbuf, sizeof(randbuf));
  763. SetSeed(randzz);
  764. if (worklist.size() == 0) {
  765. return 0;
  766. }
  767. // Initialize the output prefix
  768. char prefix[300];
  769. gethostname(prefix, 256);
  770. strcat(prefix, "-C");
  771. output_prefix = std::string(prefix);
  772. ctrlstate.worklist = worklist;
  773. // Read the modulus and the factorization of its totient from the
  774. // specified file
  775. if (!read_modulus(worklist[0].first)) {
  776. cerr << "Unable to read file " << worklist[0].first << "\n";
  777. return 1;
  778. }
  779. struct event_base *evbase = event_base_new();
  780. unsigned int myip;
  781. unsigned short myport;
  782. ctrlstate.listener = controller_create(evbase, bindport, &myip, &myport);
  783. if (ctrlstate.listener && boundcb) {
  784. struct in_addr myaddr = { myip };
  785. boundcb(inet_ntoa(myaddr), ntohs(myport));
  786. }
  787. // Kick off the first problem to solve
  788. generate_problem();
  789. event_base_dispatch(evbase);
  790. return 0;
  791. }