worker.cpp 13.4 KB
Newer Older
Stanislav Bohm's avatar
Stanislav Bohm committed
1
2
3
4
5
#include "worker.h"
#include "loomcomm.pb.h"
#include "utils.h"
#include "log.h"
#include "types.h"
Stanislav Bohm's avatar
Stanislav Bohm committed
6
#include "data/rawdata.h"
7
#include "data/array.h"
Stanislav Bohm's avatar
Stanislav Bohm committed
8
#include "data/index.h"
Stanislav Bohm's avatar
Stanislav Bohm committed
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

#include <stdlib.h>
#include <sstream>
#include <unistd.h>

using namespace loom;


Worker::Worker(uv_loop_t *loop,
               const std::string &server_address,
               int server_port,
               const std::string &work_dir_root)
    : loop(loop),
      server_conn(*this),
      server_port(server_port)
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;
    UV_CHECK(uv_tcp_init(loop, &listen_socket));
    listen_socket.data = this;
    start_listen();

    if (!server_address.empty()) {
        llog->info("Connecting to server {}:{}", server_address, server_port);
        uv_getaddrinfo_t* handle = new uv_getaddrinfo_t;
        handle->data = this;
        struct addrinfo hints;
        memset(&hints,0,sizeof(hints));
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;
        UV_CHECK(uv_getaddrinfo(
            loop, handle, _on_getaddrinfo, server_address.c_str(), "80", &hints));
    }

    if (!work_dir_root.empty()) {
        std::stringstream s;
        s << work_dir_root;
        if (work_dir_root.back() != '/') {
            s << "/";
        }
        char tmp[100];
        if (gethostname(tmp, 100)) {
            llog->error("Cannot get hostname, using 'nohostname'");
            strcpy(tmp, "nohostname");
        }
        s << "worker-" << tmp << '-' << listen_port << '/';
        work_dir = s.str();

        if (make_path(work_dir.c_str(), S_IRWXU)) {
            llog->critical("Cannot create working directory '{}'", work_dir);
            exit(1);
        }

        if (mkdir((work_dir + "data").c_str(), S_IRWXU)) {
            llog->critical("Cannot create 'data' in working directory");
            exit(1);
        }

        llog->info("Using '{}' as working directory", work_dir);
    }

69
70
71
    add_unpacker(RawData::TYPE_ID,
                 std::make_unique<SimpleUnpackFactory<RawDataUnpacker>>());

72
73
74
    add_unpacker(Array::TYPE_ID,
                 std::make_unique<SimpleUnpackFactory<ArrayUnpacker>>());

Stanislav Bohm's avatar
Stanislav Bohm committed
75
76
    add_unpacker(Index::TYPE_ID,
                 std::make_unique<SimpleUnpackFactory<IndexUnpacker>>());
77

Stanislav Bohm's avatar
Stanislav Bohm committed
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
    resource_cpus = 1;
}


void Worker::_on_getaddrinfo(uv_getaddrinfo_t* handle, int status,
        struct addrinfo* response) {
    Worker *worker = static_cast<Worker*>(handle->data);
    if (status) {
        llog->critical("Cannot resolve server name");
        uv_freeaddrinfo(response);
        delete handle;
        worker->close_all();
        exit(1);
    }
    assert(response->ai_family == AF_INET);
    char tmp[60];
    UV_CHECK(uv_ip4_name((struct sockaddr_in*) response->ai_addr, tmp, 60));
    worker->server_address = tmp;

    uv_freeaddrinfo(response);
    delete handle;

    llog->debug("Server address resolved to {}", worker->server_address);
    worker->server_conn.connect(worker->server_address, worker->server_port);
}

void Worker::_on_new_connection(uv_stream_t *stream, int status)
{
    UV_CHECK(status);
    Worker *worker = static_cast<Worker*>(stream->data);
    auto connection = std::make_unique<InterConnection>(*worker);
    connection->accept(&worker->listen_socket);
    llog->debug("Worker connection from {}", connection->get_peername());
    worker->add_connection(std::move(connection));
}

void Worker::start_listen()
{
    struct sockaddr_in addr;
    UV_CHECK(uv_ip4_addr("0.0.0.0", 0, &addr));

    UV_CHECK(uv_tcp_bind(&listen_socket, (const struct sockaddr *) &addr, 0));
    UV_CHECK(uv_listen((uv_stream_t *) &listen_socket, 10, _on_new_connection));

    struct sockaddr_in sockname;
    int namelen = sizeof(sockname);
    uv_tcp_getsockname(&listen_socket, (sockaddr*) &sockname, &namelen);
    listen_port = ntohs(sockname.sin_port);
}

/*int Worker::get_listen_port()
{
    struct sockaddr_in sa;
    int name_len = sizeof(sa);
    UV_CHECK(uv_tcp_getsockname(&listen_socket, (sockaddr *) &sa, &name_len));
    return ntohs(sa.sin_port);
}*/

void Worker::register_worker()
{
    loomcomm::Register msg;
    msg.set_type(loomcomm::Register_Type_REGISTER_WORKER);
    msg.set_protocol_version(PROTOCOL_VERSION);

    msg.set_port(get_listen_port());
Stanislav Bohm's avatar
Stanislav Bohm committed
143
    msg.set_cpus(resource_cpus);
Stanislav Bohm's avatar
Stanislav Bohm committed
144

145
    for (auto& factory : unregistered_task_factories) {
Stanislav Bohm's avatar
Stanislav Bohm committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
        msg.add_task_types(factory->get_name());
    }

    server_conn.send_message(msg);
}

void Worker::new_task(std::unique_ptr<Task> task)
{
    if (task->is_ready(*this)) {
        ready_tasks.push_back(std::move(task));
        check_ready_tasks();
        return;
    }
    waiting_tasks.push_back(std::move(task));
}

void Worker::start_task(std::unique_ptr<Task> task)
{
    llog->debug("Starting task id={} task_type={}", task->get_id(), task->get_task_type());
165
    auto i = task_factories.find(task->get_task_type());
Stanislav Bohm's avatar
Stanislav Bohm committed
166
167
168
169
    if (unlikely(i == task_factories.end())) {
        llog->critical("Task with unknown type received");
        exit(1);
    }
170
    auto task_instance = i->second->make_instance(*this, std::move(task));
Stanislav Bohm's avatar
Stanislav Bohm committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    TaskInstance *t = task_instance.get();
    active_tasks.push_back(std::move(task_instance));

    DataVector input_data;
    for (Id id : t->get_inputs()) {
        input_data.push_back(&get_data(id));
    }

    t->start(input_data);
    resource_cpus -= 1;
}

/*void Worker::new_task(const Task &task)
{
    auto task_type = task.get_task_type();
    assert(task_type >= 0 && task_type < (int) task_factories.size());
    auto task_instance = task_factories[task_type]->make_instance(*this, task);
    TaskInstance *t = task_instance.get();
    active_tasks.push_back(std::move(task_instance));
    t->start();
}*/

Stanislav Bohm's avatar
Stanislav Bohm committed
193
void Worker::publish_data(Id id, std::shared_ptr<Data> &data)
Stanislav Bohm's avatar
Stanislav Bohm committed
194
{
195
    llog->debug("Publishing data id={} size={}", id, data->get_size());
196
    public_data[id] = data;
Stanislav Bohm's avatar
Stanislav Bohm committed
197
198
199
    check_waiting_tasks();
}

200
201
202
203
204
205
206
207
void Worker::remove_data(Id id)
{
    llog->debug("Removing data id={}", id);
    auto i = public_data.find(id);
    assert(i != public_data.end());
    public_data.erase(i);
}

Stanislav Bohm's avatar
Stanislav Bohm committed
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
InterConnection& Worker::get_connection(const std::string &address)
{
    auto &connection = connections[address];
    if (connection.get() == nullptr) {
        llog->info("Connecting to {}", address);
        connection = std::make_unique<InterConnection>(*this);

        std::stringstream ss(address);
        std::string base_address;
        std::getline(ss, base_address, ':');
        int port;
        ss >> port;

        if (base_address == "!server") {
            connection->connect(server_address, port);
        } else {
            connection->connect(base_address, port);
        }
    }
    return *connection;
}

void Worker::close_all()
{
    uv_close((uv_handle_t*) &listen_socket, NULL);
    server_conn.close();
    for (auto& pair : connections) {
        pair.second->close();
    }
    for (auto& c : nonregistered_connections) {
        c->close();
    }
}

void Worker::register_connection(InterConnection &connection)
{    
    auto &c = connections[connection.get_address()];
    if (unlikely(c.get() != nullptr)) {
        // This can happen when two workers connect each other in the same time
        llog->debug("Registration collision, leaving unregisted");
        // It is ok to leave it as it be, we will just hold the redundant connection
        // in unregistered connections
        return;
    }
    auto i = std::find_if(
                nonregistered_connections.begin(),
                nonregistered_connections.end(),
255
                [&](std::unique_ptr<InterConnection>& p) { return p.get() == &connection; });
Stanislav Bohm's avatar
Stanislav Bohm committed
256
257
258
259
260
261
262
263
264
265
266
267
    assert(i != nonregistered_connections.end());
    c = std::move(*i);
    nonregistered_connections.erase(i);
}

void Worker::unregister_connection(InterConnection &connection)
{
    const auto &i = connections.find(connection.get_address());
    if (unlikely(i == connections.end())) {
        auto i = std::find_if(
                    nonregistered_connections.begin(),
                    nonregistered_connections.end(),
268
                    [&](std::unique_ptr<InterConnection>& p) { return p.get() == &connection; });
Stanislav Bohm's avatar
Stanislav Bohm committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
        assert(i != nonregistered_connections.end());
        nonregistered_connections.erase(i);
        return;
    }
    connections.erase(i);
}

std::string Worker::get_run_dir(Id id)
{
    std::stringstream s;
    s << work_dir << "run/" << id << "/";
    return s.str();
}

void Worker::check_ready_tasks()
{
    while (resource_cpus > 0 && ready_tasks.size()) {
        auto task = std::move(ready_tasks[0]);
        ready_tasks.erase(ready_tasks.begin());
        start_task(std::move(task));
    }
}

void Worker::set_cpus(int value)
{
    if (value == 0) {
        value = sysconf(_SC_NPROCESSORS_ONLN);
        llog->debug("Autodetection of CPUs: {}", value);
    }
    if (value <= 0) {
        value = 1;
    }

    resource_cpus = value;
    llog->info("Number of CPUs for worker: {}", value);
}

306
307
308
309
310
311
312
313
314
void Worker::add_unpacker(DataTypeId type_id, std::unique_ptr<UnpackFactory> factory)
{
    auto &f = unpack_factories[type_id];
    assert(f.get() == nullptr);
    f = std::move(factory);
}

std::unique_ptr<DataUnpacker> Worker::unpack(DataTypeId id)
{
315
    auto i = unpack_factories.find(id);
316
317
318
319
    assert(i != unpack_factories.end());
    return i->second->make_unpacker();
}

320
321
322
323
324
325
326
327
void Worker::on_dictionary_updated()
{
    for (auto &f : unregistered_task_factories) {
        loom::Id id = dictionary.lookup_symbol(f->get_name());
        task_factories[id] = std::move(f);
    }
}

Stanislav Bohm's avatar
Stanislav Bohm committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
void Worker::check_waiting_tasks()
{
    bool something_new = false;
    auto i = waiting_tasks.begin();
    while (i != waiting_tasks.end()) {
        auto& task_ptr = *i;
        if (task_ptr->is_ready(*this)) {
            ready_tasks.push_back(std::move(task_ptr));
            i = waiting_tasks.erase(i);
            something_new = true;
        } else {
            ++i;
        }
    }
    if (something_new) {
        check_ready_tasks();
    }
}

void Worker::remove_task(TaskInstance &task)
{
    for (auto i = active_tasks.begin(); i != active_tasks.end(); i++) {
        if ((*i)->get_id() == task.get_id()) {
            active_tasks.erase(i);
            return;
        }
    }
    assert(0);
}

Stanislav Bohm's avatar
Stanislav Bohm committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
void Worker::task_failed(TaskInstance &task, const std::string &error_msg)
{
    llog->error("Task id={} failed: {}", task.get_id(), error_msg);
    if (server_conn.is_connected()) {
        loomcomm::WorkerResponse msg;
        msg.set_type(loomcomm::WorkerResponse_Type_FAILED);
        msg.set_id(task.get_id());
        msg.set_error_msg(error_msg);
        server_conn.send_message(msg);
    }
    resource_cpus += 1;
    remove_task(task);
}

372
void Worker::task_finished(TaskInstance &task, Data &data)
Stanislav Bohm's avatar
Stanislav Bohm committed
373
374
375
{
    if (server_conn.is_connected()) {
        loomcomm::WorkerResponse msg;
Stanislav Bohm's avatar
Stanislav Bohm committed
376
        msg.set_type(loomcomm::WorkerResponse_Type_FINISH);
Stanislav Bohm's avatar
Stanislav Bohm committed
377
        msg.set_id(task.get_id());
378
379
        msg.set_size(data.get_size());
        msg.set_length(data.get_length());
Stanislav Bohm's avatar
Stanislav Bohm committed
380
381
382
383
384
385
386
        server_conn.send_message(msg);
    }
    resource_cpus += 1;
    remove_task(task);
    check_ready_tasks();
}

387
void Worker::send_data(const std::string &address, Id id, std::shared_ptr<Data> &data, bool with_size)
Stanislav Bohm's avatar
Stanislav Bohm committed
388
389
{
    auto &connection = get_connection(address);;
390
    connection.send(id, data, with_size);
Stanislav Bohm's avatar
Stanislav Bohm committed
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
}

ServerConnection::ServerConnection(Worker &worker)
    : SimpleConnectionCallback(worker.get_loop()),
      worker(worker)
{

}

void ServerConnection::on_connection()
{
    connection.start_read();
    worker.register_worker();
}

void ServerConnection::on_close()
{
    llog->critical("Connection to server is closed. Terminating ...");
    worker.close_all();
}

void ServerConnection::on_error(int error_code)
{
    llog->critical("Server connection error: {}", uv_strerror(error_code));
    connection.close();
}

void ServerConnection::on_message(const char *data, size_t size)
{
    loomcomm::WorkerCommand msg;
    assert(msg.ParseFromArray(data, size));
    auto type = msg.type();

    switch (type) {
    case loomcomm::WorkerCommand_Type_TASK: {
        llog->debug("Task id={} received", msg.id());
        auto task = std::make_unique<Task>(msg.id(),
                                           msg.task_type(),
                                           msg.task_config());
        for (int i = 0; i < msg.task_inputs_size(); i++) {
            task->add_input(msg.task_inputs(i));
        }
        worker.new_task(std::move(task));
        break;
    }
436
437
438
439
    case loomcomm::WorkerCommand_Type_REMOVE: {
        worker.remove_data(msg.id());
        break;
    }
Stanislav Bohm's avatar
Stanislav Bohm committed
440
441
442
443
444
445
446
    case loomcomm::WorkerCommand_Type_SEND: {
        auto& address = msg.address();
        /* "!" means address to server, so we replace the sign to proper address */
        if (address.size() > 2 && address[0] == '!' && address[1] == ':') {
            msg.set_address(worker.get_server_address() + ":" + address.substr(2, std::string::npos));
        }
        llog->debug("Sending data {} to {}", msg.id(), msg.address());
447
448
        bool with_size = msg.has_with_size() && msg.with_size();
        assert(worker.send_data(msg.address(), msg.id(), with_size));
Stanislav Bohm's avatar
Stanislav Bohm committed
449
450
        break;
    }
451
452
453
454
455
456
457
458
459
460
    case loomcomm::WorkerCommand_Type_DICTIONARY: {
        auto count = msg.symbols_size();
        llog->debug("New dictionary ({} symbols)", count);
        Dictionary &dictionary = worker.get_dictionary();
        for (int i = 0; i < count; i++) {
            dictionary.find_or_create(msg.symbols(i));
        }
        worker.on_dictionary_updated();

    } break;
Stanislav Bohm's avatar
Stanislav Bohm committed
461
462
463
464
465
    default:
        llog->critical("Invalid message");
        exit(1);
    }
}