dist.d 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. Interface for the VibeDist load balancer
  3. Copyright: © 2012-2013 Sönke Ludwig
  4. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
  5. Authors: Sönke Ludwig, Jan Krüger
  6. */
  7. module vibe.http.dist;
  8. import vibe.core.log;
  9. import vibe.data.json;
  10. import vibe.inet.url;
  11. import vibe.http.client;
  12. import vibe.http.server;
  13. import std.conv;
  14. import std.exception;
  15. import std.process;
  16. /**
  17. Listens for HTTP connections on the specified load balancer using the given HTTP server settings.
  18. This function is usable as direct replacement of listenHTTP
  19. */
  20. HTTPListener listenHTTPDist(HTTPServerSettings settings, HTTPServerRequestDelegate handler, string balancer_address, ushort balancer_port = 11000)
  21. @safe {
  22. Json regmsg = Json.emptyObject;
  23. regmsg["host_name"] = settings.hostName;
  24. regmsg["port"] = settings.port;
  25. regmsg["ssl_settings"] = "";
  26. regmsg["pid"] = thisProcessID;
  27. //regmsg.sslContext = settings.sslContext; // TODO: send key/cert contents
  28. HTTPServerSettings local_settings = settings.dup;
  29. local_settings.bindAddresses = ["127.0.0.1"];
  30. local_settings.port = 0;
  31. local_settings.disableDistHost = true;
  32. auto ret = listenHTTP(local_settings, handler);
  33. requestHTTP(URL("http://"~balancer_address~":"~to!string(balancer_port)~"/register"), (scope req){
  34. logInfo("Listening for VibeDist connections on port %d", req.localAddress.port);
  35. regmsg["local_address"] = "127.0.0.1";
  36. regmsg["local_port"] = req.localAddress.port;
  37. req.method = HTTPMethod.POST;
  38. req.writeJsonBody(regmsg);
  39. }, (scope res){
  40. enforce(res.statusCode == HTTPStatus.ok, "Failed to register with load balancer.");
  41. });
  42. return ret;
  43. }