summaryrefslogtreecommitdiffstats
path: root/modules/monitoring/library/Monitoring/Command/Transport/RemoteCommandFile.php
blob: 8619e87264ffaa95d4649fd67bafd6cdb2622af3 (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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<?php
/* Icinga Web 2 | (c) 2014 Icinga Development Team | GPLv2+ */

namespace Icinga\Module\Monitoring\Command\Transport;

use Icinga\Application\Logger;
use Icinga\Data\ResourceFactory;
use Icinga\Exception\ConfigurationError;
use Icinga\Module\Monitoring\Command\IcingaCommand;
use Icinga\Module\Monitoring\Command\Renderer\IcingaCommandFileCommandRenderer;
use Icinga\Module\Monitoring\Exception\CommandTransportException;

/**
 * A remote Icinga command file
 *
 * Key-based SSH login must be possible for the user to log in as on the remote host
 */
class RemoteCommandFile implements CommandTransportInterface
{
    /**
     * Transport identifier
     */
    const TRANSPORT = 'remote';

    /**
     * The name of the Icinga instance this transport will transfer commands to
     *
     * @var string
     */
    protected $instanceName;

    /**
     * Remote host
     *
     * @var string
     */
    protected $host;

    /**
     * Port to connect to on the remote host
     *
     * @var int
     */
    protected $port = 22;

    /**
     * User to log in as on the remote host
     *
     * Defaults to current PHP process' user
     *
     * @var string
     */
    protected $user;

    /**
     * Path to the private key file for the key-based authentication
     *
     * @var string
     */
    protected $privateKey;

    /**
     * Path to the Icinga command file on the remote host
     *
     * @var string
     */
    protected $path;

    /**
     * Command renderer
     *
     * @var IcingaCommandFileCommandRenderer
     */
    protected $renderer;

    /**
     * SSH subprocess pipes
     *
     * @var array
     */
    protected $sshPipes;

    /**
     * SSH subprocess
     *
     * @var resource
     */
    protected $sshProcess;

    /**
     * Create a new remote command file command transport
     */
    public function __construct()
    {
        $this->renderer = new IcingaCommandFileCommandRenderer();
    }

    /**
     * Set the name of the Icinga instance this transport will transfer commands to
     *
     * @param   string  $name
     *
     * @return  $this
     */
    public function setInstance($name)
    {
        $this->instanceName = $name;
        return $this;
    }

    /**
     * Return the name of the Icinga instance this transport will transfer commands to
     *
     * @return  string
     */
    public function getInstance()
    {
        return $this->instanceName;
    }

    /**
     * Set the remote host
     *
     * @param   string $host
     *
     * @return  $this
     */
    public function setHost($host)
    {
        $this->host = (string) $host;
        return $this;
    }

    /**
     * Get the remote host
     *
     * @return string
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * Set the port to connect to on the remote host
     *
     * @param   int $port
     *
     * @return  $this
     */
    public function setPort($port)
    {
        $this->port = (int) $port;
        return $this;
    }

    /**
     * Get the port to connect on the remote host
     *
     * @return int
     */
    public function getPort()
    {
        return $this->port;
    }

    /**
     * Set the user to log in as on the remote host
     *
     * @param   string $user
     *
     * @return  $this
     */
    public function setUser($user)
    {
        $this->user = (string) $user;
        return $this;
    }

    /**
     * Get the user to log in as on the remote host
     *
     * Defaults to current PHP process' user
     *
     * @return string|null
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Set the path to the private key file
     *
     * @param string $privateKey
     *
     * @return $this
     */
    public function setPrivateKey($privateKey)
    {
        $this->privateKey = (string) $privateKey;
        return $this;
    }

    /**
     * Get the path to the private key
     *
     * @return string
     */
    public function getPrivateKey()
    {
        return $this->privateKey;
    }

    /**
     * Use a given resource to set the user and the key
     *
     * @param ?string $resource
     *
     * @throws ConfigurationError
     */
    public function setResource($resource = null)
    {
        $config = ResourceFactory::getResourceConfig($resource);

        if (! isset($config->user)) {
            throw new ConfigurationError(
                t("Can't send external Icinga Command. Remote user is missing")
            );
        }
        if (! isset($config->private_key)) {
            throw new ConfigurationError(
                t("Can't send external Icinga Command. The private key for the remote user is missing")
            );
        }

        $this->setUser($config->user);
        $this->setPrivateKey($config->private_key);
    }

    /**
     * Set the path to the Icinga command file on the remote host
     *
     * @param   string $path
     *
     * @return  $this
     */
    public function setPath($path)
    {
        $this->path = (string) $path;
        return $this;
    }

    /**
     * Get the path to the Icinga command file on the remote host
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Write the command to the Icinga command file on the remote host
     *
     * @param   IcingaCommand   $command
     * @param   int|null        $now
     *
     * @throws  ConfigurationError
     * @throws  CommandTransportException
     */
    public function send(IcingaCommand $command, $now = null)
    {
        if (! isset($this->path)) {
            throw new ConfigurationError(
                'Can\'t send external Icinga Command. Path to the remote command file is missing'
            );
        }
        if (! isset($this->host)) {
            throw new ConfigurationError('Can\'t send external Icinga Command. Remote host is missing');
        }
        $commandString = $this->renderer->render($command, $now);
        Logger::debug(
            'Sending external Icinga command "%s" to the remote command file "%s:%u%s"',
            $commandString,
            $this->host,
            $this->port,
            $this->path
        );
        return $this->sendCommandString($commandString);
    }

    /**
     * Get the SSH command
     *
     * @return  string
     */
    protected function sshCommand()
    {
        $cmd = sprintf(
            'exec ssh -o BatchMode=yes -p %u',
            $this->port
        );
        // -o BatchMode=yes for disabling interactive authentication methods

        if (isset($this->user)) {
            $cmd .= ' -l ' . escapeshellarg($this->user);
        }

        if (isset($this->privateKey)) {
            // TODO: StrictHostKeyChecking=no for compat only, must be removed
            $cmd .= ' -o StrictHostKeyChecking=no'
                  . ' -i ' . escapeshellarg($this->privateKey);
        }

        $cmd .= sprintf(
            ' %s "cat > %s"',
            escapeshellarg($this->host),
            escapeshellarg($this->path)
        );

        return $cmd;
    }

    /**
     * Send the command over SSH
     *
     * @param   string  $commandString
     *
     * @throws  CommandTransportException
     */
    protected function sendCommandString($commandString)
    {
        if ($this->isSshAlive()) {
            $ret = fwrite($this->sshPipes[0], $commandString . "\n");
            if ($ret === false) {
                $this->throwSshFailure('Cannot write to the remote command pipe');
            } elseif ($ret !== strlen($commandString) + 1) {
                $this->throwSshFailure(
                    'Failed to write the whole command to the remote command pipe'
                );
            }
        } else {
            $this->throwSshFailure();
        }
    }

    /**
     * Get the pipes of the SSH subprocess
     *
     * @return  array
     */
    protected function getSshPipes()
    {
        if ($this->sshPipes === null) {
            $this->forkSsh();
        }

        return $this->sshPipes;
    }

    /**
     * Get the SSH subprocess
     *
     * @return  resource
     */
    protected function getSshProcess()
    {
        if ($this->sshProcess === null) {
            $this->forkSsh();
        }

        return $this->sshProcess;
    }

    /**
     * Get the status of the SSH subprocess
     *
     * @param   string  $what
     *
     * @return  mixed
     */
    protected function getSshProcessStatus($what = null)
    {
        $status = proc_get_status($this->getSshProcess());
        if ($what === null) {
            return $status;
        } else {
            return $status[$what];
        }
    }

    /**
     * Get whether the SSH subprocess is alive
     *
     * @return  bool
     */
    protected function isSshAlive()
    {
        return $this->getSshProcessStatus('running');
    }

    /**
     * Fork SSH subprocess
     *
     * @throws  CommandTransportException   If fork fails
     */
    protected function forkSsh()
    {
        $descriptors = array(
            0 => array('pipe', 'r'),
            1 => array('pipe', 'w'),
            2 => array('pipe', 'w')
        );

        $this->sshProcess = proc_open($this->sshCommand(), $descriptors, $this->sshPipes);

        if (! is_resource($this->sshProcess)) {
            throw new CommandTransportException(
                'Can\'t send external Icinga command: Failed to fork SSH'
            );
        }
    }

    /**
     * Read from STDERR
     *
     * @return  string
     */
    protected function readStderr()
    {
        return stream_get_contents($this->sshPipes[2]);
    }

    /**
     * Throw SSH failure
     *
     * @param   string  $msg
     *
     * @throws  CommandTransportException
     */
    protected function throwSshFailure($msg = 'Can\'t send external Icinga command')
    {
        throw new CommandTransportException(
            '%s: %s',
            $msg,
            $this->readStderr() . var_export($this->getSshProcessStatus(), true)
        );
    }

    /**
     * Close SSH pipes and SSH subprocess
     */
    public function __destruct()
    {
        if (is_resource($this->sshProcess)) {
            fclose($this->sshPipes[0]);
            fclose($this->sshPipes[1]);
            fclose($this->sshPipes[2]);

            proc_close($this->sshProcess);
        }
    }
}