summaryrefslogtreecommitdiffstats
path: root/library/Pdfexport/HeadlessChrome.php
blob: 06129870c27297770c6f05bd6e57303ffe77691d (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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
<?php

/* Icinga PDF Export | (c) 2018 Icinga GmbH | GPLv2 */

namespace Icinga\Module\Pdfexport;

use Exception;
use Icinga\Application\Logger;
use Icinga\Application\Platform;
use Icinga\File\Storage\StorageInterface;
use Icinga\File\Storage\TemporaryLocalFileStorage;
use ipl\Html\HtmlString;
use LogicException;
use React\ChildProcess\Process;
use React\EventLoop\Factory;
use React\EventLoop\TimerInterface;
use WebSocket\Client;
use WebSocket\ConnectionException;

class HeadlessChrome
{
    /**
     * Line of stderr output identifying the websocket url
     *
     * First matching group is the used port and the second one the browser id.
     */
    const DEBUG_ADDR_PATTERN = '/DevTools listening on ws:\/\/((?>\d+\.?){4}:\d+)\/devtools\/browser\/([\w-]+)/';

    /** @var string */
    const WAIT_FOR_NETWORK = 'wait-for-network';

    /** @var string Javascript Promise to wait for layout initialization */
    const WAIT_FOR_LAYOUT = <<<JS
new Promise((fulfill, reject) => {
    let timeoutId = setTimeout(() => reject('fail'), 10000);

    if (document.documentElement.dataset.layoutReady === 'yes') {
        clearTimeout(timeoutId);
        fulfill(null);
        return;
    }

    document.addEventListener('layout-ready', e => {
        clearTimeout(timeoutId);
        fulfill(e.detail);
    }, {
        once: true
    });
})
JS;

    /** @var string Path to the Chrome binary */
    protected $binary;

    /** @var array Host and port to the remote Chrome */
    protected $remote;

    /**
     * The document to print
     *
     * @var PrintableHtmlDocument
     */
    protected $document;

    /** @var string Target Url */
    protected $url;

    /** @var StorageInterface */
    protected $fileStorage;

    /** @var array */
    private $interceptedRequests = [];

    /** @var array */
    private $interceptedEvents = [];

    /**
     * Get the path to the Chrome binary
     *
     * @return  string
     */
    public function getBinary()
    {
        return $this->binary;
    }

    /**
     * Set the path to the Chrome binary
     *
     * @param   string  $binary
     *
     * @return  $this
     */
    public function setBinary($binary)
    {
        $this->binary = $binary;

        return $this;
    }

    /**
     * Get host and port combination of the remote chrome
     *
     * @return array
     */
    public function getRemote()
    {
        return $this->remote;
    }

    /**
     * Set host and port combination of a remote chrome
     *
     * @param string $host
     * @param int    $port
     *
     * @return $this
     */
    public function setRemote($host, $port)
    {
        $this->remote = [$host, $port];

        return $this;
    }

    /**
     * Get the target Url
     *
     * @return  string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * Set the target Url
     *
     * @param   string  $url
     *
     * @return  $this
     */
    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }

    /**
     * Get the file storage
     *
     * @return  StorageInterface
     */
    public function getFileStorage()
    {
        if ($this->fileStorage === null) {
            $this->fileStorage = new TemporaryLocalFileStorage();
        }

        return $this->fileStorage;
    }

    /**
     * Set the file storage
     *
     * @param   StorageInterface  $fileStorage
     *
     * @return  $this
     */
    public function setFileStorage($fileStorage)
    {
        $this->fileStorage = $fileStorage;

        return $this;
    }

    /**
     * Render the given argument name-value pairs as shell-escaped string
     *
     * @param   array   $arguments
     *
     * @return  string
     */
    public static function renderArgumentList(array $arguments)
    {
        $list = [];

        foreach ($arguments as $name => $value) {
            if ($value !== null) {
                $value = escapeshellarg($value);

                if (! is_int($name)) {
                    if (substr($name, -1) === '=') {
                        $glue = '';
                    } else {
                        $glue = ' ';
                    }

                    $list[] = escapeshellarg($name) . $glue . $value;
                } else {
                    $list[] = $value;
                }
            } else {
                $list[] = escapeshellarg($name);
            }
        }

        return implode(' ', $list);
    }

    /**
     * Use the given HTML as input
     *
     * @param string|PrintableHtmlDocument $html
     * @param bool $asFile
     * @return $this
     */
    public function fromHtml($html, $asFile = false)
    {
        if ($html instanceof PrintableHtmlDocument) {
            $this->document = $html;
        } else {
            $this->document = (new PrintableHtmlDocument())
                ->setContent(HtmlString::create($html));
        }

        if ($asFile) {
            $path = uniqid('icingaweb2-pdfexport-') . '.html';
            $storage = $this->getFileStorage();

            $storage->create($path, $this->document->render());

            $path = $storage->resolvePath($path, true);

            $this->setUrl("file://$path");
        }

        return $this;
    }

    /**
     * Export to PDF
     *
     * @return string
     * @throws Exception
     */
    public function toPdf()
    {
        switch (true) {
            case $this->remote !== null:
                try {
                    $result = $this->jsonVersion($this->remote[0], $this->remote[1]);
                    $parts = explode('/', $result['webSocketDebuggerUrl']);
                    $pdf = $this->printToPDF(join(':', $this->remote), end($parts), isset($this->document)
                        ? $this->document->getPrintParameters()
                        : []);
                    break;
                } catch (Exception $e) {
                    if ($this->binary === null) {
                        throw $e;
                    } else {
                        Logger::warning(
                            'Failed to connect to remote chrome: %s:%d (%s)',
                            $this->remote[0],
                            $this->remote[1],
                            $e
                        );
                    }
                }

                // Fallback to the local binary if a remote chrome is unavailable
            case $this->binary !== null:
                $browserHome = $this->getFileStorage()->resolvePath('HOME');
                $commandLine = join(' ', [
                    escapeshellarg($this->getBinary()),
                    static::renderArgumentList([
                        '--bwsi',
                        '--headless',
                        '--disable-gpu',
                        '--no-sandbox',
                        '--no-first-run',
                        '--disable-dev-shm-usage',
                        '--remote-debugging-port=0',
                        '--homedir=' => $browserHome,
                        '--user-data-dir=' => $browserHome
                    ])
                ]);

                if (Platform::isLinux()) {
                    Logger::debug('Starting browser process: HOME=%s exec %s', $browserHome, $commandLine);
                    $chrome = new Process('exec ' . $commandLine, null, ['HOME' => $browserHome]);
                } else {
                    Logger::debug('Starting browser process: %s', $commandLine);
                    $chrome = new Process($commandLine);
                }

                $loop = Factory::create();

                $killer = $loop->addTimer(10, function (TimerInterface $timer) use ($chrome) {
                    $chrome->terminate(6); // SIGABRT
                    Logger::error(
                        'Terminated browser process after %d seconds elapsed without the expected output',
                        $timer->getInterval()
                    );
                });

                $chrome->start($loop);

                $pdf = null;
                $chrome->stderr->on('data', function ($chunk) use (&$pdf, $chrome, $loop, $killer) {
                    Logger::debug('Caught browser output: %s', $chunk);

                    if (preg_match(self::DEBUG_ADDR_PATTERN, trim($chunk), $matches)) {
                        $loop->cancelTimer($killer);

                        try {
                            $pdf = $this->printToPDF($matches[1], $matches[2], isset($this->document)
                                ? $this->document->getPrintParameters()
                                : []);
                        } catch (Exception $e) {
                            Logger::error('Failed to print PDF. An error occurred: %s', $e);
                        }

                        $chrome->terminate();
                    }
                });

                $chrome->on('exit', function ($exitCode, $termSignal) use ($loop, $killer) {
                    $loop->cancelTimer($killer);

                    Logger::debug('Browser terminated by signal %d and exited with code %d', $termSignal, $exitCode);
                });

                $loop->run();
        }

        if (empty($pdf)) {
            throw new Exception(
                'Received empty response or none at all from browser.'
                . ' Please check the logs for further details.'
            );
        }

        return $pdf;
    }

    /**
     * Export to PDF and save as file on disk
     *
     * @return string The path to the file on disk
     */
    public function savePdf()
    {
        $path = uniqid('icingaweb2-pdfexport-') . '.pdf';

        $storage = $this->getFileStorage();
        $storage->create($path, '');

        $path = $storage->resolvePath($path, true);
        file_put_contents($path, $this->toPdf());

        return $path;
    }

    private function printToPDF($socket, $browserId, array $parameters)
    {
        $browser = new Client(sprintf('ws://%s/devtools/browser/%s', $socket, $browserId));

        // Open new tab, get its id
        $result = $this->communicate($browser, 'Target.createTarget', [
            'url'   => 'about:blank'
        ]);
        if (isset($result['targetId'])) {
            $targetId = $result['targetId'];
        } else {
            throw new Exception('Expected target id. Got instead: ' . json_encode($result));
        }

        $page = new Client(sprintf('ws://%s/devtools/page/%s', $socket, $targetId), ['timeout' => 300]);

        // enable various events
        $this->communicate($page, 'Log.enable');
        $this->communicate($page, 'Network.enable');
        $this->communicate($page, 'Page.enable');

        try {
            $this->communicate($page, 'Console.enable');
        } catch (Exception $_) {
            // Deprecated, might fail
        }

        if (($url = $this->getUrl()) !== null) {
            // Navigate to target
            $result = $this->communicate($page, 'Page.navigate', [
                'url'   => $url
            ]);
            if (isset($result['frameId'])) {
                $frameId = $result['frameId'];
            } else {
                throw new Exception('Expected navigation frame. Got instead: ' . json_encode($result));
            }

            // wait for page to fully load
            $this->waitFor($page, 'Page.frameStoppedLoading', ['frameId' => $frameId]);
        } elseif (isset($this->document)) {
            // If there's no url to load transfer the document's content directly
            $this->communicate($page, 'Page.setDocumentContent', [
                'frameId'   => $targetId,
                'html'      => $this->document->render()
            ]);

            // wait for page to fully load
            $this->waitFor($page, 'Page.loadEventFired');
        } else {
            throw new LogicException('Nothing to print');
        }

        // Wait for network activity to finish
        $this->waitFor($page, self::WAIT_FOR_NETWORK);

        // Wait for layout to initialize
        if (isset($this->document)) {
            // Ensure layout scripts work in the same environment as the pdf printing itself
            $this->communicate($page, 'Emulation.setEmulatedMedia', ['media' => 'print']);

            $this->communicate($page, 'Runtime.evaluate', [
                'timeout'       => 1000,
                'expression'    => 'setTimeout(() => new Layout().apply(), 0)'
            ]);

            $promisedResult = $this->communicate($page, 'Runtime.evaluate', [
                'awaitPromise'  => true,
                'returnByValue' => true,
                'timeout'       => 1000, // Failsafe, doesn't apply to `await` it seems
                'expression'    => static::WAIT_FOR_LAYOUT
            ]);
            if (isset($promisedResult['exceptionDetails'])) {
                if (isset($promisedResult['exceptionDetails']['exception']['description'])) {
                    Logger::error(
                        'PDF layout failed to initialize: %s',
                        $promisedResult['exceptionDetails']['exception']['description']
                    );
                } else {
                    Logger::warning('PDF layout failed to initialize. Pages might look skewed.');
                }
            }

            // Reset media emulation, this may prevent the real media from coming into effect?
            $this->communicate($page, 'Emulation.setEmulatedMedia', ['media' => '']);
        }

        // print pdf
        $result = $this->communicate($page, 'Page.printToPDF', array_merge(
            $parameters,
            ['transferMode' => 'ReturnAsBase64', 'printBackground' => true]
        ));
        if (isset($result['data']) && !empty($result['data'])) {
            $pdf = base64_decode($result['data']);
        } else {
            throw new Exception('Expected base64 data. Got instead: ' . json_encode($result));
        }

        // close tab
        $result = $this->communicate($browser, 'Target.closeTarget', [
            'targetId' => $targetId
        ]);
        if (! isset($result['success'])) {
            throw new Exception('Expected close confirmation. Got instead: ' . json_encode($result));
        }

        try {
            $browser->close();
        } catch (ConnectionException $e) {
            // For some reason, the browser doesn't send a response
            Logger::debug(sprintf('Failed to close browser connection: ' . $e->getMessage()));
        }

        return $pdf;
    }

    private function renderApiCall($method, $options = null)
    {
        $data = [
            'id' => time(),
            'method' => $method,
            'params' => $options ?: []
        ];

        return json_encode($data, JSON_FORCE_OBJECT);
    }

    private function parseApiResponse($payload)
    {
        $data = json_decode($payload, true);
        if (isset($data['method']) || isset($data['result'])) {
            return $data;
        } elseif (isset($data['error'])) {
            throw new Exception(sprintf(
                'Error response (%s): %s',
                $data['error']['code'],
                $data['error']['message']
            ));
        } else {
            throw new Exception(sprintf('Unknown response received: %s', $payload));
        }
    }

    private function registerEvent($method, $params)
    {
        if (Logger::getInstance()->getLevel() === Logger::DEBUG) {
            $shortenValues = function ($params) use (&$shortenValues) {
                foreach ($params as &$value) {
                    if (is_array($value)) {
                        $value = $shortenValues($value);
                    } elseif (is_string($value)) {
                        $shortened = substr($value, 0, 256);
                        if ($shortened !== $value) {
                            $value = $shortened . '...';
                        }
                    }
                }

                return $params;
            };
            $shortenedParams = $shortenValues($params);

            Logger::debug(
                'Received CDP event: %s(%s)',
                $method,
                join(',', array_map(function ($param) use ($shortenedParams) {
                    return $param . '=' . json_encode($shortenedParams[$param]);
                }, array_keys($shortenedParams)))
            );
        }

        if ($method === 'Network.requestWillBeSent') {
            $this->interceptedRequests[$params['requestId']] = $params;
        } elseif ($method === 'Network.loadingFinished') {
            unset($this->interceptedRequests[$params['requestId']]);
        } elseif ($method === 'Network.loadingFailed') {
            $requestData = $this->interceptedRequests[$params['requestId']];
            unset($this->interceptedRequests[$params['requestId']]);

            Logger::error(
                'Headless Chrome was unable to complete a request to "%s". Error: %s',
                $requestData['request']['url'],
                $params['errorText']
            );
        } else {
            $this->interceptedEvents[] = ['method' => $method, 'params' => $params];
        }
    }

    private function communicate(Client $ws, $method, $params = null)
    {
        Logger::debug('Transmitting CDP call: %s(%s)', $method, $params ? join(',', array_keys($params)) : '');
        $ws->send($this->renderApiCall($method, $params));

        do {
            $response = $this->parseApiResponse($ws->receive());
            $gotEvent = isset($response['method']);

            if ($gotEvent) {
                $this->registerEvent($response['method'], $response['params']);
            }
        } while ($gotEvent);

        Logger::debug('Received CDP result: %s', empty($response['result'])
            ? 'none'
            : join(',', array_keys($response['result'])));

        return $response['result'];
    }

    private function waitFor(Client $ws, $eventName, array $expectedParams = null)
    {
        if ($eventName !== self::WAIT_FOR_NETWORK) {
            Logger::debug(
                'Awaiting CDP event: %s(%s)',
                $eventName,
                $expectedParams ? join(',', array_keys($expectedParams)) : ''
            );
        } elseif (empty($this->interceptedRequests)) {
            return null;
        }

        $wait = true;
        $interceptedPos = -1;

        do {
            if (isset($this->interceptedEvents[++$interceptedPos])) {
                $response = $this->interceptedEvents[$interceptedPos];
                $intercepted = true;
            } else {
                $response = $this->parseApiResponse($ws->receive());
                $intercepted = false;
            }

            if (isset($response['method'])) {
                $method = $response['method'];
                $params = $response['params'];

                if (! $intercepted) {
                    $this->registerEvent($method, $params);
                }

                if ($eventName === self::WAIT_FOR_NETWORK) {
                    $wait = ! empty($this->interceptedRequests);
                } elseif ($method === $eventName) {
                    if ($expectedParams !== null) {
                        $diff = array_intersect_assoc($params, $expectedParams);
                        $wait = empty($diff);
                    } else {
                        $wait = false;
                    }
                }

                if (! $wait && $intercepted) {
                    unset($this->interceptedEvents[$interceptedPos]);
                }
            }
        } while ($wait);

        return $params;
    }

    /**
     * Get the major version number of Chrome or false on failure
     *
     * @return  int|false
     *
     * @throws  Exception
     */
    public function getVersion()
    {
        switch (true) {
            case $this->remote !== null:
                try {
                    $result = $this->jsonVersion($this->remote[0], $this->remote[1]);
                    $version = $result['Browser'];
                    break;
                } catch (Exception $e) {
                    if ($this->binary === null) {
                        throw $e;
                    } else {
                        Logger::warning(
                            'Failed to connect to remote chrome: %s:%d (%s)',
                            $this->remote[0],
                            $this->remote[1],
                            $e
                        );
                    }
                }

                // Fallback to the local binary if a remote chrome is unavailable
            case $this->binary !== null:
                $command = new ShellCommand(
                    escapeshellarg($this->getBinary()) . ' ' . static::renderArgumentList(['--version']),
                    false
                );

                $output = $command->execute();

                if ($command->getExitCode() !== 0) {
                    throw new \Exception($output->stderr);
                }

                $version = $output->stdout;
                break;
            default:
                throw new LogicException('Set a binary or remote first');
        }

        if (preg_match('/(\d+)\.[\d.]+/', $version, $match)) {
            return (int) $match[1];
        }

        return false;
    }

    /**
     * Fetch result from the /json/version API endpoint
     *
     * @param string $host
     * @param int    $port
     *
     * @return bool|array
     */
    protected function jsonVersion($host, $port)
    {
        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', sprintf('http://%s:%s/json/version', $host, $port));

        if ($response->getStatusCode() !== 200) {
            return false;
        }

        return json_decode($response->getBody(), true);
    }
}