Vladimir Mihailenco avatar Vladimir Mihailenco committed 59d893e

Add postgres support

Comments (0)

Files changed (2)

fab_deploy_ext/postgresql.py

+import datetime
+import posixpath
+
+from fabric.tasks import Task as BaseTask
+from fabric.api import settings
+from fabric.api import run
+from fabric.api import sudo
+from fabric.api import env
+from fabric import state
+
+from fab_deploy.utils import run_as_sudo
+
+
+__all__ = ['pg_dump', 'pg_create_user', 'pg_grant', 'pg_create_db']
+
+
+class Task(BaseTask):
+    def __init__(self, conf=None):
+        if conf is not None:
+            self.conf = conf
+
+    def do(self):
+        raise NotImplementedError()
+
+    def update_conf(self, conf):
+        pass
+
+    def run(self, *args, **kwargs):
+        self.conf = state._AttributeDict()
+
+        for k, v in env.conf.items():
+            self.conf[k.lower()] = v
+
+        for k, v in kwargs.items():
+            if v is not None:
+                self.conf[k] = v
+
+        self.update_conf(self.conf)
+
+        with settings(**kwargs):
+            self.do()
+
+    def __getattr__(self, name):
+        if 'conf' in self.__dict__:
+            if name in self.conf:
+                return self.conf[name]
+        raise AttributeError()
+
+    def __getitem__(self, key):
+        if hasattr(self, key):
+            return getattr(self, key)
+        return self.conf[key]
+
+
+class PgDump(Task):
+    name = 'pg_dump'
+
+    @property
+    def dirname(self):
+        if not self.conf.get('dirname'):
+            self.conf.dirname = self.conf.env_dir + '/var/backups'
+            run('mkdir --parents ' + self.conf.dirname)
+        return self.conf.dirname
+
+    @property
+    def filename(self):
+        now = datetime.datetime.now().strftime('%Y.%m.%d-%H.%M')
+        return '%s%s.pgc' % (self.db_name, now)
+
+    @property
+    def filepath(self):
+        return posixpath.join(self.project_dir, self.dirname,
+                              self.filename)
+
+    @property
+    def cmd(self):
+        return ('pg_dump --host=localhost --username=%(db_user)s '
+                '--format=c --file=%(filepath)s %(db_name)s')
+
+    @run_as_sudo
+    def do(self):
+        return sudo(self.cmd % self)
+
+pg_dump = PgDump()
+
+
+class PgExecute(Task):
+    name = 'pg_execute'
+
+    @property
+    def cmd(self):
+        return 'sudo -u %(db_root_user)s psql --command="%(command)s"'
+
+    @property
+    def sql():
+        raise NotImplementedError()
+
+    @property
+    def command(self):
+        return self.sql.replace('"', r'\"')
+
+    @run_as_sudo
+    def do(self):
+        return run(self.cmd % self)
+
+pg_execute = PgExecute()
+
+
+class PgCreateUser(PgExecute):
+    name = 'pg_create_user'
+
+    SQL_CREATE_ROLE = """
+    CREATE ROLE %(db_user)s WITH LOGIN PASSWORD '%(db_password)s';
+    """.strip()
+
+    @property
+    def sql(self):
+        return self.SQL_CREATE_ROLE % self
+
+pg_create_user = PgCreateUser()
+
+
+class PgGrant(PgExecute):
+    name = 'pg_grant'
+
+    SQL_GRANT = """
+    GRANT ALL PRIVILEGES ON DATABASE %(db_name)s TO %(db_user)s;
+    """.strip()
+
+    @property
+    def sql(self):
+        return self.SQL_GRANT % self
+
+pg_grant = PgGrant()
+
+
+class PgCreateDb(PgExecute):
+    name = 'pg_create_db'
+
+    SQL_CREATE_DB = """
+    CREATE DATABASE %(db_name)s WITH OWNER %(db_user)s;
+    """.strip()
+
+    @property
+    def sql(self):
+        return self.SQL_CREATE_DB % self
+
+pg_create_db = PgCreateDb()

fab_deploy_ext/ssh.py

 import re
 import datetime
 
-from fabric.api import get
 from fabric.contrib.files import comment
 from fabric.contrib.files import uncomment
 from fabric.contrib.files import exists
 
 def ssh_list_keys(users=None, exclude_users=None,  include_comments=False,
                   use_sudo=False):
-    for user, authorized_keys in ssh_list_files(users, exclude_users=exclude_users):
+    for user, authorized_keys in ssh_list_files(users,
+                                                exclude_users=exclude_users):
         content = file.file_read(authorized_keys, use_sudo=True)
         for ssh_key in utils.split_lines(content):
             if not include_comments and ssh_key.startswith('#'):
 
     now = datetime.datetime.now().strftime('%Y.%m.%d-%H.%M')
     backup = '.%s.bak' % now
-    for user, authorized_keys in ssh_list_files(users, exclude_users=exclude_users):
+    for user, authorized_keys in ssh_list_files(users,
+                                                exclude_users=exclude_users):
         comment(authorized_keys, regex, use_sudo=use_sudo, backup=backup)
 
 
 
     now = datetime.datetime.now().strftime('%Y.%m.%d-%H.%M')
     backup = '.%s.bak' % now
-    for user, authorized_keys in ssh_list_files(users, exclude_users=exclude_users):
+    for user, authorized_keys in ssh_list_files(users,
+                                                exclude_users=exclude_users):
         uncomment(authorized_keys, regex, use_sudo=use_sudo, backup=backup)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.