pypuppetdb 4.0.0__py3-none-any.whl

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.
pypuppetdb/__init__.py ADDED
@@ -0,0 +1,132 @@
1
+ """
2
+ pypuppetdb PuppetDB API library
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ pypuppetdb is a library to work with PuppetDB's REST API. It provides a way
6
+ to query PuppetDB and a set of additional methods and objects to make working
7
+ with PuppetDB's API and the responses easier:
8
+
9
+ >>> from pypuppetdb import connect
10
+ >>> db = connect()
11
+ >>> nodes = db.nodes()
12
+ >>> print(nodes)
13
+ <generator object 'nodes'>
14
+ >>> for node in nodes:
15
+ >>> print(node)
16
+ host1
17
+ host2
18
+ ...
19
+
20
+ This will return a generator object yielding Node objects for every returned
21
+ node from PuppetDB.
22
+
23
+ To query a single node the singular db.node() can be used:
24
+
25
+ >>> node = db.node('hostname')
26
+ >>> print(node)
27
+ hostname
28
+
29
+ The Node objects are a bit more special in that they can query for facts and
30
+ resources themselves. Using those methods from a node object will automatically
31
+ add a query to the request scoping the request to the node.
32
+
33
+ >>> node = db.node('hostname')
34
+ >>> print node.fact('osfamily')
35
+ osfamily/hostname
36
+
37
+ We can also query for facts:
38
+
39
+ >>> facts = db.facts('osfamily')
40
+ >>> print(facts)
41
+ <generator object 'facts')
42
+ >>> for fact in facts:
43
+ >>> print(fact)
44
+ osfamily/host1
45
+ osfamily/host2
46
+
47
+ That queries PuppetDB for the 'osfamily' fact and will yield Fact objects,
48
+ one per node this fact is found on.
49
+
50
+ >>> resources = db.resources('file')
51
+
52
+ Will return a generator object containing all file resources you're managing
53
+ across your infrastructure. This is probably a bad idea if you have a big
54
+ number of nodes as the response will be huge.
55
+ """
56
+
57
+ import logging
58
+
59
+ from pypuppetdb.api import API
60
+
61
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
62
+
63
+
64
+ def connect(
65
+ host="localhost",
66
+ port=8080,
67
+ ssl_verify=False,
68
+ ssl_key=None,
69
+ ssl_cert=None,
70
+ timeout=10,
71
+ protocol=None,
72
+ url_path="/",
73
+ username=None,
74
+ password=None,
75
+ token=None,
76
+ ):
77
+ """Connect with PuppetDB. This will return an object allowing you
78
+ to query the API through its methods.
79
+
80
+ :param host: (Default: 'localhost;) Hostname or IP of PuppetDB.
81
+ :type host: :obj:`string`
82
+
83
+ :param port: (Default: '8080') Port on which to talk to PuppetDB.
84
+ :type port: :obj:`int`
85
+
86
+ :param ssl_verify: (optional) Verify PuppetDB server certificate.
87
+ :type ssl_verify: :obj:`bool` or :obj:`string` True, False or filesystem \
88
+ path to CA certificate.
89
+
90
+ :param ssl_key: (optional) Path to our client secret key.
91
+ :type ssl_key: :obj:`None` or :obj:`string` representing a filesystem\
92
+ path.
93
+
94
+ :param ssl_cert: (optional) Path to our client certificate.
95
+ :type ssl_cert: :obj:`None` or :obj:`string` representing a filesystem\
96
+ path.
97
+
98
+ :param timeout: (Default: 10) Number of seconds to wait for a response.
99
+ :type timeout: :obj:`int`
100
+
101
+ :param protocol: (optional) Explicitly specify the protocol to be used
102
+ (especially handy when using HTTPS with ssl_verify=False and
103
+ without certs)
104
+ :type protocol: :obj:`None` or :obj:`string`
105
+
106
+ :param url_path: (Default: '/') The URL path where PuppetDB is served
107
+ :type url_path: :obj:`None` or :obj:`string`
108
+
109
+ :param username: (optional) The username to use for HTTP basic
110
+ authentication
111
+ :type username: :obj:`None` or :obj:`string`
112
+
113
+ :param password: (optional) The password to use for HTTP basic
114
+ authentication
115
+ :type password: :obj:`None` or :obj:`string`
116
+
117
+ :param token: (optional) The x-auth token to use for X-Authentication
118
+ :type token: :obj:`None` or :obj:`string`
119
+ """
120
+ return API(
121
+ host=host,
122
+ port=port,
123
+ timeout=timeout,
124
+ ssl_verify=ssl_verify,
125
+ ssl_key=ssl_key,
126
+ ssl_cert=ssl_cert,
127
+ protocol=protocol,
128
+ url_path=url_path,
129
+ username=username,
130
+ password=password,
131
+ token=token,
132
+ )
@@ -0,0 +1,17 @@
1
+ from pypuppetdb.api.command import CommandAPI
2
+ from pypuppetdb.api.metadata import MetadataAPI
3
+ from pypuppetdb.api.metrics import MetricsAPI
4
+ from pypuppetdb.api.pql import PqlAPI
5
+ from pypuppetdb.api.query import QueryAPI
6
+ from pypuppetdb.api.status import StatusAPI
7
+
8
+
9
+ class API(
10
+ CommandAPI,
11
+ MetadataAPI,
12
+ MetricsAPI,
13
+ PqlAPI,
14
+ QueryAPI,
15
+ StatusAPI,
16
+ ):
17
+ pass
pypuppetdb/api/base.py ADDED
@@ -0,0 +1,470 @@
1
+ import json
2
+ import logging
3
+ from urllib.parse import quote
4
+
5
+ import requests
6
+
7
+ from pypuppetdb.errors import APIError, EmptyResponseError
8
+
9
+ log = logging.getLogger(__name__)
10
+
11
+ ENDPOINTS = {
12
+ "facts": "pdb/query/v4/facts",
13
+ "fact-names": "pdb/query/v4/fact-names",
14
+ "nodes": "pdb/query/v4/nodes",
15
+ "resources": "pdb/query/v4/resources",
16
+ "catalogs": "pdb/query/v4/catalogs",
17
+ "mbean": "metrics/v1/mbeans",
18
+ # metrics v2 endpoint is now the jolokia library and all of its operations
19
+ # https://jolokia.org/reference/html/protocol.html#jolokia-operations
20
+ "metrics": "metrics/v2/read",
21
+ "metrics-base": "metrics/v2",
22
+ "metrics-exec": "metrics/v2/exec",
23
+ "metrics-list": "metrics/v2/list",
24
+ "metrics-search": "metrics/v2/search",
25
+ "metrics-write": "metrics/v2/write",
26
+ "metrics-version": "metrics/v2/version",
27
+ "reports": "pdb/query/v4/reports",
28
+ "events": "pdb/query/v4/events",
29
+ "event-counts": "pdb/query/v4/event-counts",
30
+ "aggregate-event-counts": "pdb/query/v4/aggregate-event-counts",
31
+ "server-time": "pdb/meta/v1/server-time",
32
+ "version": "pdb/meta/v1/version",
33
+ "environments": "pdb/query/v4/environments",
34
+ "factsets": "pdb/query/v4/factsets",
35
+ "fact-paths": "pdb/query/v4/fact-paths",
36
+ "fact-contents": "pdb/query/v4/fact-contents",
37
+ "edges": "pdb/query/v4/edges",
38
+ "pql": "pdb/query/v4",
39
+ "inventory": "pdb/query/v4/inventory",
40
+ "status": "status/v1/services/puppetdb-status",
41
+ "cmd": "pdb/cmd/v1",
42
+ }
43
+
44
+ PARAMETERS = {
45
+ "order_by": "order_by",
46
+ "include_total": "include_total",
47
+ "count_by": "count_by",
48
+ "counts_filter": "counts_filter",
49
+ "summarize_by": "summarize_by",
50
+ "server_time": "server_time",
51
+ }
52
+
53
+ COMMAND_VERSION = {
54
+ "deactivate node": 3,
55
+ "replace catalog": 9,
56
+ "replace facts": 5,
57
+ "store report": 8,
58
+ }
59
+
60
+ ERROR_STRINGS = {
61
+ "timeout": "Connection to PuppetDB timed out on",
62
+ "refused": "Could not reach PuppetDB on",
63
+ }
64
+
65
+
66
+ class BaseAPI:
67
+ """This is a Base or Abstract class and is not meant to be instantiated
68
+ or used directly.
69
+
70
+ The BaseAPI object defines a set of methods that can be
71
+ reused across different versions of the PuppetDB API. If querying for a
72
+ certain resource is done in an identical fashion across different versions
73
+ it will be implemented here and should be overridden in their respective
74
+ versions if they deviate.
75
+
76
+ If :attr:`ssl` is set to `True` but either :attr:`ssl_key` or\
77
+ :attr:`ssl_cert` are `None` this will raise an error.
78
+
79
+ :param host: (optional) Hostname or IP of PuppetDB.
80
+ :type host: :obj:`string`
81
+
82
+ :param port: (optional) Port on which to talk to PuppetDB.
83
+ :type port: :obj:`int`
84
+
85
+ :param ssl_verify: (optional) Verify PuppetDB server certificate.
86
+ :type ssl_verify: :obj:`bool` or :obj:`string`
87
+
88
+ :param ssl_key: (optional) Path to our client secret key.
89
+ :type ssl_key: :obj:`None` or :obj:`string` representing a filesystem\
90
+ path.
91
+
92
+ :param ssl_cert: (optional) Path to our client certificate.
93
+ :type ssl_cert: :obj:`None` or :obj:`string` representing a filesystem\
94
+ path.
95
+
96
+ :param timeout: (optional) Number of seconds to wait for a response.
97
+ :type timeout: :obj:`int`
98
+
99
+ :param protocol: (optional) Explicitly specify the protocol to be used
100
+ (especially handy when using HTTPS with ssl_verify=False and
101
+ without certs)
102
+ :type protocol: :obj:`None` or :obj:`string`
103
+
104
+ :param url_path: (optional) The URL path where PuppetDB is served
105
+ (if not at the root / path)
106
+ :type url_path: :obj:`None` or :obj:`string`
107
+
108
+ :param username: (optional) The username to use for HTTP basic
109
+ authentication
110
+ :type username: :obj:`None` or :obj:`string`
111
+
112
+ :param password: (optional) The password to use for HTTP basic
113
+ authentication
114
+ :type password: :obj:`None` or :obj:`string`
115
+
116
+ :param token: (optional) The X-auth token to use for X-Authentication
117
+ :type token: :obj:`None` or :obj:`string`
118
+
119
+ :param metric_api_version: (Default 'v2') Version of the metric API we're initialising.
120
+ :type metric_api_version: :obj:`None` or :obj:`string`
121
+
122
+ :raises: :class:`~pypuppetdb.errors.ImproperlyConfiguredError`
123
+ """
124
+
125
+ def __init__(
126
+ self,
127
+ host="localhost",
128
+ port=8080,
129
+ ssl_verify=True,
130
+ ssl_key=None,
131
+ ssl_cert=None,
132
+ timeout=10,
133
+ protocol=None,
134
+ url_path=None,
135
+ username=None,
136
+ password=None,
137
+ token=None,
138
+ metric_api_version=None,
139
+ ):
140
+ """Initialises our BaseAPI object passing the parameters needed in
141
+ order to be able to create the connection strings, set up SSL and
142
+ timeouts and so forth."""
143
+
144
+ self.api_version = "v4"
145
+ if metric_api_version is not None and metric_api_version not in ["v1", "v2"]:
146
+ raise ValueError(
147
+ "metric_api_version specified must be None, 'v1' or 'v2',"
148
+ " was given: '{}'".format(metric_api_version)
149
+ )
150
+ self.metric_api_version = metric_api_version if metric_api_version else "v2"
151
+ self.host = host
152
+ self.port = port
153
+ self.ssl_verify = ssl_verify
154
+ self.ssl_key = ssl_key
155
+ self.ssl_cert = ssl_cert
156
+ self.timeout = timeout
157
+ self.token = token
158
+
159
+ # Standardise the URL path to a format similar to /puppetdb
160
+ if url_path:
161
+ if not url_path.startswith("/"):
162
+ url_path = "/" + url_path
163
+ if url_path.endswith("/"):
164
+ url_path = url_path[:-1]
165
+ else:
166
+ url_path = ""
167
+
168
+ self.url_path = url_path
169
+
170
+ self.session = requests.Session()
171
+
172
+ if username and password:
173
+ self.session.auth = (username, password)
174
+
175
+ self.session.headers = {
176
+ "content-type": "application/json",
177
+ "accept": "application/json",
178
+ "accept-charset": "utf-8",
179
+ }
180
+
181
+ if self.token:
182
+ self.session.headers["X-Authentication"] = self.token
183
+
184
+ if protocol is not None:
185
+ protocol = protocol.lower()
186
+ if protocol not in ["http", "https"]:
187
+ raise ValueError("Protocol specified must be http or https")
188
+ self.protocol = protocol
189
+ elif self.ssl_key is not None and self.ssl_cert is not None:
190
+ self.protocol = "https"
191
+ elif self.token is not None:
192
+ self.protocol = "https"
193
+ else:
194
+ self.protocol = "http"
195
+
196
+ def disconnect(self):
197
+ """Close all connections that this class opened up."""
198
+ # If we don't explicitly close connections, we might cause other
199
+ # functions or libraries to hang on the open connections. This happens
200
+ # for example with using paramiko to tunnel PuppetDB connections
201
+ # through ssh.
202
+ self.session.close()
203
+
204
+ def __enter__(self):
205
+ """Set up environment for 'with' statement."""
206
+ # Once this class has been instantiated, there's nothing more required
207
+ return self
208
+
209
+ def __exit__(self, type, value, trace):
210
+ """Tear down connections."""
211
+ self.disconnect()
212
+
213
+ @property
214
+ def version(self):
215
+ """The version of the API we're querying against.
216
+
217
+ :returns: Current API version.
218
+ :rtype: :obj:`string`"""
219
+ return self.api_version
220
+
221
+ @property
222
+ def base_url(self):
223
+ """A base_url that will be used to construct the final
224
+ URL we're going to query against.
225
+
226
+ :returns: A URL of the form: ``proto://host:port``.
227
+ :rtype: :obj:`string`
228
+ """
229
+ return "{proto}://{host}:{port}{url_path}".format(
230
+ proto=self.protocol,
231
+ host=self.host,
232
+ port=self.port,
233
+ url_path=self.url_path,
234
+ )
235
+
236
+ @property
237
+ def total(self):
238
+ """The total-count of the last request to PuppetDB
239
+ if enabled as parameter in _query method
240
+
241
+ :returns Number of total results
242
+ :rtype :obj:`int`
243
+ """
244
+ if self.last_total is not None:
245
+ return int(self.last_total)
246
+
247
+ @staticmethod
248
+ def _normalize_resource_type(type_):
249
+ """Normalizes the type passed to the api by capitalizing each part
250
+ of the type. For example:
251
+
252
+ sysctl::value -> Sysctl::Value
253
+ user -> User
254
+
255
+ """
256
+ return "::".join([s.capitalize() for s in type_.split("::")])
257
+
258
+ def _url(self, endpoint, path=None):
259
+ """The complete URL we will end up querying. Depending on the
260
+ endpoint we pass in this will result in different URL's with
261
+ different prefixes.
262
+
263
+ :param endpoint: The PuppetDB API endpoint we want to query.
264
+ :type endpoint: :obj:`string`
265
+ :param path: An additional path if we don't wish to query the\
266
+ bare endpoint.
267
+ :type path: :obj:`string`
268
+
269
+ :returns: A URL constructed from :func:`base_url` with the\
270
+ apropraite API version/prefix and the rest of the path added\
271
+ to it.
272
+ :rtype: :obj:`string`
273
+ """
274
+
275
+ log.debug("_url called with endpoint: {} and path: {}".format(endpoint, path))
276
+
277
+ try:
278
+ endpoint = ENDPOINTS[endpoint]
279
+ except KeyError:
280
+ # If we reach this we're trying to query an endpoint that doesn't
281
+ # exist. This shouldn't happen unless someone made a booboo.
282
+ raise APIError
283
+
284
+ url = "{base_url}/{endpoint}".format(
285
+ base_url=self.base_url,
286
+ endpoint=endpoint,
287
+ )
288
+
289
+ if path is not None:
290
+ url = f"{url}/{quote(path)}"
291
+
292
+ return url
293
+
294
+ def _query(
295
+ self,
296
+ endpoint=None,
297
+ path=None,
298
+ query=None,
299
+ order_by=None,
300
+ limit=None,
301
+ offset=None,
302
+ include_total=False,
303
+ summarize_by=None,
304
+ count_by=None,
305
+ count_filter=None,
306
+ payload=None,
307
+ request_method="GET",
308
+ ):
309
+ """This method prepares a non-PQL query to PuppetDB. Actual making
310
+ the HTTP request is done by _make_request().
311
+
312
+ :param endpoint: (optional) The PuppetDB API endpoint we want to query.
313
+ Unnecessary when using PQL.
314
+ :type endpoint: :obj:`string`
315
+ :param path: An additional path if we don't wish to query the\
316
+ bare endpoint.
317
+ :type path: :obj:`string`
318
+ :param query: (optional) An AST query to further narrow down the resultset.
319
+ :type query: :obj:`string`
320
+ :param order_by: (optional) Set the order parameters for the resultset.
321
+ :type order_by: :obj:`string`
322
+ :param limit: (optional) Tell PuppetDB to limit it's response to this\
323
+ number of objects.
324
+ :type limit: :obj:`int`
325
+ :param offset: (optional) Tell PuppetDB to start it's response from\
326
+ the given offset. This is useful for implementing pagination\
327
+ but is not supported just yet.
328
+ :type offset: :obj:`string`
329
+ :param include_total: (optional) Include the total number of results
330
+ :type order_by: :obj:`bool`
331
+ :param summarize_by: (optional) Specify what type of object you'd like\
332
+ to see counts at the event-counts and aggregate-event-counts \
333
+ endpoints
334
+ :type summarize_by: :obj:`string`
335
+ :param count_by: (optional) Specify what type of object is counted
336
+ :type count_by: :obj:`string`
337
+ :param count_filter: (optional) Specify a filter for the results
338
+ :type count_filter: :obj:`string`
339
+ :param payload: (optional) Arbitrary payload to send as part of the request.
340
+ :type payload: :obj:`dict`
341
+
342
+ :raises: :class:`~pypuppetdb.errors.EmptyResponseError`
343
+
344
+ :returns: The decoded response from PuppetDB
345
+ :rtype: :obj:`dict` or :obj:`list`
346
+ """
347
+
348
+ # inside the list comprehension the locals()'s value changes
349
+ # so we need to make a copy of the function's local() to use it there
350
+ function_locals = locals().copy()
351
+ log.debug(
352
+ "_query called with: "
353
+ +
354
+ # comma-separated list of method arguments with their values
355
+ ", ".join(
356
+ [
357
+ f"{arg}={function_locals.get(arg, 'None')}"
358
+ for arg in function_locals.keys()
359
+ if arg != "self"
360
+ ]
361
+ )
362
+ )
363
+
364
+ if not endpoint:
365
+ log.error("Endpoint is required!")
366
+ raise APIError
367
+
368
+ if payload is None:
369
+ payload = {}
370
+
371
+ url = self._url(endpoint, path=path)
372
+ if query is not None:
373
+ payload["query"] = query
374
+ if order_by is not None:
375
+ payload[PARAMETERS["order_by"]] = order_by
376
+ if limit is not None:
377
+ payload["limit"] = limit
378
+ if include_total is True:
379
+ payload[PARAMETERS["include_total"]] = json.dumps(include_total)
380
+ if offset is not None:
381
+ payload["offset"] = offset
382
+ if summarize_by is not None:
383
+ payload[PARAMETERS["summarize_by"]] = summarize_by
384
+ if count_by is not None:
385
+ payload[PARAMETERS["count_by"]] = count_by
386
+ if count_filter is not None:
387
+ payload[PARAMETERS["counts_filter"]] = count_filter
388
+
389
+ return self._make_request(url, request_method, payload)
390
+
391
+ def _make_request(self, url, request_method, payload):
392
+ """
393
+ Makes a GET or POST HTTP request to PuppetDB. If PuppetDB can be
394
+ reached and answers within the timeout we'll decode the response
395
+ and give it back or raise for the HTTP Status Code PuppetDB gave back.
396
+
397
+ :param url: Complete URL to call
398
+ :param request_method: GET or POST
399
+ :param payload: data to send as parameters (GET) or in the body (POST)
400
+ :return: response body as JSON
401
+ or raises an EmptyResponseError exception if it's empty
402
+ """
403
+
404
+ if request_method.upper() not in ["GET", "POST"]:
405
+ log.error(f"Only GET or POST supported, {request_method} unsupported")
406
+ raise APIError
407
+
408
+ try:
409
+ if request_method.upper() == "GET":
410
+ r = self.session.get(
411
+ url,
412
+ params=payload,
413
+ verify=self.ssl_verify,
414
+ cert=(self.ssl_cert, self.ssl_key),
415
+ timeout=self.timeout,
416
+ )
417
+ else:
418
+ r = self.session.post(
419
+ url,
420
+ data=json.dumps(payload, default=str),
421
+ verify=self.ssl_verify,
422
+ cert=(self.ssl_cert, self.ssl_key),
423
+ timeout=self.timeout,
424
+ )
425
+
426
+ r.raise_for_status()
427
+
428
+ # get total number of results if requested with include-total
429
+ # just a quick hack - needs improvement
430
+ if "X-Records" in r.headers:
431
+ self.last_total = r.headers["X-Records"]
432
+ else:
433
+ self.last_total = None
434
+
435
+ json_body = r.json()
436
+ if json_body is not None:
437
+ return json_body
438
+ else:
439
+ del json_body
440
+ raise EmptyResponseError
441
+
442
+ except requests.exceptions.Timeout:
443
+ log.error(
444
+ "{} {}:{} over {}.".format(
445
+ ERROR_STRINGS["timeout"],
446
+ self.host,
447
+ self.port,
448
+ self.protocol.upper(),
449
+ )
450
+ )
451
+ raise
452
+
453
+ except requests.exceptions.ConnectionError:
454
+ log.error(
455
+ "{} {}:{} over {}.".format(
456
+ ERROR_STRINGS["refused"],
457
+ self.host,
458
+ self.port,
459
+ self.protocol.upper(),
460
+ )
461
+ )
462
+ raise
463
+
464
+ except requests.exceptions.HTTPError as err:
465
+ log.error(
466
+ "{} {}:{} over {}.".format(
467
+ err.response.text, self.host, self.port, self.protocol.upper()
468
+ )
469
+ )
470
+ raise