-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoffline-generator.py
1368 lines (1073 loc) · 49.5 KB
/
offline-generator.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
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
#!/usr/bin/env python
# offline-gen
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'Sabha Parameswaran'
import os
import json
import copy
import yaml, sys, requests
from pprint import pprint
import argparse
import traceback
PATH = os.path.dirname(os.path.realpath(__file__))
LIB_PATH = os.path.realpath(os.path.join(PATH, 'lib'))
TEMPLATE_PATH = os.path.realpath(os.path.join(PATH, 'templates'))
#sys.path.append(REPO_PATH)
sys.path.append(LIB_PATH)
import template
from utils import *
repo = '.'
pipeline = None
handler_config = None
default_bucket_config = {}
analysis_output_file = None
CONFIG_FILE = 'input.yml'
DEFAULT_VERSION = '1.0'
DEFAULT_RESOURCES_PATH = 'resources'
input_config_file = None
offline_pipeline = None
src_pipeline = None
RUN_NAME = None
param_file = None
process_resource_jobs = []
final_input_resources = []
final_output_resources = []
git_resources = {}
git_task_list = {}
docker_image_for_git_task_list = {}
full_docker_ref = []
docker_image_analysis_map = None
DEFAULT_GITHUB_RAW_CONTENT = 'raw.githubusercontent.com'
github_raw_content = None
def init():
parser = argparse.ArgumentParser()
parser.add_argument('target_pipeline', type=str,
help='path to the target pipeline git repo dir')
parser.add_argument('input_yml', type=str,
help='path to the input yml file')
parser.add_argument('-kickoff',
action='store_true',
help='kickoff offline-gen first phase')
parser.add_argument('-analyze',
action='store_true',
help='docker dependency analysis only of tasks in github resources')
return parser.parse_args()
def main():
global repo, handler_config, input_config_file, pipeline, params, default_bucket_config, github_raw_content, analysis_output_file, RUN_NAME
args = init()
input_config_file = args.input_yml if args.input_yml is not None else CONFIG_FILE
print 'General Settings from: {}\n'.format(input_config_file)
analysis_only = args.analyze
kickoff_only = args.kickoff
handler_config = read_config(input_config_file)
repo = args.target_pipeline if args.target_pipeline is not None else handler_config['repo']
pipeline = handler_config['pipeline']
default_bucket_config = handler_config['s3_blobstore']
pipeline_name_tokens = pipeline.split('/')
target_pipeline_name = pipeline_name_tokens[len(pipeline_name_tokens) - 1]
RUN_NAME = handler_config['offline_run_id'] if handler_config.get('offline_run_id') is not None else 'Run1'
print 'Using Offline Run Id : {}'.format(RUN_NAME)
github_raw_content = handler_config.get('github_raw_content')
if github_raw_content is None:
github_raw_content = DEFAULT_GITHUB_RAW_CONTENT
analysis_output_file = 'analysis-' + target_pipeline_name
if kickoff_only:
handle_kickoff_pipeline_generation()
elif analysis_only:
handle_docker_analysis_of_pipelines()
else:
handle_pipelines()
def handle_docker_analysis_of_pipelines():
global src_pipeline, offline_pipeline
#print('Repo Path: {}\nPipeline file: {}'.format(repo, pipeline))
src_pipeline = read_config(repo + '/' + pipeline )
offline_pipeline = copy.copy(src_pipeline)
docker_analysis_map = analyze_pipeline_for_docker_images(None, src_pipeline)
write_config( docker_analysis_map, analysis_output_file)
#print ''
#print 'Created docker image analysis of pipeline: ' + analysis_output_file
return docker_analysis_map
def handle_kickoff_pipeline_generation():
global src_pipeline
print('Repo Path: {}\nPipeline file: {}'.format(repo, pipeline))
src_pipeline = read_config(repo + '/' + pipeline )
#print 'Got src pipeline: {}'.format(src_pipeline)
pipeline_name_tokens = pipeline.split('/')
target_pipeline_name = pipeline_name_tokens[len(pipeline_name_tokens) - 1]
git_only_pipeline_filename= 'kickoff-full-offline-gen-' + target_pipeline_name
try:
git_input_resources = handle_git_only_resources()
save_kickoff_pipeline( git_input_resources,
git_only_pipeline_filename
)
print '\nFinished git_only pipeline generation!!\n\n'
except Exception as e:
print('Error : {}'.format(e))
print(traceback.format_exc())
print >> sys.stderr, 'Error occured.'
sys.exit(1)
def save_kickoff_pipeline(git_input_resources, git_only_pipeline_filename):
print 'Input git resources:{}'.format(git_input_resources)
offlinegen_param_file_source = copy.copy(default_bucket_config)
pipeline_param_file_source = copy.copy(default_bucket_config)
analysis_results_filesource = copy.copy(default_bucket_config)
blobstore_upload_pipeline_source = copy.copy(default_bucket_config)
offline_pipeline_source = copy.copy(default_bucket_config)
OFFLINE_GEN_RESOURCE_BASE_PATH = '%s/%s/%s' % ( RUN_NAME, DEFAULT_RESOURCES_PATH, 'offline-gen')
offlinegen_param_file_source['regexp'] = '%s/offline-gen-params-*(.*).yml' % ( OFFLINE_GEN_RESOURCE_BASE_PATH)
pipeline_param_file_source['regexp'] = '%s/pipeline-params-*(.*).yml' % ( OFFLINE_GEN_RESOURCE_BASE_PATH)
analysis_results_filesource['regexp'] = '%s/analysis-*(.*).yml' % ( OFFLINE_GEN_RESOURCE_BASE_PATH)
offline_pipeline_source['regexp'] = '%s/offline-*(.*).yml' % ( OFFLINE_GEN_RESOURCE_BASE_PATH)
blobstore_upload_pipeline_source['regexp'] = '%s/blobstore-upload-*(.*).yml' % ( OFFLINE_GEN_RESOURCE_BASE_PATH)
try:
context = {}
resource_context = {
'context': context,
'source_resource_types': [],
#'process_resource_jobs': process_resource_jobs,
'offline_gen_param_file_source': offlinegen_param_file_source,
'pipeline_param_file_source': pipeline_param_file_source,
'git_resources': git_input_resources,
'target_pipeline_branch': handler_config['target_pipeline_branch'],
'target_pipeline_uri': handler_config['target_pipeline_uri'],
'analysis_results_filesource': analysis_results_filesource,
'blobstore_upload_pipeline_source': blobstore_upload_pipeline_source,
'offline_pipeline_source': offline_pipeline_source
}
git_only_pipeline = template.render_as_config(
os.path.join('.', 'blobstore/full_offline_generation.v1.yml' ),
resource_context
)
write_config(git_only_pipeline, git_only_pipeline_filename)
print ''
#print 'Created full offline analysis pipeline: ' + git_only_pipeline_filename
except Exception as e:
print('Error during git only pipeline generation : {}'.format(e))
print(traceback.format_exc())
print >> sys.stderr, 'Error occured.'
sys.exit(1)
def handle_pipelines():
global src_pipeline, offline_pipeline
print('Repo Path: {}\nPipeline file: {}'.format(repo, pipeline))
src_pipeline = read_config(repo + '/' + pipeline )
offline_pipeline = copy.copy(src_pipeline)
#print 'Got src pipeline: {}'.format(src_pipeline)
pipeline_name_tokens = pipeline.split('/')
target_pipeline_name = pipeline_name_tokens[len(pipeline_name_tokens) - 1]
offline_pipeline_filename= 'offline-' + target_pipeline_name
blobstore_upload_pipeline_filename = 'blobstore-upload-' + target_pipeline_name
try:
handle_resources()
save_blobuploader_pipeline( final_input_resources,
final_output_resources,
blobstore_upload_pipeline_filename
)
save_offline_pipeline(offline_pipeline_filename)
print '\nFinished offline generation!!\n\n'
except Exception as e:
print('Error : {}'.format(e))
print(traceback.format_exc())
print >> sys.stderr, 'Error occured.'
sys.exit(1)
def save_offline_pipeline(offline_pipeline_filename):
try:
handle_offline_tasks()
if "true" == handler_config.get('parameterize_s3_bucket_params'):
handle_inline_parameterization_of_s3blobstore(offline_pipeline)
write_config(offline_pipeline, offline_pipeline_filename, useNoAliasDumper=False)
print 'Created offline pipeline: ' + offline_pipeline_filename
except Exception as e:
print('Error during offline pipeline generation : {}'.format(e))
print(traceback.format_exc())
print >> sys.stderr, 'Error occured.'
sys.exit(1)
# Change parameters in final generated offline pipeline s3 source to be s3_blobstore_parameterized_tokens
# for porting across S3 blobstore_source. This will allow replacement of actual s3 configs to parameterized list
# Sample generated S3 source
#source: {access_key_id: my_access_id, bucket: offline-bucket, endpoint: 'http://10.85.24.5:9000/',
# regexp: test1/resources/docker/czero-cflinuxfs2-latest-docker.(.*), secret_access_key: my_secret_access_key}
# Modified to
#source: {access_key_id: ((final_s3_access_key_id)), bucket: ((final_s3_bucket)), endpoint: ((final_s3_endpoint)),
# regexp: test1/resources/docker/czero-cflinuxfs2-latest-docker.(.*), secret_access_key: ((final_s3_secret_access_key))}
def handle_inline_parameterization_of_s3blobstore(content):
s3blobstore_replacement_token_map = handler_config.get('s3_blobstore_parameterized_tokens')
if s3blobstore_replacement_token_map is None:
return
if type(content) == list:
for item in content:
handle_inline_parameterization_of_s3blobstore(item)
elif type(content) == dict:
for key in content.keys():
if key == 'source':
source = content[key]
if 'access_key_id' not in source.keys():
return
for key in s3blobstore_replacement_token_map:
source[key] = '((%s))' % (s3blobstore_replacement_token_map[key])
# Replace the actual run name in the regexp to 'offline_run_id' label
# so it can be overridden or left empty string
# Example: regexp: test1/resources/pivnet-tile/pivotal-container-service/(.*).pivotal
# Replace this with: ((offline_run_id))/resources/pivnet-tile/pivotal-container-service/(.*).pivotal
source['regexp'] = source['regexp'].replace(RUN_NAME, '((offline_run_id))')
else:
handle_inline_parameterization_of_s3blobstore(content[key])
def save_blobuploader_pipeline(input_resources, output_resources, blobstore_upload_pipeline_filename):
if src_pipeline.get('resource_types') is None:
src_pipeline['resource_types'] = []
try:
context = {}
resource_context = {
'context': context,
'source_resource_types': src_pipeline.get('resource_types'),
#'process_resource_jobs': process_resource_jobs,
'resources': src_pipeline['resources'],
'final_input_resources': input_resources,
'final_output_resources': output_resources,
'files': []
}
blobstore_upload_pipeline = template.render_as_config(
os.path.join('.', 'blobstore/blobstore_upload_pipeline.v1.yml' ),
resource_context
)
if "true" == handler_config.get('parameterize_s3_bucket_params'):
handle_inline_parameterization_of_s3blobstore(blobstore_upload_pipeline)
write_config(blobstore_upload_pipeline, blobstore_upload_pipeline_filename)
print ''
print 'Created blobstore upload pipeline: ' + blobstore_upload_pipeline_filename
except Exception as e:
print('Error during blobuploader pipeline generation : {}'.format(e))
print(traceback.format_exc())
print >> sys.stderr, 'Error occured.'
sys.exit(1)
def analyze_pipeline_for_docker_images(pipeline_repo_path, target_pipeline):
global docker_image_analysis_map
if target_pipeline is None:
target_pipeline = read_config(pipeline_repo_path)
task_files = identify_all_task_files(target_pipeline)
identify_associated_docker_image_for_task(git_task_list)
# print '\nFinal Docker dependency list'
# pprint(full_docker_ref)
# print '\nDependency graph of Github Repos, tasks and docker images references\n'
# pprint(docker_image_for_git_task_list)
docker_image_analysis_map = { 'docker_list': full_docker_ref, 'pipeline_task_docker_references': docker_image_for_git_task_list }
write_config( docker_image_analysis_map, analysis_output_file)
# print ''
# print 'Created docker image analysis of pipeline: ' + analysis_output_file
return docker_image_analysis_map
def identify_all_task_files(target_pipeline):
task_files = []
for resource in target_pipeline['resources']:
if resource['type'] == 'git':
print 'Input Resource: {}'.format(resource)
branch = resource['source'].get('branch')
if branch is None:
branch = 'master'
uri = resource['source']['uri'].replace('.git', '').replace('github.com', 'raw.githubusercontent.com')
git_resources[resource['name']] = {'uri' : uri, 'branch' : branch }
git_task_list[resource['name']] = []
docker_image_task_entry = { 'git_path': 'pipeline' }
docker_image_task_entry['task_defns'] = []
docker_image_task_entry['docker_references'] = []
docker_image_task_entry['job_tasks_references'] = []
for job in target_pipeline['jobs']:
job_tasks = []
for plan in job['plan']:
for plan_key in plan.keys():
if str(plan_key) in [ 'aggregate', 'do' ]:
aggregate = plan[plan_key]
for entry in aggregate:
for nested_entry_key in entry:
if nested_entry_key == 'task':
task_file = entry.get('file')
if task_file is None:
continue
if task_file is not None:
git_resource_id = task_file.split('/')[0]
job_tasks.append( { 'task': entry.get('task'), 'file': task_file, 'git_resource' : git_resource_id } )
if task_file is not None and task_file not in task_files:
task_files.append(task_file)
git_task_list[git_resource_id].append({ 'task': entry.get('task'), 'file': task_file } )
elif str(plan_key) == 'task':
task_file = plan.get('file')
if task_file is None:
continue
if task_file is not None:
git_resource_id = task_file.split('/')[0]
job_tasks.append( { 'task': plan[plan_key], 'file': task_file, 'git_resource' : git_resource_id } )
if task_file is not None and task_file not in task_files:
task_files.append(task_file)
git_task_list[git_resource_id].append({ 'task': plan.get('task'), 'file': task_file })
elif task_file is None:
image_source = plan['config']['image_resource']
if image_source is not None and 'docker' in image_source['type']:
docker_repo = image_source['source']
docker_image_task_entry['task_defns'].append( { plan.get('task') : { 'image': docker_repo } } )
if docker_repo not in full_docker_ref:
full_docker_ref.append(docker_repo)
if docker_repo not in docker_image_task_entry['docker_references']:
docker_image_task_entry['docker_references'].append(docker_repo)
docker_image_task_entry['job_tasks_references'].append( { job['name'] : job_tasks } )
docker_image_for_git_task_list['target-pipeline'] = docker_image_task_entry
# print '\nComplete task list\n'
# pprint(task_files)
# print '\nComplete git task list\n'
# pprint(git_task_list)
# print '\n'
return task_files
def identify_associated_docker_image_for_task(git_task_list):
for git_repo_id in git_resources:
git_resource = git_resources[git_repo_id]
git_repo_path = '%s/%s/' % (git_resource['uri'], git_resource['branch'])
git_repo_path = git_repo_path.replace('git@%s/' % (github_raw_content), 'https://%s/' % (github_raw_content) )
if git_resource.get('username') is not None:
git_repo_path = git_repo_path.replace('https://',
'https://%s:%s@' % (git_resource.get('username') , git_resource.get('password') ))
docker_image_task_entry = { 'git_path': git_repo_path }
docker_image_task_entry['task_defns'] = []
docker_image_task_entry['docker_references'] = []
task_list = git_task_list[git_repo_id]
for task in task_list:
index = task['file'].index('/')
task_path = task['file'][index+1:]
task_defn = load_github_resource(git_repo_id, git_repo_path, task_path)
image_source = task_defn.get('image_source')
if image_source is None:
image_source = task_defn.get('image_resource')
if image_source is not None and 'docker' in image_source['type']:
docker_repo = image_source['source']
docker_image_task_entry['task_defns'].append( {
task.get('task'): {
'file': task_path,
'image': docker_repo ,
'script': task_defn['run']['path'] ,
'inputs': task_defn.get('inputs'),
'outputs': task_defn.get('outputs'),
'params': task_defn.get('params')
}
}
)
if docker_repo not in docker_image_task_entry['docker_references']:
docker_image_task_entry['docker_references'].append(docker_repo)
if docker_repo not in full_docker_ref:
full_docker_ref.append(docker_repo)
docker_image_for_git_task_list[git_repo_id] = docker_image_task_entry
#print 'Full Docker image task entry: {}'.format(docker_image_task_entry)
def load_github_resource(git_repo_id, git_remote_uri, task_file_path):
try:
# First try with local file path
input_file = git_repo_id + '/' + task_file_path
with open(input_file) as task_file:
yamlcontent = yaml.safe_load(task_file)
#print 'Successful reading task as local file: {}\n'.format(input_file)
return yamlcontent
except IOError as e:
try:
print >> sys.stderr, 'Problem with reading task as local file: {}'.format(input_file)
response = requests.get(git_remote_uri + task_file_path)
yamlcontent = yaml.safe_load(response.content)
print 'Went with Remote url for task: {}\n'.format(git_remote_uri + task_file_path)
return yamlcontent
except IOError as e:
print e
print >> sys.stderr, 'Not able to load content from : ' + uri
sys.exit(1)
def handle_resources():
global docker_image_analysis_map
#task_list = identify_all_task_files(src_pipeline)
# Identify all tasks and docker images used in the final pipeline
# Add docker images as resources in source pipeline
# Then rejigger the resources to be input and output in the blobuploader pipeline
# Try to use saved default docker image analysis map file
docker_image_analysis_map = read_config( analysis_output_file, abort=False)
# Else handle full parsing
if docker_image_analysis_map is None:
docker_image_analysis_map = analyze_pipeline_for_docker_images(None, offline_pipeline)
#else:
# print 'Used existing docker image analysis map of pipeline from: ' + analysis_output_file
for docker_image_ref in docker_image_analysis_map['docker_list']:
version = 'latest' if docker_image_ref.get('tag') is None else docker_image_ref.get('tag')
docker_image_ref['tag'] = version
docker_image_name = '%s-%s-%s' % (docker_image_ref['repository'].replace('/', '-'), version, 'docker')
src_pipeline['resources'].append( { 'name': docker_image_name, 'type' : 'docker-image', 'source' : docker_image_ref})
# Reset all resources in the offline pipeline
offline_pipeline['resources'] = []
offline_pipeline['resource_types'] = []
# Then add the modified resources to the offline_pipeline
for resource in src_pipeline['resources']:
res_type = resource['type']
res_name = resource['name']
resource_process_job = None
if res_type == 's3':
resource['base_type'] = 's3'
resource_process_job = handle_s3_resource(copy.copy(resource))
elif res_type == 'git':
resource['base_type'] = 'git'
resource_process_job = handle_git_resource(resource, src_pipeline, docker_image_analysis_map['pipeline_task_docker_references'][res_name])
elif 'docker' in res_type:
resource['base_type'] = 'docker'
resource_process_job = handle_docker_image(resource)
elif res_type == 'pivnet':
if resource['source']['product_slug'] in [ 'ops-manager' ]:
resource['base_type'] = 'pivnet-non-tile'
resource_process_job = handle_pivnet_non_tile_resource(resource)
else:
resource['base_type'] = 'tile'
resource_process_job = handle_pivnet_tile_resource(copy.deepcopy(resource))
else:
resource['base_type'] = 'file'
resource_process_job = handle_default_resource(resource)
print '\nFinished handling of all resource jobs\n'
def add_inout_resources(resource):
input_resource = copy.copy(resource)
output_resource = copy.copy(resource)
input_resource['name'] = 'input-%s-%s' % (input_resource['base_type'], resource['name'])
output_resource['name'] = 'output-%s-%s' % (input_resource['base_type'], resource['name'])
output_resource['source'] = copy.copy(default_bucket_config)
output_resource['source']['regexp'] = output_resource['regexp']
final_input_resources.append(input_resource)
final_output_resources.append(output_resource)
offline_resource = { 'name' : resource['name'] , 'type': 's3' , 'source': copy.copy(default_bucket_config) }
offline_resource['source']['regexp'] = copy.copy(resource['regexp'])
# For git or docker resource, change name to *-tarball
if resource['base_type'] in ['git', 'docker' ]:
offline_resource['name'] = '%s-tarball' % (resource['name'])
# Dont add the tile base type as input as we bundle the tarball for tiles in offline pipeline
if resource['base_type'] not in ['tile']:
offline_pipeline['resources'].append(offline_resource)
def handle_git_only_resources():
#task_list = identify_all_task_files(src_pipeline)
# Identify all tasks and docker images used in the final pipeline
# Add docker images as resources in source pipeline
# Then rejigger the resources to be input and output in the blobuploader pipeline
git_only_resources = []
# Then add the modified resources to the offline_pipeline
for resource in src_pipeline['resources']:
res_type = resource['type']
res_name = resource['name']
resource_process_job = None
if res_type == 'git':
git_only_resources.append(resource)
print '\nFinished handling of all git only resource jobs\n'
return git_only_resources
def handle_docker_image(resource):
resource['base_type'] = 'docker'
tag = resource['source'].get('tag')
if tag is None:
tag = 'latest'
resource['tag'] = tag
tagged_docker = '%s-docker' % tag
# If the tag + 'docker' is already in the resource name, dont add it again
if tagged_docker in resource['name']:
resource['regexp'] = '%s/%s/docker/%s.(.*)' % ( RUN_NAME, DEFAULT_RESOURCES_PATH, resource['name'])
else:
resource['regexp'] = '%s/%s/docker/%s-%s-docker.(.*)' % ( RUN_NAME, DEFAULT_RESOURCES_PATH, resource['name'], tag)
context = {}
resource_context = {
'context': context,
'resource': resource,
'files': []
}
docker_job_resource = template.render_as_config(
os.path.join('.', 'blobstore/handle_docker_image.yml' ),
resource_context
)
# Register the in/out resources
add_inout_resources(resource)
return docker_job_resource
def handle_git_resource(resource, src_pipeline, task_list):
res_name = resource['name']
resource['base_type'] = 'git'
resource['regexp'] = '%s/%s/%s/%s-tar(.*).tgz' % ( RUN_NAME, DEFAULT_RESOURCES_PATH, 'git', resource['name'])
matching_task_files = []
for task_file in task_list:
if task_file.startswith(res_name):
matching_task_files.append(task_file.replace(res_name + '/', ''))
#print '####### Task list for git resource: {}'.format(matching_task_files)
# Jinja template would barf against single quote. so change to double quotes
task_list_arr = str(matching_task_files)#.replace('\'', '"')
bucket_config = str(default_bucket_config)#.replace('\'', '"')
resource['task_list'] = task_list_arr
resource['blobstore_source'] = bucket_config
context = {}
resource_context = {
'context': context,
'resource': resource,
'task_list': task_list_arr,
'blobstore_source' : bucket_config,
'files': []
}
git_job_resource = template.render_as_config(
os.path.join('.', 'blobstore/handle_git_resource.yml' ),
resource_context
)
# Register the in/out resources
add_inout_resources(resource)
return git_job_resource
def handle_pivnet_tile_resource(resource):
resource['base_type'] = 'tile'
resource['regexp'] = '%s/%s/pivnet-tile/%s/(.*).pivotal' % ( RUN_NAME, DEFAULT_RESOURCES_PATH, resource['name'])
context = {}
resource_context = {
'context': context,
'resource': resource,
'files': []
}
pivnet_tile_job_resource = template.render_as_config(
os.path.join('.', 'blobstore/handle_pivnet_tile.yml' ),
resource_context
)
# Register the default in/out resources
add_inout_resources(resource)
# Register the combined tile + stemcell also
combined_tile_stemcell_regexp = '%s/%s/pivnet-tile/%s-tarball/%s-(.*).tgz' % ( RUN_NAME, DEFAULT_RESOURCES_PATH, resource['name'], resource['name'])
output_tile_stemcell_resource = { 'type': 's3' , 'source': copy.deepcopy(default_bucket_config) }
output_tile_stemcell_resource['name'] = 'output-%s-%s' % ('tile-stemcell', resource['name'])
output_tile_stemcell_resource['source']['regexp'] = combined_tile_stemcell_regexp
final_output_resources.append(output_tile_stemcell_resource)
tile_tarball_regexp = '%s/%s/pivnet-tile/%s-tarball/(.*).tgz' % ( RUN_NAME, DEFAULT_RESOURCES_PATH, resource['name'])
offline_tile_tarball_resource = { 'name' : '%s' % resource['name'] , 'type': 's3' , 'source': copy.deepcopy(default_bucket_config) }
offline_tile_tarball_resource = { 'name' : '%s-tarball' % resource['name'] , 'type': 's3' , 'source': copy.deepcopy(default_bucket_config) }
offline_tile_tarball_resource['source']['regexp'] = tile_tarball_regexp
offline_tile_tarball_resource['name'] = '%s-%s' % (resource['name'], 'tarball')
offline_pipeline['resources'].append(offline_tile_tarball_resource)
return pivnet_tile_job_resource
def handle_pivnet_non_tile_resource(resource):
resource['base_type'] = 'pivnet-non-tile'
resource['regexp'] = '%s/%s/pivnet-non-tile/%s-(.*)' % ( RUN_NAME, DEFAULT_RESOURCES_PATH, resource['name'])
context = {}
resource_context = {
'context': context,
'resource': resource,
'files': []
}
non_pivnet_job_resource = template.render_as_config(
os.path.join('.', 'blobstore/handle_non_pivnet_tile.yml' ),
resource_context
)
# Register the in/out resources
add_inout_resources(resource)
#print 'Job for Pivnet non-Tile resource: {}'.format(non_pivnet_job_resource)
return non_pivnet_job_resource
def handle_s3_resource(resource):
# If the source and destination are the same s3 buckets/access keys,
# then just simply copy the resource into offline pipeline
resource['base_type'] = 's3'
if resource['source']['endpoint'] == default_bucket_config['endpoint'] \
and resource['source']['bucket'] == default_bucket_config['bucket'] \
and resource['source']['access_key_id'] == \
default_bucket_config['access_key_id'] \
and resource['source']['secret_access_key'] == \
default_bucket_config['secret_access_key']:
# Just add to the offline resource list
offline_pipeline['resources'].append(resource)
return None
# Requires modification
resource['base_type'] = 's3'
resource['regexp'] = '%s/%s/s3/%s-(.*)' % ( RUN_NAME, DEFAULT_RESOURCES_PATH, resource['name'])
context = {}
resource_context = {
'context': context,
'resource': resource,
'files': []
}
s3_job_resource = template.render_as_config(
os.path.join('.', 'blobstore/handle_file_resource.yml' ),
resource_context
)
# Register the in/out resources
add_inout_resources(resource)
#print 'Job for S3 resource: {}'.format(s3_job_resource)
return s3_job_resource
def handle_default_resource(resource):
resource['base_type'] = 'file'
resource['regexp'] = '%s/%s/file/%s-*-(.*)' % ( RUN_NAME, DEFAULT_RESOURCES_PATH, resource['name'])
context = {}
resource_context = {
'context': context,
'resource': resource,
'files': []
}
file_job_resource = template.render_as_config(
os.path.join('.', 'blobstore/handle_file_resource.yml' ),
resource_context
)
# Register the in/out resources
add_inout_resources(resource)
#print 'Job for File resource: {}'.format(file_job_resource)
return file_job_resource
def find_match_in_list(list, name):
for entry in list:
if entry['name'] == name + '-tarball':
return entry
elif entry['name'] == name:
return entry
return None
def create_resource_map(resource_list):
resource_map = {}
for entry in resource_list:
name = entry['name']
resource_map[entry['name']] = entry
name_without_tarball = name.replace('-tarball', '')
if resource_map.get(name_without_tarball) is None:
resource_map[name_without_tarball] = entry
return resource_map
def handle_offline_tasks():
job_tasks_references = docker_image_analysis_map['pipeline_task_docker_references']['target-pipeline']['job_tasks_references']
for offline_job in offline_pipeline['jobs']:
found_job_tasks_reference = False
target_task_name = None
target_task_file = None
ref_map_target_job_name = None
alias_resource_map = {}
for job_tasks_reference in job_tasks_references:
ref_map_target_job_name = job_tasks_reference.keys()[0]
if offline_job['name'] == ref_map_target_job_name:
found_job_tasks_reference = True
break
plan_index = 0
saved_plan_inputs = []
for plan in offline_job['plan']:
#print '## Offline job: {}, job_tasks_reference: {}, set of keys inside plan: {} and type: {}\n\n\n'.format(
# offline_job['name'], job_tasks_reference, plan.keys(), type(plan))
non_resource_related_entry_map = {}
last_saved_plan_entry_map = {}
for plan_key in plan:
plan_entry = plan[plan_key]
if plan_key in ['aggregate' , 'do' ]:
original_aggregate = copy.copy(plan_entry)
handle_aggregated_plan_entry(plan, plan_key, original_aggregate, alias_resource_map, job_tasks_reference)
#print 'Plan after get aggregated resource details: {}'.format(plan)
# We need to strip off the *.pivotal tile from input resources from the aggregated gets of the plan
# - aggregate:
# - {get: nsx-t-ci-pipeline-tarball}
# - {get: czero-cflinuxfs2-latest-docker-tarball}
# - get: pivotal-container-service-tarball
# params:
# globs: [pivotal-container-service*.pivotal] --> remove this
# - get: pcf-ops-manager
# params:
# globs: []
# passed: [deploy-director]
# trigger: true
for entry in plan['aggregate']:
if entry.get('params') and entry['params'].get('globs'):
#print 'Glob entry within plan: {}'.format(entry['params']['globs'])
copy_of_glob_entries = copy.copy(entry['params']['globs'])
for glob_entry in copy_of_glob_entries:
if glob_entry.endswith('.pivotal'):
entry['params']['globs'].remove(glob_entry)
# if not entry['params']['globs']:
# entry['params'].pop('globs', None)
# if not entry['params']:
# entry.pop('params', None)
for new_entry in plan[plan_key]:
for entry_key, entry_value in new_entry.items():
if entry_key == 'get' and entry_value not in saved_plan_inputs:
saved_plan_inputs.append(entry_value)
elif plan_key in [ 'file', 'task' ]:
inline_task_details(plan, alias_resource_map, ref_map_target_job_name, saved_plan_inputs)
elif 'get' == plan_key:
for plan_entry in plan.keys():
if plan_entry != 'get':
# Skip non-get attributes
continue
original_get_resource_name = plan[plan_entry]
new_nested_plan_entries = handle_get_resource_details(original_get_resource_name, job_tasks_reference)
if new_nested_plan_entries is not None:
plan['aggregate'] = new_nested_plan_entries
for nested_plan_entry in new_nested_plan_entries:
(entry_key, entry_value), = nested_plan_entry.items()
if entry_key == 'get' and entry_value not in saved_plan_inputs:
saved_plan_inputs.append(entry_value)
#print 'Saved Plan Inputs: {}'.format(saved_plan_inputs)
plan.pop('get', None)
else:
# Just save the entry as is (we are only worried abt tasks and gets that need modification)
# Check if the task has already been processed!!
embedded_task = plan.get('task')
# Pop off any image references from the plan
# We want to purely go with image_resource and not image
plan.pop('image', None)
#print 'Finally modified Plan: {}'.format(plan)
plan_index += 1
print 'Finished handling of all jobs in offline pipeline'
def handle_aggregated_plan_entry(plan, aggregate_key, original_aggregate, alias_resource_map, job_tasks_reference):
non_resource_related_entry_map = {}
last_saved_plan_entry_map = {}
original_aggregate_list = plan[aggregate_key]
new_aggregate_list = []
offline_resource_map = create_resource_map(offline_pipeline['resources'])
for entry in original_aggregate_list:
for nested_entry_key, nested_entry_value in entry.items():
if nested_entry_key == 'get':
original_get_resource_name = nested_entry_value
# Rare cases where the get is tagged as pivnet-prodcut
# - get: pivnet-product
# resource: pivotal-container-service
# params: {globs: ["pivotal-container-service*.pivotal"]}
matching_resource = offline_resource_map.get(original_get_resource_name)
if matching_resource is None:
aliased_resource_name = original_get_resource_name
if entry.get('resource') is not None:
original_get_resource_name = entry.get('resource')
entry.pop('resource', None)
alias_resource_map[aliased_resource_name] = original_get_resource_name
#print 'Setting entry {} for alias_resource_map to {} and original resource {}'.format(aliased_resource_name,
# original_get_resource_name, original_get_resource_name)
new_nested_entries = handle_get_resource_details(original_get_resource_name, job_tasks_reference)
#print 'Got nested plan entries as {} '.format(new_nested_entries)
if new_nested_entries is not None:
for new_nested_entry in new_nested_entries:
for new_nested_entry_key, new_nested_entry_value in new_nested_entry.items():
if 'docker' not in new_nested_entry_key:
last_saved_plan_entry_map[new_nested_entry_key] = new_nested_entry_value
# Close out previously saved current_plan_entry_map entry
if last_saved_plan_entry_map:
new_aggregate_list.append(last_saved_plan_entry_map )
last_saved_plan_entry_map = { }
else:
new_aggregate_list.append( { new_nested_entry_key : new_nested_entry_value } )
else:
if nested_entry_key == 'resource':
continue
last_saved_plan_entry_map[nested_entry_key] = nested_entry_value
if last_saved_plan_entry_map:
new_aggregate_list.append(last_saved_plan_entry_map)
# Save this as the new plan entry against the aggregate key
plan[aggregate_key] = new_aggregate_list
#print 'After saving updated plan, got offline resources as: \n {}'.format(offline_pipeline['resources'])
def handle_get_resource_details(get_resource_name, job_tasks_reference):
new_nested_plan_entries = []
resource_type = 'file'
src_resource_map = create_resource_map(src_pipeline['resources'])
offline_resource_map = create_resource_map(offline_pipeline['resources'])
matching_tarballed_resource = None
matching_orginal_resource = src_resource_map[get_resource_name]
if matching_orginal_resource is not None:
resource_type = matching_orginal_resource['type']
else:
print 'Error!! Unable to find matching resource: {} from src pipeline!'.format(get_resource_name)
return None
matching_offline_resource = offline_resource_map.get(get_resource_name)
if matching_offline_resource is not None:
matching_tarballed_resource = matching_offline_resource
if resource_type in [ 'file-url', 'file', 's3' ]:
# Add original input resource as is
new_nested_plan_entries.append( { 'get' : get_resource_name } )
elif resource_type in [ 'docker', 'docker-image', 'git' ]:
# Add the github tarball as input if its a match against git resources in offline pipeline
if matching_tarballed_resource is None:
print 'Unable to find matching resource: {}'.format(get_resource_name + '-tarball')
return None
resource_id = get_resource_name
job_name = job_tasks_reference.keys()[0]
# print 'COMPLETE JOB TASKS REFERENCE: {} , JOB NAME ***** :{} before \
# adding docker reference'.format(job_tasks_reference.keys(), job_name)
# Sample job_tasks_ref
# {'standalone-install-nsx-t': [{'file': 'nsx-t-gen-pipeline/tasks/install-nsx-t/task.yml',
# 'git_resource': 'nsx-t-gen-pipeline',
# 'task': 'install-nsx-t'}]},
docker_image_tarball_name = None
original_task_input_params = None
for job_task in job_tasks_reference[job_name]:
#print 'Job tasks is {} and Task is {}'.format(job_tasks_reference, job_task)
matching_task_name = job_task['task']