Project

General

Profile

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

root / wcsinst / wcsinstd / deploy.py @ 833ba5e2

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
        cur = pgconn.cursor()
108
        cur.execute('''CREATE DATABASE %s''' % database_name)
109
        pgconn.commit()
110
        cur.close()
111

    
112
        wcs_cfg['postgresql']['database'] = database_name
113

    
114
        return True
115

    
116
    def make_sql_tables(self, wcs_cfg):
117
        params = []
118
        for param in ('dbname', 'user', 'password', 'host', 'port'):
119
            if wcs_cfg.get('postgresql').get(param):
120
                params.append(param)
121
                params.append(wcs_cfg.get('postgresql').get(param))
122
        os.system('wcsctl convertsql %s %s' % (' '.join(params), self.domain))
123

    
124
    def make_sso_config(self, wcs_cfg):
125
        has_idff = False
126
        has_saml2 = False
127

    
128
        service_provider_configuration = {}
129

    
130
        if self.url.endswith('/'):
131
            url_stripped = self.url[:-1]
132
        else:
133
            url_stripped = self.url
134

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

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

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

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

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

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

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

    
192

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

    
201

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

    
213

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