This repository has been archived by the owner on Feb 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
app.js
1230 lines (1220 loc) · 43.2 KB
/
app.js
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
// Taisun
// Main Node.js app
//// Application Variables ////
const uuidv4 = require('uuid/v4');
const { spawn } = require('child_process');
const si = require('systeminformation');
var gitClone = require('git-clone');
var rmdir = require('rmdir');
var tar = require('tar-fs');
var AU = require('ansi_up');
var stream = require('stream');
var ansi_up = new AU.default;
var nunjucks = require('nunjucks');
var yaml = require('js-yaml');
var request = require('request');
const crypto = require('crypto');
var ejs = require('ejs');
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Docker = require('dockerode');
var docker = new Docker({socketPath: '/var/run/docker.sock'});
var exec = require('child_process').exec;
var dockops = require('dockops');
var dockerops = dockops.createDocker();
var images = new dockops.Images(dockerops);
var xparse = require('xrandr-parse');
var fs = require('fs');
var path = require('path');
let dockerHubAPI = require('docker-hub-api');
dockerHubAPI.setCacheOptions({enabled: false});
// Sleep Helper
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
///// Guac Websocket Tunnel ////
const GuacamoleLite = require('guacamole-lite');
var clientOptions = {
crypt: {
cypher: 'AES-256-CBC',
key: 'TaisunKYTaisunKYTaisunKYTaisunKY'
},
log: {
verbose: false
}
};
// Spinup the Guac websocket proxy on port 3000 if guacd is running
var guacontainer = docker.getContainer('guacd');
guacontainer.inspect(function (err, containerdata) {
if (err) return;
// For first time users or people that do not care about VDI
if (containerdata == null){
console.log('Guacd does not exist on this server will not start websocket tunnel');
startstacks();
}
else {
// Start Guacd if it exists and it not running then exit the process supervisor will pick it up
if (containerdata.State.Status != 'running'){
guacontainer.start(function (err, data) {
if (err) return;
console.log('Guacd exists starting and restarting app via exit for nodemon to pickup');
sleep(5000).then(() => {
process.exit();
});
});
}
// If it is up and running use the IP we got from inspect to fire up the websocket tunnel used by the VDI application
else {
const guacServer = new GuacamoleLite({server: http,path:'/guaclite'},{host:containerdata.NetworkSettings.IPAddress,port:4822},clientOptions);
startstacks();
}
}
});
// Function needed to encrypt the token string for guacamole connections
const encrypt = (value) => {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(clientOptions.crypt.cypher, clientOptions.crypt.key, iv);
let crypted = cipher.update(JSON.stringify(value), 'utf8', 'base64');
crypted += cipher.final('base64');
const data = {
iv: iv.toString('base64'),
value: crypted
};
return new Buffer(JSON.stringify(data)).toString('base64');
};
// Start all Taisun Stack containers
function startstacks(){
docker.listContainers({all: true}, function (err, containers) {
if (err){
console.log(err);
}
else{
containers.forEach(function(container){
// If the container has a stackname label assume it is a taisun container
if (container.Labels.stackname){
// If the container is not running
if (container.State != 'running'){
var contostart = docker.getContainer(container.Id);
contostart.start();
console.log('Started ' + container.Names[0] + ' time=' + (new Date).getTime());
}
}
});
}
});
}
////// PATHS //////
//// Main ////
app.get("/", function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
//// Public JS and CSS ////
app.use('/public', express.static(__dirname + '/public'));
//// Embedded guac ////
app.get("/desktop/:containerid", function (req, res) {
var container = docker.getContainer(req.params.containerid);
// Make sure this is a container
container.inspect(function (err, data) {
if (data == null){
res.send('container does not exist');
}
else{
var labels = data.Config.Labels;
if (typeof labels.vditype != 'undefined' && labels.vditype == 'RDP' ){
console.log(req.query);
if (req.query.login){
var connectionstring = encrypt(
{
"connection":{
"type":"rdp",
"settings":{
"hostname":data.NetworkSettings.IPAddress,
"port":"3389",
"security": "any",
"ignore-cert": true
}
}
});
}
else{
var connectionstring = encrypt(
{
"connection":{
"type":"rdp",
"settings":{
"hostname":data.NetworkSettings.IPAddress,
"port":"3389",
"username":"abc",
"password":"abc",
"security": "any",
"ignore-cert": true
}
}
});
}
res.render(__dirname + '/views/rdp.ejs', {token : connectionstring});
}
else {
var connectionstring = encrypt(
{
"connection":{
"type":"vnc",
"settings":{
"hostname":data.NetworkSettings.IPAddress,
"port":"5900"
}
}
});
res.render(__dirname + '/views/guac.ejs', {token : connectionstring});
}
}
});
});
//// Embedded VNC ////
app.get("/VNC/:containerid", function (req, res) {
var container = docker.getContainer(req.params.containerid);
// Make sure this is a container
container.inspect(function (err, data) {
if (data == null){
res.send('container does not exist');
}
else{
var labels = data.Config.Labels;
var connectionstring = encrypt(
{
"connection":{
"type":"vnc",
"settings":{
"hostname":labels.host,
"port":labels.port,
"username":labels.host,
"password":labels.password
}
}
});
console.log(connectionstring);
res.render(__dirname + '/views/vnc.ejs', {token : connectionstring});
}
});
});
//// Embedded RDP ////
app.get("/RDP/:containerid", function (req, res) {
var container = docker.getContainer(req.params.containerid);
// Make sure this is a container
container.inspect(function (err, data) {
if (data == null){
res.send('container does not exist');
}
else{
var labels = data.Config.Labels;
var connectionstring = encrypt(
{
"connection":{
"type":"rdp",
"settings":{
"hostname":labels.host,
"port":labels.port,
"username":labels.user,
"password":labels.password,
"security": "any",
"ignore-cert": true
}
}
});
console.log(connectionstring);
res.render(__dirname + '/views/rdp.ejs', {token : connectionstring});
}
});
});
//// Terminal Emulator ////
app.get("/terminal/:containerid", function (req, res) {
var container = docker.getContainer(req.params.containerid);
// Make sure this is a container
container.inspect(function (err, data) {
if (data == null){
res.send('container does not exist');
}
// If this is a tmux container attach to the running session
else if ( JSON.stringify(data.Config.Labels).indexOf('taisuntmux.yml') > -1 ) {
res.render(__dirname + '/views/terminal.ejs', {containerid : req.params.containerid,shell : 'tmux'});
}
else{
// Shell check
var options = {
Cmd: ['/bin/sh', '-c', 'test -e /bin/bash'],
AttachStdout: true,
AttachStderr: true
};
container.exec(options, function(err, exec) {
if (err) return;
exec.start(function(err, stream) {
if (err) return;
container.modem.demuxStream(stream, process.stdout, process.stderr);
stream.on('end', function(output){
exec.inspect(function(err, data) {
if (err) return;
if (data.ExitCode == 0){
res.render(__dirname + '/views/terminal.ejs', {containerid : req.params.containerid,shell : '/bin/bash'});
}
else{
res.render(__dirname + '/views/terminal.ejs', {containerid : req.params.containerid,shell : '/bin/sh'});
}
});
});
});
});
}
});
});
//// Api ////
// Container data
app.get("/containers", function (req, res) {
docker.listContainers({all: true}, function (err, containers) {
if (err){
res.send(JSON.stringify({'error':'cannot access docker on taisun'}));
}
else{
res.send(JSON.stringify(containers));
}
});
});
// Socket IO connection
io.on('connection', function(socket){
//// Socket Connect ////
// Log Client and connection time
console.log(socket.id + ' connected time=' + (new Date).getTime());
socket.join(socket.id);
///////////////////////////
////// Socket events //////
///////////////////////////
// When dash info is requested send to client
socket.on('getdashinfo', function(){
var dashinfo = {};
si.cpu(function(cpu) {
dashinfo['cpu'] = cpu;
si.mem(function(mem) {
dashinfo['mem'] = mem;
si.currentLoad(function(currentLoad) {
dashinfo['CPUpercent'] = currentLoad.currentload_user;
docker.listContainers({all: true}, function (err, containers) {
if (err){
io.sockets.in(socket.id).emit('renderdash',dashinfo);
}
else{
dashinfo['containers'] = containers;
images.list(function (err, images) {
if (err) return;
dashinfo['images'] = images;
io.sockets.in(socket.id).emit('renderdash',dashinfo);
});
}
});
});
});
});
});
//// VDI related
// When vdi info is requested send to client
socket.on('getvdi', function(){
containerinfo('updatevdi');
});
// destroy a desktop
socket.on('destroydesktop', function(name){
destroydesktop(name, 'no');
});
// resize a desktop
socket.on('resizedesktop', function(width,height,path,monitor){
var id = path.replace('/desktop/','');
resizedesktop(width,height,id,monitor);
});
// When client requests resolutions call container xrandr
socket.on('getres', function(path){
var id = path.replace('/desktop/','');
getres(id);
});
// Send local images
socket.on('getimages', function(){
images.list(function (err, res) {
if (err) return;
io.sockets.in(socket.id).emit('sendimages',res);
});
});
// Launch Guacd
socket.on('launchguac', function(){
io.sockets.in(socket.id).emit('modal_update','Starting Launch Process for Guacd');
// Check if the guacd image exists on this server
images.list(function (err, res) {
if (err) return;
if (JSON.stringify(res).indexOf('linuxserver/guacd:latest') > -1 ){
deployguac();
}
else {
io.sockets.in(socket.id).emit('modal_update','Guacd image not present on server downloading now');
docker.pull('linuxserver/guacd:latest', function(err, stream) {
if (err) return;
stream.pipe(process.stdout);
stream.once('end', deployguac);
});
}
});
});
// Get Docker Hub results
socket.on('searchdocker', function(string, page){
request.get({url:'https://registry.hub.docker.com/v1/search?q=' + string + '&page=' + page},function(error, response, body){
io.sockets.in(socket.id).emit('hubresults',JSON.parse(body));
});
});
// Get complete dockerhub info for given image
socket.on('gethubinfo', function(name){
if (name.indexOf("/") != -1 ){
var user = name.split('/')[0];
var repo = name.split('/')[1];
}
else {
var user = '_';
var repo = name;
}
dockerHubAPI.repository(user, repo).then(function (info) {
io.sockets.in(socket.id).emit('sendhubinfo', info);
});
});
// Get the tags for a specific image from dockerhub
socket.on('gettags', function(name){
var user = name.split('/')[0];
var repo = name.split('/')[1];
dockerHubAPI.tags(user, repo).then(function (data) {
io.sockets.in(socket.id).emit('sendtagsinfo', [data, name]);
});
});
// Pull image
socket.on('sendpullcommand', function(image){
io.sockets.in(socket.id).emit('senddockerodeoutstart', 'Starting Pull process for ' + image);
console.log('Pulling ' + image);
docker.pull(image, function(err, stream) {
if (err) return;
docker.modem.followProgress(stream, onFinished, onProgress);
function onProgress(event) {
io.sockets.in(socket.id).emit('senddockerodeout', event);
}
function onFinished(err, output) {
if (err) return;
io.sockets.in(socket.id).emit('senddockerodeoutdone', 'Finished Pull process for ' + image);
console.log('Finished Pulling ' + image);
}
});
});
// Get Taisun.io stacks running locally
socket.on('getstacks', function(){
containerinfo('localstacks');
});
// Get remote list of stack definition files from stacks.taisun.io
socket.on('browsestacks', function(page){
request.get({url:'https://api.taisun.io/stacks'},function(error, response, body){
io.sockets.in(socket.id).emit('stacksresults',JSON.parse(body));
});
});
// Get Stack search results
socket.on('searchstacks', function(string, page){
request.get({url:'https://api.taisun.io/stacks?search=' + string + '&page=' + page},function(error, response, body){
io.sockets.in(socket.id).emit('stacksresults',JSON.parse(body));
});
});
// Parse Taisun Stacks Yaml and send form to client
socket.on('sendstackurl', function(url){
if (url.substring(0,4) == 'http'){
request.get({url:url},function(error, response, body){
var yml = yaml.safeLoad(body);
var name = yml.name;
var description = yml.description;
var form = yml.form;
io.sockets.in(socket.id).emit('stackurlresults', [name,description,form,url,body]);
});
}
// Try to grab a dockerhub endpoint for stack data if this is not a URL
else{
renderprivatestack(url);
}
});
// Parse Yaml for single container and send to user
socket.on('sendimagename', function(imagename){
request.get({url:'http://localhost:3000/public/taisuntemplates/basetemplate.yml'},function(error, response, body){
var yml = yaml.safeLoad(body);
var name = yml.name;
var description = yml.description;
var form = yml.form;
form.push({type:'input',format:'text',label:'image',FormName:'Image',placeholder:'',value:imagename});
io.sockets.in(socket.id).emit('stackurlresults', [name,description,form,'http://localhost:3000/public/taisuntemplates/basetemplate.yml',body]);
});
});
// Get custom Yaml from user and create a temp file for using the standard workflow
socket.on('sendyaml', function(code){
var guid = uuidv4().substring(0,12);
var file = path.join(__dirname, 'public/stackstemp/', guid + '.yml');
fs.writeFile(file, code, function(err) {
if(err) {
return console.log(err);
}
var yml = yaml.safeLoad(code);
var name = yml.name;
var description = yml.description;
var form = yml.form;
io.sockets.in(socket.id).emit('stackurlresults', [name,description,form,'http://localhost:3000/public/stackstemp/' + guid + '.yml',code]);
});
});
// When user submits stack data launch the stack
socket.on('launchstack', function(userinput){
var url = userinput.stackurl;
var inputs = userinput.inputs;
var template = userinput.template;
var templatename = url.split('/').slice(-1)[0];
var stacktype = 'community';
inputs['stacktype'] = stacktype;
inputs['stackurl'] = url;
if (inputs.name){
inputs['stackname'] = inputs.name;
}
else {
inputs['stackname'] = uuidv4().substring(0,8);
}
var yml = yaml.safeLoad(template);
var compose = yml.compose;
var composefile = nunjucks.renderString(compose, inputs);
var composeupcommand = ['sh','-c','echo \'' + composefile + '\' | docker-compose -p '+ inputs.stackname+' -f - up -d'];
var composepullcommand = ['sh','-c','echo \'' + composefile + '\' | docker-compose -p '+ inputs.stackname+' -f - pull'];
const composepull = spawn('unbuffer', composepullcommand);
composepull.stdout.setEncoding('utf8');
composepull.stdout.on('data', (data) => {
io.sockets.in(socket.id).emit('sendconsoleout',ansi_up.ansi_to_html(data).trim());
});
composepull.on('close', (code) => {
if (code != '0'){
destroystack(inputs.stackname);
io.sockets.in(socket.id).emit('sendconsoleoutdone','Compose pull process exited with code ' + code);
}
else{
const composeup = spawn('unbuffer', composeupcommand);
composeup.stdout.setEncoding('utf8');
composeup.stdout.on('data', (data) => {
io.sockets.in(socket.id).emit('sendconsoleout',ansi_up.ansi_to_html(data).trim());
});
composeup.on('close', (code) => {
io.sockets.in(socket.id).emit('sendconsoleoutdone','Compose up process exited with code ' + code);
containerinfo('updatestacks');
if (code != '0'){
destroystack(inputs.stackname);
}
if (stacktype == 'community' && url.indexOf('https://stacks.taisun.io/templates/') > -1){
var guid = templatename.replace('.yml','');
request.get({url:'https://api.taisun.io/stacks/download?guid=' + guid},function(error, response, body){
console.log('updated download count for stack ' + guid);
});
}
});
}
});
});
// Get GuacD full container information and render VDI page based on status
socket.on('checkguac', function(return_name){
var guacontainer = docker.getContainer('guacd');
guacontainer.inspect(function (err, data) {
if (data == null){
io.sockets.in(socket.id).emit(return_name, 'no');
}
else{
io.sockets.in(socket.id).emit(return_name, 'yes');
}
});
});
// Send GuacD container info to client
socket.on('getguacinfo', function(){
var guacontainer = docker.getContainer('guacd');
guacontainer.inspect(function (err, data) {
if (data == null){
io.sockets.in(socket.id).emit('guacinfo', 'Error Getting GuacD infor');
}
else{
io.sockets.in(socket.id).emit('guacinfo', data);
}
});
});
// When the user checks the status of the remote gateway send it back
socket.on('checkremote', function(){
var remotecontainer = docker.getContainer('taisun_gateway');
remotecontainer.inspect(function (err, data) {
if (data == null){
io.sockets.in(socket.id).emit('renderremote', 'no');
}
else{
io.sockets.in(socket.id).emit('renderremote', data);
containerinfo('updategateway');
}
});
});
// When devstacks info is requested send to client
socket.on('getdev', function(){
containerinfo('updatedev');
});
// When termstacks info is requested send to client
socket.on('getterm', function(){
containerinfo('updateterm');
});
// When rdpvnc info is requested send to client
socket.on('getrdpvnc', function(){
containerinfo('updaterdbvnc');
});
// When stack destruction is requested initiate
socket.on('destroystack', function(name){
destroystack(name, 'no');
});
// When Upgrade is requested launch upgrade helper
socket.on('upgradetaisun', function(){
upgradetaisun();
});
// When Guacd Upgrade is requested launch upgrade helper
socket.on('upgradeguacd', function(){
upgradeguacd();
});
// When version is requested send
socket.on('getversion', function(){
fs.readFile('version', 'utf8', function (err, version) {
if (err) return;
var taisunversion = version;
io.sockets.in(socket.id).emit('sendversion', taisunversion);
});
});
// When Stack Upgrade is requested execute
socket.on('upgradestack', function(stackname){
upgradestack(stackname);
});
// When Stack Restart is requested execute
socket.on('restartstack', function(stackname){
restartstack(stackname);
});
// When Stack Stop is requested execute
socket.on('stopstack', function(stackname){
stopstack(stackname);
});
// When Stack Start is requested execute
socket.on('startstack', function(stackname){
startstack(stackname);
});
// When Stack Logs are requested execute
socket.on('containerlogs', function(containerid){
containerlogs(containerid);
});
// When build from git is requested execute
socket.on('builddockergit', function(formdata){
var repo = formdata[0];
var path = formdata[1];
var checkout = formdata[2];
var tag = formdata[3];
builddockergit(repo,path,checkout,tag);
});
// When user chooses to push a stack template to dockerhub execute
socket.on('buildencrypto', function(formdata){
var tag = formdata[0];
var template = formdata[1];
var dockeruser = formdata[2];
var dockerpass = formdata[3];
var pass = uuidv4();
buildencrypto(tag,pass,template,dockeruser,dockerpass);
});
// When the user requests a remote access check ping the port checker with the URL
socket.on('checkremoteaccess', function(domain){
var url = 'https://api.taisun.io/server/portcheck?host=' + domain;
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
io.sockets.in(socket.id).emit('sendremotestatus', JSON.parse(body));
}
});
});
// Get Taisun.io stacks running locally for stack management
socket.on('getmanage', function(){
containerinfo('manageinfo');
});
// Container Terminal access
socket.on('spawnterm', function(containerid, w, h, shell){
console.log('Spawning terminal on ' + containerid);
var container = docker.getContainer(containerid);
if (shell != 'tmux'){
var cmd = {
"AttachStdout": true,
"AttachStderr": true,
"AttachStdin": true,
"Tty": true,
Cmd: [shell]
};
}
else {
var cmd = {
"AttachStdout": true,
"AttachStderr": true,
"AttachStdin": true,
"Tty": true,
Cmd: ['/usr/bin/tmux','a','-t','taisun']
};
}
container.exec(cmd, (err, exec) => {
if (err) return;
var options = {
'Tty': true,
stream: true,
stdin: true,
stdout: true,
stderr: true,
hijack: true
};
exec.start(options, (err, stream) => {
if (err) return;
var dimensions = { h, w };
exec.resize(dimensions, () => { });
stream.on('data', (chunk) => {
io.sockets.in(socket.id).emit('termdata', chunk.toString());
});
socket.on('termdata', (data) => {
stream.write(data);
});
socket.on('resizeterm', (w, h) => {
var dimensions = { h, w };
exec.resize(dimensions, () => { });
});
// Close Terminal
socket.on('killterm', function(){
console.log('Killing Terminal on ' + containerid);
stream.end();
});
});
});
});
// Destroy a single container by name
socket.on('destroycontainer', function(name){
destroycontainer(name);
});
///////////////////
//// Functions ////
///////////////////
// Resize monitor when clients browser sends it to us
function resizedesktop(width,height,id,monitor){
var cmd = 'docker exec ' + id + ' /changeres.sh ' + monitor.toString() + ' ' + width.toString() + ' ' + height.toString() ;
exec(cmd, function(err, stdout, stderr) {
if (err){
console.log(err);
}
else{
console.log('Resized Desktop for ' + id + ' on screen ' + monitor.toString() + ' to the dimensions ' + width.toString() + 'x' + height.toString());
}
});
}
// Get available resolutions from container
function getres(id){
var xcmd = 'docker exec ' + id + ' xrandr';
exec(xcmd, function (err, stdout) {
if (err) return;
var resolutions = xparse(stdout);
io.sockets.in(socket.id).emit('sendres', resolutions);
});
}
// Get all container information
function containerinfo(target){
docker.listContainers({all: true}, function (err, containers) {
if (err){
io.sockets.in(socket.id).emit(target,err);
}
else{
io.sockets.in(socket.id).emit(target,containers);
}
});
}
// Destroy a Stack
function destroystack(name, auto){
docker.listContainers({all: true}, function (err, containers) {
if (err){
io.sockets.in(socket.id).emit('error_popup','Could not list containers something is wrong with docker on this host');
}
else{
containers.forEach(function (container){
if (container.Labels.stackname){
if (container.Labels.stackname == name){
docker.getContainer(container.Id).remove({force: true},function (err, data) {
if (err){
console.log(JSON.stringify(err));
io.sockets.in(socket.id).emit('error_popup','Could destroy Stack container for ' + name);
}
else{
console.log('Destroyed Stack container ' + container.Names[0] + ' for stack ' + name);
containerinfo('updatestacks');
}
});
}
}
});
}
});
}
// Destroy a Single container
function destroycontainer(name){
io.sockets.in(socket.id).emit('modal_update','Attempting to destroy ' + name);
docker.getContainer(name).remove({force: true},function (err, data) {
if (err){
console.log(JSON.stringify(err));
io.sockets.in(socket.id).emit('modal_finish','Cannot destroy ' + name + ' does not exist');
}
else{
console.log('Destroyed container ' + name);
io.sockets.in(socket.id).emit('modal_finish','Destroyed ' + name);
// Restart the app if we just killed the guacd container
if (name == 'guacd'){
process.exit();
}
}
});
}
// Launch Guacd container
function deployguac(){
// Grab the current running docker container information
docker.listContainers(function (err, containers) {
if (err){
io.sockets.in(socket.id).emit('error_popup','Could not list containers something is wrong with docker on this host');
}
else{
var guacoptions ={
Image: 'linuxserver/guacd',
name: 'guacd'
};
docker.createContainer(guacoptions, function (err, container){
if (err){
console.log(JSON.stringify(err));
io.sockets.in(socket.id).emit('error_popup','Could not pull Guacd container');
}
else{
io.sockets.in(socket.id).emit('modal_update','Downloaded image and created Guacd container');
container.start(function (err, data){
if (err){
console.log(JSON.stringify(err));
io.sockets.in(socket.id).emit('error_popup','Could not start Guacd');
}
else{
io.sockets.in(socket.id).emit('modal_finish','Guacd launched , Restarting page will refresh in 5 seconds');
// Exit the application supervisor will restart
process.exit();
}
});
}
});
}
});
}
// Launch Upgrade container
function upgradetaisun(){
// Check if the upgrade image exists on this server
images.list(function (err, res) {
if (err) return;
if (JSON.stringify(res).indexOf('containrrr/watchtower:latest') > -1 ){
runupgrade();
}
else {
docker.pull('containrrr/watchtower:latest', function(err, stream) {
if (err) return;
stream.pipe(process.stdout);
stream.once('end', runupgrade);
});
}
});
}
function runupgrade(){
// Grab the current running docker container information
docker.listContainers(function (err, containers) {
if (err){
io.sockets.in(socket.id).emit('error_popup','Could not list containers something is wrong with docker on this host');
}
else{
docker.run('containrrr/watchtower:latest', ['--run-once', 'taisun'], process.stdout, {
HostConfig: {
Binds: ["/var/run/docker.sock:/var/run/docker.sock"],
AutoRemove: true
}
}, {},function (err, data, container) {
if(err)
console.log("Error: ", err);
else
console.log(data.StatusCode);
});
}
});
}
// Launch Upgrade container
function upgradeguacd(){
// Check if the upgrade image exists on this server
images.list(function (err, res) {
if (err) return;
if (JSON.stringify(res).indexOf('containrrr/watchtower:latest') > -1 ){
runupgrade();
}
else {
docker.pull('containrrr/watchtower:latest', function(err, stream) {
if (err) return;
stream.pipe(process.stdout);
stream.once('end', runupgradeguacd);
});
}
});
}
function runupgradeguacd(){
// Grab the current running docker container information
docker.listContainers(function (err, containers) {
if (err){
io.sockets.in(socket.id).emit('error_popup','Could not list containers something is wrong with docker on this host');
}
else{
docker.run('containrrr/watchtower:latest', ['--run-once', 'guacd'], process.stdout, {
HostConfig: {
Binds: ["/var/run/docker.sock:/var/run/docker.sock"],
AutoRemove: true
}
}, {},function (err, data, container) {
if(err)
console.log("Error: ", err);
else
console.log(data.StatusCode);
});
}
});
}
// Launch Upgrade container
function upgradestack(stackname){
// Check if the upgrade image exists on this server
images.list(function (err, res) {
if (err) return;
if (JSON.stringify(res).indexOf('containrrr/watchtower:latest') > -1 ){
stackupgrade(stackname);
}
else {
io.sockets.in(socket.id).emit('senddockerodeoutstart','Need to pull the updater image');
docker.pull('containrrr/watchtower:latest', function(err, stream) {
if (err) return;
docker.modem.followProgress(stream, onFinished, onProgress);
function onProgress(event) {
io.sockets.in(socket.id).emit('senddockerodeout', event);
}
function onFinished(err) {
if (err) return;
io.sockets.in(socket.id).emit('senddockerodeoutstart', 'Finished Pull process for updater');
stackupgrade(stackname);
console.log('Finished Pulling updater');
}
});
}
});
}
function stackupgrade(stackname){
// Grab the current running docker container information
docker.listContainers(function (err, containers) {
if (err){
io.sockets.in(socket.id).emit('error_popup','Could not list containers something is wrong with docker on this host');
}
else{
containers.forEach(function(container){
// If the container has the stackname passed
if (container.Labels.stackname == stackname){
io.sockets.in(socket.id).emit('senddockerodeoutstart','Started upgrade run for ' + container.Names[0]);
docker.run('containrrr/watchtower:latest', ['--run-once', container.Names[0]], process.stdout,{
HostConfig: {
Binds: ["/var/run/docker.sock:/var/run/docker.sock"],
AutoRemove: true
}
},function (err, data, container) {
if(err)
console.log("Error: "+ err);
}).on('stream', function (stream) {
stream.setEncoding('utf8');
stream.on('data', (data) => {
io.sockets.in(socket.id).emit('sendconsoleout',ansi_up.ansi_to_html(data).trim());
});
stream.on('end', function(){
io.sockets.in(socket.id).emit('sendconsoleoutdone','Finished upgrade run for ' + container.Names[0]);
});
});
}
});
}
});
}
// Build a docker container from a git repository
function builddockergit(repo,path,checkout,tag){
var tempfolder = '/tmp/' + uuidv4(); + '/';
if (checkout == ''){
var checkout = 'master';
}
io.sockets.in(socket.id).emit('senddockerodeoutstart', 'Starting git clone process for ' + repo);
gitClone(repo, tempfolder, {
checkout: checkout },
function(err) {
if (err){
io.sockets.in(socket.id).emit('senddockerodeoutdone', 'Error unable to checkout ' + repo);
console.log(err);
rmdir(tempfolder);
}
else{
io.sockets.in(socket.id).emit('senddockerodeoutstart', repo + ' checked out');
var tarStream = tar.pack(tempfolder + path);
docker.buildImage(tarStream, {
t: tag
}, function(error, output) {
if (error) {
io.sockets.in(socket.id).emit('senddockerodeoutdone', 'Error executing build');
console.error(error);
rmdir(tempfolder);
}
else{
io.sockets.in(socket.id).emit('senddockerodeoutstart', 'Building ' + tag);
docker.modem.followProgress(output, onFinished, onProgress);
function onProgress(event) {
io.sockets.in(socket.id).emit('senddockerodeout', event);
}
function onFinished(err, output) {
if (err) return;
io.sockets.in(socket.id).emit('senddockerodeoutdone', 'Finished Build process for ' + repo + ' at ' + checkout);
console.log('Finished building ' + repo + ' at ' + checkout);
rmdir(tempfolder);
}
}
});
}
});
}
// Build and push an encrypto image with a stack in it
function buildencrypto(tag,pass,template,dockeruser,dockerpass){
var tarStream = tar.pack('/usr/src/Taisun/buildlocal/encrypto/');
docker.buildImage(tarStream, {
t: tag,
buildargs: {
"INPUT": template,
"PASS": pass