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,735 @@
1
+ import datetime
2
+ import json
3
+ import logging
4
+
5
+ from pypuppetdb.errors import APIError
6
+
7
+ log = logging.getLogger(__name__)
8
+
9
+
10
+ class BinaryOperator:
11
+ """
12
+ This is a parent helper class used to create PuppetDB AST queries
13
+ for single key-value pairs for the available operators.
14
+
15
+ It is possible to directly declare the various types of queries
16
+ from this class. For instance the code
17
+ BinaryOperator('=', 'certname', 'node1.example.com') generates the
18
+ PuppetDB query '["=", "certname", "node1.example.com"]'. It is preferred
19
+ to use the child classes as they may have restrictions specific
20
+ to that operator.
21
+
22
+ See
23
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#binary-operators
24
+ for more information.
25
+
26
+ :param operator: The binary query operation performed. There is
27
+ no value checking on this field.
28
+ :type operator: :obj:`string`
29
+ :param field: The PuppetDB endpoint query field. See endpoint
30
+ documentation for valid values.
31
+ :type field: any
32
+ :param value: The values of the field to match, or not match.
33
+ :type value: any
34
+ """
35
+
36
+ def __init__(self, operator, field, value):
37
+ if isinstance(value, datetime.datetime):
38
+ value = str(value)
39
+ self.data = [operator, field, value]
40
+
41
+ def __repr__(self):
42
+ return f"Query: {self}"
43
+
44
+ def __str__(self):
45
+ return json.dumps(self.json_data())
46
+
47
+ def json_data(self):
48
+ return self.data
49
+
50
+
51
+ class BooleanOperator:
52
+ """
53
+ This is a parent helper class used to create PuppetDB AST queries
54
+ for available boolean queries.
55
+
56
+ It is possible to directly declare a boolean query from this class.
57
+ For instance the code BooleanOperator("and") will create an empty
58
+ query '["and",]'. An error will be raised if there are no queries
59
+ added via :func:`~pypuppetdb.QueryBuilder.BooleanOperator.add`
60
+
61
+ See
62
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#binary-operators
63
+ for more information.
64
+
65
+ :param operator: The boolean query operation to perform.
66
+ :type operator: :obj:`string`
67
+ """
68
+
69
+ def __init__(self, operator):
70
+ self.operator = operator
71
+ self.operations = []
72
+
73
+ def add(self, query):
74
+ if isinstance(query, list):
75
+ for i in query:
76
+ self.add(i)
77
+ elif isinstance(query, str):
78
+ self.operations.append(json.loads(query))
79
+ elif isinstance(query, (BinaryOperator, InOperator, BooleanOperator)):
80
+ self.operations.append(query.json_data())
81
+ else:
82
+ raise APIError(
83
+ "Can only accept fixed-string queries, arrays " + "or operator objects"
84
+ )
85
+
86
+ def __repr__(self):
87
+ return f"Query: {self}"
88
+
89
+ def __str__(self):
90
+ return json.dumps(self.json_data())
91
+
92
+ def json_data(self):
93
+ if len(self.operations) == 0:
94
+ raise APIError("At least one query operation is required")
95
+ return [self.operator] + self.operations
96
+
97
+
98
+ class ExtractOperator:
99
+ """
100
+ Queries that either do not or cannot require all the key-value pairs
101
+ from an endpoint can use the Extract Operator as described in
102
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#projection-operators.
103
+
104
+ The syntax of this operator requires a function and/or a list of fields,
105
+ an optional standard query and an optional group by clause including a
106
+ list of fields.
107
+ """
108
+
109
+ def __init__(self):
110
+ self.fields = []
111
+ self.query = None
112
+ self.group_by = []
113
+
114
+ def add_field(self, field):
115
+ if isinstance(field, list):
116
+ for i in field:
117
+ self.add_field(i)
118
+ elif isinstance(field, str):
119
+ self.fields.append(field)
120
+ elif isinstance(field, FunctionOperator):
121
+ self.fields.append(field.json_data())
122
+ else:
123
+ raise APIError(
124
+ "ExtractOperator.add_field only supports " "lists and strings"
125
+ )
126
+
127
+ def add_query(self, query):
128
+ if self.query is not None:
129
+ raise APIError("Only one query is supported by ExtractOperator")
130
+ elif isinstance(query, str):
131
+ self.query = json.loads(query)
132
+ elif isinstance(query, (BinaryOperator, SubqueryOperator, BooleanOperator)):
133
+ self.query = query.json_data()
134
+ else:
135
+ raise APIError(
136
+ "ExtractOperator.add_query only supports "
137
+ "strings, BinaryOperator, BooleanOperator "
138
+ "and SubqueryOperator objects"
139
+ )
140
+
141
+ def add_group_by(self, field):
142
+ if isinstance(field, list):
143
+ for i in field:
144
+ self.add_group_by(i)
145
+ elif isinstance(field, str):
146
+ if len(self.group_by) == 0:
147
+ self.group_by.append("group_by")
148
+ self.group_by.append(field)
149
+ elif isinstance(field, FunctionOperator):
150
+ if len(self.group_by) == 0:
151
+ self.group_by.append("group_by")
152
+ self.group_by.append(field.json_data())
153
+ else:
154
+ raise APIError(
155
+ "ExtractOperator.add_group_by only supports "
156
+ "lists, strings, and FunctionOperator objects"
157
+ )
158
+
159
+ def __repr__(self):
160
+ return f"Query: {self}"
161
+
162
+ def __str__(self):
163
+ return json.dumps(self.json_data())
164
+
165
+ def json_data(self):
166
+ if len(self.fields) == 0:
167
+ raise APIError("ExtractOperator needs at least one field")
168
+
169
+ arr = ["extract", self.fields]
170
+
171
+ if self.query is not None:
172
+ arr.append(self.query)
173
+ if len(self.group_by) > 0:
174
+ arr.append(self.group_by)
175
+
176
+ return arr
177
+
178
+
179
+ class FunctionOperator:
180
+ """
181
+ Performs an aggregate function on the result of a subquery, full
182
+ documentation is available at
183
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#function.
184
+ This object can only be used in the field list or group by list of
185
+ an ExtractOperator object.
186
+
187
+ :param function: The name of the function to perform.
188
+ :type function: :obj:`str`
189
+ :param field: The name of the field to perform the function on. All
190
+ functions with the exception of count require this value.
191
+ :type field: :obj:`str`
192
+ """
193
+
194
+ def __init__(self, function, field=None, fmt=None):
195
+ if function not in ["count", "avg", "sum", "min", "max", "to_string"]:
196
+ raise APIError(f"Unsupport function: {function}")
197
+ elif function != "count" and field is None:
198
+ raise APIError("Function {} requires a field value".format(function))
199
+ elif function == "to_string" and fmt is None:
200
+ raise APIError("Function {0} requires an extra 'fmt' parameter")
201
+
202
+ self.arr = ["function", function]
203
+
204
+ if field is not None:
205
+ self.arr.append(field)
206
+
207
+ if function == "to_string":
208
+ self.arr.append(fmt)
209
+
210
+ def __repr__(self):
211
+ return f"Query: {self}"
212
+
213
+ def __str__(self):
214
+ return json.dumps(self.json_data())
215
+
216
+ def json_data(self):
217
+ return self.arr
218
+
219
+
220
+ class SubqueryOperator:
221
+ """
222
+ Performs a subquery to another puppetDB object, full
223
+ documentation is available at
224
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#subquery-operators
225
+ This object must be used in combination with the InOperator according
226
+ to documentation.
227
+
228
+ :param endpoint: The name of the subquery object
229
+ :type function: :obj:`str`
230
+ """
231
+
232
+ def __init__(self, endpoint):
233
+ if endpoint not in [
234
+ "catalogs",
235
+ "edges",
236
+ "environments",
237
+ "events",
238
+ "facts",
239
+ "fact_contents",
240
+ "fact_paths",
241
+ "nodes",
242
+ "reports",
243
+ "resources",
244
+ ]:
245
+ raise APIError(f"Unsupported endpoint: {endpoint}")
246
+
247
+ self.query = None
248
+ self.arr = [f"select_{endpoint}"]
249
+
250
+ def add_query(self, query):
251
+ if self.query is not None:
252
+ raise APIError("Only one query is supported by ExtractOperator")
253
+ else:
254
+ self.query = True
255
+ self.arr.append(query.json_data())
256
+
257
+ def __repr__(self):
258
+ return f"Query: {self}"
259
+
260
+ def __str__(self):
261
+ return json.dumps(self.json_data())
262
+
263
+ def json_data(self):
264
+ return self.arr
265
+
266
+
267
+ class InOperator:
268
+ """
269
+ Performs boolean compare between a field a subquery result
270
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#subquery-operators
271
+ This object must be used in combination with the SubqueryOperator according
272
+ to documentation.
273
+
274
+ :param field: The name of the subquery object
275
+ :type function: :obj:`str`
276
+ """
277
+
278
+ def __init__(self, field):
279
+ self.query = None
280
+ self.arr = ["in", field]
281
+
282
+ def add_query(self, query):
283
+ if self.query is not None:
284
+ raise APIError("Only one query is supported by ExtractOperator")
285
+ elif isinstance(query, str):
286
+ self.query = True
287
+ self.arr.append(json.loads(query))
288
+ elif isinstance(query, (ExtractOperator, FromOperator)):
289
+ self.query = True
290
+ self.arr.append(query.json_data())
291
+ else:
292
+ raise APIError(
293
+ "InOperator.add_query only supports "
294
+ "strings, ExtractOperator, and"
295
+ "FromOperator objects"
296
+ )
297
+
298
+ def add_array(self, values):
299
+ if self.query is not None:
300
+ raise APIError("Only one array is supported by the InOperator")
301
+ elif isinstance(values, list):
302
+
303
+ def depth(a_list):
304
+ return (isinstance(a_list, list) and len(a_list) != 0) and max(
305
+ map(depth, a_list)
306
+ ) + 1
307
+
308
+ if depth(values) == 1:
309
+ self.query = True
310
+ self.arr.append(["array", values])
311
+ else:
312
+ raise APIError(
313
+ "InOperator.add_array: cannot pass in "
314
+ "nested arrays (or empty arrays)"
315
+ )
316
+ else:
317
+ raise APIError(
318
+ "InOperator.add_array: Ill-formatted array, "
319
+ "must be of the format: "
320
+ "['array', [<array values>]]"
321
+ )
322
+
323
+ def __repr__(self):
324
+ return f"Query: {self}"
325
+
326
+ def __str__(self):
327
+ return json.dumps(self.json_data())
328
+
329
+ def json_data(self):
330
+ return self.arr
331
+
332
+
333
+ class FromOperator:
334
+ """
335
+ From contextual operator that allows for queries on the root endpoint
336
+ or subqueries into other entities:
337
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#from
338
+
339
+ Ex.)
340
+ fr = FromOperator("facts")
341
+ fr.add_query(EqualsOperator("foo", "bar"))
342
+ fr.add_order_by(["certname"])
343
+ fr.add_limit(10)
344
+
345
+ note: only supports single entity From operations
346
+ """
347
+
348
+ def __init__(self, endpoint):
349
+ valid_entities = [
350
+ "aggregate_event_counts",
351
+ "catalogs",
352
+ "edges",
353
+ "environments",
354
+ "event_counts",
355
+ "events",
356
+ "facts",
357
+ "fact_contents",
358
+ "fact_names",
359
+ "fact_paths",
360
+ "nodes",
361
+ "producers",
362
+ "reports",
363
+ "resources",
364
+ ]
365
+
366
+ if endpoint in valid_entities:
367
+ self.endpoint = endpoint
368
+ else:
369
+ raise APIError(
370
+ "Endpoint is invalid. Must be "
371
+ "one of the following : %s" % valid_entities
372
+ )
373
+
374
+ self.query = None
375
+ self.order_by = []
376
+ self.limit = None
377
+ self.offset = None
378
+
379
+ def add_query(self, query):
380
+ if self.query is not None:
381
+ raise APIError("Only one main query is supported by FromOperator")
382
+ elif isinstance(
383
+ query,
384
+ (
385
+ InOperator,
386
+ ExtractOperator,
387
+ BinaryOperator,
388
+ BooleanOperator,
389
+ FunctionOperator,
390
+ ),
391
+ ):
392
+ self.query = query.json_data()
393
+ else:
394
+ raise APIError("FromOperator.add_field only supports " "Operator Objects")
395
+
396
+ def add_order_by(self, fields):
397
+ def depth(a_list):
398
+ return isinstance(a_list, list) and max(map(depth, a_list)) + 1
399
+
400
+ fields_depth = depth(fields)
401
+
402
+ if isinstance(fields, list):
403
+ if fields_depth == 1 or fields_depth == 2:
404
+ self.order_by = fields
405
+ else:
406
+ raise APIError(
407
+ "ExtractOperator.add_order_by only "
408
+ "supports lists of fields of depth "
409
+ "one or two: [value, <desc/asc>] or "
410
+ "[value]"
411
+ )
412
+ else:
413
+ raise APIError(
414
+ "ExtractOperator.add_group_by only supports "
415
+ "lists of one or more fields"
416
+ )
417
+
418
+ def add_limit(self, lim):
419
+ if isinstance(lim, int):
420
+ self.limit = lim
421
+ else:
422
+ raise APIError("ExtractOperator.add_limit only supports ints")
423
+
424
+ def add_offset(self, off):
425
+ if isinstance(off, int):
426
+ self.offset = off
427
+ else:
428
+ raise APIError("ExtractOperator.add_offset only supports ints")
429
+
430
+ def __repr__(self):
431
+ return f"Query: {self}"
432
+
433
+ def __str__(self):
434
+ return json.dumps(self.json_data())
435
+
436
+ def json_data(self):
437
+ if self.query is None:
438
+ raise APIError("FromOperator needs one main query")
439
+
440
+ arr = ["from", self.endpoint, self.query]
441
+
442
+ if len(self.order_by) > 0:
443
+ arr.append(["order_by", self.order_by])
444
+ if self.limit is not None:
445
+ arr.append(["limit", self.limit])
446
+ if self.offset is not None:
447
+ arr.append(["offset", self.offset])
448
+
449
+ return arr
450
+
451
+
452
+ class EqualsOperator(BinaryOperator):
453
+ """
454
+ Builds an equality filter based on the supplied field-value pair as
455
+ described
456
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#equality.
457
+
458
+ In order to create the following query:
459
+
460
+ ["=", "environment", "production"]
461
+
462
+ The following code can be used.
463
+
464
+ EqualsOperator('environment', 'production')
465
+
466
+ :param field: The PuppetDB endpoint query field. See endpoint
467
+ documentation for valid values.
468
+ :type field: any
469
+ :param value: The value of the field to match, or not match.
470
+ :type value: any
471
+ """
472
+
473
+ def __init__(self, field, value):
474
+ super().__init__("=", field, value)
475
+
476
+
477
+ class GreaterOperator(BinaryOperator):
478
+ """
479
+ Builds a greater-than filter based on the supplied field-value pair as
480
+ described
481
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#greater-than.
482
+
483
+ In order to create the following query:
484
+
485
+ [">", "catalog_timestamp", "2016-06-01 00:00:00"]
486
+
487
+ The following code can be used.
488
+
489
+ GreaterOperator('catalog_timestamp', datetime.datetime(2016, 06, 01))
490
+
491
+ :param field: The PuppetDB endpoint query field. See endpoint
492
+ documentation for valid values.
493
+ :type field: any
494
+ :param value: Matches if the field is greater than this value.
495
+ :type value: Number, timestamp or array
496
+ """
497
+
498
+ def __init__(self, field, value):
499
+ super().__init__(">", field, value)
500
+
501
+
502
+ class LessOperator(BinaryOperator):
503
+ """
504
+ Builds a less-than filter based on the supplied field-value pair as
505
+ described
506
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#less-than.
507
+
508
+ In order to create the following query:
509
+
510
+ ["<", "catalog_timestamp", "2016-06-01 00:00:00"]
511
+
512
+ The following code can be used.
513
+
514
+ LessOperator('catalog_timestamp', datetime.datetime(2016, 06, 01))
515
+
516
+ :param field: The PuppetDB endpoint query field. See endpoint
517
+ documentation for valid values.
518
+ :type field: any
519
+ :param value: Matches if the field is less than this value.
520
+ :type value: Number, timestamp or array
521
+ """
522
+
523
+ def __init__(self, field, value):
524
+ super().__init__("<", field, value)
525
+
526
+
527
+ class GreaterEqualOperator(BinaryOperator):
528
+ """
529
+ Builds a greater-than or equal-to filter based on the supplied
530
+ field-value pair as described
531
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#greater-than-or-equal-to.
532
+
533
+ In order to create the following query:
534
+
535
+ [">=", "facts_timestamp", "2016-06-01 00:00:00"]
536
+
537
+ The following code can be used.
538
+
539
+ GreaterEqualOperator('facts_timestamp', datetime.datetime(2016, 06, 01))
540
+
541
+ :param field: The PuppetDB endpoint query field. See endpoint
542
+ documentation for valid values.
543
+ :type field: any
544
+ :param value: Matches if the field is greater than or equal to\
545
+ this value.
546
+ :type value: Number, timestamp or array
547
+ """
548
+
549
+ def __init__(self, field, value):
550
+ super().__init__(">=", field, value)
551
+
552
+
553
+ class LessEqualOperator(BinaryOperator):
554
+ """
555
+ Builds a less-than or equal-to filter based on the supplied
556
+ field-value pair as described
557
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#less-than-or-equal-to.
558
+
559
+ In order to create the following query:
560
+
561
+ ["<=", "facts_timestamp", "2016-06-01 00:00:00"]
562
+
563
+ The following code can be used.
564
+
565
+ LessEqualOperator('facts_timestamp', datetime.datetime(2016, 06, 01))
566
+
567
+ :param field: The PuppetDB endpoint query field. See endpoint
568
+ documentation for valid values.
569
+ :type field: any
570
+ :param value: Matches if the field is less than or equal to\
571
+ this value.
572
+ :type value: Number, timestamp or array
573
+ """
574
+
575
+ def __init__(self, field, value):
576
+ super().__init__("<=", field, value)
577
+
578
+
579
+ class RegexOperator(BinaryOperator):
580
+ """
581
+ Builds a regular expression filter based on the supplied field-value
582
+ pair as described
583
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#regexp-match.
584
+
585
+ In order to create the following query:
586
+
587
+ ["~", "certname", "www\\d+\\.example\\.com"]
588
+
589
+ The following code can be used.
590
+
591
+ RegexOperator('certname', 'www\\d+\\.example\\.com')
592
+
593
+ :param field: The PuppetDB endpoint query field. See endpoint
594
+ documentation for valid values.
595
+ :type field: any
596
+ :param value: Matches if the field matches this regular expression.
597
+ :type value: :obj:`string`
598
+ """
599
+
600
+ def __init__(self, field, value):
601
+ super().__init__("~", field, value)
602
+
603
+
604
+ class RegexArrayOperator(BinaryOperator):
605
+ """
606
+ Builds a regular expression array filter based on the supplied
607
+ field-value pair. This query only works on fields with paths as
608
+ described
609
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#regexp-array-match.
610
+
611
+ In order to create the following query:
612
+
613
+ ["~", "path", ["networking", "eth.*", "macaddress"]]
614
+
615
+ The following code can be used.
616
+
617
+ RegexArrayOperator('path', ["networking", "eth.*", "macaddress"])
618
+
619
+ :param field: The PuppetDB endpoint query field. See endpoint
620
+ documentation for valid values.
621
+ :type field: any
622
+ :param value: Matches if the field matches this regular expression.
623
+ :type value: :obj:`list`
624
+ """
625
+
626
+ def __init__(self, field, value):
627
+ super().__init__("~>", field, value)
628
+
629
+
630
+ class NullOperator(BinaryOperator):
631
+ """
632
+ Builds a null filter based on the field and boolean value pair as
633
+ described
634
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#null-is-null.
635
+ This filter only works on field that may be null. Value may only
636
+ be True or False.
637
+
638
+ In order to create the following query:
639
+
640
+ ["null?", "deactivated", true]
641
+
642
+ The following code can be used.
643
+
644
+ NullOperator('deactivated', True)
645
+
646
+ :param field: The PuppetDB endpoint query field. See endpoint
647
+ documentation for valid values.
648
+ :type field: any
649
+ :param value: Matches if the field value is null (if True) or\
650
+ not null (if False)
651
+ :type value: :obj:`bool`
652
+ """
653
+
654
+ def __init__(self, field, value):
655
+ if not isinstance(value, bool):
656
+ raise APIError("NullOperator value must be boolean")
657
+
658
+ super().__init__("null?", field, value)
659
+
660
+
661
+ class AndOperator(BooleanOperator):
662
+ """
663
+ Builds an AND boolean filter. Only results that match ALL
664
+ criteria from the included query strings will be returned
665
+ from PuppetDB. Full documentation is available
666
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#and
667
+
668
+ In order to create the following query:
669
+
670
+ ["and",
671
+ ["=", "catalog_environment", "production"],
672
+ ["=", "facts_environment", "production"]]
673
+
674
+ The following code can be used:
675
+
676
+ op = AndOperator()
677
+ op.add(EqualsOperator("catalog_environment", "production"))
678
+ op.add(EqualsOperator("facts_environment", "production"))
679
+ """
680
+
681
+ def __init__(self):
682
+ super().__init__("and")
683
+
684
+
685
+ class OrOperator(BooleanOperator):
686
+ """
687
+ Builds an OR boolean filter. Only results that match ANY
688
+ criteria from the included query strings will be returned
689
+ from PuppetDB. Full documentation is available
690
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#or.
691
+
692
+ In order to create the following query:
693
+
694
+ ["or", ["=", "name", "hostname"], ["=", "name", "architecture"]]
695
+
696
+ The following code can be used:
697
+
698
+ op = OrOperator()
699
+ op.add(EqualsOperator("name", "hostname"))
700
+ op.add(EqualsOperator("name", "architecture"))
701
+ """
702
+
703
+ def __init__(self):
704
+ super().__init__("or")
705
+
706
+
707
+ class NotOperator(BooleanOperator):
708
+ """
709
+ Builds a NOT boolean filter. Only results that DO NOT match
710
+ criteria from the included query strings will be returned
711
+ from PuppetDB. Full documentation is available
712
+ https://puppet.com/docs/puppetdb/7/api/query/v4/ast.html#not
713
+
714
+ Unlike the other Boolean Operator objects this operator only
715
+ accepts a single query string.
716
+
717
+ In order to create the following query:
718
+
719
+ ["not", ["=", "osfamily", "RedHat"]]
720
+
721
+ The following code can be used.
722
+
723
+ op = NotOperator()
724
+ op.add(EqualsOperator("osfamily", "RedHat"))
725
+ """
726
+
727
+ def __init__(self):
728
+ super().__init__("not")
729
+
730
+ def add(self, query):
731
+ if len(self.operations) > 0:
732
+ raise APIError("This operator only accept one query string")
733
+ elif isinstance(query, list) and len(query) > 1:
734
+ raise APIError("This operator only accept one query string")
735
+ super().add(query)