forked from samuelclay/NewsBlur
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fabfile.py
1693 lines (1467 loc) · 60.3 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
from fabric.api import cd, lcd, env, local, parallel, serial
from fabric.api import put, run, settings, sudo, prefix
from fabric.operations import prompt
from fabric.contrib import django
from fabric.contrib import files
from fabric.state import connections
# from fabric.colors import red, green, blue, cyan, magenta, white, yellow
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from boto.ec2.connection import EC2Connection
from vendor import yaml
from pprint import pprint
from collections import defaultdict
from contextlib import contextmanager as _contextmanager
import os
import time
import sys
import re
try:
import digitalocean
except ImportError:
print "Digital Ocean's API not loaded. Install python-digitalocean."
django.settings_module('settings')
try:
from django.conf import settings as django_settings
except ImportError:
print " ---> Django not installed yet."
django_settings = None
# ============
# = DEFAULTS =
# ============
env.NEWSBLUR_PATH = "/srv/newsblur"
env.SECRETS_PATH = "/srv/secrets-newsblur"
env.VENDOR_PATH = "/srv/code"
env.user = 'sclay'
env.key_filename = os.path.join(env.SECRETS_PATH, 'keys/newsblur.key')
env.connection_attempts = 10
env.do_ip_to_hostname = {}
env.colorize_errors = True
# =========
# = Roles =
# =========
try:
hosts_path = os.path.expanduser(os.path.join(env.SECRETS_PATH, 'configs/hosts.yml'))
roles = yaml.load(open(hosts_path))
for role_name, hosts in roles.items():
if isinstance(hosts, dict):
roles[role_name] = [host for host in hosts.keys()]
env.roledefs = roles
except:
print " ***> No role definitions found in %s. Using default roles." % hosts_path
env.roledefs = {
'app' : ['app01.newsblur.com'],
'db' : ['db01.newsblur.com'],
'task' : ['task01.newsblur.com'],
}
def do_roledefs(split=False):
doapi = digitalocean.Manager(token=django_settings.DO_TOKEN_FABRIC)
droplets = doapi.get_all_droplets()
env.do_ip_to_hostname = {}
hostnames = {}
for droplet in droplets:
roledef = re.split(r"([0-9]+)", droplet.name)[0]
if roledef not in env.roledefs:
env.roledefs[roledef] = []
if roledef not in hostnames:
hostnames[roledef] = []
if droplet.ip_address not in hostnames[roledef]:
hostnames[roledef].append({'name': droplet.name, 'address': droplet.ip_address})
env.do_ip_to_hostname[droplet.ip_address] = droplet.name
if droplet.ip_address not in env.roledefs[roledef]:
env.roledefs[roledef].append(droplet.ip_address)
if split:
return hostnames
return droplets
def list_do():
droplets = assign_digitalocean_roledefs(split=True)
pprint(droplets)
doapi = digitalocean.Manager(token=django_settings.DO_TOKEN_FABRIC)
droplets = doapi.get_all_droplets()
sizes = doapi.get_all_sizes()
sizes = dict((size.slug, size.price_monthly) for size in sizes)
role_costs = defaultdict(int)
total_cost = 0
for droplet in droplets:
roledef = re.split(r"([0-9]+)", droplet.name)[0]
cost = droplet.size['price_monthly']
role_costs[roledef] += cost
total_cost += cost
print "\n\n Costs:"
pprint(dict(role_costs))
print " ---> Total cost: $%s/month" % total_cost
def host(*names):
env.hosts = []
env.doname = ','.join(names)
hostnames = assign_digitalocean_roledefs(split=True)
for role, hosts in hostnames.items():
for host in hosts:
if isinstance(host, dict) and host['name'] in names:
env.hosts.append(host['address'])
print " ---> Using %s as hosts" % env.hosts
# ================
# = Environments =
# ================
def server():
env.NEWSBLUR_PATH = "/srv/newsblur"
env.VENDOR_PATH = "/srv/code"
def assign_digitalocean_roledefs(split=False):
server()
droplets = do_roledefs(split=split)
if split:
for roledef, hosts in env.roledefs.items():
if roledef not in droplets:
droplets[roledef] = hosts
return droplets
def app():
web()
def web():
assign_digitalocean_roledefs()
env.roles = ['app', 'push', 'work', 'search']
def work():
assign_digitalocean_roledefs()
env.roles = ['work', 'search']
def www():
assign_digitalocean_roledefs()
env.roles = ['www']
def dev():
assign_digitalocean_roledefs()
env.roles = ['dev']
def debug():
assign_digitalocean_roledefs()
env.roles = ['debug']
def node():
assign_digitalocean_roledefs()
env.roles = ['node']
def push():
assign_digitalocean_roledefs()
env.roles = ['push']
def db():
assign_digitalocean_roledefs()
env.roles = ['db', 'search']
def task():
assign_digitalocean_roledefs()
env.roles = ['task']
def ec2task():
ec2()
env.roles = ['ec2task']
def ec2():
env.user = 'ubuntu'
env.key_filename = ['/Users/sclay/.ec2/sclay.pem']
assign_digitalocean_roledefs()
def all():
assign_digitalocean_roledefs()
env.roles = ['app', 'db', 'task', 'debug', 'node', 'push', 'work', 'www', 'search']
# =============
# = Bootstrap =
# =============
def setup_common():
setup_installs()
change_shell()
setup_user()
setup_sudoers()
setup_ulimit()
setup_libxml()
setup_psql_client()
setup_repo()
setup_local_files()
setup_time_calibration()
setup_pip()
setup_virtualenv()
setup_repo_local_settings()
pip()
setup_supervisor()
setup_hosts()
# setup_pgbouncer()
config_pgbouncer()
setup_mongoengine_repo()
# setup_forked_mongoengine()
# setup_pymongo_repo()
setup_logrotate()
setup_nginx()
# setup_imaging()
setup_munin()
def setup_all():
setup_common()
setup_app(skip_common=True)
setup_db(skip_common=True)
setup_task(skip_common=True)
def setup_app(skip_common=False):
if not skip_common:
setup_common()
setup_app_firewall()
setup_motd('app')
copy_app_settings()
config_nginx()
setup_gunicorn(supervisor=True)
# setup_node_app()
# config_node()
deploy_web()
config_monit_app()
setup_usage_monitor()
done()
def setup_app_image():
copy_app_settings()
setup_hosts()
config_pgbouncer()
pull()
pip()
deploy_web()
done()
sudo('reboot')
def setup_node():
setup_node_app()
config_node()
def setup_db(engine=None, skip_common=False):
if not skip_common:
setup_common()
setup_db_firewall()
setup_motd('db')
copy_db_settings()
if engine == "postgres":
setup_postgres(standby=False)
setup_postgres_backups()
elif engine == "postgres_slave":
setup_postgres(standby=True)
elif engine.startswith("mongo"):
setup_mongo()
setup_mongo_mms()
setup_mongo_backups()
elif engine == "redis":
setup_redis()
setup_redis_backups()
setup_redis_monitor()
elif engine == "redis_slave":
setup_redis(slave=True)
setup_redis_monitor()
elif engine == "elasticsearch":
setup_elasticsearch()
setup_db_search()
setup_gunicorn(supervisor=False)
setup_db_munin()
setup_db_monitor()
setup_usage_monitor()
done()
# if env.user == 'ubuntu':
# setup_db_mdadm()
def setup_task(queue=None, skip_common=False):
if not skip_common:
setup_common()
setup_task_firewall()
setup_motd('task')
copy_task_settings()
enable_celery_supervisor(queue)
setup_gunicorn(supervisor=False)
config_monit_task()
setup_usage_monitor()
done()
def setup_task_image():
setup_installs()
copy_task_settings()
setup_hosts()
config_pgbouncer()
pull()
pip()
deploy(reload=True)
done()
# ==================
# = Setup - Common =
# ==================
def done():
print "\n\n\n\n-----------------------------------------------------"
print "\n\n %s IS SUCCESSFULLY BOOTSTRAPPED" % (env.get('doname') or env.host_string)
print "\n\n-----------------------------------------------------\n\n\n\n"
def setup_installs():
packages = [
'build-essential',
'gcc',
'scons',
'libreadline-dev',
'sysstat',
'iotop',
'git',
'python-dev',
'locate',
'python-software-properties',
'software-properties-common',
'libpcre3-dev',
'libncurses5-dev',
'libdbd-pg-perl',
'libssl-dev',
'libffi-dev',
'libevent-dev',
'make',
'postgresql-common',
'ssl-cert',
'pgbouncer',
'openssl-blacklist',
'python-setuptools',
'python-psycopg2',
'libyaml-0-2',
'python-yaml',
'python-numpy',
'python-scipy',
'curl',
'monit',
'ufw',
'libjpeg8',
'libjpeg62-dev',
'libfreetype6',
'libfreetype6-dev',
'python-imaging',
'libmysqlclient-dev',
'libblas-dev',
'liblapack-dev',
'libatlas-base-dev',
'gfortran',
'libpq-dev',
]
# sudo("sed -i -e 's/archive.ubuntu.com\|security.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list")
put("config/apt_sources.conf", "/etc/apt/sources.list", use_sudo=True)
sudo('apt-get -y update')
sudo('DEBIAN_FRONTEND=noninteractive apt-get -y --force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" dist-upgrade')
sudo('DEBIAN_FRONTEND=noninteractive apt-get -y --force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install %s' % ' '.join(packages))
with settings(warn_only=True):
sudo("ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib")
sudo("ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib")
sudo("ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib")
with settings(warn_only=True):
sudo('mkdir -p %s' % env.VENDOR_PATH)
sudo('chown %s.%s %s' % (env.user, env.user, env.VENDOR_PATH))
def change_shell():
sudo('apt-get -y install zsh')
with settings(warn_only=True):
run('git clone git://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh')
sudo('chsh %s -s /bin/zsh' % env.user)
def setup_user():
# run('useradd -c "NewsBlur" -m newsblur -s /bin/zsh')
# run('openssl rand -base64 8 | tee -a ~conesus/.password | passwd -stdin conesus')
run('mkdir -p ~/.ssh && chmod 700 ~/.ssh')
run('rm -fr ~/.ssh/id_dsa*')
run('ssh-keygen -t dsa -f ~/.ssh/id_dsa -N ""')
run('touch ~/.ssh/authorized_keys')
put("~/.ssh/id_dsa.pub", "authorized_keys")
run("echo \"\n\" >> ~sclay/.ssh/authorized_keys")
run('echo `cat authorized_keys` >> ~sclay/.ssh/authorized_keys')
run('rm authorized_keys')
def copy_ssh_keys():
put(os.path.join(env.SECRETS_PATH, 'keys/newsblur.key.pub'), "local_keys")
run("echo \"\n\" >> ~sclay/.ssh/authorized_keys")
run("echo `cat local_keys` >> ~sclay/.ssh/authorized_keys")
run("rm local_keys")
def setup_repo():
sudo('mkdir -p /srv')
sudo('chown -R %s.%s /srv' % (env.user, env.user))
with settings(warn_only=True):
run('git clone https://github.com/samuelclay/NewsBlur.git %s' % env.NEWSBLUR_PATH)
with settings(warn_only=True):
sudo('ln -sfn /srv/code /home/%s/code' % env.user)
sudo('ln -sfn /srv/newsblur /home/%s/newsblur' % env.user)
def setup_repo_local_settings():
with virtualenv():
run('cp local_settings.py.template local_settings.py')
run('mkdir -p logs')
run('touch logs/newsblur.log')
def setup_local_files():
put("config/toprc", "~/.toprc")
put("config/zshrc", "~/.zshrc")
put('config/gitconfig.txt', '~/.gitconfig')
put('config/ssh.conf', '~/.ssh/config')
def setup_psql_client():
sudo('apt-get -y --force-yes install postgresql-client')
sudo('mkdir -p /var/run/postgresql')
with settings(warn_only=True):
sudo('chown postgres.postgres /var/run/postgresql')
def setup_libxml():
sudo('apt-get -y install libxml2-dev libxslt1-dev python-lxml')
def setup_libxml_code():
with cd(env.VENDOR_PATH):
run('git clone git://git.gnome.org/libxml2')
run('git clone git://git.gnome.org/libxslt')
with cd(os.path.join(env.VENDOR_PATH, 'libxml2')):
run('./configure && make && sudo make install')
with cd(os.path.join(env.VENDOR_PATH, 'libxslt')):
run('./configure && make && sudo make install')
def setup_psycopg():
sudo('easy_install -U psycopg2')
# def setup_python():
# # sudo('easy_install -U $(<%s)' %
# # os.path.join(env.NEWSBLUR_PATH, 'config/requirements.txt'))
# pip()
# put('config/pystartup.py', '.pystartup')
#
# # with cd(os.path.join(env.NEWSBLUR_PATH, 'vendor/cjson')):
# # sudo('python setup.py install')
#
# with settings(warn_only=True):
# sudo('echo "import sys; sys.setdefaultencoding(\'utf-8\')" | sudo tee /usr/lib/python2.7/sitecustomize.py')
# sudo("chmod a+r /usr/local/lib/python2.7/dist-packages/httplib2-0.8-py2.7.egg/EGG-INFO/top_level.txt")
# sudo("chmod a+r /usr/local/lib/python2.7/dist-packages/python_dateutil-2.1-py2.7.egg/EGG-INFO/top_level.txt")
# sudo("chmod a+r /usr/local/lib/python2.7/dist-packages/httplib2-0.8-py2.7.egg/httplib2/cacerts.txt")
#
# if env.user == 'ubuntu':
# with settings(warn_only=True):
# sudo('chown -R ubuntu.ubuntu /home/ubuntu/.python-eggs')
def setup_virtualenv():
sudo('pip install --upgrade virtualenv')
sudo('pip install --upgrade virtualenvwrapper')
setup_local_files()
sudo('rm -fr ~/.cache') # Clean `sudo pip`
with prefix('WORKON_HOME=%s' % os.path.join(env.NEWSBLUR_PATH, 'venv')):
with prefix('source /usr/local/bin/virtualenvwrapper.sh'):
with cd(env.NEWSBLUR_PATH):
# sudo('rmvirtualenv newsblur')
# sudo('rm -fr venv')
with settings(warn_only=True):
run('mkvirtualenv --no-site-packages newsblur')
run('echo "import sys; sys.setdefaultencoding(\'utf-8\')" | sudo tee venv/newsblur/lib/python2.7/sitecustomize.py')
@_contextmanager
def virtualenv():
with prefix('WORKON_HOME=%s' % os.path.join(env.NEWSBLUR_PATH, 'venv')):
with prefix('source /usr/local/bin/virtualenvwrapper.sh'):
with cd(env.NEWSBLUR_PATH):
with prefix('workon newsblur'):
yield
def setup_pip():
sudo('easy_install -U pip')
@parallel
def pip():
pull()
with virtualenv():
with settings(warn_only=True):
sudo('fallocate -l 4G /swapfile')
sudo('chmod 600 /swapfile')
sudo('mkswap /swapfile')
sudo('swapon /swapfile')
run('easy_install -U pip')
run('pip install --upgrade pip')
run('pip install -r requirements.txt')
sudo('swapoff /swapfile')
# PIL - Only if python-imaging didn't install through apt-get, like on Mac OS X.
def setup_imaging():
sudo('easy_install --always-unzip pil')
def setup_supervisor():
sudo('apt-get -y install supervisor')
put('config/supervisord.conf', '/etc/supervisor/supervisord.conf', use_sudo=True)
sudo('/etc/init.d/supervisor stop')
sudo('sleep 2')
sudo('ulimit -n 100000 && /etc/init.d/supervisor start')
@parallel
def setup_hosts():
put(os.path.join(env.SECRETS_PATH, 'configs/hosts'), '/etc/hosts', use_sudo=True)
sudo('echo "\n\n127.0.0.1 `hostname`" | sudo tee -a /etc/hosts')
def setup_pgbouncer():
sudo('apt-get remove -y pgbouncer')
sudo('apt-get install -y libevent-dev')
PGBOUNCER_VERSION = '1.7.2'
with cd(env.VENDOR_PATH), settings(warn_only=True):
run('wget https://pgbouncer.github.io/downloads/files/%s/pgbouncer-%s.tar.gz' % (PGBOUNCER_VERSION, PGBOUNCER_VERSION))
run('tar -xzf pgbouncer-%s.tar.gz' % PGBOUNCER_VERSION)
run('rm pgbouncer-%s.tar.gz' % PGBOUNCER_VERSION)
with cd('pgbouncer-%s' % PGBOUNCER_VERSION):
run('./configure --prefix=/usr/local --with-libevent=libevent-prefix')
run('make')
sudo('make install')
sudo('ln -s /usr/local/bin/pgbouncer /usr/sbin/pgbouncer')
config_pgbouncer()
def config_pgbouncer():
sudo('mkdir -p /etc/pgbouncer')
put('config/pgbouncer.conf', 'pgbouncer.conf')
sudo('mv pgbouncer.conf /etc/pgbouncer/pgbouncer.ini')
put(os.path.join(env.SECRETS_PATH, 'configs/pgbouncer_auth.conf'), 'userlist.txt')
sudo('mv userlist.txt /etc/pgbouncer/userlist.txt')
sudo('echo "START=1" | sudo tee /etc/default/pgbouncer')
sudo('su postgres -c "/etc/init.d/pgbouncer stop"', pty=False)
with settings(warn_only=True):
sudo('pkill -9 pgbouncer -e')
run('sleep 2')
sudo('/etc/init.d/pgbouncer start', pty=False)
def kill_pgbouncer(bounce=False):
sudo('su postgres -c "/etc/init.d/pgbouncer stop"', pty=False)
run('sleep 2')
with settings(warn_only=True):
sudo('pkill -9 pgbouncer')
run('sleep 2')
if bounce:
run('sudo /etc/init.d/pgbouncer start', pty=False)
def config_monit_task():
put('config/monit_task.conf', '/etc/monit/conf.d/celery.conf', use_sudo=True)
sudo('echo "START=yes" | sudo tee /etc/default/monit')
sudo('/etc/init.d/monit restart')
def config_monit_node():
put('config/monit_node.conf', '/etc/monit/conf.d/node.conf', use_sudo=True)
sudo('echo "START=yes" | sudo tee /etc/default/monit')
sudo('/etc/init.d/monit restart')
def config_monit_original():
put('config/monit_original.conf', '/etc/monit/conf.d/node_original.conf', use_sudo=True)
sudo('echo "START=yes" | sudo tee /etc/default/monit')
sudo('/etc/init.d/monit restart')
def config_monit_app():
put('config/monit_app.conf', '/etc/monit/conf.d/gunicorn.conf', use_sudo=True)
sudo('echo "START=yes" | sudo tee /etc/default/monit')
sudo('/etc/init.d/monit restart')
def config_monit_work():
put('config/monit_work.conf', '/etc/monit/conf.d/work.conf', use_sudo=True)
sudo('echo "START=yes" | sudo tee /etc/default/monit')
sudo('/etc/init.d/monit restart')
def config_monit_redis():
sudo('chown root.root /etc/init.d/redis')
sudo('chmod a+x /etc/init.d/redis')
put('config/monit_debug.sh', '/etc/monit/monit_debug.sh', use_sudo=True)
sudo('chmod a+x /etc/monit/monit_debug.sh')
put('config/monit_redis.conf', '/etc/monit/conf.d/redis.conf', use_sudo=True)
sudo('echo "START=yes" | sudo tee /etc/default/monit')
sudo('/etc/init.d/monit restart')
def setup_mongoengine_repo():
with cd(env.VENDOR_PATH), settings(warn_only=True):
run('rm -fr mongoengine')
run('git clone https://github.com/MongoEngine/mongoengine.git')
sudo('rm -fr /usr/local/lib/python2.7/dist-packages/mongoengine')
sudo('rm -fr /usr/local/lib/python2.7/dist-packages/mongoengine-*')
sudo('ln -sfn %s /usr/local/lib/python2.7/dist-packages/mongoengine' %
os.path.join(env.VENDOR_PATH, 'mongoengine/mongoengine'))
with cd(os.path.join(env.VENDOR_PATH, 'mongoengine')), settings(warn_only=True):
run('git co v0.8.2')
def clear_pymongo_repo():
sudo('rm -fr /usr/local/lib/python2.7/dist-packages/pymongo*')
sudo('rm -fr /usr/local/lib/python2.7/dist-packages/bson*')
sudo('rm -fr /usr/local/lib/python2.7/dist-packages/gridfs*')
def setup_pymongo_repo():
with cd(env.VENDOR_PATH), settings(warn_only=True):
run('git clone git://github.com/mongodb/mongo-python-driver.git pymongo')
# with cd(os.path.join(env.VENDOR_PATH, 'pymongo')):
# sudo('python setup.py install')
clear_pymongo_repo()
sudo('ln -sfn %s /usr/local/lib/python2.7/dist-packages/' %
os.path.join(env.VENDOR_PATH, 'pymongo/{pymongo,bson,gridfs}'))
def setup_forked_mongoengine():
with cd(os.path.join(env.VENDOR_PATH, 'mongoengine')), settings(warn_only=True):
run('git remote add clay https://github.com/samuelclay/mongoengine.git')
run('git pull')
run('git fetch clay')
run('git checkout -b clay_master clay/master')
def switch_forked_mongoengine():
with cd(os.path.join(env.VENDOR_PATH, 'mongoengine')):
run('git co dev')
run('git pull %s dev --force' % env.user)
# run('git checkout .')
# run('git checkout master')
# run('get branch -D dev')
# run('git checkout -b dev origin/dev')
def setup_logrotate(clear=True):
if clear:
run('find /srv/newsblur/logs/*.log | xargs tee')
put('config/logrotate.conf', '/etc/logrotate.d/newsblur', use_sudo=True)
put('config/logrotate.mongo.conf', '/etc/logrotate.d/mongodb', use_sudo=True)
put('config/logrotate.nginx.conf', '/etc/logrotate.d/nginx', use_sudo=True)
sudo('chown root.root /etc/logrotate.d/{newsblur,mongodb,nginx}')
sudo('chmod 644 /etc/logrotate.d/{newsblur,mongodb,nginx}')
with settings(warn_only=True):
sudo('chown sclay.sclay /srv/newsblur/logs/*.log')
sudo('logrotate -f /etc/logrotate.d/newsblur')
sudo('logrotate -f /etc/logrotate.d/nginx')
sudo('logrotate -f /etc/logrotate.d/mongodb')
def setup_ulimit():
# Increase File Descriptor limits.
run('export FILEMAX=`sysctl -n fs.file-max`', pty=False)
sudo('mv /etc/security/limits.conf /etc/security/limits.conf.bak', pty=False)
sudo('touch /etc/security/limits.conf', pty=False)
run('echo "root soft nofile 100000\n" | sudo tee -a /etc/security/limits.conf', pty=False)
run('echo "root hard nofile 100000\n" | sudo tee -a /etc/security/limits.conf', pty=False)
run('echo "* soft nofile 100000\n" | sudo tee -a /etc/security/limits.conf', pty=False)
run('echo "* hard nofile 100090\n" | sudo tee -a /etc/security/limits.conf', pty=False)
run('echo "fs.file-max = 100000\n" | sudo tee -a /etc/sysctl.conf', pty=False)
sudo('sysctl -p')
sudo('ulimit -n 100000')
connections.connect(env.host_string)
# run('touch /home/ubuntu/.bash_profile')
# run('echo "ulimit -n $FILEMAX" >> /home/ubuntu/.bash_profile')
# Increase Ephemeral Ports.
# sudo chmod 666 /etc/sysctl.conf
# echo "net.ipv4.ip_local_port_range = 1024 65535" >> /etc/sysctl.conf
# sudo chmod 644 /etc/sysctl.conf
def setup_syncookies():
sudo('echo 1 | sudo tee /proc/sys/net/ipv4/tcp_syncookies')
sudo('sudo /sbin/sysctl -w net.ipv4.tcp_syncookies=1')
def setup_sudoers(user=None):
sudo('echo "%s ALL=(ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/sclay' % (user or env.user))
sudo('chmod 0440 /etc/sudoers.d/sclay')
def setup_nginx():
NGINX_VERSION = '1.6.2'
with cd(env.VENDOR_PATH), settings(warn_only=True):
sudo("groupadd nginx")
sudo("useradd -g nginx -d /var/www/htdocs -s /bin/false nginx")
run('wget http://nginx.org/download/nginx-%s.tar.gz' % NGINX_VERSION)
run('tar -xzf nginx-%s.tar.gz' % NGINX_VERSION)
run('rm nginx-%s.tar.gz' % NGINX_VERSION)
with cd('nginx-%s' % NGINX_VERSION):
run('./configure --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_realip_module ')
run('make')
sudo('make install')
config_nginx()
def config_nginx():
put("config/nginx.conf", "/usr/local/nginx/conf/nginx.conf", use_sudo=True)
sudo("mkdir -p /usr/local/nginx/conf/sites-enabled")
sudo("mkdir -p /var/log/nginx")
put("config/nginx.newsblur.conf", "/usr/local/nginx/conf/sites-enabled/newsblur.conf", use_sudo=True)
put("config/nginx-init", "/etc/init.d/nginx", use_sudo=True)
sudo('sed -i -e s/nginx_none/`cat /etc/hostname`/g /usr/local/nginx/conf/sites-enabled/newsblur.conf')
sudo("chmod 0755 /etc/init.d/nginx")
sudo("/usr/sbin/update-rc.d -f nginx defaults")
sudo("/etc/init.d/nginx restart")
copy_certificates()
# ===============
# = Setup - App =
# ===============
def setup_app_firewall():
sudo('ufw default deny')
sudo('ufw allow ssh') # ssh
sudo('ufw allow 80') # http
sudo('ufw allow 8000') # gunicorn
sudo('ufw allow 8888') # socket.io
sudo('ufw allow 8889') # socket.io ssl
sudo('ufw allow 443') # https
sudo('ufw --force enable')
def remove_gunicorn():
with cd(env.VENDOR_PATH):
sudo('rm -fr gunicorn')
def setup_gunicorn(supervisor=True, restart=True):
if supervisor:
put('config/supervisor_gunicorn.conf', '/etc/supervisor/conf.d/gunicorn.conf', use_sudo=True)
sudo('supervisorctl reread')
if restart:
restart_gunicorn()
# with cd(env.VENDOR_PATH):
# sudo('rm -fr gunicorn')
# run('git clone git://github.com/benoitc/gunicorn.git')
# with cd(os.path.join(env.VENDOR_PATH, 'gunicorn')):
# run('git pull')
# sudo('python setup.py develop')
def update_gunicorn():
with cd(os.path.join(env.VENDOR_PATH, 'gunicorn')):
run('git pull')
sudo('python setup.py develop')
def setup_staging():
run('git clone https://github.com/samuelclay/NewsBlur.git staging')
with cd('~/staging'):
run('cp ../newsblur/local_settings.py local_settings.py')
run('mkdir -p logs')
run('touch logs/newsblur.log')
def setup_node_app():
sudo('add-apt-repository -y ppa:chris-lea/node.js')
sudo('apt-get update')
sudo('apt-get install -y nodejs')
run('curl -L https://npmjs.org/install.sh | sudo sh')
sudo('npm install -g supervisor')
sudo('ufw allow 8888')
def config_node():
sudo('rm -fr /etc/supervisor/conf.d/node.conf')
put('config/supervisor_node_unread.conf', '/etc/supervisor/conf.d/node_unread.conf', use_sudo=True)
put('config/supervisor_node_unread_ssl.conf', '/etc/supervisor/conf.d/node_unread_ssl.conf', use_sudo=True)
put('config/supervisor_node_favicons.conf', '/etc/supervisor/conf.d/node_favicons.conf', use_sudo=True)
sudo('supervisorctl reload')
@parallel
def copy_app_settings():
put(os.path.join(env.SECRETS_PATH, 'settings/app_settings.py'),
'%s/local_settings.py' % env.NEWSBLUR_PATH)
run('echo "\nSERVER_NAME = \\\\"`hostname`\\\\"" >> %s/local_settings.py' % env.NEWSBLUR_PATH)
def assemble_certificates():
with lcd(os.path.join(env.SECRETS_PATH, 'certificates/comodo')):
local('pwd')
local('cat STAR_newsblur_com.crt EssentialSSLCA_2.crt ComodoUTNSGCCA.crt UTNAddTrustSGCCA.crt AddTrustExternalCARoot.crt > newsblur.com.crt')
def copy_certificates():
cert_path = '%s/config/certificates' % env.NEWSBLUR_PATH
run('mkdir -p %s' % cert_path)
put(os.path.join(env.SECRETS_PATH, 'certificates/newsblur.com.crt'), cert_path)
put(os.path.join(env.SECRETS_PATH, 'certificates/newsblur.com.key'), cert_path)
put(os.path.join(env.SECRETS_PATH, 'certificates/comodo/newsblur.com.pem'), cert_path)
run('cat %s/newsblur.com.pem > %s/newsblur.pem' % (cert_path, cert_path))
run('cat %s/newsblur.com.key >> %s/newsblur.pem' % (cert_path, cert_path))
@parallel
def maintenance_on():
put('templates/maintenance_off.html', '%s/templates/maintenance_off.html' % env.NEWSBLUR_PATH)
with virtualenv():
run('mv templates/maintenance_off.html templates/maintenance_on.html')
@parallel
def maintenance_off():
with virtualenv():
run('mv templates/maintenance_on.html templates/maintenance_off.html')
run('git checkout templates/maintenance_off.html')
def setup_haproxy(debug=False):
version = "1.5.14"
sudo('ufw allow 81') # nginx moved
sudo('ufw allow 1936') # haproxy stats
# sudo('apt-get install -y haproxy')
# sudo('apt-get remove -y haproxy')
with cd(env.VENDOR_PATH):
run('wget http://www.haproxy.org/download/1.5/src/haproxy-%s.tar.gz' % version)
run('tar -xf haproxy-%s.tar.gz' % version)
with cd('haproxy-%s' % version):
run('make TARGET=linux2628 USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1')
sudo('make install')
put('config/haproxy-init', '/etc/init.d/haproxy', use_sudo=True)
sudo('chmod u+x /etc/init.d/haproxy')
sudo('mkdir -p /etc/haproxy')
if debug:
put('config/debug_haproxy.conf', '/etc/haproxy/haproxy.cfg', use_sudo=True)
else:
put(os.path.join(env.SECRETS_PATH, 'configs/haproxy.conf'),
'/etc/haproxy/haproxy.cfg', use_sudo=True)
sudo('echo "ENABLED=1" | sudo tee /etc/default/haproxy')
cert_path = "%s/config/certificates" % env.NEWSBLUR_PATH
run('cat %s/newsblur.com.crt > %s/newsblur.pem' % (cert_path, cert_path))
run('cat %s/newsblur.com.key >> %s/newsblur.pem' % (cert_path, cert_path))
put('config/haproxy_rsyslog.conf', '/etc/rsyslog.d/49-haproxy.conf', use_sudo=True)
sudo('restart rsyslog')
sudo('update-rc.d -f haproxy defaults')
sudo('/etc/init.d/haproxy stop')
run('sleep 1')
sudo('/etc/init.d/haproxy start')
def config_haproxy(debug=False):
if debug:
put('config/debug_haproxy.conf', '/etc/haproxy/haproxy.cfg', use_sudo=True)
else:
put(os.path.join(env.SECRETS_PATH, 'configs/haproxy.conf'),
'/etc/haproxy/haproxy.cfg', use_sudo=True)
haproxy_check = run('haproxy -c -f /etc/haproxy/haproxy.cfg')
if haproxy_check.return_code == 0:
sudo('/etc/init.d/haproxy reload')
else:
print " !!!> Uh-oh, HAProxy config doesn't check out: %s" % haproxy_check.return_code
def upgrade_django():
with virtualenv(), settings(warn_only=True):
sudo('supervisorctl stop gunicorn')
run('./utils/kill_gunicorn.sh')
sudo('easy_install -U django gunicorn')
pull()
sudo('supervisorctl reload')
def upgrade_pil():
with virtualenv():
pull()
sudo('pip install --upgrade pillow')
# celery_stop()
sudo('apt-get remove -y python-imaging')
sudo('supervisorctl reload')
# kill()
def downgrade_pil():
with virtualenv():
sudo('apt-get install -y python-imaging')
sudo('rm -fr /usr/local/lib/python2.7/dist-packages/Pillow*')
pull()
sudo('supervisorctl reload')
# kill()
def setup_db_monitor():
pull()
with virtualenv():
sudo('apt-get install -y python-mysqldb')
sudo('apt-get install -y libpq-dev python-dev')
sudo('pip install -r flask/requirements.txt')
put('flask/supervisor_db_monitor.conf', '/etc/supervisor/conf.d/db_monitor.conf', use_sudo=True)
sudo('supervisorctl reread')
sudo('supervisorctl update')
# ==============
# = Setup - DB =
# ==============
@parallel
def setup_db_firewall():
ports = [
5432, # PostgreSQL
27017, # MongoDB
28017, # MongoDB web
27019, # MongoDB config
6379, # Redis
# 11211, # Memcached
3060, # Node original page server
9200, # Elasticsearch
5000, # DB Monitor
]
sudo('ufw --force reset')
sudo('ufw default deny')
sudo('ufw allow ssh')
sudo('ufw allow 80')
# DigitalOcean
for ip in set(env.roledefs['app'] +
env.roledefs['db'] +
env.roledefs['debug'] +
env.roledefs['task'] +
env.roledefs['work'] +
env.roledefs['push'] +
env.roledefs['www'] +
env.roledefs['search'] +
env.roledefs['node']):
sudo('ufw allow proto tcp from %s to any port %s' % (
ip,
','.join(map(str, ports))
))
# EC2
# for host in set(env.roledefs['ec2task']):
# ip = re.search('ec2-(\d+-\d+-\d+-\d+)', host).group(1).replace('-', '.')
# sudo('ufw allow proto tcp from %s to any port %s' % (
# ip,
# ','.join(map(str, ports))
# ))
sudo('ufw --force enable')
def setup_rabbitmq():
sudo('echo "deb http://www.rabbitmq.com/debian/ testing main" | sudo tee -a /etc/apt/sources.list')
run('wget http://www.rabbitmq.com/rabbitmq-signing-key-public.asc')
sudo('apt-key add rabbitmq-signing-key-public.asc')
run('rm rabbitmq-signing-key-public.asc')
sudo('apt-get update')
sudo('apt-get install -y rabbitmq-server')
sudo('rabbitmqctl add_user newsblur newsblur')
sudo('rabbitmqctl add_vhost newsblurvhost')
sudo('rabbitmqctl set_permissions -p newsblurvhost newsblur ".*" ".*" ".*"')
# def setup_memcached():
# sudo('apt-get -y install memcached')
def setup_postgres(standby=False):
shmmax = 17672445952
hugepages = 9000
sudo('echo "deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list')
sudo('wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -')
sudo('apt-get update')
sudo('apt-get -y install postgresql-9.4 postgresql-client-9.4 postgresql-contrib-9.4 libpq-dev')
put('config/postgresql.conf', '/etc/postgresql/9.4/main/postgresql.conf', use_sudo=True)
put('config/postgresql_hba.conf', '/etc/postgresql/9.4/main/pg_hba.conf', use_sudo=True)
sudo('echo "%s" | sudo tee /proc/sys/kernel/shmmax' % shmmax)
sudo('echo "\nkernel.shmmax = %s" | sudo tee -a /etc/sysctl.conf' % shmmax)
sudo('echo "\nvm.nr_hugepages = %s\n" | sudo tee -a /etc/sysctl.conf' % hugepages)
sudo('sysctl -p')
if standby:
put('config/postgresql_recovery.conf', '/var/lib/postgresql/9.4/recovery.conf', use_sudo=True)
sudo('/etc/init.d/postgresql stop')
sudo('/etc/init.d/postgresql start')
def config_postgres(standby=False):
put('config/postgresql.conf', '/etc/postgresql/9.4/main/postgresql.conf', use_sudo=True)
sudo('/etc/init.d/postgresql reload 9.4')
def copy_postgres_to_standby(master='db01'):
# http://www.rassoc.com/gregr/weblog/2013/02/16/zero-to-postgresql-streaming-replication-in-10-mins/
# Make sure you can ssh from master to slave and back with the postgres user account.
# Need to give postgres accounts keys in authroized_keys.
# sudo('su postgres -c "psql -c \"SELECT pg_start_backup(\'label\', true)\""', pty=False)
# sudo('su postgres -c \"rsync -a --stats --progress /var/lib/postgresql/9.4/main postgres@%s:/var/lib/postgresql/9.4/ --exclude postmaster.pid\"' % slave, pty=False)
# sudo('su postgres -c "psql -c \"SELECT pg_stop_backup()\""', pty=False)
# sudo('su postgres -c "pg_basebackup -h %s -D /var/lib/postgresql/9.4/main -v -P -X fetch"' % master)
put('config/postgresql_recovery.conf', '/var/lib/postgresql/9.4/main/recovery.conf', use_sudo=True)
def setup_mongo():
sudo('apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10')
# sudo('echo "deb http://downloads.mongodb.org/distros/ubuntu 10.10 10gen" >> /etc/apt/sources.list.d/10gen.list')
sudo('echo "\ndeb http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen" | sudo tee -a /etc/apt/sources.list')
sudo('apt-get update')
sudo('apt-get -y install mongodb-10gen')
put('config/mongodb.%s.conf' % ('prod' if env.user != 'ubuntu' else 'ec2'),
'/etc/mongodb.conf', use_sudo=True)
run('echo "ulimit -n 100000" > mongodb.defaults')
sudo('mv mongodb.defaults /etc/default/mongodb')
sudo('/etc/init.d/mongodb restart')
put('config/logrotate.mongo.conf', '/etc/logrotate.d/mongodb', use_sudo=True)
# Reclaim 5% disk space used for root logs. Set to 1%.
with settings(warn_only=True):
sudo('tune2fs -m 1 /dev/vda')
def setup_mongo_configsvr():
sudo('mkdir -p /var/lib/mongodb_configsvr')
sudo('chown mongodb.mongodb /var/lib/mongodb_configsvr')
put('config/mongodb.configsvr.conf', '/etc/mongodb.configsvr.conf', use_sudo=True)
put('config/mongodb.configsvr-init', '/etc/init.d/mongodb-configsvr', use_sudo=True)
sudo('chmod u+x /etc/init.d/mongodb-configsvr')
run('echo "ulimit -n 100000" > mongodb_configsvr.defaults')
sudo('mv mongodb_configsvr.defaults /etc/default/mongodb_configsvr')
sudo('update-rc.d -f mongodb-configsvr defaults')
sudo('/etc/init.d/mongodb-configsvr start')
def setup_mongo_mongos():