-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsb.py
1765 lines (1412 loc) · 57.6 KB
/
sb.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
import argparse
import asyncio
import glob
import json
import os
import shlex
import shutil
import subprocess
import sys
import threading
import time
from subprocess import CompletedProcess, CalledProcessError
from typing import Any, Callable, Dict, List, Optional, Union
import magic
import requests
import yaml
from yaml.loader import SafeLoader
__version__ = "0.0.0"
# Constants
ANSIBLE_PLAYBOOK_BINARY_PATH = "/usr/local/bin/ansible-playbook"
SALTBOX_REPO_PATH = "/srv/git/saltbox"
SALTBOX_PLAYBOOK_PATH = f"{SALTBOX_REPO_PATH}/saltbox.yml"
SALTBOX_ACCOUNTS_PATH = '/srv/git/saltbox/accounts.yml'
SANDBOX_REPO_PATH = "/opt/sandbox"
SANDBOX_PLAYBOOK_PATH = f"{SANDBOX_REPO_PATH}/sandbox.yml"
SALTBOXMOD_REPO_PATH = "/opt/saltbox_mod"
SALTBOXMOD_PLAYBOOK_PATH = f"{SALTBOXMOD_REPO_PATH}/saltbox_mod.yml"
SB_REPO_PATH = "/srv/git/sb"
SB_CACHE_FILE = "/srv/git/sb/cache.json"
# Global variable
saltbox_user = None
# Functions
def get_saltbox_user():
try:
with open(SALTBOX_ACCOUNTS_PATH, 'r') as file:
data = yaml.load(file, Loader=SafeLoader)
if data and isinstance(data, dict) and 'user' in data and 'name' in data['user']:
return data['user']['name']
else:
print(f"Error: 'user.name' not found in {SALTBOX_ACCOUNTS_PATH}.")
sys.exit(1)
except FileNotFoundError:
print(f"Error: {SALTBOX_ACCOUNTS_PATH} not found.")
sys.exit(1)
except yaml.YAMLError as e:
print(f"Error parsing {SALTBOX_ACCOUNTS_PATH}: {e}")
sys.exit(1)
except Exception as e:
print(f"Unexpected error reading {SALTBOX_ACCOUNTS_PATH}: {e}")
sys.exit(1)
def is_root():
"""
Check if the current user has root privileges.
Returns:
bool: True if the user has root privileges, False otherwise.
"""
return os.geteuid() == 0
def relaunch_as_root():
"""
Relaunch the script with root privileges if not already root.
Raises:
SystemExit: Always exits after attempting to relaunch.
"""
if not is_root():
print("Relaunching with root privileges.")
executable_path = os.path.abspath(sys.argv[0])
try:
subprocess.check_call(['sudo', executable_path] + sys.argv[1:])
except subprocess.CalledProcessError as e:
print(f"Failed to relaunch with root privileges: {e}")
sys.exit(0)
def get_cached_tags(repo_path):
"""
Retrieve cached tags and commit hash for the given repo_path.
Args:
repo_path (str): Path to the repository.
Returns:
dict: A dictionary containing cached tags and commit hash,
or an empty dict if no cache exists.
"""
try:
with open(SB_CACHE_FILE, "r") as cache_file:
cache = json.load(cache_file)
return cache.get(repo_path, {})
except FileNotFoundError:
return {}
def update_cache(repo_path, commit_hash, tags):
"""
Update the cache with the new commit hash and tags.
Args:
repo_path (str): Path to the repository.
commit_hash (str): The current commit hash.
tags (list): List of tags to cache.
"""
try:
with open(SB_CACHE_FILE, "r") as cache_file:
cache = json.load(cache_file)
except FileNotFoundError:
cache = {}
cache[repo_path] = {"commit": commit_hash, "tags": tags}
with open(SB_CACHE_FILE, "w") as cache_file:
json.dump(cache, cache_file)
def check_cache(repo_path, tags):
"""
Check if all requested tags are present in the cache.
Args:
repo_path (str): The path to the repository.
tags (list): The list of tags to check.
Returns:
tuple: A boolean indicating if all tags are cached and a list of missing tags.
"""
cache = get_cached_tags(repo_path)
if not cache:
# If cache doesn't exist, proceed with playbook execution
return True, []
cached_tags = set(cache.get("tags", []))
requested_tags = set(tags)
missing_tags = requested_tags - cached_tags
return not missing_tags, list(missing_tags)
def supports_color():
"""
Returns True if the running system's terminal supports color,
and False otherwise.
"""
plat = sys.platform
supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ)
# isatty is not always implemented, #6223.
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
if not supported_platform or not is_a_tty:
return False
return True
class ColorPrinter:
"""A class for printing colored text to the console."""
def __init__(self):
"""Initialize the ColorPrinter with color support and ANSI color codes."""
self.use_color = supports_color()
self.colors = {
'red': '\033[91m',
'green': '\033[92m',
'yellow': '\033[93m',
'blue': '\033[94m',
'reset': '\033[0m'
}
def print_color(self, color, text):
"""
Print text in the specified color if color is supported.
Args:
color (str): The color to print the text in.
text (str): The text to print.
"""
if self.use_color:
color_code = self.colors.get(color, '')
print(f"{color_code}{text}{self.colors['reset']}")
else:
print(text)
def get_console_width(default=80):
"""
Get the width of the console in columns.
Args:
default (int): Default width to return if unable to determine.
Returns:
int: The width of the console in columns.
"""
try:
columns, _ = shutil.get_terminal_size()
except AttributeError:
columns = default
return columns
def print_in_columns(tags, padding=2):
"""
Print the given tags in columns that fit the console width.
Args:
tags (list): List of tags to print.
padding (int): Number of spaces to add between columns.
"""
if not tags:
return
console_width = shutil.get_terminal_size().columns
max_tag_length = max(len(tag) for tag in tags) + padding
# Ensure at least one column
num_columns = max(1, console_width // max_tag_length)
# Ceiling division to ensure all tags are included
num_rows = (len(tags) + num_columns - 1) // num_columns
for row in range(num_rows):
for col in range(num_columns):
idx = row + col * num_rows
if idx < len(tags):
print(f"{tags[idx]:{max_tag_length}}", end='')
print() # Newline after each row
def get_git_commit_hash(repo_path):
"""
Get the current Git commit hash of the repository.
Args:
repo_path (str): The path to the Git repository.
Returns:
str: The current Git commit hash.
Raises:
SystemExit: If the repository doesn't exist or if there's an error
getting the commit hash.
"""
try:
completed_process = subprocess.run(
["git", "rev-parse", "HEAD"],
cwd=repo_path,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
except FileNotFoundError:
print(f"\nThe folder '{repo_path}' does not exist. "
f"This indicates an incomplete install.\n")
sys.exit(1)
except subprocess.CalledProcessError as e:
print(f"Error occurred while trying to get the git commit hash: "
f"{e.stderr}")
sys.exit(e.returncode)
return completed_process.stdout.strip()
async def run_and_cache_ansible_tags(repo_path, playbook_path, extra_skip_tags):
"""
Run ansible-playbook to list tags and cache the results.
Args:
repo_path (str): Path to the repository.
playbook_path (str): Path to the Ansible playbook.
extra_skip_tags (str): Additional tags to skip.
"""
command, tag_parser = prepare_ansible_list_tags(
repo_path, playbook_path, extra_skip_tags
)
if command: # Need to fetch tags
process = await asyncio.create_subprocess_exec(
*command,
cwd=repo_path,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT
)
stdout, _ = await process.communicate()
output = stdout.decode()
tag_parser(output)
def prepare_ansible_list_tags(repo_path, playbook_path, extra_skip_tags):
"""
Prepare the command to list Ansible tags and the parser for the output.
Args:
repo_path (str): Path to the repository.
playbook_path (str): Path to the Ansible playbook.
extra_skip_tags (str): Additional tags to skip.
Returns:
tuple: The command to execute and the parser function for the output.
"""
def parse_output(output):
try:
task_tags_line = next(
line for line in output.split('\n') if "TASK TAGS:" in line
)
task_tags = (task_tags_line.split("TASK TAGS:")[1]
.replace('[', '').replace(']', '').strip())
tags = [tag.strip() for tag in task_tags.split(',') if tag.strip()]
except StopIteration:
return (f"Error: 'TASK TAGS:' not found in the ansible-playbook "
f"output. Please make sure '{playbook_path}' "
f"is formatted correctly.")
except Exception as e:
return f"Error processing command output: {str(e)}"
if repo_path != SALTBOXMOD_REPO_PATH:
commit_hash = get_git_commit_hash(repo_path)
update_cache(repo_path, commit_hash, tags)
return tags
if repo_path == SALTBOXMOD_REPO_PATH:
command = [
ANSIBLE_PLAYBOOK_BINARY_PATH,
playbook_path,
'--become',
'--list-tags',
f'--skip-tags=always,{extra_skip_tags}'
]
else:
cache = get_cached_tags(repo_path)
current_commit = get_git_commit_hash(repo_path)
if cache.get("commit") == current_commit:
return None, lambda _: cache["tags"] # Use cached tags
command = [
ANSIBLE_PLAYBOOK_BINARY_PATH,
playbook_path,
'--become',
'--list-tags',
f'--skip-tags=always,{extra_skip_tags}'
]
return command, parse_output
async def handle_list_async():
"""
Asynchronously handle listing of tags for different repositories.
"""
repo_info = [
(SALTBOX_REPO_PATH, SALTBOX_PLAYBOOK_PATH, "", "Saltbox tags:"),
(SANDBOX_REPO_PATH, SANDBOX_PLAYBOOK_PATH, "sanity_check",
"\nSandbox tags (prepend sandbox-):"),
]
if os.path.isdir(SALTBOXMOD_REPO_PATH):
repo_info.append(
(SALTBOXMOD_REPO_PATH, SALTBOXMOD_PLAYBOOK_PATH, "sanity_check",
"\nSaltbox_mod tags (prepend mod-):")
)
for repo_path, playbook_path, extra_skip_tags, base_title in repo_info:
command, tag_parser = prepare_ansible_list_tags(
repo_path, playbook_path, extra_skip_tags
)
cache_status = " (cached)" if command is None else ""
if command: # Fetch and parse tags if not using cache
process = await asyncio.create_subprocess_exec(
*command,
cwd=repo_path,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT
)
stdout, _ = await process.communicate()
tags = tag_parser(stdout.decode())
else: # Cached tags are available
tags = tag_parser(None) # Get cached tags directly
title_with_status = f"{base_title}{cache_status}\n"
print(title_with_status)
if isinstance(tags, str) and tags.startswith("Error"):
print(tags) # Print the error message directly
else:
print_in_columns(tags)
def handle_list(_arguments):
"""
Handle the list command by running the asynchronous list function.
Args:
_arguments: Unused arguments.
"""
asyncio.run(handle_list_async())
def handle_recreate_venv(_arguments):
"""
Handle the command to recreate the Ansible virtual environment.
This function calls manage_ansible_venv with the force_recreate flag set to True.
Args:
_arguments: Unused arguments from the command line parser.
"""
manage_ansible_venv(force_recreate=True)
def run_ansible_playbook(repo_path, playbook_path, ansible_binary_path,
tags=None, skip_tags=None, verbosity=0,
extra_vars=None):
"""
Run an Ansible playbook with the given parameters.
Args:
repo_path (str): Path to the repository.
playbook_path (str): Path to the Ansible playbook.
ansible_binary_path (str): Path to the Ansible binary.
tags (list): List of tags to run.
skip_tags (list): List of tags to skip.
verbosity (int): Verbosity level for Ansible output.
extra_vars (list): List of extra variables to pass to Ansible.
Raises:
SystemExit: If the playbook execution fails or is interrupted.
"""
command = [ansible_binary_path, playbook_path, "--become"]
if tags:
command += ["--tags", ','.join(tags)]
if skip_tags:
command += ["--skip-tags", ','.join(skip_tags)]
if verbosity > 0:
command.append('-' + 'v' * verbosity)
if extra_vars:
combined_extra_vars = {}
file_extra_vars = []
for var in extra_vars:
if var.startswith("@"):
file_extra_vars.append(var)
else:
try:
parsed_var = json.loads(var)
if isinstance(parsed_var, dict):
combined_extra_vars.update(parsed_var)
else:
raise ValueError("The provided JSON is not a dictionary.")
except json.JSONDecodeError:
if "=" in var:
key, value = var.split("=", 1)
try:
parsed_value = json.loads(value, parse_float=str)
except json.JSONDecodeError:
parsed_value = value
combined_extra_vars[key] = parsed_value
else:
print(f"Error: Failed to parse '{var}' as valid JSON "
f"or a key=value pair.")
sys.exit(1)
if combined_extra_vars:
command += ["--extra-vars", json.dumps(combined_extra_vars)]
for file_var in file_extra_vars:
command += ["--extra-vars", file_var]
print("Executing Ansible playbook with command: "
f"{' '.join(shlex.quote(arg) for arg in command)}")
try:
_result = subprocess.run(command, cwd=repo_path, check=True)
except KeyboardInterrupt:
print(f"\nError: Playbook {playbook_path} run was aborted "
f"by the user.\n")
sys.exit(1)
except subprocess.CalledProcessError as e:
print(f"\nError: Playbook {playbook_path} run failed, scroll up "
f"to the failed task to review.\n")
sys.exit(e.returncode)
print(f"\nPlaybook {playbook_path} executed successfully.\n")
def git_fetch_and_reset(repo_path, default_branch='master',
post_fetch_script=None, custom_commands=None):
"""
Fetch and reset a Git repository to a specified branch.
Args:
repo_path (str): Path to the Git repository.
default_branch (str): The default branch to reset to.
post_fetch_script (str): Optional script to run after fetching.
custom_commands (list): Optional list of custom commands to run.
"""
global saltbox_user
# Get current branch name
result = subprocess.run(
['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
cwd=repo_path,
stdout=subprocess.PIPE,
text=True,
check=True
)
current_branch = result.stdout.strip()
# Determine if a reset to default_branch is needed
if current_branch != default_branch:
print(f"Currently on branch '{current_branch}'.")
reset_to_default = input(
f"Do you want to reset to the '{default_branch}' branch? (y/n): "
).strip().lower()
if reset_to_default != 'y':
print(f"Updating the current branch '{current_branch}'...")
branch = current_branch
else:
branch = default_branch
else:
branch = default_branch
# Commands to fetch and reset
commands = [
['git', 'fetch', '--quiet'],
['git', 'clean', '--quiet', '-df'],
['git', 'reset', '--quiet', '--hard', '@{u}'],
['git', 'checkout', '--quiet', branch],
['git', 'clean', '--quiet', '-df'],
['git', 'reset', '--quiet', '--hard', '@{u}'],
['git', 'submodule', 'update', '--init', '--recursive'],
['chown', '-R', f'{saltbox_user}:{saltbox_user}', repo_path]
]
for command in commands:
subprocess.run(command, cwd=repo_path,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True)
if post_fetch_script:
subprocess.run(post_fetch_script, shell=True, cwd=repo_path,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True)
if custom_commands:
for command in custom_commands:
subprocess.run(command, shell=True, cwd=repo_path,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True)
print(f"Repository at {repo_path} has been updated. "
f"Current branch: '{branch}'.")
def version_compare(v1: str, v2: str) -> int:
"""
Compare two version strings.
Args:
v1 (str): First version string to compare.
v2 (str): Second version string to compare.
Returns:
int: -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2
Examples:
>>> version_compare('1.0.0', '2.0.0')
-1
>>> version_compare('2.0.0', '2.0.0')
0
>>> version_compare('2.1.0', '2.0.0')
1
"""
v1_parts = v1.lstrip('v').split('.')
v2_parts = v2.lstrip('v').split('.')
for i in range(max(len(v1_parts), len(v2_parts))):
v1_part = int(v1_parts[i]) if i < len(v1_parts) else 0
v2_part = int(v2_parts[i]) if i < len(v2_parts) else 0
if v1_part < v2_part:
return -1
elif v1_part > v2_part:
return 1
return 0
def download_and_install_saltbox_fact(always_update=False):
"""
Download and install the latest saltbox.fact file.
Args:
always_update (bool): If True, force update regardless of current version.
Raises:
requests.RequestException: If there's an error downloading the file.
IOError: If there's an error writing the file.
Exception: For any other unexpected errors.
"""
download_url = "https://github.com/saltyorg/ansible-facts/releases/latest/download/saltbox-facts"
target_path = "/srv/git/saltbox/ansible_facts.d/saltbox.fact"
api_url = "https://api.github.com/repos/saltyorg/ansible-facts/releases/latest"
try:
# Fetch the latest release info from GitHub
response = requests.get(api_url)
response.raise_for_status()
latest_release = response.json()
latest_version = latest_release['tag_name']
if os.path.exists(target_path) and not always_update:
# Run the existing saltbox.fact and parse its output
result = subprocess.run([target_path], capture_output=True, text=True)
if result.returncode == 0:
try:
current_data = json.loads(result.stdout)
current_version = current_data.get("saltbox_facts_version")
if current_version is None:
print("Current saltbox.fact doesn't have version info. Updating...")
elif version_compare(current_version, latest_version) >= 0:
print(f"saltbox.fact is up to date (version {current_version})")
return
else:
print(f"New version available. Updating from {current_version} "
f"to {latest_version}")
except json.JSONDecodeError:
print("Failed to parse current saltbox.fact output. "
"Proceeding with update.")
else:
print("Failed to run current saltbox.fact. Proceeding with update.")
else:
if always_update:
print("Update forced. Proceeding with update.")
else:
print("saltbox.fact not found. Proceeding with update.")
print(f"Updating saltbox.fact to version {latest_version}")
response = requests.get(download_url)
response.raise_for_status()
# Ensure the directory exists
os.makedirs(os.path.dirname(target_path), exist_ok=True)
# Write the content to the file
with open(target_path, 'wb') as f:
f.write(response.content)
# Make the file executable
os.chmod(target_path, 0o755)
print(f"Successfully updated saltbox.fact to version {latest_version} "
f"at {target_path}")
except requests.RequestException as e:
print(f"Error downloading saltbox.fact: {e}")
except IOError as e:
print(f"Error writing saltbox.fact: {e}")
except Exception as e:
print(f"Unexpected error updating saltbox.fact: {e}")
def update_saltbox(saltbox_repo_path, saltbox_playbook_file, verbosity=0):
"""
Update Saltbox repository and run necessary tasks.
Args:
saltbox_repo_path (str): Path to the Saltbox repository.
saltbox_playbook_file (str): Path to the Saltbox playbook file.
verbosity (int): Verbosity level for Ansible playbook execution.
Raises:
SystemExit: If the Saltbox repository path does not exist.
"""
print("Updating Saltbox...")
if not os.path.isdir(saltbox_repo_path):
print("Error: SB_REPO_PATH does not exist or is not a directory.")
sys.exit(1)
manage_ansible_venv(force_recreate=False)
# Define custom commands for Saltbox update
custom_commands = [
f"cp {saltbox_repo_path}/defaults/ansible.cfg.default "
f"{saltbox_repo_path}/ansible.cfg"
]
# Check commit hash before update
old_commit_hash = get_git_commit_hash(saltbox_repo_path)
git_fetch_and_reset(saltbox_repo_path, "master",
custom_commands=custom_commands)
# Always update saltbox.fact during update
download_and_install_saltbox_fact(always_update=False)
# Run Settings role with specified tags and skip-tags
tags = ['settings']
skip_tags = ['sanity-check', 'pre-tasks']
run_ansible_playbook(
saltbox_repo_path,
saltbox_playbook_file,
ANSIBLE_PLAYBOOK_BINARY_PATH,
tags,
skip_tags,
verbosity
)
# Check commit hash after update
new_commit_hash = get_git_commit_hash(saltbox_repo_path)
if old_commit_hash != new_commit_hash:
print("Saltbox Commit Hash changed, updating tags cache.")
asyncio.run(run_and_cache_ansible_tags(
saltbox_repo_path,
saltbox_playbook_file,
""
))
print("Saltbox Update Completed.")
def update_sandbox(sandbox_repo_path, sandbox_playbook_file, verbosity=0):
"""
Update Sandbox repository and run necessary tasks.
Args:
sandbox_repo_path (str): Path to the Sandbox repository.
sandbox_playbook_file (str): Path to the Sandbox playbook file.
verbosity (int): Verbosity level for Ansible playbook execution.
Raises:
SystemExit: If the Sandbox repository path does not exist.
"""
print("Updating Sandbox...")
if not os.path.isdir(sandbox_repo_path):
print(f"Error: {sandbox_repo_path} does not exist or is not a directory.")
sys.exit(1)
# Define custom commands for Sandbox update
custom_commands = [
f"cp {sandbox_repo_path}/defaults/ansible.cfg.default "
f"{sandbox_repo_path}/ansible.cfg"
]
# Check commit hash before update
old_commit_hash = get_git_commit_hash(sandbox_repo_path)
git_fetch_and_reset(sandbox_repo_path, "master",
custom_commands=custom_commands)
# Run Settings role with specified tags and skip-tags
tags = ['settings']
skip_tags = ['sanity-check', 'pre-tasks']
run_ansible_playbook(
sandbox_repo_path,
sandbox_playbook_file,
ANSIBLE_PLAYBOOK_BINARY_PATH,
tags,
skip_tags,
verbosity
)
# Check commit hash after update
new_commit_hash = get_git_commit_hash(sandbox_repo_path)
if old_commit_hash != new_commit_hash:
print("Sandbox Commit Hash changed, updating tags cache.")
asyncio.run(run_and_cache_ansible_tags(
sandbox_repo_path,
sandbox_playbook_file,
""
))
print("Sandbox Update Completed.")
def update_sb(sb_repo_path):
"""
Update the sb repository and binary.
Args:
sb_repo_path (str): Path to the sb repository.
Raises:
SystemExit: If any critical error occurs during the update process.
"""
print("Updating sb.")
if not os.path.isdir(sb_repo_path):
print(f"Error: {sb_repo_path} does not exist or is not a directory.")
sys.exit(1)
# Perform git operations
git_fetch_and_reset(sb_repo_path, "master")
# Change permissions of sb.sh to 775
sb_sh_path = os.path.join(sb_repo_path, 'sb.sh')
if os.path.isfile(sb_sh_path):
os.chmod(sb_sh_path, 0o775)
print(f"Permissions changed for {sb_sh_path}.")
else:
print(f"Error: {sb_sh_path} does not exist or is not a file.")
sys.exit(1)
# Hardcoded paths
release_file_path = os.path.join(sb_repo_path, 'release.txt')
target_binary_path = os.path.join(sb_repo_path, 'sb')
# Read the release.txt file to get the GitHub tag
if not os.path.isfile(release_file_path):
print(f"Error: {release_file_path} does not exist.")
sys.exit(1)
with open(release_file_path, 'r') as release_file:
github_tag = release_file.readline().strip()
# Extract the version number from the tag
if not github_tag.startswith('refs/tags/'):
print(f"Error: Invalid tag format in {release_file_path}.")
sys.exit(1)
version = github_tag[len('refs/tags/'):]
if not version:
print(f"Error: No version found in tag {github_tag}.")
sys.exit(1)
# Form the URL for the binary download
download_url = f"https://github.com/saltyorg/sb/releases/download/{version}/sb"
# Download the binary file
response = requests.get(download_url)
if response.status_code != 200:
print(f"Error: Failed to download the binary from {download_url}.")
sys.exit(1)
# Save the downloaded binary to a temporary file
temp_binary_path = target_binary_path + '.tmp'
with open(temp_binary_path, 'wb') as temp_binary_file:
temp_binary_file.write(response.content)
# Check if the downloaded file is a binary
mime = magic.Magic(mime=True)
file_type = mime.from_file(temp_binary_path)
if not file_type.startswith('application/'):
print(f"Error: Downloaded file is not a binary. "
f"Detected type: {file_type}")
os.remove(temp_binary_path)
sys.exit(1)
# Replace the old binary with the new one
if os.path.isfile(temp_binary_path):
os.replace(temp_binary_path, target_binary_path)
print(f"Updated binary at {target_binary_path}.")
# Ensure the new binary is executable
os.chmod(target_binary_path, 0o755)
print(f"Permissions changed for {target_binary_path} to be executable.")
else:
print(f"Error: Failed to write the new binary to {temp_binary_path}.")
sys.exit(1)
def add_git_safe_directory_if_needed(directory):
"""
Add a directory to git's safe.directory if it's not already there.
Args:
directory (str): The directory path to add.
"""
result = subprocess.run(
['git', 'config', '--global', '--get-all', 'safe.directory'],
stdout=subprocess.PIPE,
text=True
)
safe_directories = result.stdout.strip().split('\n')
if directory not in safe_directories:
subprocess.run(
['git', 'config', '--global', '--add', 'safe.directory', directory]
)
print(f"Added {directory} to git safe.directory.")
def check_and_update_repo(sb_repo_path):
"""
Check if the sb repository is up-to-date and update if necessary.
Args:
sb_repo_path (str): Path to the sb repository.
Raises:
SystemExit: If the directory doesn't exist or other errors occur.
"""
has_updated = False
try:
if not os.path.isdir(sb_repo_path):
raise OSError(f"Directory does not exist: {sb_repo_path}")
for repo_path in [SALTBOXMOD_REPO_PATH, SALTBOX_REPO_PATH, SANDBOX_REPO_PATH]:
if os.path.isdir(repo_path):
add_git_safe_directory_if_needed(repo_path)
# Fetch latest changes from the remote
subprocess.run(
['git', 'fetch'],
cwd=sb_repo_path,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True
)
# Get the current HEAD hash and the upstream master hash
head_hash = subprocess.check_output(
['git', 'rev-parse', 'HEAD'],
cwd=sb_repo_path
).strip()
upstream_hash = subprocess.check_output(
['git', 'rev-parse', 'master@{upstream}'],
cwd=sb_repo_path
).strip()
if head_hash != upstream_hash:
print("sb is not up to date with origin. Updating.")
update_sb(sb_repo_path)
has_updated = True
print("Relaunching with previous arguments.")
executable_path = os.path.abspath(sys.argv[0])
result = subprocess.run(['sudo', executable_path] + sys.argv[1:], check=True)
sys.exit(result.returncode)
except OSError as e:
print(f"Error: {e}")
sys.exit(1)
except subprocess.CalledProcessError as e:
if not has_updated:
print(f"Error executing git command: {e}")
sys.exit(1)
def handle_update(arguments):
"""
Handle the update command for Saltbox and Sandbox.
This function updates both Saltbox and Sandbox repositories
using their respective update functions.
Args:
arguments (argparse.Namespace): Command line arguments,
expected to have a 'verbose' attribute.
"""
update_saltbox(
SALTBOX_REPO_PATH,
SALTBOX_PLAYBOOK_PATH,
arguments.verbose
)
update_sandbox(
SANDBOX_REPO_PATH,
SANDBOX_PLAYBOOK_PATH,
arguments.verbose
)
def handle_install(arguments):
"""
Handle the installation process for Saltbox, Sandbox, and mod tags.
Args:
arguments: Parsed command-line arguments.
Raises:
SystemExit: If no valid tags are provided or if there are issues with the tags.
"""
saltbox_tags: List[str] = []
mod_tags: List[str] = []
sandbox_tags: List[str] = []
tags = [tag.strip() for arg in arguments.tags
for tag in arg.split(',') if tag.strip()]
skip_tags = [skip_tag.strip() for arg in arguments.skip_tags
for skip_tag in arg.split(',') if skip_tag.strip()]
ignore_cache = any(var.startswith("sanity_check_use_cache=")
for var in arguments.extra_vars)