-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzuul-migrate
1769 lines (1533 loc) · 65.7 KB
/
zuul-migrate
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
# Copyright 2017 Red Hat, Inc.
#
# 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.
# Run this using a JJB virtual env:
#
# tox -e jenkins-jobs --notest
# ./.tox/jenkins-jobs/bin/python zuul-migrate
#
# To verify syntax
# ./.tox/jenkins-jobs/bin/pip install 'ansible==9.*'
# ./.tox/jenkins-jobs/bin/python zuul-migrate --syntax-check
#
# The resulting playbooks and zuul.d are written in the current working
# directory
#
# TODO(mordred):
# * Read and apply filters from the jobs: section
# * Figure out shared job queues
# * Emit job definitions
# * figure out from builders whether or not it's a normal job or a
# a devstack-legacy job
# * Handle emitting arbitrary tox jobs (see tox-py27dj18)
import argparse
import collections
import copy
import getopt
import logging
import os
import subprocess
import sys
import tempfile
import re
from typing import Any, Dict, List, Optional
import jenkins_jobs.builder
from jenkins_jobs.config import JJBConfig
import jenkins_jobs.formatter
from jenkins_jobs.local_yaml import Jinja2Loader
import jenkins_jobs.registry
from jenkins_jobs.parser import YamlParser
import jenkins_jobs.parser
import yaml
JOB_MATCHERS = {} # type: Dict[str, Dict[str, Dict]]
TEMPLATES_TO_EXPAND = {} # type: Dict[str, List]
JOBS_FOR_EXPAND = collections.defaultdict(dict) # type: ignore
SUFFIXES = [] # type: ignore
SKIP_MACROS = [] # type: ignore
# Jenkins jobs we are not migrated
SKIP_JOBS = [
'fail-archived-repositories',
]
ENVIRONMENT = '{{ zuul | zuul_legacy_vars }}'
DESCRIPTION = """Migrate zuul v2 and Jenkins Job Builder to Zuul v3.
This program takes a zuul v2 layout.yaml and a collection of Jenkins Job
Builder job definitions and transforms them into a Zuul v3 config. An
optional mapping config can be given that defines how to map old jobs
to new jobs.
"""
def colored_logging():
# Color codes http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
logging.addLevelName( # cyan
logging.DEBUG,
"\033[36m%s\033[0m" % logging.getLevelName(logging.DEBUG),
)
logging.addLevelName( # green
logging.INFO, "\033[32m%s\033[0m" % logging.getLevelName(logging.INFO)
)
logging.addLevelName( # yellow
logging.WARNING,
"\033[33m%s\033[0m" % logging.getLevelName(logging.WARNING),
)
logging.addLevelName( # red
logging.ERROR,
"\033[31m%s\033[0m" % logging.getLevelName(logging.ERROR),
)
logging.addLevelName( # red background
logging.CRITICAL,
"\033[41m%s\033[0m" % logging.getLevelName(logging.CRITICAL),
)
def deal_with_shebang(data):
# Ansible shell blocks do not honor shebang lines. That's fine - but
# we do have a bunch of scripts that have either nothing, -x, -xe,
# -ex or -eux. Transform those into leading set commands
if not data.startswith('#!'):
return (None, data)
data_lines = data.split('\n')
data_lines.reverse()
shebang = data_lines.pop()
split_line = shebang.split()
# Strip the # and the !
executable = split_line[0][2:]
if executable == '/bin/sh':
# Ansible default
executable = None
if len(split_line) > 1:
flag_x = False
flag_e = False
flag_u = False
optlist, args = getopt.getopt(split_line[1:], 'uex')
for opt, _ in optlist:
if opt == '-x':
flag_x = True
elif opt == '-e':
flag_e = True
elif opt == '-u':
flag_u = True
if flag_x:
data_lines.append('set -x')
if flag_e:
data_lines.append('set -e')
if flag_u:
data_lines.append('set -u')
data_lines.reverse()
data = '\n'.join(data_lines).lstrip()
return (executable, data)
def _extract_from_vars(line):
# export PROJECTS="openstack/blazar $PROJECTS"
# export DEVSTACK_PROJECT_FROM_GIT=python-swiftclient
# export DEVSTACK_PROJECT_FROM_GIT="python-octaviaclient"
# export DEVSTACK_PROJECT_FROM_GIT+=",glean"
projects = []
line = line.replace('"', '').replace('+', '').replace(',', ' ')
if (line.startswith('export PROJECTS') or
line.startswith('export DEVSTACK_PROJECT_FROM_GIT')):
nothing, project_string = line.split('=')
project_string = project_string.replace('$PROJECTS', '').strip()
projects = project_string.split()
return projects
def extract_projects(data):
# clonemap:
# - name: openstack/windmill
# dest: .
# EOF
projects = []
data_lines = data.split('\n')
in_clonemap = False
in_clonemap_cli = False
for line in data_lines:
line = line.strip()
if line == 'clonemap:':
in_clonemap = True
continue
elif line == 'EOF':
in_clonemap = False
continue
elif line.startswith('/usr/zuul-env/bin/zuul-cloner'):
in_clonemap_cli = True
continue
elif in_clonemap_cli and not line.endswith('\\'):
in_clonemap_cli = False
continue
if in_clonemap:
if line.startswith('- name:'):
garbage, project = line.split(':')
project = project.strip().replace("'", '').replace('"', '')
if project == '$ZUUL_PROJECT':
continue
projects.append(project)
elif in_clonemap_cli and line.startswith('openstack/'):
line = line.replace('\\', '').strip()
projects.append(line)
elif in_clonemap_cli:
continue
else:
projects.extend(_extract_from_vars(line))
return projects
def expand_project_names(required, full):
projects = []
for name in full:
repo = name
if '/' in name:
org, repo = name.split('/')
if repo in required or name in required:
projects.append(name)
return projects
def list_to_project_dicts(projects):
project_dicts = dict()
for project in projects:
project_dicts[project['project']['name']] = project['project']
return project_dicts
def project_dicts_to_list(project_dicts):
project_config = []
for key in sorted(project_dicts.keys()):
project_config.append(dict(project=project_dicts[key]))
return project_config
def merge_project_dict(project_dicts, name, project):
if name not in project_dicts:
project_dicts[name] = project
return
old = project_dicts[name]
for key in project:
if key not in old:
old[key] = project[key]
elif isinstance(old[key], list):
old[key].extend(project[key])
elif isinstance(old[key], dict) and 'jobs' in old[key]:
old[key]['jobs'].extend(project[key]['jobs'])
return
def normalize_project_expansions():
remove_from_job_matchers = []
# First find the matchers that are the same for all jobs
for job_name, project in copy.deepcopy(JOBS_FOR_EXPAND).items():
JOB_MATCHERS[job_name] = None
for project_name, expansion in project.items():
if not JOB_MATCHERS[job_name]:
JOB_MATCHERS[job_name] = copy.deepcopy(expansion['info'])
else:
if JOB_MATCHERS[job_name] != expansion['info']:
# We have different expansions for this job, it can't be
# done at the job level
remove_from_job_matchers.append(job_name)
for job_name in remove_from_job_matchers:
JOB_MATCHERS.pop(job_name, None)
# Second, find out which projects need to expand a given template
for job_name, project in copy.deepcopy(JOBS_FOR_EXPAND).items():
# There is a job-level expansion for this one
if job_name in JOB_MATCHERS:
continue
for project_name, expansion in project.items():
TEMPLATES_TO_EXPAND[project_name] = []
if expansion['info']:
# There is an expansion for this project
TEMPLATES_TO_EXPAND[project_name].append(expansion['template'])
# from :
# http://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data # noqa
def should_use_block(value):
for c in u"\u000a\u000d\u001c\u001d\u001e\u0085\u2028\u2029":
if c in value:
return True
return False
def my_represent_scalar(self, tag, value, style=None):
if style is None:
if should_use_block(value):
style = '|'
else:
style = self.default_style
node = yaml.representer.ScalarNode(tag, value, style=style)
if self.alias_key is not None:
self.represented_objects[self.alias_key] = node
return node
def project_representer(dumper, data):
return dumper.represent_mapping('tag:yaml.org,2002:map',
data.items())
def construct_yaml_map(self, node):
data = collections.OrderedDict()
yield data
value = self.construct_mapping(node)
if isinstance(node, yaml.MappingNode):
self.flatten_mapping(node)
else:
raise yaml.constructor.ConstructorError(
None, None,
'expected a mapping node, but found %s' % node.id,
node.start_mark)
mapping = collections.OrderedDict()
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=False)
try:
hash(key)
except TypeError as exc:
raise yaml.constructor.ConstructorError(
'while constructing a mapping', node.start_mark,
'found unacceptable key (%s)' % exc, key_node.start_mark)
value = self.construct_object(value_node, deep=False)
mapping[key] = value
data.update(mapping)
class IndentedEmitter(yaml.emitter.Emitter):
def expect_block_sequence(self):
self.increase_indent(flow=False, indentless=False)
self.state = self.expect_first_block_sequence_item
class IndentedDumper(IndentedEmitter, yaml.serializer.Serializer,
yaml.representer.Representer, yaml.resolver.Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=None,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None, sort_keys=True):
IndentedEmitter.__init__(
self, stream, canonical=canonical,
indent=indent, width=width,
allow_unicode=allow_unicode,
line_break=line_break)
yaml.serializer.Serializer.__init__(
self, encoding=encoding,
explicit_start=explicit_start,
explicit_end=explicit_end,
version=version, tags=tags)
yaml.representer.Representer.__init__(
self, default_style=default_style,
default_flow_style=default_flow_style)
yaml.resolver.Resolver.__init__(self)
def ordered_load(stream, *args, **kwargs):
return yaml.load(stream=stream, *args, Loader=yaml.SafeLoader, **kwargs)
def ordered_dump(data, stream=None, *args, **kwargs):
dumper = IndentedDumper
# We need to do this because of how template expasion into a project
# works. Without it, we end up with YAML references to the expanded jobs.
dumper.ignore_aliases = lambda self, data: True
output = yaml.dump(
data, default_flow_style=False,
Dumper=dumper, width=80, *args, **kwargs).replace(
'\n -', '\n\n -')
if stream:
stream.write(output)
else:
return output
def get_single_key(var):
if isinstance(var, str):
return var
elif isinstance(var, list):
return var[0]
return list(var.keys())[0]
def has_single_key(var):
if isinstance(var, list):
return len(var) == 1
if isinstance(var, str):
return True
dict_keys = list(var.keys())
if len(dict_keys) != 1:
return False
if var[get_single_key(var)]:
return False
return True
def combination_matches(combination, match_combinations):
"""
Checks if the given combination is matches for any of the given combination
globs, being those a set of combinations where if a key is missing, it's
considered matching
(key1=2, key2=3)
would match the combination match:
(key2=3)
but not:
(key1=2, key2=2)
"""
for cmatch in match_combinations:
for key, val in combination.items():
if cmatch.get(key, val) != val:
break
else:
return True
return False
class JJB(jenkins_jobs.builder.JenkinsManager):
def __init__(self, parser):
self.global_config = None
self._plugins_list = []
self.parser = parser
def expandComponent(self, component_type, component, template_data):
component_list_type = component_type + 's'
new_components = []
if isinstance(component, dict):
# The component is a singleton dictionary of name: dict(args)
name, component_data = next(iter(component.items()))
if template_data or isinstance(component_data, Jinja2Loader):
try:
component_data = jenkins_jobs.formatter.deep_format(
component_data, template_data, True)
except Exception:
logging.error(
"Failure formatting component ('%s') data '%s'",
name,
component_data,
)
raise
else:
name = component
component_data = {}
new_component = self.parser.data.get(component_type, {}).get(name)
if new_component:
for new_sub_component in new_component[component_list_type]:
new_components.extend(
self.expandComponent(component_type,
new_sub_component, component_data))
else:
new_components.append({name: component_data})
return new_components
def expandMacros(self, job):
for component_type in ['builder', 'publisher', 'wrapper']:
component_list_type = component_type + 's'
new_components = []
for new_component in job.get(component_list_type, []):
# Skip macros defined in mappings.yaml
if new_component in SKIP_MACROS:
continue
new_components.extend(self.expandComponent(component_type,
new_component, {}))
job[component_list_type] = new_components
class OldProject:
def __init__(self, name, gate_jobs):
self.name = name
self.gate_jobs = gate_jobs
class OldJob:
def __init__(self, name):
self.name = name
self.queue_name = None
def __repr__(self):
return self.name
class Job:
log = logging.getLogger("zuul.Migrate")
def __init__(self,
orig: str,
name: str=None,
content: Dict[str, Any]=None,
vars: Dict[str, str]=None,
nodes: List[str]=None,
parent=None) -> None:
self.orig = orig
self.voting = True
self.name = name
self.content = content.copy() if content else None
self.vars = vars or {}
self.required_projects = [] # type: ignore
self.nodes = nodes or []
self.parent = parent
self.branch = None
self.files = None
self.jjb_job = None
self.emit = True
if self.content and not self.name:
self.name = get_single_key(content)
if not self.name:
self.name = self.orig
self.name = self.name.replace('-{name}', '').replace('{name}-', '')
for suffix in SUFFIXES:
suffix = '-{suffix}'.format(suffix=suffix)
if self.name.endswith(suffix):
self.name = self.name.replace(suffix, '')
def _stripNodeName(self, node):
node_key = '-{node}'.format(node=node)
self.name = self.name.replace(node_key, '')
def setNoEmit(self):
self.emit = False
def setVars(self, vars):
self.vars = vars
def setParent(self, parent):
self.parent = parent
def extractNode(self, default_node, labels):
matching_label = None
for label in labels:
if label in self.orig:
if not matching_label:
matching_label = label
elif len(label) > len(matching_label):
matching_label = label
if matching_label:
if matching_label == default_node:
self._stripNodeName(matching_label)
else:
self.nodes.append(matching_label)
def getDepends(self):
return [self.parent.name]
def getNodes(self):
return self.nodes
def addJJBJob(self, jobs):
self.jjb_job = jobs[self.orig]
def getTimeout(self):
timeout = None
if self.jjb_job:
for wrapper in self.jjb_job.get('wrappers', []):
if isinstance(wrapper, dict):
build_timeout = wrapper.get(
'build-timeout', wrapper.get('timeout'))
if isinstance(build_timeout, dict):
timeout = build_timeout.get('timeout')
if timeout is not None:
try:
timeout = int(timeout) * 60
except ValueError:
# XXX The debian-glue jobs use '$BUILD_TIMEOUT'
# which is injected by Zuul
self.log.warning(
'Can not process timeout for %s: '
'timeout "%s" is invalid',
self.jjb_job['name'], timeout)
timeout = 10800
# NOTE: This should be read from tenant config
if timeout > 10800:
timeout = 10800
return timeout
@property
def short_name(self):
return self.name.replace('legacy-', '')
@property
def job_path(self):
return 'playbooks/legacy/{name}'.format(name=self.short_name)
def _getRsyncOptions(self, source):
# If the source starts with ** then we want to match any
# number of directories, so don't anchor the include filter.
# If it does not start with **, then the intent is likely to
# at least start by matching an immediate file or subdirectory
# (even if later we have a ** in the middle), so in this case,
# anchor it to the root of the transfer (the workspace).
if not source.startswith('**'):
source = os.path.join('/', source)
# These options mean: include the thing we want, include any
# directories (so that we continue to search for the thing we
# want no matter how deep it is), exclude anything that
# doesn't match the thing we want or is a directory, then get
# rid of empty directories left over at the end.
rsync_opts = ['--include=%s' % source,
'--include=*/',
'--exclude=*',
'--prune-empty-dirs']
return rsync_opts
def _makeSCPTask(self, publisher):
# NOTE(mordred) About docs-draft manipulation:
# The target of html/ was chosen to put the node contents into the
# html dir inside of logs such that if the node's contents have an
# index.html in them setting the success-url to html/ will render
# things as expected. Existing builder macros look like:
#
# - publisher:
# name: upload-sphinx-draft
# publishers:
# - scp:
# site: 'static.openstack.org'
# files:
# - target: 'docs-draft/$LOG_PATH'
# source: 'doc/build/html/**'
# keep-hierarchy: true
# copy-after-failure: true
#
# Which is pulling the tree of the remote html directory starting with
# doc/build/html and putting that whole thing into
# docs-draft/$LOG_PATH.
#
# Then there is a success-pattern in layout.yaml that looks like:
#
# http://{url}/{log_path}/doc/build/html/
#
# Which gets reports. There are many variations on that URL. So rather
# than needing to figure out varying success-urls to report in v3,
# we'll remote the ** and not process this through the rsync_opts
# processing we use for the other publishers, but instead will just
# pass doc/build/html/ to get the contents of doc/build/html/ and we'll
# put those in {{ log_root }}/html/ locally meaning the success-url
# can always be html/. This should work for all values of source
# from v2.
tasks = []
artifacts = False
draft = False
site = publisher['scp']['site']
for scpfile in publisher['scp']['files']:
if 'ZUUL_PROJECT' in scpfile.get('source', ''):
self.log.error(
"Job {name} uses ZUUL_PROJECT in source".format(
name=self.name))
continue
if scpfile.get('copy-console'):
continue
else:
src = "{{ ansible_user_dir }}/workspace/"
rsync_opts = self._getRsyncOptions(scpfile['source'])
target = scpfile['target']
# TODO(mordred) Generalize this next section, it's SUPER
# openstack specific. We can likely do this in mapping.yaml
if site == 'static.openstack.org':
for f in ('service-types', 'specs'):
if target.startswith(f):
self.log.error(
"Job {name} uses {f} publishing".format(
name=self.name, f=f))
continue
if target.startswith('docs-draft'):
target = "{{ zuul.executor.log_root }}/html/"
src = scpfile['source'].replace('**', '')
rsync_opts = None
draft = True
else:
target = target.replace(
'logs/$LOG_PATH',
"{{ zuul.executor.log_root }}")
elif site == 'tarballs.openstack.org':
if not target.startswith('tarballs'):
self.log.error(
'Job {name} wants to publish artifacts to non'
' tarballs dir'.format(name=self.name))
continue
if target.startswith('tarballs/ci'):
target = target.split('/', 3)[-1]
else:
target = target.split('/', 2)[-1]
target = "{{ zuul.executor.work_root }}/artifacts/" + target
artifacts = True
elif site == 'yaml2ical':
self.log.error('Job {name} uses yaml2ical publisher')
continue
syncargs = collections.OrderedDict()
syncargs['src'] = src
syncargs['dest'] = target
syncargs['mode'] = 'pull'
syncargs['copy_links'] = True
syncargs['verify_host'] = True
if rsync_opts:
syncargs['rsync_opts'] = rsync_opts
task = collections.OrderedDict()
task['name'] = 'Copy files from {src} on node'.format(src=src)
task['synchronize'] = syncargs
# We don't use retry_args here because there is a bug in
# the synchronize module that breaks subsequent attempts at
# retrying. Better to try once and get an accurate error
# message if it fails.
# https://github.com/ansible/ansible/issues/18281
tasks.append(task)
if artifacts:
ensure_task = collections.OrderedDict()
ensure_task['name'] = 'Ensure artifacts directory exists'
ensure_task['file'] = collections.OrderedDict()
ensure_task['file']['path'] = \
"{{ zuul.executor.work_root }}/artifacts"
ensure_task['file']['state'] = 'directory'
ensure_task['delegate_to'] = 'localhost'
tasks.insert(0, ensure_task)
return dict(tasks=tasks, artifacts=artifacts, draft=draft)
def _emitShellTask(self, data, syntax_check):
shell, data = deal_with_shebang(data)
task = collections.OrderedDict()
# Putting the data directly into shell: causes here docs to break.
task['shell'] = collections.OrderedDict()
task['shell']['cmd'] = data
if shell:
task['shell']['executable'] = shell
task['shell']['chdir'] = '{{ ansible_user_dir }}/workspace'
if syntax_check:
# Emit a test playbook with this shell task in it then run
# ansible-playbook --syntax-check on it. This will fail if there
# are embedding issues, such as with unbalanced single quotes
# The end result should be less scripts and more shell
play = dict(hosts='all', tasks=[task])
(fd, tmp_path) = tempfile.mkstemp()
try:
f = os.fdopen(fd, 'w')
ordered_dump([play], f)
f.close()
proc = subprocess.run(
['ansible-playbook', '--syntax-check', tmp_path],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if proc.returncode != 0:
# Return of None means we must emit a script
self.log.error(
"Job {name} had an ansible syntax error, using script"
" instead of shell".format(name=self.name))
self.log.error(proc.stdout)
return None
finally:
os.unlink(tmp_path)
return task
def _emitScriptContent(self, data, playbook_dir, seq):
script_fn = '%s-%02d.sh' % (self.short_name, seq)
script_path = os.path.join(playbook_dir, script_fn)
with open(script_path, 'w') as script:
if not data.startswith('#!'):
data = '#!/bin/bash -x\n %s' % (data,)
script.write(data)
task = collections.OrderedDict()
task['name'] = 'Running playbooks/legacy/{playbook}'.format(
playbook=script_fn)
task['script'] = script_fn
return task
def _makeBuilderTask(self, playbook_dir, builder, sequence, syntax_check):
# Don't write a script to echo the template line
# TODO(mordred) Put these into mapping.yaml
if builder['shell'].startswith('echo JJB template: '):
return
if 'echo "Detailed logs:' in builder['shell']:
return
if ('cat /etc/dib-builddate.txt' in builder['shell'] and
'echo "Network configuration data..."' in builder['shell']):
return
task = self._emitShellTask(builder['shell'], syntax_check)
if not task:
task = self._emitScriptContent(
builder['shell'], playbook_dir, sequence)
task['environment'] = ENVIRONMENT
return task
def _transformPublishers(self, jjb_job):
early_publishers = []
late_publishers = []
old_publishers = jjb_job.get('publishers', [])
for publisher in old_publishers:
early_scpfiles = []
late_scpfiles = []
if 'scp' not in publisher:
early_publishers.append(publisher)
continue
copy_console = False
for scpfile in publisher['scp']['files']:
if scpfile.get('copy-console'):
scpfile['keep-hierarchy'] = True
late_scpfiles.append(scpfile)
copy_console = True
else:
early_scpfiles.append(scpfile)
publisher['scp']['files'] = early_scpfiles + late_scpfiles
if copy_console:
late_publishers.append(publisher)
else:
early_publishers.append(publisher)
publishers = early_publishers + late_publishers
if old_publishers != publishers:
self.log.debug("Transformed job publishers")
return early_publishers, late_publishers
def emitPlaybooks(self, jobsdir, syntax_check=False):
has_artifacts = False
has_draft = False
if not self.jjb_job:
if self.emit:
self.log.error(
'Job {name} has no job content'.format(name=self.name))
return False, False, False
playbook_dir = os.path.join(jobsdir, self.job_path)
if not os.path.exists(playbook_dir):
os.makedirs(playbook_dir)
run_playbook = os.path.join(playbook_dir, 'run.yaml')
post_playbook = os.path.join(playbook_dir, 'post.yaml')
tasks = []
workspace_task = collections.OrderedDict()
workspace_task['name'] = "Ensure legacy workspace directory"
workspace_task['file'] = collections.OrderedDict()
workspace_task['file']['path'] = '{{ ansible_user_dir }}/workspace'
workspace_task['file']['state'] = 'directory'
tasks.append(workspace_task)
sequence = 0
for builder in self.jjb_job.get('builders', []):
if 'shell' in builder:
self.required_projects.extend(
extract_projects(builder['shell']))
task = self._makeBuilderTask(
playbook_dir, builder, sequence, syntax_check)
if task:
if 'script' in task:
sequence += 1
tasks.append(task)
play = collections.OrderedDict()
play['hosts'] = 'all'
play['name'] = 'Autoconverted job {name} from old job {old}'.format(
name=self.name, old=self.orig)
play['tasks'] = tasks
with open(run_playbook, 'w') as run_playbook_out:
ordered_dump([play], run_playbook_out)
has_post = False
tasks = []
early_publishers, late_publishers = self._transformPublishers(
self.jjb_job)
for publishers in [early_publishers, late_publishers]:
for publisher in publishers:
if 'scp' in publisher:
ret = self._makeSCPTask(publisher)
if ret['artifacts']:
has_artifacts = True
if ret['draft']:
has_draft = True
tasks.extend(ret['tasks'])
if 'afs' in builder:
self.log.error(
"Job {name} uses AFS publisher".format(name=self.name))
if tasks:
has_post = True
play = collections.OrderedDict()
play['hosts'] = 'all'
play['tasks'] = tasks
with open(post_playbook, 'w') as post_playbook_out:
ordered_dump([play], post_playbook_out)
return has_artifacts, has_post, has_draft
def toJobDict(
self, has_artifacts=False, has_post=False, has_draft=False,
project_names=[]):
output = collections.OrderedDict()
output['name'] = self.name
expanded_projects = []
if self.required_projects:
expanded_projects = expand_project_names(
self.required_projects, project_names)
# Look for project names in the job name. Lookie there - the
# python in operator works on lists and strings.
expanded_projects.extend(expand_project_names(
self.name, project_names))
output['parent'] = 'legacy-base'
if 'dsvm' in self.name:
output['parent'] = 'legacy-dsvm-base'
elif 'puppet-openstack-integration' in self.name:
output['parent'] = 'legacy-puppet-openstack-integration'
elif 'openstack/puppet-openstack-integration' in expanded_projects:
output['parent'] = 'legacy-puppet-openstack-integration'
elif has_artifacts:
output['parent'] = 'legacy-publish-openstack-artifacts'
elif has_draft:
output['success-url'] = 'html/'
output['run'] = os.path.join(self.job_path, 'run.yaml')
if has_post:
output['post-run'] = os.path.join(self.job_path, 'post.yaml')
if self.vars:
output['vars'] = self.vars.copy()
timeout = self.getTimeout()
if timeout:
output['timeout'] = timeout
if self.nodes:
if len(self.nodes) == 1:
output['nodeset'] = self.getNodes()[0]
else:
output['nodeset'] = dict(nodes=self.getNodes())
if expanded_projects:
output['required-projects'] = sorted(list(set(expanded_projects)))
if self.name in JOB_MATCHERS:
for k, v in JOB_MATCHERS[self.name].items():
if k in output:
self.log.error(
'Job %s has attributes directly and from matchers',
self.name)
output[k] = v
return output
def toPipelineDict(self):
if self.content:
output = self.content
else:
output = collections.OrderedDict()
output[self.name] = collections.OrderedDict()
if self.parent:
output[self.name].setdefault('dependencies', self.getDepends())
if not self.voting:
output[self.name].setdefault('voting', False)
if self.vars:
job_vars = output[self.name].get('vars', collections.OrderedDict())
job_vars.update(self.vars)
if self.branch:
output[self.name]['branches'] = self.branch
if self.files:
output[self.name]['files'] = self.files
if not output[self.name]:
return self.name
return output
class JobMapping:
log = logging.getLogger("zuul.Migrate.JobMapping")
def __init__(self, nodepool_config, layout, mapping_file=None):
self.layout = layout
self.job_direct = {}
self.labels = []
self.job_mapping = []
self.template_mapping = {}
self.jjb_jobs = {}
self.seen_new_jobs = []
self.unshare = []
nodepool_data = ordered_load(open(nodepool_config, 'r'))
for label in nodepool_data['labels']:
self.labels.append(label['name'])
if not mapping_file:
self.default_node = 'ubuntu-xenial'
else:
mapping_data = ordered_load(open(mapping_file, 'r'))
self.default_node = mapping_data['default-node']
global SUFFIXES
SUFFIXES = mapping_data.get('strip-suffixes', [])
global SKIP_MACROS
SKIP_MACROS = mapping_data.get('skip-macros', [])
self.unshare = mapping_data.get('unshare', [])
for map_info in mapping_data.get('job-mapping', []):
if map_info['old'].startswith('^'):
map_info['pattern'] = re.compile(map_info['old'])
self.job_mapping.append(map_info)
else: