controller.cc 26 KB

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