-
Notifications
You must be signed in to change notification settings - Fork 0
/
piku.py
executable file
·1706 lines (1408 loc) · 63.3 KB
/
piku.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
"Piku Micro-PaaS"
try:
from sys import version_info
assert version_info >= (3, 7)
except AssertionError:
exit("Piku requires Python 3.7 or above")
from importlib import import_module
from collections import defaultdict, deque
from fcntl import fcntl, F_SETFL, F_GETFL
from glob import glob
from json import loads
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, isdir
from pwd import getpwuid
from grp import getgrgid
from re import sub, match
from shutil import copyfile, rmtree, which
from socket import socket, AF_INET, SOCK_STREAM
from stat import S_IRUSR, S_IWUSR, S_IXUSR
from subprocess import call, check_output, Popen, STDOUT
from sys import argv, stdin, stdout, stderr, version_info, exit, path as sys_path
from tempfile import NamedTemporaryFile
from time import sleep
from traceback import format_exc
from urllib.request import urlopen
from click import argument, group, secho as echo, pass_context, CommandCollection
# === Make sure we can access all system binaries ===
if 'sbin' not in environ['PATH']:
environ['PATH'] = "/usr/local/sbin:/usr/sbin:/sbin:" + environ['PATH']
# === Globals - all tweakable settings are here ===
PIKU_RAW_SOURCE_URL = "https://raw.githubusercontent.com/piku/piku/master/piku.py"
PIKU_ROOT = environ.get('PIKU_ROOT', join(environ['HOME'], '.piku'))
PIKU_BIN = join(environ['HOME'], 'bin')
PIKU_SCRIPT = realpath(__file__)
PIKU_PLUGIN_ROOT = abspath(join(PIKU_ROOT, "plugins"))
APP_ROOT = abspath(join(PIKU_ROOT, "apps"))
DATA_ROOT = abspath(join(PIKU_ROOT, "data"))
ENV_ROOT = abspath(join(PIKU_ROOT, "envs"))
GIT_ROOT = abspath(join(PIKU_ROOT, "repos"))
LOG_ROOT = abspath(join(PIKU_ROOT, "logs"))
NGINX_ROOT = abspath(join(PIKU_ROOT, "nginx"))
CACHE_ROOT = abspath(join(PIKU_ROOT, "cache"))
UWSGI_AVAILABLE = abspath(join(PIKU_ROOT, "uwsgi-available"))
UWSGI_ENABLED = abspath(join(PIKU_ROOT, "uwsgi-enabled"))
UWSGI_ROOT = abspath(join(PIKU_ROOT, "uwsgi"))
UWSGI_LOG_MAXSIZE = '1048576'
ACME_ROOT = environ.get('ACME_ROOT', join(environ['HOME'], '.acme.sh'))
ACME_WWW = abspath(join(PIKU_ROOT, "acme"))
ACME_ROOT_CA = environ.get('ACME_ROOT_CA', 'letsencrypt.org')
# === Make sure we can access piku user-installed binaries === #
if PIKU_BIN not in environ['PATH']:
environ['PATH'] = PIKU_BIN + ":" + environ['PATH']
# pylint: disable=anomalous-backslash-in-string
NGINX_TEMPLATE = """
$PIKU_INTERNAL_PROXY_CACHE_PATH
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};
}
$PIKU_INTERNAL_NGINX_COMMON
}
"""
NGINX_HTTPS_ONLY_TEMPLATE = """
$PIKU_INTERNAL_PROXY_CACHE_PATH
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 {
$PIKU_INTERNAL_NGINX_COMMON
}
"""
# pylint: enable=anomalous-backslash-in-string
NGINX_COMMON_FRAGMENT = r"""
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;
# These are not required under systemd - enable for debugging only
# access_log $LOG_ROOT/$APP/access.log;
# error_log $LOG_ROOT/$APP/error.log;
# Enable gzip compression
gzip on;
gzip_proxied any;
gzip_types text/plain text/xml text/css text/javascript text/js application/x-javascript application/javascript application/json application/xml+rss application/atom+xml image/svg+xml;
gzip_comp_level 7;
gzip_min_length 2048;
gzip_vary on;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
# set a custom header for requests
add_header X-Deployed-By Piku;
$PIKU_INTERNAL_NGINX_CUSTOM_CLAUSES
$PIKU_INTERNAL_NGINX_STATIC_MAPPINGS
$PIKU_INTERNAL_NGINX_CACHE_MAPPINGS
$PIKU_INTERNAL_NGINX_BLOCK_GIT
$PIKU_INTERNAL_NGINX_PORTMAP
"""
NGINX_PORTMAP_FRAGMENT = """
location / {
$PIKU_INTERNAL_NGINX_UWSGI_SETTINGS
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Remote-Address $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};
}
}
"""
PIKU_INTERNAL_NGINX_STATIC_MAPPING = """
location $static_url {
sendfile on;
sendfile_max_chunk 1m;
tcp_nopush on;
directio 8m;
aio threads;
alias $static_path;
try_files $uri $uri.html $uri/ =404;
}
"""
PIKU_INTERNAL_PROXY_CACHE_PATH = """
uwsgi_cache_path $cache_path levels=1:2 keys_zone=$app:20m inactive=$cache_time_expiry max_size=$cache_size use_temp_path=off;
"""
PIKU_INTERNAL_NGINX_CACHE_MAPPING = """
location ~* ^/($cache_prefixes) {
uwsgi_cache $APP;
uwsgi_cache_min_uses 1;
uwsgi_cache_key $host$uri;
uwsgi_cache_valid 200 304 $cache_time_content;
uwsgi_cache_valid 301 307 $cache_time_redirects;
uwsgi_cache_valid 500 502 503 504 0s;
uwsgi_cache_valid any $cache_time_any;
uwsgi_hide_header Cache-Control;
add_header Cache-Control "public, max-age=$cache_time_control";
add_header X-Cache $upstream_cache_status;
$PIKU_INTERNAL_NGINX_UWSGI_SETTINGS
}
"""
PIKU_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 X_FORWARDED_FOR $proxy_add_x_forwarded_for;
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;
"""
CRON_REGEXP = r"^((?:(?:\*\/)?\d+)|\*) ((?:(?:\*\/)?\d+)|\*) ((?:(?:\*\/)?\d+)|\*) ((?:(?:\*\/)?\d+)|\*) ((?:(?:\*\/)?\d+)|\*) (.*)$"
# === Utility functions ===
def sanitize_app_name(app):
"""Sanitize the app name and build matching path"""
app = "".join(c for c in app if c.isalnum() or c in ('.', '_', '-')).rstrip().lstrip('/')
return app
def exit_if_invalid(app):
"""Utility function for error checking upon command startup."""
app = sanitize_app_name(app)
if not exists(join(APP_ROOT, app)):
echo("Error: app '{}' not found.".format(app), fg='red')
exit(1)
return app
def get_free_port(address=""):
"""Find a free TCP port (entirely at random)"""
s = socket(AF_INET, SOCK_STREAM)
s.bind((address, 0)) # lgtm [py/bind-socket-all-network-interfaces]
port = s.getsockname()[1]
s.close()
return port
def get_boolean(value):
"""Convert a boolean-ish string to a boolean."""
return value.lower() in ['1', 'on', 'true', 'enabled', 'yes', 'y']
def write_config(filename, bag, separator='='):
"""Helper for writing out config files"""
with open(filename, 'w') as h:
# pylint: disable=unused-variable
for k, v in bag.items():
h.write('{k:s}{separator:s}{v}\n'.format(**locals()))
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 parse_procfile(filename):
"""Parses a Procfile and returns the worker types. Only one worker of each type is allowed."""
workers = {}
if not exists(filename):
return None
with open(filename, 'r') as procfile:
for line_number, line in enumerate(procfile):
line = line.strip()
if line.startswith("#") or not line:
continue
try:
kind, command = map(lambda x: x.strip(), line.split(":", 1))
# Check for cron patterns
if kind == "cron":
limits = [59, 24, 31, 12, 7]
res = match(CRON_REGEXP, command)
if res:
matches = res.groups()
for i in range(len(limits)):
if int(matches[i].replace("*/", "").replace("*", "1")) > limits[i]:
raise ValueError
workers[kind] = command
except Exception:
echo("Warning: misformatted Procfile entry '{}' at line {}".format(line, line_number), fg='yellow')
if len(workers) == 0:
return {}
# WSGI trumps regular web workers
if 'wsgi' in workers or 'jwsgi' in workers or 'rwsgi' in workers:
if 'web' in workers:
echo("Warning: found both 'wsgi' and 'web' workers, disabling 'web'", fg='yellow')
del workers['web']
return workers
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 Exception:
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 Exception:
echo("Error: malformed setting '{}', ignoring file.".format(line), fg='red')
return {}
return env
def check_requirements(binaries):
"""Checks if all the binaries exist and are executable"""
echo("-----> Checking requirements: {}".format(binaries), fg='green')
requirements = list(map(which, binaries))
echo(str(requirements))
if None in requirements:
return False
return True
def found_app(kind):
"""Helper function to output app detected"""
echo("-----> {} app detected.".format(kind), fg='green')
return True
def do_deploy(app, deltas={}, newrev=None):
"""Deploy an app by resetting the work directory"""
app_path = join(APP_ROOT, app)
procfile = join(app_path, 'Procfile')
log_path = join(LOG_ROOT, app)
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:
call('git reset --hard {}'.format(newrev), cwd=app_path, env=env, shell=True)
call('git submodule init', cwd=app_path, env=env, shell=True)
call('git submodule update', cwd=app_path, env=env, shell=True)
if not exists(log_path):
makedirs(log_path)
workers = parse_procfile(procfile)
if workers and len(workers) > 0:
settings = {}
if "preflight" in workers:
echo("-----> Running preflight.", fg='green')
retval = call(workers["preflight"], cwd=app_path, env=settings, shell=True)
if retval:
echo("-----> Exiting due to preflight command error value: {}".format(retval))
exit(retval)
workers.pop("preflight", None)
if exists(join(app_path, 'requirements.txt')) and found_app("Python"):
settings.update(deploy_python(app, deltas))
elif exists(join(app_path, 'Gemfile')) and found_app("Ruby Application") and check_requirements(['ruby', 'gem', 'bundle']):
settings.update(deploy_ruby(app, deltas))
elif exists(join(app_path, 'package.json')) and found_app("Node") and (
check_requirements(['nodejs', 'npm']) or check_requirements(['node', 'npm']) or check_requirements(['nodeenv'])):
settings.update(deploy_node(app, deltas))
elif exists(join(app_path, 'pom.xml')) and found_app("Java Maven") and check_requirements(['java', 'mvn']):
settings.update(deploy_java_maven(app, deltas))
elif exists(join(app_path, 'build.gradle')) and found_app("Java Gradle") and check_requirements(['java', 'gradle']):
settings.update(deploy_java_gradle(app, deltas))
elif (exists(join(app_path, 'Godeps')) or len(glob(join(app_path, '*.go')))) and found_app("Go") and check_requirements(['go']):
settings.update(deploy_go(app, deltas))
elif exists(join(app_path, 'deps.edn')) and found_app("Clojure CLI") and check_requirements(['java', 'clojure']):
settings.update(deploy_clojure_cli(app, deltas))
elif exists(join(app_path, 'project.clj')) and found_app("Clojure Lein") and check_requirements(['java', 'lein']):
settings.update(deploy_clojure_leiningen(app, deltas))
elif 'release' in workers and 'web' in workers:
echo("-----> Generic app detected.", fg='green')
settings.update(deploy_identity(app, deltas))
elif 'static' in workers:
echo("-----> Static app detected.", fg='green')
settings.update(deploy_identity(app, deltas))
else:
echo("-----> Could not detect runtime!", fg='red')
# TODO: detect other runtimes
if "release" in workers:
echo("-----> Releasing", fg='green')
retval = call(workers["release"], cwd=app_path, env=settings, shell=True)
if retval:
echo("-----> Exiting due to release command error value: {}".format(retval))
exit(retval)
workers.pop("release", None)
else:
echo("Error: Invalid Procfile for app '{}'.".format(app), fg='red')
else:
echo("Error: app '{}' not found.".format(app), fg='red')
def deploy_java_gradle(app, deltas={}):
"""Deploy a Java application using Gradle"""
java_path = join(ENV_ROOT, app)
build_path = join(APP_ROOT, app, 'build')
env_file = join(APP_ROOT, app, 'ENV')
env = {
'VIRTUAL_ENV': java_path,
"PATH": ':'.join([join(java_path, "bin"), join(app, ".bin"), environ['PATH']])
}
if exists(env_file):
env.update(parse_settings(env_file, env))
if not exists(java_path):
makedirs(java_path)
if not exists(build_path):
echo("-----> Building Java Application")
call('gradle build', cwd=join(APP_ROOT, app), env=env, shell=True)
else:
echo("-----> Removing previous builds")
echo("-----> Rebuilding Java Application")
call('gradle clean build', cwd=join(APP_ROOT, app), env=env, shell=True)
return spawn_app(app, deltas)
def deploy_java_maven(app, deltas={}):
"""Deploy a Java application using Maven"""
# TODO: Use jenv to isolate Java Application environments
java_path = join(ENV_ROOT, app)
target_path = join(APP_ROOT, app, 'target')
env_file = join(APP_ROOT, app, 'ENV')
env = {
'VIRTUAL_ENV': java_path,
"PATH": ':'.join([join(java_path, "bin"), join(app, ".bin"), environ['PATH']])
}
if exists(env_file):
env.update(parse_settings(env_file, env))
if not exists(java_path):
makedirs(java_path)
if not exists(target_path):
echo("-----> Building Java Application")
call('mvn package', cwd=join(APP_ROOT, app), env=env, shell=True)
else:
echo("-----> Removing previous builds")
echo("-----> Rebuilding Java Application")
call('mvn clean package', cwd=join(APP_ROOT, app), env=env, shell=True)
return spawn_app(app, deltas)
def deploy_clojure_cli(app, deltas={}):
"""Deploy a Clojure Application"""
virtual = join(ENV_ROOT, app)
target_path = join(APP_ROOT, app, 'target')
env_file = join(APP_ROOT, app, 'ENV')
if not exists(target_path):
makedirs(virtual)
env = {
'VIRTUAL_ENV': virtual,
"PATH": ':'.join([join(virtual, "bin"), join(app, ".bin"), environ['PATH']]),
"CLJ_CONFIG": environ.get('CLJ_CONFIG', join(environ['HOME'], '.clojure')),
}
if exists(env_file):
env.update(parse_settings(env_file, env))
echo("-----> Building Clojure Application")
call('clojure -T:build release', cwd=join(APP_ROOT, app), env=env, shell=True)
return spawn_app(app, deltas)
def deploy_clojure_leiningen(app, deltas={}):
"""Deploy a Clojure Application"""
virtual = join(ENV_ROOT, app)
target_path = join(APP_ROOT, app, 'target')
env_file = join(APP_ROOT, app, 'ENV')
if not exists(target_path):
makedirs(virtual)
env = {
'VIRTUAL_ENV': virtual,
"PATH": ':'.join([join(virtual, "bin"), join(app, ".bin"), environ['PATH']]),
"LEIN_HOME": environ.get('LEIN_HOME', join(environ['HOME'], '.lein')),
}
if exists(env_file):
env.update(parse_settings(env_file, env))
echo("-----> Building Clojure Application")
call('lein clean', cwd=join(APP_ROOT, app), env=env, shell=True)
call('lein uberjar', cwd=join(APP_ROOT, app), env=env, shell=True)
return spawn_app(app, deltas)
def deploy_ruby(app, deltas={}):
"""Deploy a Ruby Application"""
virtual = join(ENV_ROOT, app)
env_file = join(APP_ROOT, app, 'ENV')
env = {
'VIRTUAL_ENV': virtual,
"PATH": ':'.join([join(virtual, "bin"), join(app, ".bin"), environ['PATH']]),
}
if exists(env_file):
env.update(parse_settings(env_file, env))
if not exists(virtual):
echo("-----> Building Ruby Application")
makedirs(virtual)
call('bundle config set --local path $VIRTUAL_ENV', cwd=join(APP_ROOT, app), env=env, shell=True)
else:
echo("------> Rebuilding Ruby Application")
call('bundle install', cwd=join(APP_ROOT, app), env=env, shell=True)
return spawn_app(app, deltas)
def deploy_go(app, deltas={}):
"""Deploy a Go application"""
go_path = join(ENV_ROOT, app)
deps = join(APP_ROOT, app, 'Godeps')
first_time = False
if not exists(go_path):
echo("-----> Creating GOPATH for '{}'".format(app), fg='green')
makedirs(go_path)
# copy across a pre-built GOPATH to save provisioning time
call('cp -a $HOME/gopath {}'.format(app), cwd=ENV_ROOT, shell=True)
first_time = True
if exists(deps):
if first_time or getmtime(deps) > getmtime(go_path):
echo("-----> Running godep for '{}'".format(app), fg='green')
env = {
'GOPATH': '$HOME/gopath',
'GOROOT': '$HOME/go',
'PATH': '$PATH:$HOME/go/bin',
'GO15VENDOREXPERIMENT': '1'
}
call('godep update ...', cwd=join(APP_ROOT, app), env=env, shell=True)
return spawn_app(app, deltas)
def deploy_node(app, deltas={}):
"""Deploy a Node application"""
virtualenv_path = join(ENV_ROOT, app)
node_path = join(ENV_ROOT, app, "node_modules")
node_modules_symlink = join(APP_ROOT, app, "node_modules")
npm_prefix = abspath(join(node_path, ".."))
env_file = join(APP_ROOT, app, 'ENV')
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 = {
'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']])
}
if exists(env_file):
env.update(parse_settings(env_file, env))
# include node binaries on our path
environ["PATH"] = env["PATH"]
version = env.get("NODE_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 version and check_requirements(['nodeenv']):
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.", fg='yellow')
else:
echo("-----> Installing node version '{NODE_VERSION:s}' using nodeenv".format(**env), fg='green')
call("nodeenv --prebuilt --node={NODE_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) and check_requirements(['npm']):
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), fg='green')
call('npm install --prefix {} --package-lock=false'.format(npm_prefix), cwd=join(APP_ROOT, app), env=env, shell=True)
return spawn_app(app, deltas)
def deploy_python(app, deltas={}):
"""Deploy a Python application"""
virtualenv_path = join(ENV_ROOT, app)
requirements = join(APP_ROOT, app, 'requirements.txt')
env_file = join(APP_ROOT, app, 'ENV')
# Set unbuffered output and readable UTF-8 mapping
env = {
'PYTHONUNBUFFERED': '1',
'PYTHONIOENCODING': 'UTF_8:replace'
}
if exists(env_file):
env.update(parse_settings(env_file, env))
# TODO: improve version parsing
# pylint: disable=unused-variable
version = int(env.get("PYTHON_VERSION", "3"))
first_time = False
if not exists(join(virtualenv_path, "bin", "activate")):
echo("-----> Creating virtualenv for '{}'".format(app), fg='green')
try:
makedirs(virtualenv_path)
except FileExistsError:
echo("-----> Env dir already exists: '{}'".format(app), fg='yellow')
call('virtualenv --python=python{version:d} {app:s}'.format(**locals()), cwd=ENV_ROOT, shell=True)
first_time = True
activation_script = join(virtualenv_path, 'bin', 'activate_this.py')
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 {}'.format(requirements), cwd=virtualenv_path, shell=True)
return spawn_app(app, deltas)
def deploy_identity(app, deltas={}):
env_path = join(ENV_ROOT, app)
if not exists(env_path):
makedirs(env_path)
return spawn_app(app, deltas)
def spawn_app(app, deltas={}):
"""Create all workers for an app"""
# pylint: disable=unused-variable
app_path = join(APP_ROOT, app)
procfile = join(app_path, 'Procfile')
workers = parse_procfile(procfile)
workers.pop("preflight", None)
workers.pop("release", None)
ordinals = defaultdict(lambda: 1)
worker_count = {k: 1 for k in workers.keys()}
# the Python virtualenv
virtualenv_path = join(ENV_ROOT, app)
# Settings shipped with the app
env_file = join(APP_ROOT, app, 'ENV')
# Custom overrides
settings = join(ENV_ROOT, app, 'ENV')
# Live settings
live = join(ENV_ROOT, app, 'LIVE_ENV')
# Scaling
scaling = join(ENV_ROOT, app, 'SCALING')
# Bootstrap environment
env = {
'APP': app,
'LOG_ROOT': LOG_ROOT,
'HOME': environ['HOME'],
'USER': environ['USER'],
'PATH': ':'.join([join(virtualenv_path, 'bin'), environ['PATH']]),
'PWD': dirname(env_file),
'VIRTUAL_ENV': virtualenv_path,
}
safe_defaults = {
'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']])
# Load environment variables shipped with repo (if any)
if exists(env_file):
env.update(parse_settings(env_file, env))
# Override with custom settings (if any)
if exists(settings):
env.update(parse_settings(settings, env)) # lgtm [py/modification-of-default-value]
if 'web' in workers or 'wsgi' in workers or 'jwsgi' in workers or 'static' in workers or 'rwsgi' in workers:
# Pick a port if none defined
if 'PORT' not in env:
env['PORT'] = str(get_free_port())
echo("-----> picking free port {PORT}".format(**env))
if get_boolean(env.get('DISABLE_IPV6', 'false')):
safe_defaults.pop('NGINX_IPV6_ADDRESS', None)
echo("-----> nginx will NOT use IPv6".format(**locals()))
# Safe defaults for addressing
for k, v in safe_defaults.items():
if k not in env:
echo("-----> nginx {k:s} will be set to {v}".format(**locals()))
env[k] = v
# Set up nginx if we have NGINX_SERVER_NAME set
if 'NGINX_SERVER_NAME' in env:
# Hack to get around ClickCommand
env['NGINX_SERVER_NAME'] = env['NGINX_SERVER_NAME'].split(',')
env['NGINX_SERVER_NAME'] = ' '.join(env['NGINX_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: # avoid Raspbian bug
nginx_ssl += " spdy"
nginx_conf = join(NGINX_ROOT, "{}.conf".format(app))
env.update({ # lgtm [py/modification-of-default-value]
'NGINX_SSL': nginx_ssl,
'NGINX_ROOT': NGINX_ROOT,
'ACME_WWW': ACME_WWW,
})
# default to reverse proxying to the TCP port we picked
env['PIKU_INTERNAL_NGINX_UWSGI_SETTINGS'] = 'proxy_pass http://{BIND_ADDRESS:s}:{PORT:s};'.format(**env)
if 'wsgi' in workers or 'jwsgi' in workers:
sock = join(NGINX_ROOT, "{}.sock".format(app))
env['PIKU_INTERNAL_NGINX_UWSGI_SETTINGS'] = expandvars(PIKU_INTERNAL_NGINX_UWSGI_SETTINGS, env)
env['NGINX_SOCKET'] = env['BIND_ADDRESS'] = "unix://" + sock
if 'PORT' in env:
del env['PORT']
else:
env['NGINX_SOCKET'] = "{BIND_ADDRESS:s}:{PORT:s}".format(**env)
echo("-----> nginx will look for app '{}' on {}".format(app, env['NGINX_SOCKET']))
domains = env['NGINX_SERVER_NAME'].split()
domain = domains[0]
issuefile = join(ACME_ROOT, domain, "issued-" + "-".join(domains))
key, crt = [join(NGINX_ROOT, "{}.{}".format(app, x)) for x in ['key', 'crt']]
if exists(join(ACME_ROOT, "acme.sh")):
acme = ACME_ROOT
www = ACME_WWW
root_ca = ACME_ROOT_CA
# 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)
if not exists(key) or not exists(issuefile):
echo("-----> getting letsencrypt certificate")
certlist = " ".join(["-d {}".format(d) for d in domains])
call('{acme:s}/acme.sh --issue {certlist:s} -w {www:s} --server {root_ca:s}'.format(**locals()), shell=True)
call('{acme:s}/acme.sh --install-cert {certlist: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))
try:
symlink("/dev/null", issuefile)
except Exception:
pass
else:
echo("-----> letsencrypt certificate already installed")
# fall back to creating self-signed certificate if acme failed
if not exists(key) or stat(crt).st_size == 0:
echo("-----> generating self-signed certificate")
call(
'openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=NY/L=New York/O=Piku/OU=Self-Signed/CN={domain:s}" -keyout {key:s} -out {crt:s}'.format(
**locals()), shell=True)
# restrict access to server from CloudFlare IP addresses
acl = []
if get_boolean(env.get('NGINX_CLOUDFLARE_ACL', 'false')):
try:
cf = loads(urlopen('https://api.cloudflare.com/client/v4/ips').read().decode("utf-8"))
if cf['success'] is True:
for i in cf['result']['ipv4_cidrs']:
acl.append("allow {};".format(i))
if get_boolean(env.get('DISABLE_IPV6', 'false')):
for i in cf['result']['ipv6_cidrs']:
acl.append("allow {};".format(i))
# allow access from controlling machine
if 'SSH_CLIENT' in environ:
remote_ip = environ['SSH_CLIENT'].split()[0]
echo("-----> nginx ACL will include your IP ({})".format(remote_ip))
acl.append("allow {};".format(remote_ip))
acl.extend(["allow 127.0.0.1;", "deny all;"])
except Exception:
cf = defaultdict()
echo("-----> Could not retrieve CloudFlare IP ranges: {}".format(format_exc()), fg="red")
env['NGINX_ACL'] = " ".join(acl)
env['PIKU_INTERNAL_NGINX_BLOCK_GIT'] = "" if env.get('NGINX_ALLOW_GIT_FOLDERS') else r"location ~ /\.git { deny all; }"
env['PIKU_INTERNAL_PROXY_CACHE_PATH'] = ''
env['PIKU_INTERNAL_NGINX_CACHE_MAPPINGS'] = ''
# Get a mapping of /prefix1,/prefix2
default_cache_path = join(CACHE_ROOT, app)
if not exists(default_cache_path):
makedirs(default_cache_path)
try:
cache_size = int(env.get('NGINX_CACHE_SIZE', '1'))
except Exception:
echo("=====> Invalid cache size, defaulting to 1GB")
cache_size = 1
cache_size = str(cache_size) + "g"
try:
cache_time_control = int(env.get('NGINX_CACHE_CONTROL', '3600'))
except Exception:
echo("=====> Invalid time for cache control, defaulting to 3600s")
cache_time_control = 3600
cache_time_control = str(cache_time_control)
try:
cache_time_content = int(env.get('NGINX_CACHE_TIME', '3600'))
except Exception:
echo("=====> Invalid cache time for content, defaulting to 3600s")
cache_time_content = 3600
cache_time_content = str(cache_time_content) + "s"
try:
cache_time_redirects = int(env.get('NGINX_CACHE_REDIRECTS', '3600'))
except Exception:
echo("=====> Invalid cache time for redirects, defaulting to 3600s")
cache_time_redirects = 3600
cache_time_redirects = str(cache_time_redirects) + "s"
try:
cache_time_any = int(env.get('NGINX_CACHE_ANY', '3600'))
except Exception:
echo("=====> Invalid cache expiry fallback, defaulting to 3600s")
cache_time_any = 3600
cache_time_any = str(cache_time_any) + "s"
try:
cache_time_expiry = int(env.get('NGINX_CACHE_EXPIRY', '86400'))
except Exception:
echo("=====> Invalid cache expiry, defaulting to 86400s")
cache_time_expiry = 86400
cache_time_expiry = str(cache_time_expiry) + "s"
cache_prefixes = env.get('NGINX_CACHE_PREFIXES', '')
cache_path = env.get('NGINX_CACHE_PATH', default_cache_path)
if not exists(cache_path):
echo("=====> Cache path {} does not exist, using default {}, be aware of disk usage.".format(cache_path, default_cache_path))
cache_path = env.get(default_cache_path)
if len(cache_prefixes):
prefixes = [] # this will turn into part of /(path1|path2|path3)
try:
items = cache_prefixes.split(',')
for item in items:
if item[0] == '/':
prefixes.append(item[1:])
else:
prefixes.append(item)
cache_prefixes = "|".join(prefixes)
echo("-----> nginx will cache /({}) prefixes up to {} or {} of disk space, with the following timings:".format(cache_prefixes, cache_time_expiry, cache_size))
echo("-----> nginx will cache content for {}.".format(cache_time_content))
echo("-----> nginx will cache redirects for {}.".format(cache_time_redirects))
echo("-----> nginx will cache everything else for {}.".format(cache_time_any))
echo("-----> nginx will send caching headers asking for {} seconds of public caching.".format(cache_time_control))
env['PIKU_INTERNAL_PROXY_CACHE_PATH'] = expandvars(
PIKU_INTERNAL_PROXY_CACHE_PATH, locals())
env['PIKU_INTERNAL_NGINX_CACHE_MAPPINGS'] = expandvars(
PIKU_INTERNAL_NGINX_CACHE_MAPPING, locals())
env['PIKU_INTERNAL_NGINX_CACHE_MAPPINGS'] = expandvars(
env['PIKU_INTERNAL_NGINX_CACHE_MAPPINGS'], env)
except Exception as e:
echo("Error {} in cache path spec: should be /prefix1:[,/prefix2], ignoring.".format(e))
env['PIKU_INTERNAL_NGINX_CACHE_MAPPINGS'] = ''
env['PIKU_INTERNAL_NGINX_STATIC_MAPPINGS'] = ''
# Get a mapping of /prefix1:path1,/prefix2:path2
static_paths = env.get('NGINX_STATIC_PATHS', '')
# prepend static worker path if present
if 'static' in workers:
stripped = workers['static'].strip("/").rstrip("/")
static_paths = ("/" if stripped[0:1] == ":" else "/:") + (stripped if stripped else ".") + "/" + ("," if static_paths else "") + static_paths
if len(static_paths):
try:
items = static_paths.split(',')
for item in items:
static_url, static_path = item.split(':')
if static_path[0] != '/':
static_path = join(app_path, static_path).rstrip("/") + "/"
echo("-----> nginx will map {} to {}.".format(static_url, static_path))
env['PIKU_INTERNAL_NGINX_STATIC_MAPPINGS'] = env['PIKU_INTERNAL_NGINX_STATIC_MAPPINGS'] + expandvars(
PIKU_INTERNAL_NGINX_STATIC_MAPPING, locals())
except Exception as e:
echo("Error {} in static path spec: should be /prefix1:path1[,/prefix2:path2], ignoring.".format(e))
env['PIKU_INTERNAL_NGINX_STATIC_MAPPINGS'] = ''
env['PIKU_INTERNAL_NGINX_CUSTOM_CLAUSES'] = expandvars(open(join(app_path, env["NGINX_INCLUDE_FILE"])).read(), env) if env.get("NGINX_INCLUDE_FILE") else ""
env['PIKU_INTERNAL_NGINX_PORTMAP'] = ""
if 'web' in workers or 'wsgi' in workers or 'jwsgi' in workers or 'rwsgi' in workers:
env['PIKU_INTERNAL_NGINX_PORTMAP'] = expandvars(NGINX_PORTMAP_FRAGMENT, env)
env['PIKU_INTERNAL_NGINX_COMMON'] = expandvars(NGINX_COMMON_FRAGMENT, env)
echo("-----> nginx will map app '{}' to hostname(s) '{}'".format(app, env['NGINX_SERVER_NAME']))
if get_boolean(env.get('NGINX_HTTPS_ONLY', 'false')):
buffer = expandvars(NGINX_HTTPS_ONLY_TEMPLATE, env)
echo("-----> nginx will redirect all requests to hostname(s) '{}' to HTTPS".format(env['NGINX_SERVER_NAME']))
else:
buffer = expandvars(NGINX_TEMPLATE, env)
# remove all references to IPv6 listeners (for enviroments where it's disabled)
if get_boolean(env.get('DISABLE_IPV6', 'false')):
buffer = '\n'.join([line for line in buffer.split('\n') if 'NGINX_IPV6' not in line])
# change any unecessary uWSGI specific directives to standard proxy ones
if 'wsgi' not in workers and 'jwsgi' not in workers:
buffer = buffer.replace("uwsgi_", "proxy_")
# map Cloudflare connecting IP to REMOTE_ADDR
if get_boolean(env.get('NGINX_CLOUDFLARE_ACL', 'false')):
buffer = buffer.replace("REMOTE_ADDR $remote_addr", "REMOTE_ADDR $http_cf_connecting_ip")
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 -E '{}\.conf:[0-9]+$'".format(app), env=environ, shell=True))
except Exception:
nginx_config_test = None
if nginx_config_test:
echo("Error: [nginx config] {}".format(nginx_config_test), fg='red')
echo("Warning: removing broken nginx config.", fg='yellow')
unlink(nginx_conf)
# Configured worker count
if exists(scaling):
worker_count.update({k: int(v) for k, v in parse_procfile(scaling).items() if k 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()):