Skip to content

Commit

Permalink
Merge pull request #30 from kiddico/master
Browse files Browse the repository at this point in the history
first pass at adding python3 support; it's 2023, so merging this is the right thing to do.
  • Loading branch information
amccurdy authored Apr 3, 2023
2 parents 11ecb0c + 579689f commit 2478717
Show file tree
Hide file tree
Showing 46 changed files with 244 additions and 183 deletions.
2 changes: 1 addition & 1 deletion ZenAPIConnector.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def send(self):
if response.status_code == 200:
return response
else:
print 'HTTP Status: %s' % (response.status_code)
print('HTTP Status: %s' % (response.status_code))


class ZenDeviceUuidFinder():
Expand Down
13 changes: 7 additions & 6 deletions examples/APIGetDocumentation.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/bin/env python
from __future__ import print_function
import zenApiLib
import argparse
import sys
Expand Down Expand Up @@ -56,7 +57,7 @@ def buildArgs():
api.setRouter(apiRouterName)
except Exception as e:
if not args['silent']:
print e
print(e)
continue
if amName == "*":
mName = api._routersInfo[apiRouterName]['methods'].keys()
Expand All @@ -65,14 +66,14 @@ def buildArgs():
for apiMethodName in mName:
if apiMethodName not in api._routersInfo[apiRouterName]['methods'].keys():
if not args['silent']:
print "Specified router method '%s' is not an option. Available methods for '%s' router are: %s" % (
print("Specified router method '%s' is not an option. Available methods for '%s' router are: %s" % (
apiMethodName,
apiRouterName,
sorted(api._routersInfo[apiRouterName]['methods'].keys())
)
))
continue
mInfo = api._routersInfo[apiRouterName]['methods'][apiMethodName]
print >>rOut, (
print((
"ROUTER NAME: {}\n"
"METHOD NAME: {}\n"
"METHOD DOCUMENTATION: {}\n"
Expand All @@ -85,6 +86,6 @@ def buildArgs():
mInfo['args'],
mInfo['kwargs']
)
)
), file=rOut)
if len(rName) > 1:
print '======================================'
print('======================================')
13 changes: 7 additions & 6 deletions examples/Analytics_dumpAliases.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/bin/env python
from __future__ import print_function
import zenApiLib
import argparse
import sys
Expand Down Expand Up @@ -64,7 +65,7 @@ def __printAliasLine(outputFile, path, dsName, dpName, alias, oid):
writeStr = '%s # oid: %s' % ('|'.join(tokens), oid)
else:
writeStr = '%s' % ('|'.join(tokens))
print >>outputFile, writeStr
print(writeStr, file=outputFile)


if __name__ == '__main__':
Expand All @@ -89,9 +90,9 @@ def __printAliasLine(outputFile, path, dsName, dpName, alias, oid):
id='/zport/dmd/Devices')
seenTpls = []
ALIASES = args['aliases']
print 'Writing all datapoints %s aliases to %s' % (ALIASES,
args['outFileName'])
print >>ALIAS_FILE, '#template binding path|template|datasource|datapoint|alias|rpn'
print('Writing all datapoints %s aliases to %s' % (ALIASES,
args['outFileName']))
print('#template binding path|template|datasource|datapoint|alias|rpn', file=ALIAS_FILE)
for templ in getAllTemplates():
path = templ['uid']
# Skip template if we're already done it
Expand Down Expand Up @@ -123,5 +124,5 @@ def __printAliasLine(outputFile, path, dsName, dpName, alias, oid):
elif not dp['aliases']:
__printAliasLine(ALIAS_FILE, path, dsName, dpName, None, oid)

print 'Finished. All datapoints %s aliases exported to %s' % (ALIASES,
args['outFileName'])
print('Finished. All datapoints %s aliases exported to %s' % (ALIASES,
args['outFileName']))
31 changes: 16 additions & 15 deletions examples/Analytics_manageAliases.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/bin/env python
from __future__ import print_function
import zenApiLib
import argparse
import sys
Expand Down Expand Up @@ -82,9 +83,9 @@ def rreplace(s, old, new):
api.config['timeout'] = 30

if args['commit']:
print "Commit turned on, changes will be commited via the API"
print("Commit turned on, changes will be commited via the API")
else:
print "Dry run only - no changes will be commited. Reun with --commit after reviewing output."
print("Dry run only - no changes will be commited. Reun with --commit after reviewing output.")

# now that we've validated args, open the aliases file and loop through it looking for specified aliases in dmd
with open(args['inFileName']) as fp:
Expand All @@ -99,7 +100,7 @@ def rreplace(s, old, new):
path, tplId, dsId, dpId, aliasId, rpnFormula = lineChunk.split('|')
except ValueError:
# Malformed line
print ' X',line
print(' X',line)
continue

# Do not need to get Template or DataSource Details...
Expand Down Expand Up @@ -134,10 +135,10 @@ def rreplace(s, old, new):
formula = '' if formula is None else formula
if formula == rpnFormula:
# We found the alias, and the RPN matches, so log a match, nothing to do
print ' ', line.rstrip()
print(' ', line.rstrip())
else:
# We found the alias, but we need to update the RPN, so log an RPN update
print 'R ', line.rstrip()
print('R ', line.rstrip())
if args['commit']:
apiDPChg = api.callMethod('setInfo',
uid = dsUid,
Expand All @@ -147,14 +148,14 @@ def rreplace(s, old, new):
}]
)
if not apiDPChg['result']['success']:
print >>sys.stderr, "Formula change for alias '{}' was not successful. {}".format(
print("Formula change for alias '{}' was not successful. {}".format(
dsUid,
pformat(apiDPChg)
)
), file=sys.stderr)
sys.exit()
else:
# We didn't find the alias, so add it and the RPN, if any, and log an add
print '+ ', line.rstrip()
print('+ ', line.rstrip())
if args['commit']:
apiDPChg = api.callMethod('setInfo',
uid = dsUid,
Expand All @@ -164,10 +165,10 @@ def rreplace(s, old, new):
}]
)
if not apiDPChg['result']['success']:
print >>sys.stderr, "Formula change for alias '{}' was not successful. {}".format(
print("Formula change for alias '{}' was not successful. {}".format(
dsUid,
pformat(apiDPChg)
)
), file=sys.stderr)
# If we're attempting to remove an alias...
elif args['action'] == 'remove':
if alias:
Expand All @@ -177,20 +178,20 @@ def rreplace(s, old, new):
formula = '' if formula is None else formula
if formula == rpnFormula:
# We found the RPN matches, so remove the alias and RPN and log a removal
print '- ', line.rstrip()
print('- ', line.rstrip())
#datapoint.removeAlias(aliasId)
if args['commit']:
apiDPChg = api.callMethod('setInfo',
uid = dsUid,
aliases = rmAlias)
if not apiDPChg['result']['success']:
print >>sys.stderr, "Formula change for alias '{}' was not successful. {}".format(
print("Formula change for alias '{}' was not successful. {}".format(
dsUid,
pformat(apiDPChg)
)
), file=sys.stderr)
else:
# We RPN doesn't match so log the inability to remove the alias and RPN due to RPN mismatch
print ' r', line.rstrip()
print(' r', line.rstrip())
else:
# We couldn't find the alias, so log the inability to find the alias
print ' a', line.rstrip()
print(' a', line.rstrip())
10 changes: 5 additions & 5 deletions examples/DashboardRouter_getDeviceIssues.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# JSON API and the ZenAPIConnector class written by #
# Adam McCurdy @ Zenoss #
#####################################################

from __future__ import print_function
import zenApiLib


Expand All @@ -15,8 +15,8 @@ def deviceIssuesReport():
.csv format. There are several other fields one might be
interested in here, but here are a few as an example.
'''
print 'Device, Device Class, ProdState, Clear, Debug, Info '\
'Warning, Error, Critical'
print('Device, Device Class, ProdState, Clear, Debug, Info '\
'Warning, Error, Critical')
dr = zenApiLib.zenConnector(routerName = 'DashboardRouter')
report_data = dr.callMethod('getDeviceIssues')
if report_data.get('result', {}).get('success', False) is False:
Expand All @@ -33,15 +33,15 @@ def deviceIssuesReport():
warning = events['warning']['count']
error = events['error']['count']
critical = events['critical']['count']
print '%s, %s, %s, %s, %s, %s, %s, %s, %s' % (device,
print('%s, %s, %s, %s, %s, %s, %s, %s, %s' % (device,
deviceClass,
prodState,
clear,
debug,
info,
warning,
error,
critical)
critical))


if __name__ == '__main__':
Expand Down
28 changes: 18 additions & 10 deletions examples/DeviceDumpLoadRouter_exportDevices.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
#!/bin/env python
#!/usr/bin/env python

from __future__ import print_function
import zenApiLib
import argparse
import sys
import logging
import os
from urlparse import urlparse
from datetime import date
from pprint import pformat

try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse

def buildArgs():
parser = argparse.ArgumentParser(description='Poll & display API Router & '
'Method information. Wildcards can be used to "search"'
Expand Down Expand Up @@ -61,7 +67,7 @@ def buildArgs():
# ?Bug? (ZEN-31017) - work-around via multiple api calls
# -- Get device classes first
if args['exOrg']:
print >>rOut, "#### {} extract of classes ####".format(devClass)
print("#### {} extract of classes ####".format(devClass), file=rOut)
apiResult = api.callMethod(
'exportDevices',
options={
Expand All @@ -74,13 +80,14 @@ def buildArgs():
devClass,
apiResult['result']['deviceCount']
))
print >>rOut, apiResult['result']['data']
print(apiResult['result']['data'], file=rOut)
else:
print >>sys.stderr, "ERROR: API results nonsuccessfull\n{}".format(
pass
print("ERROR: API results nonsuccessfull\n{}".format(
pformat(apiResult)
)
), file=sys.stderr)
if args['exDev']:
print >>rOut, "#### {} extract of devices ####".format(devClass)
print("#### {} extract of devices ####".format(devClass), file=rOut)
# -- now devices, with its deviceClass defined in the moveDevice batchload parameter
apiResult = api.callMethod(
'exportDevices',
Expand All @@ -94,8 +101,9 @@ def buildArgs():
devClass,
apiResult['result']['deviceCount']
))
print >>rOut, apiResult['result']['data']
print(apiResult['result']['data'], file=rOut)
else:
print >>sys.stderr, "ERROR: API results nonsuccessfull\n{}".format(
pass
print("ERROR: API results nonsuccessfull\n{}".format(
pformat(apiResult)
)
), file=sys.stderr)
9 changes: 5 additions & 4 deletions examples/DeviceDumpLoadRouter_importDevices.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/bin/env python
from __future__ import print_function
import zenApiLib
import argparse
import sys
Expand Down Expand Up @@ -50,9 +51,9 @@ def buildArgs():
data=fp.read())
fp.close()
if apiResult['result']['success']:
print >>sys.stderr, "Import successful, import stats: {}".format(
print("Import successful, import stats: {}".format(
apiResult['result']['stats']
)
), file=sys.stderr)
else:
print >>sys.stderr, "ERROR: API results nonsuccessfull\n{}".format(
pformat(apiResult))
print("ERROR: API results nonsuccessfull\n{}".format(
pformat(apiResult)), file=sys.stderr)
3 changes: 2 additions & 1 deletion examples/DeviceManagementRouter_DeleteMaintenanceWindows.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# example of how to remove old maintenance windows from a #
# specific device #
################################################################
from __future__ import print_function
import zenApiLib
from time import time

Expand All @@ -21,4 +22,4 @@ def delete_maint_window(mw_uid, mw_id):
time_to_delete = curr_time - 86400
if mwindow['start'] < time_to_delete:
del_resp = delete_maint_window(mwindow['uid'], mwindow['id'])
print del_resp
print(del_resp)
3 changes: 2 additions & 1 deletion examples/DeviceManagementRouter_addMaintWindow_SysArgv.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#!/usr/bin/env python
from __future__ import print_function
import zenApiLib
import time
import sys

usage = '%s <uid> <durationHours> <prodState> <name>' % (sys.argv[0])

if len(sys.argv) != 5:
print usage
print(usage)
sys.exit(1)
else:
uid = sys.argv[1]
Expand Down
17 changes: 10 additions & 7 deletions examples/DeviceModelAgeReport.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/bin/env python
from __future__ import print_function
import zenApiLib
import argparse
import sys
Expand Down Expand Up @@ -55,13 +56,15 @@ def buildArgs():
if not pagedResults['result']['success']:
raise Exception(pagedResults['msg'])
except Exception as e:
print >> sys.stderr, "ERROR: {!r}".format(e)
print >> sys.stderr, pformat(pagedResults)
print("ERROR: {!r}".format(e), file=sys.stderr)
print(pformat(pagedResults), file=sys.stderr)
sys.exit(1)
for event in pagedResults['result']['events']:
issues[event['device']['text']] = event['summary']
# Loop through Devices and report on model dates
print >> rOut, "Device Class, Device ID, Device Title, Last Modeled DateTime, Last Modeled Date, Collector, Production State, Model Events, Status Up/Down"

print("Device Class, Device ID, Device Title, Last Modeled DateTime, Last Modeled Date, Production State, Model Events, Status Up/Down", file=rOut)

api.setRouter('DeviceRouter')
for pagedResults in api.pagingMethodCall('getDevices',
keys=['uid', 'id', 'name', 'status', 'lastCollected', 'collector', 'productionStateLabel'],
Expand All @@ -70,11 +73,11 @@ def buildArgs():
if not pagedResults['result']['success']:
raise Exception(pagedResults['msg'])
except Exception as e:
print >> sys.stderr, "ERROR: {!r}".format(e)
print >> sys.stderr, pformat(pagedResults)
print("ERROR: {!r}".format(e), file=sys.stderr)
print(pformat(pagedResults), file=sys.stderr)
sys.exit(1)
for device in pagedResults['result']['devices']:
print >> rOut, '{},{},{},{},{},{},{},"{}",{}'.format(
print('{},{},{},{},{},{},"{}",{}'.format(
'/'.join(device['uid'].split('/')[4:-2]),
device['id'],
(device['name'] if device['name'] != device['id'] else ''),
Expand All @@ -86,4 +89,4 @@ def buildArgs():
device['productionStateLabel'],
issues.get(device['name'], 'No Events'),
('UP' if device['status'] else 'DOWN')
)
), file=rOut)
3 changes: 2 additions & 1 deletion examples/DeviceRouter_ResetIPandRemodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# addresses and remodel devices based on a device #
# organizer using the JSON API and zenAPILib #
#####################################################
from __future__ import print_function

import zenApiLib

Expand All @@ -26,7 +27,7 @@ def resetIPAndRemodel():
for dev in devlist:
deviceRouter.callMethod('resetIp', uids=dev)
deviceRouter.callMethod('remodel', deviceUid=dev)
print "Resetting IP and Remodeling %s" % dev
print("Resetting IP and Remodeling %s" % dev)

if __name__ == '__main__':
resetIPAndRemodel()
Loading

0 comments on commit 2478717

Please sign in to comment.