aboutsummaryrefslogtreecommitdiff
path: root/src/Client.php
blob: b8bdb5a4774798fd58ffe57cea8d9f02e2145e64 (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
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
<?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
     * @throws \Exception
     */
    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 ResponseMessage
     * @throws \Exception
     */
    public function ping() {
        $this->send(new RequestMessage('ping'));
        return $this->recv();
    }

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

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

    /**
     * @param array $targets
     * @return ResponseMessage
     * @throws \Exception
     */
    public function poll(array $targets) {
        $this->send(new RequestMessage('poll', ['targets' => $targets]));
        return $this->recv();
    }

    /**
     * @param int $id
     * @return ResponseMessage
     */
    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 ResponseMessage
     * @throws \Exception
     */
    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");

        $response = self::parseMessage($messages[0]);
        if (!($response instanceof ResponseMessage))
            throw new \Exception('Unexpected message type');

        if ($error = $response->getError())
            throw new \Exception('jobd error: '.$response->getError());

        return $response;
    }

    /**
     * @param string $raw_string
     * @return RequestMessage|ResponseMessage
     * @throws \Exception
     */
    protected static function parseMessage(string $raw_string) {
        $raw = json_decode($raw_string, true);
        if (!is_array($raw) || count($raw) != 2)
            throw new \Exception("Malformed message: {$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;

            default:
                throw new \Exception("Malformed message: unexpected type {$type}");
        }
    }

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

}