Advertisement
Guest User

Untitled

a guest
Sep 30th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.35 KB | None | 0 0
  1. from __future__ import print_function, unicode_literals
  2. from future.builtins import open
  3.  
  4. import os
  5. import re
  6. import sys
  7. from contextlib import contextmanager
  8. from functools import wraps
  9. from getpass import getpass, getuser
  10. from glob import glob
  11. from importlib import import_module
  12. from posixpath import join
  13.  
  14. from mezzanine.utils.conf import real_project_name
  15.  
  16. from fabric.api import abort, env, cd, prefix, sudo as _sudo, run as _run, \
  17. hide, task, local
  18. from fabric.context_managers import settings as fab_settings
  19. from fabric.contrib.console import confirm
  20. from fabric.contrib.files import exists, upload_template
  21. from fabric.contrib.project import rsync_project
  22. from fabric.colors import yellow, green, blue, red
  23. from fabric.decorators import hosts
  24.  
  25.  
  26. ################
  27. # Config setup #
  28. ################
  29.  
  30. env.proj_app = real_project_name("in1_insider_intranet")
  31.  
  32. conf = {}
  33. if sys.argv[0].split(os.sep)[-1] in ("fab", "fab-script.py"):
  34. # Ensure we import settings from the current dir
  35. try:
  36. conf = import_module("%s.settings" % env.proj_app).FABRIC
  37. try:
  38. conf["HOSTS"][0]
  39. except (KeyError, ValueError):
  40. raise ImportError
  41. except (ImportError, AttributeError):
  42. print("Aborting, no hosts defined.")
  43. exit()
  44.  
  45. env.db_pass = conf.get("DB_PASS", None)
  46. env.admin_pass = conf.get("ADMIN_PASS", None)
  47. env.user = conf.get("SSH_USER", getuser())
  48. env.password = conf.get("SSH_PASS", None)
  49. env.key_filename = conf.get("SSH_KEY_PATH", None)
  50. env.hosts = conf.get("HOSTS", [""])
  51. env.proj_name = conf.get("PROJECT_NAME", env.proj_app)
  52. env.venv_home = conf.get("VIRTUALENV_HOME", "/home/%s/.virtualenvs" % env.user)
  53. env.venv_path = join(env.venv_home, env.proj_name)
  54. env.proj_path = "/home/%s/mezzanine/%s" % (env.user, env.proj_name)
  55. env.manage = "%s/bin/python %s/manage.py" % (env.venv_path, env.proj_path)
  56. env.domains = conf.get("DOMAINS", [conf.get("LIVE_HOSTNAME", env.hosts[0])])
  57. env.domains_nginx = " ".join(env.domains)
  58. env.domains_regex = "|".join(env.domains)
  59. env.domains_python = ", ".join(["'%s'" % s for s in env.domains])
  60. env.ssl_disabled = "#" if len(env.domains) > 1 else ""
  61. env.vcs_tools = ["git", "hg"]
  62. env.deploy_tool = conf.get("DEPLOY_TOOL", "rsync")
  63. env.reqs_path = conf.get("REQUIREMENTS_PATH", None)
  64. env.locale = conf.get("LOCALE", "en_US.UTF-8")
  65. env.num_workers = conf.get("NUM_WORKERS",
  66. "multiprocessing.cpu_count() * 2 + 1")
  67.  
  68. env.secret_key = conf.get("SECRET_KEY", "")
  69. env.nevercache_key = conf.get("NEVERCACHE_KEY", "")
  70.  
  71. # Remote git repos need to be "bare" and reside separated from the project
  72. if env.deploy_tool == "git":
  73. env.repo_path = "/home/%s/git/%s.git" % (env.user, env.proj_name)
  74. else:
  75. env.repo_path = env.proj_path
  76.  
  77.  
  78. ##################
  79. # Template setup #
  80. ##################
  81.  
  82. # Each template gets uploaded at deploy time, only if their
  83. # contents has changed, in which case, the reload command is
  84. # also run.
  85.  
  86. templates = {
  87. "nginx": {
  88. "local_path": "deploy/nginx.conf.template",
  89. "remote_path": "/etc/nginx/sites-enabled/%(proj_name)s.conf",
  90. "reload_command": "service nginx restart",
  91. },
  92. "supervisor": {
  93. "local_path": "deploy/supervisor.conf.template",
  94. "remote_path": "/etc/supervisor/conf.d/%(proj_name)s.conf",
  95. "reload_command": "supervisorctl update gunicorn_%(proj_name)s",
  96. },
  97. "cron": {
  98. "local_path": "deploy/crontab.template",
  99. "remote_path": "/etc/cron.d/%(proj_name)s",
  100. "owner": "root",
  101. "mode": "600",
  102. },
  103. "gunicorn": {
  104. "local_path": "deploy/gunicorn.conf.py.template",
  105. "remote_path": "%(proj_path)s/gunicorn.conf.py",
  106. },
  107. "settings": {
  108. "local_path": "deploy/local_settings.py.template",
  109. "remote_path": "%(proj_path)s/%(proj_app)s/local_settings.py",
  110. },
  111. }
  112.  
  113.  
  114. ######################################
  115. # Context for virtualenv and project #
  116. ######################################
  117.  
  118. @contextmanager
  119. def virtualenv():
  120. """
  121. Runs commands within the project's virtualenv.
  122. """
  123. with cd(env.venv_path):
  124. with prefix("source %s/bin/activate" % env.venv_path):
  125. yield
  126.  
  127.  
  128. @contextmanager
  129. def project():
  130. """
  131. Runs commands within the project's directory.
  132. """
  133. with virtualenv():
  134. with cd(env.proj_path):
  135. yield
  136.  
  137.  
  138. @contextmanager
  139. def update_changed_requirements():
  140. """
  141. Checks for changes in the requirements file across an update,
  142. and gets new requirements if changes have occurred.
  143. """
  144. reqs_path = join(env.proj_path, env.reqs_path)
  145. get_reqs = lambda: run("cat %s" % reqs_path, show=False)
  146. old_reqs = get_reqs() if env.reqs_path else ""
  147. yield
  148. if old_reqs:
  149. new_reqs = get_reqs()
  150. if old_reqs == new_reqs:
  151. # Unpinned requirements should always be checked.
  152. for req in new_reqs.split("\n"):
  153. if req.startswith("-e"):
  154. if "@" not in req:
  155. # Editable requirement without pinned commit.
  156. break
  157. elif req.strip() and not req.startswith("#"):
  158. if not set(">=<") & set(req):
  159. # PyPI requirement without version.
  160. break
  161. else:
  162. # All requirements are pinned.
  163. return
  164. pip("-r %s/%s" % (env.proj_path, env.reqs_path))
  165.  
  166.  
  167. ###########################################
  168. # Utils and wrappers for various commands #
  169. ###########################################
  170.  
  171. def _print(output):
  172. print()
  173. print(output)
  174. print()
  175.  
  176.  
  177. def print_command(command):
  178. _print(blue("$ ", bold=True) +
  179. yellow(command, bold=True) +
  180. red(" ->", bold=True))
  181.  
  182.  
  183. @task
  184. def run(command, show=True, *args, **kwargs):
  185. """
  186. Runs a shell comand on the remote server.
  187. """
  188. if show:
  189. print_command(command)
  190. with hide("running"):
  191. return _run(command, *args, **kwargs)
  192.  
  193.  
  194. @task
  195. def sudo(command, show=True, *args, **kwargs):
  196. """
  197. Runs a command as sudo on the remote server.
  198. """
  199. if show:
  200. print_command(command)
  201. with hide("running"):
  202. return _sudo(command, *args, **kwargs)
  203.  
  204.  
  205. def log_call(func):
  206. @wraps(func)
  207. def logged(*args, **kawrgs):
  208. header = "-" * len(func.__name__)
  209. _print(green("\n".join([header, func.__name__, header]), bold=True))
  210. return func(*args, **kawrgs)
  211. return logged
  212.  
  213.  
  214. def get_templates():
  215. """
  216. Returns each of the templates with env vars injected.
  217. """
  218. injected = {}
  219. for name, data in templates.items():
  220. injected[name] = dict([(k, v % env) for k, v in data.items()])
  221. return injected
  222.  
  223.  
  224. def upload_template_and_reload(name):
  225. """
  226. Uploads a template only if it has changed, and if so, reload the
  227. related service.
  228. """
  229. template = get_templates()[name]
  230. local_path = template["local_path"]
  231. if not os.path.exists(local_path):
  232. project_root = os.path.dirname(os.path.abspath(__file__))
  233. local_path = os.path.join(project_root, local_path)
  234. remote_path = template["remote_path"]
  235. reload_command = template.get("reload_command")
  236. owner = template.get("owner")
  237. mode = template.get("mode")
  238. remote_data = ""
  239. if exists(remote_path):
  240. with show("stdout"):
  241. remote_data = sudo("cat %s" % remote_path, show=False)
  242. with open(local_path, "r") as f:
  243. local_data = f.read()
  244. # Escape all non-string-formatting-placeholder occurrences of '%':
  245. local_data = re.sub(r"%(?!\(\w+\)s)", "%%", local_data)
  246. if "%(db_pass)s" in local_data:
  247. env.db_pass = db_pass()
  248. local_data %= env
  249. clean = lambda s: s.replace("\n", "").replace("\r", "").strip()
  250. if clean(remote_data) == clean(local_data):
  251. return
  252. upload_template(local_path, remote_path, env, use_sudo=True, backup=False)
  253. if owner:
  254. sudo("chown %s %s" % (owner, remote_path))
  255. if mode:
  256. sudo("chmod %s %s" % (mode, remote_path))
  257. if reload_command:
  258. sudo(reload_command)
  259.  
  260.  
  261. def rsync_upload():
  262. """
  263. Uploads the project with rsync excluding some files and folders.
  264. """
  265. excludes = ["*.pyc", "*.pyo", "*.db", ".DS_Store", ".coverage",
  266. "local_settings.py", "/static", "/.git", "/.hg"]
  267. local_dir = os.getcwd() + os.sep
  268. return rsync_project(remote_dir=env.proj_path, local_dir=local_dir,
  269. exclude=excludes)
  270.  
  271.  
  272. def vcs_upload():
  273. """
  274. Uploads the project with the selected VCS tool.
  275. """
  276. if env.deploy_tool == "git":
  277. remote_path = "ssh://%s@%s%s" % (env.user, env.host_string,
  278. env.repo_path)
  279. if not exists(env.repo_path):
  280. run("mkdir -p %s" % env.repo_path)
  281. with cd(env.repo_path):
  282. run("git init --bare")
  283. local("git push -f %s fabric " % remote_path)
  284. with cd(env.repo_path):
  285. run("GIT_WORK_TREE=%s git checkout -f fabric" % env.proj_path)
  286. run("GIT_WORK_TREE=%s git reset --hard" % env.proj_path)
  287. elif env.deploy_tool == "hg":
  288. remote_path = "ssh://%s@%s/%s" % (env.user, env.host_string,
  289. env.repo_path)
  290. with cd(env.repo_path):
  291. if not exists("%s/.hg" % env.repo_path):
  292. run("hg init")
  293. print(env.repo_path)
  294. with fab_settings(warn_only=True):
  295. push = local("hg push -f %s" % remote_path)
  296. if push.return_code == 255:
  297. abort()
  298. run("hg update")
  299.  
  300.  
  301. def db_pass():
  302. """
  303. Prompts for the database password if unknown.
  304. """
  305. if not env.db_pass:
  306. env.db_pass = getpass("Enter the database password: ")
  307. return env.db_pass
  308.  
  309.  
  310. @task
  311. def yum(packages):
  312. """
  313. Installs one or more system packages via yum.
  314. """
  315. return sudo("yum install -y -q " + packages)
  316.  
  317.  
  318. @task
  319. def pip(packages):
  320. """
  321. Installs one or more Python packages within the virtual environment.
  322. """
  323. with virtualenv():
  324. return run("pip install %s" % packages)
  325.  
  326.  
  327. def postgres(command):
  328. """
  329. Runs the given command as the postgres user.
  330. """
  331. show = not command.startswith("psql")
  332. return sudo(command, show=show, user="postgres")
  333.  
  334.  
  335. @task
  336. def psql(sql, show=True):
  337. """
  338. Runs SQL against the project's database.
  339. """
  340. out = postgres('psql -c "%s"' % sql)
  341. if show:
  342. print_command(sql)
  343. return out
  344.  
  345.  
  346. @task
  347. def backup(filename):
  348. """
  349. Backs up the project database.
  350. """
  351. tmp_file = "/tmp/%s" % filename
  352. # We dump to /tmp because user "postgres" can't write to other user folders
  353. # We cd to / because user "postgres" might not have read permissions
  354. # elsewhere.
  355. with cd("/"):
  356. postgres("pg_dump -Fc %s > %s" % (env.proj_name, tmp_file))
  357. run("cp %s ." % tmp_file)
  358. sudo("rm -f %s" % tmp_file)
  359.  
  360.  
  361. @task
  362. def restore(filename):
  363. """
  364. Restores the project database from a previous backup.
  365. """
  366. return postgres("pg_restore -c -d %s %s" % (env.proj_name, filename))
  367.  
  368.  
  369. @task
  370. def python(code, show=True):
  371. """
  372. Runs Python code in the project's virtual environment, with Django loaded.
  373. """
  374. setup = "import os;" \
  375. "os.environ[\'DJANGO_SETTINGS_MODULE\']=\'%s.settings\';" \
  376. "import django;" \
  377. "django.setup();" % env.proj_app
  378. full_code = 'python -c "%s%s"' % (setup, code.replace("`", "\\\`"))
  379. with project():
  380. if show:
  381. print_command(code)
  382. result = run(full_code, show=False)
  383. return result
  384.  
  385.  
  386. def static():
  387. """
  388. Returns the live STATIC_ROOT directory.
  389. """
  390. return python("from django.conf import settings;"
  391. "print(settings.STATIC_ROOT)", show=False).split("\n")[-1]
  392.  
  393.  
  394. @task
  395. def manage(command):
  396. """
  397. Runs a Django management command.
  398. """
  399. return run("%s %s" % (env.manage, command))
  400.  
  401.  
  402. ###########################
  403. # Security best practices #
  404. ###########################
  405.  
  406. @task
  407. @log_call
  408. @hosts(["root@%s" % host for host in env.hosts])
  409. def secure(new_user=env.user):
  410. """
  411. Minimal security steps for brand new servers.
  412. Installs system updates, creates new user (with sudo privileges) for future
  413. usage, and disables root login via SSH.
  414. """
  415. run("yum update -q")
  416. run("yum upgrade -y -q")
  417. run("adduser --gecos '' %s" % new_user)
  418. run("usermod -G wheel %s" % new_user)
  419. run("sed -i 's:RootLogin yes:RootLogin no:' /etc/ssh/sshd_config")
  420. run("service ssh restart")
  421. print(green("Security steps completed. Log in to the server as '%s' from "
  422. "now on." % new_user, bold=True))
  423.  
  424.  
  425. #########################
  426. # Install and configure #
  427. #########################
  428.  
  429. @task
  430. @log_call
  431. def install():
  432. """
  433. Installs the base system and Python requirements for the entire server.
  434. """
  435. # Install system requirements
  436. sudo("yum update -y -q")
  437. yum("nginx libjpeg-dev python-dev python-setuptools git-core libtiff-devel libjpeg-devel libzip-devel freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel "
  438. "postgresql-server postgresql-contrib libpq-dev memcached supervisor python-pip")
  439. run("mkdir -p /home/%s/logs" % env.user)
  440. sudo("mkdir -p /etc/nginx/sites-available")
  441.  
  442. # Install Python requirements
  443. sudo("pip install -U pip virtualenv virtualenvwrapper ")
  444.  
  445. # Set up virtualenv
  446. run("mkdir -p %s" % env.venv_home)
  447. run("echo 'export WORKON_HOME=%s' >> /home/%s/.bashrc" % (env.venv_home,
  448. env.user))
  449. run("echo 'source /usr/bin/virtualenvwrapper.sh' >> "
  450. "/home/%s/.bashrc" % env.user)
  451. print(green("Successfully set up git, pip, virtualenv, "
  452. "supervisor, memcached.", bold=True))
  453.  
  454.  
  455. @task
  456. @log_call
  457. def create():
  458. """
  459. Creates the environment needed to host the project.
  460. The environment consists of: system locales, virtualenv, database, project
  461. files, SSL certificate, and project-specific Python requirements.
  462. """
  463. # Generate project locale
  464. locale = env.locale.replace("UTF-8", "utf8")
  465. with hide("stdout"):
  466. # sudo("postgresql-setup initdb")
  467. sudo("service postgresql restart")
  468.  
  469. # Create project path
  470. run("mkdir -p %s" % env.proj_path)
  471.  
  472. # Set up virtual env
  473. run("mkdir -p %s" % env.venv_home)
  474. with cd(env.venv_home):
  475. if exists(env.proj_name):
  476. if confirm("Virtualenv already exists in host server: %s"
  477. "\nWould you like to replace it?" % env.proj_name):
  478. run("rm -rf %s" % env.proj_name)
  479. else:
  480. abort()
  481. run("virtualenv %s" % env.proj_name)
  482.  
  483. # Upload project files
  484. if env.deploy_tool in env.vcs_tools:
  485. vcs_upload()
  486. else:
  487. rsync_upload()
  488.  
  489. # Create DB and DB user
  490. pw = db_pass()
  491. user_sql_args = (env.proj_name, pw.replace("'", "\'"))
  492. user_sql = "CREATE USER %s WITH ENCRYPTED PASSWORD '%s';" % user_sql_args
  493. psql(user_sql, show=False)
  494. shadowed = "*" * len(pw)
  495. print_command(user_sql.replace("'%s'" % pw, "'%s'" % shadowed))
  496. psql("CREATE DATABASE %s WITH OWNER %s ENCODING = 'UTF8' "
  497. "LC_CTYPE = '%s' LC_COLLATE = '%s' TEMPLATE template0;" %
  498. (env.proj_name, env.proj_name, env.locale, env.locale))
  499.  
  500. # Set up SSL certificate
  501. if not env.ssl_disabled:
  502. conf_path = "/etc/nginx/conf"
  503. if not exists(conf_path):
  504. sudo("mkdir %s" % conf_path)
  505. with cd(conf_path):
  506. crt_file = env.proj_name + ".crt"
  507. key_file = env.proj_name + ".key"
  508. if not exists(crt_file) and not exists(key_file):
  509. try:
  510. crt_local, = glob(join("deploy", "*.crt"))
  511. key_local, = glob(join("deploy", "*.key"))
  512. except ValueError:
  513. parts = (crt_file, key_file, env.domains[0])
  514. sudo("openssl req -new -x509 -nodes -out %s -keyout %s "
  515. "-subj '/CN=%s' -days 3650" % parts)
  516. else:
  517. upload_template(crt_local, crt_file, use_sudo=True)
  518. upload_template(key_local, key_file, use_sudo=True)
  519.  
  520. # Install project-specific requirements
  521. upload_template_and_reload("settings")
  522. with project():
  523. if env.reqs_path:
  524. pip("-r %s/%s" % (env.proj_path, env.reqs_path))
  525. pip("gunicorn setproctitle psycopg2 "
  526. "django-compressor pillow python-memcached")
  527. # Bootstrap the DB
  528. manage("createdb --noinput --nodata")
  529. python("from django.conf import settings;"
  530. "from django.contrib.sites.models import Site;"
  531. "Site.objects.filter(id=settings.SITE_ID).update(domain='%s');"
  532. % env.domains[0])
  533. for domain in env.domains:
  534. python("from django.contrib.sites.models import Site;"
  535. "Site.objects.get_or_create(domain='%s');" % domain)
  536. if env.admin_pass:
  537. pw = env.admin_pass
  538. user_py = ("from django.contrib.auth import get_user_model;"
  539. "User = get_user_model();"
  540. "u, _ = User.objects.get_or_create(username='admin');"
  541. "u.is_staff = u.is_superuser = True;"
  542. "u.set_password('%s');"
  543. "u.save();" % pw)
  544. python(user_py, show=False)
  545. shadowed = "*" * len(pw)
  546. print_command(user_py.replace("'%s'" % pw, "'%s'" % shadowed))
  547.  
  548. return True
  549.  
  550.  
  551. @task
  552. @log_call
  553. def remove():
  554. """
  555. Blow away the current project.
  556. """
  557. if exists(env.venv_path):
  558. run("rm -rf %s" % env.venv_path)
  559. if exists(env.proj_path):
  560. run("rm -rf %s" % env.proj_path)
  561. for template in get_templates().values():
  562. remote_path = template["remote_path"]
  563. if exists(remote_path):
  564. sudo("rm %s" % remote_path)
  565. if exists(env.repo_path):
  566. run("rm -rf %s" % env.repo_path)
  567. sudo("supervisorctl update")
  568. psql("DROP DATABASE IF EXISTS %s;" % env.proj_name)
  569. psql("DROP USER IF EXISTS %s;" % env.proj_name)
  570.  
  571.  
  572. ##############
  573. # Deployment #
  574. ##############
  575.  
  576. @task
  577. @log_call
  578. def restart():
  579. """
  580. Restart gunicorn worker processes for the project.
  581. If the processes are not running, they will be started.
  582. """
  583. pid_path = "%s/gunicorn.pid" % env.proj_path
  584. if exists(pid_path):
  585. run("kill -HUP `cat %s`" % pid_path)
  586. else:
  587. sudo("supervisorctl update")
  588.  
  589.  
  590. @task
  591. @log_call
  592. def deploy():
  593. """
  594. Deploy latest version of the project.
  595. Backup current version of the project, push latest version of the project
  596. via version control or rsync, install new requirements, sync and migrate
  597. the database, collect any new static assets, and restart gunicorn's worker
  598. processes for the project.
  599. """
  600. if not exists(env.proj_path):
  601. if confirm("Project does not exist in host server: %s"
  602. "\nWould you like to create it?" % env.proj_name):
  603. create()
  604. else:
  605. abort()
  606.  
  607. # Backup current version of the project
  608. with cd(env.proj_path):
  609. backup("last.db")
  610. if env.deploy_tool in env.vcs_tools:
  611. with cd(env.repo_path):
  612. if env.deploy_tool == "git":
  613. run("git rev-parse HEAD > %s/last.commit" % env.proj_path)
  614. elif env.deploy_tool == "hg":
  615. run("hg id -i > last.commit")
  616. with project():
  617. static_dir = static()
  618. if exists(static_dir):
  619. run("tar -cf static.tar --exclude='*.thumbnails' %s" %
  620. static_dir)
  621. else:
  622. with cd(join(env.proj_path, "..")):
  623. excludes = ["*.pyc", "*.pio", "*.thumbnails"]
  624. exclude_arg = " ".join("--exclude='%s'" % e for e in excludes)
  625. run("tar -cf {0}.tar {1} {0}".format(env.proj_name, exclude_arg))
  626.  
  627. # Deploy latest version of the project
  628. with update_changed_requirements():
  629. if env.deploy_tool in env.vcs_tools:
  630. vcs_upload()
  631. else:
  632. rsync_upload()
  633. with project():
  634. manage("collectstatic -v 0 --noinput")
  635. manage("migrate --noinput")
  636. for name in get_templates():
  637. upload_template_and_reload(name)
  638. restart()
  639. return True
  640.  
  641.  
  642. @task
  643. @log_call
  644. def rollback():
  645. """
  646. Reverts project state to the last deploy.
  647. When a deploy is performed, the current state of the project is
  648. backed up. This includes the project files, the database, and all static
  649. files. Calling rollback will revert all of these to their state prior to
  650. the last deploy.
  651. """
  652. with update_changed_requirements():
  653. if env.deploy_tool in env.vcs_tools:
  654. with cd(env.repo_path):
  655. if env.deploy_tool == "git":
  656. run("GIT_WORK_TREE={0} git checkout -f "
  657. "`cat {0}/last.commit`".format(env.proj_path))
  658. elif env.deploy_tool == "hg":
  659. run("hg update -C `cat last.commit`")
  660. with project():
  661. with cd(join(static(), "..")):
  662. run("tar -xf %s/static.tar" % env.proj_path)
  663. else:
  664. with cd(env.proj_path.rsplit("/", 1)[0]):
  665. run("rm -rf %s" % env.proj_name)
  666. run("tar -xf %s.tar" % env.proj_name)
  667. with cd(env.proj_path):
  668. restore("last.db")
  669. restart()
  670.  
  671.  
  672. @task
  673. @log_call
  674. def all():
  675. """
  676. Installs everything required on a new system and deploy.
  677. From the base software, up to the deployed project.
  678. """
  679. install()
  680. if create():
  681. deploy()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement