summaryrefslogtreecommitdiff
path: root/src/Client.php
blob: 54427f47c655c9925616271be5d8673d12ff1054 (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
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
<?php

namespace jobd;


class Client {

    const WORKER_PORT = 13596;
    const MASTER_PORT = 13597;

    const EOT = "\4";

    protected $host;
    protected $port;
    protected $password;
    protected $sock;

    /**
     * JobdClient constructor.
     * @param int $port
     * @param string $host
     * @param string $password
     */
    public function __construct(int $port, string $host = '127.0.0.1', string $password = '') {
        $this->port = $port;
        $this->host = $host;
        $this->password = $password;

        $this->sock = fsockopen($this->host, $this->port);
        if (!$this->sock)
            throw new \Exception("Failed to connect to {$this->host}:{$this->port}");
    }

    /**
     * @return mixed
     */
    public function ping() {
        $this->send(new RequestMessage('ping'));
        return $this->recv();
    }

    /**
     * @param array $targets
     * @return mixed
     */
    public function poke(array $targets) {
        $this->send(new RequestMessage('poke', ['targets' => $targets]));
        return $this->recv();
    }

    /**
     * @return mixed
     */
    public function status() {
        $this->send(new RequestMessage('status'));
        return $this->recv();
    }

    public function poll(array $targets) {
        $this->send(new RequestMessage('poll', ['targets' => $targets]));
        return $this->recv();
    }

    /**
     * @param int $id
     * @return mixed
     */
    public function runManual(int $id) {
        $this->send(new RequestMessage('run-manual', ['id' => $id]));
        return $this->recv();
    }

    /**
     * @param RequestMessage $request
     */
    public function send(RequestMessage $request) {
        if ($this->password)
            $request->setPassword($this->password);

        $serialized = $request->serialize();

        fwrite($this->sock, $serialized . self::EOT);
    }

    /**
     * @return mixed
     */
    public function recv() {
        $messages = [];
        $buf = '';
        while (!feof($this->sock)) {
            $buf .= fread($this->sock, 1024);
            $buflen = strlen($buf);
            if ($buflen > 0 && $buf[$buflen-1] == self::EOT)
                break;
        }

        $offset = 0;
        $eot_pos = 0;
        do {
            $eot_pos = strpos($buf, self::EOT, $offset);
            if ($eot_pos !== false) {
                $message = substr($buf, $offset, $eot_pos);
                $messages[] = $message;

                $offset = $eot_pos + 1;
            }
        } while ($eot_pos !== false && $offset < $buflen-1);

        if (empty($message))
            throw new \Exception("Malformed response: no messages found. Response: {$buf}");

        if (count($messages) > 1)
            trigger_error(__METHOD__.": received more than one message");

        return self::parseMessage($messages[0]);
    }

    protected static function parseMessage(string $raw_string) {
        $raw = json_decode($raw_string, true);
        if (!is_array($raw) || count($raw) != 2)
            throw new \Exception("Malformed response: {$raw_string}");

        list($type, $data) = $raw;

        switch ($type) {
            case Message::REQUEST:
                if (!$data || !is_array($data) || !isset($data['type']) || !is_string($data['type']))
                    throw new \Exception('Malformed REQUEST message');

                $message = new RequestMessage($data['type'], $data['data'] ?? null);
                if (isset($data['password']))
                    $message->setPassword($data['password']);

                return $message;

            case Message::RESPONSE:
                if (!is_array($data) || count($data) < 2)
                    throw new \Exception('Malformed RESPONSE message');

                $message = new ResponseMessage(...$data);
                return $message;
        }
    }

    /**
     * @return bool
     */
    public function close() {
        return fclose($this->sock);
    }

}