Project

General

Profile

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

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

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 ('database', 'user', 'password', 'host', 'port'):
122
            if wcs_cfg.get('postgresql').get(param):
123
                if param == 'database':
124
                    params.append('--dbname')
125
                else:
126
                    params.append('--' + param)
127
                params.append(wcs_cfg.get('postgresql').get(param))
128
        os.system('%s convert-to-sql %s %s' % (app_settings.WCSCTL_SCRIPT, ' '.join(params), self.domain))
129

    
130
    def make_sso_config(self, wcs_cfg):
131
        has_idff = False
132
        has_saml2 = False
133

    
134
        service_provider_configuration = {}
135

    
136
        if self.url.endswith('/'):
137
            url_stripped = self.url[:-1]
138
        else:
139
            url_stripped = self.url
140

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

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

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

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

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

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

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

    
198

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

    
207

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

    
219

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