-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathutils.py
More file actions
6952 lines (5791 loc) · 229 KB
/
Copy pathutils.py
File metadata and controls
6952 lines (5791 loc) · 229 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tempfile
from datetime import datetime, timedelta
from functools import reduce
import base64
import io
import json
import logging
import os
import platform
import random
import re
import shlex
import smtplib
import socket
import string
import subprocess
import time
import traceback
from typing import Match, Iterator
import stat
import shutil
from copy import deepcopy
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import pandas as pd
from scipy.stats import tmean, scoreatpercentile
from shutil import which, move, rmtree
import pexpect
import pytest
import unicodedata
import hcl2
import requests
from requests.adapters import HTTPAdapter
from urllib3 import Retry
import yaml
import git
from bs4 import BeautifulSoup
from paramiko import SSHClient, AutoAddPolicy
from paramiko.auth_handler import AuthenticationException, SSHException
from semantic_version import Version
from tempfile import NamedTemporaryFile, mkdtemp, TemporaryDirectory
from jinja2 import FileSystemLoader, Environment
from ocs_ci.framework import config
from ocs_ci.framework import GlobalVariables as GV
from ocs_ci.ocs import constants, defaults
from ocs_ci.ocs.exceptions import (
CephHealthException,
CephHealthRecoveredException,
CephHealthNotRecoveredException,
CommandFailed,
ConfigurationError,
ResourceNotFoundError,
TagNotFoundException,
TimeoutException,
TimeoutExpiredError,
UnexpectedImage,
UnknownCloneTypeException,
UnsupportedOSType,
InteractivePromptException,
NotFoundError,
CephToolBoxNotFoundException,
NoRunningCephToolBoxException,
ClusterNotInSTSModeException,
)
from ocs_ci.utility import version as version_module
from ocs_ci.utility.flexy import load_cluster_info
from ocs_ci.utility.retry import retry
from ocs_ci.utility.jira import JiraHelper
from psutil._common import bytes2human
from ocs_ci.ocs.constants import HCI_PROVIDER_CLIENT_PLATFORMS
log = logging.getLogger(__name__)
# variables
mounting_dir = "/mnt/cephfs/"
clients = []
md5sum_list1 = []
md5sum_list2 = []
fuse_clients = []
kernel_clients = []
mon_node = ""
mon_node_ip = ""
mds_nodes = []
md5sum_file_lock = []
active_mdss = []
RC = []
failure = {}
output = []
unique_test_names = []
# function for getting the clients
def get_client_info(ceph_nodes, clients):
log.info("Getting Clients")
for node in ceph_nodes:
if node.role == "client":
clients.append(node)
# Identifying MON node
for node in ceph_nodes:
if node.role == "mon":
mon_node = node
out, err = mon_node.exec_command(cmd="sudo hostname -I")
mon_node_ip = out.read().decode().rstrip("\n")
break
for node in ceph_nodes:
if node.role == "mds":
mds_nodes.append(node)
for node in clients:
node.exec_command(cmd="sudo yum install -y attr")
fuse_clients = clients[0:2] # seperating clients for fuse and kernel
kernel_clients = clients[2:4]
return (
fuse_clients,
kernel_clients,
mon_node,
mounting_dir,
mds_nodes,
md5sum_file_lock,
mon_node_ip,
)
# function for providing authorization to the clients from MON ndoe
def auth_list(clients, mon_node):
for node in clients:
log.info("Giving required permissions for clients from MON node:")
mon_node.exec_command(
cmd="sudo ceph auth get-or-create client.%s mon 'allow *' mds 'allow *, allow rw path=/' "
"osd 'allow rw pool=cephfs_data' -o /etc/ceph/ceph.client.%s.keyring"
% (node.hostname, node.hostname)
)
out, err = mon_node.exec_command(
sudo=True, cmd="cat /etc/ceph/ceph.client.%s.keyring" % (node.hostname)
)
keyring = out.read().decode()
key_file = node.write_file(
sudo=True,
file_name="/etc/ceph/ceph.client.%s.keyring" % (node.hostname),
file_mode="w",
)
key_file.write(keyring)
key_file.flush()
node.exec_command(
cmd="sudo chmod 644 /etc/ceph/ceph.client.%s.keyring" % (node.hostname)
)
# creating mounting directory
node.exec_command(cmd="sudo mkdir %s" % (mounting_dir))
# MOunting single FS with ceph-fuse
def fuse_mount(fuse_clients, mounting_dir):
try:
for client in fuse_clients:
log.info("Creating mounting dir:")
log.info("Mounting fs with ceph-fuse on client %s:" % (client.hostname))
client.exec_command(
cmd="sudo ceph-fuse -n client.%s %s" % (client.hostname, mounting_dir)
)
out, err = client.exec_command(cmd="mount")
mount_output = out.read().decode()
mount_output.split()
log.info("Checking if fuse mount is is passed of failed:")
if "fuse" in mount_output:
log.info("ceph-fuse mounting passed")
else:
log.error("ceph-fuse mounting failed")
return md5sum_list1
except Exception as e:
log.error(e)
def kernel_mount(mounting_dir, mon_node_ip, kernel_clients):
try:
for client in kernel_clients:
out, err = client.exec_command(
cmd="sudo ceph auth get-key client.%s" % (client.hostname)
)
secret_key = out.read().decode().rstrip("\n")
mon_node_ip = mon_node_ip.replace(" ", "")
client.exec_command(
cmd="sudo mount -t ceph %s:6789:/ %s -o name=%s,secret=%s"
% (mon_node_ip, mounting_dir, client.hostname, secret_key)
)
out, err = client.exec_command(cmd="mount")
mount_output = out.read().decode()
mount_output.split()
log.info("Checking if kernel mount is is passed of failed:")
if "%s:6789:/" % (mon_node_ip) in mount_output:
log.info("kernel mount passed")
else:
log.error("kernel mount failed")
return md5sum_list2
except Exception as e:
log.error(e)
def fuse_client_io(client, mounting_dir):
try:
rand_count = random.randint(1, 5)
rand_bs = random.randint(100, 300)
log.info("Performing IOs on fuse-clients")
client.exec_command(
cmd="sudo dd if=/dev/zero of=%snewfile_%s bs=%dM count=%d"
% (mounting_dir, client.hostname, rand_bs, rand_count),
long_running=True,
)
except Exception as e:
log.error(e)
def kernel_client_io(client, mounting_dir):
try:
rand_count = random.randint(1, 6)
rand_bs = random.randint(100, 500)
log.info("Performing IOs on kernel-clients")
client.exec_command(
cmd="sudo dd if=/dev/zero of=%snewfile_%s bs=%dM count=%d"
% (mounting_dir, client.hostname, rand_bs, rand_count),
long_running=True,
)
except Exception as e:
log.error(e)
def fuse_client_md5(fuse_clients, md5sum_list1):
try:
log.info("Calculating MD5 sums of files in fuse-clients:")
for client in fuse_clients:
md5sum_list1.append(
client.exec_command(
cmd="sudo md5sum %s* | awk '{print $1}' " % (mounting_dir),
long_running=True,
)
)
except Exception as e:
log.error(e)
def kernel_client_md5(kernel_clients, md5sum_list2):
try:
log.info("Calculating MD5 sums of files in kernel-clients:")
for client in kernel_clients:
md5sum_list2.append(
client.exec_command(
cmd="sudo md5sum %s* | awk '{print $1}' " % (mounting_dir),
long_running=True,
)
)
except Exception as e:
log.error(e)
# checking file locking mechanism
def file_locking(client):
try:
to_lock_file = """
import fcntl
import subprocess
import time
try:
f = open('/mnt/cephfs/to_test_file_lock', 'w+')
fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
print "locking file:--------------------------------"
subprocess.check_output(["sudo","dd","if=/dev/zero","of=/mnt/cephfs/to_test_file_lock","bs=1M","count=2"])
except IOError as e:
print e
finally:
print "Unlocking file:------------------------------"
fcntl.lockf(f,fcntl.LOCK_UN)
"""
to_lock_code = client.write_file(
sudo=True, file_name="/home/cephuser/file_lock.py", file_mode="w"
)
to_lock_code.write(to_lock_file)
to_lock_code.flush()
out, err = client.exec_command(cmd="sudo python /home/cephuser/file_lock.py")
output = out.read().decode()
output.split()
if "Errno 11" in output:
log.info("File locking achieved, data is not corrupted")
elif "locking" in output:
log.info("File locking achieved, data is not corrupted")
else:
log.error("Data is corrupted")
out, err = client.exec_command(
cmd="sudo md5sum %sto_test_file_lock | awk '{print $1}'" % (mounting_dir)
)
md5sum_file_lock.append(out.read().decode())
except Exception as e:
log.error(e)
def activate_multiple_mdss(mds_nodes):
try:
log.info("Activating Multiple MDSs")
for node in mds_nodes:
out1, err = node.exec_command(
cmd="sudo ceph fs set cephfs allow_multimds true --yes-i-really-mean-it"
)
out2, err = node.exec_command(cmd="sudo ceph fs set cephfs max_mds 2")
break
except Exception as e:
log.error(e)
def mkdir_pinning(clients, range1, range2, dir_name, pin_val):
try:
log.info("Creating Directories and Pinning to MDS %s" % (pin_val))
for client in clients:
for num in range(range1, range2):
out, err = client.exec_command(
cmd="sudo mkdir %s%s_%d" % (mounting_dir, dir_name, num)
)
if pin_val != "":
client.exec_command(
cmd="sudo setfattr -n ceph.dir.pin -v %s %s%s_%d"
% (pin_val, mounting_dir, dir_name, num)
)
else:
print("Pin val not given")
print(out.read().decode())
print(time.time())
break
except Exception as e:
log.error(e)
def allow_dir_fragmentation(mds_nodes):
try:
log.info("Allowing directorty fragmenation for splitting")
for node in mds_nodes:
node.exec_command(cmd="sudo ceph fs set cephfs allow_dirfrags 1")
break
except Exception as e:
log.error(e)
def mds_fail_over(mds_nodes):
try:
rand = random.randint(0, 1)
for node in mds_nodes:
log.info("Failing MDS %d" % (rand))
node.exec_command(cmd="sudo ceph mds fail %d" % (rand))
break
except Exception as e:
log.error(e)
def pinned_dir_io(clients, mds_fail_over, num_of_files, range1, range2):
try:
log.info("Performing IOs and MDSfailovers on clients")
for client in clients:
client.exec_command(cmd="sudo pip install crefi")
for num in range(range1, range2):
if mds_fail_over != "":
mds_fail_over(mds_nodes)
out, err = client.exec_command(
cmd="sudo crefi -n %d %sdir_%d" % (num_of_files, mounting_dir, num)
)
rc = out.channel.recv_exit_status()
print(out.read().decode())
RC.append(rc)
print(time.time())
if rc == 0:
log.info("Client IO is going on,success")
else:
log.error("Client IO got interrupted")
failure.update({client: out})
break
break
except Exception as e:
log.error(e)
def custom_ceph_config(suite_config, custom_config, custom_config_file):
"""
Combines and returns custom configuration overrides for ceph.
Hierarchy is as follows::
custom_config > custom_config_file > suite_config
Args:
suite_config: ceph_conf_overrides that currently exist in the test suite
custom_config: custom config args provided by the cli (these all go to the global scope)
custom_config_file: path to custom config yaml file provided by the cli
Returns
New value to be used for ceph_conf_overrides in test config
"""
log.debug("Suite config: {}".format(suite_config))
log.debug("Custom config: {}".format(custom_config))
log.debug("Custom config file: {}".format(custom_config_file))
full_custom_config = suite_config or {}
cli_config_dict = {}
custom_config_dict = {}
# retrieve custom config from file
if custom_config_file:
with open(custom_config_file) as f:
custom_config_dict = yaml.safe_load(f)
log.info("File contents: {}".format(custom_config_dict))
# format cli configs into dict
if custom_config:
cli_config_dict = dict(item.split("=") for item in custom_config)
# combine file and cli configs
if cli_config_dict:
if not custom_config_dict.get("global"):
custom_config_dict["global"] = {}
for key, value in cli_config_dict.items():
custom_config_dict["global"][key] = value
# combine file and suite configs
for key, value in custom_config_dict.items():
subsection = {}
if full_custom_config.get(key):
subsection.update(full_custom_config[key])
subsection.update(value)
full_custom_config[key] = subsection
log.info("Full custom config: {}".format(full_custom_config))
return full_custom_config
def mask_secrets(plaintext, secrets):
"""
Replace secrets in plaintext with asterisks
Args:
plaintext (str or list): The plaintext to remove the secrets from or
list of strings to remove secrets from
secrets (list): List of secret strings to replace in the plaintext
Returns:
str: The censored version of plaintext
"""
if secrets:
for secret in secrets:
if isinstance(plaintext, list):
plaintext = [string.replace(secret, "*" * 5) for string in plaintext]
else:
plaintext = plaintext.replace(secret, "*" * 5)
return plaintext
def _is_base64_block(text_block: str, min_length: int = 100) -> bool:
"""
Check if a text block is likely base64 encoded data.
Args:
text_block (str): Text to check for base64 encoding
min_length (int): Minimum length to consider (default 100 chars)
Returns:
bool: True if text appears to be base64 encoded
"""
if not text_block or len(text_block) < min_length:
return False
# Base64 alphabet: A-Z, a-z, 0-9, +, /, = (padding)
# Using string module to avoid detect-secrets false positive
base64_chars = set(string.ascii_letters + string.digits + "+/=")
non_whitespace = (
text_block.replace("\n", "")
.replace("\r", "")
.replace(" ", "")
.replace("\t", "")
)
if not non_whitespace:
return False
# Check character composition
base64_char_count = sum(1 for char in non_whitespace if char in base64_chars)
ratio = base64_char_count / len(non_whitespace)
# Must be 95%+ base64 characters to allow YAML prefixes like "- key:"
if ratio < 0.95:
return False
# Additional heuristic: reject if it looks like regular text
# Regular text is heavily lowercase-skewed (80%+ lowercase)
# Base64 can have any distribution, so we only reject obvious text patterns
upper_count = sum(1 for c in non_whitespace if c.isupper())
lower_count = sum(1 for c in non_whitespace if c.islower())
# If there are letters, check if it's heavily lowercase (indicates text)
if upper_count + lower_count > 0:
lower_ratio = lower_count / (upper_count + lower_count)
# Regular text typically has 80%+ lowercase
if lower_ratio > 0.85:
return False
return True
def _extract_base64_blocks(lines: list) -> list:
"""
Group consecutive base64 lines into blocks with their indices.
Args:
lines (list): List of output lines to process
Returns:
list: List of tuples (start_index, end_index, is_base64_block)
"""
blocks = []
current_block_start = None
for i, line in enumerate(lines):
stripped = line.strip()
is_base64 = _is_base64_block(stripped, min_length=50)
if is_base64:
if current_block_start is None:
current_block_start = i
else:
if current_block_start is not None:
blocks.append((current_block_start, i - 1, True))
current_block_start = None
# Handle base64 block at end of output
if current_block_start is not None:
blocks.append((current_block_start, len(lines) - 1, True))
return blocks
def truncate_large_base64(output: str, max_base64_size: int = 1024) -> str:
"""
Truncate large base64 blocks in command output to reduce log noise.
Only truncates base64 strings larger than max_base64_size to preserve
small base64-encoded secrets that may need to be decoded for debugging.
Args:
output (str): Command output to process
max_base64_size (int): Maximum size for base64 blocks (default 1024 chars)
Returns:
str: Output with large base64 blocks truncated
"""
if not output or len(output) < max_base64_size:
return output
lines = output.split("\n")
base64_blocks = _extract_base64_blocks(lines)
if not base64_blocks:
return output
result_lines = []
last_processed = -1
for start_idx, end_idx, _ in base64_blocks:
# Add non-base64 lines before this block
result_lines.extend(lines[last_processed + 1 : start_idx])
# Process base64 block
block_lines = lines[start_idx : end_idx + 1]
block_text = "\n".join(block_lines)
if len(block_text) > max_base64_size:
result_lines.append(
f"[BASE64_TRUNCATED: {len(block_text)} chars removed for log brevity]"
)
else:
# Block is small, keep it (might be a secret to decode)
result_lines.extend(block_lines)
last_processed = end_idx
# Add remaining non-base64 lines after last block
result_lines.extend(lines[last_processed + 1 :])
return "\n".join(result_lines)
def run_cmd(
cmd,
secrets=None,
timeout=600,
ignore_error=False,
threading_lock=None,
silent=False,
cluster_config=None,
output_file=None,
**kwargs,
):
"""
*The deprecated form of exec_cmd.*
Run an arbitrary command locally
Args:
cmd (str): command to run
secrets (list): A list of secrets to be masked with asterisks
This kwarg is popped in order to not interfere with
subprocess.run(``**kwargs``)
timeout (int): Timeout for the command, defaults to 600 seconds.
ignore_error (bool): True if ignore non zero return code and do not
raise the exception.
threading_lock (threading.RLock): threading.RLock object that is used
for handling concurrent oc commands
silent (bool): If True will silent errors from the server, default false
output_file (str): path where to write stderr from command - apply only when silent mode is True
Raises:
CommandFailed: In case the command execution fails
Returns:
(str) Decoded stdout of command
"""
completed_process = exec_cmd(
cmd,
secrets,
timeout,
ignore_error,
threading_lock,
silent=silent,
cluster_config=cluster_config,
output_file=output_file,
**kwargs,
)
return mask_secrets(completed_process.stdout.decode(), secrets)
def run_cmd_interactive(
cmd, prompts_answers, timeout=300, string_answer=False, raise_exception=True
):
"""
Handle interactive prompts with answers during subctl command
Args:
cmd(str): Command to be executed
prompts_answers(dict): Prompts as keys and answers as values
timeout(int): Timeout in seconds, for pexpect to wait for prompt
string_answer (bool): string answer
raise_exception (bool): raise excption
Raises:
InteractivePromptException: in case something goes wrong
"""
env = os.environ.copy()
env["KUBECONFIG"] = config.RUN.get("kubeconfig")
child = pexpect.spawn(cmd, env=env)
for prompt, answer in prompts_answers.items():
if child.expect(prompt, timeout=timeout):
if raise_exception:
raise InteractivePromptException("Unexpected Prompt")
if string_answer:
send_line = answer
else:
send_line = "".join([answer, constants.ENTER_KEY])
if not child.sendline(send_line):
raise InteractivePromptException("Failed to provide answer to the prompt")
def run_cmd_multicluster(
cmd, secrets=None, timeout=600, ignore_error=False, skip_index=None, **kwargs
):
"""
Run command on multiple clusters. Useful in multicluster scenarios
This is wrapper around exec_cmd
Args:
cmd (str): command to be run
secrets (list): A list of secrets to be masked with asterisks
This kwarg is popped in order to not interfere with
subprocess.run(``**kwargs``)
timeout (int): Timeout for the command, defaults to 600 seconds.
ignore_error (bool): True if ignore non zero return code and do not
raise the exception.
skip_index (list of int): List of indexes that needs to be skipped from executing the command
Raises:
CommandFailed: In case the command execution fails
Returns:
list : of CompletedProcess objects as per cluster's index in config.clusters
i.e. [cluster1_completedprocess, None, cluster2_completedprocess]
if command execution skipped on a particular cluster then corresponding entry will have None
"""
# Skip indexed cluster while running commands
# Useful to skip operations on ACM cluster
restore_ctx_index = config.cur_index
completed_process = [None] * len(config.clusters)
# this need's to be done to skip none value as skip_index accepts type none
if not isinstance(skip_index, list):
skip_index = [skip_index]
for cluster in config.clusters:
if cluster.MULTICLUSTER["multicluster_index"] in skip_index:
log.warning(f"skipping index = {skip_index}")
continue
else:
config.switch_ctx(cluster.MULTICLUSTER["multicluster_index"])
log.info(
f"Switched the context to cluster:{cluster.ENV_DATA['cluster_name']}"
)
try:
completed_process[cluster.MULTICLUSTER["multicluster_index"]] = (
exec_cmd(
cmd,
secrets=secrets,
timeout=timeout,
ignore_error=ignore_error,
**kwargs,
)
)
except CommandFailed:
# In case of failure, restore the cluster context to where we started
config.switch_ctx(restore_ctx_index)
log.error(
f"Command {cmd} execution failed on cluster {cluster.ENV_DATA['cluster_name']} "
)
raise
config.switch_ctx(restore_ctx_index)
return completed_process
@retry(
CommandFailed,
tries=6,
delay=10,
backoff=1,
text_in_exception="client connection lost",
)
def exec_cmd(
cmd,
secrets=None,
timeout=600,
ignore_error=False,
threading_lock=None,
silent=False,
cluster_config=None,
lock_timeout=7200,
output_file=None,
**kwargs,
):
"""
Run an arbitrary command locally
If the command is grep and matching pattern is not found, then this function
returns "command terminated with exit code 1" in stderr.
Args:
cmd (str): command to run
secrets (list): A list of secrets to be masked with asterisks
This kwarg is popped in order to not interfere with
subprocess.run(``**kwargs``)
timeout (int): Timeout for the command, defaults to 600 seconds.
ignore_error (bool): True if ignore non zero return code and do not
raise the exception.
threading_lock (threading.RLock): threading.RLock object that is used
for handling concurrent oc commands
silent (bool): If True will silent errors from the server, default false
cluster_config (MultiClusterConfig): In case of multicluster environment this object
will be non-null
lock_timeout (int): maximum timeout to wait for lock to prevent deadlocks (default 2 hours)
output_file (str): path where to write output of stderr from command - apply only when silent mode is True
Raises:
CommandFailed: In case the command execution fails
Returns:
(CompletedProcess) A CompletedProcess object of the command that was executed
CompletedProcess attributes:
args: The list or str args passed to run().
returncode (str): The exit code of the process, negative for signals.
stdout (str): The standard output (None if not captured).
stderr (str): The standard error (None if not captured).
"""
_env = kwargs.pop("env", os.environ.copy())
kubeconfig_path = config.RUN.get("kubeconfig")
if kubeconfig_path:
_env["KUBECONFIG"] = kubeconfig_path
if cluster_config:
kubeconfig_path = cluster_config.RUN.get("kubeconfig")
if kubeconfig_path:
_env["KUBECONFIG"] = cluster_config.RUN.get("kubeconfig")
if isinstance(cmd, str) and not kwargs.get("shell"):
cmd = shlex.split(cmd)
if (
kubeconfig_path
and cmd[0] == "oc"
and "--kubeconfig" not in cmd
and "mirror" not in cmd
):
kube_index = 1
# check if we have an oc plugin in the command
plugin_list = "oc plugin list"
cp = subprocess.run(
shlex.split(plugin_list),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
subcmd = cmd[1].split("-")
if len(subcmd) > 1:
subcmd = "_".join(subcmd)
if not isinstance(subcmd, str) and isinstance(subcmd, list):
subcmd = str(subcmd[0])
for l in cp.stdout.decode().splitlines():
if subcmd in l:
# If oc cmdline has plugin name then we need to push the
# --kubeconfig to next index
kube_index = 2
log.info(f"Found oc plugin {subcmd}")
cmd = list_insert_at_position(cmd, kube_index, ["--kubeconfig"])
cmd = list_insert_at_position(cmd, kube_index + 1, [kubeconfig_path])
try:
if kwargs.get("shell"):
masked_cmd = mask_secrets(cmd, secrets)
else:
masked_cmd = shlex.join(mask_secrets(cmd, secrets))
log.info(f"Executing command: {masked_cmd}")
if threading_lock and cmd[0] == "oc":
threading_lock.acquire(timeout=lock_timeout)
completed_process = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
timeout=timeout,
env=_env,
**kwargs,
)
finally:
if threading_lock and cmd[0] == "oc":
threading_lock.release()
masked_stdout = mask_secrets(completed_process.stdout.decode(), secrets)
truncated_stdout = truncate_long_lines(masked_stdout)
if len(completed_process.stdout) > 0:
truncated_stdout = truncate_large_base64(truncated_stdout)
log.debug(f"Command stdout: {truncated_stdout}")
else:
log.debug("Command stdout is empty")
masked_stderr = mask_secrets(completed_process.stderr.decode(), secrets)
if len(completed_process.stderr) > 0:
if not silent:
truncated_stderr = truncate_large_base64(masked_stderr)
log.warning(f"Command stderr: {truncated_stderr}")
else:
if output_file:
with open(output_file, "a") as out_fd:
out_fd.write(masked_stderr)
else:
if not silent:
log.debug("Command stderr is empty")
log.debug(f"Command return code: {completed_process.returncode}")
if completed_process.returncode and not ignore_error:
masked_stderr = bin_xml_escape(filter_out_emojis(masked_stderr))
if (
"grep" in masked_cmd
and b"command terminated with exit code 1" in completed_process.stderr
):
log.info(f"No results found for grep command: {masked_cmd}")
else:
raise CommandFailed(
f"Error during execution of command: {masked_cmd}."
f"\nError is {masked_stderr}"
)
return completed_process
def bin_xml_escape(arg):
"""
Visually escape invalid XML characters.
For example, transforms 'hello\aworld\b' into 'hello#x07world#x08'
Args:
arg (object) Object on top of which the invalid XML characters will be escaped
Returns:
str: string with escaped invalid characters
"""
def repl(matchobj: Match[str]) -> str:
i = ord(matchobj.group())
if i <= 0xFF:
return "#x%02X" % i
else:
return "#x%04X" % i
# The spec range of valid chars is:
# Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
# For an unknown(?) reason, we disallow #x7F (DEL) as well.
illegal_xml_re = (
"[^\u0009\u000a\u000d\u0020-\u007e\u0080-\ud7ff\ue000-\ufffd\u10000-\u10ffFF]"
)
return re.sub(illegal_xml_re, repl, str(arg))
def truncate_long_lines(output: str, max_line_length: int = 500) -> str:
"""
Truncate individual lines that exceed max_line_length.
Preserves:
- First N/2 chars (includes log prefix and key info)
- Last 50 chars (for context)
- Adds truncation marker in middle
Args:
output (str): Command output to process.
max_line_length (int): Maximum line length before truncation.
Returns:
str: Output with long lines truncated.
"""
if not output:
return output
lines = output.split("\n")
result = []
for line in lines:
if len(line) > max_line_length:
# Keep prefix and suffix, truncate middle
prefix_len = max_line_length // 2
suffix_len = 50
truncated_chars = max(0, len(line) - prefix_len - suffix_len)
truncated_text = f"[...{truncated_chars} chars truncated...]"
if truncated_chars > len(truncated_text):
result.append(
f"{line[:prefix_len]}{truncated_text}{line[-suffix_len:]}"
)
else:
result.append(line) # Edge case: line just over threshold
else:
result.append(line)
return "\n".join(result)
def download_file(url, filename, **kwargs):
"""
! Deprecated, use download_with_retries instead !
Download a file from a specified url
Args:
url (str): URL of the file to download
filename (str): Name of the file to write the download to
kwargs (dict): additional keyword arguments passed to requests.get(...)
"""
log.debug(f"Download '{url}' to '{filename}'.")
if "timeout" not in kwargs:
kwargs["timeout"] = 600
with open(filename, "wb") as f:
r = requests.get(url, **kwargs)
assert r.ok, f"The URL {url} is not available! Status: {r.status_code}."
f.write(r.content)
def download_with_retries(url, filename, max_retries=3):
"""
Download file with retries and proper error handling
Args:
url (str): URL of the file to download
filename (str): Path where to save the downloaded file
max_retries (int): Maximum number of retries for downloading the file
Returns:
str: Path to the downloaded file if successful, None otherwise
"""
session = requests.Session()
retry_strategy = Retry(
total=max_retries,
backoff_factor=2,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET"],
respect_retry_after_header=True,
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)