restructured a bit

This commit is contained in:
Rafael.Timmerberg 2013-08-20 00:49:04 +02:00
commit e8462537d3
3 changed files with 89 additions and 83 deletions

View file

@ -5,6 +5,7 @@ import imp
from layouts import Layout from layouts import Layout
from hostgroups import HostGroup from hostgroups import HostGroup
from members import Member from members import Member
from config import LinspectorConfig
from periods import CronPeriod, DatePeriod, IntervalPeriod from periods import CronPeriod, DatePeriod, IntervalPeriod
from lib.services.service import Service from lib.services.service import Service
@ -200,14 +201,17 @@ class FullConfigParser(ConfigParser):
:param configFilename: the configuration file to parse :param configFilename: the configuration file to parse
""" """
self.jsonDict = self._read_json_config(configFilename) self.jsonDict = self._read_json_config(configFilename)
# first step # first step
creator = lambda name, values: Layout(name,**values) creator = lambda name, values: Layout(name,**values)
layouts = self._create_raw_Object(self.jsonDict[KEY_LAYOUTS], "Layout", creator) layouts = self._create_raw_Object(self.jsonDict[KEY_LAYOUTS], "Layout", creator)
creator = lambda name, values: Member(name, **values) creator = lambda name, values: Member(name, **values)
members = self._create_raw_Object(self.jsonDict[KEY_MEMBERS], "Member", creator) members = self._create_raw_Object(self.jsonDict[KEY_MEMBERS], "Member", creator)
creator = lambda name, values: HostGroup(name, **values) creator = lambda name, values: HostGroup(name, **values)
self.hostgroups = self._create_raw_Object(self.jsonDict[KEY_HOSTGROUPS], "Hostgroup", creator) self.hostgroups = self._create_raw_Object(self.jsonDict[KEY_HOSTGROUPS], "Hostgroup", creator)
@ -248,6 +252,12 @@ class FullConfigParser(ConfigParser):
id_get_func = lambda hostgroup: hostgroup.get_name() id_get_func = lambda hostgroup: hostgroup.get_name()
self.replace_pointer(layouts, self.hostgroups, id_list_func, id_get_func) self.replace_pointer(layouts, self.hostgroups, id_list_func, id_get_func)
linConf = LinspectorConfig()
linConf.set_layouts(layouts)
linConf.set_hostgroups(self.hostgroups)
linConf.set_members(members)
linConf.set_periods(periods)
for hg in self.hostgroups: for hg in self.hostgroups:
for service in hg.get_services(): for service in hg.get_services():
service.set_hostgroup(hg) service.set_hostgroup(hg)
@ -255,4 +265,4 @@ class FullConfigParser(ConfigParser):
if "core" in self.jsonDict: if "core" in self.jsonDict:
core = self.jsonDict["core"] core = self.jsonDict["core"]
return layouts, core return linConf, core

View file

@ -4,47 +4,8 @@ Lish is the Linspector Interactive Shell...
This will become a commandline interface to Linspector. Think of a network switch or router like those from Cisco. This will become a commandline interface to Linspector. Think of a network switch or router like those from Cisco.
""" """
# what is this?
#from requests.status_codes import title
'''
#see http://docs.python.org/dev/library/argparse.html
Cheat Sheet:
++++++++++++ Argument Parser creation +++++++++++++++++
prog - The name of the program (default: sys.argv[0])
usage - The string describing the program usage (default: generated from arguments added to parser)
description - Text to display before the argument help (default: none)
epilog - Text to display after the argument help (default: none)
parents - A list of ArgumentParser objects whose arguments should also be included
formatter_class - A class for customizing the help output
prefix_chars - The set of characters that prefix optional arguments (default: -)
fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)
argument_default - The global default value for arguments (default: None)
conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)
++++++++++++++++++ add_argument() +++++++++++++++++++++
name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
action - The basic type of action to be taken when this argument is encountered at the command line.
nargs - The number of command-line arguments that should be consumed.
const - A constant value required by some action and nargs selections.
default - The value produced if the argument is absent from the command line.
type - The type to which the command-line argument should be converted.
choices - A container of the allowable values for the argument.
required - Whether or not the command-line option may be omitted (optionals only).
help - A brief description of what the argument does.
metavar - A name for the argument in usage messages.
dest - The name of the attribute to be added to the object returned by parse_args().
+++++++ add_subparsers()-> obj with one method -> add_parser() +++++++++
'''
from lib.frontends.frontend import Frontend from lib.frontends.frontend import Frontend
import argparse
import os import os
from shlex import split as shsplit from shlex import split as shsplit
from cmd import Cmd from cmd import Cmd
@ -58,8 +19,6 @@ class LishFrontend(Frontend):
print(kwargs) print(kwargs)
#self.jobs = kwargs["jobs"] #self.jobs = kwargs["jobs"]
ns = argparse.Namespace()
commander = LishCommander(kwargs) commander = LishCommander(kwargs)
run = True run = True
while run: while run:
@ -74,10 +33,25 @@ class LishFrontend(Frontend):
run = False run = False
class Exit(Cmd, object): class CommandBase(Cmd, object):
def __init__(self):
super(CommandBase, self).__init__()
self._needs_update = False
def get_completion(self, args, text, showOnZeroText=True):
if len(text) == 0 and showOnZeroText:
return args
else:
return [x for x in args if x.startswith(text)]
class Exit(CommandBase, object):
def __init__(self): def __init__(self):
super(Exit, self).__init__() super(Exit, self).__init__()
self._canExit = False self.set_can_exit(False)
def set_can_exit(self, canExit=True):
self._canExit = canExit
def can_exit(self): def can_exit(self):
return self._canExit return self._canExit
@ -101,13 +75,24 @@ class LogCommander(Cmd, object):
print("manage logging") print("manage logging")
class ShellCommander(Cmd, object): class ShellCommander(CommandBase, object):
def do_shell(self, text): def do_shell(self, text):
os.system(text) os.system(text)
def help_shell(self): def help_shell(self):
print("execute any shell command. Can also be achieved by a '!' postfix") print("execute any shell command. Can also be achieved by a '!' postfix")
def complete_shell(self, text, line, begidx, endidx):
try:
PATH = os.environ['PATH'].split(os.pathsep)
bins = []
for p in PATH:
bins.extend(os.listdir(p))
return self.get_completion(bins, text, False)
except:
pass
class HostgroupCommander(Exit, object): class HostgroupCommander(Exit, object):
def __init__(self, hostgroup): def __init__(self, hostgroup):
@ -133,7 +118,7 @@ class LishCommander(Exit, ShellCommander, LogCommander):
self.prompt = "<Lish>: " self.prompt = "<Lish>: "
self._layouts = kwargs["layouts"] self._linConf = kwargs["linspectorConfig"]
self._jobs = kwargs["jobs"] self._jobs = kwargs["jobs"]
self._scheduler = kwargs["scheduler"] self._scheduler = kwargs["scheduler"]
@ -144,32 +129,37 @@ class LishCommander(Exit, ShellCommander, LogCommander):
if args[0] == "list": if args[0] == "list":
print("current active Hostgroups:\n") print("current active Hostgroups:\n")
for l in self._layouts: for l in self._linConf.get_enabled_layouts():
if l.is_enabled(): print l.get_name()
print l.get_name() space = 4 * " "
space = 4 * " " for hg in l.get_hostgroups():
for hg in l.get_hostgroups(): print space + hg.get_name()
print space + hg.get_name()
print 3 * "\n" print 3 * "\n"
elif args[0] == "select": elif args[0] == "select":
hostgroupName = args[1] if len(args) < 2 or len(args[1]) == 0:
if len(hostgroupName) == 0: print("must select an hostgroup")
print "must select an hostgroup" else:
for layout in self._layouts: hgName = args[1]
for lhg in layout.get_hostgroups(): hg = self._linConf.get_hostgroup_by_name(hgName)
if lhg.get_name() == hostgroupName: if hg is None:
try: print("unknown hostgroup %s! type hostgroup list to get a list of hostgroups" % hgName)
hgCommander = HostgroupCommander(lhg) else:
hgCommander.cmdloop("Entering Hostmode of " + hostgroupName) try:
except KeyboardInterrupt, ke: hgCommander = HostgroupCommander(hg)
pass hgCommander.cmdloop("Entering Hostmode of " + hgName + ":\n")
except KeyboardInterrupt, ke:
pass
def help_hostgroup(self): def help_hostgroup(self):
print ''' print '''
help for Hostgroup usage:
hostgroup list
prints a list of all hostgroups
hostgroup select HOSTGROUPNAME
select a hostgroup to make changes on it
''' '''
def complete_hostgroup(self, text, line, begidx, endidx): def complete_hostgroup(self, text, line, begidx, endidx):
"hostgroup + ' '"
if begidx == 10: if begidx == 10:
return [x for x in self._hostgroupArgs if x.startswith(text)] if len(text) > 0 else self._hostgroupArgs return [x for x in self._hostgroupArgs if x.startswith(text)] if len(text) > 0 else self._hostgroupArgs

View file

@ -55,26 +55,32 @@ def main():
if args.action == "start": if args.action == "start":
configParser = FullConfigParser(log) configParser = FullConfigParser(log)
layouts, core = configParser.parse_config(args.config) linConf, core = configParser.parse_config(args.config)
scheduler = Scheduler() scheduler = Scheduler()
scheduler.start() scheduler.start()
jobs = [] jobs = []
for layout in layouts:
if layout.is_enabled():
for hostgroup in layout.get_hostgroups():
for service in hostgroup.get_services():
for host in hostgroup.get_hosts():
for period in service.get_periods():
job = Job(service, host, hostgroup.get_members(), hostgroup.get_processors())
schedulerJob = period.createJob(scheduler, job, handleJob)
if schedulerJob is not None:
job.set_job(schedulerJob)
job.set_logger(log)
jobs.append(job)
frontend = LishFrontend(jobs=jobs, scheduler=scheduler, layouts=layouts)
for layout in linConf.get_enabled_layouts():
for hostgroup in layout.get_hostgroups():
for service in hostgroup.get_services():
for host in hostgroup.get_hosts():
for period in service.get_periods():
job = Job(service, host, hostgroup.get_members(), hostgroup.get_processors())
schedulerJob = period.createJob(scheduler, job, handleJob)
if schedulerJob is not None:
job.set_job(schedulerJob)
job.set_logger(log)
jobs.append(job)
frontend = LishFrontend(jobs=jobs, scheduler=scheduler, linspectorConfig=linConf)
log.d("shutting down scheduler")
scheduler.shutdown(wait=False)
elif args.action == "stop": elif args.action == "stop":