diff --git a/Email.py b/Email.py index c6f1e9f..39994f0 100644 --- a/Email.py +++ b/Email.py @@ -5,6 +5,7 @@ from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText + def sendEmail (address, alarmDate, alarmLocation, alarmMessage, alarmSource): msg = MIMEMultipart() @@ -19,4 +20,17 @@ def sendEmail (address, alarmDate, alarmLocation, alarmMessage, alarmSource): s = smtplib.SMTP('mail.fhi-berlin.mpg.de') s.sendmail(address, address, msg.as_string()) - s.quit() \ No newline at end of file + s.quit() + + +def getMailAddress(currentHour, mailAddresses, timePeriods): + + periods = timePeriods.split(',') + + for n, period in enumerate(periods): + times = period.split('-') + if int(times[0]) <= currentHour < int(times[1]): + break + + addresses = mailAddresses.replace(' ','').split(',') + return addresses[n] \ No newline at end of file diff --git a/Environment.py b/Environment.py new file mode 100644 index 0000000..52d7328 --- /dev/null +++ b/Environment.py @@ -0,0 +1,17 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +def readSettings(file): + + f = open(file, 'r') + settings = {} + + for line in f: + if line.startswith('WC_'): + parts = line.replace(' ', '').replace('\n','').replace("'", "").split('=') + key = parts[0] + value = parts[1] + settings[key] = value + + f.close() + return settings \ No newline at end of file diff --git a/README b/README index 49b7479..6da72f0 100644 --- a/README +++ b/README @@ -63,3 +63,7 @@ To be able to import the wc_* tools append to the PYTHONPATH the webctrl directo 2) Set the python path inside the python script before the import statement: sys.path.append('/path/to/webctrl') + +Alle Argumente können via Kommandozeile UND via Env. Var. angegeben werden. Es werden KEINE Defaults gesetzt. +Die URL ist nur über die Env. Var. setzbar. +Das Passwort ist nur via Kommandozeile setzbar. diff --git a/SETTINGS b/SETTINGS new file mode 100644 index 0000000..8d44e34 --- /dev/null +++ b/SETTINGS @@ -0,0 +1,16 @@ +WC_USERNAME = 'wsdl' +#WC_NODE = '/trees/geographic' +WC_NODE = '/trees/geographic/#geb_e/#kaltw_erzeuger_fel/#km_speicher_fel' +WC_URL = 'https://webctrl.rz-berlin.mpg.de' +# wc_checkAlarms +WC_ALARMS_ALERT_EMAIL = 'weiher@fhi-berlin.mpg.de,weiher@fhi-berlin.mpg.de,weiher@fhi-berlin.mpg.de' +WC_ALARMS_ALERT_PERIODS = '8-16,16-22,22-8' +WC_ALARMS_INTERVAL = 1 +WC_ALARMS_TAKEACTION = 1 +# wc_getReport +WC_REPORT_TYPE = '~point-list-report' +# wc_getTrend +WC_TREND_STIME = '' +WC_TREND_ETIME = '' +WC_TREND_LIMIT = '' +WC_TREND_MAXREC = '' \ No newline at end of file diff --git a/wc_checkAlarms.py b/wc_checkAlarms.py index 778b949..17410f9 100644 --- a/wc_checkAlarms.py +++ b/wc_checkAlarms.py @@ -8,76 +8,126 @@ from alarm import alarm from time import sleep import datetime -from Email import sendEmail +from Email import sendEmail,getMailAddress +from Environment import readSettings def main(args): - # Check all arguments + + #################################################################################################################### + ### Check all arguments + #################################################################################################################### + + errorMessage = "No path to SETTINGS file specified. Provide one via '-f my_settingsFile' or {..., 'settingsFile':'my_settingsFile', ...}" try: - if args['username'] is None: - print 'No username specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['settingsFile'] is None or not args['settingsFile']: + print(errorMessage) sys.exit(1) else: - username = args['username'] + settingsFile = args['settingsFile'] + except KeyError: + print(errorMessage) + sys.exit(1) + settings = readSettings(settingsFile) + + errorMessage = "No username specified. Provide one via '-u my_username' or {..., 'username':'my_username', ...} or WC_USERNAME=my_username" + try: + if args['username'] is None or not args['username']: + if not settings['WC_USERNAME']: + print(errorMessage) + sys.exit(1) + else: + username = settings['WC_USERNAME'] + else: + username = str(args['username']) except KeyError: - print 'No "username" key specified. Please provide the key-value pair: \'username\':\'myUsername\'' + print(errorMessage) sys.exit(1) + # The password cannot be given via environment variable + errorMessage = "No password specified. Provide one via '-p my_password' or {..., 'password':'my_password', ...}" try: - if args['password'] is None: - print 'No password specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['password'] is None or not args['password']: + print(errorMessage) sys.exit(1) else: password = args['password'] except KeyError: - print 'No "password" key specified. Please provide the key-value pair: \'password\':\'myPassword\'' + print(errorMessage) sys.exit(1) + errorMessage = "No node specified. Provide one via '-n my_node' or {..., 'node':'my_node', ...} or WC_NODE=my_node" try: - if args['node'] is None: - print 'No path to a node specified. Check all options for this command via -h' - sys.exit(1) + if args['node'] is None or not args['node']: + if not settings['WC_NODE']: + print(errorMessage) + sys.exit(1) + else: + node = settings['WC_NODE'] + else: + node = str(args['node']) except KeyError: - print 'No "node" key specified. Please provide the key-value pair: \'node\':\'/my/node\'' + print(errorMessage) sys.exit(1) + errorMessage = "No URL specified. Provide one via WC_URL=my_url" + url = settings['WC_URL'] try: - if args['url'] is None: - print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' + if not url: + print(errorMessage) sys.exit(1) else: - wsdlFile = args['url'] + '/_common/webservices/Report?wsdl' + wsdlFile = url + '/_common/webservices/Report?wsdl' except KeyError: - print 'No "url" key specified. Please provide the key-value pair: \'url\':\'http://myURL.de\'' + print(errorMessage) sys.exit(1) + errorMessage = "No interval specified. Provide one via '-i my_interval' or {..., 'interval':'my_interval', ...} or WC_ALARMS_INTERVAL=my_interval" try: - if args['interval'] is None: - print 'No interval (in minutes) for checking for new alarms specified. Using a default.' - checkForNewAlarmsInterval = 1 + if args['interval'] is None or not args['interval']: + if float(settings['WC_ALARMS_INTERVAL']) is None: + print(errorMessage) + sys.exit(1) + else: + interval = float(settings['WC_ALARMS_INTERVAL']) else: - checkForNewAlarmsInterval = args['interval'] + interval = args['interval'] except KeyError: - print 'No "interval" key specified. Please provide the key-value pair: \'interval\':\'time in minutes\'' + print(errorMessage) + sys.exit(1) + if interval <= 0.0: + print 'The interval must be bigger than 0.0.' sys.exit(1) + checkForNewAlarmsInterval = interval + errorMessage = "No time to take action specified. Provide one via '-a my_takeAction' or {..., 'takeAction':'my_takeAction', ...} or WC_ALARMS_TAKEACTION=my_takeAction" try: - if args['takeAction'] is None: - print 'No time (in minutes) specified after which an action is taken in case an alarm is not acknowledged. Using a default.' - takeActionTime = 5 + if args['takeAction'] is None or not args['takeAction']: + if float(settings['WC_ALARMS_TAKEACTION']) is None: + print(errorMessage) + sys.exit(1) + else: + takeAction = float(settings['WC_ALARMS_TAKEACTION']) else: - takeActionTime = args['takeAction'] + takeAction = args['takeAction'] except KeyError: - print 'No "takeAction" key specified. Please provide the key-value pair: \'takeAction\':\'time in minutes\'' + print(errorMessage) sys.exit(1) + if takeAction <= 0.0: + print 'The time to take action must be bigger than 0.0.' + sys.exit(1) + takeActionTime = takeAction + if takeActionTime < checkForNewAlarmsInterval: print 'The time after which action is taken for not acknowledged alarms is smaller than the interval for checking' + \ 'for new alarms: ' + str(takeActionTime) + ' < ' + str(checkForNewAlarmsInterval) print 'The take action time should be bigger or equal to the checking for new alarms time. Exiting now...' sys.exit(1) + #################################################################################################################### + ### Connect to the webCTRL server + #################################################################################################################### - # Connect to the webCTRL server try: client = suds.client.Client(wsdlFile, username=username, password=password) except AttributeError: @@ -87,12 +137,15 @@ def main(args): sys.exit(1) except: print("Unexpected error:", sys.exc_info()[0]) - print('Perhaps your URL to the WSDL file is not correct.') + print('Perhaps your URL to the WSDL file, ' + wsdlFile + ', is not correct.') sys.exit(1) + #################################################################################################################### + ### Get the alarms and process them for as long as this script runs + #################################################################################################################### - alarmsActive = [] # running alarms waiting to be checked/acknowledged and, eventually, switched off - alarmsChecked = [] # alarms that are already acknowloedged or switched off + alarmsActive = [] # active alarms waiting to be checked/acknowledged and, eventually, switched off + alarmsChecked = [] # alarms that are already acknowledged or switched off # As long as this script runs get a report about all current alarms and their status every X seconds. The alarms are # managed in objects that will be deleted once the status of an alarm has switched to "Normal". It will be checked @@ -101,17 +154,15 @@ def main(args): while True: # Get a report about all current alarms in the network or in parts of the network (depending on the node setting) try: - report = client.service.runReport(args['node'], '~alarms', 'csv') + report = client.service.runReport(node, '~alarms', 'csv') except suds.WebFault as fault: print fault sys.exit(1) - #print report - - #lines = report.split("\n") - #lines = lines[1:] - file = open("testAlarms.txt", "r") - lines = file.read().split("\n") + lines = report.split("\n") + lines = lines[1:] + #file = open("testAlarms.txt", "r") + #lines = file.read().split("\n") # Go through the report and create alarm objects distinguishing by their current alarm status. # Start looping from the last line in order to process the oldest alarms first. @@ -170,11 +221,6 @@ def main(args): # Ignore the alarms that have a 'Normal' status without another matching alarm with 'Unnormal' # status because it's already solved pass - ## This should actually not happen: to have an alarm with status 'Normal' but to not find an - ## appropriate alarm with status 'Unnormal' - ##age = 0 - ##alarmsChecked.append(alarm(date, age, standort, message, quelle, bestaetigtVon, kategorie, status)) - ##print "This shouldn't have happened..." else: # Before appending the current alarm to the list of alarms check if this alarm is already contained # in the list: @@ -187,7 +233,7 @@ def main(args): a.age += checkForNewAlarmsInterval if not alarmAlreadyKnown: print('Appending alarm ' + str(date) + ' ' + quelle + ' to alarmsActive') - age = 0 + age = 0.0 alarmsActive.append(alarm(date, age, standort, message, quelle, bestaetigtVon, kategorie, status)) if alarmsChecked: @@ -199,32 +245,38 @@ def main(args): if alarmsActive: for a in alarmsActive: print(a.date, a.standort, a.message, a.quelle, a.bestaetigtVon, a.kategorie, a.status) - # Check the age of the still running alarms and take action in case of, for example, the age is greater than e.g. 20 min + # Check the age of the still active alarms and take action in case of, for example, the age is greater than e.g. 20 min print 'Age: ' + str(a.age) if a.age >= takeActionTime: - mailAddress = 'weiher@fhi-berlin.mpg.de' + currentHour = datetime.datetime.now().hour + mailAddress = getMailAddress(currentHour, settings['WC_ALARMS_ALERT_EMAIL'], settings['WC_ALARMS_ALERT_PERIODS']) print 'Sending an e-mail to ' + mailAddress sendEmail(mailAddress, a.date, a.standort, a.message, a.quelle) else: print('No alarms in list alarmsActive') + # sleep for n minutes sleep(checkForNewAlarmsInterval*60) -if __name__=='__main__': +# The argument parser is only called if this script is called as a script/executable (via command line) but not when +# imported by another script +if __name__ == '__main__': if len(sys.argv) < 2: print "You haven't specified any arguments. Use -h to get more details on how to use this command." sys.exit(1) parser = argparse.ArgumentParser() - parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') - parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') - parser.add_argument('--node', '-n', type=str, default='trees/geographic', + parser._action_groups.pop() + required = parser.add_argument_group('required arguments') + optional = parser.add_argument_group('optional arguments (can also be specified via SETTINGS file)') + required.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') + required.add_argument('--settingsFile', '-f', type=str, default=None, help='File name of settings containing WC_* variables') + optional.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') + optional.add_argument('--node', '-n', type=str, default=None, help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') - parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', - help="URL of the WebCTRL server as e.g. http://google.de") - parser.add_argument('-interval', '-i', type=int, default=1, help="Interval in MINUTES in which the script checks for new alarms") - parser.add_argument('-takeAction', '-a', type=int, default=1, help="Time in MINUTES after which an action is taken if an alarm still hasn't been acknowledged") + optional.add_argument('-interval', '-i', type=int, default=None, help="Interval in MINUTES in which the script checks for new alarms") + optional.add_argument('-takeAction', '-a', type=int, default=None, help="Time in MINUTES after which an action is taken if an alarm still hasn't been acknowledged") args = parser.parse_args() # Get the password if it hasn't been passed as argument diff --git a/wc_getReport.py b/wc_getReport.py index 14283c5..68a9a9d 100644 --- a/wc_getReport.py +++ b/wc_getReport.py @@ -6,59 +6,97 @@ import xml import argparse import getpass +from Environment import readSettings def main(args): - # Check all arguments + + #################################################################################################################### + ### Check all arguments + #################################################################################################################### + + errorMessage = "No path to SETTINGS file specified. Provide one via '-f my_settingsFile' or {..., 'settingsFile':'my_settingsFile', ...}" try: - if args['username'] is None: - print 'No username specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['settingsFile'] is None or not args['settingsFile']: + print(errorMessage) sys.exit(1) else: - username = args['username'] + settingsFile = args['settingsFile'] + except KeyError: + print(errorMessage) + sys.exit(1) + settings = readSettings(settingsFile) + + errorMessage = "No username specified. Provide one via '-u my_username' or {..., 'username':'my_username', ...} or WC_USERNAME=my_username" + try: + if args['username'] is None or not args['username']: + if not settings['WC_USERNAME']: + print(errorMessage) + sys.exit(1) + else: + username = settings['WC_USERNAME'] + else: + username = str(args['username']) except KeyError: - print 'No "username" key specified. Please provide the key-value pair: \'username\':\'myUsername\'' + print(errorMessage) sys.exit(1) + # The password cannot be given via environment variable + errorMessage = "No password specified. Provide one via '-p my_password' or {..., 'password':'my_password', ...}" try: - if args['password'] is None: - print 'No password specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['password'] is None or not args['password']: + print(errorMessage) sys.exit(1) else: password = args['password'] except KeyError: - print 'No "password" key specified. Please provide the key-value pair: \'password\':\'myPassword\'' + print(errorMessage) sys.exit(1) + errorMessage = "No node specified. Provide one via '-n my_node' or {..., 'node':'my_node', ...} or WC_NODE=my_node" try: - if args['node'] is None: - print 'No path to a node specified. Check all options for this command via -h' - sys.exit(1) + if args['node'] is None or not args['node']: + if not settings['WC_NODE']: + print(errorMessage) + sys.exit(1) + else: + node = settings['WC_NODE'] + else: + node = str(args['node']) except KeyError: - print 'No "node" key specified. Please provide the key-value pair: \'node\':\'/my/node\'' + print(errorMessage) sys.exit(1) + errorMessage = "No URL specified. Provide one via WC_URL=my_url" + url = settings['WC_URL'] try: - if args['url'] is None: - print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' + if not url: + print(errorMessage) sys.exit(1) else: - wsdlFile = args['url'] + '/_common/webservices/Report?wsdl' + wsdlFile = url + '/_common/webservices/Report?wsdl' except KeyError: - print 'No "url" key specified. Please provide the key-value pair: \'url\':\'http://myURL.de\'' + print(errorMessage) sys.exit(1) + errorMessage = "No report type specified. Provide one via '-t my_reportType' or {..., 'reportType':'my_reportType', ...} or WC_REPORT_TYPE=my_reportType" try: - if args['reportType'] is None: - print 'No report type specified. Using a default: ~point-list-report' + if args['reportType'] is None or not args['reportType']: + if not settings['WC_REPORT_TYPE']: + print(errorMessage) + sys.exit(1) + else: + reportType = settings['WC_REPORT_TYPE'] else: - reportType = args['reportType'] + reportType = str(args['reportType']) except KeyError: - print 'No "reportType" key specified. Please provide the key-value pair, e.g.: \'reportType\':\'~point-list-report\'' + print(errorMessage) sys.exit(1) + #################################################################################################################### + ### Connect to the webCTRL server + #################################################################################################################### - # Connect to the webCTRL server try: client = suds.client.Client(wsdlFile, username=username, password=password) except AttributeError: @@ -71,16 +109,16 @@ def main(args): print('Perhaps your URL to the WSDL file is not correct.') sys.exit(1) + #################################################################################################################### + ### Get the report + #################################################################################################################### - # Get the report try: - report = client.service.runReport(args['node'], reportType, 'csv') + report = client.service.runReport(node, reportType, 'csv') except suds.WebFault as fault: print fault sys.exit(1) - print report - # Split the report into separate lines and calculate the number of columns lines = report.split("\n") nColumns = len(lines[0].split(",")) @@ -123,19 +161,23 @@ def main(args): print c +# The argument parser is only called if this script is called as a script/executable (via command line) but not when +# imported by another script if __name__=='__main__': if len(sys.argv) < 2: print "You haven't specified any arguments. Use -h to get more details on how to use this command." sys.exit(1) parser = argparse.ArgumentParser() - parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') - parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') - parser.add_argument('--node', '-n', type=str, default=None, + parser._action_groups.pop() + required = parser.add_argument_group('required arguments') + optional = parser.add_argument_group('optional arguments (can also be specified via SETTINGS file)') + required.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') + required.add_argument('--settingsFile', '-f', type=str, default=None, help='File name of settings containing WC_* variables') + optional.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') + optional.add_argument('--node', '-n', type=str, default=None, help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') - parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', - help="URL of the WebCTRL server as e.g. http://google.de") - parser.add_argument('-reportType', '-t', type=str, default='~point-list-report', + optional.add_argument('-reportType', '-t', type=str, default=None, help="The type of the report: ~schedule-instance, ~effective-schedule, ~point-list-report, ~locked-value, \ ~network-io, ~test-and-balance, ~equipment-checkout, ~audit-log, ~alarms, ~alarm-source, ~network-status, \ ~module-version, ~security-assignment, ~alarm-messages, ~alarm-actions, ~trend-usage, ~parameter-mismatch") diff --git a/wc_getTrend.py b/wc_getTrend.py index e063a0a..b117ae6 100644 --- a/wc_getTrend.py +++ b/wc_getTrend.py @@ -5,62 +5,136 @@ import xml import argparse import getpass +from Environment import readSettings def main(args): - # Check all arguments + + #################################################################################################################### + ### Check all arguments + #################################################################################################################### + + errorMessage = "No path to SETTINGS file specified. Provide one via '-f my_settingsFile' or {..., 'settingsFile':'my_settingsFile', ...}" try: - if args['username'] is None: - print 'No username specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['settingsFile'] is None or not args['settingsFile']: + print(errorMessage) sys.exit(1) else: - username = args['username'] + settingsFile = args['settingsFile'] + except KeyError: + print(errorMessage) + sys.exit(1) + settings = readSettings(settingsFile) + + errorMessage = "No username specified. Provide one via '-u my_username' or {..., 'username':'my_username', ...} or WC_USERNAME=my_username" + try: + if args['username'] is None or not args['username']: + if not settings['WC_USERNAME']: + print(errorMessage) + sys.exit(1) + else: + username = settings['WC_USERNAME'] + else: + username = str(args['username']) except KeyError: - print 'No "username" key specified. Please provide the key-value pair: \'username\':\'myUsername\'' + print(errorMessage) sys.exit(1) + # The password cannot be given via environment variable + errorMessage = "No password specified. Provide one via '-p my_password' or {..., 'password':'my_password', ...}" try: - if args['password'] is None: - print 'No password specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['password'] is None or not args['password']: + print(errorMessage) sys.exit(1) else: password = args['password'] except KeyError: - print 'No "password" key specified. Please provide the key-value pair: \'password\':\'myPassword\'' + print(errorMessage) sys.exit(1) + errorMessage = "No node specified. Provide one via '-n my_node' or {..., 'node':'my_node', ...} or WC_NODE=my_node" try: - if args['node'] is None: - print 'No path to a node specified. Check all options for this command via -h' - sys.exit(1) + if args['node'] is None or not args['node']: + if not settings['WC_NODE']: + print(errorMessage) + sys.exit(1) + else: + node = settings['WC_NODE'] + else: + node = str(args['node']) except KeyError: - print 'No "node" key specified. Please provide the key-value pair: \'node\':\'/my/node\'' + print(errorMessage) sys.exit(1) + errorMessage = "No URL specified. Provide one via WC_URL=my_url" + url = settings['WC_URL'] try: - if args['url'] is None: - print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' + if not url: + print(errorMessage) sys.exit(1) else: - wsdlFile = args['url'] + '/_common/webservices/Trend?wsdl' + wsdlFile = url + '/_common/webservices/Report?wsdl' except KeyError: - print 'No "url" key specified. Please provide the key-value pair: \'url\':\'http://myURL.de\'' + print(errorMessage) sys.exit(1) + errorMessage = "No start time specified. Provide one via '-s my_stime' or {..., 'sTime':'my_sTime', ...} or WC_TREND_STIME=my_sTime. " \ + "sTime requires the following pattern: 'MM/DD/YYYY HH:MM:SS AM'. Using a default now." try: - if args['sTime'] is None: - print 'Use -s to define start date and time yourself. Now, a default is used.' + if args['sTime'] is None or not args['sTime']: + if not settings['WC_TREND_STIME']: + print(errorMessage) + sys.exit(1) + else: + sTime = settings['WC_TREND_STIME'] + else: + sTime = str(args['sTime']) except KeyError: - print 'No "sTime" key specified. Use -s to define start date and time yourself. Now, a default is used.' + print(errorMessage) + errorMessage = "No end time specified. Provide one via '-e my_eTime' or {..., 'eTime':'my_eTime', ...} or WC_TREND_ETIME=my_eTime. " \ + "eTime requires the following pattern: 'MM/DD/YYYY HH:MM:SS PM'. Using a default now." try: - if args['eTime'] is None: - print 'Use -e to define end date and time yourself. Now, a default is used.' + if args['eTime'] is None or not args['eTime']: + if not settings['WC_TREND_ETIME']: + print(errorMessage) + sys.exit(1) + else: + eTime = settings['WC_TREND_ETIME'] + else: + eTime = str(args['eTime']) + except KeyError: + print(errorMessage) + + errorMessage = "No parameter 'limit' specified. Provide one via '-l my_limit' or {..., 'limit':'my_limit', ...} or " \ + "WC_TREND_LIMIT=my_limit. limit=False: a maximum number of records, 'maxRecords', is retrieved from the start of the " \ + "specified time period. limit=True: 'maxRecords' are retrieved from the end of the time period. Now, " \ + "a default, limit=False, is set." + try: + if args['limit'] is None or not args['limit']: + if not settings['WC_TREND_LIMIT']: + print(errorMessage) + #sys.exit(1) + limit = False + else: + limit = settings['WC_TREND_LIMIT'] + else: + limit = str(args['limit']) except KeyError: - print 'No "eTime" key specified. Use -e to define end date and time yourself. Now, a default is used.' + print(errorMessage) + #sys.exit(1) + limit = False + + + # maxRec ... + # Default-Werte siehe unten + + + #################################################################################################################### + ### Connect to the webCTRL server + #################################################################################################################### - # Connect to the webCTRL server try: client = suds.client.Client(wsdlFile, username=username, password=password) except AttributeError: @@ -73,10 +147,12 @@ def main(args): print('Perhaps your URL to the WSDL file is not correct.') sys.exit(1) + #################################################################################################################### + ### Get the answer from the server + #################################################################################################################### - # Get the answer from the server and print the output try: - trendData = client.service.getTrendData(args['node'], args['sTime'], args['eTime'], args['limit'], args['maxRec']) + trendData = client.service.getTrendData(node, sTime, eTime, limit, args['maxRec']) except suds.WebFault as fault: print fault sys.exit(1) @@ -89,7 +165,8 @@ def main(args): sys.exit(1) -# The argument parser is only called if this script is called as a script/executable (via command line) but not when imported by another script +# The argument parser is only called if this script is called as a script/executable (via command line) but not when +# imported by another script if __name__=='__main__': if len(sys.argv) < 2: print "You haven't specified any arguments. Use -h to get more details on how to use this command." @@ -100,13 +177,13 @@ def main(args): parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') parser.add_argument('--node', '-n', type=str, default=None, help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') - parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', - help="URL of the WebCTRL server as e.g. http://google.de") + #parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', + # help="URL of the WebCTRL server as e.g. http://google.de") parser.add_argument('--sTime', '-s', type=str, default=None, help="Start Time. Returns trend data values starting with this time. Like this: 'MM/DD/YYYY HH:MM:SS AM'.") parser.add_argument('--eTime', '-e', type=str, default=None, help="End Time. Returns trend data values until this time. Like this: 'MM/DD/YYYY HH:MM:SS PM'.") - parser.add_argument('--limit', '-l', action='store_true', default=False, + parser.add_argument('--limit', '-l', action='store_true', default=None, help='If specified maxRecords are retrieved from the start. If not specified maxRecords are retrieved from the end.') parser.add_argument('--maxRec', '-m', type=int, default=10, help='Maximum number of records desired. Use a number >0 to limit records; use 0 to retrieve unlimited records.') diff --git a/wc_getValue.py b/wc_getValue.py index e78b92e..c885023 100644 --- a/wc_getValue.py +++ b/wc_getValue.py @@ -5,50 +5,83 @@ import xml import argparse import getpass +from Environment import readSettings def main(args): - # Check all arguments + + #################################################################################################################### + ### Check all arguments + #################################################################################################################### + + errorMessage = "No path to SETTINGS file specified. Provide one via '-f my_settingsFile' or {..., 'settingsFile':'my_settingsFile', ...}" try: - if args['username'] is None: - print 'No username specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['settingsFile'] is None or not args['settingsFile']: + print(errorMessage) sys.exit(1) else: - username = args['username'] + settingsFile = args['settingsFile'] except KeyError: - print 'No "username" key specified. Please provide the key-value pair: \'username\':\'myUsername\'' + print(errorMessage) sys.exit(1) + settings = readSettings(settingsFile) + errorMessage = "No username specified. Provide one via '-u my_username' or {..., 'username':'my_username', ...} or WC_USERNAME=my_username" try: - if args['password'] is None: - print 'No password specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['username'] is None or not args['username']: + if not settings['WC_USERNAME']: + print(errorMessage) + sys.exit(1) + else: + username = settings['WC_USERNAME'] + else: + username = str(args['username']) + except KeyError: + print(errorMessage) + sys.exit(1) + + # The password cannot be given via environment variable + errorMessage = "No password specified. Provide one via '-p my_password' or {..., 'password':'my_password', ...}" + try: + if args['password'] is None or not args['password']: + print(errorMessage) sys.exit(1) else: password = args['password'] except KeyError: - print 'No "password" key specified. Please provide the key-value pair: \'password\':\'myPassword\'' + print(errorMessage) sys.exit(1) + errorMessage = "No node specified. Provide one via '-n my_node' or {..., 'node':'my_node', ...} or WC_NODE=my_node" try: - if args['node'] is None: - print 'No path to a node specified. Check all options for this command via -h' - sys.exit(1) + if args['node'] is None or not args['node']: + if not settings['WC_NODE']: + print(errorMessage) + sys.exit(1) + else: + node = settings['WC_NODE'] + else: + node = str(args['node']) except KeyError: - print 'No "node" key specified. Please provide the key-value pair: \'node\':\'/my/node\'' + print(errorMessage) sys.exit(1) + errorMessage = "No URL specified. Provide one via WC_URL=my_url" + url = settings['WC_URL'] try: - if args['url'] is None: - print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' + if not url: + print(errorMessage) sys.exit(1) else: - wsdlFile = args['url'] + '/_common/webservices/Eval?wsdl' + wsdlFile = url + '/_common/webservices/Eval?wsdl' except KeyError: - print 'No "url" key specified. Please provide the key-value pair: \'url\':\'http://myURL.de\'' + print(errorMessage) sys.exit(1) + #################################################################################################################### + ### Connect to the webCTRL server + #################################################################################################################### - # Connect to the webCTRL server try: client = suds.client.Client(wsdlFile, username=username, password=password) except AttributeError: @@ -61,10 +94,12 @@ def main(args): print('Perhaps your URL to the WSDL file is not correct.') sys.exit(1) + #################################################################################################################### + ### Get the answer from the server and print the output + #################################################################################################################### - # Get the answer from the server and print the output try: - value = client.service.getValue(args['node']) + value = client.service.getValue(node) except suds.WebFault as fault: print fault sys.exit(1) @@ -73,22 +108,25 @@ def main(args): print "You haven't specified a particular controller. The command could look like this:" print '$ wc_getValue "#controller/m001"' else: - print "Present value of " + args['node'] + " is: " + value + print "Present value of " + node + " is: " + value -# The argument parser is only called if this script is called as a script/executable (via command line) but not when imported by another script +# The argument parser is only called if this script is called as a script/executable (via command line) but not when +# imported by another script if __name__=='__main__': if len(sys.argv) < 2: print "You haven't specified any arguments. Use -h to get more details on how to use this command." sys.exit(1) parser = argparse.ArgumentParser() - parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') - parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') - parser.add_argument('--node', '-n', type=str, default=None, + parser._action_groups.pop() + required = parser.add_argument_group('required arguments') + optional = parser.add_argument_group('optional arguments (can also be specified via SETTINGS file)') + required.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') + required.add_argument('--settingsFile', '-f', type=str, default=None, help='File name of settings containing WC_* variables') + optional.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') + optional.add_argument('--node', '-n', type=str, default=None, help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') - parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', - help="URL of the WebCTRL server as e.g. http://google.de") args = parser.parse_args() # Get the password if it hasn't been passed as argument diff --git a/wc_monitor.py b/wc_monitor.py index d4e0d6e..aa642ad 100644 --- a/wc_monitor.py +++ b/wc_monitor.py @@ -7,50 +7,83 @@ import getpass import time import datetime +from Environment import readSettings def main(args): - # Check all arguments + + #################################################################################################################### + ### Check all arguments + #################################################################################################################### + + errorMessage = "No path to SETTINGS file specified. Provide one via '-f my_settingsFile' or {..., 'settingsFile':'my_settingsFile', ...}" try: - if args['username'] is None: - print 'No username specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['settingsFile'] is None or not args['settingsFile']: + print(errorMessage) sys.exit(1) else: - username = args['username'] + settingsFile = args['settingsFile'] except KeyError: - print 'No "username" key specified. Please provide the key-value pair: \'username\':\'myUsername\'' + print(errorMessage) sys.exit(1) + settings = readSettings(settingsFile) + errorMessage = "No username specified. Provide one via '-u my_username' or {..., 'username':'my_username', ...} or WC_USERNAME=my_username" try: - if args['password'] is None: - print 'No password specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['username'] is None or not args['username']: + if not settings['WC_USERNAME']: + print(errorMessage) + sys.exit(1) + else: + username = settings['WC_USERNAME'] + else: + username = str(args['username']) + except KeyError: + print(errorMessage) + sys.exit(1) + + # The password cannot be given via environment variable + errorMessage = "No password specified. Provide one via '-p my_password' or {..., 'password':'my_password', ...}" + try: + if args['password'] is None or not args['password']: + print(errorMessage) sys.exit(1) else: password = args['password'] except KeyError: - print 'No "password" key specified. Please provide the key-value pair: \'password\':\'myPassword\'' + print(errorMessage) sys.exit(1) + errorMessage = "No node specified. Provide one via '-n my_node' or {..., 'node':'my_node', ...} or WC_NODE=my_node" try: - if args['node'] is None: - print 'No path to a node specified. Check all options for this command via -h' - sys.exit(1) + if args['node'] is None or not args['node']: + if not settings['WC_NODE']: + print(errorMessage) + sys.exit(1) + else: + node = settings['WC_NODE'] + else: + node = str(args['node']) except KeyError: - print 'No "node" key specified. Please provide the key-value pair: \'node\':\'/my/node\'' + print(errorMessage) sys.exit(1) + errorMessage = "No URL specified. Provide one via WC_URL=my_url" + url = settings['WC_URL'] try: - if args['url'] is None: - print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' + if not url: + print(errorMessage) sys.exit(1) else: - wsdlFile = args['url'] + '/_common/webservices/Eval?wsdl' + wsdlFile = url + '/_common/webservices/Eval?wsdl' except KeyError: - print 'No "url" key specified. Please provide the key-value pair: \'url\':\'http://myURL.de\'' + print(errorMessage) sys.exit(1) + #################################################################################################################### + ### Connect to the webCTRL server + #################################################################################################################### - # Connect to the webCTRL server try: client = suds.client.Client(wsdlFile, username=username, password=password) except AttributeError: @@ -63,22 +96,24 @@ def main(args): print('Perhaps your URL to the WSDL file is not correct.') sys.exit(1) + #################################################################################################################### + ### Go into an infinite loop and retrieve a value every second but only print it to the screen if the current value + ### is different from the last one; the loop is exited once CTRL+C is pressed + #################################################################################################################### - # Go into an infinite loop and retrieve a value every second but only print it to the screen if the current value - # is different from the last one; the loop is exited once CTRL+C is pressed currentValue = 0 try: while True: oldValue = currentValue try: - currentValue = client.service.getValue(args['node']) + currentValue = client.service.getValue(node) except suds.WebFault as fault: print fault sys.exit(1) if currentValue is None: print "You haven't specified a particular controller. The command could look like this:" - print '$ wc_getValue "#controller/m001"' + print '$ wc_monitor "#controller/m001"' sys.exit(1) elif currentValue != oldValue: print datetime.datetime.now().time().strftime("%H:%M:%S") + " " + currentValue @@ -89,19 +124,22 @@ def main(args): print('Exiting due to keyboard interupt...') -# The argument parser is only called if this script is called as a script/executable (via command line) but not when imported by another script -if __name__=='__main__': +# The argument parser is only called if this script is called as a script/executable (via command line) but not when +# imported by another script +if __name__ == '__main__': if len(sys.argv) < 2: print "You haven't specified any arguments. Use -h to get more details on how to use this command." sys.exit(1) parser = argparse.ArgumentParser() - parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') - parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') - parser.add_argument('--node', '-n', type=str, default=None, + parser._action_groups.pop() + required = parser.add_argument_group('required arguments') + optional = parser.add_argument_group('optional arguments (can also be specified via SETTINGS file)') + required.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') + required.add_argument('--settingsFile', '-f', type=str, default=None, help='File name of settings containing WC_* variables') + optional.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') + optional.add_argument('--node', '-n', type=str, default=None, help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') - parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', - help="URL of the WebCTRL server as e.g. http://google.de") args = parser.parse_args() # Get the password if it hasn't been passed as argument diff --git a/wc_query.py b/wc_query.py index 36774a0..a5ecada 100644 --- a/wc_query.py +++ b/wc_query.py @@ -5,50 +5,83 @@ import xml import argparse import getpass +from Environment import readSettings def main(args): - # Check all arguments + + #################################################################################################################### + ### Check all arguments + #################################################################################################################### + + errorMessage = "No path to SETTINGS file specified. Provide one via '-f my_settingsFile' or {..., 'settingsFile':'my_settingsFile', ...}" try: - if args['username'] is None: - print 'No username specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['settingsFile'] is None or not args['settingsFile']: + print(errorMessage) sys.exit(1) else: - username = args['username'] + settingsFile = args['settingsFile'] except KeyError: - print 'No "username" key specified. Please provide the key-value pair: \'username\':\'myUsername\'' + print(errorMessage) sys.exit(1) + settings = readSettings(settingsFile) + errorMessage = "No username specified. Provide one via '-u my_username' or {..., 'username':'my_username', ...} or WC_USERNAME=my_username" try: - if args['password'] is None: - print 'No password specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + if args['username'] is None or not args['username']: + if not settings['WC_USERNAME']: + print(errorMessage) + sys.exit(1) + else: + username = settings['WC_USERNAME'] + else: + username = str(args['username']) + except KeyError: + print(errorMessage) + sys.exit(1) + + # The password cannot be given via environment variable + errorMessage = "No password specified. Provide one via '-p my_password' or {..., 'password':'my_password', ...}" + try: + if args['password'] is None or not args['password']: + print(errorMessage) sys.exit(1) else: password = args['password'] except KeyError: - print 'No "password" key specified. Please provide the key-value pair: \'password\':\'myPassword\'' + print(errorMessage) sys.exit(1) + errorMessage = "No node specified. Provide one via '-n my_node' or {..., 'node':'my_node', ...} or WC_NODE=my_node" try: - if args['node'] is None: - print 'No path to a node specified. Check all options for this command via -h' - sys.exit(1) + if args['node'] is None or not args['node']: + if not settings['WC_NODE']: + print(errorMessage) + sys.exit(1) + else: + node = settings['WC_NODE'] + else: + node = str(args['node']) except KeyError: - print 'No "node" key specified. Please provide the key-value pair: \'node\':\'/my/node\'' + print(errorMessage) sys.exit(1) + errorMessage = "No URL specified. Provide one via WC_URL=my_url" + url = settings['WC_URL'] try: - if args['url'] is None: - print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' + if not url: + print(errorMessage) sys.exit(1) else: - wsdlFile = args['url'] + '/_common/webservices/Eval?wsdl' + wsdlFile = url + '/_common/webservices/Eval?wsdl' except KeyError: - print 'No "url" key specified. Please provide the key-value pair: \'url\':\'http://myURL.de\'' + print(errorMessage) sys.exit(1) + #################################################################################################################### + ### Connect to the webCTRL server + #################################################################################################################### - # Connect to the webCTRL server try: client = suds.client.Client(wsdlFile, username=username, password=password) except AttributeError: @@ -61,29 +94,34 @@ def main(args): print('Perhaps your URL to the WSDL file is not correct.') sys.exit(1) + #################################################################################################################### + ### Get the answer from the server + #################################################################################################################### - # Get the answer from the server and print the output try: - print 'Children of "' + args['node'] + '":' - print client.service.getChildren(args['node']) + print 'Children of "' + node + '":' + print client.service.getChildren(node) except suds.WebFault as fault: print fault sys.exit(1) -# The argument parser is only called if this script is called as a script/executable (via command line) but not when imported by another script -if __name__=='__main__': +# The argument parser is only called if this script is called as a script/executable (via command line) but not when +# imported by another script +if __name__ == '__main__': if len(sys.argv) < 2: print "You haven't specified any arguments. Use -h to get more details on how to use this command." sys.exit(1) parser = argparse.ArgumentParser() - parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') - parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') - parser.add_argument('--node', '-n', type=str, default=None, + parser._action_groups.pop() + required = parser.add_argument_group('required arguments') + optional = parser.add_argument_group('optional arguments (can also be specified via SETTINGS file)') + required.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') + required.add_argument('--settingsFile', '-f', type=str, default=None, help='File name of settings containing WC_* variables') + optional.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') + optional.add_argument('--node', '-n', type=str, default=None, help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') - parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', - help="URL of the WebCTRL server as e.g. http://google.de") args = parser.parse_args() # Get the password if it hasn't been passed as argument