Skip to content

Commit 1a8a690

Browse files
committed
expand list of the editable arguments
1 parent 5b3f6e8 commit 1a8a690

File tree

4 files changed

+71
-48
lines changed

4 files changed

+71
-48
lines changed

source/confParser.py

Lines changed: 38 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,40 @@
2727
import configparser
2828

2929

30-
def findKeyFile(path):
31-
for name in ["privkey.pem", "tls.key"]:
32-
for root, dirs, files in os.walk(path):
33-
if name in files:
34-
return name
35-
return None
36-
37-
38-
def findCertFile(path):
39-
for name in ["cert.pem", "tls.crt"]:
40-
for root, dirs, files in os.walk(path):
41-
if name in files:
42-
return name
43-
return None
30+
def checkFileExists(path, filename):
31+
for root, dirs, files in os.walk(path):
32+
if filename in files:
33+
return True
34+
return False
35+
36+
37+
def checkTLSsettings(args):
38+
if args.get('port') == 8443 and (not args.get('tlsKeyPath') or not args.get('tlsKeyFile') or not args.get('tlsCertFile')):
39+
return False, MSG['MissingParm']
40+
elif args.get('port') == 8443 and not os.path.exists(args.get('tlsKeyPath')):
41+
return False, MSG['KeyPathError']
42+
elif args.get('port') == 8443:
43+
if (not checkFileExists(args.get('tlsKeyPath'), args.get('tlsCertFile'))) or (not checkFileExists(args.get('tlsKeyPath'), args.get('tlsKeyFile'))):
44+
return False, MSG['CertError']
45+
return True, ''
46+
47+
48+
def getSettings(argv):
49+
settings = {}
50+
msg = ''
51+
args, msg = parse_cmd_args(argv)
52+
defaults = parse_defaults_from_config_file()
53+
if args and defaults:
54+
settings = merge_defaults_and_args(defaults, args)
55+
elif args:
56+
settings = args
57+
else:
58+
return None, msg
59+
# check TLS settings
60+
valid, msg = checkTLSsettings(settings)
61+
if valid:
62+
return settings, ''
63+
return None, msg
4464

4565

4666
def merge_defaults_and_args(defaults, args):
@@ -76,21 +96,13 @@ def parse_cmd_args(argv):
7696
NOTE: Per default ZIMon does not accept queries from remote machines. \
7797
To run the bridge from outside of the ZIMon collector, you need to modify ZIMon queryinterface settings (\'ZIMonCollector.cfg\')')
7898
parser.add_argument('-P', '--serverPort', action="store", type=int, default=9084, help='ZIMon collector port number (Default: 9084)')
79-
parser.add_argument('-l', '--logFile', action="store", default="./logs/zserver.log", help='location of the log file (Default: ./logs/zserver.log')
99+
parser.add_argument('-l', '--logPath', action="store", default="/var/log/ibm_bridge_for_grafana", help='location path of the log file (Default: /var/log/ibm_bridge_for_grafana')
100+
parser.add_argument('-f', '--logFile', action="store", default="zserver.log", help='Name of the log file (Default: zserver.log')
80101
parser.add_argument('-c', '--logLevel', action="store", type=int, default=logging.INFO, help='log level 10 (DEBUG), 20 (INFO), 30 (WARN), 40 (ERROR) (Default: 20)')
81102
parser.add_argument('-p', '--port', action="store", type=int, choices=[4242, 8443], default=4242, help='port number listening on for HTTP(S) connections (Default: 4242)')
82103
parser.add_argument('-t', '--tlsKeyPath', action="store", help='Directory path of tls privkey.pem and cert.pem file location (Required only for HTTPS port 8443)')
104+
parser.add_argument('-k', '--tlsKeyFile', action="store", help='Name of TLS key file, f.e.: privkey.pem (Required only for HTTPS port 8443)')
105+
parser.add_argument('-m', '--tlsCertFile', action="store", help='Name of TLS certificate file, f.e.: cert.pem (Required only for HTTPS port 8443)')
83106

84107
args = parser.parse_args(argv)
85-
86-
if args.port == 8443 and not args.tlsKeyPath:
87-
return None, MSG['MissingParm']
88-
elif args.port == 8443 and not os.path.exists(args.tlsKeyPath):
89-
return None, MSG['KeyPathError']
90-
elif args.port == 8443:
91-
certFile = findCertFile(args.tlsKeyPath)
92-
keyFile = findKeyFile(args.tlsKeyPath)
93-
if (not certFile) or (not keyFile):
94-
return None, MSG['CertError']
95-
96108
return args, ''

source/messages.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,5 +52,6 @@
5252
'TimerInfo': 'Processing {} took {} seconds',
5353
'Query2port': 'For better bridge performance multithreaded port {} will be used',
5454
'CollectorConnInfo': 'Connection to the collector server established successfully',
55-
'BridgeVersionInfo': ' *** IBM Spectrum Scale bridge for Grafana - Version: {} ***'
55+
'BridgeVersionInfo': ' *** IBM Spectrum Scale bridge for Grafana - Version: {} ***',
56+
'FileNotFound': 'The file {} not found.'
5657
}

source/zimonGrafanaIntf.py

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
from queryHandler import SensorConfig
3535
from __version__ import __version__
3636
from messages import ERR, MSG
37-
from confParser import parse_cmd_args, findCertFile, findKeyFile
37+
from confParser import getSettings
3838
from collections import defaultdict
3939
from timeit import default_timer as timer
4040

@@ -534,11 +534,11 @@ def processFormJSON(entity):
534534
cherrypy.serving.request.json = json.loads('{}')
535535

536536

537-
def configureLogging(logfile, loglevel):
537+
def configureLogging(logPath, logfile, loglevel):
538538
# create the logfile path if needed
539-
path, folder = os.path.split(logfile)
540-
if not os.path.exists(path):
541-
os.makedirs(path)
539+
if not os.path.exists(logPath):
540+
os.makedirs(logPath)
541+
logfile = os.path.join(logPath, logfile)
542542

543543
# prepare the logger
544544
logger = logging.getLogger('zimonGrafanaIntf')
@@ -556,32 +556,32 @@ def configureLogging(logfile, loglevel):
556556

557557
def validateCollectorConf(args, logger):
558558

559-
if not (args.server == 'localhost') and not (args.server == '127.0.0.1'):
559+
if not (args.get('server') == 'localhost') and not (args.get('server') == '127.0.0.1'):
560560
try:
561561
s = socket.socket()
562-
s.connect((args.server, args.serverPort))
562+
s.connect((args.get('server'), args.get('serverPort')))
563563
print(MSG['CollectorConnInfo'])
564564
finally:
565565
s.close()
566566
else:
567567
# get queryport
568568
foundPorts = SensorConfig.getCollectorPorts(logger)
569-
if foundPorts and str(args.serverPort) not in foundPorts:
569+
if foundPorts and str(args.get('serverPort')) not in foundPorts:
570570
raise Exception("Invalid serverPort specified. Try with: %s" % str(foundPorts))
571-
elif foundPorts[1] and not (args.serverPort == int(foundPorts[1])):
572-
args.serverPort = int(foundPorts[1])
573-
logger.info(MSG['Query2port'].format(args.serverPort))
571+
elif foundPorts[1] and not (args.get('serverPort') == int(foundPorts[1])):
572+
args['serverPort'] = int(foundPorts[1])
573+
logger.info(MSG['Query2port'].format(args['serverPort']))
574574

575575

576576
def updateCherrypyConf(args):
577577

578-
path, folder = os.path.split(args.logFile)
578+
path = args.get('logPath')
579579
if not os.path.exists(path):
580580
os.makedirs(path)
581581
accesslog = os.path.join(path, 'cherrypy_access.log')
582582
errorlog = os.path.join(path, 'cherrypy_error.log')
583583

584-
globalConfig = {'global': {'server.socket_port': args.port,
584+
globalConfig = {'global': {'server.socket_port': args.get('port'),
585585
'log.access_file': accesslog,
586586
'log.error_file': errorlog}}
587587

@@ -593,8 +593,8 @@ def updateCherrypyConf(args):
593593

594594

595595
def updateCherrypySslConf(args):
596-
certPath = os.path.join(args.tlsKeyPath, findCertFile(args.tlsKeyPath))
597-
keyPath = os.path.join(args.tlsKeyPath, findKeyFile(args.tlsKeyPath))
596+
certPath = os.path.join(args.get('tlsKeyPath'), args.get('tlsCertFile'))
597+
keyPath = os.path.join(args.get('tlsKeyPath'), args.get('tlsKeyFile'))
598598
sslConfig = {'global': {'server.ssl_module': 'builtin',
599599
'server.ssl_certificate': certPath,
600600
'server.ssl_private_key': keyPath}}
@@ -604,25 +604,26 @@ def updateCherrypySslConf(args):
604604
def main(argv):
605605

606606
# parse input arguments
607-
args, msg = parse_cmd_args(argv)
607+
args, msg = getSettings(argv)
608608
if not args:
609609
print(msg)
610+
return
610611

611612
# prepare the logger
612-
logger = configureLogging(args.logFile, args.logLevel)
613-
logger.info('zimonGrafanaItf invoked with parameters:%s', str(args))
613+
logger = configureLogging(args.get('logPath'), args.get('logFile'), args.get('logLevel'))
614614

615615
# prepare cherrypy server configuration
616616
updateCherrypyConf(args)
617-
if args.port == 8443:
617+
if args.get('port') == 8443:
618618
updateCherrypySslConf(args)
619619

620620
# prepare metadata
621621
try:
622622
print("\n" + MSG['BridgeVersionInfo'].format(__version__))
623623
logger.info("%s", MSG['BridgeVersionInfo'].format(__version__))
624+
logger.info('zimonGrafanaItf invoked with parameters:\n %s', "\n".join("{}={}".format(k, v) for k, v in args.items()))
624625
validateCollectorConf(args, logger)
625-
mdHandler = MetadataHandler(logger, args.server, args.serverPort)
626+
mdHandler = MetadataHandler(logger, args.get('server'), args.get('serverPort'))
626627
print(MSG['MetaSuccess'])
627628
print(MSG['ReceivAttrValues'].format('sensors', "\n\n" + "\t".join(mdHandler.metaData.sensorsSpec.keys())))
628629
except (AttributeError, ValueError, TypeError) as e:

tests/test_params.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33

44

55
def my_setup():
6-
global a, b, c
6+
global a, b, c, d, e
77
a = parse_defaults_from_config_file()
88
b, c = parse_cmd_args([])
9+
d, e = parse_cmd_args(['-p', '8443', '-t', '/etc/my_tls'])
910

1011

1112
def test_case01():
@@ -42,3 +43,11 @@ def test_case06():
4243
assert len(result.keys()) > 0
4344
assert 'port' in result.keys()
4445
assert 'serverPort' in result.keys()
46+
47+
48+
@with_setup(my_setup)
49+
def test_case07():
50+
result = merge_defaults_and_args(a, d)
51+
assert len(result.keys()) > 0
52+
assert 'port' in result.keys()
53+
assert result.get('port') == 8443

0 commit comments

Comments
 (0)