-
Notifications
You must be signed in to change notification settings - Fork 17
/
fabfile.py
executable file
·1216 lines (1004 loc) · 32.9 KB
/
fabfile.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
"""
Copyright (C) 2017, ContraxSuite, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can also be released from the requirements of the license by purchasing
a commercial license from ContraxSuite, LLC. Buying such a license is
mandatory as soon as you develop commercial activities involving ContraxSuite
software without disclosing the source code of your own applications. These
activities include: offering paid services to customers as an ASP or "cloud"
provider, processing documents on the fly in a web application,
or shipping ContraxSuite within a closed source product.
"""
# -*- coding: utf-8 -*-
# Standard imports
import configparser
import csv
import datetime
import os
import platform
import sys
from collections import OrderedDict
from contextlib import contextmanager
from functools import wraps
# Fabric imports
from fabric.api import env, prefix
from fabric.colors import red, green, blue, yellow
from fabric.decorators import task
from fabric.operations import get, hide, local as _local, \
run as _run, sudo as _sudo, reboot, put
from fabric.context_managers import cd, settings
from fabric.contrib import django
from fabric.contrib.files import exists, upload_template
from fabtools.postgres import (create_database,
create_user as create_pg_user,
database_exists,
user_exists as pg_user_exists)
__author__ = "ContraxSuite, LLC; LexPredict, LLC"
__copyright__ = "Copyright 2015-2018, ContraxSuite, LLC"
__license__ = "https://github.com/LexPredict/lexpredict-contraxsuite/blob/1.1.1/LICENSE"
__version__ = "1.1.0"
__maintainer__ = "LexPredict, LLC"
__email__ = "support@contraxsuite.com"
"""
Update env from base/fabricrc
"""
try:
with open('base/fabricrc', 'r') as f:
config_string = '[dummy_section]\n' + f.read()
config = configparser.ConfigParser()
config.read_string(config_string)
for key, val in config.items('dummy_section'):
if key in env:
continue
env[key] = val
except FileNotFoundError:
pass
"""
Fabric setup for executing host.
"""
USER_HOME = os.path.expanduser('~')
# Determine base configuration directory; based on fabricrc path in env
env.config_dir = os.path.dirname(os.path.abspath(env.rcfile))
env.base_config_dir = os.path.join(os.path.dirname(__file__), 'base')
if 'localhost' not in env.hosts:
# Check env.key_filename.
if not env.key_filename:
raise RuntimeError('No env.key_filename set; ' +
'are you sure you passed -c fabric?')
ssh_key_locations = (
os.path.join(USER_HOME, '.ssh'),
os.path.dirname(__file__),
env.config_dir,
env.base_config_dir)
key_location = None
for ssh_dir in ssh_key_locations:
location = os.path.join(ssh_dir, env.key_filename)
if os.path.exists(location):
env.key_filename = key_location = location
break
if key_location is None:
raise RuntimeError('Unable to locate SSH key file ' +
'from key_filename value "{}"'.format(env.key_filename))
REBOOT_TIME = 300
# Path configuration parameters
env.project_dir = os.path.join(env.base_dir, env.project_path)
env.virtualenv_dir = os.path.join(env.base_dir, env.ve_dir)
env.ve_bin = os.path.join(env.virtualenv_dir, 'bin')
env.python_bin = os.path.join(env.ve_bin, 'python')
env.pip_bin = os.path.join(env.ve_bin, 'pip')
env.uwsgi_bin = os.path.join(env.ve_bin, 'uwsgi')
env.manage_py = os.path.join(env.project_dir, 'manage.py')
env.uwsgi_name = '%s_uwsgi' % env.templates_prefix
"""
Get local django settings
"""
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
try:
django.settings_module('settings')
from django.conf import settings as dj_settings
STATICFILES_DIR = dj_settings.STATICFILES_DIRS[0].replace(
dj_settings.PROJECT_DIR.root, env.project_dir)
STATIC_ROOT = dj_settings.STATIC_ROOT.replace(dj_settings.PROJECT_DIR.root, env.project_dir)
MEDIA_ROOT = dj_settings.MEDIA_ROOT.replace(dj_settings.PROJECT_DIR.root, env.project_dir)
FILEBROWSER_DIRECTORY = dj_settings.FILEBROWSER_DIRECTORY
CELERY_LOG_FILE_PATH = dj_settings.CELERY_LOG_FILE_PATH
LOG_FILE_PATH = dj_settings.LOG_FILE_PATH
DB_LOG_FILE_PATH = dj_settings.DB_LOG_FILE_PATH
except ImportError:
STATICFILES_DIR = os.path.join(env.project_dir, '..', 'static')
STATIC_ROOT = os.path.join(env.project_dir, 'staticfiles')
MEDIA_ROOT = os.path.join(env.project_dir, 'media')
FILEBROWSER_DIRECTORY = 'data/documents/'
CELERY_LOG_FILE_PATH = os.path.join(env.project_dir, 'logs/celery-{0}.log'.format(platform.node()))
LOG_FILE_PATH = os.path.join(env.project_dir, 'logs/django-{0}.log'.format(platform.node()))
DB_LOG_FILE_PATH = os.path.join(env.project_dir, 'logs/db-{0}.log'.format(platform.node()))
templates = OrderedDict((
('run', {
'local_path': 'templates/run.sh',
'remote_path': '~/run.sh'
}),
('502', {
'local_path': 'templates/502.html',
'remote_path': '/usr/share/nginx/html/502.html',
'use_jinja': 'true'
}),
('uwsgi-init', {
'local_path': 'templates/uwsgi.service',
'remote_path': '/etc/systemd/system/%s.service' % env.uwsgi_name
}),
('uwsgi', {
'local_path': 'templates/uwsgi.ini',
'remote_path': '/etc/uwsgi/%s.ini' % env.uwsgi_name
}),
('settings', {
'template_dir': '%(config_dir)s',
'local_path': 'local_settings.py',
'remote_path': '%(project_dir)s/local_settings.py'
}),
('nginx', {
'local_path': 'templates/nginx.conf',
'remote_path': '/etc/nginx/sites-enabled/%s_nginx.conf' % env.templates_prefix,
'reload_command': 'systemctl restart nginx',
'use_jinja': 'true',
}),
))
"""
--------------------------------
Print methods
--------------------------------
"""
def _print(output):
print()
print(output)
def print_command(command):
_print(blue("$ ", bold=True) +
yellow(command, bold=True) +
red(" ->", bold=True))
def log_call(func):
@wraps(func)
def logged(*args, **kawrgs):
header = "-" * len(func.__name__)
_print(green("\n".join([header, func.__name__, header]), bold=True))
return func(*args, **kawrgs)
return logged
"""
--------------------------------
Installers methods
--------------------------------
"""
def get_templates():
"""
Returns each of the templates with env vars injected.
"""
injected = {}
for template_name, data in templates.items():
injected[template_name] = dict([(k, v % env) for k, v in data.items()])
return injected
@task
def upload_template_and_reload(template_name):
"""
Uploads a template only if it has changed, and if so, reload a related service.
"""
template = get_templates()[template_name]
local_path = template['local_path']
remote_path = template['remote_path']
reload_command = template.get('reload_command')
owner = template.get('owner')
mode = template.get('mode')
template_dir = template.get('template_dir', '.')
upload_template(local_path, remote_path, env, use_sudo=True, backup=False,
template_dir=template_dir, use_jinja=template.get('use_jinja'))
if owner:
sudo('chown %s %s' % (owner, remote_path))
if mode:
sudo('chmod %s %s' % (mode, remote_path))
if reload_command:
sudo(reload_command)
@task
@log_call
def upload_templates(template_names=None):
"""
Upload given templates
"""
for template_name in template_names or templates:
upload_template_and_reload(template_name)
sudo('systemctl daemon-reload')
@task
def install_packages(install_command,
requirements_filename,
package_list=None,
installed_packages=None,
use_sudo=False):
"""
Install packages from custom files from given custom and base config dirs.
"""
run_ = sudo if use_sudo else run
req_paths = ((env.base_config_dir, requirements_filename),
(env.config_dir, requirements_filename))
if package_list is None:
package_list = []
for path_terms in req_paths:
path = os.path.join(*path_terms)
if not os.path.exists(path):
continue
csv_file = open(path)
csv_reader = csv.reader(csv_file)
for tokens in csv_reader:
if not tokens:
continue
package = tokens[0]
if package.strip().startswith('#'):
continue
if installed_packages and package in installed_packages:
print('Package "{}" already exists'.format(package))
continue
package_list.append(package)
csv_file.close()
for package in package_list:
apt_ret = run_('{} {}'.format(install_command, package))
if apt_ret.failed:
raise RuntimeError('Unable to install package {}.'.format(package))
@task
@log_call
def python_install(upgrade=False):
"""
Install required python packages.
"""
with virtualenv():
installed_packages = run('pip freeze').split()
install_command = 'pip install {}'.format('-U' if upgrade else '')
install_packages(install_command,
'python-requirements.txt',
installed_packages=installed_packages)
@task
def git_clone(recreate=True):
"""
Run initial `git clone` into BASE_DIR.
"""
with cd(env.base_dir):
# Check for existing git directory. If exists and recreate, delete.
if exists(env.project_dir):
if not recreate:
git_pull()
else:
# Backup the folder
date_string = datetime.datetime.now().strftime('%Y%m%d%_H%M%S')
repo_original_path = os.path.normpath(os.path.join(env.project_dir, '..'))
repo_backup_path = '{}.{}'.format(repo_original_path, date_string)
run_check('mv {} {}'.format(repo_original_path, repo_backup_path))
# Clone
result = run_check('git clone --branch {} {}'.format(env.git_branch, env.git_uri))
return result
@task
@log_call
def git_pull(branch=None):
"""
Update git by pulling.
"""
if not branch:
branch = env.git_branch
with cd(env.project_dir):
run_check('git fetch')
run_check('git checkout {}'.format(branch))
run_check('git pull origin {}'.format(branch))
run_check('find . -name "*pyc" -delete', use_sudo=True)
@task
@log_call
def git_status(branch=None):
"""
Update git by pulling.
"""
if not branch:
branch = env.git_branch
with cd(env.project_dir):
run_check('git checkout {}'.format(branch))
run_check('git status')
"""
--------------------------------
Install instance
--------------------------------
"""
"""
1. create_ssh_keys
2. add id_rsa.pub file content into github account
3. should have assigned dns name instead of IP in fabricrc
for proper ssl certification
4. setup_new_app_instance:1 if ssh keys added and dns name exists
otherwise setup_new_app_instance and partially install_project_files
"""
@task
def create_ssh_keys():
"""
Create id-rsa key. Don't forget to add it to GIT
"""
run_check('echo -e \'y\n\'|ssh-keygen -q -t rsa -N "" -f ~/.ssh/id_rsa')
run_check('chmod 600 ~/.ssh/id_rsa')
run_check('eval "$(ssh-agent -s)"')
run_check('ssh-add ~/.ssh/id_rsa')
run_check('cat ~/.ssh/id_rsa.pub')
@task
def setup_new_app_instance(install_project=False):
"""
Setup a new app instance from base Ubuntu image
"""
debian_install()
locales_install()
postgres_create()
init_daemon_install()
debian_upgrade_reboot()
create_base_directory()
python_install()
# RabbitMQ is used as message broker.
rabbitmq_install()
# Installing redis to allow easy switching and for possible usage as key-value storage.
redis_install()
java_install()
elasticsearch_install()
theme_install()
jqwidgets_install()
# stanford_install()
if install_project:
install_project_files()
@task
def install_project_files():
git_clone()
create_dirs()
upload_templates(['nginx', 'uwsgi-init', 'uwsgi',
'settings', 'run', '502'])
# run migrations without Django's system check
manage('force_migrate')
# manage('migrate --noinput')
# load roles, statuses, status groups, etc
manage('loadnewdata fixtures/common/*.json')
manage('loadnewdata fixtures/private/*.json')
# create superuser
create_superuser()
# setup site object
manage('set_site')
# collect static
manage('collectstatic -v 0 --noinput')
# download nltk data
nltk_download()
ssl_install()
start()
@task
def create_dirs():
"""
Create directories and files for the project and its services.
"""
# remove default nginx config
sudo('rm -f /etc/nginx/sites-enabled/default')
# create static and media dirs
mkdir(STATIC_ROOT, env.user, env.user, True)
mkdir(MEDIA_ROOT, env.user, env.user, True)
# create dirs for documents
mkdir(os.path.join(MEDIA_ROOT, FILEBROWSER_DIRECTORY), env.user, env.user, True)
# create tika log file, otherwise celery won't register tasks
run_check('touch /tmp/tika.log')
sudo('chown -R {}:{} /tmp/tika.log'.format(env.user, env.user))
# create log files
logs_dir_path = os.path.join(env.project_dir, 'logs')
mkdir(logs_dir_path, env.user, env.user, True)
for log_path in (LOG_FILE_PATH, CELERY_LOG_FILE_PATH, DB_LOG_FILE_PATH):
sudo('touch %s' % log_path)
sudo('chown -R {}:{} {}'.format(env.user, env.user, log_path))
@task
def create_base_directory(clean=False):
"""
Create base directory.
"""
# Check if we want to clean.
if clean and exists(env.base_dir):
clean_base_directory()
# Create path
mkdir(env.base_dir, env.user, env.user, True)
# Create Python virtualenv
run('virtualenv -p python3 {}'.format(env.virtualenv_dir))
# Check that Python and pip executable exist.
if not exists(env.python_bin):
raise RuntimeError('PYTHON_BIN {} does not exist; setup failed.'.format(env.python_bin))
if not exists(env.pip_bin):
raise RuntimeError('PIP_BIN {} does not exist; setup failed.'.format(env.pip_bin))
"""
--------------------------------
Services methods
--------------------------------
"""
@task
def status_service(service_name):
"""
Get status of systemd service
"""
sudo('systemctl status %s --no-pager -l' % service_name, warn_only=True)
@task
def is_active(service_name):
"""
Check if service is active
"""
ret = sudo('systemctl is-active %s' % service_name, warn_only=True)
active = ret == 'active'
color = green if active else red
print(color('Status %s: %s' % (service_name, ret)))
return active
@task
def restart_service(service_name):
"""
Restart service
"""
cmd = 'restart' if is_active(service_name) else 'start'
sudo('systemctl %s %s' % (cmd, service_name))
@task
def stop_service(service_name):
"""
Stop service
"""
if is_active(service_name):
sudo('systemctl stop %s' % service_name)
@task
def start_service(service_name):
"""
Start service
"""
if not is_active(service_name):
sudo('systemctl start %s' % service_name)
@task
def stop_celery(kill_process=False):
"""
Stop celery workers
"""
with cd(env.project_dir):
if kill_process:
run('pkill -f "celery"')
else:
run('{ve_dir}/bin/celery purge -A apps -f'.format(
ve_dir=env.virtualenv_dir))
@task
def start_celery():
"""
Start celery workers
"""
with cd(env.project_dir):
run('{run_as_root}{ve_dir}/bin/celery multi restart '
'worker -A apps -B -Q serial --concurrency=1 -Ofair -l DEBUG -n beat@%h'.format(
run_as_root='C_FORCE_ROOT ' if env.celery_run_as_root == 'true' else '',
ve_dir=env.virtualenv_dir))
run('{run_as_root}{ve_dir}/bin/celery multi restart '
'worker1 -A apps -Q default,high_priority --concurrency=1 -Ofair -n default_priority@%h'.format(
run_as_root='C_FORCE_ROOT ' if env.celery_run_as_root == 'true' else '',
ve_dir=env.virtualenv_dir))
@task
def status_celery():
"""
Show celery registered and active tasks
"""
with cd(env.project_dir):
run('{ve_dir}/bin/celery -A {celery_app} inspect registered'.format(
ve_dir=env.virtualenv_dir,
celery_app=env.celery_app))
run('{ve_dir}/bin/celery -A {celery_app} inspect active'.format(
ve_dir=env.virtualenv_dir,
celery_app=env.celery_app))
@task
def purge_celery():
"""
Purge celery tasks
"""
with cd(env.project_dir):
run('{ve_dir}/bin/celery -A {celery_app} purge -f'.format(
ve_dir=env.virtualenv_dir,
celery_app=env.celery_app))
@task
def stop_redis():
stop_service('redis_6379')
@task
def start_redis():
start_service('redis_6379')
@task
@log_call
def stop():
"""
Stop services
"""
stop_service('nginx')
stop_service(env.uwsgi_name)
stop_celery()
# stop_redis()
@task
@log_call
def start():
"""
Start services
"""
start_service('nginx')
start_service(env.uwsgi_name)
start_celery()
# redis doesn't start properly
# start_redis()
@task
@log_call
def restart():
"""
Restart services
"""
stop()
start()
"""
--------------------------------
Deploy methods
--------------------------------
"""
@task
@log_call
def deploy(do_upload_templates=False):
"""
Refresh a site by pulling latest repository changes,
deploying newest configuration templates,
and restarting services.
"""
# Stop services
stop()
# remove *pyc files
run_check('find {} -name "*pyc" -delete'.format(env.project_dir), use_sudo=True)
# upload config. files
if do_upload_templates:
upload_templates(['nginx', 'uwsgi-init', 'uwsgi', 'settings'])
# Git pull
git_pull()
python_install()
# run migrations
manage('migrate --noinput')
# Start services
start()
manage('collectstatic -v 0 --noinput')
@task
@log_call
def deploy1():
"""
Short deploy variant
"""
git_pull()
restart()
"""
--------------------------------
Fabric system utils
--------------------------------
"""
@task
def manage(*args):
"""
Run django management command
"""
with cd(env.project_dir):
sudo('{} manage.py {}'.format(env.python_bin, ' '.join(args)))
def run_check(command, use_sudo=False, combine_stderr=True, **kw):
"""
Wrapper around run/sudo that checks for error code/value.
"""
with settings(warn_only=True):
if use_sudo:
ret = sudo(command, combine_stderr=combine_stderr, **kw)
else:
ret = run(command, combine_stderr=combine_stderr, **kw)
if ret.failed:
raise RuntimeError('Fail in command: %s . Exit code: %s' % (
command, ret.return_code))
return ret
def mkdir(path, owner=env.user, group=env.user, use_sudo=False):
"""
Create a path with a given owner/group, possibly via sudo.
"""
if use_sudo:
sudo('mkdir -p {}'.format(path))
else:
run('mkdir -p {}'.format(path))
sudo('chown -R {}:{} {}'.format(owner, group, path))
"""
--------------------------------
Install methods
--------------------------------
"""
def debian_add_key(keyserver, recv):
"""
Add an apt key.
"""
# Use apt-key to add this
run_check('apt-key adv --keyserver {} --recv {}'.format(keyserver, recv), use_sudo=True)
def debian_add_repository(repository_string):
"""
Add an apt repository.
"""
# Use apt-add-repository
run_check("apt-add-repository '{}'".format(repository_string), use_sudo=True)
@task
def debian_update(fix_missing=False):
"""
Refresh apt repository cache.
"""
# Update repo cache
if fix_missing:
update_ret = sudo('apt-get -y update --fix-missing')
else:
update_ret = sudo('apt-get -y update')
if update_ret.failed:
raise RuntimeError('Unable to update apt repository information.')
@task
@log_call
def debian_install(package_list=None, update_cache=True):
"""
Install required debian/ubuntu packages.
If no package list specified, assume from config;
iterate over all lines of debian-requirements (base and current)
"""
# Update repo cache.
if update_cache:
debian_update()
install_command = 'apt-get -y -q install'
install_packages(install_command,
'debian-requirements.txt',
package_list=package_list,
use_sudo=True)
uwsgi_install()
yuglify_install()
@task
def debian_upgrade():
"""
Upgrade all installed debian/ubuntu packages.
"""
# Update repo cache
debian_update()
# Upgrade packages
upgrade_ret = sudo('apt-get --force-yes -y upgrade')
if upgrade_ret.failed:
raise RuntimeError('Unable to upgrade apt packages.')
@task
def debian_upgrade_reboot():
"""
debian_upgrade() + reboot for first time/kernel installs.
"""
debian_upgrade()
if exists('/var/run/reboot-required', True):
reboot(REBOOT_TIME)
@task
@log_call
def uwsgi_install(launch_uwsgi=False):
"""
Installs uwsgi LTS release
"""
sudo('pip install uwsgi==2.0.14')
try:
sudo('rm /usr/bin/uwsgi')
except:
pass
sudo('ln -s /usr/local/bin/uwsgi /usr/bin/uwsgi')
if launch_uwsgi:
start_service(env.uwsgi_name)
@task
@log_call
def init_daemon_install():
"""
Switch from upstart to systemd
"""
ret = sudo('stat /proc/1/exe')
if 'upstart' in ret:
sudo('apt-get -y install systemd-sysv ubuntu-standard')
sudo('update-initramfs -u')
reboot(REBOOT_TIME)
@task
@log_call
def locales_install():
"""
Setup locales (for postgres)
"""
sudo('locale-gen --purge en_US en_US.UTF-8')
sudo('echo -e \'LANG="en_US.UTF-8"\nLANGUAGE="en_US:en"\n\' > /etc/default/locale')
# run_check('echo export LC_ALL="en_US.UTF-8" >> ~/.bashrc')
# sudo('locale-gen en_US en_US.UTF-8')
# sudo('dpkg-reconfigure locales')
@task
@log_call
def redis_install():
"""
Installs redis
"""
with cd('/tmp'):
run('wget http://download.redis.io/releases/redis-stable.tar.gz')
run('tar xzf redis-stable.tar.gz')
with cd('redis-stable'):
run('make')
sudo('make install')
with cd('utils'):
sudo('echo -n | ./install_server.sh')
start_redis()
@task
@log_call
def rabbitmq_install():
"""
Installs RabbitMQ
"""
sudo('/bin/sh -c "wget -qO - https://www.rabbitmq.com/rabbitmq-release-signing-key.asc | apt-key add -"')
sudo('/bin/sh -c \'echo "deb http://www.rabbitmq.com/debian/ testing main" | tee -a /etc/apt/sources.list.d/rabbitmq.list\'')
sudo('apt-get update')
sudo('apt-get --yes --force-yes install rabbitmq-server')
sudo('rabbitmqctl add_user contrax1 contrax1')
sudo('rabbitmqctl add_vhost contrax1_vhost')
sudo('rabbitmqctl set_permissions -p contrax1_vhost contrax1 ".*" ".*" ".*"')
@task
@log_call
def yuglify_install():
sudo('npm -g install yuglify')
sudo('ln -s /usr/bin/nodejs /usr/bin/node')
@task
@log_call
def java_install():
"""
Installs java
"""
sudo('apt-get install -y python-software-properties debconf-utils software-properties-common')
sudo('add-apt-repository -y ppa:webupd8team/java')
sudo('apt-get update')
sudo('echo "oracle-java8-installer shared/accepted-oracle-license-v1-1 select true" | '
'debconf-set-selections')
sudo('apt-get install -y oracle-java8-installer')
run('java -version')
@task
@log_call
def elasticsearch_install():
"""
Install and run elasticsearch
"""
sudo('/bin/sh -c "wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | apt-key add -"')
# If everything start crashing: sudo apt remove --purge elasticsearch
sudo('/bin/sh -c \'echo "deb https://artifacts.elastic.co/packages/6.x/apt stable main" '
'| tee -a /etc/apt/sources.list.d/elastic-6.x.list\'')
sudo('apt-get update')
sudo('apt-get --yes --force-yes install elasticsearch')
sudo('systemctl daemon-reload')
sudo('systemctl enable elasticsearch.service')
restart_service('elasticsearch')
@task
@log_call
def ssl_install():
"""
Setup SSL certificates
"""
if env.get('https_redirect'):
sudo('letsencrypt certonly --email %s'
' --text --agree-tos -d %s' % (env.cert_email, env.dns_name))
@task
@log_call
def nltk_download():
"""
Download nltk data
"""
with cd(env.project_dir):
sudo('{} -m nltk.downloader averaged_perceptron_tagger punkt stopwords '
' words maxent_ne_chunker wordnet'.format(env.python_bin))
@task
@log_call
def postgres_create():
"""
Create postgres objects, including owner, databases, and schemas.
"""
if not pg_user_exists(env.db_user):
create_pg_user(env.db_user, password=env.db_password)
if not database_exists(env.db_name):
create_database(env.db_name, owner=env.db_user)
def clean_base_directory():
"""
Clean the base directory.
"""
# TODO: Implement.
raise NotImplementedError('clean_base_directory() not implemented.')
"""
--------------------------------
Helpers
--------------------------------
"""
@task
def run(command, show=True, *args, **kwargs):
"""
Runs a shell command on the remote server.
"""
if show:
print_command(command)
with hide("running"):
return _run(command, *args, **kwargs)
@task
def sudo(command, show=True, *args, **kwargs):
"""
Runs a command as sudo on the remote server.
"""
if show:
print_command(command)
with hide("running"):
return _sudo(command, *args, **kwargs)