Skip to content

Commit

Permalink
osfv_cli/osfv_cli: fixed zabbix files
Browse files Browse the repository at this point in the history
Signed-off-by: Mixss <michal.ziemiec@3mdeb.com>
  • Loading branch information
Mixss committed Sep 22, 2023
1 parent 92160e2 commit 53145c9
Show file tree
Hide file tree
Showing 4 changed files with 187 additions and 148 deletions.
79 changes: 60 additions & 19 deletions osfv_cli/osfv_cli/osfv_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@

import pexpect
import requests

from rte import RTE
from snipeit_api import SnipeIT
from sonoff_api import SonoffDevice
from zabbix import Zabbix


# Check out an asset
def check_out_asset(snipeit_api, asset_id):
success, data = snipeit_api.check_out_asset(asset_id)
Expand Down Expand Up @@ -112,6 +112,7 @@ def print_asset_details(asset):

print()


# extracts an asset to zabbix assets
def get_zabbix_compatible_assets_from_asset(asset):
result = {}
Expand All @@ -125,13 +126,14 @@ def get_zabbix_compatible_assets_from_asset(asset):
result[key] = field_value
return result


# Print asset details formatted as an input for Zabbix import script
def print_asset_details_for_zabbix(asset):

assets = get_zabbix_compatible_assets_from_asset(asset)
for key in assets.keys():
print(f"{key}: {assets[key]}")


def relay_toggle(rte, args):
state_str = rte.relay_get()
if state_str == "low":
Expand Down Expand Up @@ -282,19 +284,21 @@ def sonoff_tgl(sonoff, args):
except requests.exceptions.RequestException as e:
print(f"Failed to toggle Sonoff relay state. Error: {e}")


def ask_to_proceed(message="Do you want to proceed (y/n): "):
print("")
while True:
choice = input(message).lower()
if choice in ['y', 'n']:
return choice == 'y'
if choice in ["y", "n"]:
return choice == "y"
else:
print("Invalid input. Please enter 'y' or 'n'.")


def update_zabbix_assets(snipeit_api):
zabbix = Zabbix()
all_assets = snipeit_api.get_all_assets()

current_zabbix_assets = zabbix.get_all_hosts()
# snipeit assets but converted to zabbix-form assets
snipeit_assets = {}
Expand All @@ -305,28 +309,63 @@ def update_zabbix_assets(snipeit_api):
for asset in all_assets:
snipeit_assets.update(get_zabbix_compatible_assets_from_asset(asset))

keys_not_present_in_zabbix = set(snipeit_assets.keys()) - set(current_zabbix_assets.keys())
snipeit_assets_keys = list(snipeit_assets.keys())

duplicates = False
# check for duplicates
for i in range(snipeit_assets.__len__()):
for j in range(i + 1, snipeit_assets.__len__()):
if (
snipeit_assets[snipeit_assets_keys[i]]
== snipeit_assets[snipeit_assets_keys[j]]
):
print(
f"{snipeit_assets_keys[i]} has the same IP as {snipeit_assets_keys[j]}!"
)
duplicates = True
if snipeit_assets_keys[i] == snipeit_assets_keys[j]:
print(
f"There are at least 2 assets with name {snipeit_assets_keys[i]} present!"
)
duplicates = True

if duplicates:
print(
"\nSnipeIT configuration errors have been detected! Fix them and then continue."
)
return

keys_not_present_in_zabbix = set(snipeit_assets.keys()) - set(
current_zabbix_assets.keys()
)

keys_not_present_in_snipeit = set(current_zabbix_assets.keys()) - set(snipeit_assets.keys())
keys_not_present_in_snipeit = set(current_zabbix_assets.keys()) - set(
snipeit_assets.keys()
)

if keys_not_present_in_zabbix.__len__() > 0 or keys_not_present_in_snipeit.__len__() > 0:
if (
keys_not_present_in_zabbix.__len__() > 0
or keys_not_present_in_snipeit.__len__() > 0
):
update_available = True

common_keys = set(snipeit_assets.keys()) & set(current_zabbix_assets.keys())

if keys_not_present_in_zabbix.__len__() > 0:
print("Assets not present in Zabbix (these will be added):")
print('\n'.join(keys_not_present_in_zabbix))
print("\n".join(keys_not_present_in_zabbix))

if keys_not_present_in_snipeit.__len__() > 0:
print("\nAssets present in Zabbix but not in SnipeIT (these will be removed):")
print('\n'.join(keys_not_present_in_snipeit))
print("\n".join(keys_not_present_in_snipeit))

print("")
keys_for_ip_change = []
for key in common_keys:
if snipeit_assets[key] != current_zabbix_assets[key]:
print(f"{key} has wrong IP! (Zabbix one will be updated from {current_zabbix_assets[key]} to {snipeit_assets[key]})")
print(
f"{key} has wrong IP! (Zabbix one will be updated from {current_zabbix_assets[key]} to {snipeit_assets[key]})"
)
keys_for_ip_change.append(key)

if keys_for_ip_change.__len__() > 0:
Expand All @@ -339,21 +378,21 @@ def update_zabbix_assets(snipeit_api):
if not ask_to_proceed("Do you want to appply above changes? (y/n): "):
print("Changes were not applied")
return

# removing zabbix hosts
for key in keys_not_present_in_snipeit:
print(f"Removing {key}({current_zabbix_assets[key]})...")
result = zabbix.remove_host_by_name(key)
if "error" in result:
print("Failed to remove the host!")

# updating zabbix ips
for key in keys_for_ip_change:
print(f"Updating {key} IP to {snipeit_assets[key]}...")
result = zabbix.update_host_ip(key, snipeit_assets[key])
result = zabbix.update_host_ip(key, snipeit_assets[key])
if "error" in result:
print("Failed to change host's IP!")

# adding zabbix hosts
for key in keys_not_present_in_zabbix:
print(f"Adding {key}({snipeit_assets[key]})...")
Expand All @@ -362,6 +401,7 @@ def update_zabbix_assets(snipeit_api):
except ValueError:
print("Failed to add the host!")


# Main function
def main():
parser = argparse.ArgumentParser(description="Open Source Firmware Validation CLI")
Expand Down Expand Up @@ -413,8 +453,9 @@ def main():
)

update_zabbix_assets_parser = snipeit_subparsers.add_parser(
"update_zabbix", help="Syncs Zabbix assets with SnipeIT ones",
)
"update_zabbix",
help="Syncs Zabbix assets with SnipeIT ones",
)

check_out_parser = snipeit_subparsers.add_parser(
"check_out", help="Check out an asset by providing the Asset ID or RTE IP"
Expand Down
1 change: 0 additions & 1 deletion osfv_cli/osfv_cli/rte.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

import paramiko
import yaml

from rtectrl_api import rtectrl
from sonoff_api import SonoffDevice

Expand Down
Loading

0 comments on commit 53145c9

Please sign in to comment.