server.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /*
  2. *
  3. * Copyright 2015 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <memory>
  19. #include "server.h"
  20. #include <nan.h>
  21. #include <node.h>
  22. #include <vector>
  23. #include "call.h"
  24. #include "completion_queue.h"
  25. #include "grpc/grpc.h"
  26. #include "grpc/grpc_security.h"
  27. #include "grpc/support/log.h"
  28. #include "server_credentials.h"
  29. #include "slice.h"
  30. #include "timeval.h"
  31. namespace grpc {
  32. namespace node {
  33. using Nan::Callback;
  34. using Nan::EscapableHandleScope;
  35. using Nan::HandleScope;
  36. using Nan::Maybe;
  37. using Nan::MaybeLocal;
  38. using Nan::ObjectWrap;
  39. using Nan::Persistent;
  40. using Nan::Utf8String;
  41. using std::unique_ptr;
  42. using v8::Array;
  43. using v8::Boolean;
  44. using v8::Date;
  45. using v8::Exception;
  46. using v8::External;
  47. using v8::Function;
  48. using v8::FunctionTemplate;
  49. using v8::Local;
  50. using v8::Number;
  51. using v8::Object;
  52. using v8::String;
  53. using v8::Value;
  54. Nan::Callback *Server::constructor;
  55. Persistent<FunctionTemplate> Server::fun_tpl;
  56. static Callback *shutdown_callback = NULL;
  57. class ServerShutdownOp : public Op {
  58. public:
  59. ServerShutdownOp(grpc_server *server) : server(server) {}
  60. ~ServerShutdownOp() {}
  61. Local<Value> GetNodeValue() const { return Nan::Null(); }
  62. bool ParseOp(Local<Value> value, grpc_op *out) { return true; }
  63. bool IsFinalOp() { return false; }
  64. void OnComplete(bool success) {
  65. /* Because cancel_all_calls was called, we assume that shutdown_and_notify
  66. completes successfully */
  67. grpc_server_destroy(server);
  68. }
  69. grpc_server *server;
  70. protected:
  71. std::string GetTypeString() const { return "shutdown"; }
  72. };
  73. class NewCallOp : public Op {
  74. public:
  75. NewCallOp() {
  76. call = NULL;
  77. grpc_call_details_init(&details);
  78. grpc_metadata_array_init(&request_metadata);
  79. }
  80. ~NewCallOp() {
  81. grpc_call_details_destroy(&details);
  82. grpc_metadata_array_destroy(&request_metadata);
  83. }
  84. Local<Value> GetNodeValue() const {
  85. Nan::EscapableHandleScope scope;
  86. if (call == NULL) {
  87. return scope.Escape(Nan::Null());
  88. }
  89. Local<Object> obj = Nan::New<Object>();
  90. Nan::Set(obj, Nan::New("call").ToLocalChecked(), Call::WrapStruct(call));
  91. // TODO(murgatroid99): Use zero-copy string construction instead
  92. Nan::Set(obj, Nan::New("method").ToLocalChecked(),
  93. CopyStringFromSlice(details.method));
  94. Nan::Set(obj, Nan::New("host").ToLocalChecked(),
  95. CopyStringFromSlice(details.host));
  96. Nan::Set(obj, Nan::New("deadline").ToLocalChecked(),
  97. Nan::New<Date>(TimespecToMilliseconds(details.deadline))
  98. .ToLocalChecked());
  99. Nan::Set(obj, Nan::New("metadata").ToLocalChecked(),
  100. ParseMetadata(&request_metadata));
  101. return scope.Escape(obj);
  102. }
  103. bool ParseOp(Local<Value> value, grpc_op *out) { return true; }
  104. bool IsFinalOp() { return false; }
  105. void OnComplete(bool success) {}
  106. grpc_call *call;
  107. grpc_call_details details;
  108. grpc_metadata_array request_metadata;
  109. protected:
  110. std::string GetTypeString() const { return "new_call"; }
  111. };
  112. class TryShutdownOp : public Op {
  113. public:
  114. TryShutdownOp(Server *server, Local<Value> server_value) : server(server) {
  115. server_persist.Reset(server_value);
  116. }
  117. Local<Value> GetNodeValue() const {
  118. EscapableHandleScope scope;
  119. return scope.Escape(Nan::New(server_persist));
  120. }
  121. bool ParseOp(Local<Value> value, grpc_op *out) { return true; }
  122. bool IsFinalOp() { return false; }
  123. void OnComplete(bool success) {
  124. if (success) {
  125. server->DestroyWrappedServer();
  126. }
  127. }
  128. protected:
  129. std::string GetTypeString() const { return "try_shutdown"; }
  130. private:
  131. Server *server;
  132. Nan::Persistent<v8::Value, Nan::CopyablePersistentTraits<v8::Value>>
  133. server_persist;
  134. };
  135. Server::Server(grpc_server *server) : wrapped_server(server) {}
  136. Server::~Server() { this->ShutdownServer(); }
  137. void Server::Init(Local<Object> exports) {
  138. HandleScope scope;
  139. Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
  140. tpl->SetClassName(Nan::New("Server").ToLocalChecked());
  141. tpl->InstanceTemplate()->SetInternalFieldCount(1);
  142. Nan::SetPrototypeMethod(tpl, "requestCall", RequestCall);
  143. Nan::SetPrototypeMethod(tpl, "addHttp2Port", AddHttp2Port);
  144. Nan::SetPrototypeMethod(tpl, "start", Start);
  145. Nan::SetPrototypeMethod(tpl, "tryShutdown", TryShutdown);
  146. Nan::SetPrototypeMethod(tpl, "forceShutdown", ForceShutdown);
  147. fun_tpl.Reset(tpl);
  148. Local<Function> ctr = Nan::GetFunction(tpl).ToLocalChecked();
  149. Nan::Set(exports, Nan::New("Server").ToLocalChecked(), ctr);
  150. constructor = new Callback(ctr);
  151. }
  152. bool Server::HasInstance(Local<Value> val) {
  153. HandleScope scope;
  154. return Nan::New(fun_tpl)->HasInstance(val);
  155. }
  156. void Server::DestroyWrappedServer() {
  157. if (this->wrapped_server != NULL) {
  158. grpc_server_destroy(this->wrapped_server);
  159. this->wrapped_server = NULL;
  160. }
  161. }
  162. NAN_METHOD(ServerShutdownCallback) {
  163. if (!info[0]->IsNull()) {
  164. return Nan::ThrowError("forceShutdown failed somehow");
  165. }
  166. }
  167. void Server::ShutdownServer() {
  168. Nan::HandleScope scope;
  169. if (this->wrapped_server != NULL) {
  170. if (shutdown_callback == NULL) {
  171. Local<FunctionTemplate> callback_tpl =
  172. Nan::New<FunctionTemplate>(ServerShutdownCallback);
  173. shutdown_callback =
  174. new Callback(Nan::GetFunction(callback_tpl).ToLocalChecked());
  175. }
  176. ServerShutdownOp *op = new ServerShutdownOp(this->wrapped_server);
  177. unique_ptr<OpVec> ops(new OpVec());
  178. ops->push_back(unique_ptr<Op>(op));
  179. grpc_server_shutdown_and_notify(
  180. this->wrapped_server, GetCompletionQueue(),
  181. new struct tag(new Callback(**shutdown_callback), ops.release(), NULL,
  182. Nan::Null()));
  183. grpc_server_cancel_all_calls(this->wrapped_server);
  184. CompletionQueueNext();
  185. this->wrapped_server = NULL;
  186. }
  187. }
  188. NAN_METHOD(Server::New) {
  189. /* If this is not a constructor call, make a constructor call and return
  190. the result */
  191. if (!info.IsConstructCall()) {
  192. const int argc = 1;
  193. Local<Value> argv[argc] = {info[0]};
  194. MaybeLocal<Object> maybe_instance =
  195. Nan::NewInstance(constructor->GetFunction(), argc, argv);
  196. if (maybe_instance.IsEmpty()) {
  197. // There's probably a pending exception
  198. return;
  199. } else {
  200. info.GetReturnValue().Set(maybe_instance.ToLocalChecked());
  201. return;
  202. }
  203. }
  204. grpc_server *wrapped_server;
  205. grpc_completion_queue *queue = GetCompletionQueue();
  206. grpc_channel_args *channel_args;
  207. if (!ParseChannelArgs(info[0], &channel_args)) {
  208. DeallocateChannelArgs(channel_args);
  209. return Nan::ThrowTypeError(
  210. "Server options must be an object with "
  211. "string keys and integer or string values");
  212. }
  213. wrapped_server = grpc_server_create(channel_args, NULL);
  214. DeallocateChannelArgs(channel_args);
  215. grpc_server_register_completion_queue(wrapped_server, queue, NULL);
  216. Server *server = new Server(wrapped_server);
  217. server->Wrap(info.This());
  218. info.GetReturnValue().Set(info.This());
  219. }
  220. NAN_METHOD(Server::RequestCall) {
  221. if (!HasInstance(info.This())) {
  222. return Nan::ThrowTypeError("requestCall can only be called on a Server");
  223. }
  224. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  225. NewCallOp *op = new NewCallOp();
  226. unique_ptr<OpVec> ops(new OpVec());
  227. ops->push_back(unique_ptr<Op>(op));
  228. grpc_call_error error = grpc_server_request_call(
  229. server->wrapped_server, &op->call, &op->details, &op->request_metadata,
  230. GetCompletionQueue(), GetCompletionQueue(),
  231. new struct tag(new Callback(info[0].As<Function>()), ops.release(), NULL,
  232. Nan::Null()));
  233. if (error != GRPC_CALL_OK) {
  234. return Nan::ThrowError(nanErrorWithCode("requestCall failed", error));
  235. }
  236. CompletionQueueNext();
  237. }
  238. NAN_METHOD(Server::AddHttp2Port) {
  239. if (!HasInstance(info.This())) {
  240. return Nan::ThrowTypeError("addHttp2Port can only be called on a Server");
  241. }
  242. if (!info[0]->IsString()) {
  243. return Nan::ThrowTypeError(
  244. "addHttp2Port's first argument must be a String");
  245. }
  246. if (!ServerCredentials::HasInstance(info[1])) {
  247. return Nan::ThrowTypeError(
  248. "addHttp2Port's second argument must be ServerCredentials");
  249. }
  250. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  251. ServerCredentials *creds_object = ObjectWrap::Unwrap<ServerCredentials>(
  252. Nan::To<Object>(info[1]).ToLocalChecked());
  253. grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials();
  254. int port;
  255. if (creds == NULL) {
  256. port = grpc_server_add_insecure_http2_port(server->wrapped_server,
  257. *Utf8String(info[0]));
  258. } else {
  259. port = grpc_server_add_secure_http2_port(server->wrapped_server,
  260. *Utf8String(info[0]), creds);
  261. }
  262. info.GetReturnValue().Set(Nan::New<Number>(port));
  263. }
  264. NAN_METHOD(Server::Start) {
  265. Nan::HandleScope scope;
  266. if (!HasInstance(info.This())) {
  267. return Nan::ThrowTypeError("start can only be called on a Server");
  268. }
  269. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  270. grpc_server_start(server->wrapped_server);
  271. }
  272. NAN_METHOD(Server::TryShutdown) {
  273. Nan::HandleScope scope;
  274. if (!HasInstance(info.This())) {
  275. return Nan::ThrowTypeError("tryShutdown can only be called on a Server");
  276. }
  277. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  278. if (server->wrapped_server == NULL) {
  279. // Server is already shut down. Call callback immediately.
  280. Nan::Callback callback(info[0].As<Function>());
  281. callback.Call(0, {});
  282. return;
  283. }
  284. TryShutdownOp *op = new TryShutdownOp(server, info.This());
  285. unique_ptr<OpVec> ops(new OpVec());
  286. ops->push_back(unique_ptr<Op>(op));
  287. grpc_server_shutdown_and_notify(
  288. server->wrapped_server, GetCompletionQueue(),
  289. new struct tag(new Nan::Callback(info[0].As<Function>()), ops.release(),
  290. NULL, Nan::Null()));
  291. CompletionQueueNext();
  292. }
  293. NAN_METHOD(Server::ForceShutdown) {
  294. Nan::HandleScope scope;
  295. if (!HasInstance(info.This())) {
  296. return Nan::ThrowTypeError("forceShutdown can only be called on a Server");
  297. }
  298. Server *server = ObjectWrap::Unwrap<Server>(info.This());
  299. server->ShutdownServer();
  300. }
  301. } // namespace node
  302. } // namespace grpc