[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-10 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344506148
 
 

 ##
 File path: src/common/util.h
 ##
 @@ -61,6 +65,41 @@ inline int TVMPClose(FILE* stream) {
   return pclose(stream);
 #endif
 }
+
+/*
+ * gnulib sys_wait.h.in says on Windows
 
 Review comment:
   To be on the safe side(license), I think we should avoid mention gnulib if 
you created the status handling code by yourself


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-09 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344461742
 
 

 ##
 File path: apps/cpp_rpc/rpc_env.cc
 ##
 @@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file rpc_env.cc
+ * \brief Server environment of the RPC.
+ */
+#include 
+#include 
+#ifndef _MSC_VER
+#include 
+#include 
+#include 
+#else
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_env.h"
+#include "../../src/common/util.h"
+#include "../../src/runtime/file_util.h"
+
+namespace tvm {
+namespace runtime {
+
+RPCEnv::RPCEnv() {
+  #if defined(__linux__) || defined(__ANDROID__)
+base_ = "./rpc";
+mkdir(_[0], 0777);
+
+TVM_REGISTER_GLOBAL("tvm.rpc.server.workpath")
+.set_body([](TVMArgs args, TVMRetValue* rv) {
+static RPCEnv env;
+*rv = env.GetPath(args[0]);
+  });
+
+TVM_REGISTER_GLOBAL("tvm.rpc.server.load_module")
+.set_body([](TVMArgs args, TVMRetValue *rv) {
+static RPCEnv env;
+std::string file_name = env.GetPath(args[0]);
+*rv = Load(_name, "");
+LOG(INFO) << "Load module from " << file_name << " ...";
+  });
+  #else
+LOG(FATAL) << "Only support RPC in linux environment";
+  #endif
+}
+/*!
+ * \brief GetPath To get the workpath from packed function
+ * \param name The file name
+ * \return The full path of file.
+ */
+std::string RPCEnv::GetPath(std::string file_name) {
+  // we assume file_name has "/" means file_name is the exact path
+  // and does not create /.rpc/
+  if (file_name.find("/") != std::string::npos) {
+return file_name;
+  } else {
+return base_ + "/" + file_name;
+  }
+}
+/*!
+ * \brief Remove The RPC Environment cleanup function
+ */
+void RPCEnv::CleanUp() {
+  #if defined(__linux__) || defined(__ANDROID__)
+CleanDir(_[0]);
+int ret = rmdir(_[0]);
+if (ret != 0) {
+  LOG(WARNING) << "Remove directory " << base_ << " failed";
+}
+  #else
+LOG(FATAL) << "Only support RPC in linux environment";
+  #endif
+}
+
+/*!
+ * \brief ListDir get the list of files in a directory
+ * \param dirname The root directory name
+ * \return vector Files in directory.
+ */
+std::vector ListDir(const std::string ) {
+  std::vector vec;
+  #ifndef _MSC_VER
+DIR *dp = opendir(dirname.c_str());
+if (dp == NULL) {
+  int errsv = errno;
+  LOG(FATAL) << "ListDir " << dirname <<" error: " << strerror(errsv);
+}
+dirent *d;
+while ((d = readdir(dp)) != NULL) {
+  std::string filename = d->d_name;
+  if (filename != "." && filename != "..") {
+std::string f = dirname;
+if (f[f.length() - 1] != '/') {
+  f += '/';
+}
+f += d->d_name;
+vec.push_back(f);
+  }
+}
+closedir(dp);
+  #else
+WIN32_FIND_DATA fd;
+std::string pattern = dirname + "/*";
+HANDLE handle = FindFirstFile(pattern.c_str(), );
+if (handle == INVALID_HANDLE_VALUE) {
+  int errsv = GetLastError();
+  LOG(FATAL) << "ListDir " << dirname << " error: " << strerror(errsv);
+}
+do {
+  if (fd.cFileName != "." && fd.cFileName != "..") {
+std::string  f = dirname;
+char clast = f[f.length() - 1];
+if (f == ".") {
+  f = fd.cFileName;
+} else if (clast != '/' && clast != '\\') {
+  f += '/';
+  f += fd.cFileName;
+}
+vec.push_back(f);
+  }
+}  while (FindNextFile(handle, ));
+FindClose(handle);
+  #endif
+  return vec;
+}
+
+/*!
+ * \brief LinuxShared Creates a linux shared library
+ * \param output The output file name
+ * \param files The files for building
+ * \param options The compiler options
+ * \param cc The compiler
+ */
+void LinuxShared(const std::string output,
+ const std::vector ,
+ std::string options = "",
+ std::string cc = "g++") {
+std::string cmd = cc;
+cmd += " -shared -fPIC ";
+cmd += " -o " + output;
+for (auto f = files.begin(); f != files.end(); ++f) {
+ cmd += " " + *f;
+}
+cmd += " " + options;
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-09 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344461656
 
 

 ##
 File path: apps/cpp_rpc/rpc_env.cc
 ##
 @@ -164,7 +164,8 @@ void LinuxShared(const std::string output,
  cmd += " " + *f;
 }
 cmd += " " + options;
-CHECK(system(cmd.c_str()) == 0) << "Compilation error.";
+std::string executed_result = common::Execute(cmd);
 
 Review comment:
   You will need to check the status(returned by PClose), instead of the result 
message, because it could be possible that compilation prints things but still 
returns 0 status(which means compilation is successful). Please see my original 
comment


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-09 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344454480
 
 

 ##
 File path: apps/cpp_rpc/rpc_env.cc
 ##
 @@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file rpc_env.cc
+ * \brief Server environment of the RPC.
+ */
+#include 
+#include 
+#ifndef _MSC_VER
+#include 
+#include 
+#include 
+#else
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_env.h"
+#include "../../src/common/util.h"
+#include "../../src/runtime/file_util.h"
+
+namespace tvm {
+namespace runtime {
+
+RPCEnv::RPCEnv() {
+  #if defined(__linux__) || defined(__ANDROID__)
+base_ = "./rpc";
+mkdir(_[0], 0777);
+
+TVM_REGISTER_GLOBAL("tvm.rpc.server.workpath")
+.set_body([](TVMArgs args, TVMRetValue* rv) {
+static RPCEnv env;
+*rv = env.GetPath(args[0]);
+  });
+
+TVM_REGISTER_GLOBAL("tvm.rpc.server.load_module")
+.set_body([](TVMArgs args, TVMRetValue *rv) {
+static RPCEnv env;
+std::string file_name = env.GetPath(args[0]);
+*rv = Load(_name, "");
+LOG(INFO) << "Load module from " << file_name << " ...";
+  });
+  #else
+LOG(FATAL) << "Only support RPC in linux environment";
+  #endif
+}
+/*!
+ * \brief GetPath To get the workpath from packed function
+ * \param name The file name
+ * \return The full path of file.
+ */
+std::string RPCEnv::GetPath(std::string file_name) {
+  // we assume file_name has "/" means file_name is the exact path
+  // and does not create /.rpc/
+  if (file_name.find("/") != std::string::npos) {
+return file_name;
+  } else {
+return base_ + "/" + file_name;
+  }
+}
+/*!
+ * \brief Remove The RPC Environment cleanup function
+ */
+void RPCEnv::CleanUp() {
+  #if defined(__linux__) || defined(__ANDROID__)
+CleanDir(_[0]);
+int ret = rmdir(_[0]);
+if (ret != 0) {
+  LOG(WARNING) << "Remove directory " << base_ << " failed";
+}
+  #else
+LOG(FATAL) << "Only support RPC in linux environment";
+  #endif
+}
+
+/*!
+ * \brief ListDir get the list of files in a directory
+ * \param dirname The root directory name
+ * \return vector Files in directory.
+ */
+std::vector ListDir(const std::string ) {
+  std::vector vec;
+  #ifndef _MSC_VER
+DIR *dp = opendir(dirname.c_str());
+if (dp == NULL) {
+  int errsv = errno;
+  LOG(FATAL) << "ListDir " << dirname <<" error: " << strerror(errsv);
+}
+dirent *d;
+while ((d = readdir(dp)) != NULL) {
+  std::string filename = d->d_name;
+  if (filename != "." && filename != "..") {
+std::string f = dirname;
+if (f[f.length() - 1] != '/') {
+  f += '/';
+}
+f += d->d_name;
+vec.push_back(f);
+  }
+}
+closedir(dp);
+  #else
+WIN32_FIND_DATA fd;
+std::string pattern = dirname + "/*";
+HANDLE handle = FindFirstFile(pattern.c_str(), );
+if (handle == INVALID_HANDLE_VALUE) {
+  int errsv = GetLastError();
+  LOG(FATAL) << "ListDir " << dirname << " error: " << strerror(errsv);
+}
+do {
+  if (fd.cFileName != "." && fd.cFileName != "..") {
+std::string  f = dirname;
+char clast = f[f.length() - 1];
+if (f == ".") {
+  f = fd.cFileName;
+} else if (clast != '/' && clast != '\\') {
+  f += '/';
+  f += fd.cFileName;
+}
+vec.push_back(f);
+  }
+}  while (FindNextFile(handle, ));
+FindClose(handle);
+  #endif
+  return vec;
+}
+
+/*!
+ * \brief LinuxShared Creates a linux shared library
+ * \param output The output file name
+ * \param files The files for building
+ * \param options The compiler options
+ * \param cc The compiler
+ */
+void LinuxShared(const std::string output,
+ const std::vector ,
+ std::string options = "",
+ std::string cc = "g++") {
+std::string cmd = cc;
+cmd += " -shared -fPIC ";
+cmd += " -o " + output;
+for (auto f = files.begin(); f != files.end(); ++f) {
+ cmd += " " + *f;
+}
+cmd += " " + options;
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-09 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344454480
 
 

 ##
 File path: apps/cpp_rpc/rpc_env.cc
 ##
 @@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file rpc_env.cc
+ * \brief Server environment of the RPC.
+ */
+#include 
+#include 
+#ifndef _MSC_VER
+#include 
+#include 
+#include 
+#else
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_env.h"
+#include "../../src/common/util.h"
+#include "../../src/runtime/file_util.h"
+
+namespace tvm {
+namespace runtime {
+
+RPCEnv::RPCEnv() {
+  #if defined(__linux__) || defined(__ANDROID__)
+base_ = "./rpc";
+mkdir(_[0], 0777);
+
+TVM_REGISTER_GLOBAL("tvm.rpc.server.workpath")
+.set_body([](TVMArgs args, TVMRetValue* rv) {
+static RPCEnv env;
+*rv = env.GetPath(args[0]);
+  });
+
+TVM_REGISTER_GLOBAL("tvm.rpc.server.load_module")
+.set_body([](TVMArgs args, TVMRetValue *rv) {
+static RPCEnv env;
+std::string file_name = env.GetPath(args[0]);
+*rv = Load(_name, "");
+LOG(INFO) << "Load module from " << file_name << " ...";
+  });
+  #else
+LOG(FATAL) << "Only support RPC in linux environment";
+  #endif
+}
+/*!
+ * \brief GetPath To get the workpath from packed function
+ * \param name The file name
+ * \return The full path of file.
+ */
+std::string RPCEnv::GetPath(std::string file_name) {
+  // we assume file_name has "/" means file_name is the exact path
+  // and does not create /.rpc/
+  if (file_name.find("/") != std::string::npos) {
+return file_name;
+  } else {
+return base_ + "/" + file_name;
+  }
+}
+/*!
+ * \brief Remove The RPC Environment cleanup function
+ */
+void RPCEnv::CleanUp() {
+  #if defined(__linux__) || defined(__ANDROID__)
+CleanDir(_[0]);
+int ret = rmdir(_[0]);
+if (ret != 0) {
+  LOG(WARNING) << "Remove directory " << base_ << " failed";
+}
+  #else
+LOG(FATAL) << "Only support RPC in linux environment";
+  #endif
+}
+
+/*!
+ * \brief ListDir get the list of files in a directory
+ * \param dirname The root directory name
+ * \return vector Files in directory.
+ */
+std::vector ListDir(const std::string ) {
+  std::vector vec;
+  #ifndef _MSC_VER
+DIR *dp = opendir(dirname.c_str());
+if (dp == NULL) {
+  int errsv = errno;
+  LOG(FATAL) << "ListDir " << dirname <<" error: " << strerror(errsv);
+}
+dirent *d;
+while ((d = readdir(dp)) != NULL) {
+  std::string filename = d->d_name;
+  if (filename != "." && filename != "..") {
+std::string f = dirname;
+if (f[f.length() - 1] != '/') {
+  f += '/';
+}
+f += d->d_name;
+vec.push_back(f);
+  }
+}
+closedir(dp);
+  #else
+WIN32_FIND_DATA fd;
+std::string pattern = dirname + "/*";
+HANDLE handle = FindFirstFile(pattern.c_str(), );
+if (handle == INVALID_HANDLE_VALUE) {
+  int errsv = GetLastError();
+  LOG(FATAL) << "ListDir " << dirname << " error: " << strerror(errsv);
+}
+do {
+  if (fd.cFileName != "." && fd.cFileName != "..") {
+std::string  f = dirname;
+char clast = f[f.length() - 1];
+if (f == ".") {
+  f = fd.cFileName;
+} else if (clast != '/' && clast != '\\') {
+  f += '/';
+  f += fd.cFileName;
+}
+vec.push_back(f);
+  }
+}  while (FindNextFile(handle, ));
+FindClose(handle);
+  #endif
+  return vec;
+}
+
+/*!
+ * \brief LinuxShared Creates a linux shared library
+ * \param output The output file name
+ * \param files The files for building
+ * \param options The compiler options
+ * \param cc The compiler
+ */
+void LinuxShared(const std::string output,
+ const std::vector ,
+ std::string options = "",
+ std::string cc = "g++") {
+std::string cmd = cc;
+cmd += " -shared -fPIC ";
+cmd += " -o " + output;
+for (auto f = files.begin(); f != files.end(); ++f) {
+ cmd += " " + *f;
+}
+cmd += " " + options;
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-09 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344453766
 
 

 ##
 File path: apps/cpp_rpc/main.cc
 ##
 @@ -0,0 +1,269 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file rpc_server.cc
+ * \brief RPC Server for TVM.
+ */
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "../../src/common/util.h"
+#include "../../src/common/socket.h"
+#include "rpc_server.h"
+
+using namespace std;
+using namespace tvm::runtime;
+using namespace tvm::common;
+
+static const string kUSAGE = \
+"Command line usage\n" \
+" server   - Start the server\n" \
+"--host- The hostname of the server, Default=0.0.0.0\n" \
+"--port- The port of the RPC, Default=9090\n" \
+"--port-end- The end search port of the RPC, Default=9199\n" \
+"--tracker - The RPC tracker address in host:port format e.g. 
10.1.1.2:9190 Default=\"\"\n" \
+"--key - The key used to identify the device type in tracker. 
Default=\"\"\n" \
+"--custom-addr - Custom IP Address to Report to RPC Tracker. Default=\"\"\n" \
+"--silent  - Whether to run in silent mode. Default=True\n" \
+"--proxy   - Whether to run in proxy mode. Default=False\n" \
+"\n" \
+"  Example\n" \
+"  ./tvm_rpc server --host=0.0.0.0 --port=9000 --port-end=9090 "
+" --tracker=127.0.0.1:9190 --key=rasp" \
+"\n";
+
+/*!
+ * \brief RpcServerArgs.
+ * \arg host The hostname of the server, Default=0.0.0.0
+ * \arg port The port of the RPC, Default=9090
+ * \arg port_end The end search port of the RPC, Default=9199
+ * \arg tracker The address of RPC tracker in host:port format e.g. 
10.77.1.234:9190 Default=""
+ * \arg key The key used to identify the device type in tracker. Default=""
+ * \arg custom_addr Custom IP Address to Report to RPC Tracker. Default=""
+ * \arg silent Whether run in silent mode. Default=True
+ * \arg is_proxy Whether to run in proxy mode. Default=False
+ */
+struct RpcServerArgs {
+  string host = "0.0.0.0";
+  int port = 9090;
+  int port_end = 9099;
+  string tracker;
+  string key;
+  string custom_addr;
+  bool silent = false;
+  bool is_proxy = false;
+};
+
+/*!
+ * \brief PrintArgs print the contents of RpcServerArgs
+ * \param args RpcServerArgs structure
+ */
+void PrintArgs(struct RpcServerArgs args) {
+  LOG(INFO) << "host= " << args.host;
+  LOG(INFO) << "port= " << args.port;
+  LOG(INFO) << "port_end= " << args.port_end;
+  LOG(INFO) << "tracker = " << args.tracker;
+  LOG(INFO) << "key = " << args.key;
+  LOG(INFO) << "custom_addr = " << args.custom_addr;
+  LOG(INFO) << "silent  = " << ((args.silent) ? ("True"): ("False"));
+  LOG(INFO) << "proxy   = " << ((args.is_proxy) ? ("True"): ("False"));
+}
+
+/*!
+ * \brief CtrlCHandler, exits if Ctrl+C is pressed
+ * \param s signal
+ */
+void CtrlCHandler(int s) {
+  LOG(INFO) << "\nUser pressed Ctrl+C, Exiting";
+  exit(1);
+}
+
+/*!
+ * \brief HandleCtrlC Register for handling Ctrl+C event.
+ */
+void HandleCtrlC() {
+  // Ctrl+C handler
+  struct sigaction sigIntHandler;
+  sigIntHandler.sa_handler = CtrlCHandler;
+  sigemptyset(_mask);
+  sigIntHandler.sa_flags = 0;
+  sigaction(SIGINT, , NULL);
 
 Review comment:
   NULL->nullptr


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-09 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344453875
 
 

 ##
 File path: apps/cpp_rpc/rpc_server.cc
 ##
 @@ -0,0 +1,361 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file rpc_server.cc
+ * \brief RPC Server implementation.
+ */
+#include 
+
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_server.h"
+#include "rpc_env.h"
+#include "rpc_tracker_client.h"
+#include "../../src/runtime/rpc/rpc_session.h"
+#include "../../src/runtime/rpc/rpc_socket_impl.h"
+#include "../../src/common/socket.h"
+
+namespace tvm {
+namespace runtime {
+
+#if defined(__linux__) || defined(__ANDROID__)
+static pid_t waitPidEintr(int *status) {
+  pid_t pid = 0;
+  while ((pid = waitpid(-1, status, 0)) == -1) {
+if (errno == EINTR) {
+  continue;
+} else {
+  perror("waitpid");
+  abort();
+}
+  }
+  return pid;
+}
+#endif
+
+/*!
+ * \brief RPCServer RPC Server class.
+ * \param host The hostname of the server, Default=0.0.0.0
+ * \param port The port of the RPC, Default=9090
+ * \param port_end The end search port of the RPC, Default=9199
+ * \param tracker The address of RPC tracker in host:port format e.g. 
10.77.1.234:9190 Default=""
+ * \param key The key used to identify the device type in tracker. Default=""
+ * \param custom_addr Custom IP Address to Report to RPC Tracker. Default=""
+ * \param is_proxy Whether to run in proxy mode. Default=False
+ */
+class RPCServer {
+ public:
+  /*!
+   * \brief Constructor.
+  */
+  RPCServer(const std::string ,
+int port,
+int port_end,
+const std::string _addr,
+const std::string ,
+const std::string _addr,
+bool is_proxy) {
+// Init the values
+host_ = host;
+port_ = port;
+port_end_ = port_end;
+tracker_addr_ = tracker_addr;
+key_ = key;
+custom_addr_ = custom_addr;
+is_proxy_ = is_proxy;
+  }
+
+  /*!
+   * \brief Destructor.
+  */
+  ~RPCServer() {
+// Free the resources
+tracker_sock_.Close();
+listen_sock_.Close();
+  }
+
+  /*!
+   * \brief Start Creates the RPC listen process and execution.
+  */
+  void Start() {
+  listen_sock_.Create();
+  my_port_ = listen_sock_.TryBindHost(host_, port_, port_end_);
+  LOG(INFO) << "bind to " << host_ << ":" << my_port_;
+  listen_sock_.Listen(1);
+  std::future proc(std::async(std::launch::async, 
::ListenLoopProc, this));
+  proc.get();
+  // Close the listen socket
+  listen_sock_.Close();
+  }
+
+ private:
+  /*!
+   * \brief ListenLoopProc The listen process.
+   */
+  void ListenLoopProc() {
+TrackerClient tracker(tracker_addr_, key_, custom_addr_);
+while (true) {
+  common::TCPSocket conn;
+  common::SockAddr addr("0.0.0.0", 0);
+  std::string opts;
+  try {
+// step 1: setup tracker and report to tracker
+tracker.TryConnect();
+// step 2: wait for in-coming connections
+AcceptConnection(, , , );
+  }
+  catch (const char* msg) {
+LOG(WARNING) << "Socket exception: " << msg;
+// close tracker resource
+tracker.Close();
+continue;
+  }
+  catch (std::exception& e) {
+// Other errors
+LOG(WARNING) << "Exception standard: " << e.what();
+continue;
+  }
+
+  int timeout = GetTimeOutFromOpts(opts);
+  #if defined(__linux__) || defined(__ANDROID__)
+// step 3: serving
+if (timeout) {
+  const pid_t timer_pid = fork();
+  if (timer_pid == 0) {
+// Timer process
+sleep(timeout);
+exit(0);
+  }
+
+  const pid_t worker_pid = fork();
+  if (worker_pid == 0) {
+// Worker process
+ServerLoopProc(conn, addr);
+exit(0);
+  }
+
+  int status = 0;
+  const pid_t finished_first = waitPidEintr();
+  if (finished_first == timer_pid) {
+kill(worker_pid, SIGKILL);
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-09 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344453588
 
 

 ##
 File path: apps/cpp_rpc/rpc_env.cc
 ##
 @@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file rpc_env.cc
+ * \brief Server environment of the RPC.
+ */
+#include 
+#include 
+#ifndef _MSC_VER
+#include 
+#include 
+#include 
+#else
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_env.h"
+#include "../../src/common/util.h"
+#include "../../src/runtime/file_util.h"
+
+namespace tvm {
+namespace runtime {
+
+RPCEnv::RPCEnv() {
+  #if defined(__linux__) || defined(__ANDROID__)
+base_ = "./rpc";
+mkdir(_[0], 0777);
+
+TVM_REGISTER_GLOBAL("tvm.rpc.server.workpath")
+.set_body([](TVMArgs args, TVMRetValue* rv) {
+static RPCEnv env;
+*rv = env.GetPath(args[0]);
+  });
+
+TVM_REGISTER_GLOBAL("tvm.rpc.server.load_module")
+.set_body([](TVMArgs args, TVMRetValue *rv) {
+static RPCEnv env;
+std::string file_name = env.GetPath(args[0]);
+*rv = Load(_name, "");
+LOG(INFO) << "Load module from " << file_name << " ...";
+  });
+  #else
+LOG(FATAL) << "Only support RPC in linux environment";
+  #endif
+}
+/*!
+ * \brief GetPath To get the workpath from packed function
+ * \param name The file name
+ * \return The full path of file.
+ */
+std::string RPCEnv::GetPath(std::string file_name) {
+  // we assume file_name has "/" means file_name is the exact path
+  // and does not create /.rpc/
+  if (file_name.find("/") != std::string::npos) {
+return file_name;
+  } else {
+return base_ + "/" + file_name;
+  }
+}
+/*!
+ * \brief Remove The RPC Environment cleanup function
+ */
+void RPCEnv::CleanUp() {
+  #if defined(__linux__) || defined(__ANDROID__)
+CleanDir(_[0]);
+int ret = rmdir(_[0]);
+if (ret != 0) {
+  LOG(WARNING) << "Remove directory " << base_ << " failed";
+}
+  #else
+LOG(FATAL) << "Only support RPC in linux environment";
+  #endif
+}
+
+/*!
+ * \brief ListDir get the list of files in a directory
+ * \param dirname The root directory name
+ * \return vector Files in directory.
+ */
+std::vector ListDir(const std::string ) {
+  std::vector vec;
+  #ifndef _MSC_VER
+DIR *dp = opendir(dirname.c_str());
+if (dp == NULL) {
+  int errsv = errno;
+  LOG(FATAL) << "ListDir " << dirname <<" error: " << strerror(errsv);
+}
+dirent *d;
+while ((d = readdir(dp)) != NULL) {
+  std::string filename = d->d_name;
+  if (filename != "." && filename != "..") {
+std::string f = dirname;
+if (f[f.length() - 1] != '/') {
+  f += '/';
+}
+f += d->d_name;
+vec.push_back(f);
+  }
+}
+closedir(dp);
+  #else
+WIN32_FIND_DATA fd;
+std::string pattern = dirname + "/*";
+HANDLE handle = FindFirstFile(pattern.c_str(), );
+if (handle == INVALID_HANDLE_VALUE) {
+  int errsv = GetLastError();
+  LOG(FATAL) << "ListDir " << dirname << " error: " << strerror(errsv);
+}
+do {
+  if (fd.cFileName != "." && fd.cFileName != "..") {
+std::string  f = dirname;
+char clast = f[f.length() - 1];
+if (f == ".") {
+  f = fd.cFileName;
+} else if (clast != '/' && clast != '\\') {
+  f += '/';
+  f += fd.cFileName;
+}
+vec.push_back(f);
+  }
+}  while (FindNextFile(handle, ));
+FindClose(handle);
+  #endif
+  return vec;
+}
+
+/*!
+ * \brief LinuxShared Creates a linux shared library
+ * \param output The output file name
+ * \param files The files for building
+ * \param options The compiler options
+ * \param cc The compiler
+ */
+void LinuxShared(const std::string output,
+ const std::vector ,
+ std::string options = "",
+ std::string cc = "g++") {
+std::string cmd = cc;
+cmd += " -shared -fPIC ";
+cmd += " -o " + output;
+for (auto f = files.begin(); f != files.end(); ++f) {
+ cmd += " " + *f;
+}
+cmd += " " + options;
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344290589
 
 

 ##
 File path: apps/cpp_rpc/rpc_server.cc
 ##
 @@ -0,0 +1,363 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_server.cc
+ * \brief RPC Server implementation.
+ */
+
+#include 
+
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_server.h"
+#include "rpc_env.h"
+#include "rpc_tracker_client.h"
+#include "../../src/runtime/rpc/rpc_session.h"
+#include "../../src/runtime/rpc/rpc_socket_impl.h"
+#include "../../src/common/socket.h"
+
+#if defined(__linux__) || defined(__ANDROID__)
+static pid_t waitpid_eintr(int *status) {
+  pid_t pid = 0;
+  while ((pid = waitpid(-1, status, 0)) == -1) {
+if (errno == EINTR) {
+  continue;
+} else {
+  perror("waitpid");
+  abort();
+}
+  }
+  return pid;
+}
+#endif
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief RPCServer RPC Server class.
+ * \param host The hostname of the server, Default=0.0.0.0
+ * \param port The port of the RPC, Default=9090
+ * \param port_end The end search port of the RPC, Default=9199
+ * \param tracker The address of RPC tracker in host:port format e.g. 
10.77.1.234:9190 Default=""
+ * \param key The key used to identify the device type in tracker. Default=""
+ * \param custom_addr Custom IP Address to Report to RPC Tracker. Default=""
+ * \param isProxy Whether to run in proxy mode. Default=False
+ */
+class RPCServer {
+ public:
+  /*!
+   * \brief Constructor.
+  */
+  RPCServer(const std::string ,
+int port,
+int port_end,
+const std::string _addr,
+const std::string ,
+const std::string _addr,
+bool is_proxy) {
+// Init the values
+host_ = host;
+port_ = port;
+port_end_ = port_end;
+tracker_addr_ = tracker_addr;
+key_ = key;
+custom_addr_ = custom_addr;
+is_proxy_ = is_proxy;
+  }
+
+  /*!
+   * \brief Destructor.
+  */
+  ~RPCServer() {
+// Free the resources
+tracker_sock_.Close();
+listen_sock_.Close();
+  }
+
+  /*!
+   * \brief Start Creates the RPC listen process and execution.
+  */
+  void Start() {
+  listen_sock_.Create();
+  my_port_ = listen_sock_.TryBindHost(host_, port_, port_end_);
+  LOG(INFO) << "bind to " << host_ << ":" << my_port_;
+  listen_sock_.Listen(1);
+  std::future proc(std::async(std::launch::async, 
::ListenLoopProc, this));
+  proc.get();
+  // Close the listen socket
+  listen_sock_.Close();
+  }
+
+ private:
+  /*!
+   * \brief ListenLoopProc The listen process.
+   */
+  void ListenLoopProc() {
+TrackerClient tracker(tracker_addr_, key_, custom_addr_);
+while (1) {
+  common::TCPSocket conn;
+  common::SockAddr addr("0.0.0.0", 0);
+  std::string opts;
+  try {
+// step 1: setup tracker and report to tracker
+tracker.TryConnect();
+// step 2: wait for in-coming connections
+AcceptConnection(, , , );
+  }
+  catch (const char* msg) {
+LOG(WARNING) << "Socket exception: " << msg;
+// close tracker resource
+tracker.Close();
+continue;
+  }
+  catch (std::exception& e) {
+// Other errors
+LOG(WARNING) << "Exception standard: " << e.what();
+continue;
+  }
+
+  int timeout = GetTimeOutFromOpts(opts);
+  #if defined(__linux__) || defined(__ANDROID__)
+// step 3: serving
+if (timeout) {
+  const pid_t timer_pid = fork();
+  if (timer_pid == 0) {
+// Timer process
+sleep(timeout);
+exit(0);
+  }
+
+  const pid_t worker_pid = fork();
+  if (worker_pid == 0) {
+// Worker process
+ServerLoopProc(conn, addr);
+exit(0);
+  }
+
+  int status = 0;
+  const pid_t finished_first = waitpid_eintr();
+  if (finished_first == timer_pid) {
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344292628
 
 

 ##
 File path: src/common/socket.h
 ##
 @@ -468,7 +524,134 @@ class TCPSocket : public Socket {
 }
 return ndone;
   }
+  /*!
+   * \brief Send the data to remote.
+   * \param data The data to be sent.
+   */
+  void SendBytes(std::string data) {
+int datalen = data.length();
+CHECK_EQ(SendAll(, sizeof(datalen)), sizeof(datalen));
+CHECK_EQ(SendAll(data.c_str(), datalen), datalen);
+  }
+  /*!
+   * \brief Receive the data to remote.
+   * \return The data received.
+   */
+  std::string RecvBytes() {
+int datalen = 0;
+CHECK_EQ(RecvAll(, sizeof(datalen)), sizeof(datalen));
+std::string data;
+data.resize(datalen);
+CHECK_EQ(RecvAll([0], datalen), datalen);
+return data;
+  }
 };
+
+/*! \brief helper data structure to perform select */
+struct SelectHelper {
 
 Review comment:
   consider use poll instead 
https://github.com/dmlc/rabit/blob/master/include/rabit/internal/socket.h#L441 
   
   select has a limit on the descriptor size which poll resolves


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344289079
 
 

 ##
 File path: apps/cpp_rpc/rpc_server.cc
 ##
 @@ -0,0 +1,363 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_server.cc
+ * \brief RPC Server implementation.
+ */
+
+#include 
+
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_server.h"
+#include "rpc_env.h"
+#include "rpc_tracker_client.h"
+#include "../../src/runtime/rpc/rpc_session.h"
+#include "../../src/runtime/rpc/rpc_socket_impl.h"
+#include "../../src/common/socket.h"
+
+#if defined(__linux__) || defined(__ANDROID__)
+static pid_t waitpid_eintr(int *status) {
+  pid_t pid = 0;
+  while ((pid = waitpid(-1, status, 0)) == -1) {
+if (errno == EINTR) {
+  continue;
+} else {
+  perror("waitpid");
+  abort();
+}
+  }
+  return pid;
+}
+#endif
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief RPCServer RPC Server class.
+ * \param host The hostname of the server, Default=0.0.0.0
+ * \param port The port of the RPC, Default=9090
+ * \param port_end The end search port of the RPC, Default=9199
+ * \param tracker The address of RPC tracker in host:port format e.g. 
10.77.1.234:9190 Default=""
+ * \param key The key used to identify the device type in tracker. Default=""
+ * \param custom_addr Custom IP Address to Report to RPC Tracker. Default=""
+ * \param isProxy Whether to run in proxy mode. Default=False
 
 Review comment:
   is_proxy


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344291055
 
 

 ##
 File path: src/common/socket.h
 ##
 @@ -62,6 +65,25 @@ inline std::string GetHostName() {
   return std::string(buf.c_str());
 }
 
+/*!
+ * \brief ValidateIP validates an ip address.
+ * \param ip The ip address in string format localhost or x.x.x.x format
+ * \return result of operation.
+ */
+inline bool ValidateIP(std::string ip) {
+  if (ip == "localhost") {
+return true;
+  }
+  std::vector list = Split(ip, '.');
+  if (list.size() != 4)
 
 Review comment:
   google c style, enclose with {} if it contains multiple lines


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344291688
 
 

 ##
 File path: src/common/socket.h
 ##
 @@ -62,6 +65,25 @@ inline std::string GetHostName() {
   return std::string(buf.c_str());
 }
 
+/*!
+ * \brief ValidateIP validates an ip address.
+ * \param ip The ip address in string format localhost or x.x.x.x format
+ * \return result of operation.
+ */
+inline bool ValidateIP(std::string ip) {
+  if (ip == "localhost") {
+return true;
+  }
+  std::vector list = Split(ip, '.');
+  if (list.size() != 4)
 
 Review comment:
   Ideally, we should just use std::istringstream to do the validation(to 
reduce memory complexity). Given that this is a util function, we would like to 
apply such higher standard


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344288316
 
 

 ##
 File path: apps/cpp_rpc/rpc_env.h
 ##
 @@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_env.h
+ * \brief Server environment of the RPC.
+ */
+#ifndef TVM_APPS_CPP_RPC_ENV_H_
+#define TVM_APPS_CPP_RPC_ENV_H_
+
+#include 
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief Load Load module from file
+  This function will automatically call
+  cc.create_shared if the path is in format .o or .tar
+  High level handling for .o and .tar file.
+  We support this to be consistent with RPC module load.
+ * \param file The input file
+ * \param file The format of file
+ * \return Module The loaded module
+ */
+Module Load(std::string *path, const std::string fmt = "");
+
+/*!
+ * \brief CleanDir Removes the files from the directory
+ * \param dirname THe name of the directory
+ */
+void CleanDir(const std::string );
+
+/*!
+ * \brief RPCEnv The RPC Environment parameters for c++ rpc server
+ */
+struct RPCEnv {
+ public:
+   /*!
+* \brief Constructor Init The RPC Environment initialize function
+*/
+  RPCEnv();
+  /*!
+   * \brief GetPath To get the workpath from packed function
+   * \param name The file name
+   * \return The full path of file.
+   */
+  std::string GetPath(const std::string& file_name);
+  /*!
+   * \brief Remove The RPC Environment cleanup function
+   */
+  void Remove();
 
 Review comment:
   Rename to Cleanup, let us make sure that the cleanup function is 
idempotent(you can call it multiple times, so that you can also call it from 
the destructor


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344289337
 
 

 ##
 File path: apps/cpp_rpc/rpc_server.cc
 ##
 @@ -0,0 +1,363 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_server.cc
+ * \brief RPC Server implementation.
+ */
+
+#include 
+
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_server.h"
+#include "rpc_env.h"
+#include "rpc_tracker_client.h"
+#include "../../src/runtime/rpc/rpc_session.h"
+#include "../../src/runtime/rpc/rpc_socket_impl.h"
+#include "../../src/common/socket.h"
+
+#if defined(__linux__) || defined(__ANDROID__)
+static pid_t waitpid_eintr(int *status) {
+  pid_t pid = 0;
+  while ((pid = waitpid(-1, status, 0)) == -1) {
+if (errno == EINTR) {
+  continue;
+} else {
+  perror("waitpid");
+  abort();
+}
+  }
+  return pid;
+}
+#endif
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief RPCServer RPC Server class.
+ * \param host The hostname of the server, Default=0.0.0.0
+ * \param port The port of the RPC, Default=9090
+ * \param port_end The end search port of the RPC, Default=9199
+ * \param tracker The address of RPC tracker in host:port format e.g. 
10.77.1.234:9190 Default=""
+ * \param key The key used to identify the device type in tracker. Default=""
+ * \param custom_addr Custom IP Address to Report to RPC Tracker. Default=""
+ * \param isProxy Whether to run in proxy mode. Default=False
+ */
+class RPCServer {
+ public:
+  /*!
+   * \brief Constructor.
+  */
+  RPCServer(const std::string ,
+int port,
+int port_end,
+const std::string _addr,
+const std::string ,
+const std::string _addr,
+bool is_proxy) {
+// Init the values
+host_ = host;
+port_ = port;
+port_end_ = port_end;
+tracker_addr_ = tracker_addr;
+key_ = key;
+custom_addr_ = custom_addr;
+is_proxy_ = is_proxy;
+  }
+
+  /*!
+   * \brief Destructor.
+  */
+  ~RPCServer() {
+// Free the resources
+tracker_sock_.Close();
+listen_sock_.Close();
+  }
+
+  /*!
+   * \brief Start Creates the RPC listen process and execution.
+  */
+  void Start() {
+  listen_sock_.Create();
+  my_port_ = listen_sock_.TryBindHost(host_, port_, port_end_);
+  LOG(INFO) << "bind to " << host_ << ":" << my_port_;
+  listen_sock_.Listen(1);
+  std::future proc(std::async(std::launch::async, 
::ListenLoopProc, this));
+  proc.get();
+  // Close the listen socket
+  listen_sock_.Close();
+  }
+
+ private:
+  /*!
+   * \brief ListenLoopProc The listen process.
+   */
+  void ListenLoopProc() {
+TrackerClient tracker(tracker_addr_, key_, custom_addr_);
+while (1) {
+  common::TCPSocket conn;
+  common::SockAddr addr("0.0.0.0", 0);
+  std::string opts;
+  try {
+// step 1: setup tracker and report to tracker
+tracker.TryConnect();
+// step 2: wait for in-coming connections
+AcceptConnection(, , , );
+  }
+  catch (const char* msg) {
+LOG(WARNING) << "Socket exception: " << msg;
+// close tracker resource
+tracker.Close();
+continue;
+  }
+  catch (std::exception& e) {
+// Other errors
+LOG(WARNING) << "Exception standard: " << e.what();
+continue;
+  }
+
+  int timeout = GetTimeOutFromOpts(opts);
+  #if defined(__linux__) || defined(__ANDROID__)
+// step 3: serving
+if (timeout) {
+  const pid_t timer_pid = fork();
+  if (timer_pid == 0) {
+// Timer process
+sleep(timeout);
+exit(0);
+  }
+
+  const pid_t worker_pid = fork();
+  if (worker_pid == 0) {
+// Worker process
+ServerLoopProc(conn, addr);
+exit(0);
+  }
+
+  int status = 0;
+  const pid_t finished_first = waitpid_eintr();
+  if (finished_first == timer_pid) {
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344290100
 
 

 ##
 File path: apps/cpp_rpc/rpc_server.cc
 ##
 @@ -0,0 +1,363 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_server.cc
+ * \brief RPC Server implementation.
+ */
+
+#include 
+
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_server.h"
+#include "rpc_env.h"
+#include "rpc_tracker_client.h"
+#include "../../src/runtime/rpc/rpc_session.h"
+#include "../../src/runtime/rpc/rpc_socket_impl.h"
+#include "../../src/common/socket.h"
+
+#if defined(__linux__) || defined(__ANDROID__)
+static pid_t waitpid_eintr(int *status) {
+  pid_t pid = 0;
+  while ((pid = waitpid(-1, status, 0)) == -1) {
+if (errno == EINTR) {
+  continue;
+} else {
+  perror("waitpid");
+  abort();
+}
+  }
+  return pid;
+}
+#endif
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief RPCServer RPC Server class.
+ * \param host The hostname of the server, Default=0.0.0.0
+ * \param port The port of the RPC, Default=9090
+ * \param port_end The end search port of the RPC, Default=9199
+ * \param tracker The address of RPC tracker in host:port format e.g. 
10.77.1.234:9190 Default=""
+ * \param key The key used to identify the device type in tracker. Default=""
+ * \param custom_addr Custom IP Address to Report to RPC Tracker. Default=""
+ * \param isProxy Whether to run in proxy mode. Default=False
+ */
+class RPCServer {
+ public:
+  /*!
+   * \brief Constructor.
+  */
+  RPCServer(const std::string ,
+int port,
+int port_end,
+const std::string _addr,
+const std::string ,
+const std::string _addr,
+bool is_proxy) {
+// Init the values
+host_ = host;
+port_ = port;
+port_end_ = port_end;
+tracker_addr_ = tracker_addr;
+key_ = key;
+custom_addr_ = custom_addr;
+is_proxy_ = is_proxy;
+  }
+
+  /*!
+   * \brief Destructor.
+  */
+  ~RPCServer() {
+// Free the resources
+tracker_sock_.Close();
+listen_sock_.Close();
+  }
+
+  /*!
+   * \brief Start Creates the RPC listen process and execution.
+  */
+  void Start() {
+  listen_sock_.Create();
+  my_port_ = listen_sock_.TryBindHost(host_, port_, port_end_);
+  LOG(INFO) << "bind to " << host_ << ":" << my_port_;
+  listen_sock_.Listen(1);
+  std::future proc(std::async(std::launch::async, 
::ListenLoopProc, this));
+  proc.get();
+  // Close the listen socket
+  listen_sock_.Close();
+  }
+
+ private:
+  /*!
+   * \brief ListenLoopProc The listen process.
+   */
+  void ListenLoopProc() {
+TrackerClient tracker(tracker_addr_, key_, custom_addr_);
+while (1) {
+  common::TCPSocket conn;
+  common::SockAddr addr("0.0.0.0", 0);
+  std::string opts;
+  try {
+// step 1: setup tracker and report to tracker
+tracker.TryConnect();
+// step 2: wait for in-coming connections
+AcceptConnection(, , , );
+  }
+  catch (const char* msg) {
+LOG(WARNING) << "Socket exception: " << msg;
+// close tracker resource
+tracker.Close();
+continue;
+  }
+  catch (std::exception& e) {
+// Other errors
+LOG(WARNING) << "Exception standard: " << e.what();
+continue;
+  }
+
+  int timeout = GetTimeOutFromOpts(opts);
+  #if defined(__linux__) || defined(__ANDROID__)
+// step 3: serving
+if (timeout) {
+  const pid_t timer_pid = fork();
+  if (timer_pid == 0) {
+// Timer process
+sleep(timeout);
+exit(0);
+  }
+
+  const pid_t worker_pid = fork();
+  if (worker_pid == 0) {
+// Worker process
+ServerLoopProc(conn, addr);
+exit(0);
+  }
+
+  int status = 0;
+  const pid_t finished_first = waitpid_eintr();
+  if (finished_first == timer_pid) {
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344289033
 
 

 ##
 File path: apps/cpp_rpc/rpc_server.cc
 ##
 @@ -0,0 +1,363 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_server.cc
+ * \brief RPC Server implementation.
+ */
+
+#include 
+
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_server.h"
+#include "rpc_env.h"
+#include "rpc_tracker_client.h"
+#include "../../src/runtime/rpc/rpc_session.h"
+#include "../../src/runtime/rpc/rpc_socket_impl.h"
+#include "../../src/common/socket.h"
+
+#if defined(__linux__) || defined(__ANDROID__)
+static pid_t waitpid_eintr(int *status) {
+  pid_t pid = 0;
+  while ((pid = waitpid(-1, status, 0)) == -1) {
+if (errno == EINTR) {
+  continue;
+} else {
+  perror("waitpid");
+  abort();
+}
+  }
+  return pid;
+}
+#endif
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief RPCServer RPC Server class.
+ * \param host The hostname of the server, Default=0.0.0.0
 
 Review comment:
   should these arguments be part of the constructor?


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344288861
 
 

 ##
 File path: apps/cpp_rpc/rpc_server.cc
 ##
 @@ -0,0 +1,363 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_server.cc
+ * \brief RPC Server implementation.
+ */
+
+#include 
+
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_server.h"
+#include "rpc_env.h"
+#include "rpc_tracker_client.h"
+#include "../../src/runtime/rpc/rpc_session.h"
+#include "../../src/runtime/rpc/rpc_socket_impl.h"
+#include "../../src/common/socket.h"
+
+#if defined(__linux__) || defined(__ANDROID__)
+static pid_t waitpid_eintr(int *status) {
 
 Review comment:
   Use CamelCase (google C style), consider move to the internal namespace


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344288460
 
 

 ##
 File path: apps/cpp_rpc/rpc_env.h
 ##
 @@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
 
 Review comment:
   copyright is nolonger needed with ASF hader


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344293102
 
 

 ##
 File path: apps/cpp_rpc/rpc_tracker_client.h
 ##
 @@ -0,0 +1,249 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_tracker_client.h
+ * \brief RPC Tracker client to report resources.
+ */
+#ifndef TVM_APPS_CPP_RPC_TRACKER_CLIENT_H_
+#define TVM_APPS_CPP_RPC_TRACKER_CLIENT_H_
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "../../src/runtime/rpc/rpc_session.h"
+#include "../../src/common/socket.h"
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief TrackerClient Tracker client class.
+ * \param tracker The address of RPC tracker in host:port format e.g. 
10.77.1.234:9190 Default=""
+ * \param key The key used to identify the device type in tracker. Default=""
+ * \param custom_addr Custom IP Address to Report to RPC Tracker. Default=""
+ */
+class TrackerClient {
+ public:
+  /*!
+   * \brief Constructor.
+  */
+  TrackerClient(const std::string _addr,
+const std::string ,
+const std::string _addr) {
+tracker_addr_ = tracker_addr;
+key_ = key;
+custom_addr_ = custom_addr;
+  }
+  /*!
+   * \brief Destructor.
+  */
+  ~TrackerClient() {
+// Free the resources
+Close();
+  }
+  /*!
+   * \brief IsValid Check tracker is valid.
+  */
+  bool IsValid() {
+return (!tracker_addr_.empty() && !tracker_sock_.IsClosed());
+  }
+  /*!
+   * \brief TryConnect Connect to tracker if the tracker address is valid.
+  */
+  void TryConnect() {
+if (!tracker_addr_.empty() && (tracker_sock_.IsClosed())) {
+  tracker_sock_ = ConnectWithRetry();
+
+  int code = kRPCTrackerMagic;
+  CHECK_EQ(tracker_sock_.SendAll(, sizeof(code)), sizeof(code));
+  CHECK_EQ(tracker_sock_.RecvAll(, sizeof(code)), sizeof(code));
+  CHECK_EQ(code, kRPCTrackerMagic) << tracker_addr_.c_str() << " is not 
RPC Tracker";
+
+  std::ostringstream ss;
+  ss << "[" << static_cast(TrackerCode::kUpdateInfo)
+ << ", {\"key\": \"server:"<< key_ << "\"}]";
+  tracker_sock_.SendBytes(ss.str());
+
+  // Receive status and validate
+  std::string remote_status = tracker_sock_.RecvBytes();
+  CHECK_EQ(std::stoi(remote_status), 
static_cast(TrackerCode::kSuccess));
+}
+  }
+  /*!
+   * \brief Close Clean up tracker resources.
+  */
+  void Close() {
+// close tracker resource
+if (!tracker_sock_.IsClosed()) {
+  tracker_sock_.Close();
+}
+  }
+ /*!
+  * \brief ReportResourceAndGetKey Report resource to tracker.
+  * \param port listening port.
+  * \param matchkey Random match key output.
+ */
+  void ReportResourceAndGetKey(int port,
+   std::string *matchkey) {
+if (!tracker_sock_.IsClosed()) {
+  *matchkey = RandomKey(key_ + ":", old_keyset_);
+  if (custom_addr_.empty()) {
+custom_addr_ = "null";
+  }
+
+  std::ostringstream ss;
+  ss << "[" << static_cast(TrackerCode::kPut) << ", \"" << key_ << 
"\", ["
+ << port << ", \"" << *matchkey << "\"], " << custom_addr_ << "]";
+
+  tracker_sock_.SendBytes(ss.str());
+
+  // Receive status and validate
+  std::string remote_status = tracker_sock_.RecvBytes();
+  CHECK_EQ(std::stoi(remote_status), 
static_cast(TrackerCode::kSuccess));
+} else {
+*matchkey = key_;
+}
+  }
+
+  /*!
+   * \brief ReportResourceAndGetKey Report resource to tracker.
+   * \param listen_sock Listen socket details for select.
+   * \param port listening port.
+   * \param ping_period Select wait time.
+   * \param matchkey Random match key output.
+  */
+  void WaitConnectionAndUpdateKey(common::TCPSocket listen_sock,
+  int port,
+  int ping_period,
+  std::string *matchkey) {
+int unmatch_period_count = 0;
+int unmatch_timeout = 4;
+while (1) {
+  if (!tracker_sock_.IsClosed()) {
+common::SelectHelper selecter;
+selecter.WatchRead(listen_sock.sockfd);
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344293873
 
 

 ##
 File path: apps/cpp_rpc/rpc_env.cc
 ##
 @@ -0,0 +1,248 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_env.cc
+ * \brief Server environment of the RPC.
+ */
+#include 
+#include 
+#ifndef _MSC_VER
+#include 
+#include 
+#include 
+#else
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_env.h"
+#include "../../src/common/util.h"
+#include "../../src/runtime/file_util.h"
+
+namespace tvm {
+namespace runtime {
+
+RPCEnv::RPCEnv() {
+  #if defined(__linux__) || defined(__ANDROID__)
+base_ = "./rpc";
+mkdir(_[0], 0777);
+
+TVM_REGISTER_GLOBAL("tvm.rpc.server.workpath")
+.set_body([](TVMArgs args, TVMRetValue* rv) {
+static RPCEnv env;
+*rv = env.GetPath(args[0]);
+  });
+
+TVM_REGISTER_GLOBAL("tvm.rpc.server.load_module")
+.set_body([](TVMArgs args, TVMRetValue *rv) {
+static RPCEnv env;
+std::string file_name = env.GetPath(args[0]);
+*rv = Load(_name, "");
+LOG(INFO) << "Load module from " << file_name << " ...";
+  });
+  #else
+LOG(FATAL) << "Only support RPC in linux environment";
+  #endif
+}
+/*!
+ * \brief GetPath To get the workpath from packed function
+ * \param name The file name
+ * \return The full path of file.
+ */
+std::string RPCEnv::GetPath(const std::string& file_name) {
 
 Review comment:
   in the case of when we will have to copy file_name anyway, it is better to 
make the argument
   
   ```std::string file_name``` (no reference), so sometimes the compiler can do 
a move or directly elide copy if we pass a std::string that is not being used 
else-where


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344288617
 
 

 ##
 File path: apps/cpp_rpc/rpc_env.h
 ##
 @@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_env.h
+ * \brief Server environment of the RPC.
+ */
+#ifndef TVM_APPS_CPP_RPC_ENV_H_
+#define TVM_APPS_CPP_RPC_ENV_H_
+
+#include 
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
 
 Review comment:
   These headers has nothing to do with implementation, consider put them into 
the cc file instead


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344289224
 
 

 ##
 File path: apps/cpp_rpc/rpc_server.cc
 ##
 @@ -0,0 +1,363 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_server.cc
+ * \brief RPC Server implementation.
+ */
+
+#include 
+
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_server.h"
+#include "rpc_env.h"
+#include "rpc_tracker_client.h"
+#include "../../src/runtime/rpc/rpc_session.h"
+#include "../../src/runtime/rpc/rpc_socket_impl.h"
+#include "../../src/common/socket.h"
+
+#if defined(__linux__) || defined(__ANDROID__)
+static pid_t waitpid_eintr(int *status) {
+  pid_t pid = 0;
+  while ((pid = waitpid(-1, status, 0)) == -1) {
+if (errno == EINTR) {
+  continue;
+} else {
+  perror("waitpid");
+  abort();
+}
+  }
+  return pid;
+}
+#endif
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief RPCServer RPC Server class.
+ * \param host The hostname of the server, Default=0.0.0.0
+ * \param port The port of the RPC, Default=9090
+ * \param port_end The end search port of the RPC, Default=9199
+ * \param tracker The address of RPC tracker in host:port format e.g. 
10.77.1.234:9190 Default=""
+ * \param key The key used to identify the device type in tracker. Default=""
+ * \param custom_addr Custom IP Address to Report to RPC Tracker. Default=""
+ * \param isProxy Whether to run in proxy mode. Default=False
+ */
+class RPCServer {
+ public:
+  /*!
+   * \brief Constructor.
+  */
+  RPCServer(const std::string ,
+int port,
+int port_end,
+const std::string _addr,
+const std::string ,
+const std::string _addr,
+bool is_proxy) {
+// Init the values
+host_ = host;
+port_ = port;
+port_end_ = port_end;
+tracker_addr_ = tracker_addr;
+key_ = key;
+custom_addr_ = custom_addr;
+is_proxy_ = is_proxy;
+  }
+
+  /*!
+   * \brief Destructor.
+  */
+  ~RPCServer() {
+// Free the resources
+tracker_sock_.Close();
+listen_sock_.Close();
+  }
+
+  /*!
+   * \brief Start Creates the RPC listen process and execution.
+  */
+  void Start() {
+  listen_sock_.Create();
+  my_port_ = listen_sock_.TryBindHost(host_, port_, port_end_);
+  LOG(INFO) << "bind to " << host_ << ":" << my_port_;
+  listen_sock_.Listen(1);
+  std::future proc(std::async(std::launch::async, 
::ListenLoopProc, this));
+  proc.get();
+  // Close the listen socket
+  listen_sock_.Close();
+  }
+
+ private:
+  /*!
+   * \brief ListenLoopProc The listen process.
+   */
+  void ListenLoopProc() {
+TrackerClient tracker(tracker_addr_, key_, custom_addr_);
+while (1) {
+  common::TCPSocket conn;
+  common::SockAddr addr("0.0.0.0", 0);
+  std::string opts;
+  try {
+// step 1: setup tracker and report to tracker
+tracker.TryConnect();
+// step 2: wait for in-coming connections
+AcceptConnection(, , , );
+  }
+  catch (const char* msg) {
+LOG(WARNING) << "Socket exception: " << msg;
+// close tracker resource
+tracker.Close();
+continue;
+  }
+  catch (std::exception& e) {
+// Other errors
+LOG(WARNING) << "Exception standard: " << e.what();
+continue;
+  }
+
+  int timeout = GetTimeOutFromOpts(opts);
+  #if defined(__linux__) || defined(__ANDROID__)
+// step 3: serving
+if (timeout) {
+  const pid_t timer_pid = fork();
+  if (timer_pid == 0) {
+// Timer process
+sleep(timeout);
+exit(0);
+  }
+
+  const pid_t worker_pid = fork();
+  if (worker_pid == 0) {
+// Worker process
+ServerLoopProc(conn, addr);
+exit(0);
+  }
+
+  int status = 0;
+  const pid_t finished_first = waitpid_eintr();
+  if (finished_first == timer_pid) {
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344292057
 
 

 ##
 File path: src/common/socket.h
 ##
 @@ -62,6 +65,25 @@ inline std::string GetHostName() {
   return std::string(buf.c_str());
 }
 
+/*!
+ * \brief ValidateIP validates an ip address.
+ * \param ip The ip address in string format localhost or x.x.x.x format
+ * \return result of operation.
+ */
+inline bool ValidateIP(std::string ip) {
+  if (ip == "localhost") {
+return true;
+  }
+  std::vector list = Split(ip, '.');
+  if (list.size() != 4)
+return false;
+  for (std::string str : list) {
 
 Review comment:
   when iterate over a list, use const std::string& str(otherwise could result 
in a copy)


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344289299
 
 

 ##
 File path: apps/cpp_rpc/rpc_server.cc
 ##
 @@ -0,0 +1,363 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_server.cc
+ * \brief RPC Server implementation.
+ */
+
+#include 
+
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "rpc_server.h"
+#include "rpc_env.h"
+#include "rpc_tracker_client.h"
+#include "../../src/runtime/rpc/rpc_session.h"
+#include "../../src/runtime/rpc/rpc_socket_impl.h"
+#include "../../src/common/socket.h"
+
+#if defined(__linux__) || defined(__ANDROID__)
+static pid_t waitpid_eintr(int *status) {
+  pid_t pid = 0;
+  while ((pid = waitpid(-1, status, 0)) == -1) {
+if (errno == EINTR) {
+  continue;
+} else {
+  perror("waitpid");
+  abort();
+}
+  }
+  return pid;
+}
+#endif
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief RPCServer RPC Server class.
+ * \param host The hostname of the server, Default=0.0.0.0
+ * \param port The port of the RPC, Default=9090
+ * \param port_end The end search port of the RPC, Default=9199
+ * \param tracker The address of RPC tracker in host:port format e.g. 
10.77.1.234:9190 Default=""
+ * \param key The key used to identify the device type in tracker. Default=""
+ * \param custom_addr Custom IP Address to Report to RPC Tracker. Default=""
+ * \param isProxy Whether to run in proxy mode. Default=False
+ */
+class RPCServer {
+ public:
+  /*!
+   * \brief Constructor.
+  */
+  RPCServer(const std::string ,
+int port,
+int port_end,
+const std::string _addr,
+const std::string ,
+const std::string _addr,
+bool is_proxy) {
+// Init the values
+host_ = host;
+port_ = port;
+port_end_ = port_end;
+tracker_addr_ = tracker_addr;
+key_ = key;
+custom_addr_ = custom_addr;
+is_proxy_ = is_proxy;
+  }
+
+  /*!
+   * \brief Destructor.
+  */
+  ~RPCServer() {
+// Free the resources
+tracker_sock_.Close();
+listen_sock_.Close();
+  }
+
+  /*!
+   * \brief Start Creates the RPC listen process and execution.
+  */
+  void Start() {
+  listen_sock_.Create();
+  my_port_ = listen_sock_.TryBindHost(host_, port_, port_end_);
+  LOG(INFO) << "bind to " << host_ << ":" << my_port_;
+  listen_sock_.Listen(1);
+  std::future proc(std::async(std::launch::async, 
::ListenLoopProc, this));
+  proc.get();
+  // Close the listen socket
+  listen_sock_.Close();
+  }
+
+ private:
+  /*!
+   * \brief ListenLoopProc The listen process.
+   */
+  void ListenLoopProc() {
+TrackerClient tracker(tracker_addr_, key_, custom_addr_);
+while (1) {
+  common::TCPSocket conn;
+  common::SockAddr addr("0.0.0.0", 0);
+  std::string opts;
+  try {
+// step 1: setup tracker and report to tracker
+tracker.TryConnect();
+// step 2: wait for in-coming connections
+AcceptConnection(, , , );
+  }
+  catch (const char* msg) {
+LOG(WARNING) << "Socket exception: " << msg;
+// close tracker resource
+tracker.Close();
+continue;
+  }
+  catch (std::exception& e) {
+// Other errors
+LOG(WARNING) << "Exception standard: " << e.what();
+continue;
+  }
+
+  int timeout = GetTimeOutFromOpts(opts);
+  #if defined(__linux__) || defined(__ANDROID__)
+// step 3: serving
+if (timeout) {
+  const pid_t timer_pid = fork();
+  if (timer_pid == 0) {
+// Timer process
+sleep(timeout);
+exit(0);
+  }
+
+  const pid_t worker_pid = fork();
+  if (worker_pid == 0) {
+// Worker process
+ServerLoopProc(conn, addr);
+exit(0);
+  }
+
+  int status = 0;
+  const pid_t finished_first = waitpid_eintr();
+  if (finished_first == timer_pid) {
+

[GitHub] [incubator-tvm] tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC

2019-11-08 Thread GitBox
tqchen commented on a change in pull request #4281: [RUTNIME] Support C++ RPC
URL: https://github.com/apache/incubator-tvm/pull/4281#discussion_r344288389
 
 

 ##
 File path: apps/cpp_rpc/rpc_env.h
 ##
 @@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ *  Copyright (c) 2019 by Contributors
+ * \file rpc_env.h
+ * \brief Server environment of the RPC.
+ */
+#ifndef TVM_APPS_CPP_RPC_ENV_H_
+#define TVM_APPS_CPP_RPC_ENV_H_
+
+#include 
+#if defined(__linux__) || defined(__ANDROID__)
+#include 
+#include 
+#endif
+#include 
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief Load Load module from file
+  This function will automatically call
+  cc.create_shared if the path is in format .o or .tar
+  High level handling for .o and .tar file.
+  We support this to be consistent with RPC module load.
+ * \param file The input file
+ * \param file The format of file
+ * \return Module The loaded module
+ */
+Module Load(std::string *path, const std::string fmt = "");
+
+/*!
+ * \brief CleanDir Removes the files from the directory
+ * \param dirname THe name of the directory
+ */
+void CleanDir(const std::string );
+
+/*!
+ * \brief RPCEnv The RPC Environment parameters for c++ rpc server
+ */
+struct RPCEnv {
+ public:
+   /*!
+* \brief Constructor Init The RPC Environment initialize function
+*/
+  RPCEnv();
+  /*!
+   * \brief GetPath To get the workpath from packed function
+   * \param name The file name
+   * \return The full path of file.
+   */
+  std::string GetPath(const std::string& file_name);
+  /*!
+   * \brief Remove The RPC Environment cleanup function
+   */
+  void Remove();
+
+  /*!
+   * \base_ Holds the environment path.
+   */
+  std::string base_;
 
 Review comment:
   should this field be private?


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services