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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
|
def get_config_defaults():
"""Get the default configuration values."""
config = {}
config['quiet'] = False
config['daemon-mode'] = False
config['config'] = None
config['ssh-keyscan'] = False
config['force'] = False
config['ssl'] = False
config['ssl-pem-file'] = '~/.gitautodeploy.pem'
config['pidfilepath'] = '~/.gitautodeploy.pid'
config['logfilepath'] = None
config['host'] = '0.0.0.0'
config['port'] = 8001
config['intercept-stdout'] = True
# Record all log levels by default
config['log-level'] = 'NOTSET'
# Include details with deploy command return codes in HTTP response. Causes
# to await any git pull or deploy command actions before it sends the
# response.
config['detailed-response'] = False
# Log incoming webhook requests in a way they can be used as test cases
config['log-test-case'] = False
config['log-test-case-dir'] = None
config['remote-whitelist'] = ['127.0.0.1']
return config
def get_config_from_environment():
"""Get configuration values provided as environment variables."""
import os
config = {}
if 'GAD_QUIET' in os.environ:
config['quiet'] = True
if 'GAD_DAEMON_MODE' in os.environ:
config['daemon-mode'] = True
if 'GAD_CONFIG' in os.environ:
config['config'] = os.environ['GAD_CONFIG']
if 'GAD_SSH_KEYSCAN' in os.environ:
config['ssh-keyscan'] = True
if 'GAD_FORCE' in os.environ:
config['force'] = True
if 'GAD_SSL' in os.environ:
config['ssl'] = True
if 'GADGAD_SSL_PEM_FILE_SSL' in os.environ:
config['ssl-pem-file'] = os.environ['GAD_SSL_PEM_FILE']
if 'GAD_PID_FILE' in os.environ:
config['pidfilepath'] = os.environ['GAD_PID_FILE']
if 'GAD_LOG_FILE' in os.environ:
config['logfilepath'] = os.environ['GAD_LOG_FILE']
if 'GAD_HOST' in os.environ:
config['host'] = os.environ['GAD_HOST']
if 'GAD_PORT' in os.environ:
config['port'] = int(os.environ['GAD_PORT'])
return config
def get_config_from_argv(argv):
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--daemon-mode",
help="run in background (daemon mode)",
dest="daemon-mode",
action="store_true")
parser.add_argument("-q", "--quiet",
help="supress console output",
dest="quiet",
action="store_true")
parser.add_argument("-c", "--config",
help="custom configuration file",
dest="config",
type=str)
parser.add_argument("--ssh-keyscan",
help="scan repository hosts for ssh keys",
dest="ssh-keyscan",
action="store_true")
parser.add_argument("--force",
help="kill any process using the configured port",
dest="force",
action="store_true")
parser.add_argument("--pid-file",
help="specify a custom pid file",
dest="pidfilepath",
type=str)
parser.add_argument("--log-file",
help="specify a log file",
dest="logfilepath",
type=str)
parser.add_argument("--log-level",
help="specify log level",
dest="log-level",
type=str)
parser.add_argument("--host",
help="address to bind to",
dest="host",
type=str)
parser.add_argument("--port",
help="port to bind to",
dest="port",
type=int)
parser.add_argument("--ssl",
help="use ssl",
dest="ssl",
action="store_true")
parser.add_argument("--ssl-pem",
help="path to ssl pem file",
dest="ssl-pem",
type=str)
config = vars(parser.parse_args(argv))
# Delete entries for unprovided arguments
del_keys = []
for key in config:
if config[key] is None:
del_keys.append(key)
for key in del_keys:
del config[key]
return config
def find_config_file(target_directories=None):
"""Attempt to find a path to a config file. Provided paths are scanned
for *.conf(ig)?.json files."""
import os
import re
import logging
logger = logging.getLogger()
if not target_directories:
return
# Remove duplicates
target_directories = list(set(target_directories))
# Look for a *conf.json or *config.json
for dir in target_directories:
if not os.access(dir, os.R_OK):
continue
for item in os.listdir(dir):
if re.match(r".*conf(ig)?\.json$", item):
path = os.path.realpath(os.path.join(dir, item))
logger.info("Using '%s' as config" % path)
return path
def get_config_from_file(path):
"""Get configuration values from config file."""
import logging
import os
logger = logging.getLogger()
config_file_path = os.path.realpath(path)
logger.info('Using custom configuration file \'%s\'' % config_file_path)
# Read config data from json file
if config_file_path:
config_data = read_json_file(config_file_path)
else:
logger.info('No configuration file found or specified. Using default values.')
config_data = {}
return config_data
def read_json_file(file_path):
import json
import logging
import re
logger = logging.getLogger()
try:
json_string = open(file_path).read()
except Exception as e:
logger.critical("Could not load %s file\n" % file_path)
raise e
try:
# Remove commens from JSON (makes sample config options easier)
regex = r'\s*(#|\/{2}).*$'
regex_inline = r'(:?(?:\s)*([A-Za-z\d\.{}]*)|((?<=\").*\"),?)(?:\s)*(((#|(\/{2})).*)|)$'
lines = json_string.split('\n')
for index, line in enumerate(lines):
if re.search(regex, line):
if re.search(r'^' + regex, line, re.IGNORECASE):
lines[index] = ""
elif re.search(regex_inline, line):
lines[index] = re.sub(regex_inline, r'\1', line)
data = json.loads('\n'.join(lines))
except Exception as e:
logger.critical("%s file is not valid JSON\n" % file_path)
raise e
return data
def init_config(config):
"""Initialize config by filling out missing values etc."""
import os
import re
import logging
logger = logging.getLogger()
# Translate any ~ in the path into /home/<user>
if 'pidfilepath' in config and config['pidfilepath']:
config['pidfilepath'] = os.path.expanduser(config['pidfilepath'])
if 'logfilepath' in config and config['logfilepath']:
config['logfilepath'] = os.path.expanduser(config['logfilepath'])
if 'repositories' not in config:
config['repositories'] = []
for repo_config in config['repositories']:
# Setup branch if missing
if 'branch' not in repo_config:
repo_config['branch'] = "master"
# Setup remote if missing
if 'remote' not in repo_config:
repo_config['remote'] = "origin"
# Setup deploy commands list if not present
if 'deploy_commands' not in repo_config:
repo_config['deploy_commands'] = []
# Check if any global pre deploy commands is specified
if 'global_deploy' in config and len(config['global_deploy']) > 0 and len(config['global_deploy'][0]) is not 0:
repo_config['deploy_commands'].insert(0, config['global_deploy'][0])
# Check if any repo specific deploy command is specified
if 'deploy' in repo_config:
repo_config['deploy_commands'].append(repo_config['deploy'])
# Check if any global post deploy command is specified
if 'global_deploy' in config and len(config['global_deploy']) > 1 and len(config['global_deploy'][1]) is not 0:
repo_config['deploy_commands'].append(config['global_deploy'][1])
# If a repository is configured with embedded credentials, we create an alternate URL
# without these credentials that cen be used when comparing the URL with URLs referenced
# in incoming web hook requests.
if 'url' in repo_config:
regexp = re.search(r"^(https?://)([^@]+)@(.+)$", repo_config['url'])
if regexp:
repo_config['url_without_usernme'] = regexp.group(1) + regexp.group(3)
# Translate any ~ in the path into /home/<user>
if 'path' in repo_config:
repo_config['path'] = os.path.expanduser(repo_config['path'])
# Support for legacy config format
if 'filters' in repo_config:
repo_config['payload-filter'] = repo_config['filters']
del repo_config['filters']
if 'payload-filter' not in repo_config:
repo_config['payload-filter'] = []
if 'header-filter' not in repo_config:
repo_config['header-filter'] = {}
# Rewrite some legacy filter config syntax
for filter in repo_config['payload-filter']:
# Legacy config syntax?
if ('kind' in filter and filter['kind'] == 'pull-request-handler') or ('type' in filter and filter['type'] == 'pull-request-filter'):
# Reset legacy values
filter['kind'] = None
filter['type'] = None
if 'ref' in filter:
filter['pull_request.base.ref'] = filter['ref']
filter['ref'] = None
filter['pull_request'] = True
return config
def get_repo_config_from_environment():
"""Look for repository config in any defined environment variables. If
found, import to main config."""
import logging
import os
if 'GAD_REPO_URL' not in os.environ:
return
logger = logging.getLogger()
repo_config = {
'url': os.environ['GAD_REPO_URL']
}
logger.info("Added configuration for '%s' found in environment variables" % os.environ['GAD_REPO_URL'])
if 'GAD_REPO_BRANCH' in os.environ:
repo_config['branch'] = os.environ['GAD_REPO_BRANCH']
if 'GAD_REPO_REMOTE' in os.environ:
repo_config['remote'] = os.environ['GAD_REPO_REMOTE']
if 'GAD_REPO_PATH' in os.environ:
repo_config['path'] = os.environ['GAD_REPO_PATH']
if 'GAD_REPO_DEPLOY' in os.environ:
repo_config['deploy'] = os.environ['GAD_REPO_DEPLOY']
return repo_config
|