def GetAllConfigValues(FileName, section): ReturnDict = {} try: config = myconfig.MyConfig(filename=FileName, section=section) for (key, value) in config.GetList(): ReturnDict[key.lower()] = value except Exception as e1: LogErrorLine("Error GetAllConfigValues: " + FileName + ": " + str(e1)) return ReturnDict
if __name__=='__main__': # usage program.py [server_address] address='127.0.0.1' if len(sys.argv)<2 else sys.argv[1] # Set the signal handler signal.signal(signal.SIGINT, signal_handler) if os.geteuid() != 0: print("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.") sys.exit(2) console = mylog.SetupLogger("pushover_console", log_file = "", stream = True) log = mylog.SetupLogger("client", "/var/log/genpushover.log") try: config = myconfig.MyConfig(filename = '/etc/genpushover.conf', section = 'genpushover', log = log) appid = config.ReadValue('appid') userid = config.ReadValue('userid') pushsound = config.ReadValue('pushsound', default = 'updown') if appid == None or not len(appid): log.error("Error: invalid app ID") console.error("Error: invalid app ID") sys.exit(2) if userid == None or not len(userid): log.error("Error: invalid user ID") console.error("Error: invalid user ID") sys.exit(2)
def __init__(self, ConfigFilePath=None): super(Monitor, self).__init__() self.ProgramName = "Generator Monitor" self.Version = "Unknown" self.log = None self.IsStopping = False self.ProgramComplete = False if ConfigFilePath == None: self.ConfigFilePath = "/etc/" else: self.ConfigFilePath = ConfigFilePath self.ConnectionList = [] # list of incoming connections for heartbeat # defautl values self.SiteName = "Home" self.ServerSocket = None self.ServerSocketPort = 9082 # server socket for nagios heartbeat and command/status self.IncomingEmailFolder = "Generator" self.ProcessedEmailFolder = "Generator/Processed" self.FeedbackLogFile = os.path.dirname( os.path.realpath(__file__)) + "/feedback.json" self.LogLocation = "/var/log/" self.LastLogFileSize = 0 self.NumberOfLogSizeErrors = 0 # set defaults for optional parameters self.NewInstall = False # True if newly installed or newly upgraded version self.FeedbackEnabled = False # True if sending autoated feedback on missing information self.FeedbackMessages = {} self.MailInit = False # set to true once mail is init self.CommunicationsActive = False # Flag to let the heartbeat thread know we are communicating self.Controller = None self.ControllerSelected = None self.bDisablePlatformStats = False self.ReadOnlyEmailCommands = False self.SlowCPUOptimization = False # weather parameters self.WeatherAPIKey = None self.WeatherLocation = None self.UseMetric = False self.WeatherMinimum = True self.DisableWeather = False self.MyWeather = None # Time Sync Related Data self.bSyncTime = False # Sync gen to system time self.bSyncDST = False # sync time at DST change self.bDST = False # Daylight Savings Time active if True # simulation self.Simulation = False self.SimulationFile = None self.console = mylog.SetupLogger("genmon_console", log_file="", stream=True) if os.geteuid() != 0: self.LogConsole( "You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'." ) sys.exit(1) if not os.path.isfile(self.ConfigFilePath + 'genmon.conf'): self.LogConsole("Missing config file : " + self.ConfigFilePath + 'genmon.conf') sys.exit(1) if not os.path.isfile(self.ConfigFilePath + 'mymail.conf'): self.LogConsole("Missing config file : " + self.ConfigFilePath + 'mymail.conf') sys.exit(1) # log errors in this module to a file self.log = mylog.SetupLogger("genmon", self.LogLocation + "genmon.log") self.config = myconfig.MyConfig(filename=self.ConfigFilePath + 'genmon.conf', section="GenMon", log=self.console) # read config file if not self.GetConfig(): self.LogConsole("Failure in Monitor GetConfig") sys.exit(1) # log errors in this module to a file self.log = mylog.SetupLogger("genmon", self.LogLocation + "genmon.log") self.config.log = self.log if self.IsLoaded(): self.LogConsole("ERROR: genmon.py is already loaded.") self.LogError("ERROR: genmon.py is already loaded.") sys.exit(1) if self.NewInstall: self.LogError("New version detected: Old = %s, New = %s" % (self.Version, GENMON_VERSION)) self.Version = GENMON_VERSION self.ProgramStartTime = datetime.datetime.now() # used for com metrics atexit.register(self.Close) signal.signal(signal.SIGTERM, self.Close) signal.signal(signal.SIGINT, self.Close) # start thread to accept incoming sockets for nagios heartbeat and command / status clients self.Threads["InterfaceServerThread"] = mythread.MyThread( self.InterfaceServerThread, Name="InterfaceServerThread") # init mail, start processing incoming email self.mail = mymail.MyMail(monitor=True, incoming_folder=self.IncomingEmailFolder, processed_folder=self.ProcessedEmailFolder, incoming_callback=self.ProcessCommand) self.Threads = self.MergeDicts(self.Threads, self.mail.Threads) self.MailInit = True self.FeedbackPipe = mypipe.MyPipe("Feedback", self.FeedbackReceiver, log=self.log) self.Threads = self.MergeDicts(self.Threads, self.FeedbackPipe.Threads) self.MessagePipe = mypipe.MyPipe("Message", self.MessageReceiver, log=self.log, nullpipe=self.mail.DisableSNMP) self.Threads = self.MergeDicts(self.Threads, self.MessagePipe.Threads) try: #Starting device connection if self.Simulation: self.LogError("Simulation Running") if not self.ControllerSelected == None and len( self.ControllerSelected): self.LogError("Selected Controller: " + str(self.ControllerSelected)) else: self.ControllerSelected = "generac_evo_nexus" if self.ControllerSelected.lower() == "h_100": self.Controller = generac_HPanel.HPanel( self.log, newinstall=self.NewInstall, simulation=self.Simulation, simulationfile=self.SimulationFile, message=self.MessagePipe, feedback=self.FeedbackPipe, config=self.config) else: self.Controller = generac_evolution.Evolution( self.log, self.NewInstall, simulation=self.Simulation, simulationfile=self.SimulationFile, message=self.MessagePipe, feedback=self.FeedbackPipe, config=self.config) self.Threads = self.MergeDicts(self.Threads, self.Controller.Threads) except Exception as e1: self.FatalError("Error opening controller device: " + str(e1)) return None self.StartThreads() self.ProcessFeedbackInfo() # send mail to tell we are starting self.MessagePipe.SendMessage( "Generator Monitor Starting at " + self.SiteName, "Generator Monitor Starting at " + self.SiteName, msgtype="info") self.LogError("GenMon Loaded for site: " + self.SiteName)
# Set the signal handler signal.signal(signal.SIGINT, signal_handler) if os.geteuid() != 0: print( "You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting." ) sys.exit(2) console = mylog.SetupLogger("slack_console", log_file="", stream=True) log = mylog.SetupLogger("client", "/var/log/genslack.log") try: config = myconfig.MyConfig(filename='/etc/genslack.conf', section='genslack', log=log) webhook_url = config.ReadValue('webhook_url') channel = config.ReadValue('channel') username = config.ReadValue('username') icon_emoji = config.ReadValue('icon_emoji') title_link = config.ReadValue('title_link') except Exception as e1: log.error("Error reading /etc/genslack.conf: " + str(e1)) console.error("Error reading /etc/genslack.conf: " + str(e1)) sys.exit(1) try: GenNotify = mynotify.GenNotify(host=address,
if os.geteuid() != 0: LogConsole( "You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'." ) sys.exit(1) if not os.path.isfile(GENMON_CONFIG): LogConsole("Missing config file : " + GENMON_CONFIG) sys.exit(1) if not os.path.isfile(MAIL_CONFIG): LogConsole("Missing config file : " + MAIL_CONFIG) sys.exit(1) genmon_config = myconfig.MyConfig(filename=GENMON_CONFIG, section=GENMON_SECTION, log=console) mymail_config = myconfig.MyConfig(filename=MAIL_CONFIG, section=MAIL_SECTION, log=console) genloader_config = myconfig.MyConfig(filename=GENLOADER_CONFIG, section="genmon", log=console) AppPath = sys.argv[0] if not LoadConfig(): LogConsole("Error reading configuraiton file.") sys.exit(1) genmon_config.log = log mymail_config.log = log
def __init__(self, start=False, stop=False, hardstop=False, loglocation="/var/log/", log=None, localinit=False, ConfigFilePath=None): self.Start = start self.Stop = stop self.HardStop = hardstop if ConfigFilePath == None: self.ConfigFilePath = "/etc/" else: self.ConfigFilePath = ConfigFilePath self.ConfigFileName = "genloader.conf" # log errors in this module to a file if localinit == True: self.configfile = self.ConfigFileName else: self.configfile = self.ConfigFilePath + self.ConfigFileName self.ModulePath = os.path.dirname(os.path.realpath(__file__)) + "/" self.ConfPath = os.path.dirname(os.path.realpath(__file__)) + "/conf/" # log errors in this module to a file if log == None: self.log = mylog.SetupLogger("genloader", loglocation + "genloader.log") else: self.log = log self.console = mylog.SetupLogger("genloader_console", log_file="", stream=True) try: if self.Start: if not self.CheckSystem(): self.LogInfo("Error check system readiness. Exiting") sys.exit(2) self.CachedConfig = {} # check to see if genloader.conf is present, if not copy it from genmon directory if not os.path.isfile(self.configfile): self.LogInfo("Warning: unable to find config file: " + self.configfile + " Copying file to /etc/ directory.") if os.path.isfile(self.ConfPath + self.ConfigFileName): copyfile(self.ConfPath + self.ConfigFileName, self.configfile) else: self.LogInfo("Unable to find config file.") sys.exit(2) self.config = myconfig.MyConfig(filename=self.configfile, section="genmon", log=self.log) if not self.GetConfig(): self.LogInfo("Error reading config file. Exiting") sys.exit(2) if not self.ValidateConfig(): self.LogInfo("Error validating config. Exiting") sys.exit(2) self.LoadOrder = self.GetLoadOrder() if self.Stop: self.StopModules() time.sleep(2) if self.Start: self.StartModules() except Exception as e1: self.LogErrorLine("Error in init: " + str(e1))
def __init__(self, log=None): super(MyMQTT, self).__init__() self.LogFileName = "/var/log/genmqtt.log" if log != None: self.log = log else: # log errors in this module to a file self.log = mylog.SetupLogger("client", self.LogFileName) # cleanup # test self.console = mylog.SetupLogger("mymqtt_console", log_file="", stream=True) self.Username = None self.Password = None self.Address = None self.Topic = None self.MQTTAddress = "127.0.0.1" self.MonitorAddress = "127.0.0.1" self.Port = 1883 self.Topic = "generator" self.TopicRoot = None self.BlackList = None self.PollTime = 2 self.FlushInterval = float( 'inf') # default to inifite flush interval (e.g., never) self.Debug = False try: config = myconfig.MyConfig(filename='/etc/genmqtt.conf', section='genmqtt', log=log) if config.HasOption('username'): self.Username = config.ReadValue('username') if config.HasOption('password'): self.Password = config.ReadValue('password') self.MQTTAddress = config.ReadValue('mqtt_address') if config.HasOption('monitor_address'): self.MonitorAddress = config.ReadValue('monitor_address') if config.HasOption('mqtt_port'): self.MQTTPort = config.ReadValue('mqtt_port', return_type=int) if config.HasOption('poll_interval'): self.PollTime = config.ReadValue('poll_interval', return_type=float) if config.HasOption('root_topic'): self.TopicRoot = config.ReadValue('root_topic') if config.HasOption('blacklist'): BlackList = config.ReadValue('blacklist') self.BlackList = BlackList.strip().split(",") if config.HasOption('debug'): self.Debug = config.ReadValue('debug', return_type=bool) if config.HasOption('flush_interval'): self.FlushInterval = config.ReadValue('flush_interval', return_type=float) except Exception as e1: log.error("Error reading /etc/genmqtt.conf: " + str(e1)) console.error("Error reading /etc/genmqtt.conf: " + str(e1)) sys.exit(1) try: self.MQTTclient = mqtt.Client(client_id="genmon") if self.Username != None and len( self.Username) and self.Password != None: self.MQTTclient.username_pw_set(self.Username, password=self.Password) self.MQTTclient.on_connect = self.on_connect self.MQTTclient.on_message = self.on_message self.MQTTclient.connect(self.MQTTAddress, self.Port, 60) self.Push = MyGenPush(host=self.MonitorAddress, log=self.log, callback=self.PublishCallback, polltime=self.PollTime, blacklist=self.BlackList, flush_interval=self.FlushInterval) atexit.register(self.Close) signal.signal(signal.SIGTERM, self.Close) signal.signal(signal.SIGINT, self.Close) self.MQTTclient.loop_start() except Exception as e1: self.LogErrorLine("Error in MyMQTT init: " + str(e1)) self.console.error("Error in MyMQTT init: " + str(e1)) sys.exit(1)