From cfd8ac4c75f2f9038592510f24b96fde2a230e93 Mon Sep 17 00:00:00 2001 From: Allen Lin37 Date: Thu, 6 Apr 2017 11:30:08 -0400 Subject: [PATCH] refactoring nodelist and nodeattrib to use common code --- confluent_client/bin/nodeattrib | 120 +++++---------------------- confluent_client/bin/nodelist | 116 +++++++------------------- confluent_client/confluent/client.py | 101 ++++++++++++++++++++++ 3 files changed, 153 insertions(+), 184 deletions(-) diff --git a/confluent_client/bin/nodeattrib b/confluent_client/bin/nodeattrib index a05915c6..4d6678eb 100644 --- a/confluent_client/bin/nodeattrib +++ b/confluent_client/bin/nodeattrib @@ -28,18 +28,6 @@ if path.startswith('/opt'): import confluent.client as client -def attrrequested(attr, attrlist, seenattributes): - for candidate in attrlist: - truename = candidate - if candidate.startswith('hm'): - candidate = candidate.replace('hm', 'hardwaremanagement', 1) - if candidate == attr: - seenattributes.add(truename) - return True - elif '.' not in candidate and attr.startswith(candidate + '.'): - seenattributes.add(truename) - return True - return False argparser = optparse.OptionParser( usage='''\n %prog [options] noderange [list of attributes] \ \n %prog [options] noderange attribute1=value1,attribute2=value,... @@ -50,6 +38,8 @@ argparser.add_option('-c', '--clear', action='store_true', help='Clear variables') (options, args) = argparser.parse_args() + +#setting minimal output to only output current information showtype = 'current' requestargs=None try: @@ -60,101 +50,34 @@ except IndexError: session = client.Command() exitcode = 0 - #Sets attributes +nodetype="noderange" + if len(args) > 1: - #clears attribute - if options.clear: - targpath = '/noderange/{0}/attributes/all'.format(noderange) - keydata = {} - for attrib in args[1:]: - keydata[attrib] = None - for res in session.update(targpath, keydata): - if 'error' in res: - if 'errorcode' in res: - exitcode = res['errorcode'] - sys.stderr.write('Error: ' + res['error'] + '\n') - sys.exit(exitcode) - else: - if args[1] == 'all': + exitcode=client.updateattrib(session,args,nodetype, noderange, options) + try: + # setting user output to what the user inputs + if args[1] == 'all': showtype = 'all' elif args[1] == 'current': showtype = 'current' - elif "=" in args[1]: - try: - if len(args[1:]) > 1: - for val in args[1:]: - val = val.split('=') - exitcode=session.simple_noderange_command(noderange, 'attributes/all'.format(noderange), val[1], val[0]) - else: - val=args[1].split('=') - exitcode=session.simple_noderange_command(noderange, 'attributes/all'.format(noderange),val[1],val[0]) - except: - sys.stderr.write('Error: {0} not a valid expression\n'.format(str (args[1:]))) - exitcode = 1 - sys.exit(exitcode) - else: - requestargs = args[1:] + requestargs=args[2:] + except: + pass + +if exitcode != 0: + sys.exit(exitcode) # Lists all attributes if len(args) > 0: - seenattributes = set([]) - for res in session.read('/noderange/{0}/attributes/{1}'.format(noderange,showtype)): - if 'error' in res: - print "found error" - sys.stderr.write(res['error'] + '\n') - exitcode = 1 - continue - for node in res['databynode']: - for attr in res['databynode'][node]: - seenattributes.add(attr) - currattr = res['databynode'][node][attr] - if requestargs is None or attrrequested(attr, args[1:], seenattributes): - if 'value' in currattr: - if currattr['value'] is not None: - attrout = '{0}: {1}: {2}'.format( - node, attr, currattr['value']) - else: - attrout = '{0}: {1}:'.format(node, attr) - elif 'isset' in currattr: - if currattr['isset']: - attrout = '{0}: {1}: ********'.format(node, attr) - else: - attrout = '{0}: {1}:'.format(node, attr) - elif 'broken' in currattr: - attrout = '{0}: {1}: *ERROR* BROKEN EXPRESSION: ' \ - '{2}'.format(node, attr, - currattr['broken']) - elif isinstance(currattr, list) or isinstance(currattr, tuple): - attrout = '{0}: {1}: {2}'.format(node, attr, ', '.join(map(str, currattr))) - elif isinstance(currattr, dict): - dictout = [] - for k,v in currattr.items: - dictout.append("{0}={1}".format(k,v)) - attrout = '{0}: {1}: {2}'.format(node, attr, ', '.join(map(str, dictout))) - else: - print ("CODE ERROR" + repr(attr)) + # setting output to all so it can search since if we do have something to search, we want to show all outputs even if it is blank. + if requestargs is None: + showtype = 'current' + elif requestargs == []: + #showtype already set + pass - if options.blame or 'broken' in currattr: - blamedata = [] - if 'inheritedfrom' in currattr: - blamedata.append('inherited from group {0}'.format( - currattr['inheritedfrom'] - )) - if 'expression' in currattr: - blamedata.append( - 'derived from expression "{0}"'.format( - currattr['expression'])) - if blamedata: - attrout += ' (' + ', '.join(blamedata) + ')' - print attrout - - if not exitcode: - if requestargs: - for attr in args[1:]: - if attr not in seenattributes: - sys.stderr.write('Error: {0} not a valid attribute\n'.format(attr)) - exitcode = 1 + exitcode = client.printattributes(session, args, requestargs, showtype,nodetype, noderange, options) else: for res in session.read(nodelist): if 'error' in res: @@ -162,4 +85,5 @@ else: exitcode = 1 else: print res['item']['href'].replace('/', '') + sys.exit(exitcode) \ No newline at end of file diff --git a/confluent_client/bin/nodelist b/confluent_client/bin/nodelist index 92ea8320..89c3fe06 100755 --- a/confluent_client/bin/nodelist +++ b/confluent_client/bin/nodelist @@ -15,7 +15,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -__author__ = 'jjohnson2' +__author__ = 'jjohnson2,alin37' import optparse import os @@ -28,91 +28,35 @@ if path.startswith('/opt'): import confluent.client as client - -def attrrequested(attr, attrlist, seenattributes): - for candidate in attrlist: - truename = candidate - if candidate.startswith('hm'): - candidate = candidate.replace('hm', 'hardwaremanagement', 1) - if candidate == attr: - seenattributes.add(truename) - return True - elif '.' not in candidate and attr.startswith(candidate + '.'): - seenattributes.add(truename) - return True - return False -argparser = optparse.OptionParser( +def main(): + argparser = optparse.OptionParser( usage="Usage: %prog [options] noderange [list of attributes]") -argparser.add_option('-b', '--blame', action='store_true', + argparser.add_option('-b', '--blame', action='store_true', help='Show information about how attributes inherited') -(options, args) = argparser.parse_args() -try: - noderange = args[0] - nodelist = '/noderange/{0}/nodes/'.format(noderange) -except IndexError: - nodelist = '/nodes/' -session = client.Command() -exitcode = 0 -if len(args) > 1: - seenattributes = set([]) - for res in session.read('/noderange/{0}/attributes/all'.format(noderange)): - if 'error' in res: - sys.stderr.write(res['error'] + '\n') - exitcode = 1 - continue - for node in res['databynode']: - for attr in res['databynode'][node]: - seenattributes.add(attr) - currattr = res['databynode'][node][attr] - if attrrequested(attr, args[1:], seenattributes): - if 'value' in currattr: - if currattr['value'] is not None: - attrout = '{0}: {1}: {2}'.format( - node, attr, currattr['value']) - else: - attrout = '{0}: {1}:'.format(node, attr) - elif 'isset' in currattr: - if currattr['isset']: - attrout = '{0}: {1}: ********'.format(node, attr) - else: - attrout = '{0}: {1}:'.format(node, attr) - elif 'broken' in currattr: - attrout = '{0}: {1}: *ERROR* BROKEN EXPRESSION: ' \ - '{2}'.format(node, attr, - currattr['broken']) - elif isinstance(currattr, list) or isinstance(currattr, tuple): - attrout = '{0}: {1}: {2}'.format(node, attr, ', '.join(map(str, currattr))) - elif isinstance(currattr, dict): - dictout = [] - for k, v in currattr.items: - dictout.append("{0}={1}".format(k, v)) - attrout = '{0}: {1}: {2}'.format(node, attr, ', '.join(map(str, dictout))) - else: - print ("CODE ERROR" + repr(attr)) - - if options.blame or 'broken' in currattr: - blamedata = [] - if 'inheritedfrom' in currattr: - blamedata.append('inherited from group {0}'.format( - currattr['inheritedfrom'] - )) - if 'expression' in currattr: - blamedata.append( - 'derived from expression "{0}"'.format( - currattr['expression'])) - if blamedata: - attrout += ' (' + ', '.join(blamedata) + ')' - print attrout - if not exitcode: - for attr in args[1:]: - if attr not in seenattributes: - sys.stderr.write('Error: {0} not a valid attribute\n'.format(attr)) + (options, args) = argparser.parse_args() + noderange="" + nodelist="" + try: + noderange = args[0] + nodelist = '/noderange/{0}/nodes/'.format(noderange) + except IndexError: + nodelist = '/nodes/' + session = client.Command() + exitcode = 0 + showtype='all' + requestargs=args[1:] + nodetype='noderange' + if len(args) > 1: + exitcode=client.printattributes(session,args,requestargs,showtype,nodetype,noderange,options) + else: + for res in session.read(nodelist): + if 'error' in res: + sys.stderr.write(res['error'] + '\n') exitcode = 1 -else: - for res in session.read(nodelist): - if 'error' in res: - sys.stderr.write(res['error'] + '\n') - exitcode = 1 - else: - print res['item']['href'].replace('/', '') -sys.exit(exitcode) \ No newline at end of file + else: + print res['item']['href'].replace('/', '') + + sys.exit(exitcode) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/confluent_client/confluent/client.py b/confluent_client/confluent/client.py index 5d213003..cfa9d663 100644 --- a/confluent_client/confluent/client.py +++ b/confluent_client/confluent/client.py @@ -245,5 +245,106 @@ def send_request(operation, path, server, parameters=None): raise result = tlvdata.recv(server) +def attrrequested(attr, attrlist, seenattributes): + for candidate in attrlist: + truename = candidate + if candidate.startswith('hm'): + candidate = candidate.replace('hm', 'hardwaremanagement', 1) + if candidate == attr: + seenattributes.add(truename) + return True + elif '.' not in candidate and attr.startswith(candidate + '.'): + seenattributes.add(truename) + return True + return False + +def printattributes(session,args,requestargs,showtype,nodetype, noderange,options): + exitcode=0 + seenattributes = set([]) + for res in session.read('/{0}/{1}/attributes/{2}'.format(nodetype,noderange,showtype)): + if 'error' in res: + sys.stderr.write(res['error'] + '\n') + exitcode = 1 + continue + for node in res['databynode']: + for attr in res['databynode'][node]: + seenattributes.add(attr) + currattr = res['databynode'][node][attr] + if (requestargs is None or requestargs == [] or attrrequested(attr, args[1:], seenattributes)): + if 'value' in currattr: + if currattr['value'] is not None: + attrout = '{0}: {1}: {2}'.format( + node, attr, currattr['value']) + else: + attrout = '{0}: {1}:'.format(node, attr) + elif 'isset' in currattr: + if currattr['isset']: + attrout = '{0}: {1}: ********'.format(node, attr) + else: + attrout = '{0}: {1}:'.format(node, attr) + elif 'broken' in currattr: + attrout = '{0}: {1}: *ERROR* BROKEN EXPRESSION: ' \ + '{2}'.format(node, attr, + currattr['broken']) + elif isinstance(currattr, list) or isinstance(currattr, tuple): + attrout = '{0}: {1}: {2}'.format(node, attr, ', '.join(map(str, currattr))) + elif isinstance(currattr, dict): + dictout = [] + for k, v in currattr.items: + dictout.append("{0}={1}".format(k, v)) + attrout = '{0}: {1}: {2}'.format(node, attr, ', '.join(map(str, dictout))) + else: + print ("CODE ERROR" + repr(attr)) + + if options.blame or 'broken' in currattr: + blamedata = [] + if 'inheritedfrom' in currattr: + blamedata.append('inherited from group {0}'.format( + currattr['inheritedfrom'] + )) + if 'expression' in currattr: + blamedata.append( + 'derived from expression "{0}"'.format( + currattr['expression'])) + if blamedata: + attrout += ' (' + ', '.join(blamedata) + ')' + print attrout + if not exitcode: + if requestargs: + for attr in args[1:]: + if attr not in seenattributes: + sys.stderr.write('Error: {0} not a valid attribute\n'.format(attr)) + exitcode = 1 + return exitcode +def updateattrib(session,args,nodetype, noderange, options ): + #update attribute + exitcode=0 + if options.clear: + targpath = '/{0}/{1}/attributes/all'.format(nodetype,noderange) + keydata = {} + for attrib in args[1:]: + keydata[attrib] = None + for res in session.update(targpath, keydata): + if 'error' in res: + if 'errorcode' in res: + exitcode = res['errorcode'] + sys.stderr.write('Error: ' + res['error'] + '\n') + sys.exit(exitcode) + else: + if "=" in args[1]: + try: + if len(args[1:]) > 1: + for val in args[1:]: + val = val.split('=') + exitcode=session.simple_noderange_command(noderange, 'attributes/all'.format(noderange), val[1], val[0]) + else: + val=args[1].split('=') + exitcode=session.simple_noderange_command(noderange, 'attributes/all'.format(noderange),val[1],val[0]) + except: + sys.stderr.write('Error: {0} not a valid expression\n'.format(str (args[1:]))) + exitcode = 1 + sys.exit(exitcode) + return exitcode +