-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathviews.py
More file actions
1536 lines (1368 loc) · 67.9 KB
/
Copy pathviews.py
File metadata and controls
1536 lines (1368 loc) · 67.9 KB
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8
import json
import copy
import humanfriendly
from threading import Thread
from .models import App, Resource, Streamrouter, Notify, recursive_deploy, default_deploy
from .specs import render_podgroup_spec_from_json, AppType
from authorize.models import Authorize, Group
from configs.models import Config
from commons.miscs import InvalidMetaVersion, NoAvailableImages, InvalidLainYaml
from commons.settings import PRIVATE_REGISTRY, AUTH_TYPES, ETCD_AUTHORITY, PROTECTED_APPS_ETCD_PREFIX
from commons.utils import get_etcd_value
from notifies.notify import image_push_notify
from .utils import convert_time_from_deployd
from lain_sdk.yaml.parser import ProcType, resource_instance_name
from django.core.urlresolvers import reverse
from raven.contrib.django.raven_compat.models import client
from log import logger, op_logger
from oplog.models import add_oplog
from git.client import fetch_project_commits
def render_op_result(op_result):
try:
return {
"status_code": op_result.status_code,
"data": op_result.json().get('message')
}
except Exception:
return {
"status_code": op_result.status_code,
"data": op_result.content
}
def render_op_result_to_msg(op_result):
d = render_op_result(op_result)
return " status_code: %s\n" % (d['status_code']) + \
" message: %s" % (d['data'])
def render_podgroup_deploy_result_to_msg(deploy_result):
msg = 'proc deploy result:\n'
for pgname, pgr in deploy_result['podgroup_result'].iteritems():
msg += ' %s\n' % (render_op_result_to_msg(pgr))
services = deploy_result['services_need_deploy']
if services is not None and len(services) > 0:
msg += ' services_need_deploy:\n'
for pgname in services:
msg += ' %s\n' % (pgname)
return msg
def render_basic_app_deploy_result_to_msg(deploy_result):
if not deploy_result:
return 'app deploy failed!'
msg = '\n-------proc deploy results------ \n'
proc_results = deploy_result['proc_results']
successed = proc_results['proc_deploy_success']
if successed is not None and len(successed) > 0:
msg += 'procs in below are successed:\n'
for pgname, pg_result in successed.iteritems():
msg += ' %s\n%s\n' % (pgname,
render_podgroup_deploy_result_to_msg(pg_result))
failed = proc_results['proc_deploy_failed']
if failed is not None and len(failed) > 0:
msg += 'procs in below are failed:\n'
for pgname, pg_result in failed.iteritems():
msg += ' %s\n%s\n' % (pgname,
render_podgroup_deploy_result_to_msg(pg_result))
msg += '\n'
return msg
def render_resource_deploy_result_to_msg(deploy_result):
msg = ''
resources = deploy_result['resources_need_deploy']
if resources is not None and len(resources) > 0:
msg += 'resources need deploy:\n'
for rename in resources:
msg += ' %s\n' % (rename)
instance_results = deploy_result['instances_deploy_results']
if instance_results is not None and len(instance_results) > 0:
msg += ' resouce instances deploy results:\n'
for riname, ri_result in instance_results.iteritems():
msg += ' %s\n%s\n' % (riname,
render_basic_app_deploy_result_to_msg(ri_result))
return msg
def render_app_deploy_result_to_msg(deploy_result):
msg = ''
has_resource = deploy_result['dp_resources_deploy_results']['has_resource']
if has_resource:
resource_results = deploy_result['dp_resources_deploy_results']
msg += 'depended resource instance deploy results:\n'
msg += '%s\n' % (render_resource_deploy_result_to_msg(resource_results))
app_results = deploy_result['app_deploy_results']
msg += 'app_deploy_results:\n'
msg += '%s\n' % (render_basic_app_deploy_result_to_msg(app_results))
return msg
def render_podgroup_remove_result_to_msg(deploy_result):
return render_op_result_to_msg(deploy_result)
def render_basic_app_remove_result_to_msg(deploy_result):
msg = 'remove successed results:\n'
for pgname, pgr in deploy_result['remove_success_results'].iteritems():
msg += ' %s\n%s\n' % (pgname, render_op_result_to_msg(pgr))
msg += 'remove missed results:\n'
for pgname, pgr in deploy_result['remove_missed_results'].iteritems():
msg += ' %s\n%s\n' % (pgname, render_op_result_to_msg(pgr))
msg += 'remove failed results:\n'
for pgname, pgr in deploy_result['remove_failed_results'].iteritems():
msg += ' %s\n%s\n' % (pgname, render_op_result_to_msg(pgr))
return msg
def render_app_remove_result_to_msg(remove_result):
msg = 'app remove results:\n'
msg += render_basic_app_remove_result_to_msg(
remove_result['app_remove_results'])
instance_remove_results = remove_result['dp_resources_remove_results']
if instance_remove_results.get('has_resource', False):
msg += 'resource instance remove results:\n'
for riname, remove_result in instance_remove_results['instances_remove_results'].iteritems():
msg += ' %s\n%s\n' % (riname,
render_basic_app_remove_result_to_msg(remove_result))
return msg
def render_app_update_result_to_msg(update_result, is_resource_instance=False):
app_results = update_result['app_update_results']
msg = '%s\n' % (render_basic_app_deploy_result_to_msg(app_results))
return msg
def is_deployable():
return default_deploy.is_deployable()
'''
这个类响应 console.views 的 对 App 相关的所有调用
请求成功完成应返回 status_code, view_object, msg, url 的 turple
status_code / view_object / msg / url 是自己渲染的
console.views 将上面的 turple 封装成 JsonResponse
'''
class AppApi:
@classmethod
def render_app(cls, app, iteration=True, client=None, use_portals=[]):
appname, app_lain_conf, app_type = app.appname, app.lain_config, app.app_type
last_error, last_update, app_status = app.last_error, app.last_update, app.app_status
data = {
'appname': appname,
'apptype': app_type,
'metaversion': '',
'updatetime': last_update,
'deployerror': last_error,
'procs': [],
'portals': [],
'useservices': [],
'useresources': [],
'url': reverse('api_app', kwargs={'appname': appname})
}
if app_lain_conf is None:
return data
data['metaversion'] = app_lain_conf.meta_version
if iteration:
if len(app_lain_conf.use_services) > 0:
useservices = []
for service_appname, service_procname_list in app_lain_conf.use_services.iteritems():
service = App.get_or_none(service_appname)
use_portal_list = [App.get_portal_name_from_service_name(
service, s) for s in service_procname_list]
useservices.append({
'servicename': service_appname,
'serviceprocs': use_portal_list,
'service': {} if not service or not service.is_reachable() else
AppApi.render_app(
service, iteration=False, client=app_lain_conf.appname, use_portals=use_portal_list)
})
data['useservices'] = useservices
if len(app_lain_conf.use_resources) > 0:
useresources = []
for resource_appname, resource_info in app_lain_conf.use_resources.iteritems():
instance = App.get_or_none(resource_instance_name(
resource_appname, app_lain_conf.appname))
use_portal_list = [App.get_portal_name_from_service_name(
instance, s) for s in resource_info['services']]
useresources.append({
'resourcename': resource_appname,
'resourceprocs': use_portal_list,
'resourceinstance': {} if not instance or not instance.is_reachable() else
AppApi.render_app(
instance, iteration=False, client=app_lain_conf.appname, use_portals=use_portal_list)
})
data['useresources'] = useresources
procs, portals = [], []
if app_status:
data['deployerror'] = last_error if last_error else app_status[
'LastError']
for pg_status in app_status['PodGroups']:
pg_name = pg_status['Name']
procname = pg_name.split('.')[-1]
proc_lain_conf = app_lain_conf.procs.get(procname, None)
if proc_lain_conf:
procs.append(ProcApi.render_proc_data(
app_lain_conf.appname, proc_lain_conf, pg_status))
for ps_status in app_status['Portals']:
ps_name = ps_status['Name']
portalname = ps_name.split('.')[-1]
portal_lain_conf = app_lain_conf.procs.get(portalname, None)
if portal_lain_conf:
if not iteration:
if portalname in use_portals:
portals.append(ProcApi.render_proc_data(
app_lain_conf.appname, portal_lain_conf, ps_status, is_portal=True, client=client))
else:
portals.append(ProcApi.render_proc_data(
app_lain_conf.appname, portal_lain_conf, ps_status, is_portal=True))
else:
# resource apps donot have app status
for proc in app_lain_conf.procs.values():
if proc.type == ProcType.portal:
portals.append(ProcApi.render_proc_data(
app_lain_conf.appname, proc))
else:
procs.append(ProcApi.render_proc_data(
app_lain_conf.appname, proc))
data['procs'] = procs
data['portals'] = portals
if app_type == AppType.Resource:
instances = []
for instance in Resource.get_instances(app_lain_conf.appname):
instances.append(AppApi.render_app(instance))
data['resourceinstances'] = instances
return data
@classmethod
def render_repo_data(cls, appname):
data = {
'appname': appname,
'url': reverse('api_repo', kwargs={'appname': appname}),
}
return data
@classmethod
def render_version_data(cls, appname, versions):
data = {
'appname': appname,
'tags': versions,
'url': reverse('api_versions', kwargs={'appname': appname}),
}
return data
@classmethod
def render_detail_data(cls, appname, giturl, meta_version):
data = {
'appname': appname,
'giturl': giturl,
'meta_version': meta_version,
'url': reverse('api_details', kwargs={'appname': appname}),
}
return data
@classmethod
def check_app_exist(cls, appname):
app = App.get_or_none(appname)
if not app:
return False
return True
@classmethod
def list_apps(cls, open_auth, groups, options=None):
def verify_options(options):
apptype, msg = '', ''
if options:
apptype = options.get('apptype', AppType.Normal)
return True, msg, apptype
is_valid, msg, apptype = verify_options(options)
if not is_valid:
return (400, None, msg, reverse('api_docs'))
try:
apps = App.all()
if open_auth:
app_datas = [AppApi.render_app(a) for a in apps if a.is_reachable()
and (True if apptype == '' else a.get_app_type() == apptype) and AuthApi.verify_app_access(groups, a.appname)]
else:
app_datas = [AppApi.render_app(a) for a in apps if a.is_reachable()
and (True if apptype == '' else a.get_app_type() == apptype)]
except Exception, e:
client.captureException()
return (500, None,
'fatal error when getting apps:\n%s\nplease contact with admin of lain\n' % e,
reverse('api_docs'))
return (200, app_datas, '', reverse('api_apps'))
@classmethod
def list_repos(cls, open_auth, groups, options=None):
try:
apps = App.all()
if open_auth:
app_datas = [AppApi.render_repo_data(
a.appname) for a in apps if AuthApi.verify_app_access(groups, a.appname)]
else:
app_datas = [AppApi.render_repo_data(a.appname) for a in apps]
except Exception, e:
client.captureException()
return (500, None,
'fatal error when getting repos apps:\n%s\nplease contact with admin of lain\n' % e,
reverse('api_docs'))
return (200, app_datas, '', reverse('api_repos'))
@classmethod
def create_app(cls, access_token, appname, options=None):
try:
app = App.get_or_none(appname)
if app.is_reachable():
return (409, AppApi.render_app(app),
'app with appname %s already exists\n' % appname,
reverse('api_app', kwargs={'appname': appname}))
exist, target_meta_version = app.check_latest_version()
if not exist:
logger.error(
"app %s found no latest meta and release images" % appname)
return (400, None,
'not found both meta and release images,\nplease check your App images then try to update your App\n',
reverse('api_app', kwargs={'appname': appname}))
app.clear_last_error()
app.set_deploying()
err = cls._app_deploy(access_token, app, target_meta_version)
if err is not None:
return (406, None, 'request of deploy app %s is not acceptable with error:%s' %
(appname, err), reverse('api_app', kwargs={'appname': appname}))
return (202, AppApi.render_app(app), 'deploy request of app %s has been accepted.' % appname,
reverse('api_app', kwargs={'appname': appname}))
except InvalidMetaVersion, ime:
return (500, None,
'error in parsing meta_version: %s\nplease check your App images then try to update your App\n' % ime,
reverse('api_app', kwargs={'appname': appname}))
except NoAvailableImages, naie:
return (500, None,
'error in getting images: %s\nplease check your App images then try to update your App\n' % naie,
reverse('api_app', kwargs={'appname': appname}))
except Exception, e:
return (500, None,
'fatal error when creating app %s:\n%s\nplease contact with admin of lain\n' % (
appname, e),
reverse('api_docs'))
@classmethod
def _app_deploy(cls, token, app, meta_version):
try:
op_logger.info("DEPLOY: app %s deployed by %s to version %s" % (
app.appname, AuthApi.operater, meta_version))
add_oplog(AuthApi.operater, "DEPLOY", app.appname,
meta_version, "")
logger.info("ready create app %s" % app.appname)
if not app.update_meta(meta_version, force=True, update_spec=False):
raise Exception(
"error getting meta_version/meta %s for app %s" % (meta_version, app.appname))
logger.info("update metaversion to %s" % meta_version)
if app.get_app_type() != AppType.Resource:
app.add_calico_profile()
success, msg = AuthApi.create_resource_instance_group(
token, app.appname)
if not success:
raise Exception(
"error creating resource instance group for app %s : %s" % (app.appname, msg))
configed_instances = cls._get_configed_instances(
token, app, app.lain_config.use_resources)
ConfigApi.construct_config_for_app(token, app)
deploy_result = app.app_deploy(configed_instances)
logger.info("%s deploy result: %s" % (
app.appname, render_app_deploy_result_to_msg(deploy_result)))
if not deploy_result.get("OK", False):
raise Exception("\n%s\n" %
render_app_deploy_result_to_msg(deploy_result))
except Exception, e:
client.captureException()
error_msg = "\nDeploy app %s results: %s" % (app.appname, str(e))
logger.error(error_msg)
return error_msg
finally:
app.set_deployed()
@classmethod
def _get_configed_instances(cls, token, app, resources):
configed_instances = {}
if resources is None:
return configed_instances
for resourcename, resource_props in resources.iteritems():
resource = App.get_or_none(resourcename)
if resource is None or not resource.is_reachable():
# resource not existed
raise Exception(
"Error: Resource %s DoesNotExist" % resourcename)
instancename = resource_instance_name(resourcename, app.appname)
resource_instance = App.get_or_none(instancename)
if not resource_instance:
resource_instance = App.create(instancename)
resource_instance.meta_version = resource.meta_version
resource_instance.default_image = Resource.get_instance_image(
resource.appname, resource.meta_version)
resource_instance.meta = resource.get_resource_instance_meta(
app.appname, resource_props['context'])
resource_instance.add_calico_profile()
ConfigApi.construct_config_for_instance(
token, resource, resource_instance)
configed_instances[instancename] = resource_instance
return configed_instances
@classmethod
def create_repo(cls, access_token, appname, options=None):
try:
app = App.get_or_none(appname)
if app:
return (409, None, 'app with appname %s has already been reposited\n' % appname,
reverse('api_repo', kwargs={'appname': appname}))
op_logger.info("REPOSIT: app %s reposited by %s" %
(appname, AuthApi.operater))
add_oplog(AuthApi.operater, "REPOSIT",
appname, "", "")
app = App.create(appname)
success, msg = Group.create_group_for_app(access_token, appname)
if not success:
app.delete()
return (500, None, 'error reposing app %s : \n%s\n' % (appname, msg), reverse('api_docs'))
else:
return (201, AppApi.render_repo_data(appname), msg,
reverse('api_repo', kwargs={'appname': appname}))
except Exception, e:
client.captureException()
return (500, None,
'fatal error when reposing app %s:\n%s\nplease contact with admin of lain\n' % (
appname, e),
reverse('api_docs'))
@classmethod
def delete_app(cls, appname, options=None):
try:
app = App.get_or_none(appname)
if not app.is_reachable():
return (404, None,
'app with appname %s has not been deployd\n' % appname,
reverse('api_apps'))
if app.get_app_type() == AppType.Resource:
return (403, AppApi.render_app(app),
'Not allow to delete resource app.',
reverse('api_apps'))
v = get_etcd_value(PROTECTED_APPS_ETCD_PREFIX,
ETCD_AUTHORITY, '[]')
protected_apps = json.loads(v)
if appname in protected_apps:
return (403, AppApi.render_app(app),
'Not allow to delete protected app.',
reverse('api_apps'))
op_logger.info("DELETE: app %s deleted by %s" %
(appname, AuthApi.operater))
add_oplog(AuthApi.operater, "DELETE",
appname, "", "")
logger.info("ready delete app %s" % appname)
is_meta_empty = True
if app.meta != '':
is_meta_empty = False
remove_results = app.app_remove()
logger.info(render_app_remove_result_to_msg(remove_results))
if not remove_results.get("OK", False):
return (500, None,
render_app_remove_result_to_msg(remove_results),
reverse('api_app', kwargs={'appname': appname}))
app.clear()
return (202, AppApi.render_repo_data(appname),
'delete app successfully.' if is_meta_empty else render_app_remove_result_to_msg(
remove_results),
reverse('api_apps'))
except Exception, e:
client.captureException()
return (500, None,
'fatal error when delete app %s:\n%s\nplease contact with admin of lain\n' % (
appname, e),
reverse('api_app', kwargs={'appname': appname}))
@classmethod
def update_app(cls, access_token, appname, options=None):
try:
app = App.get_or_none(appname)
if not app.is_reachable():
return (404, None,
'app with appname %s has not been deployd\n' % appname,
reverse('api_apps'))
target_meta_version = options.get(
'meta_version', None) if isinstance(options, dict) else None
if target_meta_version and target_meta_version not in app.availabe_meta_versions():
return (400, AppApi.render_app(app),
'no such meta_version %s for app %s\nplease check your images\n' % (
target_meta_version, appname),
reverse('api_app', kwargs={'appname': appname}))
if appname.find('.') < 0 and target_meta_version is None:
exist, target_meta_version = app.check_latest_version()
if not exist:
return (400, None,
'can not get meta_version/meta\nplease check your App images then try to update your App\n',
reverse('api_app', kwargs={'appname': appname}))
app.clear_last_error()
app.set_deploying()
err = cls._app_update(access_token, app, target_meta_version)
if err is not None:
return (406, None, 'request of update app %s is not acceptable with error:%s' %
(appname, err), reverse('api_app', kwargs={'appname': appname}))
return (202, AppApi.render_app(app), 'update request of app %s has been accepted.' % appname,
reverse('api_app', kwargs={'appname': appname}))
except InvalidMetaVersion, ime:
return (500, None,
'error in parsing meta_version: %s\nplease check your App images then try to update your App\n' % ime,
reverse('api_app', kwargs={'appname': appname}))
except Exception, e:
client.captureException()
return (500, None,
'fatal error when update app %s:\n%s\nplease contact with admin of lain\n' % (
appname, e),
reverse('api_app', kwargs={'appname': appname}))
@classmethod
def _app_update(cls, token, app, target_meta_version):
former_version, former_meta = app.meta_version, app.meta
try:
if app.appname.find('.') > 0:
cls._update_resource_instance(token, app, target_meta_version)
else:
cls._update_normal_app(token, app, target_meta_version)
except Exception, e:
client.captureException()
error_msg = "\nUpdating app %s results: %s" % (
app.appname, str(e))
logger.error(error_msg)
# role back to the former version if error happends
app.meta_version = former_version
app.meta = former_meta
# app.update_last_error(error_msg)
return error_msg
finally:
app.set_deployed()
@classmethod
def _update_resource_instance(cls, token, instance, target_meta_version):
op_logger.info("UPDATE: resource instance %s updated by %s to version %s" % (
instance.appname, AuthApi.operater, target_meta_version))
add_oplog(AuthApi.operater, "UPDATE", instance.appname,
target_meta_version, "update resource instance")
logger.info("ready update resource instance %s" % instance.appname)
origin_procs = instance.lain_config.procs.values()
# when updating resource instance, its target_meta_version should be
# the latest meta_version of resource
resourcename = Resource.get_resourcename_from_instancename(
instance.appname)
resource = App.get(resourcename)
instance.meta_version = target_meta_version if target_meta_version else resource.meta_version
instance.default_image = Resource.get_instance_image(
resourcename, instance.meta_version)
clientname = Resource.get_clientappname_from_instancename(
instance.appname)
client_app = App.get(clientname)
resources = client_app.lain_config.use_resources
for resource_appname, resource_props in resources.iteritems():
if resource_appname == resourcename:
updated_meta = resource.get_resource_instance_meta(
clientname, resource_props['context'])
instance.update_meta(None, meta=updated_meta, update_spec=True)
ConfigApi.construct_config_for_instance(token, resource, instance)
update_result = instance.basic_app_deploy(origin_procs)
logger.info("%s update result: %s" % (instance.appname,
render_app_update_result_to_msg(update_result, is_resource_instance=True)))
if not update_result.get("OK", False):
raise Exception("\n%s\n" % render_app_update_result_to_msg(
update_result, is_resource_instance=True))
@classmethod
def _update_normal_app(cls, token, app, target_meta_version):
op_logger.info("UPDATE: app %s updated by %s to version %s" % (
app.appname, AuthApi.operater, target_meta_version))
add_oplog(AuthApi.operater, "UPDATE", app.appname,
target_meta_version, "")
# backup the former setting
origin_app = copy.deepcopy(app)
origin_resource = {} if (
app.lain_config is None) else app.lain_config.use_resources
origin_procs = {} if (
app.lain_config is None) else app.lain_config.procs.values()
logger.info("ready update app %s" % app.appname)
if not app.update_meta(target_meta_version, force=True,
update_spec=(app.get_app_type() != AppType.Resource)):
logger.error('error when loading meta_version %s for app %s' %
(target_meta_version, app.appname))
raise Exception('error when loading meta_version %s for app %s' % (
target_meta_version, app.appname))
logger.info("update metaversion to %s" % target_meta_version)
if app.get_app_type() != AppType.Resource:
success, msg = AuthApi.create_resource_instance_group(
token, app.appname)
if not success:
AppApi.recover_fail_update(origin_app, app)
logger.error('error when creating resource instance group for app %s : %s ' % (
app.appname, msg))
raise Exception(
'error when creating resource instance group for app %s : %s ' % (app.appname, msg))
configed_instances = cls._get_configed_instances(
token, app, app.lain_config.use_resources)
ConfigApi.construct_config_for_app(token, app)
update_result = app.app_update(
origin_resource, origin_procs, configed_instances)
logger.info("%s update result: %s" % (
app.appname, render_app_update_result_to_msg(update_result)))
if not update_result.get("OK", False):
raise Exception("\n%s\n" %
render_app_update_result_to_msg(update_result))
@classmethod
def recover_fail_update(self, origin_app, new_app):
new_app.meta = origin_app.meta
new_app.meta_version = origin_app.meta_version
new_app.save()
@classmethod
def get_app(cls, appname, options=None):
try:
app = App.get_or_none(appname)
if not app.is_reachable():
return (404, None,
'app with appname %s has not been deployd\n' % appname,
reverse('api_apps'))
return (200, AppApi.render_app(app),
'', reverse('api_app', kwargs={'appname': appname}))
except Exception, e:
client.captureException()
return (500, None,
'fatal error when get app %s:\n%s\nplease contact with admin of lain\n' % (
appname, e),
reverse('api_app', kwargs={'appname': appname}))
@classmethod
def get_repo(cls, appname, options=None):
try:
return (200, AppApi.render_repo_data(appname),
'', reverse('api_repo', kwargs={'appname': appname}))
except Exception, e:
client.captureException()
return (500, None,
'fatal error when get repo app %s:\n%s\nplease contact with admin of lain\n' % (
appname, e),
reverse('api_repo', kwargs={'appname': appname}))
@classmethod
def get_versions(cls, appname, options=None):
def handle(app):
availabe_meta_versions = app.availabe_meta_versions()
return (200, AppApi.render_version_data(appname, availabe_meta_versions),
'', reverse('api_versions', kwargs={'appname': appname}))
return cls.deal_with_appname(appname, handle)
@classmethod
def get_details(cls, appname, options=None):
def handle(app):
return (200, AppApi.render_detail_data(appname, app.giturl, app.meta_version),
'', reverse('api_details', kwargs={'appname': appname}))
return cls.deal_with_appname(appname, handle)
@classmethod
def post_image_push(cls, appname, authors, commits):
def handle(app):
try:
app.check_latest_giturl()
except InvalidLainYaml, e:
return (400, None, '%s' % e, reverse('api_image_push', kwargs={'appname': appname}))
uniq_authors = authors
total_commits = commits
if authors is None:
timestamp_len = 10
commits_info = fetch_project_commits(
app.giturl, int(app.meta_version[:timestamp_len]), int(app.latest_meta_version[:timestamp_len]))
if commits_info is not None:
uniq_authors, total_commits = commits_info
else:
return (400, None, 'Fetch commmits information failed', reverse('api_docs'))
if len(total_commits) == 0 or len(uniq_authors) == 0:
return (400, None, 'Nothing Changed', reverse('api_docs'))
commitid_len = 40
datas = {
"appname": appname,
"commits": total_commits,
"operator": AuthApi.operater,
"lastid": app.meta_version[-commitid_len:],
"nextid": app.latest_meta_version[-commitid_len:],
"giturl": app.giturl,
"authors": uniq_authors,
}
logger.info('notify datas:%s', str(datas))
image_push_notify(datas)
return (200, None, 'ok', reverse('api_image_push', kwargs={'appname': appname}))
return cls.deal_with_appname(appname, handle)
@classmethod
def deal_with_appname(cls, appname, handle):
try:
app = App.get_or_none(appname)
return handle(app)
except NoAvailableImages, e:
return (404, None, 'no avaible images for app %s:\n%s\nplease push images first.' % (appname, e),
reverse('api_versions', kwargs={'appname': appname}))
except Exception, e:
client.captureException()
return (500, None,
'fatal error when getting version of app %s:\n%s\nplease contact with admin of lain\n' % (
appname, e),
reverse('api_repo', kwargs={'appname': appname}))
'''
这个类响应 console.views 的 对 Proc 相关的调用
'''
class ProcApi:
@classmethod
def render_pod_data(cls, pod):
return {
'containerid': pod['Containers'][0]['Id'],
'containername': pod['Containers'][0]['Runtime']['Name'],
'containerip': pod['Containers'][0]['ContainerIp'],
'containerport': pod['Containers'][0]['ContainerPort'],
'nodeip': pod['Containers'][0]['NodeIp'],
'status': str(pod['Containers'][0]['Runtime']['State']['Running']),
'uptime': convert_time_from_deployd(pod['Containers'][0]['Runtime']['State']['StartedAt']),
'envs': pod['Containers'][0]['Runtime']['Config']['Env'],
}
@classmethod
def render_proc_data(cls, appname, proc_lain_conf, proc_status=None, is_portal=False, client=None):
data = {
'procname': proc_lain_conf.name,
'proctype': proc_lain_conf.type.name,
'image': proc_lain_conf.image,
'numinstances': proc_lain_conf.num_instances,
'cpu': proc_lain_conf.cpu,
'memory': proc_lain_conf.memory,
'persistentdirs': proc_lain_conf.volumes,
'dnssearchs': proc_lain_conf.dns_search,
'ports': [{'portnumber': p.port, 'porttype': p.type.name} for p in proc_lain_conf.port.values()],
'mountpoints': proc_lain_conf.mountpoint,
'httpsonly': proc_lain_conf.https_only,
'user': proc_lain_conf.user,
'workingdir': proc_lain_conf.working_dir,
'entrypoint': proc_lain_conf.entrypoint,
'cmd': proc_lain_conf.cmd,
'envs': proc_lain_conf.env,
'pods': [],
'depends': [],
'url': reverse('api_proc', kwargs={'appname': appname, 'procname': proc_lain_conf.name}),
'logs': proc_lain_conf.logs,
'lasterror': '',
}
if proc_status and isinstance(proc_status['Status'], dict):
pods, depends = [], []
last_error = ''
pods_meta = proc_status['Status']['Pods']
if pods_meta is not None:
# handle the situation when proc is portal
if is_portal:
for client_name, pods_info in pods_meta.iteritems():
if client and client != client_name:
continue
for pod in pods_info:
pods.append(ProcApi.render_pod_data(pod))
last_error = pod['LastError']
else:
for pod in pods_meta:
pods.append(ProcApi.render_pod_data(pod))
last_error = proc_status['Status']['LastError']
data['pods'] = pods
data['depends'] = depends
data['lasterror'] = last_error
# patch num_instances / cpu / memory spec in deploy to LainConf
try:
data['numinstances'] = proc_status[
'Status']['Spec']['NumInstances']
data['cpu'] = int(proc_status['Status']['Spec'][
'Pod']['Containers'][0]['CpuLimit'])
data['memory'] = humanfriendly.format_size(
int(proc_status['Status']['Spec']['Pod']['Containers'][0]['MemoryLimit']))
data['image'] = proc_status['Status'][
'Spec']['Pod']['Containers'][0]['Image']
except:
pass
return data
@classmethod
def list_app_procs(cls, appname, options=None):
try:
app = App.get_or_none(appname)
if not app.is_reachable():
return (404, None,
'app with appname %s has not been deployd\n' % appname,
reverse('api_apps'))
proc_datas = []
for proc in app.lain_config.procs.values():
if proc.type != ProcType.portal:
pg_status = app.podgroup_status("%s.%s.%s" % (
appname, proc.type.name, proc.name
))
proc_datas.append(ProcApi.render_proc_data(
appname, proc, pg_status))
return (200, proc_datas, '', reverse('api_procs', kwargs={'appname': appname}))
except Exception, e:
client.captureException()
return (500, None,
'fatal error when get app %s procs:\n%s\nplease contact with admin of lain\n' % (
appname, e),
reverse('api_app', kwargs={'appname': appname}))
@classmethod
def create_app_proc(cls, appname, procname, options=None):
try:
app = App.get_or_none(appname)
if not app.is_reachable():
return (404, None,
'app with appname %s has not been deployd\n' % appname,
reverse('api_apps'))
proc, pg_status = app.proc_and_pg_status(procname)
if proc is None:
return (400, None,
'no such proc %s in app %s' % (procname, appname),
reverse('api_procs', kwargs={'appname': appname}))
if pg_status and options.get('type', None) != 'canary':
return (409, ProcApi.render_proc_data(appname, proc, pg_status),
'proc with procname %s already exists\n' % procname,
reverse('api_proc', kwargs={'appname': appname, 'procname': procname}))
op_logger.info("DEPLOY: proc %s from app %s deployed by %s" % (
procname, appname, AuthApi.operater))
add_oplog(AuthApi.operater, "DEPLOY", appname, "",
"proc %s depolyd" % procname)
podgroup_name = "%s.%s.%s" % (
app.appname, proc.type.name, proc.name)
podgroup_spec = app.podgroup_spec(podgroup_name)
# if create canary type proc, 1. rename pgname 2. add canary info
if options is not None and options.get('type', None) == 'canary':
podgroup_spec.Name = "%s.%s.%s" % (
app.appname, 'canary', proc.name)
podgroup_spec.Pod.Name = podgroup_spec.Name
podgroup_spec.strategies = options.get('strategies', [])
deploy_result = recursive_deploy(podgroup_spec)
if deploy_result.get("OK", False):
return (201, ProcApi.render_proc_data(appname, proc, app.podgroup_status(podgroup_name)),
render_podgroup_deploy_result_to_msg(deploy_result),
reverse('api_proc', kwargs={'appname': appname, 'procname': procname}))
else:
return (500, None,
render_podgroup_deploy_result_to_msg(deploy_result),
reverse('api_procs', kwargs={'appname': appname}))
except Exception, e:
client.captureException()
return (500, None,
'fatal error when create app %s proc %s:\n%s\nplease contact with admin of lain\n' % (
appname, procname, e),
reverse('api_app', kwargs={'appname': appname}))
@classmethod
def get_app_proc(cls, appname, procname, options=None):
try:
app = App.get_or_none(appname)
if not app.is_reachable():
return (404, None,
'app with appname %s has not been deployd\n' % appname,
reverse('api_apps'))
proc, pg_status = app.proc_and_pg_status(procname)
if proc is None:
return (404, None,
'no such proc %s in app %s' % (procname, appname),
reverse('api_procs', kwargs={'appname': appname}))
if pg_status:
return (200, ProcApi.render_proc_data(appname, proc, pg_status),
'', reverse('api_proc', kwargs={'appname': appname, 'procname': procname}))
else:
return (200, ProcApi.render_proc_data(appname, proc),
'proc %s exists but not deployed' % (procname),
reverse('api_proc', kwargs={'appname': appname, 'procname': procname}))
except Exception, e:
client.captureException()
return (500, None,
'fatal error when get app %s proc %s:\n%s\nplease contact with admin of lain\n' % (
appname, procname, e),
reverse('api_procs', kwargs={'appname': appname}))
@classmethod
def get_proc_history(cls, appname, procname, instance, options=None):
try:
app = App.get_or_none(appname)
if not app.is_reachable():
return (404, None,
'app with appname %s has not been deployd\n' % appname,
reverse('api_apps'))
status_history = app.podgroup_status_history(procname, instance)
if status_history:
return (200, status_history,
'', reverse('api_proc_history',
kwargs={'appname': appname, 'procname': procname, 'instance': instance}))
else:
return (200, [],
'proc %s do not exists' % (procname),
reverse('api_proc_history',
kwargs={'appname': appname, 'procname': procname, 'instance': instance}))
except Exception, e:
client.captureException()
return (500, None,
'fatal error when get app %s proc %s:\n%s\nplease contact with admin of lain\n' % (
appname, procname, e),
reverse('api_procs', kwargs={'appname': appname}))
@classmethod
def update_app_proc(cls, appname, procname, options):
def verify_options(options):
num_instances_flag = None
cpu_flag = None
memory_flag = None
msg = ''
verified_options = {}
if options.has_key('num_instances'):
num_instances_flag = True
num_instances = options['num_instances']
if not isinstance(num_instances, int):
msg += 'invalid parameter: num_instances (%s) should be integer' % num_instances
num_instances_flag = False
else:
verified_options['num_instances'] = num_instances
if options.has_key('cpu'):
cpu_flag = True
cpu = options['cpu']
if not isinstance(cpu, int):
msg += 'invalid parameter: cpu (%s) should be integer' % cpu
cpu_flag = False
else:
verified_options['cpu'] = cpu
if options.has_key('memory'):
memory_flag = True
memory = options['memory']
try:
my_memory = humanfriendly.parse_size(memory)
verified_options['memory'] = my_memory
except:
msg += 'invalid parameter: memory (%s) humanfriendly.parse_size(memory) failed' % memory
memory_flag = False
ret_flag = all([
len(verified_options),