osism 0.20250701.0__py3-none-any.whl → 0.20250709.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
osism/api.py CHANGED
@@ -208,11 +208,11 @@ async def notifications_baremetal(notification: NotificationBaremetal) -> None:
208
208
 
209
209
 
210
210
  @app.post(
211
- "/v1/switches/{identifier}/ztp/complete",
211
+ "/v1/sonic/{identifier}/ztp/complete",
212
212
  response_model=DeviceSearchResult,
213
- tags=["switches"],
213
+ tags=["sonic"],
214
214
  )
215
- async def switches_ztp_complete(identifier: str) -> DeviceSearchResult:
215
+ async def sonic_ztp_complete(identifier: str) -> DeviceSearchResult:
216
216
  """Mark a switch as ZTP complete by setting provision_state to active."""
217
217
  if not utils.nb:
218
218
  raise HTTPException(
osism/commands/manage.py CHANGED
@@ -1,8 +1,5 @@
1
1
  # SPDX-License-Identifier: Apache-2.0
2
2
 
3
- import json
4
- import os
5
- from datetime import datetime
6
3
  from re import findall
7
4
  from urllib.parse import urljoin
8
5
 
@@ -10,12 +7,10 @@ from cliff.command import Command
10
7
  import docker
11
8
  from jinja2 import Template
12
9
  from loguru import logger
13
- import paramiko
14
10
  import requests
15
11
 
16
12
  from osism.data import TEMPLATE_IMAGE_CLUSTERAPI, TEMPLATE_IMAGE_OCTAVIA
17
13
  from osism.tasks import openstack, ansible, handle_task
18
- from osism import utils
19
14
 
20
15
  SUPPORTED_CLUSTERAPI_K8S_IMAGES = ["1.31", "1.32", "1.33"]
21
16
 
@@ -389,249 +384,3 @@ class Dnsmasq(Command):
389
384
  )
390
385
 
391
386
  return handle_task(task, wait, format="log", timeout=300)
392
-
393
-
394
- class Sonic(Command):
395
- def get_parser(self, prog_name):
396
- parser = super(Sonic, self).get_parser(prog_name)
397
- parser.add_argument(
398
- "hostname", type=str, help="Hostname of the SONiC switch to manage"
399
- )
400
- parser.add_argument(
401
- "--reload",
402
- action="store_true",
403
- help="Execute config reload after config load to restart services",
404
- )
405
- return parser
406
-
407
- def take_action(self, parsed_args):
408
- hostname = parsed_args.hostname
409
- reload_config = parsed_args.reload
410
- today = datetime.now().strftime("%Y%m%d")
411
-
412
- try:
413
- # Get device from NetBox - try by name first, then by inventory_hostname
414
- device = utils.nb.dcim.devices.get(name=hostname)
415
- if not device:
416
- # Try to find by inventory_hostname custom field
417
- devices = utils.nb.dcim.devices.filter(cf_inventory_hostname=hostname)
418
- if devices:
419
- device = devices[0] # Take the first match
420
- logger.info(f"Device found by inventory_hostname: {device.name}")
421
- else:
422
- logger.error(
423
- f"Device {hostname} not found in NetBox (searched by name and inventory_hostname)"
424
- )
425
- return 1
426
-
427
- # Get device configuration from local_context_data
428
- if (
429
- not hasattr(device, "local_context_data")
430
- or not device.local_context_data
431
- ):
432
- logger.error(f"Device {hostname} has no local_context_data in NetBox")
433
- return 1
434
-
435
- config_context = device.local_context_data
436
-
437
- # Save config context to local /tmp directory
438
- config_context_file = f"/tmp/config_db_{hostname}_{today}.json"
439
- try:
440
- with open(config_context_file, "w") as f:
441
- json.dump(config_context, f, indent=2)
442
- logger.info(f"Config context saved to {config_context_file}")
443
- except Exception as e:
444
- logger.error(f"Failed to save config context: {e}")
445
- return 1
446
-
447
- # Extract SSH connection details
448
- ssh_host = None
449
- ssh_username = None
450
-
451
- # Try to get SSH details from config context
452
- if "management" in config_context:
453
- mgmt = config_context["management"]
454
- if "ip" in mgmt:
455
- ssh_host = mgmt["ip"]
456
- if "username" in mgmt:
457
- ssh_username = mgmt["username"]
458
-
459
- # Fallback: try to get OOB IP from NetBox
460
- if not ssh_host:
461
- from osism.tasks.conductor.netbox import get_device_oob_ip
462
-
463
- oob_result = get_device_oob_ip(device)
464
- if oob_result:
465
- ssh_host = oob_result[0]
466
-
467
- if not ssh_host:
468
- logger.error(f"No SSH host found for device {hostname}")
469
- return 1
470
-
471
- if not ssh_username:
472
- ssh_username = "admin" # Default SONiC username
473
-
474
- # SSH private key path
475
- ssh_key_path = "/ansible/secrets/id_rsa.operator"
476
-
477
- if not os.path.exists(ssh_key_path):
478
- logger.error(f"SSH private key not found at {ssh_key_path}")
479
- return 1
480
-
481
- logger.info(
482
- f"Connecting to {hostname} ({ssh_host}) to backup SONiC configuration"
483
- )
484
-
485
- # Create SSH connection
486
- ssh = paramiko.SSHClient()
487
- ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
488
-
489
- try:
490
- # Connect with private key
491
- ssh.connect(
492
- hostname=ssh_host,
493
- username=ssh_username,
494
- key_filename=ssh_key_path,
495
- timeout=30,
496
- )
497
-
498
- # Generate backup filename with date and increment on switch
499
- base_backup_path = f"/home/admin/config_db_{hostname}_{today}"
500
- backup_filename = f"{base_backup_path}_1.json"
501
-
502
- # Find next available filename on switch
503
- x = 1
504
- while True:
505
- check_cmd = f"ls {base_backup_path}_{x}.json 2>/dev/null"
506
- stdin, stdout, stderr = ssh.exec_command(check_cmd)
507
- if stdout.read().decode().strip() == "":
508
- backup_filename = f"{base_backup_path}_{x}.json"
509
- break
510
- x += 1
511
-
512
- logger.info(
513
- f"Backing up current configuration on switch to {backup_filename}"
514
- )
515
-
516
- # Backup current configuration on switch
517
- backup_cmd = f"sudo cp /etc/sonic/config_db.json {backup_filename}"
518
- stdin, stdout, stderr = ssh.exec_command(backup_cmd)
519
- exit_status = stdout.channel.recv_exit_status()
520
-
521
- if exit_status != 0:
522
- error_msg = stderr.read().decode()
523
- logger.error(
524
- f"Failed to backup configuration on switch: {error_msg}"
525
- )
526
- return 1
527
-
528
- logger.info("Configuration backed up successfully on switch")
529
-
530
- # Upload local config context to switch /tmp directory
531
- switch_config_file = f"/tmp/config_db_{hostname}_current.json"
532
- logger.info(
533
- f"Uploading config context to {switch_config_file} on switch"
534
- )
535
-
536
- # Use SFTP to upload the config context file
537
- sftp = ssh.open_sftp()
538
- try:
539
- sftp.put(config_context_file, switch_config_file)
540
- logger.info(
541
- f"Config context successfully uploaded to {switch_config_file} on switch"
542
- )
543
- except Exception as e:
544
- logger.error(f"Failed to upload config context to switch: {e}")
545
- return 1
546
- finally:
547
- sftp.close()
548
-
549
- # Load and apply the new configuration
550
- logger.info("Loading and applying new configuration on switch")
551
-
552
- load_cmd = f"sudo config load -y {switch_config_file}"
553
- stdin, stdout, stderr = ssh.exec_command(load_cmd)
554
- exit_status = stdout.channel.recv_exit_status()
555
-
556
- if exit_status != 0:
557
- error_msg = stderr.read().decode()
558
- logger.error(f"Failed to load configuration: {error_msg}")
559
- return 1
560
-
561
- logger.info("Configuration loaded and applied successfully")
562
-
563
- # Optionally reload configuration to restart services
564
- config_operations_successful = True
565
- if reload_config:
566
- logger.info("Reloading configuration to restart services")
567
-
568
- reload_cmd = "sudo config reload -y"
569
- stdin, stdout, stderr = ssh.exec_command(reload_cmd)
570
- exit_status = stdout.channel.recv_exit_status()
571
-
572
- if exit_status != 0:
573
- error_msg = stderr.read().decode()
574
- logger.error(f"Failed to reload configuration: {error_msg}")
575
- config_operations_successful = False
576
- else:
577
- logger.info("Configuration reloaded successfully")
578
-
579
- # Save configuration only if load (and optionally reload) were successful
580
- if config_operations_successful:
581
- logger.info("Saving configuration to persist changes")
582
-
583
- save_cmd = "sudo config save -y"
584
- stdin, stdout, stderr = ssh.exec_command(save_cmd)
585
- exit_status = stdout.channel.recv_exit_status()
586
-
587
- if exit_status != 0:
588
- error_msg = stderr.read().decode()
589
- logger.error(f"Failed to save configuration: {error_msg}")
590
- return 1
591
-
592
- logger.info("Configuration saved successfully")
593
- else:
594
- logger.warning("Skipping config save due to reload failure")
595
-
596
- # Delete the temporary configuration file
597
- logger.info(f"Cleaning up temporary file {switch_config_file}")
598
-
599
- delete_cmd = f"rm {switch_config_file}"
600
- stdin, stdout, stderr = ssh.exec_command(delete_cmd)
601
- exit_status = stdout.channel.recv_exit_status()
602
-
603
- if exit_status != 0:
604
- error_msg = stderr.read().decode()
605
- logger.warning(f"Failed to delete temporary file: {error_msg}")
606
- else:
607
- logger.info("Temporary file deleted successfully")
608
-
609
- logger.info("SONiC configuration management completed successfully")
610
- logger.info(f"- Config context saved locally to: {config_context_file}")
611
- if reload_config and config_operations_successful:
612
- logger.info("- Configuration loaded, reloaded, and saved on switch")
613
- elif config_operations_successful:
614
- logger.info("- Configuration loaded and saved on switch")
615
- else:
616
- logger.info(
617
- "- Configuration loaded on switch (save skipped due to reload failure)"
618
- )
619
- logger.info(f"- Backup created on switch: {backup_filename}")
620
-
621
- return 0
622
-
623
- except paramiko.AuthenticationException:
624
- logger.error(f"Authentication failed for {ssh_host}")
625
- return 1
626
- except paramiko.SSHException as e:
627
- logger.error(f"SSH connection failed: {e}")
628
- return 1
629
- except Exception as e:
630
- logger.error(f"Unexpected error during SSH operations: {e}")
631
- return 1
632
- finally:
633
- ssh.close()
634
-
635
- except Exception as e:
636
- logger.error(f"Error managing SONiC device {hostname}: {e}")
637
- return 1