compute_server_main.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <stdio.h>
  2. #include <signal.h>
  3. #include <string.h>
  4. #include "workflow/WFHttpServer.h"
  5. #include "workflow/WFFacilities.h"
  6. #include "config/config.h"
  7. static WFFacilities::WaitGroup wait_group(1);
  8. static srpc::RPCConfig config;
  9. void sig_handler(int signo)
  10. {
  11. wait_group.done();
  12. }
  13. void init()
  14. {
  15. if (config.load("./server.conf") == false)
  16. {
  17. perror("Load config failed");
  18. exit(1);
  19. }
  20. signal(SIGINT, sig_handler);
  21. signal(SIGTERM, sig_handler);
  22. }
  23. // Example for Fibonacci.
  24. void Fibonacci(int n, protocol::HttpResponse *resp)
  25. {
  26. unsigned long long x = 0, y = 1;
  27. char buf[256];
  28. int i;
  29. if (n <= 0 || n > 94)
  30. {
  31. resp->append_output_body_nocopy("<html>Invalid Number.</html>",
  32. strlen("<html>Invalid Number.</html>"));
  33. return;
  34. }
  35. resp->append_output_body_nocopy("<html>", strlen("<html>"));
  36. for (i = 2; i < n; i++)
  37. {
  38. sprintf(buf, "<p>%llu + %llu = %llu.</p>", x, y, x + y);
  39. resp->append_output_body(buf);
  40. y = x + y;
  41. x = y - x;
  42. }
  43. if (n == 1)
  44. y = 0;
  45. sprintf(buf, "<p>The No. %d Fibonacci number is: %llu.</p>", n, y);
  46. resp->append_output_body(buf);
  47. resp->append_output_body_nocopy("</html>", strlen("</html>"));
  48. }
  49. void process(WFHttpTask *task)
  50. {
  51. const char *uri = task->get_req()->get_request_uri();
  52. if (*uri == '/')
  53. uri++;
  54. int n = atoi(uri);
  55. protocol::HttpResponse *resp = task->get_resp();
  56. fprintf(stderr, "server get request. n = %d\n", n);
  57. // All calculations can be encapsulated by 'go_task'
  58. WFGoTask *go_task = WFTaskFactory::create_go_task("go", Fibonacci, n, resp);
  59. // Tasks will be dispatch asynchonously after 'push_back()'
  60. series_of(task)->push_back(go_task);
  61. }
  62. int main()
  63. {
  64. init();
  65. WFHttpServer server(process);
  66. if (server.start(config.server_port()) == 0)
  67. {
  68. fprintf(stderr, "Computing server started, port %u\n", config.server_port());
  69. wait_group.wait();
  70. server.stop();
  71. }
  72. else
  73. perror("server start");
  74. return 0;
  75. }