File: caf-run.cpp

package info (click to toggle)
actor-framework 0.17.6-3.2
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 9,008 kB
  • sloc: cpp: 77,684; sh: 674; python: 309; makefile: 13
file content (286 lines) | stat: -rw-r--r-- 9,795 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2018 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#include <unistd.h>

#include <cstdio>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
#include <iostream>

#include "caf/all.hpp"
#include "caf/io/all.hpp"

using namespace caf;

using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;

static constexpr const char base64_tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                           "abcdefghijklmnopqrstuvwxyz"
                                           "0123456789+/";

std::string encode_base64(const string& str) {
  std::string result;
  // consumes three characters from input
  auto consume = [&](const char* i) {
    int buf[] {
      (i[0] & 0xfc) >> 2,
      ((i[0] & 0x03) << 4) + ((i[1] & 0xf0) >> 4),
      ((i[1] & 0x0f) << 2) + ((i[2] & 0xc0) >> 6),
      i[2] & 0x3f
    };
    for (auto x : buf)
      result += base64_tbl[x];
  };
  // iterate string in chunks of three characters
  auto i = str.begin();
  for ( ; std::distance(i, str.end()) >= 3; i += 3)
    consume(&(*i));
  if (i != str.end()) {
    // "fill" string with 0s
    char cbuf[] = {0, 0, 0};
    std::copy(i, str.end(), cbuf);
    consume(cbuf);
    // override filled characters (garbage) with '='
    for (auto j = result.end() - (3 - (str.size() % 3)); j != result.end(); ++j)
      *j = '=';
  }
  return result;
}

class host_desc {
public:
  std::string host;
  int cpu_slots;
  string opencl_device_ids;

  host_desc(std::string host_addr, int slots, string cldevices)
      : host(std::move(host_addr)),
        cpu_slots(slots),
        opencl_device_ids(std::move(cldevices)) {
    // nop
  }

  host_desc(host_desc&&) = default;
  host_desc(const host_desc&) = default;
  host_desc& operator=(host_desc&&) = default;
  host_desc& operator=(const host_desc&) = default;

  static void append(vector<host_desc>& xs, const string& line, size_t num) {
    vector<string> fields;
    split(fields, line, is_any_of(" "), token_compress_on);
    if (fields.empty())
      return;
    host_desc hd;
    hd.host = std::move(fields.front());
    hd.cpu_slots = 0;
    hd.opencl_device_ids = "";
    for (auto i = fields.begin() + 1; i != fields.end(); ++i) {
      if (starts_with(*i, "device_ids=")) {
        hd.opencl_device_ids.assign(std::find(i->begin(), i->end(), '=') + 1,
                                    i->end());
      } else if (sscanf(i->c_str(), "slots=%d", &hd.cpu_slots) != 0) {
        cerr << "invalid option at line " << num << ": " << *i << endl;
      }
    }
    xs.emplace_back(std::move(hd));
  }

private:
  host_desc() = default;
};

std::vector<host_desc> read_hostfile(const string& fname) {
  std::vector<host_desc> result;
  std::ifstream in{fname};
  std::string line;
  size_t line_num = 0;
  while (std::getline(in, line))
    host_desc::append(result, line, ++line_num);
  return result;
}

bool run_ssh(actor_system& system, const string& wdir,
             const string& cmd, const string& host) {
  std::cout << "runssh, wdir: " << wdir << " cmd: " << cmd
            << " host: " << host << std::endl;
  // pack command before sending it to avoid any issue with shell escaping
  string full_cmd = "cd ";
  full_cmd += wdir;
  full_cmd += '\n';
  full_cmd += cmd;
  auto packed = encode_base64(full_cmd);
  std::ostringstream oss;
  oss << "ssh -Y -o ServerAliveInterval=60 " << host
      << R"( "echo )" << packed << R"( | base64 --decode | /bin/sh")";
  //return system(oss.str().c_str());
  string line;
  std::cout << "popen: " << oss.str() << std::endl;
  auto fp = popen(oss.str().c_str(), "r");
  if (fp == nullptr)
    return false;
  char buf[512];
  auto eob = buf + sizeof(buf); // end-of-buf
  auto pred = [](char c) { return c == 0 || c == '\n'; };
  scoped_actor self{system};
  while (fgets(buf, sizeof(buf), fp) != nullptr) {
    auto i = buf;
    auto e = std::find_if(i, eob, pred);
    line.insert(line.end(), i, e);
    while (e != eob && *e != 0) {
      aout(self) << line << std::endl;
      line.clear();
      i = e + 1;
      e = std::find_if(i, eob, pred);
      line.insert(line.end(), i, e);
    }
  }
  pclose(fp);
  std::cout << "host down: " << host << std::endl;
  if (!line.empty())
    aout(self) << line << std::endl;
  return true;
}

void bootstrap(actor_system& system,
               const string& wdir,
               const host_desc& master,
               vector<host_desc> slaves,
               const string& cmd,
               vector<string> args) {
  using io::network::interfaces;
  if (!args.empty())
    args.erase(args.begin());
  scoped_actor self{system};
  // open a random port and generate a list of all
  // possible addresses slaves can use to connect to us
  auto port_res = system.middleman().publish(self, 0);
  if (!port_res) {
    cerr << "fatal: unable to publish actor: "
         << system.render(port_res.error()) << endl;
    return;
  }
  auto port = *port_res;
  // run a slave process at master host if user defined slots > 1 for it
  if (master.cpu_slots > 1)
    slaves.emplace_back(master.host, master.cpu_slots - 1,
                        master.opencl_device_ids);
  for (auto& slave : slaves) {
    using namespace caf::io::network;
    // build SSH command and pack it to avoid any issue with shell escaping
    std::thread{[=, &system](actor bootstrapper) {
      std::ostringstream oss;
      oss << cmd;
      if (slave.cpu_slots > 0)
        oss << " --caf#scheduler.max-threads=" << slave.cpu_slots;
      if (!slave.opencl_device_ids.empty())
        oss << " --caf#opencl-devices=" << slave.opencl_device_ids;
      oss << " --caf#slave-mode"
          << " --caf#slave-name=" << slave.host
          << " --caf#bootstrap-node=";
      bool is_first = true;
      interfaces::traverse(
        {protocol::ipv4, protocol::ipv6},
        [&](const char*, protocol::network, bool lo, const char* x) {
          if (lo)
            return;
          if (!is_first)
            oss << ",";
          else
            is_first = false;
          oss << x << "/" << port;
        });
      for (auto& arg : args)
        oss << " " << arg;
      if (!run_ssh(system, wdir, oss.str(), slave.host))
        anon_send(bootstrapper, slave.host);
    }, actor{self}}.detach();
  }
  std::string slaveslist;
  for (size_t i = 0; i < slaves.size(); ++i) {
    self->receive(
      [&](const string& host, uint16_t slave_port) {
        if (!slaveslist.empty())
          slaveslist += ',';
        slaveslist += host;
        slaveslist += '/';
        slaveslist += std::to_string(slave_port);
      },
      [](const string& node) {
        cerr << "unable to launch process via SSH at node " << node << endl;
      }
    );
  }
  // run (and wait for) master
  std::ostringstream oss;
  oss << cmd << " --caf#slave-nodes=" << slaveslist << " " << join(args, " ");
  run_ssh(system, wdir, oss.str(), master.host);
}

#define RETURN_WITH_ERROR(output)                                              \
  do {                                                                         \
    ::std::cerr << output << ::std::endl;                                      \
    return 1;                                                                  \
  } while (true)

namespace {

struct config : actor_system_config {
  config() {
    opt_group{custom_options_, "global"}
    .add(hostfile, "hostfile", "path to hostfile")
    .add(wdir, "wdir", "working directory");
  }
  string hostfile;
  string wdir;
};

} // namespace

int main(int argc, char** argv) {
  config cfg;
  cfg.parse(argc, argv);
  if (cfg.cli_helptext_printed)
    return 0;
  if (cfg.slave_mode)
    RETURN_WITH_ERROR("cannot use slave mode in caf-run tool");
  std::unique_ptr<char, void (*)(void*)> pwd{getcwd(nullptr, 0), ::free};
  if (cfg.hostfile.empty())
    RETURN_WITH_ERROR("no hostfile specified or hostfile is empty");
  auto& remainder = cfg.remainder;
  if (remainder.empty())
    RETURN_WITH_ERROR("empty command line");
  auto cmd = std::move(remainder.front());
  vector<string> xs;
  for (auto i = cfg.remainder.begin() + 1; i != cfg.remainder.end(); ++i)
     xs.emplace_back(std::move(*i));
  auto hosts = read_hostfile(cfg.hostfile);
  if (hosts.empty())
    RETURN_WITH_ERROR("no valid entry in hostfile");
  actor_system system{cfg};
  auto master = hosts.front();
  hosts.erase(hosts.begin());
  bootstrap(system, (cfg.wdir.empty()) ? pwd.get() : cfg.wdir.c_str(), master,
            std::move(hosts), cmd, xs);
}