summaryrefslogtreecommitdiff
path: root/src/vm.cc
blob: 29fcc43c4e22a106258f1ebb1d7e39bb81cc0aec (plain)
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
#include "vm.h"
#include <iostream>
#include <thread>

namespace vm {
    virConnectPtr conn = NULL;

    struct vmImpl {
        virDomainPtr dom;
        virStreamPtr stream;
        std::thread receiver;
    };

    void initConn() {
        if (conn == NULL) {
            conn = virConnectOpen("qemu:///system");
        }
        if (conn == NULL) {
            std::cerr << "Failed to open connection to qemu:///system\n";
        }
    }

    void clearAllVMs() {
        initConn();
        virDomainPtr *domains;
        int numDomains = virConnectListAllDomains(conn, &domains, 0);
        for (int i = 0; i < numDomains; i++) {
            virDomainDestroy(domains[i]);
            virDomainFree(domains[i]);
        }
        free(domains);
    }

    VM::VM() : data(new vmImpl()) {
        initConn();
        data->stream = virStreamNew(conn, 0);
    }

    VM::~VM() {
        virStreamAbort(data->stream);
        virStreamFree(data->stream);
    }

    int VM::start(std::string config) {
        data->dom = virDomainCreateXML(conn, config.c_str(), VIR_DOMAIN_START_AUTODESTROY);
        if (!data->dom) {
            std::cerr << "Domain creation failed\n";
            return 1;
        }
        return 0;
    }

    void VM::stop() {
        if (data->dom) {
            virDomainFree(data->dom);
        }
    }

    void receiveTask(virStreamPtr stream, std::function<int(const char*,size_t)> receiver) {

        virStreamRecvAll(stream,
                [](virStreamPtr stream, const char *data, size_t nbytes, void *opaque) {
                auto *receiver = static_cast<std::function<int(const char*,size_t)>*>(opaque);
                return (*receiver)(data, nbytes);
                },
                &receiver);
    }

    void sendTask(virStreamPtr stream, std::function<int(char*,size_t)> sender) {
        virStreamSendAll(stream,
                [](virStreamPtr stream, char *data, size_t nbytes, void *opaque) {
                auto *sender = static_cast<std::function<int(char*,size_t)>*>(opaque);
                return (*sender)(data, nbytes);
                },
                &sender);
    }

    void VM::connect(std::function<int(const char*,size_t)> receiver, std::function<int(char*,size_t)> sender) {
        if (virDomainOpenConsole(data->dom, NULL, data->stream, 0)) {
            std::cerr << "Failed to open console\n";
        }
        data->receiver = std::thread(receiveTask, data->stream, receiver);
        sendTask(data->stream, sender); // Blocking
    }
}