-
Notifications
You must be signed in to change notification settings - Fork 313
/
supplier.py
744 lines (623 loc) · 32 KB
/
supplier.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
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you 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.
import datetime
import glob
import logging
import os
import re
import shutil
import urllib.error
from esrally import exceptions, paths, PROGRAM_NAME
from esrally.exceptions import BuildError, SystemSetupError
from esrally.utils import git, io, process, net, jvm, convert, sysstats
# e.g. my-plugin:current - we cannot simply use String#split(":") as this would not work for timestamp-based revisions
REVISION_PATTERN = r"(\w.*?):(.*)"
def create(cfg, sources, distribution, car, plugins=None):
logger = logging.getLogger(__name__)
if plugins is None:
plugins = []
caching_enabled = cfg.opts("source", "cache", mandatory=False, default_value=True)
revisions = _extract_revisions(cfg.opts("mechanic", "source.revision", mandatory=sources))
distribution_version = cfg.opts("mechanic", "distribution.version", mandatory=False)
supply_requirements = _supply_requirements(sources, distribution, plugins, revisions, distribution_version)
build_needed = any([build for _, _, build in supply_requirements.values()])
es_supplier_type, es_version, _ = supply_requirements["elasticsearch"]
src_config = cfg.all_opts("source")
suppliers = []
target_os = cfg.opts("mechanic", "target.os", mandatory=False)
target_arch = cfg.opts("mechanic", "target.arch", mandatory=False)
template_renderer = TemplateRenderer(version=es_version, os_name=target_os, arch=target_arch)
if build_needed:
raw_build_jdk = car.mandatory_var("build.jdk")
try:
build_jdk = int(raw_build_jdk)
except ValueError:
raise exceptions.SystemSetupError(f"Car config key [build.jdk] is invalid: [{raw_build_jdk}] (must be int)")
es_src_dir = os.path.join(_src_dir(cfg), _config_value(src_config, "elasticsearch.src.subdir"))
builder = Builder(es_src_dir, build_jdk, paths.logs())
else:
builder = None
distributions_root = os.path.join(cfg.opts("node", "root.dir"), cfg.opts("source", "distribution.dir"))
dist_cfg = {}
# car / plugin defines defaults...
dist_cfg.update(car.variables)
for plugin in plugins:
for k, v in plugin.variables.items():
dist_cfg["plugin_{}_{}".format(plugin.name, k)] = v
# ... but the user can override it in rally.ini
dist_cfg.update(cfg.all_opts("distributions"))
if caching_enabled:
logger.info("Enabling source artifact caching.")
max_age_days = int(cfg.opts("source", "cache.days", mandatory=False, default_value=7))
if max_age_days <= 0:
raise exceptions.SystemSetupError(f"cache.days must be a positive number but is {max_age_days}")
source_distributions_root = os.path.join(distributions_root, "src")
_prune(source_distributions_root, max_age_days)
else:
logger.info("Disabling source artifact caching.")
source_distributions_root = None
if es_supplier_type == "source":
es_src_dir = os.path.join(_src_dir(cfg), _config_value(src_config, "elasticsearch.src.subdir"))
source_supplier = ElasticsearchSourceSupplier(es_version,
es_src_dir,
remote_url=cfg.opts("source", "remote.repo.url"),
car=car,
builder=builder,
template_renderer=template_renderer)
if caching_enabled:
es_file_resolver = ElasticsearchFileNameResolver(dist_cfg, template_renderer)
source_supplier = CachedSourceSupplier(source_distributions_root,
source_supplier,
es_file_resolver)
suppliers.append(source_supplier)
repo = None
else:
es_src_dir = None
repo = DistributionRepository(name=cfg.opts("mechanic", "distribution.repository"),
distribution_config=dist_cfg,
template_renderer=template_renderer)
suppliers.append(ElasticsearchDistributionSupplier(repo, es_version, distributions_root))
for plugin in plugins:
supplier_type, plugin_version, _ = supply_requirements[plugin.name]
if supplier_type == "source":
if CorePluginSourceSupplier.can_handle(plugin):
logger.info("Adding core plugin source supplier for [%s].", plugin.name)
assert es_src_dir is not None, f"Cannot build core plugin {plugin.name} when Elasticsearch is not built from source."
plugin_supplier = CorePluginSourceSupplier(plugin, es_src_dir, builder)
elif ExternalPluginSourceSupplier.can_handle(plugin):
logger.info("Adding external plugin source supplier for [%s].", plugin.name)
plugin_supplier = ExternalPluginSourceSupplier(plugin, plugin_version, _src_dir(cfg, mandatory=False), src_config, builder)
else:
raise exceptions.RallyError("Plugin %s can neither be treated as core nor as external plugin. Requirements: %s" %
(plugin.name, supply_requirements[plugin.name]))
if caching_enabled:
plugin_file_resolver = PluginFileNameResolver(plugin.name, plugin_version)
plugin_supplier = CachedSourceSupplier(source_distributions_root,
plugin_supplier,
plugin_file_resolver)
suppliers.append(plugin_supplier)
else:
logger.info("Adding plugin distribution supplier for [%s].", plugin.name)
assert repo is not None, "Cannot benchmark plugin %s from a distribution version but Elasticsearch from sources" % plugin.name
suppliers.append(PluginDistributionSupplier(repo, plugin))
return CompositeSupplier(suppliers)
def _required_version(version):
if not version or version.strip() == "":
raise exceptions.SystemSetupError("Could not determine version. Please specify the Elasticsearch distribution "
"to download with the command line parameter --distribution-version. "
"E.g. --distribution-version=5.0.0")
else:
return version
def _required_revision(revisions, key, name=None):
try:
return revisions[key]
except KeyError:
n = name if name is not None else key
raise exceptions.SystemSetupError("No revision specified for %s" % n)
def _supply_requirements(sources, distribution, plugins, revisions, distribution_version):
# per artifact (elasticsearch or a specific plugin):
# * key: artifact
# * value: ("source" | "distribution", distribution_version | revision, build = True | False)
supply_requirements = {}
# can only build Elasticsearch with source-related pipelines -> ignore revision in that case
if "elasticsearch" in revisions and sources:
supply_requirements["elasticsearch"] = ("source", _required_revision(revisions, "elasticsearch", "Elasticsearch"), True)
else:
# no revision given or explicitly specified that it's from a distribution -> must use a distribution
supply_requirements["elasticsearch"] = ("distribution", _required_version(distribution_version), False)
for plugin in plugins:
if plugin.core_plugin:
# core plugins are entirely dependent upon Elasticsearch.
supply_requirements[plugin.name] = supply_requirements["elasticsearch"]
else:
# allow catch-all only if we're generally building from sources. If it is mixed, the user should tell explicitly.
if plugin.name in revisions or ("all" in revisions and sources):
# be a bit more lenient when checking for plugin revisions. This allows users to specify `--revision="current"` and
# rely on Rally to do the right thing.
try:
plugin_revision = revisions[plugin.name]
except KeyError:
# maybe we can use the catch-all revision (only if it's not a git revision)
plugin_revision = revisions.get("all")
if not plugin_revision or SourceRepository.is_commit_hash(plugin_revision):
raise exceptions.SystemSetupError("No revision specified for plugin [%s]." % plugin.name)
else:
logging.getLogger(__name__).info("Revision for [%s] is not explicitly defined. Using catch-all revision [%s].",
plugin.name, plugin_revision)
supply_requirements[plugin.name] = ("source", plugin_revision, True)
else:
supply_requirements[plugin.name] = (distribution, _required_version(distribution_version), False)
return supply_requirements
def _src_dir(cfg, mandatory=True):
# Don't let this spread across the whole module
try:
return cfg.opts("node", "src.root.dir", mandatory=mandatory)
except exceptions.ConfigError:
raise exceptions.SystemSetupError("You cannot benchmark Elasticsearch from sources. Did you install Gradle? Please install"
" all prerequisites and reconfigure Rally with %s configure" % PROGRAM_NAME)
def _prune(root_path, max_age_days):
"""
Removes files that are older than ``max_age_days`` from ``root_path``. Subdirectories are not traversed.
:param root_path: A directory which should be checked.
:param max_age_days: Files that have been created more than ``max_age_days`` ago are deleted.
"""
logger = logging.getLogger(__name__)
if not os.path.exists(root_path):
logger.info("[%s] does not exist. Skipping pruning.", root_path)
return
for f in os.listdir(root_path):
artifact = os.path.join(root_path, f)
if os.path.isfile(artifact):
max_age = datetime.datetime.now() - datetime.timedelta(days=max_age_days)
try:
created_at = datetime.datetime.fromtimestamp(os.lstat(artifact).st_ctime)
if created_at < max_age:
logger.info("Deleting [%s] from artifact cache (reached max age).", f)
os.remove(artifact)
else:
logger.debug("Keeping [%s] (max age not yet reached)", f)
except OSError:
logger.exception("Could not check whether [%s] needs to be deleted from artifact cache.", artifact)
else:
logger.info("Skipping [%s] (not a file).", artifact)
class TemplateRenderer:
def __init__(self, version, os_name=None, arch=None):
self.version = version
if os_name is not None:
self.os = os_name
else:
self.os = sysstats.os_name().lower()
if arch is not None:
self.arch = arch
else:
self.arch = sysstats.cpu_arch().lower()
def render(self, template):
substitutions = {
"{{VERSION}}": self.version,
"{{OSNAME}}": self.os,
"{{ARCH}}": self.arch
}
r = template
for key, replacement in substitutions.items():
r = r.replace(key, str(replacement))
return r
class CompositeSupplier:
def __init__(self, suppliers):
self.suppliers = suppliers
def __call__(self, *args, **kwargs):
binaries = {}
for supplier in self.suppliers:
supplier.fetch()
for supplier in self.suppliers:
supplier.prepare()
for supplier in self.suppliers:
supplier.add(binaries)
return binaries
class ElasticsearchFileNameResolver:
def __init__(self, distribution_config, template_renderer):
self.cfg = distribution_config
self.runtime_jdk_bundled = convert.to_bool(self.cfg.get("runtime.jdk.bundled", False))
self.template_renderer = template_renderer
@property
def revision(self):
return self.template_renderer.version
@revision.setter
def revision(self, revision):
self.template_renderer.version = revision
@property
def file_name(self):
if self.runtime_jdk_bundled:
url_key = "jdk.bundled.release_url"
else:
url_key = "jdk.unbundled.release_url"
url = self.template_renderer.render(self.cfg[url_key])
return url[url.rfind("/") + 1:]
@property
def artifact_key(self):
return "elasticsearch"
def to_artifact_path(self, file_system_path):
return file_system_path
def to_file_system_path(self, artifact_path):
return artifact_path
class CachedSourceSupplier:
def __init__(self, distributions_root, source_supplier, file_resolver):
self.distributions_root = distributions_root
self.source_supplier = source_supplier
self.file_resolver = file_resolver
self.cached_path = None
self.logger = logging.getLogger(__name__)
@property
def file_name(self):
return self.file_resolver.file_name
@property
def cached(self):
return self.cached_path is not None and os.path.exists(self.cached_path)
def fetch(self):
# Can we already resolve the artifact without fetching the source tree at all? This is the case when a specific
# revision (instead of a meta-revision like "current") is provided and the artifact is already cached. This is
# also needed if an external process pushes artifacts to Rally's cache which might have been built from a
# fork. In that case the provided commit hash would not be present in any case in the main ES repo.
maybe_an_artifact = os.path.join(self.distributions_root, self.file_name)
if os.path.exists(maybe_an_artifact):
self.cached_path = maybe_an_artifact
else:
resolved_revision = self.source_supplier.fetch()
if resolved_revision:
# ensure we use the resolved revision for rendering the artifact
self.file_resolver.revision = resolved_revision
self.cached_path = os.path.join(self.distributions_root, self.file_name)
def prepare(self):
if not self.cached:
self.source_supplier.prepare()
def add(self, binaries):
if self.cached:
self.logger.info("Using cached artifact in [%s]", self.cached_path)
binaries[self.file_resolver.artifact_key] = self.file_resolver.to_artifact_path(self.cached_path)
else:
self.source_supplier.add(binaries)
original_path = self.file_resolver.to_file_system_path(binaries[self.file_resolver.artifact_key])
# this can be None if the Elasticsearch does not reside in a git repo and the user has only
# copied all source files. In that case, we cannot resolve a revision hash and thus we cannot cache.
if self.cached_path:
try:
io.ensure_dir(io.dirname(self.cached_path))
shutil.copy(original_path, self.cached_path)
self.logger.info("Caching artifact in [%s]", self.cached_path)
binaries[self.file_resolver.artifact_key] = self.file_resolver.to_artifact_path(self.cached_path)
except OSError:
self.logger.exception("Not caching [%s].", original_path)
else:
self.logger.info("Not caching [%s] (no revision info).", original_path)
class ElasticsearchSourceSupplier:
def __init__(self, revision, es_src_dir, remote_url, car, builder, template_renderer):
self.revision = revision
self.src_dir = es_src_dir
self.remote_url = remote_url
self.car = car
self.builder = builder
self.template_renderer = template_renderer
def fetch(self):
return SourceRepository("Elasticsearch", self.remote_url, self.src_dir).fetch(self.revision)
def prepare(self):
if self.builder:
self.builder.build([
self.template_renderer.render(self.car.mandatory_var("clean_command")),
self.template_renderer.render(self.car.mandatory_var("system.build_command"))
])
def add(self, binaries):
binaries["elasticsearch"] = self.resolve_binary()
def resolve_binary(self):
try:
path = os.path.join(self.src_dir,
self.template_renderer.render(self.car.mandatory_var("system.artifact_path_pattern")))
return glob.glob(path)[0]
except IndexError:
raise SystemSetupError("Couldn't find a tar.gz distribution. Please run Rally with the pipeline 'from-sources'.")
class PluginFileNameResolver:
def __init__(self, plugin_name, revision=None):
self.plugin_name = plugin_name
self.revision = revision
@property
def file_name(self):
return f"{self.plugin_name}-{self.revision}.zip"
@property
def artifact_key(self):
return self.plugin_name
def to_artifact_path(self, file_system_path):
return f"file://{file_system_path}"
def to_file_system_path(self, artifact_path):
return artifact_path[len("file://"):]
class ExternalPluginSourceSupplier:
def __init__(self, plugin, revision, src_dir, src_config, builder):
assert not plugin.core_plugin, "Plugin %s is a core plugin" % plugin.name
self.plugin = plugin
self.revision = revision
# may be None if and only if the user has set an absolute plugin directory
self.src_dir = src_dir
self.src_config = src_config
self.builder = builder
subdir_cfg_key = "plugin.%s.src.subdir" % self.plugin.name
dir_cfg_key = "plugin.%s.src.dir" % self.plugin.name
if dir_cfg_key in self.src_config and subdir_cfg_key in self.src_config:
raise exceptions.SystemSetupError("Can only specify one of %s and %s but both are set." % (dir_cfg_key, subdir_cfg_key))
elif dir_cfg_key in self.src_config:
self.plugin_src_dir = _config_value(self.src_config, dir_cfg_key)
# we must build directly in the plugin dir, not relative to Elasticsearch
self.override_build_dir = self.plugin_src_dir
elif subdir_cfg_key in self.src_config:
self.plugin_src_dir = os.path.join(self.src_dir, _config_value(self.src_config, subdir_cfg_key))
self.override_build_dir = None
else:
raise exceptions.SystemSetupError("Neither %s nor %s are set for plugin %s." % (dir_cfg_key, subdir_cfg_key, self.plugin.name))
@staticmethod
def can_handle(plugin):
return not plugin.core_plugin
def fetch(self):
# optional (but then source code is assumed to be available locally)
plugin_remote_url = self.src_config.get("plugin.%s.remote.repo.url" % self.plugin.name)
return SourceRepository(self.plugin.name, plugin_remote_url, self.plugin_src_dir).fetch(self.revision)
def prepare(self):
if self.builder:
command = _config_value(self.src_config, "plugin.{}.build.command".format(self.plugin.name))
self.builder.build([command], override_src_dir=self.override_build_dir)
def add(self, binaries):
binaries[self.plugin.name] = self.resolve_binary()
def resolve_binary(self):
artifact_path = _config_value(self.src_config, "plugin.%s.build.artifact.subdir" % self.plugin.name)
try:
name = glob.glob("%s/%s/*.zip" % (self.plugin_src_dir, artifact_path))[0]
return "file://%s" % name
except IndexError:
raise SystemSetupError("Couldn't find a plugin zip file for [%s]. Please run Rally with the pipeline 'from-sources'." %
self.plugin.name)
class CorePluginSourceSupplier:
def __init__(self, plugin, es_src_dir, builder):
assert plugin.core_plugin, "Plugin %s is not a core plugin" % plugin.name
self.plugin = plugin
self.es_src_dir = es_src_dir
self.builder = builder
@staticmethod
def can_handle(plugin):
return plugin.core_plugin
def fetch(self):
# Just retrieve the current revision *number* and assume that Elasticsearch has prepared the source tree.
return SourceRepository("Elasticsearch", None, self.es_src_dir).fetch(revision="current")
def prepare(self):
if self.builder:
self.builder.build(["./gradlew :plugins:{}:assemble".format(self.plugin.name)])
def add(self, binaries):
binaries[self.plugin.name] = self.resolve_binary()
def resolve_binary(self):
try:
name = glob.glob("%s/plugins/%s/build/distributions/*.zip" % (self.es_src_dir, self.plugin.name))[0]
return "file://%s" % name
except IndexError:
raise SystemSetupError("Couldn't find a plugin zip file for [%s]. Please run Rally with the pipeline 'from-sources'." %
self.plugin.name)
class ElasticsearchDistributionSupplier:
def __init__(self, repo, version, distributions_root):
self.repo = repo
self.version = version
self.distributions_root = distributions_root
# will be defined in the prepare phase
self.distribution_path = None
self.logger = logging.getLogger(__name__)
def fetch(self):
io.ensure_dir(self.distributions_root)
download_url = net.add_url_param_elastic_no_kpi(self.repo.download_url)
distribution_path = os.path.join(self.distributions_root, self.repo.file_name)
self.logger.info("Resolved download URL [%s] for version [%s]", download_url, self.version)
if not os.path.isfile(distribution_path) or not self.repo.cache:
try:
self.logger.info("Starting download of Elasticsearch [%s]", self.version)
progress = net.Progress("[INFO] Downloading Elasticsearch %s" % self.version)
net.download(download_url, distribution_path, progress_indicator=progress)
progress.finish()
self.logger.info("Successfully downloaded Elasticsearch [%s].", self.version)
except urllib.error.HTTPError:
self.logger.exception("Cannot download Elasticsearch distribution for version [%s] from [%s].", self.version, download_url)
raise exceptions.SystemSetupError("Cannot download Elasticsearch distribution from [%s]. Please check that the specified "
"version [%s] is correct." % (download_url, self.version))
else:
self.logger.info("Skipping download for version [%s]. Found an existing binary at [%s].", self.version, distribution_path)
self.distribution_path = distribution_path
def prepare(self):
pass
def add(self, binaries):
binaries["elasticsearch"] = self.distribution_path
class PluginDistributionSupplier:
def __init__(self, repo, plugin):
self.repo = repo
self.plugin = plugin
def fetch(self):
pass
def prepare(self):
pass
def add(self, binaries):
# if we have multiple plugin configurations for a plugin we will override entries here but as this is always the same
# key-value pair this is ok.
plugin_url = self.repo.plugin_download_url(self.plugin.name)
if plugin_url:
binaries[self.plugin.name] = plugin_url
def _config_value(src_config, key):
try:
return src_config[key]
except KeyError:
raise exceptions.SystemSetupError("Mandatory config key [%s] is undefined. Please add it in the [source] section of the "
"config file." % key)
def _extract_revisions(revision):
revisions = revision.split(",") if revision else []
if len(revisions) == 1:
r = revisions[0]
if r.startswith("elasticsearch:"):
r = r[len("elasticsearch:"):]
# may as well be just a single plugin
m = re.match(REVISION_PATTERN, r)
if m:
return {
m.group(1): m.group(2)
}
else:
return {
"elasticsearch": r,
# use a catch-all value
"all": r
}
else:
results = {}
for r in revisions:
m = re.match(REVISION_PATTERN, r)
if m:
results[m.group(1)] = m.group(2)
else:
raise exceptions.SystemSetupError("Revision [%s] does not match expected format [name:revision]." % r)
return results
class SourceRepository:
"""
Supplier fetches the benchmark candidate source tree from the remote repository.
"""
def __init__(self, name, remote_url, src_dir):
self.name = name
self.remote_url = remote_url
self.src_dir = src_dir
self.logger = logging.getLogger(__name__)
def fetch(self, revision):
# if and only if we want to benchmark the current revision, Rally may skip repo initialization (if it is already present)
self._try_init(may_skip_init=revision == "current")
return self._update(revision)
def has_remote(self):
return self.remote_url is not None
def _try_init(self, may_skip_init=False):
if not git.is_working_copy(self.src_dir):
if self.has_remote():
self.logger.info("Downloading sources for %s from %s to %s.", self.name, self.remote_url, self.src_dir)
git.clone(self.src_dir, self.remote_url)
elif os.path.isdir(self.src_dir) and may_skip_init:
self.logger.info("Skipping repository initialization for %s.", self.name)
else:
exceptions.SystemSetupError("A remote repository URL is mandatory for %s" % self.name)
def _update(self, revision):
if self.has_remote() and revision == "latest":
self.logger.info("Fetching latest sources for %s from origin.", self.name)
git.pull(self.src_dir)
elif revision == "current":
self.logger.info("Skip fetching sources for %s.", self.name)
elif self.has_remote() and revision.startswith("@"):
# convert timestamp annotated for Rally to something git understands -> we strip leading and trailing " and the @.
git_ts_revision = revision[1:]
self.logger.info("Fetching from remote and checking out revision with timestamp [%s] for %s.", git_ts_revision, self.name)
git.pull_ts(self.src_dir, git_ts_revision)
elif self.has_remote(): # assume a git commit hash
self.logger.info("Fetching from remote and checking out revision [%s] for %s.", revision, self.name)
git.pull_revision(self.src_dir, revision)
else:
self.logger.info("Checking out local revision [%s] for %s.", revision, self.name)
git.checkout(self.src_dir, revision)
if git.is_working_copy(self.src_dir):
git_revision = git.head_revision(self.src_dir)
self.logger.info("User-specified revision [%s] for [%s] results in git revision [%s]", revision, self.name, git_revision)
return git_revision
else:
self.logger.info("Skipping git revision resolution for %s (%s is not a git repository).", self.name, self.src_dir)
return None
@classmethod
def is_commit_hash(cls, revision):
return revision != "latest" and revision != "current" and not revision.startswith("@")
class Builder:
"""
A builder is responsible for creating an installable binary from the source files.
It is not intended to be used directly but should be triggered by its mechanic.
"""
def __init__(self, src_dir, build_jdk=None, log_dir=None):
self.src_dir = src_dir
self.build_jdk = build_jdk
self._java_home = None
self.log_dir = log_dir
self.logger = logging.getLogger(__name__)
@property
def java_home(self):
if not self._java_home:
_, self._java_home = jvm.resolve_path(self.build_jdk)
return self._java_home
def build(self, commands, override_src_dir=None):
for command in commands:
self.run(command, override_src_dir)
def run(self, command, override_src_dir=None):
src_dir = self.src_dir if override_src_dir is None else override_src_dir
io.ensure_dir(self.log_dir)
log_file = os.path.join(self.log_dir, "build.log")
# we capture all output to a dedicated build log file
build_cmd = "export JAVA_HOME={}; cd {}; {} > {} 2>&1".format(self.java_home, src_dir, command, log_file)
self.logger.info("Running build command [%s]", build_cmd)
if process.run_subprocess(build_cmd):
msg = "Executing '{}' failed. The last 20 lines in the build log file are:\n".format(command)
msg += "=========================================================================================================\n"
with open(log_file, "r", encoding="utf-8") as f:
msg += "\t"
msg += "\t".join(f.readlines()[-20:])
msg += "=========================================================================================================\n"
msg += "The full build log is available at [{}].".format(log_file)
raise BuildError(msg)
class DistributionRepository:
def __init__(self, name, distribution_config, template_renderer):
self.name = name
self.cfg = distribution_config
self.runtime_jdk_bundled = convert.to_bool(self.cfg.get("runtime.jdk.bundled", False))
self.template_renderer = template_renderer
@property
def download_url(self):
# team repo
if self.runtime_jdk_bundled:
default_key = "jdk.bundled.{}_url".format(self.name)
else:
default_key = "jdk.unbundled.{}_url".format(self.name)
# rally.ini
override_key = "{}.url".format(self.name)
return self._url_for(override_key, default_key)
@property
def file_name(self):
url = self.download_url
return url[url.rfind("/") + 1:]
def plugin_download_url(self, plugin_name):
# team repo
default_key = "plugin_{}_{}_url".format(plugin_name, self.name)
# rally.ini
override_key = "plugin.{}.{}.url".format(plugin_name, self.name)
return self._url_for(override_key, default_key, mandatory=False)
def _url_for(self, user_defined_key, default_key, mandatory=True):
try:
if user_defined_key in self.cfg:
url_template = self.cfg[user_defined_key]
else:
url_template = self.cfg[default_key]
except KeyError:
if mandatory:
raise exceptions.SystemSetupError("Neither config key [{}] nor [{}] is defined.".format(user_defined_key, default_key))
else:
return None
return self.template_renderer.render(url_template)
@property
def cache(self):
k = "{}.cache".format(self.name)
try:
raw_value = self.cfg[k]
except KeyError:
raise exceptions.SystemSetupError("Mandatory config key [%s] is undefined." % k)
try:
return convert.to_bool(raw_value)
except ValueError:
raise exceptions.SystemSetupError("Value [%s] for config key [%s] is not a valid boolean value." % (raw_value, k))