akips 0.2.2__tar.gz → 0.3.0__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.2
3
+ Version: 0.3.0
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.2.2'
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.3.0'
3
4
 
4
5
  import io
5
6
  import re
@@ -16,22 +17,30 @@ 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
+ """
36
+ Pull a list of key attributes for multiple devices. Can be filtered by group
37
+ but the default is all devices.
38
+
39
+ AKiPS command syntax:
40
+ `mget {type} [{parent regex} [{child regex} [{attribute regex}]]]
41
+ [value {text|/regex/|integer|ipaddr}] [profile {profile name}]
42
+ [any|all|not group {group name} ...]`
43
+ """
35
44
  attributes = [
36
45
  'ip4addr',
37
46
  'SNMPv2-MIB.sysName',
@@ -43,7 +52,7 @@ class AKIPS:
43
52
  'cmds': f'mget text * sys /{cmd_attributes}/',
44
53
  }
45
54
  if groups:
46
- ''' [any|all|not group {group name} ...] '''
55
+ # [any|all|not group {group name} ...]
47
56
  group_list = " ".join(groups)
48
57
  params['cmds'] += f" {group_filter} group {group_list}"
49
58
  text = self._get(params=params)
@@ -64,7 +73,14 @@ class AKIPS:
64
73
  return None
65
74
 
66
75
  def get_device(self, name):
67
- ''' Pull the entire configuration for a single device '''
76
+ """
77
+ Pull the entire configuration for a single device.
78
+
79
+ AKiPS command syntax:
80
+ `mget {type} [{parent regex} [{child regex} [{attribute regex}]]]
81
+ [value {text|/regex/|integer|ipaddr}] [profile {profile name}]
82
+ [any|all|not group {group name} ...]`
83
+ """
68
84
  params = {
69
85
  'cmds': f'mget * {name} * *'
70
86
  }
@@ -93,17 +109,38 @@ class AKIPS:
93
109
  return None
94
110
 
95
111
  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 '''
98
- # params = {
99
- # 'function': 'web_find_device_by_ip',
100
- # 'ipaddr': ipaddr
101
- # }
102
- # section = '/api-script/'
103
- pass
112
+ """
113
+ Devices may have additional IP addresses recorded in akips, but only one primary
114
+ name and address. Search for a device name by an alternate IP address.
115
+
116
+ AKiPS user "api-rw" is required to run api scripts. This call makes use of a
117
+ special site script and not the normal web API commands.
118
+ """
119
+ params = {
120
+ 'function': 'web_find_device_by_ip',
121
+ 'ipaddr': ipaddr
122
+ }
123
+ text = self._get(section='/api-script/', params=params)
124
+ if text:
125
+ lines = text.split('\n')
126
+ for line in lines:
127
+ match = re.match(r"IP Address (\S+) is configured on (\S+)", line)
128
+ if match:
129
+ address = match.group(1)
130
+ device_name = match.group(2)
131
+ logger.debug(f"Found {address} on device {device_name}")
132
+ return device_name
133
+ return None
104
134
 
105
135
  def get_unreachable(self):
106
- ''' Pull a list of unreachable IPv4 ping devices '''
136
+ """
137
+ Pull a list of unreachable IPv4 ping devices
138
+
139
+ AKiPS command syntax:
140
+ `mget {type} [{parent regex} [{child regex} [{attribute regex}]]]
141
+ [value {text|/regex/|integer|ipaddr}] [profile {profile name}]
142
+ [any|all|not group {group name} ...]`
143
+ """
107
144
  params = {
108
145
  'cmds': 'mget * * * /PING.icmpState|SNMP.snmpState/ value /down/',
109
146
  }
@@ -117,7 +154,8 @@ class AKIPS:
117
154
  # epoch fields are in the server's timezone
118
155
  name = match.group(1)
119
156
  attribute = match.group(3)
120
- event_start = datetime.fromtimestamp(int(match.group(7)), tz=pytz.timezone(self.server_timezone))
157
+ event_start = datetime.fromtimestamp(
158
+ int(match.group(7)), tz=pytz.timezone(self.server_timezone))
121
159
  if name not in data:
122
160
  # populate a starting point for this device
123
161
  data[name] = {
@@ -130,39 +168,42 @@ class AKIPS:
130
168
  data[name]['child'] = match.group(2),
131
169
  data[name]['ping_state'] = match.group(5)
132
170
  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))
171
+ data[name]['device_added'] = datetime.fromtimestamp(
172
+ int(match.group(6)), tz=pytz.timezone(self.server_timezone))
173
+ data[name]['event_start'] = datetime.fromtimestamp(
174
+ int(match.group(7)), tz=pytz.timezone(self.server_timezone))
135
175
  data[name]['ip4addr'] = match.group(8)
136
176
  elif attribute == 'SNMP.snmpState':
137
177
  data[name]['child'] = match.group(2),
138
178
  data[name]['snmp_state'] = match.group(5)
139
179
  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))
180
+ data[name]['device_added'] = datetime.fromtimestamp(
181
+ int(match.group(6)), tz=pytz.timezone(self.server_timezone))
182
+ data[name]['event_start'] = datetime.fromtimestamp(
183
+ int(match.group(7)), tz=pytz.timezone(self.server_timezone))
142
184
  data[name]['ip4addr'] = None
143
185
  if event_start < data[name]['event_start']:
144
186
  data[name]['event_start'] = event_start
145
187
  logger.debug("Found {} devices in akips".format(len(data)))
146
188
  logger.debug("data: {}".format(data))
147
189
 
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
190
  return data
160
191
 
161
- def get_group_membership(self):
162
- ''' Pull a list of device to group memberships '''
192
+ def get_group_membership(self, device='*', group_filter='any', groups=[]):
193
+ """
194
+ Pull a list of device names to group memberships. Defaults to all devices
195
+ and all groups (including the special 'maintenance_mode' group).
196
+
197
+ AKiPS command syntax:
198
+ `mgroup {type} [{parent regex}]
199
+ [any|all|not group {group name} ...]`
200
+ """
163
201
  params = {
164
- 'cmds': 'mgroup device *',
202
+ 'cmds': f'mgroup {device} *',
165
203
  }
204
+ if groups:
205
+ group_list = " ".join(groups)
206
+ params['cmds'] += f" {group_filter} group {group_list}"
166
207
  text = self._get(params=params)
167
208
  if text:
168
209
  data = {}
@@ -178,34 +219,55 @@ class AKIPS:
178
219
  return data
179
220
  return None
180
221
 
181
- def get_maintenance_mode(self):
182
- ''' Pull a list of devices in maintenance mode '''
183
- # params = {
184
- # 'cmds': 'mget * * any group maintenance_mode',
185
- # }
186
- pass
222
+ def set_group_membership(self, device, group, mode):
223
+ """
224
+ Update manual grouping rules for a device, including the special
225
+ 'maintenance_mode' group. The web api script fails silently if the device or group
226
+ does not exist.
187
227
 
188
- def set_maintenance_mode(self, device_name, mode='True'):
189
- ''' Set maintenance mode on or off for a device '''
190
- # params = {
191
- # 'function': 'web_manual_grouping',
192
- # 'type': 'device',
193
- # 'group': 'maintenance_mode',
194
- # 'device': device_name
195
- # }
196
- pass
228
+ AKiPS user "api-rw" is required to run api scripts. This call makes use of a
229
+ special site script and not the normal web API commands.
230
+ """
231
+ if not device:
232
+ raise ValueError("a valid device name must be provided for manual grouping update")
233
+ if not group:
234
+ raise ValueError("a valid group name must be provided for manual grouping update")
235
+ if mode not in ('assign', 'clear'):
236
+ raise ValueError("mode must be 'assign' or 'clear' for manual grouping update")
237
+ params = {
238
+ 'function': 'web_manual_grouping',
239
+ 'type': 'device',
240
+ 'group': group, # group_name
241
+ 'mode': mode, # 'assign' or 'clear' for device memberships
242
+ 'device': device # device_name
243
+ }
244
+ text = self._get(section='/api-script/', params=params)
245
+ if text:
246
+ logger.error("Web API request failed: {}".format(text))
247
+ raise AkipsError(message=text)
248
+ return None
197
249
 
198
250
  def get_status(self, device='*', child='*', attribute='*'):
199
- ''' Pull the status values we are most interested in '''
251
+ """
252
+ Pull the status values we are most interested in
253
+
254
+ AKiPS command syntax:
255
+ `mget {type} [{parent regex} [{child regex} [{attribute regex}]]]
256
+ [value {text|/regex/|integer|ipaddr}] [profile {profile name}]
257
+ [any|all|not group {group name} ...]`
258
+ """
200
259
  pass
201
260
 
202
261
  def get_events(self, event_type='all', period='last1h'):
203
- ''' Pull a list of events. Command syntax:
204
- mget event {all,critical,enum,threshold,uptime}
262
+ """
263
+ Pull a list of events.
264
+
265
+ AKiPS command syntax:
266
+ `mget event {all,critical,enum,threshold,uptime}
205
267
  time {time filter} [{parent regex} {child regex}
206
268
  {attribute regex}] [profile {profile name}]
207
- [any|all|not group {group name} ...] '''
208
-
269
+ [any|all|not group {group name} ...]`
270
+ """
209
271
  params = {
210
272
  'cmds': f'mget event {event_type} time {period}'
211
273
  }
@@ -232,11 +294,16 @@ class AKIPS:
232
294
 
233
295
  # Time-series commands
234
296
 
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
297
+ def get_series(self, period='last1h', device='*', attribute='*', get_dict=True,
298
+ group_filter='any', groups=[]):
299
+ """
300
+ Pull a series of counter values.
301
+
302
+ AKiPS command syntax:
303
+ `cseries avg
238
304
  time {time filter} type parent child attribute
239
- [any|all|not group {group name} ...] '''
305
+ [any|all|not group {group name} ...]`
306
+ """
240
307
  params = {
241
308
  'cmds': f'cseries avg time {period} * {device} * {attribute}'
242
309
  }
@@ -258,11 +325,16 @@ class AKIPS:
258
325
  return csv_to_list
259
326
  return None
260
327
 
261
- def get_aggregate(self, operator='avg', interval='300', period='last1h', device='*', attribute='*', group_filter='any', groups=[]):
262
- ''' Aggregate stats in intervals over a period of time. Command syntax:
263
- aggregate interval {avg|total seconds}
328
+ def get_aggregate(self, period='last1h', device='*', attribute='*',
329
+ operator='avg', interval='300', group_filter='any', groups=[]):
330
+ """
331
+ Aggregate counter values in intervals over a period of time.
332
+
333
+ AKiPS command syntax:
334
+ `aggregate interval {avg|total seconds}
264
335
  time {time filter} type parent child attribute
265
- [any|all|not group {group name} ...] '''
336
+ [any|all|not group {group name} ...]`
337
+ """
266
338
  params = {
267
339
  'cmds': f'aggregate interval {operator} {interval} time {period} * {device} * {attribute}'
268
340
  }
@@ -280,8 +352,31 @@ class AKIPS:
280
352
 
281
353
  # Base operations
282
354
 
355
+ def _parse_enum(self, enum_string):
356
+ """
357
+ Attributes with a type of enum return five values separated by commas.
358
+ """
359
+ match = re.match(r'^(\S*),(\S*),(\S*),(\S*),(\S*)$', enum_string)
360
+ if match:
361
+ entry = {
362
+ 'number': match.group(1), # list number (from MIB)
363
+ 'value': match.group(2), # text value (from MIB)
364
+ # 'created': match.group(3), # time created (epoch timestamp)
365
+ # 'modified': match.group(4), # time modified (epoch timestamp)
366
+ 'description': match.group(5) # child description
367
+ }
368
+ entry['created'] = datetime.fromtimestamp(
369
+ int(match.group(3)), tz=pytz.timezone(self.server_timezone))
370
+ entry['modified'] = datetime.fromtimestamp(
371
+ int(match.group(4)), tz=pytz.timezone(self.server_timezone))
372
+ return entry
373
+ else:
374
+ raise AkipsError(message=f'Not a ENUM type value: {enum_string}')
375
+
283
376
  def _get(self, section='/api-db/', params=None, timeout=30):
284
- ''' Call HTTP GET against the AKiPS server '''
377
+ """
378
+ Call HTTP GET against the AKiPS server
379
+ """
285
380
  server_url = 'https://' + self.server + section
286
381
  params['username'] = self.username
287
382
  params['password'] = self.password
@@ -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.2"
3
+ version = "0.3.0"
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