You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
3.3 KiB

import hashlib
import json
import shlex
from enum import Enum
def wrap(input: str, ws_base, max_length=70) -> str:
output: str = str()
if len(input) < max_length:
return input
temp = shlex.split(input, posix=False)
length = len(temp[0])
whitespace = str()
for _ in range(0, ws_base):
whitespace += " "
separator = " \\\n " + whitespace
for i in range(0, len(temp)):
if i < len(temp) - 1:
if length + len(temp[i]) < max_length:
output += " " + temp[i]
length += len(temp[i + 1])
else:
output += separator + temp[i]
length = len(temp[i]) + len(" \\\n\t\t")
else:
if length < max_length - len(temp[i]):
output += " " + temp[i]
else:
output += separator + temp[i]
return output
class NagObjectType(Enum):
Command = "command"
Comment = "comment"
ContactGroup = "contactgroup"
Contact = "contact"
HostDependency = "hostdependency"
HostEscalation = "hostescalation"
HostGroup = "hostgroup"
Host = "host"
ServiceDependency = "servicedependency"
ServiceEscalation = "serviceescalation"
ServiceGroup = "servicegroup"
Service = "service"
TimePeriod = "timeperiod"
Nil = "nil"
class NagObject:
def __init__(self,
config_file: str = str(),
directives: list[list[str]] = list(),
line_no: int = 0,
type: NagObjectType = NagObjectType.Nil):
self.m_config_file: str = config_file
self.m_directives: list[list[str]] = directives
self.m_line_no: int = line_no
self.m_type: NagObjectType = type
def __str__(self):
string = 'define {}'.format(self.m_type.value) + ' {\n'
ws_base = len(max([x[0] for x in self.m_directives], key=len)) + 4
for dir in self.m_directives:
num_whitespace = ws_base - len(dir[0])
whitespace = str()
for _ in range(0, num_whitespace):
whitespace += " "
string += ' {}{}{}\n'.format(
dir[0], whitespace,
wrap(dir[1], ws_base).strip().strip('\\\n').strip())
return string + '}\n'
def from_object(self, object: dict) -> None:
self.m_type.value = object['type']
self.m_config_file = object['config_file']
self.m_directives = object['directives']
self.m_line_no = object['line_number']
def to_object(self) -> dict:
object = {
'type': self.m_type.value,
'config_file': self.m_config_file,
'directives': self.m_directives,
'line_number': self.m_line_no
}
return object
def from_json(self, string: str) -> None:
self.from_object(json.loads(string))
def to_json(self) -> str:
return json.dumps(self.to_object)
def get_type(self) -> NagObjectType:
return self.m_type
def get_directives(self) -> list[list[str]]:
return self.m_directives
def get_config_hash(self) -> int:
hash = hashlib.sha256()
hash.update(self.m_config_file.encode('utf-8'))
digest = hash.hexdigest()
return int(digest,16) * 1000000
def get_id(self) -> int:
return self.get_config_hash() + self.m_line_no