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.
@@ -0,0 +1,362 @@
1
+ import logging
2
+ from datetime import datetime
3
+
4
+ from pypuppetdb.QueryBuilder import EqualsOperator
5
+ from pypuppetdb.api.base import BaseAPI
6
+ from pypuppetdb.types import (
7
+ Catalog,
8
+ Edge,
9
+ Event,
10
+ Fact,
11
+ Inventory,
12
+ Node,
13
+ Report,
14
+ Resource,
15
+ )
16
+
17
+ log = logging.getLogger(__name__)
18
+
19
+
20
+ class QueryAPI(BaseAPI):
21
+ """This class provides methods that interact with the `pdb/query/v4/*`
22
+ PuppetDB API endpoints.
23
+ """
24
+
25
+ def nodes(self, unreported=2, with_status=False, with_event_numbers=True, **kwargs):
26
+ r"""Query for nodes by either name or query. If both aren't
27
+ provided this will return a list of all nodes. This method
28
+ also (optionally) fetches the nodes status and (optionally)
29
+ event counts of the latest report from puppetdb.
30
+
31
+ :param with_status: (optional) include the node status in the\
32
+ returned nodes
33
+ :type with_status: :bool:
34
+ :param unreported: (optional) amount of hours when a node gets
35
+ marked as unreported
36
+ :type unreported: :obj:`None` or integer
37
+ :param with_event_numbers: (optional) include the exact number of\
38
+ changed/unchanged/failed/noop events when\
39
+ with_status is set to True. If set to False
40
+ only "some" string is provided if there are
41
+ resources with such status in the last report.
42
+ This provides performance benefits as potentially
43
+ slow event-counts query is omitted completely.
44
+ :type with_event_numbers: :bool:
45
+ :param \**kwargs: The rest of the keyword arguments are passed
46
+ to the _query function
47
+
48
+ :returns: A generator yieling Nodes.
49
+ :rtype: :class:`pypuppetdb.types.Node`
50
+ """
51
+ nodes = self._query("nodes", **kwargs)
52
+ now = datetime.utcnow()
53
+
54
+ # If we happen to only get one node back it
55
+ # won't be inside a list so iterating over it
56
+ # goes boom. Therefor we wrap a list around it.
57
+ if isinstance(nodes, dict):
58
+ nodes = [
59
+ nodes,
60
+ ]
61
+
62
+ latest_events = None
63
+ if with_status and with_event_numbers:
64
+ latest_events = self._query(
65
+ "event-counts",
66
+ query=EqualsOperator("latest_report?", True),
67
+ summarize_by="certname",
68
+ )
69
+
70
+ for node in nodes:
71
+ yield Node.create_from_dict(
72
+ self,
73
+ node,
74
+ with_status,
75
+ with_event_numbers,
76
+ latest_events,
77
+ now,
78
+ unreported,
79
+ )
80
+
81
+ def node(self, name):
82
+ """Gets a single node from PuppetDB.
83
+
84
+ :param name: The name of the node search.
85
+ :type name: :obj:`string`
86
+
87
+ :return: An instance of Node
88
+ :rtype: :class:`pypuppetdb.types.Node`
89
+ """
90
+ nodes = self.nodes(path=name)
91
+ return next(node for node in nodes)
92
+
93
+ def edges(self, **kwargs):
94
+ r"""Get the known catalog edges, formed between two resources.
95
+
96
+ :param \**kwargs: The rest of the keyword arguments are passed
97
+ to the _query function.
98
+
99
+ :returns: A generating yielding Edges.
100
+ :rtype: :class:`pypuppetdb.types.Edge`
101
+ """
102
+ edges = self._query("edges", **kwargs)
103
+
104
+ for edge in edges:
105
+ yield Edge.create_from_dict(edge)
106
+
107
+ def environments(self, **kwargs):
108
+ r"""Get all known environments from Puppetdb.
109
+
110
+ :param \**kwargs: The rest of the keyword arguments are passed
111
+ to the _query function.
112
+
113
+ :returns: A list of dictionaries containing the results.
114
+ :rtype: :obj:`list` of :obj:`dict`
115
+ """
116
+ return self._query("environments", **kwargs)
117
+
118
+ def facts(self, name=None, value=None, **kwargs):
119
+ r"""Query for facts limited by either name, value and/or query.
120
+
121
+ :param name: (Optional) Only return facts that match this name.
122
+ :type name: :obj:`string`
123
+ :param value: (Optional) Only return facts of `name` that\
124
+ match this value. Use of this parameter requires the `name`\
125
+ parameter be set.
126
+ :type value: :obj:`string`
127
+ :param \**kwargs: The rest of the keyword arguments are passed
128
+ to the _query function
129
+
130
+ :returns: A generator yielding Facts.
131
+ :rtype: :class:`pypuppetdb.types.Fact`
132
+ """
133
+ if name is not None and value is not None:
134
+ path = f"{name}/{value}"
135
+ elif name is not None and value is None:
136
+ path = name
137
+ else:
138
+ path = None
139
+
140
+ facts = self._query("facts", path=path, **kwargs)
141
+ for fact in facts:
142
+ yield Fact.create_from_dict(fact)
143
+
144
+ def factsets(self, **kwargs):
145
+ r"""Returns a set of all facts or for a single certname.
146
+
147
+ :param \**kwargs: The rest of the keyword arguments are passed
148
+ to the _query function.
149
+
150
+ :returns: A list of dictionaries containg the results.
151
+ :rtype: :obj:`list` of :obj:`dict`
152
+ """
153
+ return self._query("factsets", **kwargs)
154
+
155
+ def fact_contents(self, **kwargs):
156
+ r"""To complement fact_paths(), this endpoint provides the capability
157
+ to descend into structured facts and retreive the values associated
158
+ with fact paths.
159
+
160
+ :param \**kwargs: The rest of the keyword arguments are passed
161
+ to the _query function.
162
+
163
+ :returns: A list of dictionaries containg the results.
164
+ :rtype: :obj:`list` of :obj:`dict`
165
+ """
166
+ return self._query("fact-contents", **kwargs)
167
+
168
+ def fact_paths(self, **kwargs):
169
+ r"""Fact Paths are intended to be a counter-part of the fact-names
170
+ endpoint. It provides increased granularity around structured
171
+ facts and may be used for building GUI autocompletions or other
172
+ applications that require a basic top-level view of fact paths.
173
+
174
+ :param \**kwargs: The rest of the keyword arguments are passed
175
+ to the _query function.
176
+
177
+ :returns: A list of dictionaries containg the results.
178
+ :rtype: :obj:`list` of :obj:`dict`
179
+ """
180
+ return self._query("fact-paths", **kwargs)
181
+
182
+ def resources(self, type_=None, title=None, **kwargs):
183
+ r"""Query for resources limited by either type and/or title or query.
184
+ This will yield a Resources object for every returned resource.
185
+
186
+ :param type_: (Optional) The resource type. This can be any resource
187
+ type referenced in\
188
+ https://puppet.com/docs/puppet/7/type.html
189
+ :type type_: :obj:`string`
190
+ :param title: (Optional) The name of the resource as declared as the
191
+ 'namevar' in the Puppet Manifests. This parameter requires the\
192
+ `type_` parameter be set.
193
+ :type title: :obj:`string`
194
+ :param \**kwargs: The rest of the keyword arguments are passed
195
+ to the _query function
196
+
197
+ :returns: A generator yielding Resources
198
+ :rtype: :class:`pypuppetdb.types.Resource`
199
+ """
200
+
201
+ path = None
202
+
203
+ if type_ is not None:
204
+ type_ = self._normalize_resource_type(type_)
205
+
206
+ if title is not None:
207
+ path = f"{type_}/{title}"
208
+ elif title is None:
209
+ path = type_
210
+
211
+ resources = self._query("resources", path=path, **kwargs)
212
+ for resource in resources:
213
+ yield Resource.create_from_dict(resource)
214
+
215
+ def catalog(self, node):
216
+ """Get the available catalog for a given node.
217
+
218
+ :param node: (Required) The name of the PuppetDB node.
219
+ :type: :obj:`string`
220
+
221
+ :returns: An instance of Catalog
222
+ :rtype: :class:`pypuppetdb.types.Catalog`
223
+ """
224
+ catalogs = self.catalogs(path=node)
225
+ return next(catalog for catalog in catalogs)
226
+
227
+ def catalogs(self, **kwargs):
228
+ r"""Get the catalog information from the infrastructure based on path
229
+ and/or query results. It is strongly recommended to include query
230
+ and/or paging parameters for this endpoint to prevent large result
231
+ sets or PuppetDB performance bottlenecks.
232
+
233
+ :param \**kwargs: The rest of the keyword arguments are passed
234
+ to the _query function.
235
+
236
+ :returns: A generator yielding Catalogs
237
+ :rtype: :class:`pypuppetdb.types.Catalog`
238
+ """
239
+
240
+ catalogs = self._query("catalogs", **kwargs)
241
+
242
+ if isinstance(catalogs, dict):
243
+ catalogs = [
244
+ catalogs,
245
+ ]
246
+
247
+ for catalog in catalogs:
248
+ yield Catalog.create_from_dict(catalog)
249
+
250
+ def events(self, **kwargs):
251
+ r"""A report is made up of events which can be queried either
252
+ individually or based on their associated report hash. It is strongly
253
+ recommended to include query and/or paging parameters for this
254
+ endpoint to prevent large result sets or PuppetDB performance
255
+ bottlenecks.
256
+
257
+ :param \**kwargs: The rest of the keyword arguments are passed
258
+ to the _query function
259
+
260
+ :returns: A generator yielding Events
261
+ :rtype: :class:`pypuppetdb.types.Event`
262
+ """
263
+ events = self._query("events", **kwargs)
264
+ for event in events:
265
+ yield Event.create_from_dict(event)
266
+
267
+ def event_counts(self, summarize_by, **kwargs):
268
+ r"""Get event counts from puppetdb.
269
+
270
+ :param summarize_by: (Required) The object type to be counted on.
271
+ Valid values are 'containing_class', 'resource'
272
+ and 'certname'.
273
+ :type summarize_by: :obj:`string`
274
+ :param count_by: (Optional) The object type that is counted when
275
+ building the counts of 'successes', 'failures',
276
+ 'noops' and 'skips'. Support values are 'certname'
277
+ and 'resource' (default)
278
+ :type count_by: :obj:`string`
279
+ :param count_filter: (Optional) A JSON query that is applied to the
280
+ event-counts output but before the results are
281
+ aggregated. Supported operators are `=`, `>`,
282
+ `<`, `>=`, and `<=`. Supported fields are
283
+ `failures`, `successes`, `noops`, and `skips`.
284
+ :type count_filter: :obj:`string`
285
+ :param \**kwargs: The rest of the keyword arguments are passed
286
+ to the _query function.
287
+
288
+ :returns: A list of dictionaries containing the results.
289
+ :rtype: :obj:`list`
290
+ """
291
+ return self._query("event-counts", summarize_by=summarize_by, **kwargs)
292
+
293
+ def aggregate_event_counts(
294
+ self, summarize_by, query=None, count_by=None, count_filter=None
295
+ ):
296
+ """Get event counts from puppetdb aggregated into a single map.
297
+
298
+ :param summarize_by: (Required) The object type to be counted on.
299
+ Valid values are 'containing_class', 'resource'
300
+ and 'certname' or any comma-separated value
301
+ thereof.
302
+ :type summarize_by: :obj:`string`
303
+ :param query: (Optional) The PuppetDB query to filter the results.
304
+ This query is passed to the `events` endpoint.
305
+ :type query: :obj:`string`
306
+ :param count_by: (Optional) The object type that is counted when
307
+ building the counts of 'successes', 'failures',
308
+ 'noops' and 'skips'. Support values are 'certname'
309
+ and 'resource' (default)
310
+ :type count_by: :obj:`string`
311
+ :param count_filter: (Optional) A JSON query that is applied to the
312
+ event-counts output but before the results are
313
+ aggregated. Supported operators are `=`, `>`,
314
+ `<`, `>=`, and `<=`. Supported fields are
315
+ `failures`, `successes`, `noops`, and `skips`.
316
+ :type count_filter: :obj:`string`
317
+
318
+ :returns: A dictionary of name/value results.
319
+ :rtype: :obj:`dict`
320
+ """
321
+ return self._query(
322
+ "aggregate-event-counts",
323
+ query=query,
324
+ summarize_by=summarize_by,
325
+ count_by=count_by,
326
+ count_filter=count_filter,
327
+ )
328
+
329
+ def fact_names(self):
330
+ """Get a list of all known facts."""
331
+ return self._query("fact-names")
332
+
333
+ def reports(self, **kwargs):
334
+ r"""Get reports for our infrastructure. It is strongly recommended
335
+ to include query and/or paging parameters for this endpoint to
336
+ prevent large result sets and potential PuppetDB performance
337
+ bottlenecks.
338
+
339
+ :param \**kwargs: The rest of the keyword arguments are passed
340
+ to the _query function
341
+
342
+ :returns: A generating yielding Reports
343
+ :rtype: :class:`pypuppetdb.types.Report`
344
+ """
345
+ reports = self._query("reports", **kwargs)
346
+ for report in reports:
347
+ yield Report.create_from_dict(self, report)
348
+
349
+ def inventory(self, **kwargs):
350
+ r"""Get Node and Fact information with an alternative query syntax
351
+ for structured facts instead of using the facts, fact-contents and
352
+ factsets endpoints for many fact-related queries.
353
+
354
+ :param \**kwargs: The rest of the keyword arguments are passed
355
+ to the _query function.
356
+
357
+ :returns: A generator yielding Inventory
358
+ :rtype: :class:`pypuppetdb.types.Inventory`
359
+ """
360
+ inventory = self._query("inventory", **kwargs)
361
+ for inv in inventory:
362
+ yield Inventory.create_from_dict(inv)
@@ -0,0 +1,19 @@
1
+ import logging
2
+
3
+ from pypuppetdb.api.base import BaseAPI
4
+
5
+ log = logging.getLogger(__name__)
6
+
7
+
8
+ class StatusAPI(BaseAPI):
9
+ """This class provides methods that interact with the `status/*`
10
+ PuppetDB API endpoints.
11
+ """
12
+
13
+ def status(self):
14
+ """Get PuppetDB server status.
15
+
16
+ :returns: A dict with the PuppetDB status information
17
+ :rtype: :obj:`dict`
18
+ """
19
+ return self._query("status")
pypuppetdb/errors.py ADDED
@@ -0,0 +1,28 @@
1
+ class APIError(Exception):
2
+ """Our base exception the other errors inherit from."""
3
+
4
+ pass
5
+
6
+
7
+ class ImproperlyConfiguredError(APIError):
8
+ """This exception is thrown when the API is initialised
9
+ and it detects incompatible configuration such as SSL turned
10
+ on but no certificates provided."""
11
+
12
+ pass
13
+
14
+
15
+ class EmptyResponseError(APIError):
16
+ """Will be thrown when we did receive a response but the
17
+ response is empty."""
18
+
19
+ pass
20
+
21
+
22
+ class DoesNotComputeError(APIError):
23
+ """This error will be thrown when a function is called with
24
+ an incompatible set of optional parameters. This is the 'you are
25
+ being a naughty developer, go read the docs' error.
26
+ """
27
+
28
+ pass