-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathdeploy.py
225 lines (178 loc) · 7.92 KB
/
deploy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# -*- coding: utf-8 -*-
# Copyright 2015 tsuru authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import os
import yaml
import sys
import re
from utils import parse_env
from interpretor import interpretors
from frontend import frontends
from vars import php_versions, default_version
class ConfigurationException(Exception):
pass
class InstallationException(Exception):
pass
class Manager(object):
def __init__(self, configuration, application):
self.configuration = configuration
self.application = application
self.frontend = self.create_frontend()
self.interpretor = self.create_interpretor()
def install(self):
# Calling pre-install hooks
self.frontend.pre_install()
if self.interpretor is not None:
self.interpretor.pre_install()
packages_php_extensions = []
if self.interpretor is not None:
packages_php_extensions = self.interpretor.get_packages_extensions()
if packages_php_extensions:
print('Installing php extensions..')
packages_to_install = []
for package in packages_php_extensions:
if "-" in package:
packages_to_install.append(self.prefix_package_version(package.split("-")[1]))
else:
packages_to_install.append(self.prefix_package_version(package))
try:
if os.system("sudo apt-get install -y --force-yes %s" % (' '.join(packages_to_install))) != 0:
raise InstallationException('An error appeared while installing needed packages')
except InstallationException:
os.system("apt-get update")
if os.system("sudo apt-get install -y --force-yes %s" % (' '.join(packages_to_install))) != 0:
raise InstallationException('An error appeared while installing needed packages')
for package in packages_to_install:
module_name = package.split("-")[1]
if os.system("phpenmod %s" % module_name) != 0:
raise InstallationException('Could not enable %s php module' % module_name)
# Calling post-install hooks
self.frontend.post_install()
if self.interpretor is not None:
self.interpretor.post_install()
self.update_alternatives(self.get_php_version())
if self.configuration.get('composer', True):
self.install_composer()
def create_procfile(self):
# If there's no Procfile, create it
procfile_path = os.path.join(self.application.get('directory'), 'Procfile')
procfile_contents = None
if os.path.isfile(procfile_path):
with open(procfile_path, 'r') as f:
web_match = re.search(r"^web:", f.read(), flags=re.MULTILINE)
if web_match is None:
f.seek(0)
procfile_contents = f.read()
if not os.path.isfile(procfile_path) or procfile_contents:
with open(procfile_path, 'w') as f:
f.write('web: /bin/bash -lc "sudo -E %s' % self.frontend.get_startup_cmd())
if self.interpretor is not None:
f.write(' && %s' % self.interpretor.get_startup_cmd(self.get_php_version()))
f.write(' "\n')
if procfile_contents:
f.write(procfile_contents)
def get_php_version(self):
version = str(self.configuration.get('version', default_version))
if version not in php_versions:
version = default_version
return version
def prefix_package_version(self, package):
return "php{}-{}".format(self.get_php_version(), package)
def update_alternatives(self, version):
for app in ['php', 'phar', 'phar.phar']:
os.system('/usr/bin/update-alternatives --set {0} /usr/bin/{0}{1}'.format(app, version))
def install_composer(self):
if os.path.isfile(os.path.join(self.application.get('directory'), 'composer.json')):
print('Install composer dependencies')
composer_phar = '/usr/local/bin/composer_phar'
if os.system('cd %s && sudo -u %s %s install' % (self.application.get('directory'),
self.application.get('user'), composer_phar)) != 0:
raise InstallationException('Unable to install composer dependencies')
def configure(self):
if self.interpretor is not None:
print('Configuring interpretor...')
self.interpretor.configure(self.frontend)
print('Configuring frontend...')
self.frontend.configure(self.interpretor)
def setup_environment(self):
self.create_procfile()
if self.interpretor is not None:
self.interpretor.setup_environment()
self.frontend.setup_environment()
def create_frontend(self):
interpretor = self.configuration.get('interpretor', None)
if interpretor:
frontend = self.configuration.get('frontend', {
'name': 'apache'
})
else:
frontend = self.configuration.get('frontend', {
'name': 'apache-mod-php'
})
frontend_options = frontend.get('options', {})
frontend_options['version'] = self.configuration.get('version', default_version)
return self.get_frontend_by_name(frontend.get('name'))(frontend_options, self.application)
def create_interpretor(self):
interpretor = self.configuration.get('interpretor', None)
if interpretor is None:
return None
elif 'name' not in interpretor:
raise ConfigurationException('Interpretor name must be set')
return self.get_interpretor_by_name(interpretor.get('name'))(interpretor.get('options', {}), self.application)
@staticmethod
def get_interpretor_by_name(name):
if name not in interpretors:
raise ConfigurationException('Interpretor %s is unknown' % name)
return interpretors.get(name)
@staticmethod
def get_frontend_by_name(name):
if name not in frontends:
raise ConfigurationException('Frontend %s is unknown' % name)
return frontends.get(name)
def load_file(working_dir="/home/application/current"):
files_name = ["tsuru.yml", "tsuru.yaml", "app.yaml", "app.yml"]
for file_name in files_name:
try:
file_path = os.path.join(working_dir, file_name)
if os.path.exists(file_path) and file_name[0:3] == 'app':
print('[WARNING] The `%s` configuration file name is deprecated' % file_name)
with open(file_path) as f:
return f.read()
except IOError:
pass
return ""
def load_configuration():
result = yaml.load(load_file())
if result:
return result.get('php', {})
return {}
def print_help():
print('This have to be called with 1 argument, which is the action')
print()
print('Possible values are:')
print('- install: Install dependencies and configure system')
print('- environment: Setup the environment')
if __name__ == '__main__':
# Load PHP configuration from `tsuru.yml`
config = load_configuration()
# Create an application object from environ
application = {
'directory': '/home/application/current',
'user': 'ubuntu',
'source_directory': '/var/lib/tsuru',
'env': parse_env(config)
}
# Get the application manager
manager = Manager(config, application)
# Run installation & configuration
if len(sys.argv) <= 1:
print_help()
elif sys.argv[1] == 'install':
manager.install()
manager.configure()
elif sys.argv[1] == 'environment':
manager.setup_environment()
else:
print('Action "%s" not found\n' % sys.argv[1])
print_help()