1/**
2 * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15
16 * \author Dianzhang.Chen
17 * \date Feb 2021
18 * \brief PortHelper definition
19 */
20
21#pragma once
22
23#include <fstream>
24#include <iostream>
25#include <string>
26
27namespace proxima {
28namespace be {
29namespace repository {
30
31class PortHelper {
32 public:
33 static void GetPort(int *port, int *pid) {
34 *pid = getpid();
35 static std::string cmd =
36 "export PORT=$(python -c 'import socket; s=socket.socket(); "
37 "s.bind((\"\", 0)); print(s.getsockname()[1]); s.close()')"
38 "&& echo ${PORT} >> %s.txt";
39 char cmd_buf[1024];
40 snprintf(cmd_buf, 1024, cmd.c_str(), std::to_string(*pid).c_str());
41 system(cmd_buf);
42 char filename_buf[1024];
43 snprintf(filename_buf, 1024, "%s.txt", std::to_string(*pid).c_str());
44 std::string filename = std::string(filename_buf);
45 std::ifstream infile(filename);
46 std::string port_str;
47 std::getline(infile, port_str);
48 *port = std::stoi(port_str);
49 }
50
51 static void RemovePortFile(int pid) {
52 static std::string cmd = "rm %s.txt";
53 char cmd_buf[1024];
54 snprintf(cmd_buf, 1024, cmd.c_str(), std::to_string(pid).c_str());
55 std::cout << "Execute: " << std::string(cmd_buf) << std::endl;
56 system(cmd_buf);
57 }
58};
59
60} // end namespace repository
61} // namespace be
62} // end namespace proxima
63