-
Notifications
You must be signed in to change notification settings - Fork 155
/
datadog-setup.php
2433 lines (2204 loc) · 89.9 KB
/
datadog-setup.php
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// Tests for the installer are in 'dockerfiles/verify_packages/installer'
const INI_SCANDIR = 'Scan this dir for additional .ini files';
const INI_MAIN = 'Loaded Configuration File';
const EXTENSION_DIR = 'extension_dir';
const THREAD_SAFETY = 'Thread Safety';
const PHP_VER = 'PHP Version';
const PHP_API = 'PHP API';
const IS_DEBUG = 'Debug Build';
// Commands
const CMD_CONFIG_GET = 'config get';
const CMD_CONFIG_SET = 'config set';
const CMD_CONFIG_LIST = 'config list';
// Options
const OPT_HELP = 'help';
const OPT_INSTALL_DIR = 'install-dir';
const OPT_EXTENSION_DIR = 'extension-dir';
const OPT_PHP_BIN = 'php-bin';
const OPT_PHP_INI = 'ini';
const OPT_FILE = 'file';
const OPT_UNINSTALL = 'uninstall';
const OPT_ENABLE_APPSEC = 'enable-appsec';
const OPT_ENABLE_PROFILING = 'enable-profiling';
const OPT_INI_SETTING = 'd';
// Release version is set while generating the final release files
const RELEASE_VERSION = '@release_version@';
// phpcs:disable Generic.Files.LineLength.TooLong
// For testing purposes, we need an alternate repo where we can push bundles that includes changes that we are
// trying to test, as the previously released versions would not have those changes.
define('RELEASE_URL_PREFIX', (getenv('DD_TEST_INSTALLER_REPO') ?: "https://github.com/DataDog/dd-trace-php") . "/releases/download/" . RELEASE_VERSION . "/");
// phpcs:enable Generic.Files.LineLength.TooLong
define('IS_WINDOWS', strncasecmp(PHP_OS, "WIN", 3) == 0);
define('EXTENSION_PREFIX', IS_WINDOWS ? "php_" : "");
define('EXTENSION_SUFFIX', IS_WINDOWS ? "dll" : "so");
define('DEFAULT_INSTALL_DIR', IS_WINDOWS ? getenv('ProgramW6432') . '\Datadog\PHP Tracer' : '/opt/datadog');
/**
* The number of items to shift off `get_ini_settings` for config commands.
*/
const CMD_CONFIG_NUM_SHIFT = 3;
function main()
{
if (is_truthy(getenv('DD_TEST_EXECUTION'))) {
return;
}
$arguments = parse_validate_user_options();
$options = $arguments['opts'];
switch ($arguments['cmd']) {
case CMD_CONFIG_GET:
cmd_config_get($options);
break;
case CMD_CONFIG_SET:
cmd_config_set($options);
break;
case CMD_CONFIG_LIST:
cmd_config_list($options);
break;
default:
if ($options[OPT_UNINSTALL]) {
uninstall($options);
} else {
install($options);
}
}
}
function print_help()
{
$installdir = DEFAULT_INSTALL_DIR;
echo <<<EOD
Usage:
Interactive
php datadog-setup.php [command] ...
Non-Interactive
php datadog-setup.php --php-bin php ...
php datadog-setup.php --php-bin php --php-bin /usr/local/sbin/php-fpm ...
php datadog-setup.php config get --php-bin php -d datadog.profiling.enabled
php datadog-setup.php config set --php-bin php -d datadog.profiling.enabled=On
Options:
-h, --help Print this help text and exit.
--php-bin all|<path to php> Install the library to the specified binary or
all php binaries in standard search paths. The
option can be provided multiple times.
--install-dir <path> Install to a specific directory. Default: '$installdir'
--uninstall Uninstall the library from the specified binaries.
--file <path to .tar.gz> Path to a dd-library-php-*.tar.gz file. Can be used for offline installation.
--extension-dir <path> Specify the extension directory. Default: PHP's extension directory.
--ini <path> Specify the INI file to use. Default: <ini-dir>/98-ddtrace.ini
--enable-appsec Enable the application security monitoring module.
--enable-profiling Enable the profiling module.
-d setting[=value] Used in conjunction with `config <set|get>`
command to specify the INI setting to get or set.
Available commands:
config list List Datadog's INI setting for the specified binaries.
config get Get INI setting for the specified binaries.
config set Set INI setting for the specified binaries.
EOD;
}
// phpcs:disable PSR1.Classes.ClassDeclaration.MissingNamespace
class IniRecord
{
/** @var string */
public $setting;
/** @var string */
public $currentValue;
/** @var string */
public $defaultValue;
/** @var string */
public $iniFile;
/** @var string */
public $binary;
public function println()
{
// phpcs:disable Generic.Files.LineLength.TooLong
echo "$this->setting = $this->currentValue; default: $this->defaultValue, binary: $this->binary, INI file: $this->iniFile\n";
// phpcs:disable Generic.Files.LineLength.TooLong
}
}
/**
* @param array $options
* @return array<string, IniRecord>
*/
function config_list(array $options)
{
$iniSettings = get_ini_settings('', '', '');
// The first 3 are 'extension' type of settings.
$iniSettings = array_slice($iniSettings, CMD_CONFIG_NUM_SHIFT);
// Build an index by unique names for filtering.
$indexByName = array_column($iniSettings, null, 'name');
$return = [];
foreach (require_binaries_or_exit($options) as $command => $fullPath) {
$binaryForLog = ($command === $fullPath) ? $fullPath : "$command ($fullPath)";
$iniFilePaths = find_all_ini_files(ini_values($fullPath));
foreach ($iniFilePaths as $iniFilePath) {
$iniFileSettings = parse_ini_file($iniFilePath, false, INI_SCANNER_RAW);
$settings = array_intersect_key($iniFileSettings, $indexByName);
foreach ($settings as $iniFileSetting => $currentValue) {
$iniSetting = $indexByName[$iniFileSetting];
$record = new IniRecord();
$record->setting = $iniFileSetting;
$record->currentValue = $currentValue;
$record->defaultValue = $iniSetting['default'];
$record->iniFile = $iniFilePath;
$record->binary = $binaryForLog;
$return[$record->setting] = $record;
}
}
}
return $return;
}
/**
* This function will print out all Datadog specific PHP INI settings. The list
* of Datadog specific settings is retrieved by calling `get_ini_settings()`. It
* will also show the default and INI file this setting was found.
* The output will be grouped by PHP binary, example:
*
* $ php datadog-setup.php config list --php-bin all
* Searching for available php binaries, this operation might take a while.
* datadog.profiling.enabled = On; default: 1, binary: /opt/php/8.2/bin/php, INI file: /opt/php/etc/conf.d/98-ddtrace.ini
* datadog.profiling.experimental_allocation_enabled = On; default: 1, binary: /opt/php/8.2/bin/php, INI file: /opt/php/etc/conf.d/98-ddtrace.ini
*
* @see get_ini_settings
* @return void
*/
function cmd_config_list(array $options)
{
foreach (config_list($options) as $record) {
$record->println();
}
}
/**
* This function will print the specified PHP INI settings. It only prints
* information for Datadog's own settings; it can't be used to parse opcache,
* xdebug, etc.
* The output will be grouped by PHP binary, example:
*
* $ php datadog-setup.php config get --php-bin all \
* -ddatadog.profiling.experimental_allocation_enabled \
* -ddatadog.profiling.experimental_cpu_time_enabled \
* -dnonexisting \
* -dopcache.preload
* datadog.profiling.experimental_allocation_enabled = On; binary: /opt/php/8.2/bin/php, INI file: /opt/php/etc/conf.d/98-ddtrace.ini
* datadog.profiling.experimental_cpu_time_enabled = On; binary: /opt/php/8.2/bin/php, INI file: /opt/php/etc/conf.d/98-ddtrace.ini
* nonexisting = undefined; is missing in INI files
* opcache.preload = undefined; is missing in INI files
* @return void
*/
function cmd_config_get(array $options)
{
if (!isset($options['d'])) {
print_help();
return;
}
/* A value could be set in multiple places:
* - /opt/php/8.1/etc/conf.d/98-ddtrace.ini
* - /opt/php/8.1/etc/conf.d/90-ddtrace-custom.ini
* So, a given setting like 'datadog.trace.enabled' is not necessarily
* unique in the iterator's keys.
*/
$records = [];
foreach (config_list($options) as $setting => $record) {
$records[$setting][] = $record;
}
foreach ($options['d'] as $iniSetting) {
if (!isset($records[$iniSetting])) {
echo '; ', $iniSetting, ' = undefined; is missing in INI files', PHP_EOL;
} else {
foreach ($records[$iniSetting] as $record) {
$record->println();
}
}
}
}
/**
* This function will set the given INI settings for any given PHP binary
*
* 1. Scan all INI files for for this INI setting and update if found (updates
* in all INI files in case it finds in multiple places and warns about the
* mess it found).
* 2. In case it could not find, it searches for commented out versions of this
* INI setting, uncomments it and updates the value. It first checks this in
* the "default" INI file (the one that holds the `extension = ddtrace` line,
* then others and only promotes the first commented version found.
* 3. In case this INI setting is not there yet it creates a new entry in the
* "default" INI file (see above).
*
* $ php datadog-setup.php config set --php-bin all \
* -ddatadog.profiling.experimental_allocation_enabled=On \
* -ddatadog.profiling.experimental_cpu_time_enabled=On \
* Setting configuration for binary: php (/opt/php/8.2/bin/php)
* Set 'datadog.profiling.experimental_allocation_enabled' to 'On' in INI file: /opt/php/etc/conf.d/98-ddtrace.ini
* Set 'datadog.profiling.experimental_cpu_time_enabled' to 'On' in INI file: /opt/php/etc/conf.d/98-ddtrace.ini
*/
function cmd_config_set(array $options)
{
if (!isset($options['d'])) {
print_help();
return;
}
$selectedBinaries = require_binaries_or_exit($options);
foreach ($selectedBinaries as $command => $fullPath) {
$binaryForLog = ($command === $fullPath) ? $fullPath : "$command ($fullPath)";
echo "Setting configuration for binary: $binaryForLog", PHP_EOL;
$phpProps = ini_values($fullPath);
foreach ($options['d'] as $cliIniSetting) {
if (($setting = parse_ini_setting($cliIniSetting)) === false) {
echo "The given INI setting '", $cliIniSetting,
"' can't be converted to a valid INI setting, skipping.", PHP_EOL;
continue;
}
$allIniFilePaths = find_all_ini_files($phpProps);
$matchCount = 0;
// look for INI setting in INI files
foreach ($allIniFilePaths as $iniFile) {
$count = update_ini_setting($setting, $iniFile, false);
if ($count === 0) {
continue;
}
if ($count === false) {
echo "Could not set '", $setting[0], "' to '", $setting[1],
"' in INI file: ", $iniFile , PHP_EOL;
continue;
}
echo "Set '", $setting[0], "' to '", $setting[1], "' in INI file: ", $iniFile, PHP_EOL;
$matchCount += $count;
}
if ($matchCount >= 1) {
// found and updated
if ($matchCount >= 2) {
echo "Warning: '$setting[0]' was found in multiple places, ",
"you might want to remove duplicates.", PHP_EOL;
}
continue;
}
// If we are here, we could not find the INI setting in any files, so
// we try and look for commented versions
$matchCount = 0;
// look for INI setting in INI files
foreach ($allIniFilePaths as $iniFile) {
$count = update_ini_setting($setting, $iniFile, true);
if ($count === 0) {
continue;
}
if ($count === false) {
echo "Could not set '", $setting[0], "' to '", $setting[1],
"' in INI file: ", $iniFile , PHP_EOL;
continue;
}
echo "Set '", $setting[0], "' to '", $setting[1], "' in INI file: ", $iniFile, PHP_EOL;
$matchCount += $count;
break;
}
if ($matchCount >= 1) {
// found, promoted from comment and updated
continue;
}
// Now we are here, meaning we could not find it, not in active nor in
// commented version, so we just add it to the default INI file(s)
$mainIniFilePaths = find_main_ini_files($phpProps);
$set = false;
foreach ($mainIniFilePaths as $iniFile) {
if (!file_exists($iniFile)) {
echo "File '$iniFile' does not exist. Trying to create it... ";
if (file_put_contents($iniFile, '') === false) {
echo "Could not set '{$setting[0]}' to '{$setting[1]}' in INI file: {$iniFile}.\n";
$directory = dirname($iniFile);
if (!is_dir($directory)) {
echo "Directory '$directory' doesn't exist. Create it and try again if you want to use '$iniFile'.\n";
}
continue;
} else {
echo "Success.\n";
}
}
$iniFileContent = file_get_contents($iniFile);
// check for "End of Line" symbol at the end of the file and
// add in case it is missing
if (strlen($iniFileContent) > 0 && substr($iniFileContent, -1, 1) !== PHP_EOL) {
$iniFileContent .= PHP_EOL;
}
$iniFileContent .= implode(' = ', $setting) . PHP_EOL;
if (file_put_contents($iniFile, $iniFileContent) === false) {
echo "Could not set '{$setting[0]}' to '{$setting[1]}' in INI file: {$iniFile}.\n";
continue;
}
echo "Set '{$setting[0]}' to '{$setting[1]}' in INI file: $iniFile.\n";
$set = true;
}
if (!$set) {
echo "Unable to set '{$setting[0]}' to '{$setting[1]}' in any INI file for $binaryForLog.\n";
exit(1);
}
}
}
}
/**
* Parse a given INI setting (from CLI) into an array and return it. It also tries
* to parse the new setting with `parse_ini_string()` to validate it is actually
* working
*
* @param string $setting
* @return false|array{0:string, 1:string}
*/
function parse_ini_setting($setting)
{
// `trim()` should not be needed, but better safe than sorry
$setting = array_map(
'trim',
explode(
'=',
$setting,
2
)
);
if (count($setting) !== 2) {
return false;
}
// safety: try out if parsing the generated ini setting is actually possible
if (parse_ini_string($setting[0] . '=' . $setting[1], false, INI_SCANNER_RAW) === false) {
return false;
}
return $setting;
}
/**
* This function will try and update a given `$setting` in the INI file given in
* `$iniFile`. First it tries to find an uncommented version of the setting in
* the file and replace this with the new value. In case no uncommented version
* was found it tries to find commented versions of this INI setting.
*
* In case `$promoteComment` is set to `true`, this function will replace and
* therefore promote only the first occurrence it finds from a comment to an INI
* setting in the given `$iniFile`.
*
* @param array{0: string, 1: string} $setting
* @param string $iniFile
* @param bool $promoteComment
* @return false|int
*/
function update_ini_setting($setting, $iniFile, $promoteComment)
{
$iniFileContent = file_get_contents($iniFile);
if ($promoteComment) {
$regex = '/^[\h;]*' . preg_quote($setting[0]) . '\h*=\h*?[^;\n\r]*/mi';
} else {
$regex = '/^\h*' . preg_quote($setting[0]) . '\h*=\h*?[^;\n\r]*/mi';
}
$count = 0;
$iniFileContent = preg_replace($regex, implode(' = ', $setting), $iniFileContent, $promoteComment ? 1 : -1, $count);
if ($iniFileContent === null) {
// something wrong with the regex, the user should see a warning
// in the form of "Warning: preg_replace(): Compilation failed ..."
return false;
}
if ($count > 0) {
if (file_put_contents($iniFile, $iniFileContent) === false) {
return false;
}
}
return $count;
}
function install($options)
{
$architecture = get_architecture();
$platform = "$architecture-" . (IS_WINDOWS ? "windows" : "linux-" . (is_alpine() ? 'musl' : 'gnu'));
// Checking required libraries
check_library_prerequisite_or_exit('libcurl');
check_library_prerequisite_or_exit('libgcc_s');
if (!is_alpine()) {
if (is_truthy($options[OPT_ENABLE_PROFILING])) {
check_library_prerequisite_or_exit('libdl.so');
check_library_prerequisite_or_exit('libpthread');
check_library_prerequisite_or_exit('librt');
}
}
// Picking the right binaries to install the library
$selectedBinaries = require_binaries_or_exit($options);
$interactive = empty($options[OPT_PHP_BIN]);
$commandExtensionSuffixes = [];
$downloadVersions = [];
foreach ($selectedBinaries as $command => $fullPath) {
$binaryForLog = ($command === $fullPath) ? $fullPath : "$command ($fullPath)";
echo "Checking for binary: $binaryForLog\n";
check_php_ext_prerequisite_or_exit($fullPath, 'json');
$phpProperties = ini_values($fullPath);
if (!isset($phpProperties[INI_SCANDIR])) {
if (!isset($phpProperties[INI_MAIN])) {
if (IS_WINDOWS) {
$phpProperties[INI_MAIN] = dirname($fullPath) . "/php.ini";
} else {
print_error_and_exit(
"It is not possible to perform installation on this "
. "system because there is no scan directory and no "
. "configuration file loaded."
);
}
}
print_warning(
"Performing an installation without a scan directory may "
. "result in fragile installations that are broken by normal "
. "system upgrades. It is advisable to use the configure "
. "switch --with-config-file-scan-dir when building PHP."
);
}
// Suffix (zts/debug)
$extensionSuffix = '';
if (is_truthy($phpProperties[IS_DEBUG])) {
$extensionSuffix .= '-debug';
}
if (is_truthy($phpProperties[THREAD_SAFETY])) {
$extensionSuffix .= '-zts';
}
$commandExtensionSuffixes[$command] = $extensionSuffix;
$extensionVersion = $phpProperties[PHP_API];
$downloadVersions["$extensionVersion$extensionSuffix"] = true;
}
$tar_gz_suffix = "";
if (count($downloadVersions) === 1) {
$tar_gz_suffix = "-" . key($downloadVersions);
}
// Preparing clean tmp folder to extract files
$tmpDir = sys_get_temp_dir() . '/dd-install';
$tmpArchiveRoot = $tmpDir . '/dd-library-php';
$tmpArchiveTraceRoot = $tmpDir . '/dd-library-php/trace';
$tmpArchiveAppsecRoot = $tmpDir . '/dd-library-php/appsec';
$tmpArchiveAppsecLib = "{$tmpArchiveAppsecRoot}/lib";
$tmpArchiveAppsecEtc = "{$tmpArchiveAppsecRoot}/etc";
$tmpArchiveProfilingRoot = $tmpDir . '/dd-library-php/profiling';
$tmpSrcDir = $tmpArchiveTraceRoot . '/src';
if (!file_exists($tmpDir)) {
execute_or_exit("Cannot create directory '$tmpDir'", "mkdir " . (IS_WINDOWS ? "" : "-p ") . escapeshellarg($tmpDir));
}
register_shutdown_function(function () use ($tmpDir) {
execute_or_exit("Cannot remove temporary directory '$tmpDir'", (IS_WINDOWS ? "rd /s /q " : "rm -rf ") . escapeshellarg($tmpDir));
});
if (!IS_WINDOWS) {
execute_or_exit(
"Cannot clean '$tmpDir'",
"rm -rf " . escapeshellarg($tmpDir) . "/* "
);
}
// Retrieve and extract the archive to a tmp location
if (isset($options[OPT_FILE])) {
print_warning('--' . OPT_FILE . ' option is intended for internal usage and can be removed without notice');
$tmpDirTarGz = $options[OPT_FILE];
} else {
for (;;) {
$url = RELEASE_URL_PREFIX . "dd-library-php-" . RELEASE_VERSION . "-{$platform}{$tar_gz_suffix}.tar.gz";
$tmpDirTarGz = $tmpDir . "/dd-library-php-{$platform}{$tar_gz_suffix}.tar.gz";
if (download($url, $tmpDirTarGz, $tar_gz_suffix != "")) {
break;
}
$tar_gz_suffix = ""; // retry with the full archive if the original download failed
}
}
if (!IS_WINDOWS || `where tar 2> nul` !== null) {
execute_or_exit(
"Cannot extract the archive",
"tar -xf " . escapeshellarg($tmpDirTarGz) . " -C " . escapeshellarg($tmpDir)
);
} elseif (($defaultPath = `where 7z 2> nul`) !== null || @is_dir($installDir7z = getenv("PROGRAMFILES") . "\\7-Zip")) {
if ($defaultPath === null) {
putenv("PATH=" . getenv("PATH") . ";$installDir7z");
}
execute_or_exit(
"Cannot extract the archive",
"7z x " . escapeshellarg($tmpDirTarGz) . " -so | 7z x -aoa -si -ttar -o" . escapeshellarg($tmpDir)
);
} else {
die("ERROR: neither tar nor 7z are installed and available in %PATH%. Please install either to continue the installation.\n");
}
$releaseVersion = trim(file_get_contents("$tmpArchiveRoot/VERSION"));
$installDir = $options[OPT_INSTALL_DIR] . '/' . $releaseVersion;
// Tracer sources
$installDirSourcesDir = $installDir . '/dd-trace-sources';
$installDirSrcDir = $installDirSourcesDir . '/src';
// copying sources to the final destination
if (!file_exists($installDirSourcesDir)) {
execute_or_exit(
"Cannot create directory '$installDirSourcesDir'",
"mkdir " . (IS_WINDOWS ? "" : "-p ") . escapeshellarg($installDirSourcesDir)
);
}
execute_or_exit(
"Cannot copy files from '$tmpSrcDir' to '$installDirSourcesDir'",
(IS_WINDOWS ? "echo d | xcopy /s /e /y /g /b /o /h " : "cp -r ") . escapeshellarg("$tmpSrcDir") . ' ' . escapeshellarg($installDirSrcDir)
);
echo "Installed required source files to '$installDir'\n";
// Appsec helper and rules
if (file_exists($tmpArchiveAppsecRoot)) {
execute_or_exit(
"Cannot copy files from '$tmpArchiveAppsecLib' to '$installDir'",
(IS_WINDOWS ? "xcopy /s /e /y /g /b /o /h " : "cp -rf ") . escapeshellarg("$tmpArchiveAppsecLib") . ' ' . escapeshellarg($installDir)
);
execute_or_exit(
"Cannot copy files from '$tmpArchiveAppsecEtc' to '$installDir'",
(IS_WINDOWS ? "xcopy /s /e /y /g /b /o /h " : "cp -r ") . escapeshellarg("$tmpArchiveAppsecEtc") . ' ' . escapeshellarg($installDir)
);
}
$appSecRulesPath = $installDir . '/etc/recommended.json';
// Actual installation
foreach ($selectedBinaries as $command => $fullPath) {
$binaryForLog = ($command === $fullPath) ? $fullPath : "$command ($fullPath)";
echo "Installing to binary: $binaryForLog\n";
check_php_ext_prerequisite_or_exit($fullPath, 'json');
$phpProperties = ini_values($fullPath);
if (!isset($phpProperties[INI_SCANDIR])) {
if (!isset($phpProperties[INI_MAIN])) {
if (IS_WINDOWS) {
$phpProperties[INI_MAIN] = dirname($fullPath) . "/php.ini";
} else {
print_error_and_exit(
"It is not possible to perform installation on this "
. "system because there is no scan directory and no "
. "configuration file loaded."
);
}
}
print_warning(
"Performing an installation without a scan directory may "
. "result in fragile installations that are broken by normal "
. "system upgrades. It is advisable to use the configure "
. "switch --with-config-file-scan-dir when building PHP."
);
}
// Copying the extension
$extensionVersion = $phpProperties[PHP_API];
$extensionSuffix = $commandExtensionSuffixes[$command];
$extDir = isset($options[OPT_EXTENSION_DIR]) ? $options[OPT_EXTENSION_DIR] : $phpProperties[EXTENSION_DIR];
echo "Installing extension to $extDir\n";
// Trace
$extensionRealPath = "$tmpArchiveTraceRoot/ext/$extensionVersion/"
. EXTENSION_PREFIX . "ddtrace$extensionSuffix." . EXTENSION_SUFFIX;
if (!file_exists($extensionRealPath)) {
print_error_and_exit(substr($extensionSuffix ?: '-nts', 1)
. ' builds of PHP ' . $phpProperties[PHP_VER] . ' are currently not supported');
}
$extensionDestination = $extDir . '/' . EXTENSION_PREFIX . 'ddtrace.' . EXTENSION_SUFFIX;
safe_copy_extension($extensionRealPath, $extensionDestination);
// Profiling
$profilingExtensionRealPath = "$tmpArchiveProfilingRoot/ext/$extensionVersion/"
. EXTENSION_PREFIX . "datadog-profiling$extensionSuffix." . EXTENSION_SUFFIX;
$shouldInstallProfiling = file_exists($profilingExtensionRealPath);
if ($shouldInstallProfiling) {
$profilingExtensionDestination = $extDir . '/' . EXTENSION_PREFIX . 'datadog-profiling.' . EXTENSION_SUFFIX;
safe_copy_extension($profilingExtensionRealPath, $profilingExtensionDestination);
}
// Appsec
$appsecExtensionRealPath = "{$tmpArchiveAppsecRoot}/ext/{$extensionVersion}/"
. EXTENSION_PREFIX . "ddappsec{$extensionSuffix}." . EXTENSION_SUFFIX;
$shouldInstallAppsec = file_exists($appsecExtensionRealPath);
if ($shouldInstallAppsec) {
$appsecExtensionDestination = $extDir . '/' . EXTENSION_PREFIX . 'ddappsec.' . EXTENSION_SUFFIX;
safe_copy_extension($appsecExtensionRealPath, $appsecExtensionDestination);
}
$appSecHelperPath = $installDir . '/lib/libddappsec-helper.so';
if (isset($options[OPT_PHP_INI])) {
$iniFilePaths = $options[OPT_PHP_INI];
} else {
$iniFilePaths = find_main_ini_files($phpProperties);
}
foreach ($iniFilePaths as $iniFilePath) {
$replacements = [];
if (!file_exists($iniFilePath)) {
$iniDir = dirname($iniFilePath);
if (!file_exists($iniDir)) {
execute_or_exit(
"Cannot create directory '$iniDir'",
"mkdir " . (IS_WINDOWS ? "" : "-p ") . escapeshellarg($iniDir)
);
}
if (false === file_put_contents($iniFilePath, '')) {
print_error_and_exit("Cannot create INI file $iniFilePath");
}
echo "Created INI file '$iniFilePath'\n";
} else {
echo "Updating existing INI file '$iniFilePath'";
if (is_link($iniFilePath)) {
$iniFilePath = readlink($iniFilePath);
echo " which is a symlink to '$iniFilePath'";
}
echo "\n";
$replacements += [
// Old name is deprecated
'(ddtrace\.request_init_hook)' => 'datadog.trace.sources_path',
'(datadog\.trace\.request_init_hook)' => 'datadog.trace.sources_path',
'((datadog\.trace\.sources_path)\s*=\s*.*)' => "$1 = $installDirSrcDir",
];
}
if (isset($options[OPT_EXTENSION_DIR])) {
$replacements += [
'(^\s*;?\s*extension\s*=\s*.*ddtrace.*)m' => "extension = $extensionDestination",
];
} else {
$replacements += [
/* In order to support upgrading from legacy installation method to new installation method, we
* replace "extension = /opt/datadog-php/xyz.so" with "extension = ddtrace.so" honoring trailing
* `;`, hence not automatically re-activating the extension if the user had commented it out.
*/
'(^\s*;?\s*extension\s*=\s*.*ddtrace.*)m' => "extension = ddtrace" . (IS_WINDOWS ? "" : "." . EXTENSION_SUFFIX),
// Support upgrading from the C based zend_extension.
'(zend_extension\s*=\s*.*datadog-profiling.*)' => "extension = datadog-profiling" . (IS_WINDOWS ? "" : "." . EXTENSION_SUFFIX),
];
}
// Enabling profiling
if (is_truthy($options[OPT_ENABLE_PROFILING])) {
// phpcs:disable Generic.Files.LineLength.TooLong
if ($shouldInstallProfiling) {
if (isset($options[OPT_EXTENSION_DIR])) {
$replacements['(zend_extension\s*=\s*.*datadog-profiling.*)'] = "extension = $profilingExtensionDestination";
$replacements['(^\s*;?\s*extension\s*=\s*.*datadog-profiling.*)m'] = "extension = $profilingExtensionDestination";
} else {
$replacements['(^\s*;?\s*extension\s*=\s*.*datadog-profiling.*)m'] = "extension = datadog-profiling" . (IS_WINDOWS ? "" : "." . EXTENSION_SUFFIX);
}
} else {
$enableProfiling = OPT_ENABLE_PROFILING;
print_error_and_exit(
"Option --{$enableProfiling} was provided, but it is not supported on this PHP build or version.\n"
);
}
// phpcs:enable Generic.Files.LineLength.TooLong
}
// Load AppSec and enable/disable as required
// phpcs:disable Generic.Files.LineLength.TooLong
if ($shouldInstallAppsec) {
$rulesPathRegex = preg_quote($options[OPT_INSTALL_DIR]) . "/[0-9\.]*/etc/recommended.json";
$iniAppsecExtension = isset($options[OPT_EXTENSION_DIR])
? $appsecExtensionDestination
: ("ddappsec" . (IS_WINDOWS ? "" : "." . EXTENSION_SUFFIX));
$replacements += [
'(^\s*;?\s*extension\s*=\s*.*ddappsec.*)m' => "extension = $iniAppsecExtension",
// Update helper path
'(datadog.appsec.helper_path\s*=.*)' => "datadog.appsec.helper_path = $appSecHelperPath",
// Update and comment rules path
'(^[\s;]*datadog.appsec.rules\s*=\s*' . $rulesPathRegex . ')m' => "; datadog.appsec.rules = " . $appSecRulesPath,
];
if (is_truthy($options[OPT_ENABLE_APPSEC])) {
$replacements += ['(^[\s;]*datadog.appsec.enabled\s*=.*)m' => 'datadog.appsec.enabled = On'];
}
} else {
// Ensure AppSec isn't loaded if not compatible
$replacements['(^[\s;]*extension\s*=\s*.*ddappsec.*)m'] = "; extension = ddappsec" . (IS_WINDOWS ? "" : "." . EXTENSION_SUFFIX);
if (is_truthy($options[OPT_ENABLE_APPSEC])) {
$enableAppsec = OPT_ENABLE_APPSEC;
print_error_and_exit(
"Option --{$enableAppsec} was provided, but it is not supported on this PHP build or version.\n"
);
}
}
add_missing_ini_settings(
$iniFilePath,
get_ini_settings($installDirSrcDir, $appSecHelperPath, $appSecRulesPath),
$replacements
);
// phpcs:enable Generic.Files.LineLength.TooLong
echo "Installation to '$binaryForLog' was successful\n";
}
}
echo "--------------------------------------------------\n";
echo "SUCCESS\n\n";
if ($interactive) {
echo "To run this script in a non interactive mode, use the following options:\n";
$args = array_merge(
$_SERVER["argv"],
array_map(
function ($el) {
return '--php-bin=' . $el;
},
array_keys($selectedBinaries)
)
);
echo " php " . implode(" ", array_map("escapeshellarg", $args)) . "\n";
}
}
/**
* Returns a list of all INI files found for the `$phpProperties` given.
*
* Does so by scanning the INI scan directory for `.ini` files. Additionally we
* check if we are running on a Debian based distribution so we assume the INI
* files are split by SAPI, so we try and add the Apache SAPI INI files as
* well. In case it exists, we also add the default `php.ini` file to the list.
*
* The returned array is somewhat sorted to have the "default" INI file for
* Datadog (`98-ddtrace.ini`) in the beginning of the array.
*
* @see ini_values
* @return string[]
*/
function find_all_ini_files(array $phpProperties)
{
$iniFilePaths = [];
$addIniFiles = function ($path) use (&$iniFilePaths) {
if (!is_dir($path)) {
return;
}
foreach (scandir($path) as $ini) {
if (!is_file($path . '/' . $ini) || substr($ini, -4) !== '.ini') {
continue;
}
$iniFile = $path . '/' . $ini;
if (strpos($ini, '98-ddtrace.ini') !== false) {
array_unshift($iniFilePaths, $iniFile);
} else {
$iniFilePaths[] = $iniFile;
}
}
};
if ($phpProperties[INI_SCANDIR]) {
$addIniFiles($phpProperties[INI_SCANDIR]);
if (strpos($phpProperties[INI_SCANDIR], '/cli/conf.d') !== false) {
/* debian based distros have INI folders split by SAPI, in a predefined way:
* - <...>/cli/conf.d <-- we know this from php -i
* - <...>/apache2/conf.d <-- we derive this from relative path
* - <...>/fpm/conf.d <-- we derive this from relative path
*/
$apacheConfd = str_replace('/cli/conf.d', '/apache2/conf.d', $phpProperties[INI_SCANDIR]);
$addIniFiles($apacheConfd);
}
}
if (isset($phpProperties[INI_MAIN]) && is_file($phpProperties[INI_MAIN])) {
$iniFilePaths = [$phpProperties[INI_MAIN]];
}
return $iniFilePaths;
}
/**
* This function will find the main INI file(s) for the given `$phpProperties`.
*
* The "main" or "default" INI file is either a `98-ddtrace.ini` file or
* another INI file that loads the extension (or rephrasing this as: the file
* the has the `extension = ddtrace` line in it).
*
* In most cases this function will return an array with exactly one element,
* only in case we detect a Debian based distribution, it might contain two
* elements, as debian based distributions split the INI folders based on SAPI
* and we include those as well.
*
* The `$phpProperties` can be retrieved by calling `ini_values($pathToPHPBinary)`.
*
* @see ini_values
* @return string[]
*/
function find_main_ini_files(array $phpProperties)
{
if (isset($phpProperties[INI_SCANDIR])) {
$pos = strpos($phpProperties[INI_SCANDIR], \PATH_SEPARATOR);
if ($pos !== false) {
// https://www.php.net/manual/en/configuration.file.php#configuration.file.scandir
$phpProperties[INI_SCANDIR] = current(array_filter(explode(\PATH_SEPARATOR, $phpProperties[INI_SCANDIR])));
}
$iniFileName = '98-ddtrace.ini';
// Search for pre-existing files with extension = ddtrace.so to avoid conflicts
// See issue https://github.com/DataDog/dd-trace-php/issues/1833
if (is_dir($phpProperties[INI_SCANDIR])) {
foreach (scandir($phpProperties[INI_SCANDIR]) as $ini) {
$path = "{$phpProperties[INI_SCANDIR]}/$ini";
if (is_file($path)) {
// match /path/to/ddtrace.so, plain extension = ddtrace or future extensions like ddtrace.dll
if (preg_match("(^\s*extension\s*=\s*(\S*ddtrace)\b)m", file_get_contents($path), $res)) {
if (basename($res[1]) == "ddtrace") {
$iniFileName = $ini;
}
}
}
}
}
$iniFilePaths = [$phpProperties[INI_SCANDIR] . '/' . $iniFileName];
if (strpos($phpProperties[INI_SCANDIR], '/cli/conf.d') !== false) {
/* debian based distros have INI folders split by SAPI, in a predefined way:
* - <...>/cli/conf.d <-- we know this from php -i
* - <...>/apache2/conf.d <-- we derive this from relative path
* - <...>/fpm/conf.d <-- we derive this from relative path
*/
$apacheConfd = str_replace('/cli/conf.d', '/apache2/conf.d', $phpProperties[INI_SCANDIR]);
if (is_dir($apacheConfd)) {
$iniFilePaths[] = "$apacheConfd/$iniFileName";
}
}
} else {
$iniFileName = $phpProperties[INI_MAIN];
$iniFilePaths = [$iniFileName];
}
return $iniFilePaths;
}
/**
* Copies an extension's file to a destination using copy+rename to avoid segfault if the file is loaded by php.
*
* @param string $source
* @param string $destination
* @return void
*/
function safe_copy_extension($source, $destination)
{
/* Move - rename() - instead of copy() since copying does a fopen() and copies to the stream itself, causing a
* segfault in the PHP process that is running and had loaded the old shared object file.
*/
if (IS_WINDOWS && file_exists($destination)) {
// We have to blackhole it in tempdir because it is likely currently loaded and may not be replaced in place.
rename($destination, getenv("TEMP") . "\\" . time() . "-" . basename($destination));
}
$destinationDir = dirname($destination);
if (!file_exists($destinationDir)) {
execute_or_exit(
"Cannot create directory '$destinationDir'",
"mkdir " . (IS_WINDOWS ? "" : "-p ") . escapeshellarg($destinationDir)
);
}
$tmpName = $destination . '.tmp';
copy($source, $tmpName);
rename($tmpName, $destination);
echo "Copied '$source' to '$destination'\n";
}
function uninstall($options)
{
$selectedBinaries = require_binaries_or_exit($options);
foreach ($selectedBinaries as $command => $fullPath) {
$binaryForLog = ($command === $fullPath) ? $fullPath : "$command ($fullPath)";
echo "Uninstalling from binary: $binaryForLog\n";
$phpProperties = ini_values($fullPath);
$extensionDir = isset($options[OPT_EXTENSION_DIR]) ? $options[OPT_EXTENSION_DIR] : $phpProperties[EXTENSION_DIR];
$extensionDestinations = [
$extensionDir . '/' . EXTENSION_PREFIX . 'ddtrace.' . EXTENSION_SUFFIX,
$extensionDir . '/' . EXTENSION_PREFIX . 'datadog-profiling.' . EXTENSION_SUFFIX,
$extensionDir . '/' . EXTENSION_PREFIX . 'ddappsec.' . EXTENSION_SUFFIX,
];
$iniFileName = '98-ddtrace.ini';
if (isset($phpProperties[INI_SCANDIR])) {
$iniFilePaths = [$phpProperties[INI_SCANDIR] . '/' . $iniFileName];
if (strpos('/cli/conf.d', $phpProperties[INI_SCANDIR]) >= 0) {
/* debian based distros have INI folders split by SAPI, in a predefined way:
* - <...>/cli/conf.d <-- we know this from php -i
* - <...>/apache2/conf.d <-- we derive this from relative path
* - <...>/fpm/conf.d <-- we derive this from relative path
*/
$apacheConfd = str_replace('/cli/conf.d', '/apache2/conf.d', $phpProperties[INI_SCANDIR]);
if (is_dir($apacheConfd)) {
$iniFilePaths[] = "$apacheConfd/$iniFileName";
}
}
} else {
if (!isset($phpProperties[INI_MAIN])) {
print_error_and_exit(
"It is not possible to perform uninstallation on this "
. "system because there is no scan directory and no "
. "configuration file loaded."
);
}
$iniFilePaths = [$phpProperties[INI_MAIN]];
}
/* Actual uninstall
* 1) comment out extension=ddtrace.so
* 2) remove ddtrace.so
*/