server.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /*
  2. *
  3. * Copyright 2015, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. #include <memory>
  34. #include "server.h"
  35. #include <nan.h>
  36. #include <node.h>
  37. #include <vector>
  38. #include "call.h"
  39. #include "completion_queue.h"
  40. #include "grpc/grpc.h"
  41. #include "grpc/grpc_security.h"
  42. #include "grpc/support/log.h"
  43. #include "server_credentials.h"
  44. #include "slice.h"
  45. #include "timeval.h"
  46. namespace grpc {
  47. namespace node {
  48. using Nan::Callback;
  49. using Nan::EscapableHandleScope;
  50. using Nan::HandleScope;
  51. using Nan::Maybe;
  52. using Nan::MaybeLocal;
  53. using Nan::ObjectWrap;
  54. using Nan::Persistent;
  55. using Nan::Utf8String;
  56. using std::unique_ptr;
  57. using v8::Array;
  58. using v8::Boolean;
  59. using v8::Date;
  60. using v8::Exception;
  61. using v8::External;
  62. using v8::Function;
  63. using v8::FunctionTemplate;
  64. using v8::Local;
  65. using v8::Number;
  66. using v8::Object;
  67. using v8::String;
  68. using v8::Value;
  69. Nan::Callback *Server::constructor;
  70. Persistent<FunctionTemplate> Server::fun_tpl;
  71. static Callback *shutdown_callback = NULL;
  72. class ServerShutdownOp : public Op {
  73. public:
  74. ServerShutdownOp(grpc_server *server) : server(server) {}
  75. ~ServerShutdownOp() {}
  76. Local<Value> GetNodeValue() const { return Nan::Null(); }
  77. bool ParseOp(Local<Value> value, grpc_op *out) { return true; }
  78. bool IsFinalOp() { return false; }
  79. void OnComplete(bool success) {
  80. /* Because cancel_all_calls was called, we assume that shutdown_and_notify
  81. completes successfully */
  82. grpc_server_destroy(server);
  83. }
  84. grpc_server *server;
  85. protected:
  86. std::string GetTypeString() const { return "shutdown"; }
  87. };
  88. class NewCallOp : public Op {
  89. public:
  90. NewCallOp() {
  91. call = NULL;
  92. grpc_call_details_init(&details);
  93. grpc_metadata_array_init(&request_metadata);
  94. }
  95. ~NewCallOp() {
  96. grpc_call_details_destroy(&details);
  97. grpc_metadata_array_destroy(&request_metadata);
  98. }
  99. Local<Value> GetNodeValue() const {
  100. Nan::EscapableHandleScope scope;
  101. if (call == NULL) {
  102. return scope.Escape(Nan::Null());
  103. }
  104. Local<Object> obj = Nan::New<Object>();
  105. Nan::Set(obj, Nan::New("call").ToLocalChecked(), Call::WrapStruct(call));
  106. // TODO(murgatroid99): Use zero-copy string construction instead
  107. Nan::Set(obj, Nan::New("method").ToLocalChecked(),
  108. CopyStringFromSlice(details.method));
  109. Nan::Set(obj, Nan::New("host").ToLocalChecked(),
  110. CopyStringFromSlice(details.host));
  111. Nan::Set(obj, Nan::New("deadline").ToLocalChecked(),
  112. Nan::New<Date>(TimespecToMilliseconds(details.deadline))
  113. .ToLocalChecked());
  114. Nan::Set(obj, Nan::New("metadata").ToLocalChecked(),
  115. ParseMetadata(&request_metadata));
  116. return scope.Escape(obj);
  117. }
  118. bool ParseOp(Local<Value> value, grpc_op *out) { return true; }
  119. bool IsFinalOp() { return false; }
  120. void OnComplete(bool success) {}
  121. grpc_call *call;
  122. grpc_call_details details;
  123. grpc_metadata_array request_metadata;
  124. protected:
  125. std::string GetTypeString() const { return "new_call"; }
  126. };
  127. class TryShutdownOp : public Op {
  128. public:
  129. TryShutdownOp(Server *server, Local<Value> server_value) : server(server) {
  130. server_persist.Reset(server_value);
  131. }
  132. Local<Value> GetNodeValue() const {
  133. EscapableHandleScope scope;
  134. return scope.Escape(Nan::New(server_persist));
  135. }
  136. bool ParseOp(Local<Value> value, grpc_op *out) { return true; }
  137. bool IsFinalOp() { return false; }
  138. void OnComplete(bool success) {
  139. if (success) {
  140. server->DestroyWrappedServer();
  141. }
  142. }
  143. protected:
  144. std::string GetTypeString() const { return "try_shutdown"; }
  145. private:
  146. Server *server;
  147. Nan::Persistent<v8::Value, Nan::CopyablePersistentTraits<v8::Value>>
  148. server_persist;
  149. };
  150. Server::Server(grpc_server *server) : wrapped_server(server) {}
  151. Server::~Server() { this->ShutdownServer(); }
  152. void Server::Init(Local<Object> exports) {
  153. HandleScope scope;
  154. Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
  155. tpl->SetClassName(Nan::New("Server").ToLocalChecked());
  156. tpl->InstanceTemplate()->SetInternalFieldCount(1);
  157. Nan::SetPrototypeMethod(tpl, "requestCall", RequestCall);
  158. Nan::SetPrototypeMethod(tpl, "addHttp2Port", AddHttp2Port);
  159. Nan::SetPrototypeMethod(tpl, "start", Start);
  160. Nan::SetPrototypeMethod(tpl, "tryShutdown", TryShutdown);
  161. Nan::SetPrototypeMethod(tpl, "forceShutdown", ForceShutdown);
  162. fun_tpl.Reset(tpl);
  163. Local<Function> ctr = Nan::GetFunction(tpl).ToLocalChecked();
  164. Nan::Set(exports, Nan::New("Server").ToLocalChecked(), ctr);
  165. constructor = new Callback(ctr);
  166. }
  167. bool Server::HasInstance(Local<Value> val) {
  168. HandleScope scope;
  169. return Nan::New(fun_tpl)->HasInstance(val);
  170. }
  171. void Server::DestroyWrappedServer() {
  172. if (this->wrapped_server != NULL) {
  173. grpc_server_destroy(this->wrapped_server);
  174. this->wrapped_server = NULL;
  175. }
  176. }
  177. NAN_METHOD(ServerShutdownCallback) {
  178. if (!info[0]->IsNull()) {
  179. return Nan::ThrowError("forceShutdown failed somehow");
  180. }
  181. }
  182. void Server::ShutdownServer() {
  183. Nan::HandleScope scope;
  184. if (this->wrapped_server != NULL) {
  185. if (shutdown_callback == NULL) {
  186. Local<FunctionTemplate> callback_tpl =
  187. Nan::New<FunctionTemplate>(ServerShutdownCallback);
  188. shutdown_callback =
  189. new Callback(Nan::GetFunction(callback_tpl).ToLocalChecked());
  190. }
  191. ServerShutdownOp *op = new ServerShutdownOp(this->wrapped_server);
  192. unique_ptr<OpVec> ops(new OpVec());
  193. ops->push_back(unique_ptr<Op>(op));
  194. grpc_server_shutdown_and_notify(
  195. this->wrapped_server, GetCompletionQueue(),
  196. new struct tag(new Callback(**shutdown_callback), ops.release(), NULL,
  197. Nan::Null()));
  198. grpc_server_cancel_all_calls(this->wrapped_server);
  199. CompletionQueueNext();
  200. this->wrapped_server = NULL;
  201. }
  202. }
  203. NAN_METHOD(Server::New) {
  204. /* If this is not a constructor call, make a constructor call and return
  205. the result */
  206. if (!info.IsConstructCall()) {
  207. const int argc = 1;
  208. Local<Value> argv[argc] = {info[0]};
  209. MaybeLocal<Object> maybe_instance =
  210. Nan::NewInstance(constructor->GetFunction(), argc, argv);
  211. if (maybe_instance.IsEmpty()) {
  212. // There's probably a pending exception
  213. return;
  214. } else {
  215. info.GetReturnValue().Set(maybe_instance.ToLocalChecked());
  216. return;
  217. }
  218. }
  219. grpc_server *wrapped_server;
  220. grpc_completion_queue *queue = GetCompletionQueue();
  221. grpc_channel_args *channel_args;
  222. if (!ParseChannelArgs(info[0], &channel_args)) {
  223. DeallocateChannelArgs(channel_args);
  224. return Nan::ThrowTypeError(
  225. "Server options must be an object with "
  226. "string keys and integer or string values");
  227. }
  228. wrapped_server = grpc_server_create(channel_args, NULL);
  229. DeallocateChannelArgs(channel_args);
  230. grpc_server_register_completion_queue(wrapped_server, queue, NULL);
  231. Server *server = new Server(wrapped_server);
  232. server->Wrap(info.This());
  233. info.GetReturnValue().Set(info.This());
  234. }
  235. NAN_METHOD(Server::RequestCall) {
  236. if (!HasInstance(info.This())) {
  237. return Nan::ThrowTypeError("requestCall can only be called on a Server");
  238. }
  239. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  240. NewCallOp *op = new NewCallOp();
  241. unique_ptr<OpVec> ops(new OpVec());
  242. ops->push_back(unique_ptr<Op>(op));
  243. grpc_call_error error = grpc_server_request_call(
  244. server->wrapped_server, &op->call, &op->details, &op->request_metadata,
  245. GetCompletionQueue(), GetCompletionQueue(),
  246. new struct tag(new Callback(info[0].As<Function>()), ops.release(), NULL,
  247. Nan::Null()));
  248. if (error != GRPC_CALL_OK) {
  249. return Nan::ThrowError(nanErrorWithCode("requestCall failed", error));
  250. }
  251. CompletionQueueNext();
  252. }
  253. NAN_METHOD(Server::AddHttp2Port) {
  254. if (!HasInstance(info.This())) {
  255. return Nan::ThrowTypeError("addHttp2Port can only be called on a Server");
  256. }
  257. if (!info[0]->IsString()) {
  258. return Nan::ThrowTypeError(
  259. "addHttp2Port's first argument must be a String");
  260. }
  261. if (!ServerCredentials::HasInstance(info[1])) {
  262. return Nan::ThrowTypeError(
  263. "addHttp2Port's second argument must be ServerCredentials");
  264. }
  265. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  266. ServerCredentials *creds_object = ObjectWrap::Unwrap<ServerCredentials>(
  267. Nan::To<Object>(info[1]).ToLocalChecked());
  268. grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials();
  269. int port;
  270. if (creds == NULL) {
  271. port = grpc_server_add_insecure_http2_port(server->wrapped_server,
  272. *Utf8String(info[0]));
  273. } else {
  274. port = grpc_server_add_secure_http2_port(server->wrapped_server,
  275. *Utf8String(info[0]), creds);
  276. }
  277. info.GetReturnValue().Set(Nan::New<Number>(port));
  278. }
  279. NAN_METHOD(Server::Start) {
  280. Nan::HandleScope scope;
  281. if (!HasInstance(info.This())) {
  282. return Nan::ThrowTypeError("start can only be called on a Server");
  283. }
  284. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  285. grpc_server_start(server->wrapped_server);
  286. }
  287. NAN_METHOD(Server::TryShutdown) {
  288. Nan::HandleScope scope;
  289. if (!HasInstance(info.This())) {
  290. return Nan::ThrowTypeError("tryShutdown can only be called on a Server");
  291. }
  292. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  293. if (server->wrapped_server == NULL) {
  294. // Server is already shut down. Call callback immediately.
  295. Nan::Callback callback(info[0].As<Function>());
  296. callback.Call(0, {});
  297. return;
  298. }
  299. TryShutdownOp *op = new TryShutdownOp(server, info.This());
  300. unique_ptr<OpVec> ops(new OpVec());
  301. ops->push_back(unique_ptr<Op>(op));
  302. grpc_server_shutdown_and_notify(
  303. server->wrapped_server, GetCompletionQueue(),
  304. new struct tag(new Nan::Callback(info[0].As<Function>()), ops.release(),
  305. NULL, Nan::Null()));
  306. CompletionQueueNext();
  307. }
  308. NAN_METHOD(Server::ForceShutdown) {
  309. Nan::HandleScope scope;
  310. if (!HasInstance(info.This())) {
  311. return Nan::ThrowTypeError("forceShutdown can only be called on a Server");
  312. }
  313. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  314. server->ShutdownServer();
  315. }
  316. } // namespace node
  317. } // namespace grpc