-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlws.py
2900 lines (2381 loc) Β· 138 KB
/
lws.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
# to create lws alias:
# chmod +x lws.py && alias lws='python3 lws.py'
# then u can just run..
# lws
import os
import time
import subprocess
import shutil
import logging
import logging.config
import json
import requests
import gzip
import yaml
import click
import socket
from concurrent.futures import ThreadPoolExecutor, as_completed
class JsonFormatter(logging.Formatter):
"""Custom JSON formatter for logging."""
def format(self, record):
log_record = {
'timestamp': self.formatTime(record, self.datefmt),
'level': record.levelname,
'module': record.name,
'message': record.getMessage(),
}
if record.exc_info:
log_record['exception'] = self.formatException(record.exc_info)
return json.dumps(log_record)
def setup_logging(log_level=logging.DEBUG, log_file=None, json_log_file=None):
"""
Sets up the logging configuration.
Parameters:
- log_level: The logging level (e.g., logging.DEBUG, logging.INFO).
- log_file: Optional file path to log in standard format.
- json_log_file: Optional file path to log in JSON format.
"""
log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
log_date_format = "%Y-%m-%d %H:%M:%S"
handlers = {
'console': {
'level': log_level,
'class': 'logging.StreamHandler',
'formatter': 'default',
}
}
if log_file:
handlers['file'] = {
'level': log_level,
'class': 'logging.FileHandler',
'formatter': 'default',
'filename': log_file,
}
if json_log_file:
handlers['json_file'] = {
'level': log_level,
'class': 'logging.FileHandler',
'formatter': 'json',
'filename': json_log_file,
}
logging_config = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': log_format,
'datefmt': log_date_format,
},
'json': {
'()': JsonFormatter,
'datefmt': log_date_format,
}
},
'handlers': handlers,
'root': {
'level': log_level,
'handlers': (handlers.keys()),
},
}
logging.config.dictConfig(logging_config)
logging.debug("π Logging to console, and additional JSON logging to file {}".format(json_log_file if json_log_file else "not configured"))
# Example usage:
log_file_path = os.path.join(os.getcwd(), 'lws.log') # Standard log file path
json_log_file_path = os.path.join(os.getcwd(), 'lws.json.log') # JSON log file path
# Set up logging: standard logging to console and file, JSON logging to a separate file
setup_logging(log_level=logging.ERROR, log_file=log_file_path, json_log_file=json_log_file_path)
# Load and validate the configuration
def load_config():
try:
with open('config.yaml', 'r') as file:
config = yaml.safe_load(file)
validate_config(config)
return config
except FileNotFoundError:
logging.error("β Configuration file 'config.yaml' not found.")
raise
except yaml.YAMLError as e:
logging.error(f"β Error parsing configuration file: {e}")
raise
def validate_config(config):
required_keys = ['regions', 'instance_sizes']
for key in required_keys:
if key not in config:
logging.error(f"β Missing required configuration key: {key}")
raise ValueError(f"β Missing required configuration key: {key}")
if not isinstance(config['regions'], dict) or not config['regions']:
logging.error("β Invalid or empty 'regions' configuration.")
raise ValueError("β Invalid or empty 'regions' configuration.")
if not isinstance(config['instance_sizes'], dict) or not config['instance_sizes']:
logging.error("β Invalid or empty 'instance_sizes' configuration.")
raise ValueError("β Invalid or empty 'instance_sizes' configuration.")
config = load_config()
# lws
@click.group()
def lws():
"""π§ linux (containers) web services"""
pass
def run_ssh_command(host, user, ssh_password, command):
"""Runs an SSH command on a remote host, with error handling and logging."""
ssh_cmd = ["sshpass", "-p", ssh_password, "ssh", f"{user}@{host}"] + command
# Construct a sanitized command for logging (hides the password)
sanitized_ssh_cmd = ["sshpass", "-p", "****", "ssh", f"{user}@{host}"] + command
try:
# Log the sanitized command instead of the real command with the password
logging.debug(f"π Executing SSH command: {' '.join(sanitized_ssh_cmd)}")
# Execute the command
result = subprocess.run(ssh_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
result.check_returncode() # This raises CalledProcessError if returncode is non-zero
# Log the successful execution and output
logging.debug(f"π SSH command executed successfully: {' '.join(sanitized_ssh_cmd)}")
logging.debug(f"π Command output: {result.stdout}")
return result # Return the entire result object
except subprocess.CalledProcessError as e:
# Log the error without showing the password
logging.debug(f"β SSH command failed with return code {e.returncode}: {' '.join(sanitized_ssh_cmd)}")
logging.debug(f"β Error output: {e.stderr}")
return e
except Exception as e:
logging.error(f"β An unexpected error occurred while running SSH command: {str(e)}")
return None
def execute_command(cmd, use_local_only, host_details=None):
"""Executes a command locally or via SSH based on the configuration."""
if use_local_only:
logging.debug(f"π Executing local command: {' '.join(cmd)}")
try:
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
result.check_returncode()
logging.debug(f"π Local command output: {result.stdout}")
return result
except subprocess.CalledProcessError as e:
logging.error(f"β Local command failed: {e}")
return e
else:
logging.debug(f"π Executing remote command: {' '.join(cmd)} on {host_details['host']}")
return run_ssh_command(host_details['host'], host_details['user'], host_details['ssh_password'], cmd)
def run_proxmox_command(local_cmd, remote_cmd=None, use_local_only=False, host_details=None):
"""Executes a Proxmox command either locally or remotely."""
cmd = local_cmd if use_local_only else remote_cmd
if cmd is None:
raise ValueError("Command cannot be None.")
return execute_command(cmd, use_local_only, host_details)
# Command alias decorator
def command_alias(*aliases):
def decorator(f):
for alias in aliases:
lws.command(alias)(f)
return f
return decorator
# Generic function to process instance commands
def process_instance_command(instance_ids, command_type, region, az, **kwargs):
host_details = config['regions'][region]['availability_zones'][az]
command_map = {
'stop': lambda instance_id: (["pct", "shutdown", instance_id], ["pct", "shutdown", instance_id]),
'terminate': lambda instance_id: (["pct", "destroy", instance_id, "--purge"], ["pct", "destroy", instance_id, "--purge"]),
'describe': lambda instance_id: (["pct", "config", instance_id], ["pct", "config", instance_id]),
'resize': lambda instance_id: build_resize_command(instance_id, **kwargs),
'start': lambda instance_id: (["pct", "start", instance_id], ["pct", "start", instance_id]),
'reboot': lambda instance_id: (["pct", "reboot", instance_id], ["pct", "reboot", instance_id]),
'snapshot_create': lambda instance_id, snapshot_name: (
["pct", "snapshot", instance_id, snapshot_name],
["pct", "snapshot", instance_id, snapshot_name]
),
'snapshot_delete': lambda instance_id, snapshot_name: (
["pct", "delsnapshot", instance_id, snapshot_name],
["pct", "delsnapshot", instance_id, snapshot_name]
),
'_snapshots': lambda instance_id: (["pct", "snapshot", instance_id], ["pct", "snapshot", instance_id]),
}
for instance_id in instance_ids:
if command_type in ['snapshot_create', 'snapshot_delete']:
local_cmd, remote_cmd = command_map[command_type](instance_id, kwargs.get('snapshot_name'))
else:
local_cmd, remote_cmd = command_map[command_type](instance_id)
result = run_proxmox_command(local_cmd, remote_cmd, config['use_local_only'], host_details)
if result.returncode == 0:
if command_type == 'describe':
click.secho(f"π§ Instance {instance_id} configuration:\n{result.stdout}", fg='cyan')
elif command_type == '_snapshots':
click.secho(f"π Snapshots for instance {instance_id}:\n{result.stdout}", fg='cyan')
else:
click.secho(f"β
Instance {instance_id} {command_type} executed successfully.", fg='green')
else:
click.secho(f"β Failed to {command_type} instance {instance_id}: {result.stderr}", fg='red')
def build_resize_command(instance_id, memory=None, cpulimit=None, storage_size=None):
resize_cmd = ["pct", "set", instance_id]
if memory:
resize_cmd.extend(["--memory", str(memory)])
if cpulimit:
resize_cmd.extend(["--cpulimit", str(cpulimit)])
if storage_size:
resize_cmd.extend(["--rootfs", f"{config['default_storage']}:{storage_size}"])
return (resize_cmd, resize_cmd)
# Function to mask sensitive information
def mask_sensitive_info(config):
if isinstance(config, dict):
return {k: ("***" if "ssh_password" in k.lower() else mask_sensitive_info(v)) for k, v in config.items()}
elif isinstance(config, list):
return [mask_sensitive_info(i) for i in config]
else:
return config
@lws.group()
@command_alias('conf')
def conf():
"""π οΈ Manage client configuration."""
pass
@conf.command('show')
def show_conf():
"""π Show current configuration."""
config = load_config()
masked_config = mask_sensitive_info(config)
click.secho(yaml.dump(masked_config, default_flow_style=False), fg='cyan')
@conf.command('validate')
def validate_configuration_command():
"""π Validate the current configuration."""
logging.info("Validating configuration")
try:
validate_config(config) # Using the existing validate_config function
click.secho(f"β
Configuration is valid.", fg='green')
logging.info("β
Configuration validation succeeded")
except ValueError as e:
click.secho(f"β Configuration validation failed: {str(e)}", fg='red')
logging.error(f"β Configuration validation failed: {str(e)}")
@conf.command('backup')
@click.argument('destination_path')
@click.option('--timestamp', is_flag=True, help="Append timestamp to the backup file name.")
@click.option('--compress', is_flag=True, help="Compress the backup file.")
def backup_config(destination_path, timestamp, compress):
"""πΎ Backup the current configuration to a file."""
if timestamp:
destination_path = f"{destination_path}_{time.strftime('%Y%m%d%H%M%S')}"
logging.info(f"Backing up configuration to {destination_path}")
# Write the configuration to a file
with open(destination_path, 'w') as backup_file:
yaml.dump(config, backup_file)
click.secho(f"β
Configuration backed up to {destination_path}.", fg='green')
logging.info(f"β
Configuration backed up to {destination_path}")
if compress:
compressed_path = f"{destination_path}.gz"
with open(destination_path, 'rb') as f_in, gzip.open(compressed_path, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
os.remove(destination_path) # Remove the uncompressed file
click.secho(f"β
Backup compressed to {compressed_path}.", fg='green')
logging.info(f"β
Backup compressed to {compressed_path}")
@lws.group()
@command_alias('lxc')
def lxc():
"""βοΈ Manage LXC containers."""
pass
@lws.group()
@command_alias('px')
def px():
"""π Manage Proxmox hosts."""
pass
@px.command('list')
@click.option('--region', default=None, help='Filter hosts by region.')
def list_hosts(region):
"""π List all available Proxmox hosts."""
def resolve_host(host, timeout=0.2):
"""Resolve host with a timeout."""
try:
return socket.gethostbyname(host)
except socket.gaierror:
return None
def check_tcp_port(host, port, timeout=0.2):
"""Check if a TCP port is open."""
try:
with socket.create_connection((host, port), timeout=timeout):
return True
except (socket.timeout, ConnectionRefusedError, OSError):
return False
def check_host_reachability(host):
"""Check host reachability with DNS timeout, TCP probe, and fallback ping."""
resolved_ip = resolve_host(host)
if not resolved_ip:
return host, "π΄" # DNS resolution failed
if check_tcp_port(resolved_ip, 22):
return host, "π’" # TCP port 22 is open
else:
# Fall back to ping
try:
result = subprocess.run(
['ping', '-c', '1', '-W', '0.2', resolved_ip],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
if result.returncode == 0:
return host, "π‘" # Host is reachable via ping, but port 22 is closed
else:
return host, "π΄" # Host is not reachable
except subprocess.CalledProcessError:
return host, "π΄" # Host is not reachable
def process_host(region, az, az_details):
host = az_details['host']
status_symbol = check_host_reachability(host)
return f"{status_symbol[1]} -> Region: {region} - AZ: {az} - Host: {status_symbol[0]}"
# Collect tasks for parallel execution
tasks = []
with ThreadPoolExecutor(max_workers=10) as executor:
for reg, details in config['regions'].items():
if region and reg != region:
continue
for az, az_details in details['availability_zones'].items():
tasks.append(executor.submit(process_host, reg, az, az_details))
# Process results as they complete
for future in as_completed(tasks):
try:
result = future.result()
click.secho(result, fg='cyan')
except Exception as e:
click.secho(f"Error checking host: {e}", fg='red')
@px.command('reboot')
#@command_alias('proxmox-reboot')
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
@click.option('--confirm', is_flag=True, help="Confirm that you want to reboot the Proxmox host.")
def reboot_proxmox(region, az, confirm):
"""π Reboot the Proxmox host.
This command will reboot the entire Proxmox host. Use with caution.
"""
if not confirm:
click.secho("β Rebooting the Proxmox host is a critical action. Use the --confirm flag to proceed.", fg='red')
return
# Retrieve the host details from the configuration
host_details = config['regions'][region]['availability_zones'][az]
host = host_details['host']
user = host_details['user']
ssh_password = host_details['ssh_password']
# Construct the ssh command to reboot the Proxmox host
ssh_cmd = [
"sshpass", "-p", ssh_password, "ssh",
f"{user}@{host}", "reboot"
]
try:
# Execute the SSH command to reboot the Proxmox host
result = subprocess.run(ssh_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode == 0:
click.secho(f"β
Proxmox host {host} rebooted successfully.", fg='green')
else:
click.secho(f"β Failed to reboot Proxmox host {host}: {result.stderr}", fg='red')
except Exception as e:
click.secho(f"β An error occurred: {str(e)}", fg='red')
@px.command('upload')
#@command_alias('upload-template')
@click.argument('local_path')
@click.argument('remote_template_name', required=False)
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
@click.option('--storage-path', default='/var/lib/vz/template/cache', help="Remote path to upload the template. Defaults to Proxmox template directory.")
def upload_template(local_path, remote_template_name, region, az, storage_path):
"""π½ Upload template to Proxmox host.
LOCAL_PATH: The path to the template file on your local machine.
REMOTE_TEMPLATE_NAME: (Optional) The name under which the template will be stored on the Proxmox server. Defaults to the name of the local file.
"""
# Use the local filename if remote_template_name is not provided
if not remote_template_name:
remote_template_name = os.path.basename(local_path)
# Retrieve the host details from the configuration
host_details = config['regions'][region]['availability_zones'][az]
host = host_details['host']
user = host_details['user']
ssh_password = host_details['ssh_password']
# Construct the scp command to copy the file to the remote Proxmox server
scp_cmd = [
"sshpass", "-p", ssh_password, "scp",
local_path,
f"{user}@{host}:{storage_path}/{remote_template_name}"
]
try:
# Execute the SCP command to upload the template
result = subprocess.run(scp_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode == 0:
click.secho(f"β
Template '{remote_template_name}' uploaded successfully to {storage_path} on {host}.", fg='green')
else:
click.secho(f"β Failed to upload template: {result.stderr}", fg='red')
except Exception as e:
click.secho(f"β An error occurred: {str(e)}", fg='red')
@px.command('status')
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def px_status(region, az):
"""π Monitor resource usage of a Proxmox host."""
# click.secho(f"π Debug: Loading configuration for region '{region}' and availability zone '{az}'", fg='yellow')
config = load_config()
host_details = config['regions'][region]['availability_zones'][az]
# click.secho(f"π Debug: Retrieved host details: {host_details}", fg='yellow')
host = host_details['host']
user = host_details['user']
ssh_password = host_details['ssh_password']
commands = {
"Load Avg": ["cat", "/proc/loadavg"],
"Memory Info": ["cat", "/proc/meminfo"],
"Disk Space": ["df", "-h", "/"],
"Swap Space": ["cat", "/proc/swaps"]
}
for metric_name, command in commands.items():
result = run_ssh_command(host, user, ssh_password, command)
if result and result.returncode == 0:
output = result.stdout.strip()
if metric_name == "Load Avg":
loadavg = output.split()[0:3]
click.secho(f"π Proxmox {host} - {metric_name}: {' '.join(loadavg)}", fg='cyan')
elif metric_name == "Memory Usage":
meminfo_lines = output.splitlines()
meminfo_dict = {line.split(":")[0]: line.split(":")[1].strip() for line in meminfo_lines if line}
mem_total = meminfo_dict["MemTotal"].split()[0]
mem_free = meminfo_dict["MemFree"].split()[0]
mem_used = int(mem_total) - int(mem_free)
click.secho(f"π Proxmox {host} - {metric_name}: Used {mem_used} kB / {mem_total} kB", fg='cyan')
elif metric_name == "Disk Space":
disk_info = output.splitlines()[1] # Assuming the first line is headers
click.secho(f"π Proxmox {host} - {metric_name}: {disk_info}", fg='cyan')
elif metric_name == "Swap Space":
swap_info_lines = output.splitlines()[1:] # First line is header
for swap_info in swap_info_lines:
swap_details = swap_info.split()
swap_name = swap_details[0]
swap_size = swap_details[2]
swap_used = swap_details[3]
click.secho(f"π Proxmox {host} - {metric_name}: {swap_used} kB used / {swap_size} kB total ({swap_name})", fg='cyan')
else:
click.secho(f"β Failed to retrieve {metric_name} on host {host}: {result.stderr if result else 'Unknown error'}", fg='red')
@px.command('clusters')
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def px_list_clusters(region, az):
"""π List all clusters in the Proxmox environment."""
# Load configuration
config = load_config()
host_details = config['regions'][region]['availability_zones'][az]
host = host_details['host']
user = host_details['user']
ssh_password = host_details['ssh_password']
# Command to list cluster status using pvecm
command = ["pvecm", "status"]
# Execute the command on the Proxmox host using SSH
result = run_ssh_command(host, user, ssh_password, command)
# Output the result of the command
if result.returncode == 0:
click.secho(f"π Clusters:\n{result.stdout}", fg='cyan')
else:
click.secho(f"β Failed to list clusters: {result.stderr.strip()}", fg='red')
@px.command('update')
def px_update_hosts():
"""π Update all Proxmox hosts."""
command = ["apt-get", "update", "&&", "apt-get", "upgrade", "-y"]
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode == 0:
click.secho("β
All hosts updated successfully.", fg='green')
else:
click.secho(f"β Failed to update hosts: {result.stderr}", fg='red')
@px.command('cluster-start')
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def px_start_cluster_services(region, az):
"""π Start all cluster services on Proxmox hosts."""
# Load configuration
config = load_config()
host_details = config['regions'][region]['availability_zones'][az]
host = host_details['host']
user = host_details['user']
ssh_password = host_details['ssh_password']
# Command to start cluster services
command = ["systemctl", "start", "pve-cluster", "corosync"]
# Execute the command on the Proxmox host using SSH
result = run_ssh_command(host, user, ssh_password, command)
# Output the result of the command
if result.returncode == 0:
click.secho("β
Cluster services started successfully.", fg='green')
else:
click.secho(f"β Failed to start cluster services on host {host}: {result.stderr.strip()}", fg='red')
@px.command('cluster-stop')
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def px_stop_cluster_services(region, az):
"""π Stop all cluster services on Proxmox hosts."""
# Load configuration
config = load_config()
host_details = config['regions'][region]['availability_zones'][az]
host = host_details['host']
user = host_details['user']
ssh_password = host_details['ssh_password']
# Command to stop cluster services
command = ["systemctl", "stop", "pve-cluster", "corosync"]
# Execute the command on the Proxmox host using SSH
result = run_ssh_command(host, user, ssh_password, command)
# Output the result of the command
if result.returncode == 0:
click.secho("β
Cluster services stopped successfully.", fg='green')
else:
click.secho(f"β Failed to stop cluster services on host {host}: {result.stderr.strip()}", fg='red')
@px.command('cluster-restart')
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def px_restart_cluster_services(region, az):
"""π Restart all cluster services on Proxmox hosts."""
# Load configuration
config = load_config()
host_details = config['regions'][region]['availability_zones'][az]
host = host_details['host']
user = host_details['user']
ssh_password = host_details['ssh_password']
# Command to restart cluster services
command = ["systemctl", "restart", "pve-cluster", "corosync"]
# Execute the command on the Proxmox host using SSH
result = run_ssh_command(host, user, ssh_password, command)
# Output the result of the command
if result.returncode == 0:
click.secho("β
Cluster services restarted successfully.", fg='green')
else:
click.secho(f"β Failed to restart cluster services on host {host}: {result.stderr.strip()}", fg='red')
@px.command('backup-lxc')
@click.argument('vmid')
@click.option('--storage', required=True, help="The storage target where the backup will be stored.")
@click.option('--mode', default='snapshot', type=click.Choice(['snapshot', 'suspend', 'stop']), help="Backup mode: snapshot, suspend, or stop.")
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def px_create_backup(vmid, storage, mode, region, az):
"""πΎ Create a backup of a specific LXC container."""
# Load configuration
config = load_config()
host_details = config['regions'][region]['availability_zones'][az]
host = host_details['host']
user = host_details['user']
ssh_password = host_details['ssh_password']
# Command to create the backup
backup_cmd = ["vzdump", vmid, "--storage", storage, "--mode", mode]
# Execute the backup command on the Proxmox host
result = run_ssh_command(host, user, ssh_password, backup_cmd)
# Output the result of the command
if result.returncode == 0:
click.secho(f"β
Backup of instance {vmid} successfully created and stored on {storage}.", fg='green')
else:
click.secho(f"β Failed to create backup of instance {vmid}: {result.stderr.strip()}", fg='red')
# lxc
# Function to get the next available VMID
def get_next_vmid(start_vmid=10000, use_local_only=False, host_details=None):
"""
Generate the next available VMID by finding the highest existing VMID and incrementing it.
Parameters:
- start_vmid: The starting VMID to use if no containers exist.
- use_local_only: Boolean to determine if the command should be run locally or remotely.
- host_details: Dictionary containing the host, user, and ssh_password for remote execution.
Returns:
- The next available VMID as an integer.
"""
# Command to list the existing containers and their VMIDs
list_cmd = ["pct", "list"]
# Execute the command either locally or remotely
result = run_proxmox_command(list_cmd, list_cmd, use_local_only, host_details)
if result and result.returncode == 0:
existing_vmids = []
lines = result.stdout.splitlines()
for line in lines:
# Skip the header line and extract VMID from each line
if line.startswith("VMID"):
continue
vmid = int(line.split()[0])
existing_vmids.append(vmid)
# Find the next available VMID
if existing_vmids:
next_vmid = max(existing_vmids) + 1
else:
next_vmid = start_vmid
return next_vmid
else:
logging.error("β Failed to retrieve existing VMIDs. Defaulting to start_vmid.")
return start_vmid
# Command to run LXC instances
import time
def is_container_locked(instance_id, host_details):
"""Checks if the container is locked by using the pct config command."""
check_lock_cmd = ["pct", "config", str(instance_id)]
result = run_proxmox_command(check_lock_cmd, check_lock_cmd, config['use_local_only'], host_details)
if result.returncode == 0:
return 'lock' in result.stdout
else:
logging.error(f"β Failed to check lock status for instance {instance_id}: {result.stderr}")
return False # Assume it's not locked if the command fails to avoid indefinite retries
@lxc.command('run')
@click.option('--image-id', required=True, help="ID of the container image template.")
@click.option('--count', default=1, help="Number of instances to run.")
@click.option('--size', default='small', type=click.Choice(list(config['instance_sizes'].keys())), help="Instance size.")
@click.option('--hostname', default=None, help="Hostname for the container.")
@click.option('--net0', default=f"name=eth0,bridge={config.get('default_network', 'vmbr0')}", help="Network settings for the container.")
@click.option('--storage-size', default=None, help="Override storage size for the container (e.g., 16G).")
@click.option('--onboot', default=config.get('default_onboot', True), help="Start the container on boot.")
@click.option('--lock', default=None, help="Set lock for the container. By default, no lock is set.")
@click.option('--init', default=False, is_flag=True, help="Run initialization script after container creation.")
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1.")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1.")
@click.option('--max-retries', default=5, help="Maximum number of retries to start the container.")
@click.option('--retry-delay', default=5, help="Delay in seconds between retries.")
@click.option('--password', default=None, help="Set the root password for the container.")
@click.option('--ip', default=None, help="Set a fixed IP address for the container (e.g., 192.168.1.100).")
@click.option('--netmask', default='24', help="Set the netmask for the fixed IP address. Default is 24.")
@click.option('--gateway', default=None, help="Set the gateway for the container's network.")
@click.option('--dns', default=None, help="Set DNS servers for the container (comma-separated).")
@click.option('--dhcp', is_flag=True, default=False, help="Enable DHCP for the container.")
def run_instances(image_id, count, size, hostname, net0, storage_size, onboot, lock, init, region, az, max_retries, retry_delay, password, ip, netmask, gateway, dns, dhcp):
"""π οΈ Create and start LXC containers with optional network configuration, root password, gateway, and DNS settings."""
start_vmid = config.get('start_vmid', 10000)
instance_config = config['instance_sizes'][size]
storage = instance_config['storage']
if storage_size:
storage = f"{config['default_storage']}:{storage_size}"
host_details = config['regions'][region]['availability_zones'][az]
for i in range(count):
instance_id = get_next_vmid(start_vmid=start_vmid, use_local_only=config['use_local_only'], host_details=host_details)
create_cmd = [
"pct", "create", str(instance_id),
image_id,
"--memory", str(instance_config['memory']),
"--cpulimit", str(instance_config['cpulimit']),
"--net0", net0,
"--rootfs", storage,
"--onboot", str(int(onboot))
]
if lock:
create_cmd.extend(["--lock", lock])
if hostname:
create_cmd.extend(["--hostname", f"{hostname}-{instance_id}"])
if password:
create_cmd.extend(["--password", password])
# Set up network configuration
if dhcp:
create_cmd.extend(["--net0", f"{net0},ip=dhcp"])
elif ip:
net_config = f"{net0},ip={ip}/{netmask}"
if gateway:
net_config += f",gw={gateway}"
create_cmd.extend(["--net0", net_config])
# Add DNS settings if provided
if dns:
create_cmd.extend(["--nameserver", dns])
create_result = run_proxmox_command(create_cmd, create_cmd, config['use_local_only'], host_details)
if create_result.returncode == 0:
click.secho(f"β
Instance {instance_id} created successfully.", fg='green')
# Retry logic for starting the container
for attempt in range(max_retries):
if is_container_locked(instance_id, host_details):
click.secho(f"π Instance {instance_id} is locked. Retrying in {retry_delay} seconds... (Attempt {attempt + 1}/{max_retries})", fg='yellow')
time.sleep(retry_delay)
else:
start_result = run_proxmox_command(
["pct", "start", str(instance_id)],
["pct", "start", str(instance_id)],
config['use_local_only'],
host_details
)
if start_result.returncode == 0:
click.secho(f"π Instance {instance_id} started.", fg='green')
# Run an initialization script if the --init flag is set
if init:
init_cmd = ["pct", "exec", str(instance_id), "--", "/path/to/init-script.sh"]
init_result = run_proxmox_command(init_cmd, init_cmd, config['use_local_only'], host_details)
if init_result.returncode == 0:
click.secho(f"π§ Initialization script executed successfully on {instance_id}.", fg='green')
else:
click.secho(f"β Failed to execute initialization script on {instance_id}: {init_result.stderr}", fg='red')
break
else:
click.secho(f"β Failed to start instance {instance_id}: {start_result.stderr}", fg='red')
break
else:
click.secho(f"β Failed to start instance {instance_id} after {max_retries} attempts.", fg='red')
else:
click.secho(f"β Failed to create instance {instance_id}: {create_result.stderr}", fg='red')
@lxc.command('stop')
@click.argument('instance_ids', nargs=-1)
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def stop_instances(instance_ids, region, az):
"""π Stop running LXC containers."""
process_instance_command(instance_ids, 'stop', region, az)
@lxc.command('terminate')
@click.argument('instance_ids', nargs=-1)
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def terminate_instances(instance_ids, region, az):
"""π₯ Terminate (destroy) LXC containers."""
process_instance_command(instance_ids, 'terminate', region, az)
@lxc.command('show')
@click.argument('instance_ids', nargs=-1, required=False)
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def describe_instances(instance_ids, region, az):
"""π Describe LXC containers."""
if instance_ids:
process_instance_command(instance_ids, 'describe', region, az)
else:
host_details = config['regions'][region]['availability_zones'][az]
list_result = run_proxmox_command(["pct", "list"], ["pct", "list"], config['use_local_only'], host_details)
if list_result.returncode == 0:
click.secho(f"π Instances:\n{list_result.stdout}", fg='cyan')
else:
click.secho(f"β Failed to list instances: {list_result.stderr}", fg='red')
@lxc.command('scale')
@click.argument('instance_ids', nargs=-1)
@click.option('--memory', default=None, help="New memory size in MB.")
@click.option('--cpulimit', default=None, help="New CPU limit.")
@click.option('--cpucores', default=None, help="New number of CPU cores.")
@click.option('--storage-size', default=None, help="New root storage size (e.g., 16G).")
@click.option('--net-limit', default=None, help="Network bandwidth limit (e.g., 10mbit).")
@click.option('--disk-read-limit', default=None, help="Disk read limit (e.g., 50mb).")
@click.option('--disk-write-limit', default=None, help="Disk write limit (e.g., 30mb).")
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def scale_instances(instance_ids, memory, cpulimit, cpucores, storage_size, net_limit, disk_read_limit, disk_write_limit, region, az):
"""π Scale resources LXC containers."""
# Retrieve the host details from the configuration
host_details = config['regions'][region]['availability_zones'][az]
host = host_details['host']
user = host_details['user']
ssh_password = host_details['ssh_password']
# Loop through each instance ID and apply the scaling configuration
for instance_id in instance_ids:
# Build the command to set the new resource parameters
scale_cmd = ["pct", "set", instance_id]
if memory:
scale_cmd.extend(["--memory", str(memory)])
if cpulimit:
scale_cmd.extend(["--cpulimit", str(cpulimit)])
if cpucores:
scale_cmd.extend(["--cores", str(cpucores)])
if storage_size:
scale_cmd.extend(["--rootfs", f"{config['default_storage']}:{storage_size}"])
if net_limit:
scale_cmd.extend(["--net0", f"rate={net_limit}"])
if disk_read_limit:
scale_cmd.extend(["--mp0", f"iops_rd={disk_read_limit}"])
if disk_write_limit:
scale_cmd.extend(["--mp0", f"iops_wr={disk_write_limit}"])
# Execute the scale command on the Proxmox host using SSH
result = run_proxmox_command(scale_cmd, scale_cmd, config['use_local_only'], host_details)
# Output the result of the command
if result.returncode == 0:
click.secho(f"β
Instance '{instance_id}' successfully scaled.", fg='green')
else:
click.secho(f"β Failed to scale instance '{instance_id}': {result.stderr.strip()}", fg='red')
@lxc.command('snapshot-add')
@click.argument('instance_id')
@click.argument('snapshot_name')
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def create_snapshot(instance_id, snapshot_name, region, az):
"""πΈ Create a snapshot of an LXC container."""
process_instance_command([instance_id], 'snapshot_create', region, az, snapshot_name=snapshot_name)
@lxc.command('snapshot-rm')
@click.argument('instance_id')
@click.argument('snapshot_name')
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def delete_snapshot(instance_id, snapshot_name, region, az):
"""ποΈ Delete a snapshot of an LXC container."""
process_instance_command([instance_id], 'snapshot_delete', region, az, snapshot_name=snapshot_name)
@lxc.command('snapshots')
@click.argument('instance_id')
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Defaults to eu-south-1.")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Defaults to az1.")
@click.option('--use-local-only', is_flag=False, help="Execute the command locally instead of via SSH.")
def snapshots(instance_id, region, az, use_local_only):
"""ποΈ List all snapshots of an LXC container."""
# Get the host details from the configuration
host_details = config['regions'][region]['availability_zones'][az]
# Command to list snapshots locally on the Proxmox node
local_cmd = ["pct", "listsnapshot", instance_id]
# Command to list snapshots remotely via SSH
remote_cmd = ["pct", "listsnapshot", instance_id]
# Execute the command using the run_proxmox_command utility
result = run_proxmox_command(local_cmd, remote_cmd, use_local_only, host_details)
if result is not None and result.returncode == 0:
click.echo(result.stdout)
else:
click.echo(f"Failed to list snapshots for LXC container {instance_id}.")
@lxc.command('start')
@click.argument('instance_ids', nargs=-1)
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def start_instances(instance_ids, region, az):
"""π Start stopped LXC containers."""
process_instance_command(instance_ids, 'start', region, az)
@lxc.command('reboot')
@click.argument('instance_ids', nargs=-1)
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def reboot_instances(instance_ids, region, az):
"""π Reboot running LXC containers."""
process_instance_command(instance_ids, 'reboot', region, az)
@px.command('image-add')
@click.argument('instance_id')
@click.argument('template_name')
@click.option('--region', '--location', default='eu-south-1', help="Region in which to operate. Default to eu-south-1")
@click.option('--az', '--node', default='az1', help="Availability zone (Proxmox host) to target. Default to az1")
def create_image(instance_id, template_name, region, az):
"""π¦ Create a template image from an LXC container."""
host_details = config['regions'][region]['availability_zones'][az]
# Stop the instance before converting to a template
stop_result = run_proxmox_command(["pct", "shutdown", instance_id], ["pct", "shutdown", instance_id], config['use_local_only'], host_details)