akips 0.2.1__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,15 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: akips
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Module to interact with the AKiPS Network Monitoring Software API interface
5
5
  Home-page: https://github.com/wwhitaker/akips
6
6
  License: MIT
7
7
  Author: William E Whitaker
8
8
  Author-email: will.whitaker@unc.edu
9
- Requires-Python: >=3.8.1,<4.0
9
+ Requires-Python: >=3.8,<4.0
10
10
  Classifier: License :: OSI Approved :: MIT License
11
11
  Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
12
13
  Classifier: Programming Language :: Python :: 3.9
13
14
  Classifier: Programming Language :: Python :: 3.10
14
15
  Classifier: Programming Language :: Python :: 3.11
@@ -58,6 +59,9 @@ for name, fields in devices.items():
58
59
 
59
60
  ```
60
61
 
62
+ ## API Documentation
63
+ [API Documentation](https://wwhitaker.github.io/akips/docs/akips/index.html)
64
+
61
65
  ## Bugs/Requests
62
66
 
63
67
  Please use the [GitHub issue tracker](https://github.com/wwhitaker/akips/issues)
@@ -39,6 +39,9 @@ for name, fields in devices.items():
39
39
 
40
40
  ```
41
41
 
42
+ ## API Documentation
43
+ [API Documentation](https://wwhitaker.github.io/akips/docs/akips/index.html)
44
+
42
45
  ## Bugs/Requests
43
46
 
44
47
  Please use the [GitHub issue tracker](https://github.com/wwhitaker/akips/issues)
@@ -1,5 +1,6 @@
1
- ''' Base module '''
2
- __version__ = '0.1.5'
1
+ """ This akips python module provides a simple way for python scripts to interact with
2
+ the AKiPS Network Monitoring Software Web API interface. """
3
+ __version__ = '0.2.3'
3
4
 
4
5
  import io
5
6
  import re
@@ -16,22 +17,22 @@ logger = logging.getLogger(__name__)
16
17
 
17
18
 
18
19
  class AKIPS:
19
- ''' Class to handle interactions with AKiPS API '''
20
- server_timezone = 'America/New_York'
20
+ """ Class to handle interactions with AKiPS API """
21
21
 
22
- def __init__(self, server, username='api-ro', password=None, verify=True):
23
- ''' Connect to the AKiPS instance '''
22
+ def __init__(self, server, username='api-ro', password=None,
23
+ verify=True, timezone='America/New_York'):
24
24
  self.server = server
25
25
  self.username = username
26
26
  self.password = password
27
27
  self.verify = verify
28
+ self.server_timezone = timezone
28
29
  self.session = requests.Session()
29
30
 
30
31
  if not verify:
31
32
  requests.packages.urllib3.disable_warnings() # pylint: disable=no-member
32
33
 
33
34
  def get_devices(self, group_filter='any', groups=[]):
34
- ''' Pull a list of key attributes for all devices in akips '''
35
+ """ Pull a list of key attributes for all devices in akips """
35
36
  attributes = [
36
37
  'ip4addr',
37
38
  'SNMPv2-MIB.sysName',
@@ -43,7 +44,7 @@ class AKIPS:
43
44
  'cmds': f'mget text * sys /{cmd_attributes}/',
44
45
  }
45
46
  if groups:
46
- ''' [any|all|not group {group name} ...] '''
47
+ """ [any|all|not group {group name} ...] """
47
48
  group_list = " ".join(groups)
48
49
  params['cmds'] += f" {group_filter} group {group_list}"
49
50
  text = self._get(params=params)
@@ -64,7 +65,7 @@ class AKIPS:
64
65
  return None
65
66
 
66
67
  def get_device(self, name):
67
- ''' Pull the entire configuration for a single device '''
68
+ """ Pull the entire configuration for a single device """
68
69
  params = {
69
70
  'cmds': f'mget * {name} * *'
70
71
  }
@@ -93,8 +94,8 @@ class AKIPS:
93
94
  return None
94
95
 
95
96
  def get_device_by_ip(self, ipaddr, use_cache=True):
96
- ''' Search for a device by an alternate IP address
97
- This makes use of a special site script and not the normal api '''
97
+ """ Search for a device by an alternate IP address
98
+ This makes use of a special site script and not the normal api """
98
99
  # params = {
99
100
  # 'function': 'web_find_device_by_ip',
100
101
  # 'ipaddr': ipaddr
@@ -103,7 +104,7 @@ class AKIPS:
103
104
  pass
104
105
 
105
106
  def get_unreachable(self):
106
- ''' Pull a list of unreachable IPv4 ping devices '''
107
+ """ Pull a list of unreachable IPv4 ping devices """
107
108
  params = {
108
109
  'cmds': 'mget * * * /PING.icmpState|SNMP.snmpState/ value /down/',
109
110
  }
@@ -117,7 +118,8 @@ class AKIPS:
117
118
  # epoch fields are in the server's timezone
118
119
  name = match.group(1)
119
120
  attribute = match.group(3)
120
- event_start = datetime.fromtimestamp(int(match.group(7)), tz=pytz.timezone(self.server_timezone))
121
+ event_start = datetime.fromtimestamp(
122
+ int(match.group(7)), tz=pytz.timezone(self.server_timezone))
121
123
  if name not in data:
122
124
  # populate a starting point for this device
123
125
  data[name] = {
@@ -130,36 +132,29 @@ class AKIPS:
130
132
  data[name]['child'] = match.group(2),
131
133
  data[name]['ping_state'] = match.group(5)
132
134
  data[name]['index'] = match.group(4)
133
- data[name]['device_added'] = datetime.fromtimestamp(int(match.group(6)), tz=pytz.timezone(self.server_timezone))
134
- data[name]['event_start'] = datetime.fromtimestamp(int(match.group(7)), tz=pytz.timezone(self.server_timezone))
135
+ data[name]['device_added'] = datetime.fromtimestamp(
136
+ int(match.group(6)), tz=pytz.timezone(self.server_timezone))
137
+ data[name]['event_start'] = datetime.fromtimestamp(
138
+ int(match.group(7)), tz=pytz.timezone(self.server_timezone))
135
139
  data[name]['ip4addr'] = match.group(8)
136
140
  elif attribute == 'SNMP.snmpState':
137
141
  data[name]['child'] = match.group(2),
138
142
  data[name]['snmp_state'] = match.group(5)
139
143
  data[name]['index'] = match.group(4)
140
- data[name]['device_added'] = datetime.fromtimestamp(int(match.group(6)), tz=pytz.timezone(self.server_timezone))
141
- data[name]['event_start'] = datetime.fromtimestamp(int(match.group(7)), tz=pytz.timezone(self.server_timezone))
144
+ data[name]['device_added'] = datetime.fromtimestamp(
145
+ int(match.group(6)), tz=pytz.timezone(self.server_timezone))
146
+ data[name]['event_start'] = datetime.fromtimestamp(
147
+ int(match.group(7)), tz=pytz.timezone(self.server_timezone))
142
148
  data[name]['ip4addr'] = None
143
149
  if event_start < data[name]['event_start']:
144
150
  data[name]['event_start'] = event_start
145
151
  logger.debug("Found {} devices in akips".format(len(data)))
146
152
  logger.debug("data: {}".format(data))
147
153
 
148
- # for name in data:
149
- # # Fill in the unreported gaps so we have ping4 and snmp up/down data
150
- # if data[name]['ping_state'] == 'n/a':
151
- # ping_status = self.get_status(device=name, child='ping4', attribute='PING.icmpState')
152
-
153
- # if data[name]['snmp_state'] == 'n/a':
154
- # snmp_status = self.get_status(device=name, child='sys', attribute='SNMP.snmpState')
155
-
156
- # ideal data return based on unreachable device report
157
- # Device, Ping4 (state,IPv4), SNMP (state,IP), Last Change (... ago), Location, Description
158
-
159
154
  return data
160
155
 
161
156
  def get_group_membership(self):
162
- ''' Pull a list of device to group memberships '''
157
+ """ Pull a list of device to group memberships """
163
158
  params = {
164
159
  'cmds': 'mgroup device *',
165
160
  }
@@ -179,14 +174,14 @@ class AKIPS:
179
174
  return None
180
175
 
181
176
  def get_maintenance_mode(self):
182
- ''' Pull a list of devices in maintenance mode '''
177
+ """ Pull a list of devices in maintenance mode """
183
178
  # params = {
184
179
  # 'cmds': 'mget * * any group maintenance_mode',
185
180
  # }
186
181
  pass
187
182
 
188
183
  def set_maintenance_mode(self, device_name, mode='True'):
189
- ''' Set maintenance mode on or off for a device '''
184
+ """ Set maintenance mode on or off for a device """
190
185
  # params = {
191
186
  # 'function': 'web_manual_grouping',
192
187
  # 'type': 'device',
@@ -196,15 +191,15 @@ class AKIPS:
196
191
  pass
197
192
 
198
193
  def get_status(self, device='*', child='*', attribute='*'):
199
- ''' Pull the status values we are most interested in '''
194
+ """ Pull the status values we are most interested in """
200
195
  pass
201
196
 
202
197
  def get_events(self, event_type='all', period='last1h'):
203
- ''' Pull a list of events. Command syntax:
198
+ """ Pull a list of events. Command syntax:
204
199
  mget event {all,critical,enum,threshold,uptime}
205
200
  time {time filter} [{parent regex} {child regex}
206
201
  {attribute regex}] [profile {profile name}]
207
- [any|all|not group {group name} ...] '''
202
+ [any|all|not group {group name} ...] """
208
203
 
209
204
  params = {
210
205
  'cmds': f'mget event {event_type} time {period}'
@@ -230,13 +225,14 @@ class AKIPS:
230
225
  return data
231
226
  return None
232
227
 
233
- ### Time-series commands
228
+ # Time-series commands
234
229
 
235
- def get_series(self, period='last1h', device='*', attribute='*', group_filter='any', groups=[], get_dict=True):
236
- ''' Pull a series of values. Command syntax:
237
- cseries avg
238
- time {time filter] type parent child attribute
239
- [any|all|not group {group name} ...] '''
230
+ def get_series(self, period='last1h', device='*', attribute='*', get_dict=True,
231
+ group_filter='any', groups=[]):
232
+ """ Pull a series of values. Command syntax:
233
+ cseries avg
234
+ time {time filter} type parent child attribute
235
+ [any|all|not group {group name} ...] """
240
236
  params = {
241
237
  'cmds': f'cseries avg time {period} * {device} * {attribute}'
242
238
  }
@@ -258,14 +254,56 @@ class AKIPS:
258
254
  return csv_to_list
259
255
  return None
260
256
 
261
- ### Base operations
257
+ def get_aggregate(self, period='last1h', device='*', attribute='*',
258
+ operator='avg', interval='300', group_filter='any', groups=[]):
259
+ """ Aggregate stats in intervals over a period of time. Command syntax:
260
+ aggregate interval {avg|total seconds}
261
+ time {time filter} type parent child attribute
262
+ [any|all|not group {group name} ...] """
263
+ params = {
264
+ 'cmds': f'aggregate interval {operator} {interval} time {period} * {device} * {attribute}'
265
+ }
266
+ if groups:
267
+ group_list = " ".join(groups)
268
+ params['cmds'] += f" {group_filter} group {group_list}"
269
+ text = self._get(params=params)
270
+ if text:
271
+ # Text should be one CSV line followed by one blank line
272
+ lines = text.split('\n')
273
+ values = lines[0].split(',')
274
+ logger.debug("Found {} aggregate values".format(len(values)))
275
+ return values
276
+ return None
277
+
278
+ # Base operations
279
+
280
+ def _parse_enum(self, enum_string):
281
+ """ Attributes with a type of enum return five values separated by commas. """
282
+ match = re.match(r'^(\S*),(\S*),(\S*),(\S*),(\S*)$', enum_string)
283
+ if match:
284
+ entry = {
285
+ 'number': match.group(1), # list number (from MIB)
286
+ 'value': match.group(2), # text value (from MIB)
287
+ # 'created': match.group(3), # time created (epoch timestamp)
288
+ # 'modified': match.group(4), # time modified (epoch timestamp)
289
+ 'description': match.group(5) # child description
290
+ }
291
+ entry['created'] = datetime.fromtimestamp(
292
+ int(match.group(3)), tz=pytz.timezone(self.server_timezone))
293
+ entry['modified'] = datetime.fromtimestamp(
294
+ int(match.group(4)), tz=pytz.timezone(self.server_timezone))
295
+ return entry
296
+ else:
297
+ raise AkipsError(message=f'Not a ENUM type value: {enum_string}')
262
298
 
263
299
  def _get(self, section='/api-db/', params=None, timeout=30):
264
- ''' Call HTTP GET against the AKiPS server '''
300
+ """ Call HTTP GET against the AKiPS server """
265
301
  server_url = 'https://' + self.server + section
266
302
  params['username'] = self.username
267
303
  params['password'] = self.password
268
304
 
305
+ if 'cmds' in params:
306
+ logger.debug("akips command: {}".format(params['cmds']))
269
307
  try:
270
308
  r = self.session.get(server_url, params=params, verify=self.verify, timeout=timeout)
271
309
  r.raise_for_status()
@@ -287,4 +325,5 @@ class AKIPS:
287
325
  logger.error("Web API request failed: {}".format(r.text))
288
326
  raise AkipsError(message=r.text)
289
327
  else:
328
+ logger.debug("akips output: {}".format(r.text))
290
329
  return r.text
@@ -1,7 +1,7 @@
1
1
  # AKiPS specific Exceptions
2
2
 
3
3
  class AkipsError(Exception):
4
- """Exception raised for Errors return in AKiPS web api"""
4
+ """ Exception raised for Errors return in AKiPS web api """
5
5
  def __init__(self, message="AKiPS web api returned error"):
6
6
  self.message = message
7
7
  super().__init__(self.message)
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "akips"
3
- version = "0.2.1"
3
+ version = "0.2.3"
4
4
  description = "Module to interact with the AKiPS Network Monitoring Software API interface"
5
5
  authors = ["William E Whitaker <will.whitaker@unc.edu>"]
6
6
  readme = "README.md"
@@ -8,13 +8,15 @@ license = "MIT"
8
8
  repository = "https://github.com/wwhitaker/akips"
9
9
 
10
10
  [tool.poetry.dependencies]
11
- python = ">=3.8.1,<4.0"
11
+ python = ">=3.8,<4.0"
12
12
  requests = ">=2.31"
13
13
  pytz = "*"
14
14
 
15
- [tool.poetry.dev-dependencies]
16
- pytest = "^7.4"
17
- flake8 = "^6.1"
15
+ [tool.poetry.group.dev.dependencies]
16
+ pytest = "^8.2.0"
17
+ #flake8 = "^7.0.0"
18
+ pdoc3 = "^0.10.0"
19
+ pylama = "^8.4.1"
18
20
 
19
21
  [build-system]
20
22
  requires = ["poetry-core"]
File without changes