forked from scylladb/scylla-cluster-tests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sct.py
executable file
·1881 lines (1617 loc) · 84.3 KB
/
sct.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 python3
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright (c) 2021 ScyllaDB
# pylint: disable=too-many-lines
from collections import defaultdict
from datetime import datetime, timezone, timedelta
import os
import re
import sys
import unittest
import logging
import time
import subprocess
import traceback
import uuid
import pprint
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from functools import partial, reduce
from typing import List
from uuid import UUID
import pytest
import click
import yaml
from prettytable import PrettyTable
from argus.client.sct.types import LogLink
from argus.client.base import ArgusClientError
from argus.common.enums import TestStatus
import sct_ssh
import sct_scan_issues
from sdcm.keystore import KeyStore
from sdcm.localhost import LocalHost
from sdcm.provision import AzureProvisioner
from sdcm.provision.provisioner import VmInstance
from sdcm.remote import LOCALRUNNER
from sdcm.nemesis import SisyphusMonkey
from sdcm.results_analyze import PerformanceResultsAnalyzer, BaseResultsAnalyzer
from sdcm.sct_config import SCTConfiguration
from sdcm.sct_provision.common.layout import SCTProvisionLayout, create_sct_configuration
from sdcm.sct_provision.instances_provider import provision_sct_resources
from sdcm.sct_runner import AwsSctRunner, GceSctRunner, AzureSctRunner, get_sct_runner, clean_sct_runners, \
update_sct_runner_tags, list_sct_runners
from sdcm.utils.ci_tools import get_job_name, get_job_url
from sdcm.utils.git import get_git_commit_id, get_git_status_info
from sdcm.utils.argus import argus_offline_collect_events, get_argus_client
from sdcm.utils.aws_kms import AwsKms
from sdcm.utils.azure_region import AzureRegion
from sdcm.utils.cloud_monitor import cloud_report, cloud_qa_report
from sdcm.utils.cloud_monitor.cloud_monitor import cloud_non_qa_report
from sdcm.utils.common import (
S3Storage,
aws_tags_to_dict,
create_pretty_table,
format_timestamp,
get_ami_images,
get_ami_images_versioned,
get_gce_images,
get_gce_images_versioned,
gce_meta_to_dict,
get_builder_by_test_id,
get_testrun_dir,
list_clusters_eks,
list_clusters_gke,
list_elastic_ips_aws,
list_test_security_groups,
list_load_balancers_aws,
list_cloudformation_stacks_aws,
list_instances_aws,
list_placement_groups_aws,
list_instances_gce,
list_logs_by_test_id,
list_resources_docker,
list_parallel_timelines_report_urls,
search_test_id_in_latest,
get_latest_scylla_release,
)
from sdcm.utils.resources_cleanup import (
clean_cloud_resources,
clean_resources_according_post_behavior,
)
from sdcm.utils.nemesis import NemesisJobGenerator
from sdcm.utils.net import get_sct_runner_ip
from sdcm.utils.jepsen import JepsenResults
from sdcm.utils.docker_utils import docker_hub_login
from sdcm.monitorstack import (restore_monitoring_stack, get_monitoring_stack_services,
kill_running_monitoring_stack_services)
from sdcm.utils.log import setup_stdout_logger, disable_loggers_during_startup
from sdcm.utils.aws_region import AwsRegion
from sdcm.utils.aws_builder import AwsCiBuilder, AwsBuilder
from sdcm.utils.gce_region import GceRegion
from sdcm.utils.gce_builder import GceBuilder
from sdcm.utils.aws_peering import AwsVpcPeering
from sdcm.utils.get_username import get_username
from sdcm.utils.sct_cmd_helpers import add_file_logger, CloudRegion, get_test_config, get_all_regions
from sdcm.send_email import get_running_instances_for_email_report, read_email_data_from_file, build_reporter, \
send_perf_email
from sdcm.parallel_timeline_report.generate_pt_report import ParallelTimelinesReportGenerator
from sdcm.utils.aws_utils import AwsArchType, is_using_aws_mock
from sdcm.utils.aws_okta import try_auth_with_okta
from sdcm.utils.gce_utils import SUPPORTED_PROJECTS, gce_public_addresses
from sdcm.utils.context_managers import environment
from sdcm.cluster_k8s import mini_k8s
from sdcm.utils.es_index import create_index, get_mapping
from sdcm.utils.version_utils import get_s3_scylla_repos_mapping
import sdcm.provision.azure.utils as azure_utils
from utils.build_system.create_test_release_jobs import JenkinsPipelines # pylint: disable=no-name-in-module,import-error
from utils.get_supported_scylla_base_versions import UpgradeBaseVersion # pylint: disable=no-name-in-module,import-error
from utils.mocks.aws_mock import AwsMock # pylint: disable=no-name-in-module,import-error
SUPPORTED_CLOUDS = ("aws", "gce", "azure",)
DEFAULT_CLOUD = SUPPORTED_CLOUDS[0]
SCT_RUNNER_HOST = get_sct_runner_ip()
LOGGER = setup_stdout_logger()
def sct_option(name, sct_name, **kwargs):
sct_opt = SCTConfiguration.get_config_option(sct_name)
multimple_use = kwargs.pop('multiple', False)
sct_opt.update(kwargs)
return click.option(name, type=sct_opt['type'], help=sct_opt['help'], multiple=multimple_use)
def install_callback(ctx, _, value):
if not value or ctx.resilient_parsing:
return value
LOGGER.info("install-bash-completion current path: %s", os.getcwd())
shell, path = "bash", Path.home() / '.bash_completion'
path.write_text((Path(__file__).parent / 'utils' / '.bash_completion').read_text())
click.echo('%s completion installed in %s' % (shell, path))
return sys.exit(0)
def install_package_from_dir(ctx, _, directories):
if directories or not ctx.resilient_parsing:
for directory in directories:
subprocess.check_call(["sudo", sys.executable, "-m", "pip", "install", directory])
return directories
def cloud_provider_option(function=None, default: str | None = DEFAULT_CLOUD,
required: bool = True, help: str = "Cloud provider"): # pylint:disable=redefined-builtin
def actual_decorator(func):
return click.option(
"-c", "--cloud-provider",
required=required,
type=click.Choice(choices=SUPPORTED_CLOUDS, case_sensitive=False),
default=default,
is_eager=True,
help=help
)(func)
if function:
return actual_decorator(function)
return actual_decorator
class SctLoader(unittest.TestLoader):
def getTestCaseNames(self, testCaseClass):
test_cases = super().getTestCaseNames(testCaseClass)
num_of_cases = len(test_cases)
assert num_of_cases < 2, f"SCT expect only one test case to be selected, found {num_of_cases}:" \
f"\n{pprint.pformat(test_cases)}"
return test_cases
@click.group()
@click.option("--install-bash-completion",
is_flag=True,
callback=install_callback,
expose_value=False,
help="Install completion for the current shell. Make sure to have psutil installed.")
@click.option("--install-package-from-directory",
callback=install_package_from_dir,
multiple=True,
envvar="PACKAGES_PATHS",
type=click.Path(),
expose_value=False,
help="Install paths for extra python packages to install, scylla-cluster-plugins for example")
def cli():
disable_loggers_during_startup()
try_auth_with_okta()
if not is_using_aws_mock():
key_store = KeyStore()
# TODO: still leaving old keys, until we'll rebuild runner images - and reconfigure jenkins
key_store.sync(keys=['scylla-qa-ec2', 'scylla-test', 'scylla_test_id_ed25519'],
local_path=Path('~/.ssh/').expanduser(), permissions=0o0600)
docker_hub_login(remoter=LOCALRUNNER)
@cli.command('provision-resources', help="Provision resources for the test")
@click.option('-b', '--backend', type=click.Choice(SCTConfiguration.available_backends), help="Backend to use")
@click.option('-t', '--test-name', type=str, help="Test name")
@click.option('-c', '--config', multiple=True, type=click.Path(exists=True), help="Test config .yaml to use, can have multiple of those")
def provision_resources(backend, test_name: str, config: str):
if config:
os.environ['SCT_CONFIG_FILES'] = str(list(config))
if backend:
os.environ['SCT_CLUSTER_BACKEND'] = backend
add_file_logger()
params = create_sct_configuration(test_name=test_name)
test_config = get_test_config()
test_id = test_config.test_id()
if not test_id or test_id == "None":
raise ValueError("No test_id was provided. Aborting provisioning.")
localhost = LocalHost(user_prefix=params.get("user_prefix"), test_id=test_config.test_id())
if params.get("logs_transport") == 'syslog-ng':
click.echo("Provision syslog-ng logging service")
test_config.configure_syslogng(localhost)
else:
click.echo("No need provision logging service")
click.echo(f"Provision {backend} cloud resources")
if backend == "aws":
layout = SCTProvisionLayout(params=params)
layout.provision()
elif backend == "azure":
provision_sct_resources(params=params, test_config=test_config)
else:
raise ValueError(f"backend {backend} is not supported")
@cli.command("clean-aws-kms-aliases", help="clean AWS KMS old aliases")
@click.option("-r", "--regions", type=CloudRegion(cloud_provider="aws"), multiple=True,
help="List of regions to cover")
@click.option("--time-delta-h", type=int, required=False,
help="Time delta in hours. Used to detect 'old' aliases.")
@click.option("--dry-run", is_flag=True, default=False,
help="Only show result of search not deleting aliases")
@click.pass_context
def clean_aws_kms_aliases(ctx, regions, time_delta_h, dry_run):
"""Clean AWS KMS old aliases."""
add_file_logger()
regions = regions or SCTConfiguration.aws_supported_regions
aws_kms, kwargs = AwsKms(region_names=regions), {"dry_run": dry_run}
if time_delta_h:
kwargs["time_delta_h"] = time_delta_h
aws_kms.cleanup_old_aliases(**kwargs)
@cli.command('clean-resources', help='clean tagged instances in both clouds (AWS/GCE)')
@click.option('--post-behavior', is_flag=True, default=False, help="clean all resources according to post behavior")
@click.option('--user', type=str, help='user name to filter instances by')
@sct_option('--test-id', 'test_id', help='test id to filter by. Could be used multiple times', multiple=True)
@click.option('--logdir', type=str, help='directory with test run')
@click.option('--dry-run', is_flag=True, default=False, help='dry run')
@click.option('-b', '--backend', type=click.Choice(SCTConfiguration.available_backends), help="Backend to use")
@click.pass_context
def clean_resources(ctx, post_behavior, user, test_id, logdir, dry_run, backend): # pylint: disable=too-many-arguments,too-many-branches
"""Clean cloud resources.
There are different options how to run clean up:
- To clean resources for the latest run according to post behavior
$ hydra clean-resources --post-behavior
- The same as above but with altered logdir
$ hydra clean-resources --post-behavior --logdir /path/to/logdir
- To clean resources for some Test ID according to post behavior (test run status extracted from logdir)
$ hydra clean-resources --post-behavior --test-id TESTID
- The same as above but with altered logdir
$ hydra clean-resources --post-behavior --test-id TESTID --logdir /path/to/logdir
- To clean resources for the latest run ignoring post behavior
$ hydra clean-resources
- The same as above but with altered logdir
$ hydra clean-resources --logdir /path/to/logdir
- To clean all resources belong to some Test ID:
$ hydra clean-resources --test-id TESTID
- To clean all resources belong to some user:
$ hydra clean-resources --user vasya.pupkin
Also you can add --dry-run option to see what should be cleaned.
"""
add_file_logger()
user_param = {"RunByUser": user} if user else {}
if not post_behavior and user and not test_id and not logdir:
click.echo(f"Clean all resources belong to user `{user}'")
user_param["CreatedBy"] = "SCT"
params = (user_param, )
else:
if not logdir and (post_behavior or not test_id):
logdir = get_test_config().base_logdir()
if not test_id and (latest_test_id := search_test_id_in_latest(logdir)):
click.echo(f"Latest TestId in {logdir} is {latest_test_id}")
test_id = (latest_test_id, )
if not test_id:
click.echo(clean_resources.get_help(ctx))
return
if post_behavior:
click.echo(f"Clean resources according to post behavior for following Test IDs: {test_id}")
else:
click.echo(f"Clean all resources for following Test IDs: {test_id}")
params = ({"TestId": tid, **user_param} for tid in test_id)
if backend is None:
if os.environ.get('SCT_CLUSTER_BACKEND', None) is None:
os.environ['SCT_CLUSTER_BACKEND'] = 'aws'
else:
os.environ['SCT_CLUSTER_BACKEND'] = backend
config = SCTConfiguration()
if post_behavior:
click.echo(f"Use {logdir} as a logdir")
clean_func = partial(clean_resources_according_post_behavior, config=config, logdir=logdir)
else:
clean_func = partial(clean_cloud_resources, config=config)
if dry_run:
click.echo("Make a dry-run")
for param in params:
clean_func(param, dry_run=dry_run)
click.echo(f"Cleanup for the {param} resources has been finished")
@cli.command('list-resources', help='list tagged instances in cloud (AWS/GCE/Azure)')
@click.option('--user', type=str, help='user name to filter instances by')
@click.option('--get-all', is_flag=True, default=False, help='All resources')
@click.option('--get-all-running', is_flag=True, default=False, help='All running resources')
@sct_option('--test-id', 'test_id', help='test id to filter by')
@click.option('--verbose', is_flag=True, default=False, help='if enable, will log progress')
@click.pass_context
def list_resources(ctx, user, test_id, get_all, get_all_running, verbose): # noqa: PLR0912, PLR0914, PLR0915
# pylint: disable=too-many-locals,too-many-arguments,too-many-branches,too-many-statements
add_file_logger()
params = {}
if user:
params['RunByUser'] = user
if test_id:
params['TestId'] = test_id
if all([not get_all, not get_all_running, not user, not test_id]):
click.echo(list_resources.get_help(ctx))
if get_all_running:
table_header = ["Name", "Region-AZ", "PublicIP", "TestId", "RunByUser", "LaunchTime"]
else:
table_header = ["Name", "Region-AZ", "State", "TestId", "RunByUser", "LaunchTime"]
click.secho("Checking AWS EC2...", fg='green')
aws_instances = list_instances_aws(tags_dict=params, running=get_all_running, verbose=verbose)
if aws_instances:
aws_table = PrettyTable(table_header)
aws_table.align = "l"
aws_table.sortby = 'LaunchTime'
for instance in aws_instances:
tags = aws_tags_to_dict(instance.get('Tags'))
name = tags.get("Name", "N/A")
test_id = tags.get("TestId", "N/A")
run_by_user = tags.get("RunByUser", "N/A")
aws_table.add_row([
name,
instance['Placement']['AvailabilityZone'],
instance.get('PublicIpAddress', 'N/A') if get_all_running else instance['State']['Name'],
test_id,
run_by_user,
instance['LaunchTime'].ctime()])
click.echo(aws_table.get_string(title="Instances used on AWS"))
else:
click.secho("Nothing found for selected filters in AWS!", fg="yellow")
click.secho("Checking AWS Elastic IPs...", fg='green')
elastic_ips_aws = list_elastic_ips_aws(tags_dict=params, verbose=verbose)
if elastic_ips_aws:
aws_table = PrettyTable(["AllocationId", "PublicIP", "TestId", "RunByUser", "InstanceId (attached to)"])
aws_table.align = "l"
aws_table.sortby = 'AllocationId'
for eip in elastic_ips_aws:
tags = aws_tags_to_dict(eip.get('Tags'))
test_id = tags.get("TestId", "N/A")
run_by_user = tags.get("RunByUser", "N/A")
aws_table.add_row([
eip['AllocationId'],
eip['PublicIp'],
test_id,
run_by_user,
eip.get('InstanceId', 'N/A')])
click.echo(aws_table.get_string(title="EIPs used on AWS"))
else:
click.secho("No elastic ips found for selected filters in AWS!", fg="yellow")
click.secho("Checking AWS Security Groups...", fg='green')
security_groups = list_test_security_groups(tags_dict=params, verbose=verbose)
if security_groups:
aws_table = PrettyTable(["Name", "Id", "TestId", "RunByUser"])
aws_table.align = "l"
aws_table.sortby = 'Id'
for group in security_groups:
tags = aws_tags_to_dict(group.get('Tags'))
test_id = tags.get("TestId", "N/A")
run_by_user = tags.get("RunByUser", "N/A")
name = tags.get("Name", "N/A")
aws_table.add_row([
name,
group['GroupId'],
test_id,
run_by_user])
click.echo(aws_table.get_string(title="SGs used on AWS"))
else:
click.secho("No security groups found for selected filters in AWS!", fg="yellow")
click.secho("Checking AWS Placement Groups...", fg='green')
placement_groups = list_placement_groups_aws(tags_dict=params, available=get_all_running, verbose=verbose)
if placement_groups:
aws_table = PrettyTable(["Name", "Id", "TestId", "RunByUser"])
aws_table.align = "l"
aws_table.sortby = 'Id'
for group in placement_groups:
tags = aws_tags_to_dict(group.get('Tags'))
test_id = tags.get("TestId", "N/A")
run_by_user = tags.get("RunByUser", "N/A")
name = tags.get("Name", "N/A")
aws_table.add_row([
name,
group['GroupId'],
test_id,
run_by_user])
click.echo(aws_table.get_string(title="SGs used on AWS"))
else:
click.secho("No placement groups found for selected filters in AWS!", fg="yellow")
click.secho("Checking AWS Load Balancers...", fg='green')
load_balancers = list_load_balancers_aws(tags_dict=params, verbose=verbose)
if load_balancers:
aws_table = PrettyTable(["Name", "Region", "TestId", "RunByUser"])
aws_table.align = "l"
aws_table.sortby = 'Name'
for elb in load_balancers:
tags = aws_tags_to_dict(elb.get('Tags'))
test_id = tags.get("TestId", "N/A")
run_by_user = tags.get("RunByUser", "N/A")
_, _, _, region, _, name = elb['ResourceARN'].split(':')
aws_table.add_row([
name,
region,
test_id,
run_by_user,
])
click.echo(aws_table.get_string(title="ELBs used on AWS"))
else:
click.secho("No load balancers found for selected filters in AWS!", fg="yellow")
click.secho("Checking AWS Cloudformation Stacks ...", fg='green')
cfn_stacks = list_cloudformation_stacks_aws(tags_dict=params, verbose=verbose)
if cfn_stacks:
aws_table = PrettyTable(["Name", "Region", "TestId", "RunByUser"])
aws_table.align = "l"
aws_table.sortby = 'Name'
for stack in cfn_stacks:
tags = aws_tags_to_dict(stack.get('Tags'))
test_id = tags.get("TestId", "N/A")
run_by_user = tags.get("RunByUser", "N/A")
_, _, _, region, _, name = stack['ResourceARN'].split(':')
aws_table.add_row([
name,
region,
test_id,
run_by_user,
])
click.echo(aws_table.get_string(title="Cloudformation Stacks used on AWS"))
else:
click.secho("No Cloudformation stacks found for selected filters in AWS!", fg="yellow")
click.secho("Checking GKE...", fg='green')
gke_clusters = list_clusters_gke(tags_dict=params, verbose=verbose)
if gke_clusters:
gke_table = PrettyTable(["Name", "Region-AZ", "TestId", "RunByUser", "CreateTime"])
gke_table.align = "l"
gke_table.sortby = 'CreateTime'
for cluster in gke_clusters:
tags = gce_meta_to_dict(cluster.metadata)
gke_table.add_row([cluster.name,
cluster.zone,
tags.get('TestId', 'N/A') if tags else "N/A",
tags.get('RunByUser', 'N/A') if tags else "N/A",
cluster.cluster_info['createTime'],
])
click.echo(gke_table.get_string(title="GKE clusters"))
else:
click.secho("Nothing found for selected filters in GKE!", fg="yellow")
for project in SUPPORTED_PROJECTS:
with environment(SCT_GCE_PROJECT=project):
click.secho(f"Checking GCE ({project})...", fg='green')
gce_instances = list_instances_gce(tags_dict=params, running=get_all_running, verbose=verbose)
if gce_instances:
gce_table = PrettyTable(table_header)
gce_table.align = "l"
gce_table.sortby = 'LaunchTime'
for instance in gce_instances:
tags = gce_meta_to_dict(instance.metadata)
public_ips = gce_public_addresses(instance)
public_ips = ", ".join(public_ips) if None not in public_ips else "N/A"
gce_table.add_row([instance.name,
instance.zone.split('/')[-1],
public_ips if get_all_running else instance.status,
tags.get('TestId', 'N/A') if tags else "N/A",
tags.get('RunByUser', 'N/A') if tags else "N/A",
instance.creation_timestamp,
])
click.echo(gce_table.get_string(title="Resources used on GCE"))
else:
click.secho("Nothing found for selected filters in GCE!", fg="yellow")
click.secho("Checking EKS...", fg='green')
eks_clusters = list_clusters_eks(tags_dict=params, verbose=verbose)
if eks_clusters:
eks_table = PrettyTable(["Name", "TestId", "Region", "RunByUser", "CreateTime"])
eks_table.align = "l"
eks_table.sortby = 'CreateTime'
for cluster in eks_clusters:
tags = gce_meta_to_dict(cluster.metadata)
eks_table.add_row([cluster.name,
tags.get('TestId', 'N/A') if tags else "N/A",
cluster.region_name,
tags.get('RunByUser', 'N/A') if tags else "N/A",
cluster.create_time,
])
click.echo(eks_table.get_string(title="EKS clusters"))
else:
click.secho("Nothing found for selected filters in EKS!", fg="yellow")
click.secho("Checking Docker...", fg="green")
docker_resources = \
list_resources_docker(tags_dict=params, running=get_all_running, group_as_builder=True, verbose=verbose)
if any(docker_resources.values()):
if docker_resources.get("containers"):
docker_table = PrettyTable(["Name", "Builder", "Public IP" if get_all_running else "Status",
"TestId", "RunByUser", "Created"])
docker_table.align = "l"
docker_table.sortby = "Created"
for builder_name, docker_containers in docker_resources["containers"].items():
for container in docker_containers:
container.reload()
docker_table.add_row([
container.name,
builder_name,
container.attrs["NetworkSettings"]["IPAddress"] if get_all_running else container.status,
container.labels.get("TestId", "N/A"),
container.labels.get("RunByUser", "N/A"),
container.attrs.get("Created", "N/A"),
])
click.echo(docker_table.get_string(title="Containers used on Docker"))
if docker_resources.get("images"):
docker_table = PrettyTable(["Name", "Builder", "TestId", "RunByUser", "Created"])
docker_table.align = "l"
docker_table.sortby = "Created"
for builder_name, docker_images in docker_resources["images"].items():
for image in docker_images:
image.reload()
for tag in image.tags:
docker_table.add_row([
tag,
builder_name,
image.labels.get("TestId", "N/A"),
image.labels.get("RunByUser", "N/A"),
image.attrs.get("Created", "N/A"),
])
click.echo(docker_table.get_string(title="Images used on Docker"))
else:
click.secho("Nothing found for selected filters in Docker!", fg="yellow")
click.secho("Checking Azure instances...", fg='green')
instances: List[VmInstance] = []
for provisioner in AzureProvisioner.discover_regions(params.get("TestId", "")):
instances += provisioner.list_instances()
if user:
instances = [inst for inst in instances if inst.tags.get("RunByUser") == user]
if instances:
azure_table = PrettyTable(["Name", "Region-AZ", "PublicIP", "TestId", "RunByUser", "LaunchTime"])
azure_table.align = "l"
azure_table.sortby = 'RunByUser'
for instance in instances:
creation_time = instance.creation_time.isoformat(
sep=" ", timespec="seconds") if instance.creation_time else "N/A"
tags = instance.tags
test_id = tags.get("TestId", "N/A")
run_by_user = tags.get("RunByUser", "N/A")
azure_table.add_row([
instance.name,
instance.region,
instance.public_ip_address,
test_id,
run_by_user,
creation_time])
click.echo(azure_table.get_string(title="Instances used on Azure"))
else:
click.secho("Nothing found for selected filters in Azure!", fg="yellow")
@cli.command('list-images', help="List machine images")
@cloud_provider_option(default="aws", required=False, help="Cloud provided to query. Defaults to aws.")
@click.option('-br', '--branch',
type=str,
help="Branch to query images for. Defaults to 'master:latest' Mutually exclusive with --version.")
@click.option('-v', '--version',
type=str,
help="List images by version. Use '-v all' for all versions. "
"OSS format: <4.3> Enterprise format: <enterprise-2021.1>. Mutually exclusive with --branch.")
@click.option('-r', '--region',
type=CloudRegion(),
help="Cloud region to query images in. Defaults to eu-west-1",
default="eu-west-1")
@click.option('-a', '--arch',
type=click.Choice(AwsArchType.__args__),
default='x86_64',
help="architecture of the AMI (default: x86_64)") # pylint: disable=too-many-locals
def list_images(cloud_provider: str, branch: str, version: str, region: str, arch: AwsArchType):
add_file_logger()
version_fields = ["Backend", "Name", "ImageId", "CreationDate"]
version_fields_with_tag_name = version_fields + ["NameTag"]
# TODO: align branch and version fields once scylla-pkg#2995 is resolved
branch_specific_fields = ["BuildId", "Arch", "ScyllaVersion"]
account_field = ["OwnerId"]
branch_fields = version_fields + branch_specific_fields
branch_fields_with_tag_name = version_fields_with_tag_name + branch_specific_fields + account_field
if version and branch:
click.echo("Use --version or --branch, not both.")
return
branch = branch or "master:latest"
if version is not None:
match cloud_provider:
case "aws":
rows = get_ami_images_versioned(region_name=region, arch=arch, version=version)
click.echo(
create_pretty_table(rows=rows, field_names=version_fields_with_tag_name).get_string(
title=f"AWS Machine Images by Version in region {region}")
)
case "gce":
if arch:
# TODO: align branch and version fields once scylla-pkg#2995 is resolved
click.echo("WARNING:--arch option not implemented currently for GCE machine images.")
rows = get_gce_images_versioned(version=version)
click.echo(
create_pretty_table(rows=rows, field_names=version_fields).get_string(
title="GCE Machine Images by version")
)
case "azure":
if arch:
click.echo("WARNING:--arch option not implemented currently for Azure machine images.")
azure_images = azure_utils.get_released_scylla_images(scylla_version=version, region_name=region)
rows = []
for image in azure_images:
rows.append(['Azure', image.name, image.unique_id, 'N/A'])
click.echo(
create_pretty_table(rows=rows, field_names=version_fields).get_string(
title="Azure Machine Images by version")
)
case _:
click.echo(f"Cloud provider {cloud_provider} is not supported")
elif branch:
if ":" not in branch:
branch += ":all"
match cloud_provider:
case "aws":
region = region or "eu-west-1"
ami_images = get_ami_images(branch=branch, region=region, arch=arch)
click.echo(
create_pretty_table(rows=ami_images, field_names=branch_fields_with_tag_name).get_string(
title=f"AMI Machine Images for {branch} in region {region}"
)
)
case "gce":
gce_images = get_gce_images(branch=branch, arch=arch)
click.echo(
create_pretty_table(rows=gce_images, field_names=branch_fields).get_string(
title=f"GCE Machine Images for {branch}"
)
)
case "azure":
if arch:
click.echo("WARNING:--arch option not implemented currently for Azure machine images.")
azure_images = azure_utils.get_scylla_images(scylla_version=branch, region_name=region)
rows = []
for image in azure_images:
rows.append(['Azure', image.name, image.id, 'N/A'])
click.echo(
create_pretty_table(rows=rows, field_names=version_fields).get_string(
title="Azure Machine Images by version")
)
case _:
click.echo(f"Cloud provider {cloud_provider} is not supported")
@cli.command('list-repos', help='List repos url of Scylla formal versions')
@click.option('-d', '--dist-type', type=click.Choice(['centos', 'ubuntu', 'debian']),
default='centos', help='Distribution type')
@click.option('-v', '--dist-version', type=click.Choice(['xenial', 'trusty', 'bionic', 'focal', # Ubuntu
'jessie', 'stretch', 'buster', 'bullseye']), # Debian
default=None, help='deb style versions')
def list_repos(dist_type, dist_version):
add_file_logger()
if not dist_type == 'centos' and dist_version is None:
click.secho("when passing --dist-type=debian/ubuntu need to pass --dist-version as well", fg='red')
sys.exit(1)
repo_maps = get_s3_scylla_repos_mapping(dist_type, dist_version)
tbl = PrettyTable(["Version Family", "Repo Url"])
tbl.align = "l"
for version_prefix, repo_url in repo_maps.items():
tbl.add_row([version_prefix, repo_url])
click.echo(tbl.get_string(title="Scylla Repos"))
@cli.command('get-scylla-base-versions', help='Get Scylla base versions of upgrade')
@click.option('-s', '--scylla-version', type=str,
help='Scylla version, eg: 4.5, 2021.1')
@click.option('-r', '--scylla-repo', type=str,
help='Scylla repo')
@click.option('-d', '--linux-distro', type=str, help='Linux Distribution type')
@click.option('-o', '--only-print-versions', type=bool, default=False, required=False, help='')
@click.option('-b', '--backend', type=click.Choice(SCTConfiguration.available_backends), help="Backend to use")
def get_scylla_base_versions(scylla_version, scylla_repo, linux_distro, only_print_versions, backend): # pylint: disable=too-many-locals
"""
Upgrade test try to upgrade from multiple supported base versions, this command is used to
get the base versions according to the scylla repo and distro type, then we don't need to hardcode
the base version for each branch.
"""
add_file_logger()
with Path("defaults/test_default.yaml").open(mode="r", encoding="utf-8") as test_defaults_yaml:
test_defaults = yaml.safe_load(test_defaults_yaml)
if not linux_distro or linux_distro == "null":
linux_distro = test_defaults.get("scylla_linux_distro")
version_detector = UpgradeBaseVersion(scylla_repo, linux_distro, scylla_version)
if not version_detector.dist_type == 'centos' and version_detector.dist_version is None:
click.secho("when passing --dist-type=debian/ubuntu need to pass --dist-version as well", fg='red')
sys.exit(1)
# We can't detect the support versions for this distro, which shares the repo with others, eg: centos8
# so we need to assign the start support versions for it.
version_detector.set_start_support_version(backend)
supported_versions, version_list = version_detector.get_version_list()
click.echo(f'Supported Versions: {supported_versions}')
if only_print_versions:
click.echo(f"Base Versions: {' '.join(version_list)}")
return
tbl = PrettyTable(["Version Family", "Repo Url"])
tbl.align = "l"
for version in version_list:
tbl.add_row([version, version_detector.repo_maps[version]])
click.echo(tbl.get_string(title="Base Versions"))
return
@cli.command('output-conf', help="Output test configuration readed from the file")
@click.argument('config_files', type=str, default='')
@click.option('-b', '--backend', type=click.Choice(SCTConfiguration.available_backends))
def output_conf(config_files, backend):
add_file_logger()
if backend:
os.environ['SCT_CLUSTER_BACKEND'] = backend
if config_files:
os.environ['SCT_CONFIG_FILES'] = config_files
config = SCTConfiguration()
click.secho(config.dump_config(), fg='green')
sys.exit(0)
def _run_yaml_test(backend, full_path, env):
output = []
error = False
output.append(f'---- linting: {full_path} -----')
while os.environ:
os.environ.popitem()
for key, value in env.items():
os.environ[key] = value
os.environ['SCT_CLUSTER_BACKEND'] = backend
os.environ['SCT_CONFIG_FILES'] = full_path
logging.getLogger().handlers = []
logging.getLogger().disabled = True
try:
config = SCTConfiguration()
config.verify_configuration()
config.check_required_files()
except Exception as exc: # pylint: disable=broad-except # noqa: BLE001
output.append(''.join(traceback.format_exception(type(exc), exc, exc.__traceback__)))
error = True
return error, output
@cli.command(help="Test yaml in test-cases directory")
@click.option('-b', '--backend', type=click.Choice(SCTConfiguration.available_backends), default='aws')
@click.option('-i', '--include', type=str, default='')
@click.option('-e', '--exclude', type=str, default='')
def lint_yamls(backend, exclude: str, include: str): # pylint: disable=too-many-locals,too-many-branches
if not include:
raise ValueError('You did not provide include filters')
exclude_filters = []
for flt in exclude.split(','):
if not flt:
continue
try:
exclude_filters.append(re.compile(flt))
except Exception as exc: # pylint: disable=broad-except # noqa: BLE001
raise ValueError(f'Exclude filter "{flt}" compiling failed with: {exc}') from exc
include_filters = []
for flt in include.split(','):
if not flt:
continue
try:
include_filters.append(re.compile(flt))
except Exception as exc: # pylint: disable=broad-except # noqa: BLE001
raise ValueError(f'Include filter "{flt}" compiling failed with: {exc}') from exc
original_env = {**os.environ}
process_pool = ProcessPoolExecutor(max_workers=5) # pylint: disable=consider-using-with
features = []
for root, _, files in os.walk('./test-cases'):
for file in files:
full_path = os.path.join(root, file)
if not any((flt.search(file) or flt.search(full_path) for flt in include_filters)):
continue
if any((flt.search(file) or flt.search(full_path) for flt in exclude_filters)):
continue
features.append(process_pool.submit(_run_yaml_test, backend, full_path, original_env))
failed = False
for pp_feature in features:
error, pp_output = pp_feature.result()
if error:
failed = True
click.secho('\n'.join(pp_output), fg='red')
else:
click.secho('\n'.join(pp_output), fg='green')
print()
sys.exit(1 if failed else 0)
@cli.command(help="Check test configuration file")
@click.argument('config_file', type=str, default='')
@click.option('-b', '--backend', type=click.Choice(SCTConfiguration.available_backends), default='aws')
def conf(config_file, backend):
add_file_logger()
if backend:
os.environ['SCT_CLUSTER_BACKEND'] = backend
if config_file:
os.environ['SCT_CONFIG_FILES'] = config_file
config = SCTConfiguration()
try:
config.verify_configuration()
config.check_required_files()
except Exception as ex: # pylint: disable=broad-except
logging.exception(str(ex))
click.secho(str(ex), fg='red')
sys.exit(1)
else:
click.secho(config.dump_config(), fg='green')
sys.exit(0)
@cli.command('conf-docs', help="Show all available configuration in yaml/markdown format")
@click.option('-o', '--output-format', type=click.Choice(["yaml", "markdown"]), default="yaml", help="type of the output")
def conf_docs(output_format):
add_file_logger()
os.environ['SCT_CLUSTER_BACKEND'] = "aws" # just to pass SCTConfiguration() verification.
config_logger = logging.getLogger('sdcm.sct_config')
config_logger.setLevel(logging.ERROR)
if output_format == 'markdown':
click.secho(SCTConfiguration().dump_help_config_markdown())
elif output_format == 'yaml':
click.secho(SCTConfiguration().dump_help_config_yaml())
@cli.command('update-conf-docs', help="Update the docs configuration markdown")
def update_conf_docs():
add_file_logger()
os.environ['SCT_CLUSTER_BACKEND'] = "aws" # just to pass SCTConfiguration() verification.
config_logger = logging.getLogger('sdcm.sct_config')
config_logger.setLevel(logging.ERROR)
markdown_file = Path(__name__).parent / 'docs' / 'configuration_options.md'
markdown_file.write_text(SCTConfiguration().dump_help_config_markdown())
click.secho(f"docs written into {markdown_file}")
@cli.command("perf-regression-report", help="Generate and send performance regression report")
@click.option("-i", "--es-id", required=True, type=str, help="Id of the run in Elastic Search")
@click.option("-e", "--emails", required=True, type=str, help="Comma separated list of emails. Example [email protected],[email protected]")
@click.option("--es-index", default="performancestatsv2", help="Elastic Search index")
@click.option("--extra-jobs-to-compare", default=None, type=str, multiple=True, help="Extra jobs to compare")
def perf_regression_report(es_id, emails, es_index, extra_jobs_to_compare):
add_file_logger()
emails = emails.split(',')
if not emails:
LOGGER.warning("No email recipients. Email will not be sent")
sys.exit(1)
results_analyzer = PerformanceResultsAnalyzer(es_index=es_index, es_doc_type="test_stats",
email_recipients=emails, logger=LOGGER)
results_analyzer.check_regression(es_id, extra_jobs_to_compare=extra_jobs_to_compare)
logdir = Path(get_test_config().logdir())
email_results_file = logdir / "email_data.json"
test_results = read_email_data_from_file(email_results_file)
if not test_results:
LOGGER.error("Test Results file not found")
sys.exit(1)
LOGGER.info('Email will be sent to next recipients: %s', emails)
start_time = format_timestamp(time.time())
logs = list_logs_by_test_id(test_results.get('test_id', es_id.split('_')[0]))
send_perf_email(results_analyzer, test_results, logs, emails, logdir, start_time)
@click.group(help="Group of commands for investigating testrun")
def investigate():
pass
@investigate.command('show-logs', help="Show logs collected for testrun filtered by test-id")
@click.argument('test_id')
@click.option('-o', '--output-format', type=click.Choice(["table", "markdown"]), default="table", help="type of the output")
@click.option("--update-argus/--no-update-argus", type=bool, required=False, default=False, help='Update argus with links')
def show_log(test_id, output_format, update_argus: bool):
add_file_logger()
files = list_logs_by_test_id(test_id)
if output_format == 'table':
table = PrettyTable(["Date", "Log type", "Link"])
table.align = "l"
for log in files:
table.add_row([log["date"].strftime("%Y%m%d_%H%M%S"), log["type"], log["link"]])
click.echo(table.get_string(title="Log links for testrun with test id {}".format(test_id)))
elif output_format == 'markdown':
click.echo("\n## Logs\n")
for log in files:
click.echo(f'* **{log["type"]}** - {log["link"]}')
if update_argus:
try:
store_logs_in_argus(test_id=test_id, logs=reduce(lambda acc, log: acc[log["type"]].append(
log["link"]) or acc, files, defaultdict(list)), update=True)
except Exception: # pylint: disable=broad-except # noqa: BLE001
LOGGER.error("Error updating logs in argus.", exc_info=True)
@investigate.command('show-monitor', help="Run monitoring stack with saved data locally")
@click.argument('test_id')
@click.option("--cluster-name", type=str, required=False, help='Cluster name (relevant for multi-tenant test)')
@click.option("--date-time", type=str, required=False, help='Datetime of monitor-set archive is collected')
@click.option("--kill", type=bool, required=False, help='Kill and remove containers')
def show_monitor(test_id, date_time, kill, cluster_name):
add_file_logger()
click.echo('Search monitoring stack archive files for test id {} and restoring...'.format(test_id))
containers = {}