-
Notifications
You must be signed in to change notification settings - Fork 13
/
sailor.py
1579 lines (1307 loc) · 53.4 KB
/
sailor.py
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
#!/usr/bin/env python3
"""
Sailor: A tool to deploy mutiple sites or apps on a single server
"""
try:
from sys import version_info
assert version_info >= (3, 6)
except AssertionError:
exit("Sailor requires Python >= 3.6")
import sys
import click
import json
import yaml
import configparser
from click import secho as echo
from collections import defaultdict, deque
from datetime import datetime
from fcntl import fcntl, F_SETFL, F_GETFL
from glob import glob
from hashlib import md5
from multiprocessing import cpu_count
from os import chmod, getgid, getuid, symlink, unlink, remove, stat, listdir, environ, makedirs, O_NONBLOCK
from os.path import abspath, basename, dirname, exists, getmtime, join, realpath, splitext
from re import sub
import re
from shutil import copyfile, rmtree, which
from socket import socket, AF_INET, SOCK_STREAM
from sys import argv, stdin, stdout, stderr, version_info, exit
from stat import S_IRUSR, S_IWUSR, S_IXUSR
from subprocess import call, check_output, Popen, STDOUT, PIPE
from tempfile import NamedTemporaryFile
from traceback import format_exc
from time import sleep
import urllib.request
from urllib.request import urlopen
from pwd import getpwuid
from grp import getgrgid
# -----------------------------------------------------------------------------
NAME = "Sailor"
VERSION = "0.12.0"
VALID_RUNTIME = ["python", "node", "static", "shell"]
BOX_SCRIPT = realpath(__file__)
BOX_ROOT = environ.get('BOX_ROOT', environ['HOME'])
BOX_BIN = join(environ['HOME'], 'bin')
APP_ROOT = abspath(join(BOX_ROOT, "apps"))
DOT_ROOT = abspath(join(BOX_ROOT, ".sailor"))
ENV_ROOT = abspath(join(DOT_ROOT, "envs"))
GIT_ROOT = abspath(join(DOT_ROOT, "repos"))
LOG_ROOT = abspath(join(DOT_ROOT, "logs"))
NGINX_ROOT = abspath(join(DOT_ROOT, "nginx"))
METRICS_ROOT = abspath(join(DOT_ROOT, "metrics"))
SETTINGS_ROOT = abspath(join(DOT_ROOT, "settings"))
UWSGI_AVAILABLE = abspath(join(DOT_ROOT, "uwsgi-available"))
UWSGI_ENABLED = abspath(join(DOT_ROOT, "uwsgi-enabled"))
UWSGI_ROOT = abspath(join(DOT_ROOT, "uwsgi"))
ACME_ROOT = environ.get('ACME_ROOT', join(environ['HOME'], '.acme.sh'))
ACME_WWW = abspath(join(DOT_ROOT, "acme"))
UWSGI_LOG_MAXSIZE = '1048576'
# deeploy info file
DEPLOYINFO_FILE = join(DOT_ROOT, "DEPLOYINFO")
if 'sbin' not in environ['PATH']:
environ['PATH'] = "/usr/local/sbin:/usr/sbin:/sbin:" + environ['PATH']
if BOX_BIN not in environ['PATH']:
environ['PATH'] = BOX_BIN + ":" + environ['PATH']
CRON_REGEXP = "^((?:(?:\*\/)?\d+)|\*) ((?:(?:\*\/)?\d+)|\*) ((?:(?:\*\/)?\d+)|\*) ((?:(?:\*\/)?\d+)|\*) ((?:(?:\*\/)?\d+)|\*) (.*)$"
# -----------------------------------------------------------------------------
# To disable nginx when process.web.server_name = '_'
# It will use UWSGI server as is
# it also requires 'process.web.server_port'
SKIP_NGINX_USE_UWSGI_SERVER_NAME = "_"
# NGINX
NGINX_TEMPLATE = """
upstream $APP {
server $NGINX_SOCKET;
}
server {
listen $NGINX_IPV6_ADDRESS:80;
listen $NGINX_IPV4_ADDRESS:80;
location ^~ /.well-known/acme-challenge {
allow all;
root ${ACME_WWW};
}
$INTERNAL_NGINX_COMMON
}
"""
NGINX_HTTPS_ONLY_TEMPLATE = """
upstream $APP {
server $NGINX_SOCKET;
}
server {
listen $NGINX_IPV6_ADDRESS:80;
listen $NGINX_IPV4_ADDRESS:80;
server_name $NGINX_SERVER_NAME;
location ^~ /.well-known/acme-challenge {
allow all;
root ${ACME_WWW};
}
location / {
return 301 https://$server_name$request_uri;
}
}
server {
$INTERNAL_NGINX_COMMON
}
"""
NGINX_COMMON_FRAGMENT = """
listen $NGINX_IPV6_ADDRESS:$NGINX_SSL;
listen $NGINX_IPV4_ADDRESS:$NGINX_SSL;
ssl_certificate $NGINX_ROOT/$APP.crt;
ssl_certificate_key $NGINX_ROOT/$APP.key;
server_name $NGINX_SERVER_NAME;
# Enable gzip compression
gzip on;
gzip_proxied any;
gzip_types text/plain text/xml text/css application/javascript application/x-javascript text/javascript application/json application/xml+rss application/atom+xml;
gzip_comp_level 7;
gzip_min_length 2048;
gzip_vary on;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
$INTERNAL_NGINX_CUSTOM_CLAUSES
$INTERNAL_NGINX_STATIC_CLAUSES
$INTERNAL_NGINX_STATIC_MAPPINGS
$INTERNAL_NGINX_PORTMAP
"""
NGINX_PORTMAP_FRAGMENT = """
location / {
$INTERNAL_NGINX_UWSGI_SETTINGS
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header X-Request-Start $msec;
$NGINX_ACL
}
"""
NGINX_ACME_FIRSTRUN_TEMPLATE = """
server {
listen $NGINX_IPV6_ADDRESS:80;
listen $NGINX_IPV4_ADDRESS:80;
server_name $NGINX_SERVER_NAME;
location ^~ /.well-known/acme-challenge {
allow all;
root ${ACME_WWW};
}
}
"""
INTERNAL_NGINX_STATIC_MAPPING = """
location $static_url {
sendfile on;
sendfile_max_chunk 1m;
tcp_nopush on;
directio 8m;
aio threads;
alias $static_path;
}
"""
INTERNAL_NGINX_UWSGI_SETTINGS = """
uwsgi_pass $APP;
uwsgi_param QUERY_STRING $query_string;
uwsgi_param REQUEST_METHOD $request_method;
uwsgi_param CONTENT_TYPE $content_type;
uwsgi_param CONTENT_LENGTH $content_length;
uwsgi_param REQUEST_URI $request_uri;
uwsgi_param PATH_INFO $document_uri;
uwsgi_param DOCUMENT_ROOT $document_root;
uwsgi_param SERVER_PROTOCOL $server_protocol;
uwsgi_param REMOTE_ADDR $remote_addr;
uwsgi_param REMOTE_PORT $remote_port;
uwsgi_param SERVER_ADDR $server_addr;
uwsgi_param SERVER_PORT $server_port;
uwsgi_param SERVER_NAME $server_name;
"""
INTERNAL_NGINX_STATIC_CLAUSES = """
# static: html & php
root $html_root;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ =404;
}
# Pass PHP scripts to PHP-FPM
location ~* \.php$ {
fastcgi_index index.php;
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
"""
# -----------------------------------------------------------------------------
def utcnow():
return datetime.utcnow()
def print_title(title=None, app=None):
print("-" * 80)
print("Sailor v%s" % VERSION)
if app:
print("App: %s" % app)
if title:
print(title)
print(" ")
def sanitize_app_name(app):
"""Sanitize the app name and build matching path"""
return "".join(c for c in app if c.isalnum() or c in ('.', '_', '-')).rstrip().lstrip('/')
def _error(msg):
echo(msg, fg="red")
exit(1)
def check_app(app):
"""Utility function for error checking upon command startup."""
app = sanitize_app_name(app)
if not exists(join(APP_ROOT, app)):
_error("ERROR: app '%s' not found." % app)
def get_free_port(address=""):
"""Find a free TCP port (entirely at random)"""
s = socket(AF_INET, SOCK_STREAM)
s.bind((address, 0))
port = s.getsockname()[1]
s.close()
return port
def setup_authorized_keys(ssh_fingerprint, script_path, pubkey):
"""Sets up an authorized_keys file to redirect SSH commands"""
authorized_keys = join(environ['HOME'], '.ssh', 'authorized_keys')
if not exists(dirname(authorized_keys)):
makedirs(dirname(authorized_keys))
# Restrict features and force all SSH commands to go through our script
with open(authorized_keys, 'a') as h:
h.write(
"""command="FINGERPRINT={ssh_fingerprint:s} NAME=default {script_path:s} $SSH_ORIGINAL_COMMAND",no-agent-forwarding,no-user-rc,no-X11-forwarding,no-port-forwarding {pubkey:s}\n""".format(**locals()))
chmod(dirname(authorized_keys), S_IRUSR | S_IWUSR | S_IXUSR)
chmod(authorized_keys, S_IRUSR | S_IWUSR)
def install_acme_sh():
""" Install acme.sh for letsencrypt """
if exists(ACME_ROOT):
return
echo("-------> Installing acme.sh", fg="green")
call("curl https://get.acme.sh | sh -s", cwd=BOX_ROOT, shell=True)
def write_deployinfo(app, props:dict):
""" To write deploy info """
config = configparser.ConfigParser()
config.optionxform = str
if exists(DEPLOYINFO_FILE):
config.read(DEPLOYINFO_FILE)
if not config.has_section(app):
config.add_section(app)
for k, v in props.items():
config.set(app, k, str(v))
with open(DEPLOYINFO_FILE, "w+") as f:
config.write(f)
def read_deployinfo(app):
""" To read deploy info """
config = configparser.ConfigParser()
config.optionxform = str
if exists(DEPLOYINFO_FILE):
config.read(DEPLOYINFO_FILE)
if config.has_section(app):
return {o: config.get(app, o) for o in config.options(app)}
return {}
def _get_env(app):
env_file = join(SETTINGS_ROOT, app, "ENV")
if not exists(env_file):
with open(env_file, 'w') as f:
f.write('')
config = configparser.ConfigParser()
config.optionxform = str
config.read(env_file)
return config
def read_settings(app, section):
data = json.loads(json.dumps(_get_env(app)._sections.get(section)))
return {} if not data else data
def write_settings(app, section, data):
env_file = join(SETTINGS_ROOT, app, "ENV")
env = _get_env(app)
if section not in env:
env.add_section(section)
[env.set(section, k.upper(), str(v)) for k,v in data.items()]
env.write(open(env_file, "w"))
def expandvars(buffer, env, default=None, skip_escaped=False):
"""expand shell-style environment variables in a buffer"""
def replace_var(match):
return env.get(match.group(2) or match.group(1), match.group(0) if default is None else default)
pattern = (r'(?<!\\)' if skip_escaped else '') + r'\$(\w+|\{([^}]*)\})'
return sub(pattern, replace_var, buffer)
def command_output(cmd):
"""executes a command and grabs its output, if any"""
try:
env = environ
return str(check_output(cmd, stderr=STDOUT, env=env, shell=True))
except:
return ""
def parse_settings(filename, env={}):
"""Parses a settings file and returns a dict with environment variables"""
if not exists(filename):
return {}
with open(filename, 'r') as settings:
for line in settings:
if '#' == line[0] or len(line.strip()) == 0: # ignore comments and newlines
continue
try:
k, v = map(lambda x: x.strip(), line.split("=", 1))
env[k] = expandvars(v, env)
except:
echo("Error: malformed setting '{}', ignoring file.".format(line), fg='red')
return {}
return env
def get_config(app):
""" Return the info from sailor.yml """
config_file = join(APP_ROOT, app, "sailor.yml")
with open(config_file) as f:
config = yaml.safe_load(f)["apps"]
for c in config:
if app == c["name"]:
return c
_error("App '%s' is missing or didn't match any app 'name' in sailor.yml." % app)
def get_app_processes(app):
""" Returns the applications to run """
return {k.lower(): v for k,v in get_config(app).get('process', {}).items()}
def parse_app_processes(app):
approc = get_app_processes(app)
proc = {}
for k, v in approc.items():
if isinstance(v, dict):
# Skip if the worker is !enabled -> disabled .
# by default it's enabled. Must set 'enabled=false' to disable
if v.get('enabled') is False:
continue
if "cmd" not in v:
_error("Missing 'cmd' in %s:%s" % (app, k))
if "workers" not in v:
v["workers"] = 1
proc[k] = v
else:
proc[k] = {
"cmd": v,
"workers": 1
}
if "web" in proc:
sn = proc["web"].get("server_name")
if sn:
proc["web"]["server_name"] = sn if isinstance(sn, list) else [sn]
else:
cdata = sanitize_config_data(get_config(app))
if "SERVER_NAME" in cdata:
sn = cdata.get("SERVER_NAME") or cdata.get("NGINX_SERVER_NAME")
if sn:
proc["web"]["server_name"] = [sn]
if not proc["web"].get("server_name"):
_error("missing 'process.web.server_name' in app: %s" % app)
# cron
if "cron" in proc:
# verify cron patterns
cmd = proc["cron"]["cmd"]
limits = [59, 24, 31, 12, 7]
matches = re.match(CRON_REGEXP, cmd).groups()
if matches:
for i in range(len(limits)):
if int(matches[i].replace("*/", "").replace("*", "1")) > limits[i]:
_error("invalid cron command 'cron.cmd' in app: %s" % app)
# cron must have 1 worker
if proc["cron"].get("workers") != 1:
proc["cron"]["workers"] = 1
return proc
def get_app_config(app):
""" Turn config into ENV """
config = get_config(app)
if "process" not in config:
_error("missing 'process' for app: %s" % app)
if "web" in config["process"]:
if isinstance(config["process"]["web"], dict):
if not config["process"]["web"].get("server_name"):
_error("missing 'process.web.server_name' in app: %s" % app)
elif "server_name" not in config:
_error("missing 'server_name' in app: %s" % app)
cdata = sanitize_config_data(config)
processes = parse_app_processes(app)
# Remap keys
mapper = {
"SERVER_NAME": "NGINX_SERVER_NAME",
"STATIC_PATHS": "NGINX_STATIC_PATHS",
"HTTPS_ONLY": "NGINX_HTTPS_ONLY",
"THREADS": "UWSGI_THREADS",
"GEVENT": "UWSGI_GEVENT",
"ASYNCIO": "UWSGI_ASYNCIO"
}
for k, v in mapper.items():
if k in cdata and v not in cdata:
cdata[v] = cdata[k]
if "web" in processes:
_wp = processes["web"]
sn = _wp.get("server_name")[0]
cdata["SERVER_NAME"] = sn
cdata["NGINX_SERVER_NAME"] = sn
# skip nginx and use uwsgi server as is
# server_name must be '_'
# server_port must exist
sp = _wp.get("server_port")
if sn.strip() == SKIP_NGINX_USE_UWSGI_SERVER_NAME:
if not sp:
_error("missing 'process.web.server_port' when 'process.web.server_name' is '_'")
cdata.update({
"SERVER_PORT": str(sp),
"PORT": str(sp),
"BIND_ADDRESS": "0.0.0.0",
"SSL": False,
"SSL_ISSUER": None,
"HTTPS_ONLY": False,
})
return cdata
def sanitize_config_data(config):
env = {}
# keys to remove from the config
for k in ["env", "scripts", "process"]:
if k in config:
del config[k]
for k, v in config.items():
if isinstance(v, dict):
env.update({("%s_%s" % (k, vk)).upper(): vv for vk, vv in v.items()})
else:
env[k.upper()] = v
return env
def get_app_env(app):
return get_config(app).get("env", {})
def human_size(fsize, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
return "{:.2f}{}".format(float(fsize), units[0]) if fsize < 1024 else human_size(fsize / 1024, units[1:])
def get_app_metrics(app):
metrics_dir = join(METRICS_ROOT, app)
met = {
"avg": "core.avg_response_time",
"rss": "rss_size",
"vsz": "vsz_size",
"tx": "core.total_tx"
}
metrics = {}
for fk, fv in met.items():
f2 = join(metrics_dir, fv)
try:
if exists(f2):
with open(f2) as f:
v = f.read().strip().split("\n")
metrics[fk] = human_size(int(v[0])) if len(v) > 1 else "-"
else:
metrics[fk] = "-"
except:
pass
return metrics
def get_app_runtime(app):
app_path = join(APP_ROOT, app)
config = get_app_config(app)
runtime = config.get("RUNTIME")
if runtime and runtime.lower() in VALID_RUNTIME:
return runtime.lower()
if exists(join(app_path, 'requirements.txt')):
return "python"
elif exists(join(app_path, 'package.json')):
return "node"
return "static"
def run_app_scripts(app, script_type):
cwd = join(APP_ROOT, app)
config = get_config(app)
runtime = get_app_runtime(app)
if "scripts" in config and script_type in config["scripts"]:
scripts = config["scripts"][script_type]
env = get_app_env(app)
echo("-------> Running scripts: [%s] ..." % script_type, fg="green")
# In python environment, execute everything in the virtualenv
if runtime == "python":
venv = join(join(ENV_ROOT, app), 'bin', 'activate');
scripts.insert(0, '. %s' % venv)
scripts.append("deactivate")
cmds = ("; ".join(scripts)).rstrip(";") + ";"
scripts = [cmds]
for cmd in scripts:
call(cmd, cwd=cwd, env=env, shell=True)
def deploy_app(app, deltas={}, newrev=None, release=False):
"""Deploy an app by resetting the work directory"""
app_path = join(APP_ROOT, app)
env_path = join(ENV_ROOT, app)
log_path = join(LOG_ROOT, app)
conf_path = join(SETTINGS_ROOT, app)
# list of paths that must exist
ensure_paths = [env_path, log_path, conf_path]
env = {
'GIT_WORK_DIR': app_path
}
if exists(app_path):
echo("-------> Deploying app '{}'".format(app), fg='green')
call('git fetch --quiet', cwd=app_path, env=env, shell=True)
if newrev:
write_deployinfo(app, {"revision": newrev, "received": utcnow(), "deployed": 0, "stopped": 0})
call('git reset --hard {}'.format(newrev), cwd=app_path, env=env, shell=True)
write_deployinfo(app, {"deployed": utcnow(), "stopped": 0})
call('git submodule init', cwd=app_path, env=env, shell=True)
call('git submodule update', cwd=app_path, env=env, shell=True)
config = get_config(app)
workers = parse_app_processes(app)
if not config:
_error("Invalid sailor.yml for app '%s'." % app)
elif not workers:
_error("Invalid sailor.yml - missing 'processes'")
else:
# ensure path exist
for p in ensure_paths:
if not exists(p):
makedirs(p)
runtime = get_app_runtime(app)
env2 = get_app_config(app)
if not runtime:
echo("-------> Could not detect runtime!", fg="red")
else:
echo("-------> [%s] app detected." % runtime.upper(), fg="green")
# Sanity check
if "web" in workers:
# domain name
if "NGINX_SERVER_NAME" not in env2:
_error("missing 'server_name' when there is a 'web' process")
if runtime == "static":
_cmd = workers["web"].get("cmd")
if not _cmd or not _cmd.startswith("/"):
_error("for static site the webroot must start with a '/' (slash), instead '%s' provided" % _cmd)
# Setup runtime
# python
if runtime == "python":
setup_python_runtime(app, deltas)
# node
elif runtime == "node":
setup_node_runtime(app, deltas)
# static html/php, shell
elif runtime in ["static", "shell"]:
setup_shell_runtime(app, deltas)
# Scripts ==
# Once on git push
if release is True:
run_app_scripts(app, "release")
run_app_scripts(app, "predeploy")
spawn_app(app, deltas)
run_app_scripts(app, "postdeploy")
else:
echo("Error: app '{}' not found.".format(app), fg='red')
def get_spawn_env(app):
env = {}
# base config from sailor.yml
env.update(get_app_config(app))
# Load environment variables shipped with repo (if any)
env.update(get_app_env(app))
# Override with custom settings (if any)
env.update(read_settings(app, 'CUSTOM'))
return env
def setup_node_runtime(app, deltas={}):
"""Deploy a Node application"""
config = get_app_config(app)
virtualenv_path = join(ENV_ROOT, app)
node_path = join(ENV_ROOT, app, "node_modules")
node_path_tmp = join(APP_ROOT, app, "node_modules")
node_modules_symlink = join(APP_ROOT, app, "node_modules")
npm_prefix = abspath(join(node_path, ".."))
deps = join(APP_ROOT, app, 'package.json')
first_time = False
if not exists(node_path):
echo("-------> Creating node_modules for '{}'".format(app), fg='green')
makedirs(node_path)
first_time = True
env = {
'RUNTIME_VERSION': config.get("RUNTIME_VERSION"),
'VIRTUAL_ENV': virtualenv_path,
'NODE_PATH': node_path,
'NPM_CONFIG_PREFIX': npm_prefix,
"PATH": ':'.join([join(virtualenv_path, "bin"), join(node_path, ".bin"), environ['PATH']])
}
version = env.get("RUNTIME_VERSION")
print("NODE RUNTIME VERSION 2", version)
if version:
node_binary = join(virtualenv_path, "bin", "node")
installed = check_output("{} -v".format(node_binary), cwd=join(APP_ROOT, app), env=env,
shell=True).decode("utf8").rstrip("\n") if exists(node_binary) else ""
if not installed.endswith(version):
started = glob(join(UWSGI_ENABLED, '{}*.ini'.format(app)))
if installed and len(started):
echo("Warning: Can't update node with app running. Stop the app & retry.")
else:
echo("-------> Installing node version '{RUNTIME_VERSION:s}' using nodeenv".format(**env))
call("nodeenv --prebuilt --node={RUNTIME_VERSION:s} --clean-src --force {VIRTUAL_ENV:s}".format(
**env), cwd=virtualenv_path, env=env, shell=True)
else:
echo("-------> Node is installed at {}.".format(version))
if exists(deps):
if first_time or getmtime(deps) > getmtime(node_path):
copyfile(join(APP_ROOT, app, 'package.json'), join(ENV_ROOT, app, 'package.json'))
if not exists(node_modules_symlink):
symlink(node_path, node_modules_symlink)
echo("-------> Running npm for '{}'".format(app))
call('npm install --prefix {} --package-lock=false'.format(npm_prefix), cwd=join(APP_ROOT, app), env=env, shell=True)
def setup_python_runtime(app, deltas={}):
"""Deploy a Python application"""
virtualenv_path = join(ENV_ROOT, app)
requirements = join(APP_ROOT, app, 'requirements.txt')
activation_script = join(virtualenv_path, 'bin', 'activate_this.py')
config = get_app_config(app)
version = int(config.get("RUNTIME_VERSION", "3"))
first_time = False
if not exists(activation_script):
echo("-------> Creating virtualenv for '{}'".format(app), fg='green')
if not exists(virtualenv_path):
makedirs(virtualenv_path)
call('virtualenv --python=python{version:d} {app:s}'.format(**locals()), cwd=ENV_ROOT, shell=True)
first_time = True
exec(open(activation_script).read(), dict(__file__=activation_script))
if first_time or getmtime(requirements) > getmtime(virtualenv_path):
echo("-------> Running pip for '{}'".format(app), fg='green')
call('pip install -r {} --upgrade'.format(requirements), cwd=virtualenv_path, shell=True)
def setup_shell_runtime(app, deltas={}):
pass
def spawn_app(app, deltas={}):
"""Create all workers for an app"""
app_path = join(APP_ROOT, app)
runtime = get_app_runtime(app)
workers = parse_app_processes(app)
worker_count = {k: v["workers"] for k,v in workers.items()}
if "cron" in worker_count:
worker_count["cron"] = 1
virtualenv_path = join(ENV_ROOT, app)
scaling = read_settings(app, 'SCALING')
# Bootstrap environment
env = {
'APP': app,
'LOG_ROOT': LOG_ROOT,
'HOME': environ['HOME'],
'USER': environ.get("USER"),
'PATH': ':'.join([join(virtualenv_path, 'bin'), environ['PATH']]),
'PWD': app_path,
'VIRTUAL_ENV': virtualenv_path,
'SSL': True,
'SSL_ISSUER': 'letsencrypt',
'HTTPS_ONLY': True,
'AUTO_RESTART': False,
'WSGI': True,
'NGINX_IPV4_ADDRESS': '0.0.0.0',
'NGINX_IPV6_ADDRESS': '[::]',
'BIND_ADDRESS': '127.0.0.1'
}
# add node path if present
node_path = join(virtualenv_path, "node_modules")
if exists(node_path):
env["NODE_PATH"] = node_path
env["PATH"] = ':'.join([join(node_path, ".bin"), env['PATH']])
# Update the env with app env
env.update(get_spawn_env(app))
if env.get("HTTPS_ONLY") is True and env.get("SSL") is False:
env["SSL"] = True
if 'web' in workers:
# Pick a port if none defined
if 'PORT' not in env or not env.get("PORT"):
env['PORT'] = str(get_free_port())
echo("-------> picking free port %s" % env["PORT"])
# NGINX: Set up nginx if we have NGINX_SERVER_NAME set
if env.get('NGINX_SERVER_NAME') and env.get('NGINX_SERVER_NAME', '').strip() != SKIP_NGINX_USE_UWSGI_SERVER_NAME:
nginx = command_output("nginx -V")
nginx_ssl = "443 ssl"
if "--with-http_v2_module" in nginx:
nginx_ssl += " http2"
elif "--with-http_spdy_module" in nginx and "nginx/1.6.2" not in nginx:
nginx_ssl += " spdy"
nginx_conf = join(NGINX_ROOT, "%s.conf" % app)
env.update({
'NGINX_SSL': nginx_ssl,
'NGINX_ROOT': NGINX_ROOT,
'ACME_WWW': ACME_WWW,
})
env['INTERNAL_NGINX_UWSGI_SETTINGS'] = 'proxy_pass http://{BIND_ADDRESS:s}:{PORT:s};'.format(**env)
env['NGINX_SOCKET'] = "{BIND_ADDRESS:s}:{PORT:s}".format(**env)
echo("-------> nginx will look for app '{}' on {}".format(app, env['NGINX_SOCKET']))
# SSL
if env.get("SSL") is True:
if not exists(join(ACME_ROOT, "acme.sh")):
echo("!!!!!!!FATAL ERROR!!!!!!!.", fg='red')
echo("!!!!!!!FATAL ERROR: missing 'acme.sh' script for HTTPS", fg='red')
echo("!!!!!!!FATAL ERROR: exited.", fg='red')
exit(1)
domain = env['NGINX_SERVER_NAME'].split()[0]
key = join(NGINX_ROOT, "%s.%s" % (app, 'key'))
crt = join(NGINX_ROOT, "%s.%s" % (app, 'crt'))
ssl_issuer = env.get("SSL_ISSUER", "letsencrypt") # letsencrypt|zerossl
acme = ACME_ROOT
www = ACME_WWW
# if this is the first run there will be no nginx conf yet
# create a basic conf stub just to serve the acme auth
if not exists(nginx_conf):
echo("-------> writing temporary nginx conf")
buffer = expandvars(NGINX_ACME_FIRSTRUN_TEMPLATE, env)
with open(nginx_conf, "w") as h:
h.write(buffer)
sleep(2)
if not exists(key) or not exists(join(ACME_ROOT, domain, domain + ".key")):
echo("-------> getting '%s' ssl certificate" % ssl_issuer)
call('{acme:s}/acme.sh --issue -d {domain:s} -w {www:s} --server {ssl_issuer:s}'.format(**locals()), shell=True)
call('{acme:s}/acme.sh --install-cert -d {domain:s} --key-file {key:s} --fullchain-file {crt:s}'.format(**locals()), shell=True)
if exists(join(ACME_ROOT, domain)) and not exists(join(ACME_WWW, app)):
symlink(join(ACME_ROOT, domain), join(ACME_WWW, app))
else:
echo("-------> letsencrypt certificate already installed")
# restrict access to server from CloudFlare IP addresses
acl = []
env['NGINX_ACL'] = " ".join(acl)
env['INTERNAL_NGINX_STATIC_MAPPINGS'] = ''
env['INTERNAL_NGINX_STATIC_CLAUSES'] = ''
# static requires just the path. It will set the url as web root
if runtime == 'static':
static_path = workers['web']["cmd"].strip("/").rstrip("/")
html_root = join(app_path, static_path)
env['INTERNAL_NGINX_STATIC_CLAUSES'] = expandvars(INTERNAL_NGINX_STATIC_CLAUSES, locals())
# Get a mapping of [/url1:path1, /url2:path2, ...] ...
static_paths = env.get('NGINX_STATIC_PATHS', [])
if not isinstance(static_paths, list):
static_paths = []
if len(static_paths):
try:
for item in static_paths:
static_url, static_path = item.split(':', 2)
if static_path[0] != '/':
static_path = join(app_path, static_path)
env['INTERNAL_NGINX_STATIC_MAPPINGS'] = env['INTERNAL_NGINX_STATIC_MAPPINGS'] + \
expandvars(INTERNAL_NGINX_STATIC_MAPPING, locals())
except Exception as e:
echo(
"Error {} in static_paths spec: should be a list [/url1:path1, /url2:path2, ...], ignoring.".format(e), fg="red")
env['INTERNAL_NGINX_STATIC_MAPPINGS'] = ''
env['INTERNAL_NGINX_CUSTOM_CLAUSES'] = expandvars(
open(join(app_path, env["NGINX_INCLUDE_FILE"])).read(), env) if env.get("NGINX_INCLUDE_FILE") else ""
env['INTERNAL_NGINX_PORTMAP'] = ""
if "static" not in runtime:
env['INTERNAL_NGINX_PORTMAP'] = expandvars(NGINX_PORTMAP_FRAGMENT, env)
env['INTERNAL_NGINX_COMMON'] = expandvars(NGINX_COMMON_FRAGMENT, env)
echo("-------> nginx will map app '{}' to hostname '{}'".format(app, env['NGINX_SERVER_NAME']))
if env.get('HTTPS_ONLY') is True:
buffer = expandvars(NGINX_HTTPS_ONLY_TEMPLATE, env)
echo("-------> nginx will redirect all requests to hostname '{}' to HTTPS".format(env['NGINX_SERVER_NAME']))
else:
buffer = expandvars(NGINX_TEMPLATE, env)
with open(nginx_conf, "w") as h:
h.write(buffer)
# prevent broken config from breaking other deploys
try:
nginx_config_test = str(check_output("nginx -t 2>&1 | grep {}".format(app), env=environ, shell=True))
except:
nginx_config_test = None
if nginx_config_test:
echo("!!!!!!!FATAL ERROR!!!!!!!", fg='red')
echo("!!!!!!!FATAL ERROR: [nginx config] {}".format(nginx_config_test), fg='red')
echo("!!!!!!!FATAL ERROR: removing broken nginx config.", fg='red')
unlink(nginx_conf)
echo("!!!!!!!FATAL ERROR: exited.", fg='red')
exit(1)
# Configured worker count
if scaling:
worker_count.update({k.lower(): int(v) for k, v in scaling.items() if k.lower() in workers})
to_create = {}
to_destroy = {}
for k, v in worker_count.items():
to_create[k] = range(1, worker_count[k] + 1)
if k in deltas and deltas[k]:
to_create[k] = range(1, worker_count[k] + deltas[k] + 1)
if deltas[k] < 0:
to_destroy[k] = range(worker_count[k], worker_count[k] + deltas[k], -1)
worker_count[k] = worker_count[k]+deltas[k]
# Cleanup env
for k, v in list(env.items()):
if k.startswith('INTERNAL_'):
del env[k]
# Save current settings
write_settings(app, 'ENV', env)
write_settings(app, 'SCALING', worker_count)
# auto restart
if env.get("AUTO_RESTART", False) is True:
echo("-------> auto-restart triggered", fg="green")
cleanup_uwsgi_enabled_ini(app)
# Create new workers
for k, v in to_create.items():
for w in v:
enabled = join(UWSGI_ENABLED, '{app:s}___{k:s}.{w:d}.ini'.format(**locals()))
if not exists(enabled):
echo("-------> spawning '{app:s}:{k:s}.{w:d}'".format(**locals()), fg='green')
_cmd = workers[k]["cmd"]
spawn_worker(app, k, _cmd, env, w)
# Remove unnecessary workers (leave logfiles)
for k, v in to_destroy.items():
for w in v:
enabled = join(UWSGI_ENABLED, '{app:s}___{k:s}.{w:d}.ini'.format(**locals()))
if exists(enabled):
echo("-------> terminating '{app:s}:{k:s}.{w:d}'".format(**locals()))
unlink(enabled)
return env
def spawn_worker(app, kind, command, env, ordinal=1):
"""Set up and deploy a single worker of a given kind"""
app_kind = kind
runtime = get_app_runtime(app)
config = get_app_config(app)
if app_kind == "web":
app_kind = runtime
if runtime == "python":
app_kind = "wsgi" if config.get("WSGI", True) is True else "shell"
elif runtime == "node":
app_kind = "shell"
env['PROC_TYPE'] = app_kind
env_path = join(ENV_ROOT, app)
metrics_path = join(METRICS_ROOT, app)
available = join(UWSGI_AVAILABLE, '{app:s}___{kind:s}.{ordinal:d}.ini'.format(**locals()))
enabled = join(UWSGI_ENABLED, '{app:s}___{kind:s}.{ordinal:d}.ini'.format(**locals()))
log_file = join(LOG_ROOT, app, app_kind)
# Create metrics dir
if not exists(metrics_path):
makedirs(metrics_path)
settings = [
('chdir',join(APP_ROOT, app)),
('master','true'),
('project',app),
('max-requests',env.get('UWSGI_MAX_REQUESTS', '1024')),
('listen',env.get('UWSGI_LISTEN', '16')),
('processes',env.get('UWSGI_PROCESSES', '1')),
('procname-prefix','{app:s}:{kind:s}'.format(**locals())),
('enable-threads',env.get('UWSGI_ENABLE_THREADS', 'true').lower()),
('log-x-forwarded-for',env.get('UWSGI_LOG_X_FORWARDED_FOR', 'false').lower()),
('log-maxsize',env.get('UWSGI_LOG_MAXSIZE', UWSGI_LOG_MAXSIZE)),
('logto2','{log_file:s}.{ordinal:d}.log'.format(**locals())),
('log-backupname','{log_file:s}.{ordinal:d}.log.old'.format(**locals())),
('metrics-dir',metrics_path),
('uid',getpwuid(getuid()).pw_name),
('gid',getgrgid(getgid()).gr_name),
('logfile-chown','%s:%s' % (getpwuid(getuid()).pw_name, getgrgid(getgid()).gr_name)),
('logfile-chmod','640')
]
# only add virtualenv to uwsgi if it's a real virtualenv
if exists(join(env_path, "bin", "activate_this.py")):
settings.append(('virtualenv', env_path))