[modules] add 2 execution commands: restore and reset_password
authorDavid Douard <david.douard@logilab.fr>
Tue, 19 May 2015 14:34:01 +0200
changeset 26 1c03667c96dd
parent 25 83c1a8d26a29
child 27 9e89d6d03ca9
[modules] add 2 execution commands: restore and reset_password - *reset_password* encapsulate "cubicweb-ctl reset-admin-pwd" - *restore* restore a postgresql database from a dump **without** using "cubicweb-ctl db-restore" (since this later does not play nicely with non-interactive sessions, and postgres database setup is managed by salt, not by cubicweb-ctl, which allows to have non-admin db users).
_modules/cubicweb.py
--- a/_modules/cubicweb.py	Tue May 19 14:12:38 2015 +0200
+++ b/_modules/cubicweb.py	Tue May 19 14:34:01 2015 +0200
@@ -9,9 +9,15 @@
 import pipes
 import logging
 import re
+import shutil
+import os
+import tempfile
+from subprocess import list2cmdline
+import tarfile
+from ConfigParser import ConfigParser
 
 # Import salt libs
-from salt.utils import check_or_die
+from salt.utils import check_or_die, strip_proto
 from salt.exceptions import CommandNotFoundError
 
 log = logging.getLogger(__name__)
@@ -206,6 +212,63 @@
         cmd += ' --drop'
     return __salt__['cmd.run'](cmd)
 
+def _pgdbcmd(cmd, dbhost, dbport, dbuser, *args, **kw):
+        cmd = [cmd]
+        cmd += args
+        if dbhost:
+            cmd.append('--host={0}'.format(dbhost))
+        if dbport:
+            cmd.append('--port={0}'.format(dbport))
+        if dbuser:
+            cmd.append('--username={0}'.format(dbuser))
+        for k, v in kw.items():
+            cmd.append('--{0}={1}'.format(k, v))    
+        return cmd
+
+def restore(name, dumpfileurl, drop=False):
+    '''Restore the database for an instance from a dump file
+    '''
+    dumpfile = strip_proto(dumpfileurl)
+    tmpdir = tempfile.mkdtemp()
+    ret = {}
+    try:
+        os.chdir(tmpdir)
+        dst = os.path.join(tmpdir, os.path.basename(dumpfile))
+        out = __salt__['cp.get_url'](dumpfileurl, dst)
+
+        ret['cp'] = out
+        ret['tmpdir'] = tmpdir
+        with tarfile.open(dst, 'r|gz') as bkup:
+            bkup.extractall()
+        cwsrc = ConfigParser()
+        cfgfile = os.path.join('/etc/cubicweb.d', name, 'sources')
+        ret['cfgfile'] = (cfgfile, os.path.isfile(cfgfile))
+        ret['cfg'] = cwsrc.read(cfgfile)
+        
+        src = dict(cwsrc.items('system'))
+
+        pgpass = os.path.join(tmpdir, '.pgpass')
+        with open(pgpass, 'w') as pgpassfile:
+            pgpassfile.write('*:*:{0}:{1}:{2}\n'.format(src['db-name'],
+                                                        src['db-user'],
+                                                        src['db-password']))
+        os.chmod(pgpass, 0600)
+        env = {'PGPASSFILE': pgpass}
+        cmd = _pgdbcmd('pg_restore', 
+                       src.get('db-host'),
+                       src.get('db-port'),
+                       src.get('db-user'),
+                       '-w', dbname=src['db-name'],
+                   )
+        cmd.append(os.path.join(tmpdir, 'system'))
+        ret['pg_restore'] = __salt__['cmd.run'](list2cmdline(cmd), env=env)
+    except Exception as exc:
+        ret['error'] = repr(exc)
+        raise
+    finally:
+        shutil.rmtree(tmpdir)
+        return ret
+
 def delete(name):
     '''Delete an instance
     '''
@@ -239,3 +302,12 @@
     result = __salt__['cmd.run'](cmd)
     log.debug('restart {0}: {1!r}'.format(name, result))
     return result
+ 
+def reset_password(name, password):
+    '''Reset the admin password for an instance
+    '''
+    cmd = 'cubicweb-ctl reset-admin-pwd {0} -p {1}'.format(name, password)
+    result = __salt__['cmd.run'](cmd)
+    log.debug('reset_password {0}: {1!r}'.format(name, result))
+    return result
+