-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathWADF.php
2787 lines (2493 loc) · 95.4 KB
/
WADF.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
/*
Web Application Deployment Framework
(c)2006-2021 Tim Jackson ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of version 3 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'System.php';
/**
* Main WADF class
*/
class Tools_WADF {
const SWVERSION = '@package_version@';
const VCREFTYPE_REV = 'rev';
const VCREFTYPE_TAG = 'tag';
const VCREFTYPE_BRANCH = 'branch';
const VCREFTYPE_TRUNK = 'trunk';
const VCREFTYPE_UNKNOWN = 'unknown';
const OUTPUT_SILENT = 0;
const OUTPUT_NORMAL = 50;
const OUTPUT_VERBOSE = 70;
const OUTPUT_DEBUG = 100;
const DEBUG_ERROR = 10;
const DEBUG_WARNING = 20;
const DEBUG_GENERAL = 40;
const DEBUG_INFORMATION = 60;
const DEBUG_VERBOSE = 80;
protected $_debug = self::OUTPUT_NORMAL;
const DEPENDENCY_TYPE_PEAR = 'PEAR';
// the app reference
public $appref;
// Macro definitions
// Array of Tools_WADF_MacroDef objects
protected $_macro_defs;
// resolved macro values
protected $_macro_values = array();
// generic class options
protected $_options = array(
'master_config' => '@cfg_dir@/Tools_WADF/wadf.conf',
);
// macros which we don't manage to resolve during deployment
protected $_unresolved_macros = array();
/**
* Macros which have "specific" versions based on enumerated entities
* (vhosts, databases) and which fall back to a more generic version if
* the more specific version does not exist
*/
protected $_macro_fallbacks = array(
'vhost(\d+)_name' => 'vhost_name',
'vhost(\d+)_interface' => 'vhost_interface',
'vhost(\d+)_config_template' => 'vhost_config_template',
'vhost(\d+)_config_prepend' => 'vhost_config_prepend',
'vhost(\d+)_config_append' => 'vhost_config_append',
'db(\d+)_type' => 'db_type',
'db(\d+)_name' => 'db_name',
'db(\d+)_host' => 'db_host',
'db(\d+)_user' => 'db_user',
'db(\d+)_user_host' => 'db_user_host',
'db(\d+)_pass' => 'db_pass',
'db(\d+)_schema' => 'db_schema',
'db(\d+)_deploy' => 'db_deploy',
'db(\d+)_deploy_user' => 'db_deploy_user',
'db(\d+)_deploy_pass' => 'db_deploy_pass'
);
/**
* @var Tools_WADF_VCDriver_Interface Version control driver in use
*/
protected $_vc = null;
/**
* Macros that were passed from the command line. Only used for writing
* instance files.
*/
private $_cmdline_macros = array();
public static $vc_drivers = null;
public function __construct($appref, $options=null, $cmdline_macros=null, $initial_output_level=self::OUTPUT_NORMAL)
{
$this->setDebugLevel($initial_output_level);
// Strip trailing slash from appref, if present
if (substr($appref, -1, 1) == '/') {
$appref = substr($appref, 0, strlen($appref)-1);
}
$valid_options = array('master_config');
if (is_array($options)) {
foreach ($options as $option => $value) {
if (in_array($option, $valid_options)) {
$this->_options[$option] = $value;
} else {
throw new Exception("Invalid config option '$option' passed to constructor");
}
}
}
$this->_setInternalMacros();
// set default options
$this->_appendMacroDefs($this->_options);
// set appref
$this->appref = $appref;
$options['appref'] = $appref;
// set user-supplied options
$this->_appendMacroDefs($options);
if (!is_array($cmdline_macros)) {
$cmdline_macros = array();
} else {
$this->_cmdline_macros = $cmdline_macros;
}
$this->processConfigs($cmdline_macros);
// Process macros
$this->resolveAllMacros();
$this->_setPEARMacros();
// Load version control plugin
$vc_type = strtolower($this->resolveMacro('vc_type'));
$vc_class = self::loadVCDriver($vc_type);
if (isset($vc_class)) {
$this->_vc = new $vc_class($this);
}
}
/**
* Load a version control driver for the specified type.
*
* The type is essentially the vc name but lowercased.
*
* @throws Exception If not driver found for the specified type
* @return string|null Class name for the version control driver or null if the type is undefined
*/
public static function loadVCDriver($vc_type)
{
if ($vc_type == 'none' || $vc_type == '@vc_type@') {
return null;
}
$drivers = self::getAllVCDrivers();
foreach ($drivers as $driver => $class) {
if (strtolower($driver) == strtolower($vc_type)) {
return $class;
}
}
throw new Exception("Version control plugin '$vc_type' is not supported");
}
/**
* Get an array of all available version control drivers.
*
* For each driver the array contains the driver name, the class name and
* path to the driver file.
*
* @return array
*/
public static function getAllVCDrivers()
{
if (!isset(self::$vc_drivers)) {
self::$vc_drivers = array();
$driver_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'WADF' . DIRECTORY_SEPARATOR . 'VCDriver';
$files = scandir($driver_path);
foreach ($files as $file) {
if (!in_array($file, array('.', '..', 'Interface.php')) && preg_match('@^(.*)\.php$@', $file, $matches)) {
$driver = $matches[1];
require_once $driver_path . DIRECTORY_SEPARATOR . $file; //require all as it's needed by _getFilesToIgnore()
self::$vc_drivers[$driver] = 'Tools_WADF_VCDriver_' . $driver;
}
}
}
return self::$vc_drivers;
}
public static function getFilesToIgnore()
{
$ignore = array('.', '..');
foreach (self::getAllVCDrivers() as $driver => $class) {
$ignore = array_merge($ignore, call_user_func(array($class, "getVCFilesToIgnore")));
}
return $ignore;
}
protected function _setInternalMacros()
{
$hostname = getenv('HOSTNAME');
if (!empty($hostname)) {
$macros['hostname'] = $hostname;
} else {
// TODO there is presumably a better way of doing this
$macros['hostname'] = gethostbyaddr('127.0.0.1');
}
$macros['cwd'] = getcwd();
$user_env_vars = array('USER', 'USERNAME', 'LOGNAME');
foreach ($user_env_vars as $var) {
if (!isset($macros['user'])) {
$user = getenv($var);
if (!empty($user)) {
$macros['user'] = $user;
}
}
}
if (!isset($macros['user'])) {
if (function_exists('posix_getuid')) {
$details = posix_getpwuid(posix_getuid());
$macros['user'] = $details['name'];
} else {
$macros['user'] = 'UNKNOWN';
}
}
$home = getenv('HOME');
if (!empty($home)) {
$macros['home'] = $home;
}
$this->_appendMacroDefs($macros);
}
/**
* Perform a deployment
*
* @param string $revtype Revision type - branch, trunk, tag
* @param string $rev_translated The revision control version. For branches this is the branch name, for tags the tag name.
* @param string $raw_rev Raw version control revision, if appropriate (not for revtype=tag). Can be HEAD.
* @param bool $db_deploy Whether or not to deploy databases to go with the application
* @return bool Whether deployment succeeded
*/
public function deploy($revtype, $rev_translated, $raw_rev=null, $db_deploy=false)
{
// TODO: check if there is already a deployed instance of the app!
$dir = $this->resolveMacro('deploy_path');
$this->checkout($dir, $revtype, $rev_translated, $raw_rev);
// The local config might be stored in the checkout, so check the local
// config again
$this->processLocalConfig();
// Get list of macros from files we just checked out, and force-resolve
// any with fallbacks. This is so that they get in the list of resolved
// macros and the user will then correctly be prompted for any values
// required in checkOptionsRequiringInput
$this->resolveMacrosWithFallbacksInDir($dir, $db_deploy);
// Check for any config options that require user input
if (!$this->checkOptionsRequiringInput()) {
return false;
}
$this->deployDependencies($dir);
$this->processTemplatesInDir($dir);
// TODO: handled unresolved macros? or just let UI do it?
if ($db_deploy) {
$this->deployDatabase();
}
$this->deployVhost();
$this->deployDNS();
$this->runKickstart($db_deploy);
$this->deployScheduledJobs();
$this->postDeploy();
$this->cleanupFiles();
$this->restartWebserver();
return true;
}
public function getUnresolvedMacros()
{
return $this->_unresolved_macros;
}
/**
* Remove a deployment
*
* @param bool $remove_db Whether or not to remove databases that are part of the deployment
* @return void
*/
public function undeploy($remove_db=false)
{
$dir = $this->resolveMacro('deploy_path');
if ($remove_db) {
$this->undeployDatabase();
}
$this->undeployScheduledJobs();
$this->undeployDNS();
$this->undeployVhost();
$this->undeployDependencies($dir);
$this->restartWebserver();
$this->_debugOutput("Removing directory $dir...", self::DEBUG_GENERAL);
$this->_rmDir($dir);
return true;
}
public function enumerateMultipleEntities()
{
$dir = $this->resolveMacro('deploy_path');
$macros_in_templates = $this->extractMacrosFromDir($dir);
// we need to enumerate the db and vhost numbers
$in_use = array();
foreach ($macros_in_templates as $macro) {
if (preg_match('/^(db|vhost)(\d+)_/', $macro, $matches)) {
// array like
// in_use = array (
// db => array (1=>true, 2=>true, 3=>true)
// vhost => array (1=>true, 2=>true)
$in_use[$matches[1]][$matches[2]] = true;
}
}
// now turn the array into db => array(1,2,3) etc.
foreach ($in_use as $type => $list_of_valid) {
$in_use[$type] = array_keys($list_of_valid);
}
return $in_use;
}
/**
* Deploy database(s) for the application
*
* @return void
*/
public function deployDatabase()
{
$in_use = $this->enumerateMultipleEntities();
$dir = $this->resolveMacro('deploy_path');
// deploy database
if (isset($in_use['db'])) {
if (!function_exists('mysqli_connect')) {
throw new Exception ("You need to install the mysql extension for PHP");
}
foreach ($in_use['db'] as $num) {
$host = $this->resolveMacro("db${num}_host");
$user = $this->resolveMacro("db${num}_user");
$pass = $this->resolveMacro("db${num}_pass");
$name = $this->resolveMacro("db${num}_name");
$type = $this->resolveMacro("db${num}_type");
$schema = $this->resolveMacro("db${num}_schema");
if ($type != 'mysql') {
throw new Exception("Unsupported database type '$type' when deploying database db$num");
}
$deploy_options = $this->_getDatabaseDeployOptions($num);
// Check that key database configuration options are non-empty
foreach (array('host','user','name','type') as $var_to_check) {
$name_of_option = 'db' . $num . '_' . $var_to_check;
if (empty($$var_to_check)) {
throw new Exception("The database configuration option $name_of_option is empty");
}
}
$this->_debugOutput("Setting up database $name on host $host...", self::DEBUG_GENERAL);
// FIXME quote strings!
$db_deploy_user = $this->resolveMacro("db${num}_deploy_user");
$db_deploy_pass = $this->resolveMacro("db${num}_deploy_pass");
$db = @mysqli_connect($host, $db_deploy_user, $db_deploy_pass);
if (!$db) {
throw new Exception("Could not connect to database (username=$db_deploy_user, password=$db_deploy_pass): ".mysqli_error($db));
}
if (in_array('create', $deploy_options)) {
mysqli_query($db, "CREATE DATABASE IF NOT EXISTS $name");
}
if (in_array('grant', $deploy_options)) {
$user_host = $this->resolveMacro("db${num}_user_host");
if ($db->server_version >= 80000) {
$this->_debugOutput("\tCreating user '{$user}'@'{$user_host}'");
mysqli_query($db, "CREATE USER IF NOT EXISTS '{$user}'@'{$user_host}' IDENTIFIED BY '{$pass}'");
mysqli_query($db, "GRANT ALL on {$name}.* to '{$user}'@'{$user_host}'");
} else {
mysqli_query($db, "GRANT ALL on {$name}.* to '{$user}'@'{$user_host}' IDENTIFIED BY '{$pass}'");
}
}
if (in_array('schema', $deploy_options)) {
// Remove existing database tables
$this->_removeDatabaseTables($name, $db);
// Deploy schema file if necessary
if (!empty($schema)) {
$schema_path = "$dir/$schema";
if (file_exists($schema_path)) {
$this->_debugOutput("\tDeploying new schema for database $name as user $db_deploy_user...", self::DEBUG_GENERAL);
$cmd = "mysql $name -h $host -u $db_deploy_user ".(($db_deploy_pass != null) ? "-p$db_deploy_pass" : '')." < $dir/$schema 2>&1";
mysqli_close($db);
exec($cmd, $out, $ret);
if ($ret != 0) {
throw new Exception('Error when deploying schema: ' . implode("\n", $out));
}
} else {
$this->_debugOutput("No schema file found to deploy at $schema_path", self::DEBUG_GENERAL);
}
}
}
}
} else {
$this->_debugOutput("No database to deploy", self::DEBUG_GENERAL);
}
return true;
}
public function undeployDatabase()
{
$in_use = $this->enumerateMultipleEntities();
if (isset($in_use['db'])) {
foreach ($in_use['db'] as $num) {
$host = $this->resolveMacro("db${num}_host");
$name = $this->resolveMacro("db${num}_name");
$db_deploy_user = $this->resolveMacro("db${num}_deploy_user");
$db_deploy_pass = $this->resolveMacro("db${num}_deploy_pass");
$deploy_options = $this->_getDatabaseDeployOptions($num);
$db = @mysqli_connect($host, $db_deploy_user, $db_deploy_pass);
if (!$db) {
throw new Exception("Could not connect to database (username=$db_deploy_user, password=$db_deploy_pass): " . mysqli_error($db));
}
if (in_array('grant', $deploy_options)) {
mysqli_query($db, "REVOKE ALL ON $name.*");
}
if (in_array('create', $deploy_options)) {
$this->_debugOutput("Dropping database $name...", self::DEBUG_GENERAL);
$res = mysqli_query($db, "DROP DATABASE $name");
if ($res === false) {
$this->_debugOutput("Could not drop database $name", self::DEBUG_ERROR);
}
} else if (in_array('schema', $deploy_options)) {
$this->_removeDatabaseTables($name, $db);
}
mysqli_close($db);
// TODO remove DB users? But what if other site uses them?
}
}
return true;
}
/**
*
* @param $num The database number to get the options for
* @return array|false
*/
protected function _getDatabaseDeployOptions($num)
{
$deploy = $this->resolveMacro("db${num}_deploy");
$deploy_options = array();
if (!empty($deploy) && $deploy != "@db${num}_deploy@") {
$valid_deploy_options = array('create','grant','schema');
$deploy_options = explode(',', $deploy);
foreach ($deploy_options as $i => $option) {
$option = trim($option);
if (in_array($option, $valid_deploy_options)) {
$deploy_options[$i] = $option;
} else {
throw new Exception("Invalid database deployment option in db${num}_deploy: $option");
}
}
}
return $deploy_options;
}
protected function _removeDatabaseTables($dbname, $dbconn)
{
$this->_debugOutput("\tDeleting existing tables in database $dbname...", self::DEBUG_GENERAL);
$res = mysqli_select_db($dbconn, $dbname);
if ($res === false) {
throw new Exception("Could not select database $dbname: " . mysqli_error($dbconn));
}
mysqli_query($dbconn, 'SET FOREIGN_KEY_CHECKS=0');
// MySQL 5.0+
$res = mysqli_query($dbconn, "SELECT table_name,table_type FROM information_schema.tables WHERE table_schema='$dbname' AND table_type IN ('VIEW', 'BASE TABLE') ORDER BY table_name");
if ($res === false) {
// MySQL 3.x/4.x
$res = mysqli_query($dbconn, 'SHOW TABLES');
if ($res === false) {
throw new Exception("Could not discover tables in database $dbname - SHOW TABLES failed");
} else {
while ($table = mysqli_fetch_row($res)) {
$this->_debugOutput("\t\tDropping table " . $table[0], self::DEBUG_INFORMATION);
$res2 = mysqli_query($dbconn, "DROP TABLE `" . $table[0] . "`");
if ($res2 === false) {
throw new Exception("Error dropping table $dbname.$table[0] :" . mysqli_error($dbconn));
}
}
}
} else {
while ($table = mysqli_fetch_row($res)) {
if ($table['1'] == 'VIEW') {
$this->_debugOutput("\t\tDropping view " . $table[0], self::DEBUG_INFORMATION);
$res2 = mysqli_query($dbconn, "DROP VIEW `" . $table[0] . "`");
if ($res2 === false) {
throw new Exception("Error dropping view $dbname.$table[0] :" . mysqli_error($dbconn));
}
} else {
$this->_debugOutput("\t\tDropping table " . $table[0], self::DEBUG_INFORMATION);
$res2 = mysqli_query($dbconn, "DROP TABLE `" . $table[0] . "`");
if ($res2 === false) {
throw new Exception("Error dropping table $dbname.$table[0] :" . mysqli_error($dbconn));
}
}
}
}
return true;
}
// if mode=undeploy, then undeploy(!)
public function deployDNS($mode='deploy')
{
$deploy_type = $this->resolveMacro('deploy_dns');
// NB that the string "none" is transparently converted to the empty
// string by the PHP INI file parser
if ($deploy_type == '') {
return;
}
$in_use = $this->enumerateMultipleEntities();
if (isset($in_use['vhost'])) {
foreach ($in_use['vhost'] as $vhost_id) {
$hosts[] = $this->resolveMacro("vhost${vhost_id}_name");
}
// TODO other ways of deploying DNS?
switch ($deploy_type) {
case 'hosts':
if ($mode == 'deploy') {
$this->addHostsToHostsFile($hosts);
} else {
$this->removeHostsFromHostsFile($hosts);
}
break;
default:
throw new Exception("Unknown DNS deployment method '$deploy_type'");
break;
}
}
return true;
}
public function undeployDNS()
{
$this->deployDNS('undeploy');
}
public function deployScheduledJobs()
{
$crontab_file = $this->resolveMacro('crontab');
if (file_exists($crontab_file)) {
$this->_debugOutput("Deploying scheduled jobs from $crontab_file...", self::DEBUG_GENERAL);
$instance = $this->resolveMacro('instance');
$crontab_entries = trim(file_get_contents($crontab_file));
exec('crontab -l 2>&1', $current_crontab, $ret);
// The special markers we put at the start and end of the crontab
$wadf_deploy_begin = "# wadf-deployment-begin: $instance - DO NOT REMOVE THIS";
$wadf_deploy_end = "# wadf-deployment-end: $instance - DO NOT REMOVE THIS";
// The new entries we want to add
$crontab_entries_new = "$wadf_deploy_begin\n$crontab_entries\n$wadf_deploy_end";
if ($ret == 1 || (count($current_crontab) == 1 && preg_match('/^no crontab for/i', $current_crontab[0]))) {
// No current crontab
$this->_debugOutput("\tDeploying new crontab", self::DEBUG_GENERAL);
$current_crontab = '';
$new_crontab = $crontab_entries_new . "\n";
} else {
$current_crontab = implode("\n", $current_crontab) . "\n";
$regex = "/# wadf-deployment-begin: $instance.+# wadf-deployment-end: $instance - DO NOT REMOVE THIS/ms";
if (preg_match($regex, $current_crontab)) {
$this->_debugOutput("\tFound $instance in existing crontab, replacing", self::DEBUG_GENERAL);
$new_crontab = preg_replace($regex, $crontab_entries_new, $current_crontab);
} else {
$this->_debugOutput("\tCould not find $instance in existing crontab", self::DEBUG_GENERAL);
$new_crontab = $current_crontab . "\n" . $crontab_entries_new . "\n";
}
}
$tmp_file = tempnam('/tmp', 'wadfcron');
$fp = fopen($tmp_file, 'w');
fputs($fp, $new_crontab);
fclose($fp);
exec("crontab $tmp_file");
unlink($tmp_file);
}
return true;
}
public function undeployScheduledJobs()
{
$instance = $this->resolveMacro('instance');
exec('crontab -l 2>&1', $current_crontab, $ret);
$current_crontab = implode("\n", $current_crontab);
$regex = "/# wadf-deployment-begin: $instance.+# wadf-deployment-end: $instance - DO NOT REMOVE THIS/ms";
if (preg_match($regex, $current_crontab)) {
$this->_debugOutput("Removing scheduled jobs for $instance in existing crontab", self::DEBUG_GENERAL);
$new_crontab = preg_replace($regex, '', $current_crontab);
$tmp_file = tempnam('/tmp', 'wadfcron');
$fp = fopen($tmp_file, 'w');
fputs($fp, $new_crontab);
fclose($fp);
exec("crontab $tmp_file");
unlink($tmp_file);
} else {
$this->_debugOutput("No scheduled jobs to remove for $instance", self::DEBUG_GENERAL);
}
}
public function addHostsToHostsFile($hosts)
{
$hosts_file = $this->resolveMacro('deploy_dns_hosts_file');
$deploy_ip = $this->resolveMacro('deploy_dns_hosts_ip');
$existing_hostnames = array();
$file_contents = file($hosts_file);
$line_num = 0;
$localhost_line_num = 0;
$base_host = ''; //the first host found
foreach ($file_contents as $line) {
if (substr($line, 0, strlen($deploy_ip)) == $deploy_ip) {
if (preg_match_all('/[\t\s]+(\S+)/', $line, $matches)) {
foreach ($matches[1] as $host) {
$existing_hostnames[] = trim($host);
if (!$base_host) $base_host = trim($host);
}
}
$localhost_line_num = $line_num;
}
$line_num++;
}
foreach ($hosts as $host) {
$hosts_file_format = $this->resolveMacro('deploy_dns_hosts_file_format');
if (!$hosts_file_format || $hosts_file_format == '@deploy_dns_hosts_file_format@') {
$hosts_file_format = 1;
}
if (!in_array($host, $existing_hostnames)) {
switch ($hosts_file_format) {
case 1:
array_splice($file_contents, $localhost_line_num + 1, 0, "$deploy_ip\t$base_host\t$host\n");
break;
case 2:
array_splice($file_contents, $localhost_line_num + 1, 0, "$deploy_ip\t$host\n");
break;
default:
throw new Exception("Unknown value '$hosts_file_format' for deploy_dns_hosts_file_format option");
}
}
}
$fp = @fopen($hosts_file, 'w');
if (is_resource($fp)) {
fputs($fp, implode('', $file_contents));
fclose($fp);
} else {
$this->_debugOutput("WARNING: Could not update list of local hostnames in hosts file '$hosts_file'. Check permissions.", self::DEBUG_WARNING);
}
}
protected function removeHostsFromHostsFile($hosts)
{
$this->_debugOutput("Removing hosts from DNS hosts file", self::DEBUG_GENERAL);
$hosts_file = $this->resolveMacro('deploy_dns_hosts_file');
$old_file_contents = file($hosts_file);
$new_file_contents = array();
foreach ($old_file_contents as $line) {
if (preg_match('/\s(\S+)$/', $line, $matches)) {
if (!in_array($matches[1], $hosts)) {
$new_file_contents[] = $line;
}
}
}
$new_file_contents = implode('', $new_file_contents);
$fp = @fopen($hosts_file, 'w');
if (is_resource($fp)) {
fputs($fp, $new_file_contents);
fclose($fp);
} else {
$this->_debugOutput("WARNING: Could not update list of local hostnames in hosts file '$hosts_file'. Check permissions.", self::DEBUG_WARNING);
}
}
public function deployVhost($dir=null)
{
if ($dir === null) {
$dir = $this->resolveMacro('deploy_path');
}
// deploy vhost config
$source_file = $dir.'/'.$this->resolveMacro('vhost_config_template');
if (!file_exists($source_file)) {
$this->_debugOutput("No webserver configuration to deploy (looked for $source_file)", self::DEBUG_GENERAL);
return;
}
$this->_debugOutput("Deploying webserver configuration...", self::DEBUG_GENERAL);
$vhost_config_path = $this->resolveMacro('vhost_config_path');
if (!file_exists($vhost_config_path)) {
$this->_debugOutput("Creating webserver config file path $vhost_config_path...", self::DEBUG_GENERAL);
System::mkdir(array('-p', $vhost_config_path));
}
$dest_file = $vhost_config_path . '/' . $this->resolveMacro('instance') . '.conf';
$this->_debugOutput("Copying $source_file to $dest_file", self::DEBUG_VERBOSE);
$config = file_get_contents($source_file);
// If we are using mod_php, insert the PHP config options
if ($this->resolveMacro('php_type') == 'mod_php') {
$php_ini = $dir . '/' . $this->resolveMacro('php_config_location');
$directives = $this->_convertPhpIniToApacheModPhp($php_ini);
if (count($directives) > 0) {
// Stick the PHP directives at the end of the vhost
$php_directives = implode("\n\t", $directives);
$config = str_replace("</VirtualHost>", "\n\t# PHP directives processed from $php_ini\n\t" . $php_directives . "\n" . '</VirtualHost>', $config);
}
// Process local PHP override ini file, if it exists
$php_ini_local = trim($this->resolveMacro('php_config_location_extra'));
if ($php_ini_local != '@php_config_location_extra@' && !empty($php_ini_local)) {
$directives_local = $this->_convertPhpIniToApacheModPhp($php_ini_local);
if (count($directives_local) > 0) {
$php_directives = implode("\n\t", $directives_local);
$config = str_replace("</VirtualHost>", "\n\t# PHP directives processed from $php_ini_local\n\t" . $php_directives . "\n" . '</VirtualHost>', $config);
}
}
} else {
$this->_deployPHPConfig($dir);
}
$deploy_version = $this->resolveMacro('deploy_version');
if ($deploy_version == '@deploy_version@') $deploy_version = 'unknown';
$config = "# wadf-working-copy: $dir\n# wadf-deploy-version: $deploy_version\n$config";
// Append/prepend virtual host configs
$prepend = $this->resolveMacro("vhost_config_prepend");
if (!empty($prepend) && $prepend != "vhost_config_prepend") {
$prepend = str_replace('\n', "\n", $prepend);
$prepend = str_replace('\t', "\t", $prepend);
$config = preg_replace('/(<VirtualHost[^>]+>)/', '\1' . "\n$prepend", $config);
}
$append = $this->resolveMacro("vhost_config_append");
if (!empty($append) && $append != "vhost_config_append") {
$append = str_replace('\n', "\n", $append);
$append = str_replace('\t', "\t", $append);
$config = str_replace('</VirtualHost>', $append . "\n" . '</VirtualHost>', $config);
}
$fp = fopen($dest_file, 'w');
if (is_resource($fp)) {
fputs($fp, $config);
fclose($fp);
} else {
throw new Exception("Could not open vhost config destination file '$dest_file'");
}
return true;
}
public function undeployVhost($dir=null)
{
if ($dir === null) {
$dir = $this->resolveMacro('deploy_path');
}
$vhost_config = $this->resolveMacro('vhost_config_path') . '/' . $this->resolveMacro('instance').'.conf';
$this->_debugOutput("Removing vhost config $vhost_config", self::DEBUG_VERBOSE);
@unlink($vhost_config);
$php_type = $this->resolveMacro('php_type');
if (preg_match('/^(cgi|fpm):(.+)$/', $php_type, $matches)) {
$php_ini_dest = trim($matches[1]);
if (substr($php_type, 0, 3) == 'fpm' && $php_ini_dest == 'local') {
$home = getenv('HOME');
$php_ini_dest = $home .'/.wadf/php-fpm-intermediate.d/'. $this->resolveMacro('instance') .'.conf';
}
@unlink($php_ini_dest);
}
}
public function postDeploy()
{
$cmd = $this->resolveMacro('post_deploy_script');
if ($cmd != '@post_deploy_script@' && !empty($cmd)) {
// Set environment variable to show verbosity level
if ($this->_debug >= self::DEBUG_INFORMATION) {
putenv('DEPLOY_VERBOSITY=1');
} else {
putenv('DEPLOY_VERBOSITY=0');
}
$this->_debugOutput("Running post-deploy script \"$cmd...\"", self::DEBUG_GENERAL);
$this->_debugOutput('---------- OUTPUT BELOW IS FROM POST DEPLOY SCRIPT, NOT WADF ----------', self::DEBUG_GENERAL);
passthru($cmd);
$this->_debugOutput('------------------ END OF POST DEPLOY SCRIPT OUTPUT -------------------', self::DEBUG_GENERAL);
}
}
public function cleanupFiles()
{
$files = $this->resolveMacro('post_deploy_cleanup_files');
if (!empty($files) && $files != '@post_deploy_cleanup_files@') {
$deploy_path = $this->resolveMacro('deploy_path');
$this->_debugOutput("Cleaning up special files...", self::DEBUG_INFORMATION);
$this->_debugOutput("Files to clean up are $files", self::DEBUG_VERBOSE);
foreach(explode(' ', $files) as $file) {
$force_remove = false;
$file = trim($file);
if (strlen($file) > 0) {
if (substr($file, 0, 1) == '+') { // force removal even if template doesn't exist
$file = substr($file, 1);
$force_remove = true;
}
chdir($deploy_path);
if (file_exists($file)) {
if ($force_remove || file_exists("$file.template")) {
$this->_debugOutput(" Removing $file", self::DEBUG_INFORMATION);
unlink($file);
}
}
}
}
}
}
public function restartWebserver()
{
$restart_cmd = $this->resolveMacro('webserver_restart_cmd');
if ($restart_cmd != '@webserver_restart_cmd@' && !empty($restart_cmd)) {
$this->_debugOutput("Restarting webserver...", self::DEBUG_GENERAL);
passthru($restart_cmd);
}
}
/**
* @param string $file Filename to read. If file does not exist, no error will be thrown.
* @return array Array of Apache mod_php config rules
*/
protected function _convertPhpIniToApacheModPhp($file)
{
$directives_out = array();
if (file_exists($file)) {
$this->_debugOutput("\tProcessing PHP config file $file...", self::DEBUG_INFORMATION);
$php_ini_directives = file($file);
$php_ini_all = ini_get_all();
if (!isset($php_ini_all['engine'])) { // for some reason this isn't defined in at least PHP 5.2.12
$php_ini_all['engine'] = array('access' => INI_SYSTEM);
}
$directives_out = array();
foreach ($php_ini_directives as $directive) {
$directive = trim($directive);
if (empty($directive)) continue;
if (preg_match('/^\s*;(.+)$/', $directive, $matches)) {
// Comment; convert php.ini-style semicolons to hash signs
$directives_out[] = '#' . $matches[1];
} else if (preg_match('/^([a-z0-9_\.]+)\s*=\s*(.+)$/', $directive, $matches)) {
$directive_name = strtolower(trim($matches[1]));
$directive_value = trim($matches[2]);
if (isset($php_ini_all[$directive_name])) {
$directive_type = 'value'; // flag or value
// See if it looks like a flag or a value
if (in_array(strtolower($directive_value), array('0','1','on','off'))) {
$directive_type = 'flag';
} else {
if (strpos($directive_value, ' ') && substr($directive_value, 0, 1) != '"') {
$directive_value = '"' . $directive_value . '"';
}
}
if ($php_ini_all[$directive_name]['access'] & INI_ALL & INI_PERDIR) {
$prefix = 'php_';
} else {
$prefix = 'php_admin_';
}
$directives_out[] = $prefix . $directive_type . " $directive_name $directive_value";
} else {
$directives_out[] = "# WADF: ignored unknown configuration option: $directive";
$this->_debugOutput("WARNING: Unknown PHP configuration option '$directive_name' in $file", self::DEBUG_WARNING);
}
} else {
$this->_debugOutput("WARNING: Could not parse PHP ini config line from $file:\n\t$directive", self::DEBUG_WARNING);
}
}
}
return $directives_out;
}
// Not needed for mod_php; it is done in deployVhost();
protected function _deployPHPConfig($dir)
{
$php_type = $this->resolveMacro('php_type');
if ($php_type == 'mod_php') {
return; // do nothing
} else if (preg_match('/^cgi:(.+)$/', $php_type, $matches)) {
$php_ini_dest = trim($matches[1]);
$php_ini = $this->resolveMacro('php_config_location');
$php_ini_source = $dir . '/' . $php_ini;
if (file_exists($php_ini_source)) {
$this->_debugOutput("Deploying PHP config file to $php_ini_dest...", self::DEBUG_GENERAL);
$source = file_get_contents($php_ini_source);
$php_ini_local = trim($this->resolveMacro('php_config_location_extra'));
if ($php_ini_local != '@php_config_location_extra@' && !empty($php_ini_local)) {
$extras = file_get_contents($php_ini_local);
$source .= "\n; PHP directives processed from $php_ini_local\n" . $extras;
}
$dest_dir = dirname($php_ini_dest);
if (!file_exists($dest_dir)) {
$this->_debugOutput("Creating directory $dest_dir for deployment of PHP config file...", self::DEBUG_GENERAL);
System::mkdir(array('-p', $dest_dir));
}
file_put_contents($php_ini_dest, $source);
}
} else if (preg_match('/^fpm:(.+)$/', $php_type, $matches)) {
$fpm_dest = trim($matches[1]);
if ($fpm_dest == 'local') {
$home = getenv('HOME');
$fpm_dest = $home .'/.wadf/php-fpm-intermediate.d/'. $this->resolveMacro('instance') .'.conf';
}
$php_ini = $this->resolveMacro('php_config_location');
$php_ini_source = $dir . '/' . $php_ini;
if (file_exists($php_ini_source)) {
$this->_debugOutput("Deploying intermediate PHP-FPM config file to $fpm_dest...", self::DEBUG_GENERAL);
$source = file_get_contents($php_ini_source);
$php_ini_local = trim($this->resolveMacro('php_config_location_extra'));
if ($php_ini_local != '@php_config_location_extra@' && !empty($php_ini_local)) {
if (file_exists($php_ini_local)) {
$extras = file_get_contents($php_ini_local);
$source .= "\n; PHP directives processed from $php_ini_local\n" . $extras;
}
}
$dest_dir = dirname($fpm_dest);
if (!file_exists($dest_dir)) {
$this->_debugOutput("Creating directory $dest_dir for deployment of intermediate PHP-FPM config file...", self::DEBUG_GENERAL);
System::mkdir(array('-p', $dest_dir));
}
$fpm_php_config = "; This is an incomplete FPM config which will need additional pool-related parameters adding above this line\n";
$lines = explode(PHP_EOL, $source);
foreach ($lines as $line) {
$line = trim($line);
unset($matches);
if (preg_match('/^([a-z0-9_\.]+)\s*=(.+)/i', $line, $matches)) {
$key = trim($matches[1]);
$value = trim($matches[2]);
if ((strtolower($value) == 'on' || strtolower($value) == 'off')) {
$fpm_php_config .= "php_flag[$key] = $value\n";
} else {
$fpm_php_config .= "php_value[$key] = $value\n";
}
} else if (strlen($line) > 0 && substr($line,0,1) == ';') { // pass through comments
$fpm_php_config .= $line . "\n";
}
}
file_put_contents($fpm_dest, $fpm_php_config);
}
} else {
throw new Exception("Unknown PHP type '$php_type'");
}
return true;
}