/
asgard.py
350 lines (278 loc) · 9.21 KB
/
asgard.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
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
346
347
348
349
350
# -*- coding: utf-8 -*-
# from __future__ import unicode_literals
import json
from functools import partial
from os import path, environ
from semantic_version import Version
import profig
import click
import sys
if sys.version > '3':
PY3 = True
else:
PY3 = False
try:
import sh
from sh import curl, rm, cat
except Exception:
from pbs import curl, rm, cat
CONFIG_FILE = environ.get(
'ASGARD_CONFIG', path.join(
environ.get('VIRTUAL_ENV', environ.get('HOME', '')),
'.asgard/config'))
def get_chart_repo(helm_repo):
if PY3:
repo_list = str(helm.repo.list().stdout, encoding='utf-8')
else:
repo_list = str(helm.repo.list().stdout)
for l in repo_list.split('\n')[1:]:
if not l:
continue
name, repo = l.split()
if name == helm_repo:
return repo
def get_release(release, tiller_host):
if PY3:
release_list = str(helm.list('--host', tiller_host).stdout, encoding='utf-8')
else:
release_list = str(helm.list('--host', tiller_host).stdout)
for l in release_list.split('\n')[1:]:
if not l:
continue
name, v, _ = l.split('\t', 2)
if name.strip() == release:
return v.strip()
def get_chart_version(helm_repo, path, version=''):
update_helm()
if PY3:
repo_list = str(helm.search(path).stdout, encoding='utf-8')
else:
repo_list = helm.search(path).stdout
chart = '%s/%s' % (helm_repo, path)
for l in repo_list.split('\n')[1:]:
l = l.strip()
if not l:
continue
target, version, v = l.split()[:3]
if target == chart:
return version
return '0.0.0'
try:
from sh import helm
except Exception:
click.echo(click.style('*** Can\'t find helm in $PATH. Please install it. ***', fg='red'))
helm = None
def update_helm():
click.echo(click.style('Updating Helm ...', fg='yellow'))
helm.repo.update()
click.echo(click.style('Updating Helm [OK]\n', fg='green'))
@click.group()
# TODO: Add global config, e.g., 'host', 'kube-context'
@click.pass_context
def asgard(ctx):
'''
Asgard -- A deploy tool bases on k8s ,helm and chartmuseum.
Run `asgard init` first if this is your first time to use.
'''
cmd = ctx.invoked_subcommand
keyword = 'helm'
if cmd == 'init':
return
if not path.isfile(CONFIG_FILE):
click.echo(click.style('Run init first', fg='red'))
return
cfg = profig.Config(CONFIG_FILE)
cfg.sync()
if cfg.section(keyword).get('chart_repo'):
click.echo(click.style('WARNING: the config `chart_repo` has been desperate!\n', fg='yellow'))
if not environ.get('VIRTUAL_ENV'):
click.echo(click.style('WARNING: You are using global settings!\n', fg='yellow'))
ctx.obj.update(cfg.section(keyword))
@asgard.command()
@click.pass_context
def init(ctx):
'''
Init and set asgard's config. Please run and follow it.
'''
cfg = profig.Config(CONFIG_FILE)
cfg.sync()
click.echo(click.style('Init Helm ...', fg='yellow'))
helm.init('-c')
click.echo(click.style('Init Helm [OK]', fg='green'))
setting_key = 'helm.kube_context'
kube_context = click.prompt(
'Please the name of your k8s context',
default=cfg.get(setting_key, ''))
cfg[setting_key] = kube_context
setting_key = 'helm.tiller_host'
tiller_host = click.prompt(
'Please enter uri for tiller',
default=cfg.get(setting_key, ''))
cfg[setting_key] = tiller_host
setting_key = 'helm.tiller_namespace'
tiller_namespace = click.prompt(
'Please enter namespace for tiller',
default=cfg.get(setting_key, ''))
cfg[setting_key] = tiller_namespace
setting_key = 'helm.helm_repo'
helm_repo = click.prompt(
'Please enter the default helm repo',
default=cfg.get(setting_key))
cfg[setting_key] = helm_repo
cfg.sync()
@asgard.command()
@click.pass_context
def info(ctx):
'''
Show Aagard's config.
'''
click.echo(click.style(CONFIG_FILE + ' :', fg='yellow'))
click.echo()
click.echo(cat(CONFIG_FILE))
@asgard.command()
@click.pass_context
def list(ctx):
'''
List releases already deployed.
'''
click.echo(helm.list(
'--host', ctx.obj.get('tiller_host'),
'--tiller-namespace', ctx.obj.get('tiller_namespace'),
'--kube-context', ctx.obj.get('kube_context'),
))
@asgard.command()
@click.option('--version', '-v', default='')
@click.argument('chart')
@click.pass_context
def fetch(ctx, version, chart):
'''
Fetch a chart and untar to current directory.
version: x.x.x-xxx
chart: [Repo name]/[Chart name]
'''
update_helm()
if len(chart.split('/')) == 2:
repo, chart_name = chart.split('/')
else:
click.echo(click.style('No repo specified, using default(%s)...\n' % ctx.obj.get('helm_repo'), fg='yellow'))
repo = ctx.obj.get('helm_repo')
chart_name = chart
chart = '%s/%s' % (repo, chart_name)
fetch_version = version or get_chart_version(repo, chart_name)
click.echo(click.style('Fetching %s@%s' % (chart, fetch_version), fg='yellow'))
args = ['--untar', chart]
if version:
args.append('--version')
args.append(version)
helm.fetch(args)
click.echo(click.style('SUCCESS!', fg='green'))
@asgard.command()
@click.argument('path')
@click.pass_context
def lint(ctx, path):
'''
Check chart.
'''
click.echo(helm.lint(path))
@asgard.command()
@click.argument('keyword')
@click.pass_context
def search(ctx, keyword):
'''
Search chart.
'''
update_helm()
click.echo(helm.search(keyword))
@asgard.command()
@click.argument('path')
@click.argument('version', default='')
@click.pass_context
def package(ctx, path, version):
'''
Package a current path to a new version and upload to chart repo.
'''
# helm package --app-version 0.1.9 --version 0.1.9 fantuan-base
# curl -F "chart=@mychart-0.1.0.tgz" http://localhost:8080/api/charts
update_helm()
path = path.strip('/')
chart_name = path.split('/')[-1]
if not version:
click.echo(click.style('No version specified. Reading from chart_repo ...', fg='yellow'))
version = Version(get_chart_version(ctx.obj.get('helm_repo'), chart_name))
version = str(version.next_patch())
click.echo(click.style('Get new version %s' % version, fg='green'))
Version(version)
click.echo(click.style('Updateing dependency ...', fg='yellow'))
helm.dependency.update(path)
click.echo(click.style('Done!\n', fg='green'))
click.echo(click.style('Packaging ...', fg='yellow'))
helm.package('--app-version', version, '--version', version, path)
tar = '%s-%s.tgz' % (path, version)
click.echo(click.style('Uploading ...', fg='yellow'))
cmd_result = curl('-F', 'chart=@%s' % tar, get_chart_repo(ctx.obj.get('helm_repo')) + '/api/charts')
click.echo(click.style('Cleaning ...', fg='yellow'))
rm(tar)
result = json.loads(cmd_result.stdout)
if result.get('saved'):
click.echo(click.style('SUCCESS!', fg='green'))
else:
click.echo(click.style('FAILED!: %s' % result.get('error'), fg='red'))
@asgard.command()
@click.argument('release')
@click.pass_context
def delete(ctx, release):
'''
Delete a release.
'''
click.echo(helm.delete(
'--host', ctx.obj.get('tiller_host'),
'--tiller-namespace', ctx.obj.get('tiller_namespace'),
'--kube-context', ctx.obj.get('kube_context'),
release, '--purge'
))
@asgard.command()
@click.option('--release', '-r', default='')
@click.option('--version', '-v', default='')
@click.option('--dry_run', is_flag=True, default=False)
@click.argument('chart')
@click.pass_context
def upgrade(ctx, release, version, dry_run, chart):
'''
Upgrade a release.
'''
update_helm()
# TODO: 参数
# TODO: 批量更新
click.echo(click.style(
'Release %s \'s current revision is %s' % (
release or chart, get_release(release or chart, ctx.obj.get('tiller_host'))),
fg='green'))
click.echo(click.style('Updating %s to %s ...' % (
release or chart, version or get_chart_version(ctx.obj.get('helm_repo'), release or chart)),
fg='yellow'))
click.echo(helm.upgrade(
'--host', ctx.obj.get('tiller_host'),
'--tiller-namespace', ctx.obj.get('tiller_namespace'),
'--kube-context', ctx.obj.get('kube_context'), '--force',
# '--timeout', '10', '--recreate-pods', '--wait',
'-i', release or chart, '%s/%s' % (ctx.obj.get('helm_repo'), chart),
))
@asgard.command()
@click.argument('release')
@click.pass_context
def reload(ctx, release):
'''
Restart pods of release
'''
click.echo(sh.kubectl.get.pods(
'--context', ctx.obj.get('kube_context'), '-l', 'release=%s' % release))
if not click.confirm('Continue?'):
return
click.echo(sh.kubectl.delete.pods(
'--context', ctx.obj.get('kube_context'), '-l', 'release=%s' % release))
click.echo(sh.kubectl.get.pods(
'--context', ctx.obj.get('kube_context'), '-l', 'release=%s' % release))
if __name__ == '__main__':
asgard(obj={})
else:
asgard = partial(asgard, obj={})