Project

General

Profile

Download (8.04 KB) Statistics
| Branch: | Tag: | Revision:

root / wcsinst / wcsinstd / deploy.py @ b8b9b18f

1
import string
2
import cPickle
3
import os
4
import zipfile
5
import subprocess
6
from urlparse import urlparse
7

    
8
from cStringIO import StringIO
9
import xml.etree.ElementTree as ET
10

    
11
from django.conf import settings
12

    
13
import psycopg2
14

    
15
from . import app_settings
16

    
17

    
18
def get_provider_key(provider_id):
19
    return provider_id.replace('://', '-').replace('/', '-').replace('?', '-').replace(':', '-')
20

    
21

    
22
class DeployInstance(object):
23
    skeleton = 'default'
24

    
25
    skel_dir = None
26
    collectivity_install_dir = None
27

    
28
    def __init__(self, domain, title):
29
        self.domain = domain
30
        self.title = title
31

    
32
    def make(self):
33
        self.skel_dir = os.path.join(settings.MEDIA_ROOT, 'skeletons', self.skeleton)
34

    
35
        url_template = app_settings.URL_TEMPLATE
36
        self.url = url_template % {'domain': self.domain}
37

    
38
        host, path = urlparse(self.url)[1:3]
39
        if path.endswith('/'):
40
            path = path[:-1]
41

    
42
        coldir = host
43
        if path:
44
            coldir += path.replace('/', '+')
45

    
46
        self.collectivity_install_dir = os.path.join(app_settings.WCS_APP_DIR, coldir)
47

    
48
        if os.path.exists(self.collectivity_install_dir):
49
            # site exists, let's update it
50
            pass
51
            anew = False
52
        else:
53
            anew = True
54
            os.mkdir(self.collectivity_install_dir)
55

    
56
        z = zipfile.ZipFile(os.path.join(self.skel_dir, 'export.wcs'), 'r')
57

    
58
        for f in z.namelist():
59
            path = os.path.join(self.collectivity_install_dir, f)
60
            data = z.read(f)
61
            if not os.path.exists(os.path.dirname(path)):
62
                os.mkdir(os.path.dirname(path))
63
            open(path, 'w').write(data)
64
        z.close()
65

    
66
        config_file = os.path.join(self.collectivity_install_dir, 'config.pck')
67
        if os.path.exists(config_file):
68
            wcs_cfg = cPickle.load(file(os.path.join(self.collectivity_install_dir, 'config.pck')))
69
        else:
70
            wcs_cfg = {}
71

    
72
        has_sql = self.make_sql_config(wcs_cfg)
73
        self.make_sso_config(wcs_cfg)
74
        self.make_site_options()
75

    
76
        cPickle.dump(wcs_cfg, file(config_file, 'w'))
77

    
78
        if has_sql:
79
            self.make_sql_tables(wcs_cfg)
80

    
81
        self.make_apache_vhost()
82
        self.reload_apache()
83

    
84

    
85
    def make_sql_config(self, wcs_cfg):
86
        if not wcs_cfg.get('postgresql'):
87
            # this is not a site configured to use SQL
88
            return False
89

    
90
        database_name = wcs_cfg['postgresql'].get('database', 'wcs')
91
        domain_table_name = self.domain.replace('-', '_').replace('.', '_')
92
        if '_' in database_name:
93
            database_name = '%s_%s' % (database_name.split('_')[0], domain_table_name)
94
        else:
95
            database_name = '%s_%s' % (database_name, domain_table_name)
96

    
97
        postgresql_cfg = {}
98
        for k, v in wcs_cfg['postgresql'].items():
99
            if v:
100
                postgresql_cfg[k] = v
101
        try:
102
            pgconn = psycopg2.connect(**postgresql_cfg)
103
        except psycopg2.Error:
104
            # XXX: log
105
            raise
106

    
107
        pgconn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
108
        cur = pgconn.cursor()
109
        try:
110
            cur.execute('''CREATE DATABASE %s''' % database_name)
111
        except psycopg2.Error as e:
112
            print 'got psycopg2 error:', e
113
        cur.close()
114

    
115
        wcs_cfg['postgresql']['database'] = database_name
116

    
117
        return True
118

    
119
    def make_sql_tables(self, wcs_cfg):
120
        params = []
121
        for param in ('dbname', 'user', 'password', 'host', 'port'):
122
            if wcs_cfg.get('postgresql').get(param):
123
                params.append('--' + param)
124
                params.append(wcs_cfg.get('postgresql').get(param))
125
        os.system('%s convert-to-sql %s %s' % (app_settings.WCSCTL_SCRIPT, ' '.join(params), self.domain))
126

    
127
    def make_sso_config(self, wcs_cfg):
128
        has_idff = False
129
        has_saml2 = False
130

    
131
        service_provider_configuration = {}
132

    
133
        if self.url.endswith('/'):
134
            url_stripped = self.url[:-1]
135
        else:
136
            url_stripped = self.url
137

    
138
        if os.path.exists(os.path.join(self.skel_dir, 'idff-metadata-template')):
139
            # there's a ID-FF metadata template, so we do the ID-FF stuff
140
            has_idff = True
141
            service_provider_configuration.update({
142
                'base_url': '%s/liberty' % url_stripped,
143
                'metadata': 'metadata.xml',
144
                'providerid': '%s/liberty/metadata' % url_stripped,
145
                })
146

    
147
            idff_metadata_template = file(
148
                    os.path.join(self.skel_dir, 'idff-metadata-template')).read()
149
            file(os.path.join(self.collectivity_install_dir, 'metadata.xml'), 'w').write(
150
                    string.Template(idff_metadata_template).substitute({'url': url_stripped}))
151

    
152
        if os.path.exists(os.path.join(self.skel_dir, 'saml2-metadata-template')):
153
            # there's a SAMLv2 metadata template, so we do the SAMLv2 stuff
154
            has_saml2 = True
155
            service_provider_configuration.update({
156
                'saml2_base_url': '%s/saml' % url_stripped,
157
                'saml2_metadata': 'saml2-metadata.xml',
158
                'saml2_providerid': '%s/saml/metadata' % url_stripped
159
                })
160

    
161
            saml2_metadata_template = file(
162
                    os.path.join(self.skel_dir, 'saml2-metadata-template')).read()
163
            file(os.path.join(self.collectivity_install_dir, 'saml2-metadata.xml'), 'w').write(
164
                    string.Template(saml2_metadata_template).substitute({'url': url_stripped}))
165

    
166
        if has_idff or has_saml2:
167
            idp_metadata = ET.parse(file(os.path.join(self.skel_dir, 'idp-metadata.xml')))
168
            entity_id = idp_metadata.getroot().attrib['entityID']
169
            idp_key = get_provider_key(entity_id)
170

    
171
            wcs_cfg['identification'] = {'methods': ['idp']}
172
            wcs_cfg['idp'] = {
173
                    idp_key: {
174
                        'metadata': 'provider-%s-metadata.xml' % idp_key,
175
                        'metadata_url': entity_id,
176
                        'publickey_url': None,
177
                        'role': 2}}
178
            wcs_cfg['sp'] = {
179
                    'common_domain': None,
180
                    'common_domain_getter_url': None,
181
                    'organization_name': '%s' % self.title,
182
                    'privatekey': 'private-key.pem',
183
                    'publickey': 'public-key.pem'}
184
            wcs_cfg['sp'].update(service_provider_configuration)
185

    
186
            file(os.path.join(self.collectivity_install_dir, 'provider-%s-metadata.xml' % idp_key), 'w').write(
187
                    file(os.path.join(self.skel_dir, 'idp-metadata.xml')).read())
188
            file(os.path.join(self.collectivity_install_dir, 'public-key.pem'), 'w').write(
189
                    file(os.path.join(self.skel_dir, 'public-key.pem')).read())
190
            file(os.path.join(self.collectivity_install_dir, 'private-key.pem'), 'w').write(
191
                    file(os.path.join(self.skel_dir, 'private-key.pem')).read())
192
        else:
193
            wcs_cfg['identification'] = {'methods': ['password']}
194

    
195

    
196
    def make_site_options(self):
197
        options_template_path = os.path.join(self.skel_dir, 'site-options.cfg')
198
        if not os.path.exists(options_template_path):
199
            return
200
        options_template = file(options_template_path).read()
201
        file(os.path.join(self.collectivity_install_dir, 'site-options.cfg'), 'w').write(
202
                string.Template(options_template).substitute({'domain': self.domain}))
203

    
204

    
205
    def make_apache_vhost(self):
206
        apache_vhost_template_path = os.path.join(self.skel_dir, 'apache-vhost.conf')
207
        if not os.path.exists(apache_vhost_template_path):
208
            return
209
        apache_vhost_template = file(apache_vhost_template_path).read()
210
        apache_dir = os.path.join(settings.MEDIA_ROOT, 'vhosts.d')
211
        if not os.path.exists(apache_dir):
212
            os.mkdir(apache_dir)
213
        file(os.path.join(apache_dir, '%s.conf' % self.domain), 'w').write(
214
                string.Template(apache_vhost_template).substitute({'domain': self.domain}))
215

    
216

    
217
    def reload_apache(self):
218
        os.system('sudo -n /etc/init.d/apache2 reload')
(3-3/6)