Project

General

Profile

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

root / wcsinst / wcsinstd / deploy.py @ 3d53199c

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

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

    
10
from django.conf import settings
11

    
12
import psycopg2
13

    
14
from . import app_settings
15

    
16

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

    
20

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

    
24
    skel_dir = None
25
    collectivity_install_dir = None
26

    
27
    def __init__(self, domain, title, site_options_cfg):
28
        self.domain = domain.encode('utf-8')
29
        self.title = title.encode('utf-8')
30
        self.site_options_cfg = site_options_cfg
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 = str(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, 0755)
55

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

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

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

    
74
        has_sql = self.make_sql_config(wcs_cfg)
75
        self.make_sso_config(wcs_cfg)
76
        self.make_site_options()
77

    
78
        cPickle.dump(wcs_cfg, file(config_file, 'w'))
79

    
80
        if has_sql:
81
            self.make_sql_tables(wcs_cfg)
82

    
83
        self.make_apache_vhost()
84
        self.reload_apache()
85

    
86

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

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

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

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

    
117
        wcs_cfg['postgresql']['database'] = database_name
118

    
119
        return True
120

    
121
    def make_sql_tables(self, wcs_cfg):
122
        params = []
123
        for param in ('database', 'user', 'password', 'host', 'port'):
124
            if wcs_cfg.get('postgresql').get(param):
125
                if param == 'database':
126
                    params.append('--dbname')
127
                else:
128
                    params.append('--' + param)
129
                params.append(wcs_cfg.get('postgresql').get(param))
130
        os.system('%s convert-to-sql %s %s' % (app_settings.WCSCTL_SCRIPT, ' '.join(params),
131
            os.path.basename(self.collectivity_install_dir)))
132

    
133
    def make_sso_config(self, wcs_cfg):
134
        has_idff = False
135
        has_saml2 = False
136

    
137
        service_provider_configuration = {}
138

    
139
        if self.url.endswith('/'):
140
            url_stripped = self.url[:-1]
141
        else:
142
            url_stripped = self.url
143

    
144
        if os.path.exists(os.path.join(self.skel_dir, 'idff-metadata-template')):
145
            # there's a ID-FF metadata template, so we do the ID-FF stuff
146
            has_idff = True
147
            service_provider_configuration.update({
148
                'base_url': '%s/liberty' % url_stripped,
149
                'metadata': 'metadata.xml',
150
                'providerid': '%s/liberty/metadata' % url_stripped,
151
                })
152

    
153
            idff_metadata_template = file(
154
                    os.path.join(self.skel_dir, 'idff-metadata-template')).read()
155
            file(os.path.join(self.collectivity_install_dir, 'metadata.xml'), 'w').write(
156
                    idff_metadata_template.format(url=url_stripped))
157

    
158
        if os.path.exists(os.path.join(self.skel_dir, 'saml2-metadata-template')):
159
            # there's a SAMLv2 metadata template, so we do the SAMLv2 stuff
160
            has_saml2 = True
161
            service_provider_configuration.update({
162
                'saml2_base_url': '%s/saml' % url_stripped,
163
                'saml2_metadata': 'saml2-metadata.xml',
164
                'saml2_providerid': '%s/saml/metadata' % url_stripped
165
                })
166

    
167
            saml2_metadata_template = file(
168
                    os.path.join(self.skel_dir, 'saml2-metadata-template')).read()
169
            file(os.path.join(self.collectivity_install_dir, 'saml2-metadata.xml'), 'w').write(
170
                    saml2_metadata_template.format(url=url_stripped))
171

    
172
        if has_idff or has_saml2:
173
            idp_metadata = ET.parse(file(os.path.join(self.skel_dir, 'idp-metadata.xml')))
174
            entity_id = idp_metadata.getroot().attrib['entityID']
175
            idp_key = get_provider_key(entity_id)
176
            title = self.title
177

    
178
            wcs_cfg['identification'] = {'methods': ['idp']}
179
            wcs_cfg['idp'] = {
180
                    idp_key: {
181
                        'metadata': 'idp-%s-metadata.xml' % idp_key,
182
                        'metadata_url': entity_id,
183
                        'publickey_url': None,
184
                        'admin-attributes': { 'role': title + ' - Administrateur' },
185
                        'role': 2}}
186
            wcs_cfg['sp'] = {
187
                    'common_domain': None,
188
                    'idp-manage-user-attributes': True,
189
                    'common_domain_getter_url': None,
190
                    'organization_name': title,
191
                    'privatekey': 'private-key.pem',
192
                    'publickey': 'public-key.pem'}
193
            wcs_cfg['sp'].update(service_provider_configuration)
194

    
195
            file(os.path.join(self.collectivity_install_dir, 'idp-%s-metadata.xml' % idp_key), 'w').write(
196
                    file(os.path.join(self.skel_dir, 'idp-metadata.xml')).read())
197
            file(os.path.join(self.collectivity_install_dir, 'public-key.pem'), 'w').write(
198
                    file(os.path.join(self.skel_dir, 'public-key.pem')).read())
199
            file(os.path.join(self.collectivity_install_dir, 'private-key.pem'), 'w').write(
200
                    file(os.path.join(self.skel_dir, 'private-key.pem')).read())
201
        else:
202
            wcs_cfg['identification'] = {'methods': ['password']}
203

    
204

    
205
    def make_site_options(self):
206
        options_template_path = os.path.join(self.skel_dir, 'site-options.cfg')
207
        if not os.path.exists(options_template_path):
208
            return
209
        options_template = file(options_template_path).read()
210
        file(os.path.join(self.collectivity_install_dir, 'site-options.cfg'), 'w').write(
211
                options_template.format(domain=self.domain,
212
                    options=self.site_options_cfg))
213

    
214

    
215
    def make_apache_vhost(self):
216
        apache_vhost_template_path = os.path.join(self.skel_dir, 'apache-vhost.conf')
217
        if not os.path.exists(apache_vhost_template_path):
218
            return
219
        apache_vhost_template = file(apache_vhost_template_path).read()
220
        apache_dir = os.path.join(settings.MEDIA_ROOT, 'vhosts.d')
221
        if not os.path.exists(apache_dir):
222
            os.mkdir(apache_dir, 0755)
223
        file(os.path.join(apache_dir, '%s.conf' % self.domain), 'w').write(
224
                apache_vhost_template.format(domain=self.domain))
225

    
226

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