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/types.py ADDED
@@ -0,0 +1,935 @@
1
+ import logging
2
+ from datetime import timedelta
3
+
4
+ from pypuppetdb.QueryBuilder import EqualsOperator, AndOperator
5
+ from pypuppetdb.utils import json_to_datetime
6
+
7
+ log = logging.getLogger(__name__)
8
+
9
+
10
+ class Event:
11
+ """This object represents an event. Unless otherwise specified all
12
+ parameters are required.
13
+
14
+ :param node: The hostname of the node this event fired on.
15
+ :type node: :obj:`string`
16
+ :param status: The status for the event.
17
+ :type status: :obj:`string`
18
+ :param timestamp: A timestamp of when this event occured.
19
+ :type timestamp: :obj:`string` formatted as ``%Y-%m-%dT%H:%M:%S.%fZ``
20
+ :param hash_: The hash of the report that contains this event.
21
+ :type hash_: :obj:`string`
22
+ :param title: The resource title this event was fired for.
23
+ :type title: :obj:`string`
24
+ :param property_: The property of the resource this event was fired for.
25
+ :type property_: :obj:`string`
26
+ :param message: A message associated with this event.
27
+ :type message: :obj:`string`
28
+ :param new_value: The new value/state of the resource.
29
+ :type new_value: :obj:`string`
30
+ :param old_value: The old value/state of the resource.
31
+ :type old_value: :obj:`string`
32
+ :param type_: The type of the resource this event fired for.
33
+ :type type_: :obj:`string`
34
+ :param class_: The class responsible for running this event.
35
+ :type class_: :obj:`string`
36
+ :param execution_path: The path used to reach this particular resource.
37
+ :type execution_path: :obj:`string`
38
+ :param source_file: The puppet source code file containing the class.
39
+ :type source_file: :obj:`string`
40
+ :param line_number: The line number in the source file containing the
41
+ definition responsible for triggering this event.
42
+ :type line_number: :obj:`int`
43
+
44
+ :ivar node: A :obj:`string` of this event's node certname.
45
+ :ivar status: A :obj:`string` of this event's status.
46
+ :ivar failed: The :obj:`bool` equivalent of `status`.
47
+ :ivar timestamp: A :obj:`datetime.datetime` of when this event happend.
48
+ :ivar node: The hostname of the machine this event\
49
+ occured on.
50
+ :ivar hash_: The hash of this event.
51
+ :ivar item: :obj:`dict` with information about the item/resource this\
52
+ event was triggered for.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ node,
58
+ status,
59
+ timestamp,
60
+ hash_,
61
+ title,
62
+ property_,
63
+ message,
64
+ new_value,
65
+ old_value,
66
+ type_,
67
+ class_,
68
+ execution_path,
69
+ source_file,
70
+ line_number,
71
+ ):
72
+ self.node = node
73
+ self.status = status
74
+ if self.status == "failure":
75
+ self.failed = True
76
+ else:
77
+ self.failed = False
78
+ self.timestamp = json_to_datetime(timestamp)
79
+ self.hash_ = hash_
80
+ self.item = {
81
+ "title": title,
82
+ "type": type_,
83
+ "property": property_,
84
+ "message": message,
85
+ "old": old_value,
86
+ "new": new_value,
87
+ "class": class_,
88
+ "execution_path": execution_path,
89
+ "source_file": source_file,
90
+ "line_number": line_number,
91
+ }
92
+ self.__string = "{}[{}]/{}".format(
93
+ self.item["type"], self.item["title"], self.hash_
94
+ )
95
+
96
+ def __repr__(self):
97
+ return str(f"Event: {self.__string}")
98
+
99
+ def __str__(self):
100
+ return "{}".format(self.__string)
101
+
102
+ @staticmethod
103
+ def create_from_dict(event):
104
+ return Event(
105
+ node=event["certname"],
106
+ status=event["status"],
107
+ timestamp=event["timestamp"],
108
+ hash_=event["report"],
109
+ title=event["resource_title"],
110
+ property_=event["property"],
111
+ message=event["message"],
112
+ new_value=event["new_value"],
113
+ old_value=event["old_value"],
114
+ type_=event["resource_type"],
115
+ class_=event["containing_class"],
116
+ execution_path=event["containment_path"],
117
+ source_file=event["file"],
118
+ line_number=event["line"],
119
+ )
120
+
121
+
122
+ class Report:
123
+ """This object represents a report. Unless otherwise specified all
124
+ parameters are required.
125
+
126
+ :param api: API object
127
+ :type api: :class:`pypuppetdb.api.BaseAPI`
128
+ :param node: The hostname of the node this report originated on.
129
+ :type node: :obj:`string`
130
+ :param hash_: A string uniquely identifying this report.
131
+ :type hash_: :obj:`string`
132
+ :param start: The start time of the agent run.
133
+ :type start: :obj:`string` formatted as ``%Y-%m-%dT%H:%M:%S.%fZ``
134
+ :param end: The time the agent finished its run.
135
+ :type end: :obj:`string` formatted as ``%Y-%m-%dT%H:%M:%S.%fZ``
136
+ :param received: The time PuppetDB received the report.
137
+ :type received: :obj:`string` formatted as ``%Y-%m-%dT%H:%M:%S.%fZ``
138
+ :param version: The catalog / configuration version.
139
+ :type version: :obj:`string`
140
+ :param format_: The catalog format version.
141
+ :type format_: :obj:`int`
142
+ :param agent_version: The Puppet agent version.
143
+ :type agent_version: :obj:`string`
144
+ :param transaction: The UUID of this transaction.
145
+ :type transaction: :obj:`string`
146
+ :param environment: (Optional) The environment assigned to the node that\
147
+ submitted this report.
148
+ :type environment: :obj:`string`
149
+ :param status: (Optional) The status associated to this report's node.
150
+ :type status: :obj:`string`
151
+ :param noop: (Default `False`) A flag indicating weather the report was\
152
+ produced by a noop run.
153
+ :type noop: :obj:`bool`
154
+ :param noop_pending: (Default `False`) A flag indicating weather the \
155
+ report had pending changes produced by a noop run.
156
+ :type noop_pending: :obj:`bool`
157
+ :param metrics: (Optional) All metrics associated with this report.
158
+ :type metrics: :obj:`list` containing :obj:`dict` with Metrics
159
+ :param logs: (Optional) All logs associated with this report.
160
+ :type logs: :obj:`list` containing :obj:`dict` of logs
161
+ :param code_id: (Optional) Ties the catalog to the Puppet Code that\
162
+ generated the catalog.
163
+ :type code_id: :obj:`string`
164
+ :param catalog_uuid: (Optional) Ties the report to the catalog used\
165
+ from that Puppet run.
166
+ :type catalog_uuid: :obj:`string`
167
+ :param cached_catalog_status: (Optional) Identifies if the Puppet run\
168
+ used a cached catalog and weather or not it was used due to an\
169
+ error. Can be one of 'explicitly_requested', 'on_failure',\
170
+ 'not_used' not 'null'.
171
+ :type cached_catalog_status: :obj:`string`
172
+ :param producer: (Optional) The certname of the Puppet Server that\
173
+ sent the report to PuppetDB
174
+ :type producer: :obj:`string`
175
+
176
+ :ivar node: The hostname this report originated from.
177
+ :ivar hash_: Unique identifier of this report.
178
+ :ivar start: :obj:`datetime.datetime` when the Puppet agent run started.
179
+ :ivar end: :obj:`datetime.datetime` when the Puppet agent run ended.
180
+ :ivar received: :obj:`datetime.datetime` when the report finished uploading.
181
+ :ivar version: :obj:`string` catalog configuration version.
182
+ :ivar format_: :obj:`int` catalog format version.
183
+ :ivar agent_version: :obj:`string` Puppet Agent version.
184
+ :ivar run_time: :obj:`datetime.timedelta` of **end** - **start**.
185
+ :ivar transaction: UUID identifying this transaction.
186
+ :ivar environment: The environment assigned to the node that submitted\
187
+ this report.
188
+ :ivar status: The status associated to this report's node.
189
+ :ivar metrics: :obj:`list` containing :obj:`dict` of all metrics\
190
+ associated with this report.
191
+ :ivar logs: :obj:`list` containing :obj:`dict` of all logs\
192
+ associated with this report.
193
+ :ivar code_id: :obj:`string` used to tie a catalog to the Puppet Code\
194
+ which generated the catalog.
195
+ :ivar catalog_uuid: :obj:`string` used to tie this report to the catalog\
196
+ used on this Puppet run.
197
+ :ivar cached_catalog_status: :obj:`string` identifying if this Puppet run\
198
+ used a cached catalog, if so weather it was a result of an error or\
199
+ otherwise.
200
+ :ivar producer: :obj:`string` representing the certname of the Puppet\
201
+ Server that sent the report to PuppetDB
202
+ """
203
+
204
+ def __init__(
205
+ self,
206
+ api,
207
+ node,
208
+ hash_,
209
+ start,
210
+ end,
211
+ received,
212
+ version,
213
+ format_,
214
+ agent_version,
215
+ transaction,
216
+ status=None,
217
+ metrics={},
218
+ logs={},
219
+ environment=None,
220
+ noop=False,
221
+ noop_pending=False,
222
+ code_id=None,
223
+ catalog_uuid=None,
224
+ cached_catalog_status=None,
225
+ producer=None,
226
+ ):
227
+ self.node = node
228
+ self.hash_ = hash_
229
+ self.start = json_to_datetime(start)
230
+ self.end = json_to_datetime(end)
231
+ self.received = json_to_datetime(received)
232
+ self.version = version
233
+ self.format_ = format_
234
+ self.agent_version = agent_version
235
+ self.run_time = self.end - self.start
236
+ self.transaction = transaction
237
+ self.environment = environment
238
+ self.status = "noop" if noop and noop_pending else status
239
+ self.metrics = metrics
240
+ self.logs = logs
241
+ self.code_id = code_id
242
+ self.catalog_uuid = catalog_uuid
243
+ self.cached_catalog_status = cached_catalog_status
244
+ self.producer = producer
245
+ self.__string = f"{self.hash_}"
246
+
247
+ self.__api = api
248
+
249
+ def __repr__(self):
250
+ return str(f"Report: {self.__string}")
251
+
252
+ def __str__(self):
253
+ return "{}".format(self.__string)
254
+
255
+ def events(self, **kwargs):
256
+ """Get all events for this report. Additional arguments may also be
257
+ specified that will be passed to the query function.
258
+ """
259
+ return self.__api.events(query=EqualsOperator("report", self.hash_), **kwargs)
260
+
261
+ @staticmethod
262
+ def create_from_dict(query_api, report):
263
+ return Report(
264
+ api=query_api,
265
+ node=report["certname"],
266
+ hash_=report["hash"],
267
+ start=report["start_time"],
268
+ end=report["end_time"],
269
+ received=report["receive_time"],
270
+ version=report["configuration_version"],
271
+ format_=report["report_format"],
272
+ agent_version=report["puppet_version"],
273
+ transaction=report["transaction_uuid"],
274
+ environment=report["environment"],
275
+ status=report["status"],
276
+ noop=report.get("noop"),
277
+ noop_pending=report.get("noop_pending"),
278
+ metrics=report["metrics"]["data"],
279
+ logs=report["logs"]["data"],
280
+ code_id=report.get("code_id"),
281
+ catalog_uuid=report.get("catalog_uuid"),
282
+ cached_catalog_status=report.get("cached_catalog_status"),
283
+ )
284
+
285
+
286
+ class Fact:
287
+ """This object represents a fact. Unless otherwise specified all
288
+ parameters are required.
289
+
290
+ :param node: The hostname this fact was collected from.
291
+ :type node: :obj:`string`
292
+ :param name: The fact's name, such as 'osfamily'
293
+ :type name: :obj:`string`
294
+ :param value: The fact's value, such as 'Debian'
295
+ :type value: :obj:`string` or :obj:`int` or :obj:`dict`
296
+ :param environment: (Optional) The fact's environment, such as\
297
+ 'production'
298
+ :type environment: :obj:`string`
299
+
300
+ :ivar node: :obj:`string` holding the hostname.
301
+ :ivar name: :obj:`string` holding the fact's name.
302
+ :ivar value: :obj:`string` or :obj:`int` or :obj:`dict` holding the\
303
+ fact's value.
304
+ :ivar environment: :obj:`string` holding the fact's environment
305
+ """
306
+
307
+ @staticmethod
308
+ def create_from_dict(fact):
309
+ return Fact(
310
+ node=fact["certname"],
311
+ name=fact["name"],
312
+ value=fact["value"],
313
+ environment=fact["environment"],
314
+ )
315
+
316
+ def __init__(self, node, name, value, environment=None):
317
+ self.node = node
318
+ self.name = name
319
+ self.value = value
320
+ self.environment = environment
321
+ self.__string = f"{self.name}/{self.node}"
322
+
323
+ def __repr__(self):
324
+ return str(f"Fact: {self.__string}")
325
+
326
+ def __str__(self):
327
+ return "{}".format(self.__string)
328
+
329
+
330
+ class Resource:
331
+ """This object represents a resource. Unless otherwise specified all
332
+ parameters are required.
333
+
334
+ :param node: The hostname this resource is located on.
335
+ :type node: :obj:`string`
336
+ :param name: The name of the resource in the Puppet manifest.
337
+ :type name: :obj:`string`
338
+ :param type_: Type of the Puppet resource.
339
+ :type type_: :obj:`string`
340
+ :param tags: Tags associated with this resource.
341
+ :type tags: :obj:`list`
342
+ :param exported: If it's an exported resource.
343
+ :type exported: :obj:`bool`
344
+ :param sourcefile: The Puppet manifest this resource is declared in.
345
+ :type sourcefile: :obj:`string`
346
+ :param sourceline: The line this resource is declared at.
347
+ :type sourceline: :obj:`int`
348
+ :param parameters: (Optional) The parameters this resource has been\
349
+ declared with.
350
+ :type parameters: :obj:`dict`
351
+ :param environment: (Optional) The environment of the node associated\
352
+ with this resource.
353
+ :type environment: :obj:`string`
354
+
355
+ :ivar node: The hostname this resources is located on.
356
+ :ivar name: The name of the resource in the Puppet manifest.
357
+ :ivar type_: The type of Puppet resource.
358
+ :ivar exported: :obj:`bool` if the resource is exported.
359
+ :ivar sourcefile: The Puppet manifest this resource is declared in.
360
+ :ivar sourceline: The line this resource is declared at.
361
+ :ivar parameters: :obj:`dict` with key:value pairs of parameters.
362
+ :ivar relationships: :obj:`list` Contains all relationships to other\
363
+ resources
364
+ :ivar environment: :obj:`string` The environment of the node associated\
365
+ with this resource.
366
+ """
367
+
368
+ def __init__(
369
+ self,
370
+ node,
371
+ name,
372
+ type_,
373
+ tags,
374
+ exported,
375
+ sourcefile,
376
+ sourceline,
377
+ environment=None,
378
+ parameters={},
379
+ ):
380
+ self.node = node
381
+ self.name = name
382
+ self.type_ = type_
383
+ self.tags = tags
384
+ self.exported = exported
385
+ self.sourcefile = sourcefile
386
+ self.sourceline = sourceline
387
+ self.parameters = parameters
388
+ self.relationships = []
389
+ self.environment = environment
390
+ self.__string = f"{self.type_}[{self.name}]"
391
+
392
+ def __repr__(self):
393
+ return "<Resource: {}>".format(self.__string)
394
+
395
+ def __str__(self):
396
+ return "{}".format(self.__string)
397
+
398
+ @staticmethod
399
+ def create_from_dict(resource):
400
+ return Resource(
401
+ node=resource["certname"],
402
+ name=resource["title"],
403
+ type_=resource["type"],
404
+ tags=resource["tags"],
405
+ exported=resource["exported"],
406
+ sourcefile=resource["file"],
407
+ sourceline=resource["line"],
408
+ parameters=resource["parameters"],
409
+ environment=resource["environment"],
410
+ )
411
+
412
+
413
+ class Node:
414
+ """This object represents a node. It additionally has some helper methods
415
+ so that you can query for resources or facts directly from the node scope.
416
+ Unless otherwise specified all parameters are required.
417
+
418
+ :param api: API object.
419
+ :type api: :class:`pypuppetdb.api.BaseAPI`
420
+ :param name: Hostname of this node.
421
+ :type name: :obj:`string`
422
+ :param deactivated: (default `None`) Time this node was deactivated at.
423
+ :type deactivated: :obj:`string` formatted as ``%Y-%m-%dT%H:%M:%S.%fZ``
424
+ :param report_timestamp: (default `None`) Time of the last report.
425
+ :type report_timestamp: :obj:`string` formatted as\
426
+ ``%Y-%m-%dT%H:%M:%S.%fZ``
427
+ :param catalog_timestamp: (default `None`) Time the last time a catalog\
428
+ was compiled.
429
+ :type catalog_timestamp: :obj:`string` formatted as\
430
+ ``%Y-%m-%dT%H:%M:%S.%fZ``
431
+ :param facts_timestamp: (default `None`) Time the last time facts were\
432
+ collected.
433
+ :type facts_timestamp: :obj:`string` formatted as\
434
+ ``%Y-%m-%dT%H:%M:%S.%fZ``
435
+ :param status_report: (default `None`) Status of latest report \
436
+ from the node changed | unchanged | failed
437
+ :type status: :obj:`string`
438
+ :param noop: (Default `False`) A flag indicating whether the latest \
439
+ report of the node was produced by a noop run.
440
+ :type noop: :obj:`bool`
441
+ :param noop_pending: (Default `False`) A flag indicating whether \
442
+ the latest report of the node had pending changes \
443
+ produced by a noop run.
444
+ :type noop_pending: :obj:`bool`
445
+ :param events: (default `None`) Counted events from latest Report
446
+ :type events: :obj:`dict`
447
+ :param unreported: (default `False`) if node is considered unreported
448
+ :type unreported_time: :obj:`bool`
449
+ :param unreported_time: (default `None`) Time since last report
450
+ :type unreported_time: :obj:`string`
451
+ :param report_environment: (default 'production') The environment of the\
452
+ last received report for this node
453
+ :type report_environment: :obj:`string`
454
+ :param catalog_environment: (default 'production') The environment of the\
455
+ last received catalog for this node
456
+ :type catalog_environment: :obj:`string`
457
+ :param facts_environment: (default 'production') The environment of the\
458
+ last received fact set for this node
459
+ :type facts_environment: :obj:`string`
460
+ :param latest_report_hash: The hash of the latest report from this node,\
461
+ is only available in PuppetDB 3.2 and later
462
+ :type latest_report_hash: :obj:`string`
463
+ :param cached_catalog_status: Cached catalog status of the last puppet run\
464
+ on this node, possible values are 'explicitly_requested',\
465
+ 'on_failure', 'not_used' or None.
466
+ :type cached_catalog_status: :obj:`string`
467
+
468
+ :ivar name: Hostname of this node.
469
+ :ivar deactivated: :obj:`datetime.datetime` when this host was\
470
+ deactivated or `False`.
471
+ :ivar report_timestamp: :obj:`datetime.datetime` when the last run\
472
+ occured or `None`.
473
+ :ivar catalog_timestamp: :obj:`datetime.datetime` last time a catalog was\
474
+ compiled or `None`.
475
+ :ivar facts_timestamp: :obj:`datetime.datetime` last time when facts were\
476
+ collected or `None`.
477
+ :ivar report_environment: :obj:`string` the environment of the last\
478
+ received report for this node.
479
+ :ivar catalog_environment: :obj:`string` the environment of the last\
480
+ received catalog for this node.
481
+ :ivar facts_environment: :obj:`string` the environment of the last\
482
+ received fact set for this node.
483
+ :ivar latest_report_hash: :obj:`string` the hash value of the latest\
484
+ report the current node reported. Available in PuppetDB 3.2\
485
+ and later.
486
+ :ivar cached_catalog_status: :obj:`string` the status of the cached\
487
+ catalog from the last puppet run.
488
+ """
489
+
490
+ def __init__(
491
+ self,
492
+ api,
493
+ name,
494
+ deactivated=None,
495
+ expired=None,
496
+ report_timestamp=None,
497
+ catalog_timestamp=None,
498
+ facts_timestamp=None,
499
+ status_report=None,
500
+ noop=False,
501
+ noop_pending=False,
502
+ events=None,
503
+ unreported=False,
504
+ unreported_time=None,
505
+ report_environment="production",
506
+ catalog_environment="production",
507
+ facts_environment="production",
508
+ latest_report_hash=None,
509
+ cached_catalog_status=None,
510
+ ):
511
+ self.name = name
512
+ self.events = events
513
+ self.unreported_time = unreported_time
514
+ self.report_timestamp = report_timestamp
515
+ self.catalog_timestamp = catalog_timestamp
516
+ self.facts_timestamp = facts_timestamp
517
+ self.report_environment = report_environment
518
+ self.catalog_environment = catalog_environment
519
+ self.facts_environment = facts_environment
520
+ self.latest_report_hash = latest_report_hash
521
+ self.cached_catalog_status = cached_catalog_status
522
+
523
+ if unreported:
524
+ self.status = "unreported"
525
+ elif noop and noop_pending:
526
+ self.status = "noop"
527
+ else:
528
+ self.status = status_report
529
+
530
+ if deactivated is not None:
531
+ self.deactivated = json_to_datetime(deactivated)
532
+ else:
533
+ self.deactivated = False
534
+ if expired is not None:
535
+ self.expired = json_to_datetime(expired)
536
+ else:
537
+ self.expired = False
538
+ if report_timestamp is not None:
539
+ self.report_timestamp = json_to_datetime(report_timestamp)
540
+ else:
541
+ self.report_timestamp = report_timestamp
542
+ if facts_timestamp is not None:
543
+ self.facts_timestamp = json_to_datetime(facts_timestamp)
544
+ else:
545
+ self.facts_timestamp = facts_timestamp
546
+ if catalog_timestamp is not None:
547
+ self.catalog_timestamp = json_to_datetime(catalog_timestamp)
548
+ else:
549
+ self.catalog_timestamp = catalog_timestamp
550
+
551
+ self.__api = api
552
+ self.__string = self.name
553
+
554
+ def __repr__(self):
555
+ return "<Node: {}>".format(self.__string)
556
+
557
+ def __str__(self):
558
+ return "{}".format(self.__string)
559
+
560
+ def facts(self, query=None, **kwargs):
561
+ """Get all facts of this node. Additional arguments may also be
562
+ specified that will be passed to the query function.
563
+ """
564
+ q = EqualsOperator("certname", self.name)
565
+ if query:
566
+ q = AndOperator()
567
+ q.add(EqualsOperator("certname", self.name))
568
+ q.add(query)
569
+
570
+ return self.__api.facts(query=q, **kwargs)
571
+
572
+ def fact(self, name):
573
+ """Get a single fact from this node."""
574
+ facts = self.facts(name=name)
575
+ return next(fact for fact in facts)
576
+
577
+ def resources(self, type_=None, title=None, **kwargs):
578
+ """Get all resources of this node or all resources of the specified
579
+ type. Additional arguments may also be specified that will be passed
580
+ to the query function.
581
+ """
582
+ if type_ is None:
583
+ resources = self.__api.resources(
584
+ query=EqualsOperator("certname", self.name), **kwargs
585
+ )
586
+ elif type_ is not None and title is None:
587
+ resources = self.__api.resources(
588
+ type_=type_, query=EqualsOperator("certname", self.name), **kwargs
589
+ )
590
+ else:
591
+ resources = self.__api.resources(
592
+ type_=type_,
593
+ title=title,
594
+ query=EqualsOperator("certname", self.name),
595
+ **kwargs,
596
+ )
597
+ return resources
598
+
599
+ def resource(self, type_, title, **kwargs):
600
+ """Get a resource matching the supplied type and title. Additional
601
+ arguments may also be specified that will be passed to the query
602
+ function.
603
+ """
604
+ resources = self.__api.resources(
605
+ type_=type_,
606
+ title=title,
607
+ query=EqualsOperator("certname", self.name),
608
+ **kwargs,
609
+ )
610
+ return next(resource for resource in resources)
611
+
612
+ def reports(self, **kwargs):
613
+ """Get all reports for this node. Additional arguments may also be
614
+ specified that will be passed to the query function.
615
+ """
616
+ return self.__api.reports(query=EqualsOperator("certname", self.name), **kwargs)
617
+
618
+ @staticmethod
619
+ def create_from_dict(
620
+ query_api, node, with_status, with_event_numbers, latest_events, now, unreported
621
+ ):
622
+ node["status_report"] = None
623
+ node["events"] = None
624
+
625
+ if with_status:
626
+ if with_event_numbers:
627
+ status = [
628
+ s
629
+ for s in latest_events
630
+ if s["subject"]["title"] == node["certname"]
631
+ ]
632
+
633
+ try:
634
+ node["status_report"] = node["latest_report_status"]
635
+
636
+ if status:
637
+ node["events"] = status[0]
638
+ except KeyError:
639
+ if status:
640
+ node["events"] = status = status[0]
641
+ if status["successes"] > 0:
642
+ node["status_report"] = "changed"
643
+ if status["noops"] > 0:
644
+ node["status_report"] = "noop"
645
+ if status["failures"] > 0:
646
+ node["status_report"] = "failed"
647
+ else:
648
+ node["status_report"] = "unchanged"
649
+ else:
650
+ node["status_report"] = node["latest_report_status"]
651
+ node["events"] = {
652
+ "successes": 0,
653
+ "failures": 0,
654
+ "noops": 0,
655
+ }
656
+ if node["status_report"] == "changed":
657
+ node["events"]["successes"] = "some"
658
+ elif node["status_report"] == "noop":
659
+ node["events"]["noops"] = "some"
660
+ elif node["status_report"] == "failed":
661
+ node["events"]["failures"] = "some"
662
+
663
+ # node report age
664
+ if node["report_timestamp"] is not None:
665
+ try:
666
+ last_report = json_to_datetime(node["report_timestamp"])
667
+ last_report = last_report.replace(tzinfo=None)
668
+ unreported_border = now - timedelta(hours=unreported)
669
+ if last_report < unreported_border:
670
+ delta = now - last_report
671
+ node["unreported"] = True
672
+ node["unreported_time"] = "{}d {}h {}m".format(
673
+ delta.days,
674
+ int(delta.seconds / 3600),
675
+ int((delta.seconds % 3600) / 60),
676
+ )
677
+ except AttributeError:
678
+ node["unreported"] = True
679
+
680
+ if not node["report_timestamp"]:
681
+ node["unreported"] = True
682
+
683
+ return Node(
684
+ query_api,
685
+ name=node["certname"],
686
+ deactivated=node["deactivated"],
687
+ expired=node["expired"],
688
+ report_timestamp=node["report_timestamp"],
689
+ catalog_timestamp=node["catalog_timestamp"],
690
+ facts_timestamp=node["facts_timestamp"],
691
+ status_report=node["status_report"],
692
+ noop=node.get("latest_report_noop"),
693
+ noop_pending=node.get("latest_report_noop_pending"),
694
+ events=node["events"],
695
+ unreported=node.get("unreported"),
696
+ unreported_time=node.get("unreported_time"),
697
+ report_environment=node["report_environment"],
698
+ catalog_environment=node["catalog_environment"],
699
+ facts_environment=node["facts_environment"],
700
+ latest_report_hash=node.get("latest_report_hash"),
701
+ cached_catalog_status=node.get("cached_catalog_status"),
702
+ )
703
+
704
+
705
+ class Catalog:
706
+ """
707
+ This object represents a compiled catalog from puppet. It contains\
708
+ Resource and Edge object that represent the dependency graph. Unless\
709
+ otherwise specified all parameters are required.
710
+
711
+ :param node: Name of the host
712
+ :type node: :obj:`string`
713
+ :param edges: Edges returned from Catalog data
714
+ :type edges: :obj:`list` containing :obj:`dict` of\
715
+ :class:`pypuppetdb.types.Edge`
716
+ :param resources: :class:`pypuppetdb.types.Resource` managed as of this\
717
+ Catalog.
718
+ :type resources: :obj:`dict` of :class:`pypuppetdb.types.Resource`
719
+ :param version: Catalog version from Puppet (unique for each node)
720
+ :type version: :obj:`string`
721
+ :param transaction_uuid: A string used to match the catalog with the\
722
+ corresponding report that was issued during the same puppet run
723
+ :type transaction_uuid: :obj:`string`
724
+ :param environment: The environment associated with the catalog's\
725
+ certname.
726
+ :type environment: :obj:`string`
727
+ :param code_id: The string used to tie this catalog to the Puppet code\
728
+ which generated the catalog.
729
+ :type code_id: :obj:`string`
730
+ :param catalog_uuid: Universally unique identifier of this catalog.
731
+ :type catalog_uuid: :obj:`string`
732
+ :param producer: The certname of the Puppet Server that sent the catalog\
733
+ to PuppetDB
734
+ :type producer: :obj:`string`
735
+
736
+ :ivar node: :obj:`string` Name of the host
737
+ :ivar version: :obj:`string` Catalog version from Puppet
738
+ (unique for each node)
739
+ :ivar transaction_uuid: :obj:`string` used to match the catalog with
740
+ corresponding report
741
+ :ivar edges: :obj:`list` of :obj:`Edge` The source Resource object\
742
+ of the relationship
743
+ :ivar environment: :obj:`string` Environment associated with the
744
+ catalog's certname
745
+ :ivar code_id: :obj:`string` ties the catalog to the Puppet code that\
746
+ generated the catalog
747
+ :ivar catalog_uuid: :obj:`string` uniquely identifying this catalog.
748
+ :ivar producer: :obj:`string` of the Puppet Server that sent the catalog\
749
+ to PuppetDB
750
+ """
751
+
752
+ def __init__(
753
+ self,
754
+ node,
755
+ edges,
756
+ resources,
757
+ version,
758
+ transaction_uuid,
759
+ environment=None,
760
+ code_id=None,
761
+ catalog_uuid=None,
762
+ producer=None,
763
+ ):
764
+ self.node = node
765
+ self.version = version
766
+ self.transaction_uuid = transaction_uuid
767
+ self.environment = environment
768
+ self.code_id = code_id
769
+ self.catalog_uuid = catalog_uuid
770
+ self.producer = producer
771
+
772
+ self.resources = dict()
773
+ for resource in resources:
774
+ if "file" not in resource:
775
+ resource["file"] = None
776
+ if "line" not in resource:
777
+ resource["line"] = None
778
+ identifier = resource["type"] + "[" + resource["title"] + "]"
779
+ res = Resource(
780
+ node=node,
781
+ name=resource["title"],
782
+ type_=resource["type"],
783
+ tags=resource["tags"],
784
+ exported=resource["exported"],
785
+ sourcefile=resource["file"],
786
+ sourceline=resource["line"],
787
+ parameters=resource["parameters"],
788
+ environment=self.environment,
789
+ )
790
+ self.resources[identifier] = res
791
+
792
+ self.edges = []
793
+ for edge in edges:
794
+ identifier_source = edge["source_type"] + "[" + edge["source_title"] + "]"
795
+ identifier_target = edge["target_type"] + "[" + edge["target_title"] + "]"
796
+ e = Edge(
797
+ source=self.resources[identifier_source],
798
+ target=self.resources[identifier_target],
799
+ relationship=edge["relationship"],
800
+ node=self.node,
801
+ )
802
+ self.edges.append(e)
803
+ self.resources[identifier_source].relationships.append(e)
804
+ self.resources[identifier_target].relationships.append(e)
805
+
806
+ self.__string = f"{self.node}/{self.transaction_uuid}"
807
+
808
+ def __repr__(self):
809
+ return "<Catalog: {}>".format(self.__string)
810
+
811
+ def __str__(self):
812
+ return "{}".format(self.__string)
813
+
814
+ def get_resources(self):
815
+ return self.resources.values()
816
+
817
+ def get_resource(self, resource_type, resource_title):
818
+ identifier = resource_type + "[" + resource_title + "]"
819
+ return self.resources[identifier]
820
+
821
+ def get_edges(self):
822
+ return iter(self.edges)
823
+
824
+ @staticmethod
825
+ def create_from_dict(catalog):
826
+ return Catalog(
827
+ node=catalog["certname"],
828
+ edges=catalog["edges"]["data"],
829
+ resources=catalog["resources"]["data"],
830
+ version=catalog["version"],
831
+ transaction_uuid=catalog["transaction_uuid"],
832
+ environment=catalog["environment"],
833
+ code_id=catalog.get("code_id"),
834
+ catalog_uuid=catalog.get("catalog_uuid"),
835
+ )
836
+
837
+
838
+ class Edge:
839
+ """
840
+ This object represents the connection between two Resource objects.
841
+ Unless otherwise specified all parameters are required.
842
+
843
+ :param source: The source Resource object of the relationship
844
+ :type source: :class:`pypuppetdb.Resource`
845
+ :param target: The target Resource object of the relationship
846
+ :type target: :class:`pypuppetdb.Resource`
847
+ :param relationship: Name of the Puppet Resource Relationship
848
+ :type relationship: :obj:`string`
849
+ :param node: The certname of the node that owns this Relationship
850
+ :type node: :obj:`string`
851
+
852
+ :ivar source: :obj:`Resource` The source Resource object
853
+ :ivar target: :obj:`Resource` The target Resource object
854
+ :ivar relationship: :obj:`string` Name of the Puppet Resource relationship
855
+ :ivar node: :obj:`string` The name of the node that owns this relationship
856
+ """
857
+
858
+ def __init__(self, source, target, relationship, node=None):
859
+ self.source = source
860
+ self.target = target
861
+ self.relationship = relationship
862
+ self.node = node
863
+ self.__string = "{} - {} - {}".format(
864
+ self.source, self.relationship, self.target
865
+ )
866
+
867
+ def __repr__(self):
868
+ return "<Edge: {}>".format(self.__string)
869
+
870
+ def __str__(self):
871
+ return "{}".format(self.__string)
872
+
873
+ @staticmethod
874
+ def create_from_dict(edge):
875
+ identifier_source = edge["source_type"] + "[" + edge["source_title"] + "]"
876
+ identifier_target = edge["target_type"] + "[" + edge["target_title"] + "]"
877
+ return Edge(
878
+ source=identifier_source,
879
+ target=identifier_target,
880
+ relationship=edge["relationship"],
881
+ node=edge["certname"],
882
+ )
883
+
884
+
885
+ class Inventory:
886
+ """This object represents a Node Inventory entry returned from
887
+ the Inventory endpoint.
888
+
889
+ :param node: The certname of the node associated with the inventory.
890
+ :type node: :obj:`string`
891
+ :param time: The time at which PuppetDB received the facts in the
892
+ inventory.
893
+ :type time: :obj:`string` formatted as ``%Y-%m-%dT%H:%M:%S.%fZ``
894
+ :param environment: The environment associated with the inventory's
895
+ certname.
896
+ :type environment: :obj:`string`
897
+ :param facts: The dictionary of key-value pairs for the nodes
898
+ assosciated facts.
899
+ :type facts: :obj:`dict`
900
+ :param trusted: The trusted data from the node.
901
+ :type trusted: :obj:`dict`
902
+
903
+ :ivar node: The certname of the node associated with the inventory.
904
+ :ivar time: The time at which PuppetDB received the facts in the
905
+ inventory.
906
+ :ivar environment: The environment associated with the inventory's
907
+ certname.
908
+ :ivar facts: The dictionary of key-value pairs for the nodes
909
+ assosciated facts.
910
+ :ivar trusted: The trusted data from the node.
911
+ """
912
+
913
+ def __init__(self, node, time, environment, facts, trusted):
914
+ self.node = node
915
+ self.time = json_to_datetime(time)
916
+ self.environment = environment
917
+ self.facts = facts
918
+ self.trusted = trusted
919
+ self.__string = self.node
920
+
921
+ def __repr__(self):
922
+ return "<Inventory: {}>".format(self.__string)
923
+
924
+ def __str__(self):
925
+ return "{}".format(self.__string)
926
+
927
+ @staticmethod
928
+ def create_from_dict(inv):
929
+ return Inventory(
930
+ node=inv["certname"],
931
+ time=inv["timestamp"],
932
+ environment=inv["environment"],
933
+ facts=inv["facts"],
934
+ trusted=inv["trusted"],
935
+ )