PageRenderTime 122ms CodeModel.GetById 60ms app.highlight 7ms RepoModel.GetById 53ms app.codeStats 0ms

/silversupport/service/files.py

https://bitbucket.org/ianb/silverlining/
Python | 72 lines | 56 code | 12 blank | 4 comment | 10 complexity | 8ec51f593234c23dcfc9097482dee12d MD5 | raw file
 1"""Gives a persistent location to keep files"""
 2
 3import os
 4import pwd
 5import grp
 6import shutil
 7from silversupport.shell import run
 8from silversupport.abstractservice import AbstractService
 9
10
11class AbstractFileService(AbstractService):
12
13    root = None
14    env_var = None
15    home_name = None
16
17    def dir_for_app_name(self, app_name):
18        return os.path.join(self.root, app_name)
19
20    def install(self):
21        dir = self.dir_for_app_name(self.app_config.app_name)
22        if not os.path.exists(dir):
23            os.makedirs(dir)
24            uid = pwd.getpwnam('www-data').pw_uid
25            gid = grp.getgrnam('www-data').gr_gid
26            os.chown(dir, uid, gid)
27
28    def env_setup(self):
29        environ = {}
30        app_name = self.app_config.app_name
31        if not self.devel:
32            dir = self.dir_for_app_name(app_name)
33            environ[self.env_var] = dir
34        else:
35            environ[self.env_var] = os.path.join(
36                os.environ['HOME'],
37                '.silverlining-app-data',
38                self.home_name,
39                app_name)
40            if 'files' in self.devel_config:
41                environ[self.env_var] = os.path.expanduser(
42                    self.devel_config['files'])
43            if not os.path.exists(environ[self.env_var]):
44                print 'Creating file location %s' % environ[self.env_var]
45                os.makedirs(environ[self.env_var])
46        return environ
47
48    def backup(self, output_dir):
49        path = self.env[self.env_var]
50        ## FIXME: should this be compressed, or just rely on that to
51        ## happen at a higher level?
52        ## Or should it be a tar at all, or just a copy of the files?
53        run(['tar', 'fc', os.path.join(output_dir, 'files.tar'), '.'],
54            cwd=path, fail_on_error=True)
55
56    def restore(self, input_dir):
57        path = self.env[self.env_var]
58        tar_path = os.path.join(input_dir, 'files.tar')
59        run(['sudo', '-u', 'www-data', 'tar', 'fx', tar_path],
60            cwd=path, fail_on_error=True)
61
62    def clear(self):
63        path = self.env[self.env_var]
64        for p in os.listdir(path):
65            p = os.path.join(path, p)
66            shutil.rmtree(p)
67
68
69class Service(AbstractFileService):
70    root = '/var/lib/silverlining/apps'
71    env_var = 'CONFIG_FILES'
72    home_name = 'files'