-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontroller.php
More file actions
3378 lines (3075 loc) · 134 KB
/
controller.php
File metadata and controls
3378 lines (3075 loc) · 134 KB
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
/**
* @file
* Contains \Drupal\webfact\Controller\WebfactController
*/
#use GuzzleHttp\Exception\ClientException;
#use GuzzleHttp\Exception\RequestException;
#use Monolog\Logger;
#use Monolog\Handler\StreamHandler;
use Docker\Http\DockerClient;
use Docker\Exception\ImageNotFoundException;
#use Docker\Docker;
require 'mesos.php';
/*
* encapsulate the Webfactory stuff into a calls, for easier Drupal7/8 porting
*/
class WebfactController {
protected $client, $hostname, $nid, $id, $did, $markup, $result, $status, $docker;
protected $config, $user, $website, $des, $category;
protected $verbose, $msglevel1, $msglevel2, $msglevel3;
protected $cont_image, $cont_mem, $dserver, $fserver, $loglines, $env_server; // settings
protected $container_api;
protected $is_drupal; // is this a drupal container: enable drupal features
protected $done_per; // status value back from a drupal container when build is finished
protected $docker_start_vol, $docker_ports, $docker_env, $startconfig;
protected $actual_restart, $actual_error, $actual_status, $actual_buildstatus;
protected $webroot, $sitesdir, $sitesdir_host;
public function __construct($user_id_override = FALSE, $nid=0) {
//allow the controller user to be set on creation - needed for api calls
if($user_id_override){
$account = user_load($user_id_override);
}else{
global $user;
$account = $user;
}
$this->markup = '';
$this->verbose = 1;
$this->category = 'none';
$this->docker_ports = array();
$this->fqdn = '';
$this->is_drupal = 1;
$this->done_per = 100;
$this->container_api = variable_get('webfact_container_api', 0); // default is docker API
#watchdog('webfact', 'WebfactController __construct() ' . $this->container_api);
# Load configuration defaults, override in settings.php or on admin/config/webfact
$this->cont_image= variable_get('webfact_cont_image', 'boran/drupal');
//$this->dserver = variable_get('webfact_dserver', 'tcp://mydockerserver.example.ch:2375');
$this->dserver = variable_get('webfact_dserver', 'unix:///var/run/docker.sock');
$this->fserver = variable_get('webfact_fserver', 'webfact.example.ch');
$this->rproxy = variable_get('webfact_rproxy', 'nginx');
$this->loglines = variable_get('webfact_loglines', 300);
$this->restartpolicy = variable_get('webfact_restartpolicy', 'on-failure');
$this->env_server = variable_get('webfact_env_server');
$this->msglevel1 = variable_get('webfact_msglevel1', TRUE); // normal infos
$this->msglevel2 = variable_get('webfact_msglevel2', TRUE); // more
$this->msglevel3 = variable_get('webfact_msglevel3', TRUE); // debug
$this->cont_mem = variable_get('webfact_cont_mem', 0); // default container memory
$this->webroot = variable_get('webfact_www_volume_path', '/var/www/html');
$this->sitesdir = variable_get('webfact_server_sitesdir', '/opt/sites/');
$this->sitesdir_host = variable_get('webfact_server_sitesdir_host', '/opt/sites/');
if (isset($account->name)) {
$this->user= $account->name;
} else {
$this->user= 'anonymous';
}
/*$log = new Logger('name');
$log->pushHandler(new StreamHandler('/tmp/mono.log', Logger::WARNING));
$log->addWarning('Foo');
$log->addError('Bar');*/
$destination = drupal_get_destination();
$this->des = '?destination=' . $destination['destination']; // remember where we were
if ($this->container_api == 0) { // docker API
// define docker connection params
$this->client = new Docker\Http\DockerClient(array(), $this->dserver);
$this->client->setDefaultOption('timeout', variable_get('webfact_api_timeout', 30));
$this->docker = new Docker\Docker($this->client);
}
// api call: load minimal website infos: node, container name
if ($nid>0) {
$this->website=node_load($nid);
if ($this->website!=null) {
$this->id = $this->website->field_hostname['und'][0]['safe_value'];
}
}
}
public function getContainerManager() {
if ($this->container_api == 0) { // docker API
return $this->docker->getContainerManager();
}
}
public function getImageManager() {
return $this->docker->getImageManager();
}
public function helloWorldPage() { // nostalgia: the first function
#dpm('helloWorldPage');
return array('#markup' => '<p>' . t('Hello World') . '</p>');
}
/*
* helper function. hack drupal file_transfer() to set caching headers
* and not call drupal exit.
* https://api.drupal.org/api/drupal/includes%21file.inc/function/file_transfer/7
*/
public function tar_file_transfer($uri, $filename) {
if (ob_get_level()) {
ob_end_clean();
}
drupal_add_http_header('Pragma', 'public');
drupal_add_http_header('Expires', '0');
drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
drupal_add_http_header('Content-Type', 'text/tar');
drupal_add_http_header('Content-Disposition', 'attachment; filename=' . basename($filename) . ';');
drupal_add_http_header('Content-Transfer-Encoding', 'binary');
drupal_add_http_header('Content-Length', filesize($filename));
#drupal_send_headers(); // not needed?
$scheme = file_uri_scheme($uri);
// Transfer file in 1024 byte chunks to save memory usage.
if ($scheme && file_stream_wrapper_valid_scheme($scheme) && $fd = fopen($uri, 'rb')) {
while (!feof($fd)) {
print fread($fd, 1024);
}
fclose($fd);
}
else {
drupal_not_found();
}
}
/*
* make docker date more readable:
* convert "2015-01-21T12:42:36.662998775Z"
* to 2015-01-21 12:42
* todo: correct timezone to local?
*/
public function parseDockerDate ($d) {
#$d="2015-01-21T12:42:36.662998775Z";
preg_match('/(.+:.+):.+/', $d, $matches);
$map= array('T' => ' ');
return strtr($matches[1], $map);
}
/*
* update the "date changed" of a node
*/
protected function touch_node_date() {
if (!$this->nid)
return -1;
$this->website = node_load($this->nid);
$this->website->revision = 1; // history of changes
$this->website->log = "touch node date, by $this->user";
$this->website->changed = time();
node_save($this->website); // Save the updated node
}
/*
* bootstrap navigation on the website/advanced page
*/
private function nav_menu($wpath, $des) {
if (! isset($this->website) ) {
return;
}
if (variable_get('webfact_manage_db',0) == 0) {
$rebuild1_msg = "Stop, delete and recreate " . $this->website->title .", e.g. to get the latest OS/programs in the associated image. Non-persistent data (e.g. DBs are within containers). It may make sense to choose the option 'Delete Drupal data' first to wipe the webroot too first. Are you sure?";
} else {
$rebuild1_msg = "Stop, delete and recreate " . $this->website->title .", e.g. to get the latest OS/programs in the associated image. Non-persistent data will be lost (but DB are persistent). Are you sure?";
}
$rebuild2_msg="Backup the container (docker commit). Then " . $rebuild1_msg;
$rebuild3_msg="For fast development/testing. First wipe all data, then stop, delete and recreate";
$rebuild4_msg = "Rebuild container but maintain non-persistent data. Commit to a docker backup image, stop, delete and recreate from that same image. E.g. rebuild after changing a docker environment setting. Are you sure?";
$docker_logs='';
// drupal specific menus
if ($this->is_drupal==1) { // enable drupal menus
$coappupdate = <<<END
<li class="divider"></li>
<li><a href="$wpath/coappupdate/$this->nid" onclick="return confirm('Backup the container and run webfact_update.sh to update the website?')">Run website update</a></li>
END;
$drupal_logs="<li><a href=$wpath/druplogs/$this->nid>Drupal logs</a></li>";
if ($this->container_api == 0) { // docker API
$createui = "<li><a href=$wpath/createui/$this->nid>Create</a></li>";
$docker_logs="<li><a href=$wpath/logs/$this->nid>Docker logs</a></li>";
} else { //mesos
$docker_logs ='';
$createui = "<li><a href=$wpath/create/$this->nid>Create</a></li>";
}
$deletewww = "<li><a href=$wpath/deletewww/$this->nid onclick='return confirm(\"Delete persistent data from Drupal containers: Webroot and linked Database. There is no going back, are you sure?\")'>Delete Drupal data (www+DB)</a></li>";
} else { // non-drupal container
$drupal_logs= $coappupdate= $coappupdate='';
if ($this->container_api == 0) { // docker API
$docker_logs="<li><a href=$wpath/logs/$this->nid>Docker logs</a></li>";
} else { //mesos
$docker_logs ='';
}
$createui = "<li><a href=$wpath/create/$this->nid>Create</a></li>";
$deletewww = "";
}
$nav1 = <<<END
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="$wpath/advanced/$this->nid">Status</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Manage<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="$wpath/advanced/$this->nid">Status</a></li>
<li><a href="$wpath/stop/$this->nid">Stop</a></li>
<li><a href="$wpath/start/$this->nid">Start</a></li>
<li><a href="$wpath/restart/$this->nid">Restart</a></li>
<li class="divider"></li>
$createui
<li class="divider"></li>
<li><a href="$wpath/deleteui/$this->nid" onclick="return confirm('Choose if there is no persistent data within the container. Are you sure?')">Delete container</a></li>
$deletewww
<li><a href="$wpath/deleteall/$this->nid" onclick="return confirm('Delete everything associated: Container, docker image backups, linked database (if any), webroot volume contents and this meta data. Are you REALLY sure?')">Delete everything: container, data, ..</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Advanced<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="$wpath/inspect/$this->nid">Inspect</a></li>
<li class="divider"></li>
$docker_logs
$drupal_logs
<li class="divider"></li>
<li><a href="$wpath/cocmd/$this->nid">Run command</a></li>
$coappupdate
<li class="divider"></li>
<li><a href="$wpath/rebuild/$this->nid" onclick="return confirm('$rebuild1_msg')">Rebuild container </a></li>
<li><a href="$wpath/rebuild2/$this->nid" onclick="return confirm('$rebuild2_msg')">Rebuild, commit backup image first </a></li>
<li><a href="$wpath/rebuild3/$this->nid" onclick="return confirm('$rebuild3_msg')">Rebuild, wipe data (for test containers) </a></li>
<!-- DockerAPI only
<li class="divider"></li>
<li><a href="$wpath/rebuildmeta/$this->nid" onclick="return confirm('$rebuild4_msg')">Rebuild with persistence</a></li> -->
<li class="divider"></li>
<li><a href="$wpath/corename/$this->nid">Rename container</a></li>
<li class="divider"></li>
<li><a href="$wpath/cocopyfile/$this->nid">Folder download</a></li>
<!-- <li><a href="$wpath/couploadfile/$this->nid">File Upload</a></li> -->
</ul>
</li>
</ul>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Backup/restore<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="$wpath/backup/$this->nid">Backup container now</a></li>
<li><a href="$wpath/backuplist/$this->nid">List backups </a></li>
<li class="divider"></li>
<li><a href="$wpath/backuplistdelete/$this->nid" onclick="return confirm('This will take some time to delete all backups. Continue?')">Remove ALL backup images of $this->id</a></li>
<li class="divider"></li>
<li><a href="$wpath/coexport/$this->nid" onclick="return confirm('Download this container to a tarfile? This will be slow as hundreds of MB are typical. ')">Download container</a></li>
</ul>
</li>
</ul>
END;
## Admin menu
if ( user_access('manage containers')) {
// Load the associated template
$tlink='';
if (isset($this->website->field_template['und'][0]['target_id'])) {
$tid=$this->website->field_template['und'][0]['target_id'];
if (isset($tid)) {
$tlink="<li><a href=/node/$tid/edit$des>Edit template</a></li> ";
}
}
if ($this->container_api == 0) { // docker API
$nav2 = <<<END
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Docker Admin<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="$wpath/containers/$this->nid">Containers</a></li>
<li><a href="$wpath/images/$this->nid">Images</a></li>
<li class="divider"></li>
$tlink
<li><a href="$wpath/processes/$this->nid">Container processes</a></li>
<li><a href="$wpath/kill/$this->nid">Container kill</a></li>
<li><a href="$wpath/impull/$this->nid" onclick="return confirm('Pulling the base image from Dockerhub will affect all future builds using that image. Are you sure you sure?')">Pull latest image</a></li>
<li><a href="$wpath/changes/$this->nid">Container fs changes</a></li>
<li class="divider"></li>
<li><a href="$wpath/proxyrestart/$this->nid$this->des" onclick="return confirm('Restarting nginx will break all sessions, refresh the page manually after a few secs. ')">Restart nginx</a></li>
<li><a href="$wpath/proxy2restart/$this->nid$this->des">Restart nginx-gen</a></li>
<li><a href="$wpath/proxylogs/$this->nid$this->des">Logs nginx</a></li>
<li><a href="$wpath/proxy2logs/$this->nid$this->des">Logs nginx-gen</a></li>
<li><a href="$wpath/proxyconf/$this->nid$this->des">Conf. nginx</a></li>
</ul>
</li>
</ul>
END;
} else { // mesos
$nav2 = <<<END
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Docker Admin<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
$tlink
<li class="divider"></li>
<li><a href="$wpath/version/$this->nid">Marathon version</a></li>
<li><a href="$wpath/mesos/$this->nid">Mesos</a></li>
</ul>
</li>
</ul>
END;
}
} else {
$nav2='';
}
$navend = <<<END
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</nav>
END;
return $nav1 . $nav2 . $navend;
}
protected function getContainerDockerStatus() {
if ($this->container_api == 0) { // docker API
// get container and status
$manager = $this->getContainerManager();
$container = $manager->find($this->id);
if ($container==null) {
$runstatus = 'unknown';
return $runstatus;
}
$manager->inspect($container);
$cont = array();
$cont = $container->getRuntimeInformations();
if (isset($cont['State'])) {
if ($cont['State']['Paused']==1) {
$runstatus = 'paused';
}
else if ($cont['State']['Running']==1) {
$runstatus = 'running';
}
else if ($cont['State']['Restarting']==1) {
$runstatus = 'restarting';
}
else {
//dpm($cont['State']);
$runstatus = 'stopped';
}
}
} else if ($this->container_api == 1) {
try {
$runstatus = 'mesos';
$mesos = new Mesos($this->website->nid);
$runstatus = $mesos->getStatus();
} catch (RequestException $e) {
# never called
#dpm( $e->getResponse()->json()['message'] );
} catch (Exception $e) {
$runstatus='mesos-error';
#dpm($e->getMessage());
# $this->message('Mesos:' . $e->getResponse()->getReasonPhrase() .
# " (error code " . $e->getResponse()->getStatusCode(). " )" , 'warning');
#else {
# $this->message($e->getMessage(), 'error');
#}
#echo $e->getRequest();
if ($e->hasResponse()) {
if ($e->getResponse()->getStatusCode()==404) {
$runstatus='mesos-no container';
} else {
drupal_set_message( ' :: ' . $e->getResponse()->getStatusCode()
. ', ' . $e->getResponse()->getReasonPhrase()
. ': ' . $e->getResponse()->json()['message'] );
#dpm( var_export( $e->getResponse(), true) );
drupal_set_message( $e->__toString() );
}
#throw($e); // abort downstream
}
}
} else {
$runstatus='api-unknown';
}
return $runstatus;
}
/*
* delete a container: mesos by nid, docker by name
* todo: return code for docker?
* verbose argument?
* docker: if no name, use nid
* mesos: if no nid, use name
*/
public function deleteContainer($nid, $name, $verbose=0) {
$result='';
if ($this->container_api == 1) { // mesos
watchdog('webfact', "deleteContainer mesos nid=$nid");
#$this->message("Mesos: deleting ..");
$mesos = new Mesos($nid);
$result = $mesos->deleteApp($verbose); //deploymentId version
if ($verbose > 1) { // UI message
if (isset($result[0])) {
$this->message( var_export($result[0], true) );
watchdog('webfact', var_export($result[0], true) );
}
}
} else { // docker api
$manager = $this->getContainerManager();
$container = $manager->find($name);
if (!$container) {
watchdog('webfact', "deleteContainer $name - no such container");
return;
}
if ($container->getRuntimeInformations()['State']['Running'] == TRUE) {
$manager->stop($container);
}
# keep DB.. $this->deleteContainerDB($nid, $name);
$manager->remove($container);
}
watchdog('webfact', "deleteContainer $name - removed" . ' by ' . $this->user);
if ($verbose > 1) { // UI message
$this->message("deleted $this->id");
}
return $result;
}
public function deleteContainerDB($nid, $name, $verbose=0) {
watchdog('webfact', "deleteContainerDB $name" . ' by ' . $this->user);
if ($this->container_api == 0) { // docker API
$manager = $this->getContainerManager();
$container = $manager->find($name);
if (!$container) {
watchdog('webfact', "deleteContainerDB $name - no such container");
return;
}
}
$this->nid = $nid; // needed for extdb()
$this->id = $name; // needed for extdb()
$this->extdb('delete', 0); // delete external db, if configured
if ($verbose > 1) { // UI message
$this->message("deleted database $name");
}
}
public function deleteContainerData($nid, $name, $verbose=0) {
$serverdir = $this->sitesdir . $this->id; // mount point within container, hard-coded
if ($this->container_api == 0) { // docker API
$manager = $this->getContainerManager();
$container = $manager->find($name);
if (!$container) {
watchdog('webfact', "deleteContainerData $name - no such container");
return;
}
if (!isset($container->getRuntimeInformations()['State'])
|| $container->getRuntimeInformations()['State']['Running'] == FALSE) {
watchdog('webfact', "deleteContainerData - container must be running");
return;
}
watchdog('webfact', "deleteContainerData $name /data and " . $this->webroot);
$cmd = 'cd ' . $this->webroot . ' && rm -rf * .[a-zA-Z0-9]* ';
$logs = $this->runCommand($cmd);
$cmd = 'cd /data && rm -rf * .[a-zA-Z0-9]* ';
$logs = $this->runCommand($cmd);
watchdog('webfact', "remove top directories $serverdir");
if (! rmdir($serverdir . '/www') ) { watchdog('webfact', "cannot delete " . $serverdir . '/www'); }
if (! rmdir($serverdir . '/data') ) { watchdog('webfact', "cannot delete " . $serverdir . '/data'); }
if (! rmdir($serverdir ) ) { watchdog('webfact', "cannot delete " . $serverdir ); }
watchdog('webfact', "deleteContainerData $name - " . $this->webroot);
return($logs); // todo: review
} else if ($this->container_api == 1) { // mesos
$cmd=$this->sitesdir . "webfact_rm_site.sh";
if (! is_executable($cmd)) {
$logs = 'Cannot execute ' . $cmd;
if ($verbose > 1) { // UI message
$this->message($logs);
}
return($logs);
}
watchdog('webfact', "remove directory tree $serverdir via " . "sudo " . $cmd);
$logs = exec("sudo $cmd $this->id 2>&1", $outputexec, $resultexec);
if ( $resultexec ) { watchdog('webfact', "cannot delete " . $serverdir . "<pre>" . print_r($outputexec, true) . $logs . "</pre> and " . $resultexec, 'error'); }
watchdog('webfact', "deleteContainerData $name - done ");
if ($verbose > 1) { // UI message
$this->message("deleted data " . $serverdir);
}
return($logs); // todo: review
}
}
public function stopContainerByNid($nid) {
if ($this->container_api == 1) { // mesos
$mesos = new Mesos($this->nid);
$result = $mesos->stopApp(); //deploymentId version
}
return;
}
public function stopContainer($name) {
if ($this->container_api == 1) { // mesos
// how to stop by name?
$mesos = new Mesos($this->nid);
$result = $mesos->stopApp(); //deploymentId version
return;
}
$manager = $this->getContainerManager();
$container = $manager->find($name);
if (!$container) {
watchdog('webfact', "stopContainer $name - no such container");
return;
}
if ($container->getRuntimeInformations()['State']['Running'] == TRUE) {
$manager->stop($container);
}
watchdog('webfact', "stopContainer $name - done");
}
// todo: should be protected, due to $this
public function startContainer($name) {
if ($this->container_api == 1) { // mesos
return;
}
$manager = $this->getContainerManager();
$container = $manager->find($name);
if (!$container) {
watchdog('webfact', "startContainer $name - no such container");
return;
}
if ($container->getRuntimeInformations()['State']['Running'] == FALSE) {
#$manager->start($container);
$manager->start($container, $this->startconfig);
}
watchdog('webfact', "startContainer $name - done");
}
/*
* rebuild: stop, delete, create
*/
protected function rebuildContainer($name, $verbose=0) {
if ($this->container_api == 1) { // mesos stop and start
if (is_numeric($this->website->nid) ) {
$mesos = new Mesos($this->website->nid);
$result = implode(', ', $mesos->stopApp());
$result = implode(', ', $mesos->deleteApp(1));
sleep(1); // needed?
//$result .= '. Start=' . implode(', ', $mesos->startApp());
$this->createContainer(0);
if ($verbose==1) {
$this->message('Mesos container stopped, deleted and recreated.');
$this->message($result);
}
} else {
$result = "error: no nid";
if ($verbose==1) {
$this->message('Mesos container rebuild. ' . $result);
}
}
return $result;
}
$manager = $this->getContainerManager();
$container = $manager->find($name);
if (!$container) {
watchdog('webfact', "rebuildContainer $name - no such container");
return;
}
#$this->backupContainer($name);
if ($container->getRuntimeInformations()['State']['Running'] == TRUE) {
$manager->stop($container);
}
$manager->remove($container);
$this->arguments('create', $this->nid, 0); // verbose=0
watchdog('webfact', "rebuildContainer $name - done");
if ($verbose==1) {
$this->message('Container deleted and recreated');
}
}
/*
* rename a container
* no checking of permissions,
*/
protected function renameContainer($old, $newname, $verbose) {
watchdog('webfact', "renameContainer $old to $newname" . ' by ' . $this->user);
if ($this->container_api == 1) { // mesos
// dont rename the container, just change the URL that bamboo uses.
// changer the "hostname" field, the original name for marathon is still in the marathon
// field.
$this->website->field_hostname['und'][0]['value'] = $newname;
node_save($this->website); // Save the updated node
$this->website=node_load($this->website->nid); # reload cache
# Update object with new name, run with apropriate params
$this->id=$newname;
$this->load_meta();
$mesos = new Mesos($this->website->nid);
$mesos->updateBamboo();
if ($verbose==1) {
$this->message("Renamed hostname from $old to $newname and reconfigure bamboo");
}
} else {
// else docker API
$olddir = $this->sitesdir . $old;
$newdir = $this->sitesdir . $newname;
$manager = $this->getContainerManager();
// check for name conflict, i.e. newname does not already exist
$container = $manager->find($newname);
if ($container) {
throw new Exception("renameContainer: $newname already exists.");
}
if ( file_exists($newdir) ) {
throw new Exception("renameContainer: A server folder $newdir already exists");
}
// get the current container and stop it
$container = $manager->find($old);
if (!$container) {
watchdog('webfact', "renameContainer $old - no such container");
if ($verbose==1) {
$this->message("$old does not exist");
}
throw new Exception("renameContainer $old - no such container");
}
if ($container->getRuntimeInformations()['State']['Running'] == TRUE) {
$manager->stop($container);
}
# a) Rename server folder
if ( file_exists($olddir) && is_writable($olddir) ) {
if ( rename($olddir, $newdir) ) {
watchdog('webfact', "renameContainer $olddir renamed to $newdir");
} else {
throw new Exception("renameContainer: error $olddir to $newdir");
}
} else {
if ( ! file_exists($olddir) ) {
throw new Exception("renameContainer $olddir does not exist");
}
if ( ! is_writable($olddir) ) {
throw new Exception("renameContainer $olddir not writeable");
}
}
if ($verbose==1) {
$this->message("Renamed server folder $olddir to $newdir");
}
# Rename database+user, metadata:
# 7.10.2015: disabled since the drupal settings.php would also need to be adapted
# so the db/user will always have the "old" name, but can be found in the docker and meta env.
#$this->extdb('rename', 1, $newname);
# b) rename container
$manager->rename($container, $newname);
# c) rename metadata
$this->website->field_hostname['und'][0]['value'] = $newname;
node_save($this->website); // Save the updated node
$this->website=node_load($this->website->nid); # reload cache
if ($verbose==1) {
$this->message("Renamed container and meta data hostname"); ##
}
# Update object with new name, run with apropriate params
$this->id=$newname;
$this->load_meta();
$this->startContainer($newname);
} // if docker
# re-make the container: 7.10.2015: disabled, do a level higher
#$this->rebuildContainer($newname, $verbose);
if ($verbose==1) {
if ($this->container_api == 1) { // mesos
$this->message('done.');
} else {
$this->message('done. Rebuild may still be needed.');
}
}
}
/*
* backup a container (commit an image)
* parameter: container name, returns name of the saved container
*/
public function backupContainer($id, $comment='', $tag_postfix='') {
$this->client->setDefaultOption('timeout', 80); // can take time
$manager = $this->getContainerManager();
$container = $manager->find($id);
if (!$container) {
watchdog('webfact', "backupContainer $id - no such container");
return;
}
$config = array('tag' => date('Ymd') . $tag_postfix,
'repo' => $id,
'author' => $this->user,
'comment' => $comment,);
$savedimage = $this->docker->commit($container, $config);
$savedimage = $savedimage->__toString();
watchdog('webfact', "backupContainer $id to $savedimage" . ' by ' . $this->user);
return($savedimage);
}
/*
* create a container: test function, really abstract this bit out?
* implementation does not smell good!
*/
public function createContainer($verbose = 0) { // create a container
$result='';
// todo: make sure $id and all "this" stuff is loaded
if ($verbose == 1) {
$this->message("create $this->id from $this->cont_image", 'status', 3);
}
$this->extdb('create', $verbose); // if an an external DB is needed
if (strlen($this->cont_image)<1) {
if ($verbose == 1) {
$this->message("create $this->id : no docker image specified", 'error', 3);
}
return("no image specififed");
}
// create the container
if ($this->container_api == 1) { // mesos
$cont=Array(); // container spec for mesos
if ($this->cont_mem > 0) {
$cont['mem']=$this->cont_mem;
}
$cont['image']=$this->cont_image;
$cont['cmd']='/start.sh'; // todo: parameter
$cont['port']=443; // todo: parameter
$cont['ports']=$this->docker_ports;
$cont['url']=$this->fqdn;
// Reformat $this->docker_env from key=value to key=>value for mesos
foreach ($this->docker_env as $row) {
if ( preg_match("/\s*(.+)=(.+)\s*/", $row, $matches) ) {
$cont['env'][$matches[1]] = $matches[2];
}
}
// Reformat $this->docker_vol from key=value to array for mesos
#dpm($this->docker_start_vol);
$i=0;
foreach ($this->docker_start_vol as $row) {
if ( preg_match("/\s*(.+):(.+):(.+)\s*/", $row, $matches) ) {
#dpm($matches[1] .', ' . $matches[2] . ', ' . $matches[3]);
#$cont['env'][$matches[1]] = $matches[2];
$cont['vol'][$i]['containerPath']=$matches[2];
$cont['vol'][$i]['hostPath']=$matches[1];
$cont['vol'][$i]['mode']=strtoupper($matches[3]);
$i++;
}
}
#dpm($cont);
$mesos = new Mesos($this->nid);
$result = $mesos->createApp($cont, 1);
if ($this->verbose===1) {
if ($verbose == 1) {
if (isset($result['version'])) {
$this->message("mesos: created $this->id, " . $result['version'] . " Deployment id=" . $result['deployments'][0]['id'] );
watchdog('webfact', "mesos: created $this->id, " . $result['version'] . " Deployment id=" . $result['deployments'][0]['id'] );
}
}
}
} else { // docker API
$config = ['Image' => $this->cont_image,
# Dont limit any more: 'Hostname' => $this->fqdn,
'Env' => $this->docker_env,
'Volumes' => $this->docker_vol, // ['/data' => array()],
];
#dpm('--create: config--');
#dpm($config);
$manager = $this->getContainerManager();
$container= new Docker\Container($config);
$container->setName($this->id);
$manager->create($container);
if ($verbose == 1) {
$this->message("start ", 'status', 3);
}
#dpm('--create2--');
if ($this->cont_mem > 0) {
$this->startconfig['Memory'] = $this->cont_mem;
watchdog('webfact', 'container->setMemory ' . $this->cont_mem);
}
#dpm($this->startconfig);
$manager->start($container, $this->startconfig);
}
// both APIS
$msg= "$this->action $this->id: title=" . $this->website->title
. ", docker image=$this->cont_image" . ' by ' . $this->user;
watchdog('webfact', $msg);
$this->touch_node_date();
if ($verbose == 1) {
// inform user:
//$this->message($msg, 'status', 2);
$cur_time=date("Y-m-d H:i:s"); // calculate now + 6 minutes
$newtime=date('H:i', strtotime('+6 minutes', strtotime($cur_time))); // todo setting
$this->message("Provisioning: you can connect to the new site at $newtime. The status below is updated every 30 secs, alternatively inspect the container or examine logs.", 'status');
// TODO: do some ajax to query the build status and confirm when done
#$this->message("Build=" .$this->getContainerBuildStatus());
#if ($this->getContainerBuildStatus() == 100) {
# $this->message("Build finished");
#}
}
return $result;
}
/*
* load the meta spec for a container from the website and template
* todo: what if $this->id is not loaded?
*/
public function load_meta() {
$this->docker_start_vol=array();
$this->docker_vol=array();
$this->docker_env=array();
// detect if this is a drupal container, so we can enable drupal specific management
// the logic is a bit inverted to allow seamless use on existing installations,
// if the field is not set, or does not exist, presume it is a drupal website
if ((isset($this->website->field_not_drupal))
&& !empty($this->website->field_not_drupal)
&& ($this->website->field_not_drupal['und'][0]['value']==1) ) {
$this->is_drupal = 0;
}
// Mesos
if (!empty($this->website->field_container_api['und'][0]['value']) ) {
$this->container_api = $this->website->field_container_api['und'][0]['value'];
}
// Initial docker environment variables
$this->fqdn = $this->id . '.' . $this->fserver; // e.g. MYHOST.webfact.example.ch
if ($this->is_drupal == 1) {
$this->docker_env = [
'DRUPAL_SITE_NAME=' . $this->website->title,
'DRUPAL_SITE_EMAIL=' . $this->website->field_site_email['und'][0]['safe_value'],
'DRUPAL_ADMIN_EMAIL=' . $this->website->field_site_email['und'][0]['safe_value'],
"VIRTUAL_HOST=$this->fqdn",
];
} else {
#dpm('-not drupal');
$this->docker_env = [
"VIRTUAL_HOST=$this->fqdn",
];
}
// webfactory server default
if (isset($this->env_server)) { // pull in default env
$this->docker_env[] = $this->env_server;
}
if ($this->is_drupal == 1) {
// Create a volume mount point automatically?
if (($this->container_api==0) && ! file_exists($this->sitesdir . $this->id) ) {
if ((variable_get('webfact_data_volume', 1) == 1 ) || (variable_get('webfact_www_volume', 1) == 1 ) ) {
if (! mkdir($this->sitesdir . $this->id, 0775) ) {
watchdog('webfact', 'Server folder ' . $this->sitesdir . $this->id .' could not be created.');
}
}
}
if (variable_get('webfact_data_volume', 1) == 1 ) {
$mount = '/data'; // todo: make a setting
$folder = $this->sitesdir_host . $this->id . $mount;
$this->docker_vol[$mount] = array() ;
$this->docker_start_vol[] = $folder . ':' . $mount . ':rw';
if (($this->container_api==0) && ! file_exists($folder) ) {
watchdog('webfact', "Create $folder");
if (! mkdir($folder, 0775) ) {
watchdog('webfact', 'Server folder ' . $folder .' could not be created, is the parent folder writeable?');
}
}
}
if (variable_get('webfact_www_volume', 1) == 1 ) {
$mount = $this->webroot;
$folder = $this->sitesdir_host . $this->id . '/www';
$this->docker_vol[$mount] = array() ;
$this->docker_start_vol[] = $folder . ':' . $mount . ':rw';
if (($this->container_api==0) && ! file_exists($folder) ) {
watchdog('webfact', "Create $folder");
if (! mkdir($folder, 0775) ) {
# log, but not to UI
#drupal_set_message("Server folder $folder could not be created.", 'warning');
watchdog('webfact', 'Server folder ' . $folder .' could not be created');
}
}
}
} // if drupal
// Template? : Load values there first
if (isset($this->website->field_template['und'][0]['target_id'])) {
#$this->message("A template must be associated with $this->id($this->website->title)", 'error');
$tid=$this->website->field_template['und'][0]['target_id'];
if ($tid!=null) {
#dpm("reading template ");
$template=node_load($tid);
if ($template!=null) {
#dpm($template);
// image
if (!empty($template->field_docker_image['und'][0]['safe_value']) ) {
$this->cont_image = $template->field_docker_image['und'][0]['safe_value'];
}
// environment key/value array
if (!empty($template->field_docker_environment['und']) ) {
foreach ($template->field_docker_environment['und'] as $row) {
#dpm($row['safe_value']);
if (!empty($row['safe_value'])) {
$this->docker_env[]= $row['safe_value'];
}
}
}
// volumes from template
if (!empty($template->field_docker_volumes['und']) ) {
foreach ($template->field_docker_volumes['und'] as $row) {
//dpm($row);
if (!empty($row['safe_value'])) {
# image "create time" mapping: foo:bar:baz, extract the foo:
$count = preg_match('/^(.+)\:.+:/', $row['safe_value'], $matches);
#dpm($matches);
if (isset($matches[1])) {
# $this->docker_vol = ["/root/gitwrap/id_rsa" =>"{}", "/root/gitwrap/id_rsa.pub" =>"{}" ];
//Pre docker 1.7: $this->docker_vol[] .= "$matches[1] =>{}";
$this->docker_vol[$matches[1]] = array();
# runtime mapping
$this->docker_start_vol[] .= $row['safe_value'];
}
else {
$this->message("Template volume field must be of the form xx:y:z", 'error');
return;
}
}
}
}
// ports from template
if (!empty($template->field_docker_ports['und']) ) {
foreach ($template->field_docker_ports['und'] as $row) {
#dpm($row['safe_value']);
if (!empty($row['safe_value'])) {
# port "create time" mapping: sourceport:dstnport
$count = preg_match('/^(.+)\:(.+)/', $row['safe_value'], $matches);
#dpm($matches);
if (isset($matches[1])) {
$this->docker_ports[ "$matches[1]/tcp" ] =
[[ 'HostIp' => '0.0.0.0', 'HostPort' => "$matches[2]" ]] ;
}