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/QueryBuilder.py +735 -0
- pypuppetdb/__init__.py +132 -0
- pypuppetdb/api/__init__.py +17 -0
- pypuppetdb/api/base.py +470 -0
- pypuppetdb/api/command.py +102 -0
- pypuppetdb/api/metadata.py +26 -0
- pypuppetdb/api/metrics.py +60 -0
- pypuppetdb/api/pql.py +164 -0
- pypuppetdb/api/query.py +362 -0
- pypuppetdb/api/status.py +19 -0
- pypuppetdb/errors.py +28 -0
- pypuppetdb/types.py +935 -0
- pypuppetdb/utils.py +40 -0
- pypuppetdb-4.0.0.dist-info/METADATA +83 -0
- pypuppetdb-4.0.0.dist-info/RECORD +17 -0
- pypuppetdb-4.0.0.dist-info/WHEEL +4 -0
- pypuppetdb-4.0.0.dist-info/licenses/LICENSE +191 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
import requests
|
|
6
|
+
|
|
7
|
+
from pypuppetdb.api.base import BaseAPI, COMMAND_VERSION, ERROR_STRINGS
|
|
8
|
+
from pypuppetdb.errors import APIError, EmptyResponseError
|
|
9
|
+
|
|
10
|
+
log = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CommandAPI(BaseAPI):
|
|
14
|
+
"""This class provides methods that interact with the `pdb/cmd/*`
|
|
15
|
+
PuppetDB API endpoints.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def command(self, command, payload):
|
|
19
|
+
return self._cmd(command, payload)
|
|
20
|
+
|
|
21
|
+
def _cmd(self, command, payload):
|
|
22
|
+
"""This method posts commands to PuppetDB. Provided a command and payload
|
|
23
|
+
it will fire a request at PuppetDB. If PuppetDB can be reached and
|
|
24
|
+
answers within the timeout we'll decode the response and give it back
|
|
25
|
+
or raise for the HTTP Status Code PuppetDB gave back.
|
|
26
|
+
|
|
27
|
+
:param command: The PuppetDB Command we want to execute.
|
|
28
|
+
:type command: :obj:`string`
|
|
29
|
+
|
|
30
|
+
:param command: The payload, in wire format, specific to the command.
|
|
31
|
+
:type command: :obj:`dict`
|
|
32
|
+
|
|
33
|
+
:raises: :class:`~pypuppetdb.errors.EmptyResponseError`
|
|
34
|
+
|
|
35
|
+
:returns: The decoded response from PuppetDB
|
|
36
|
+
:rtype: :obj:`dict` or :obj:`list`
|
|
37
|
+
"""
|
|
38
|
+
log.debug("_cmd called with command: {}, data: {}".format(command, payload))
|
|
39
|
+
|
|
40
|
+
url = self._url("cmd")
|
|
41
|
+
|
|
42
|
+
if command not in COMMAND_VERSION:
|
|
43
|
+
log.error(
|
|
44
|
+
"Only {} supported, {} unsupported".format(
|
|
45
|
+
list(COMMAND_VERSION.keys()), command
|
|
46
|
+
)
|
|
47
|
+
)
|
|
48
|
+
raise APIError
|
|
49
|
+
|
|
50
|
+
params = {
|
|
51
|
+
"command": command,
|
|
52
|
+
"version": COMMAND_VERSION[command],
|
|
53
|
+
"certname": payload["certname"],
|
|
54
|
+
"checksum": hashlib.sha1(str(payload).encode("utf-8")).hexdigest(), # nosec
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
r = self.session.post(
|
|
59
|
+
url,
|
|
60
|
+
params=params,
|
|
61
|
+
data=json.dumps(payload, default=str),
|
|
62
|
+
verify=self.ssl_verify,
|
|
63
|
+
cert=(self.ssl_cert, self.ssl_key),
|
|
64
|
+
timeout=self.timeout,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
r.raise_for_status()
|
|
68
|
+
|
|
69
|
+
json_body = r.json()
|
|
70
|
+
if json_body is not None:
|
|
71
|
+
return json_body
|
|
72
|
+
else:
|
|
73
|
+
del json_body
|
|
74
|
+
raise EmptyResponseError
|
|
75
|
+
|
|
76
|
+
except requests.exceptions.Timeout:
|
|
77
|
+
log.error(
|
|
78
|
+
"{} {}:{} over {}.".format(
|
|
79
|
+
ERROR_STRINGS["timeout"],
|
|
80
|
+
self.host,
|
|
81
|
+
self.port,
|
|
82
|
+
self.protocol.upper(),
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
raise
|
|
86
|
+
except requests.exceptions.ConnectionError:
|
|
87
|
+
log.error(
|
|
88
|
+
"{} {}:{} over {}.".format(
|
|
89
|
+
ERROR_STRINGS["refused"],
|
|
90
|
+
self.host,
|
|
91
|
+
self.port,
|
|
92
|
+
self.protocol.upper(),
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
raise
|
|
96
|
+
except requests.exceptions.HTTPError as err:
|
|
97
|
+
log.error(
|
|
98
|
+
"{} {}:{} over {}.".format(
|
|
99
|
+
err.response.text, self.host, self.port, self.protocol.upper()
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
raise
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from pypuppetdb.api.base import BaseAPI
|
|
4
|
+
|
|
5
|
+
log = logging.getLogger(__name__)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MetadataAPI(BaseAPI):
|
|
9
|
+
"""This class provides methods that interact with the `pdb/meta/*`
|
|
10
|
+
PuppetDB API endpoints.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def server_time(self):
|
|
14
|
+
"""Get the current time of the clock on the PuppetDB server.
|
|
15
|
+
:returns: An ISO-8091 formatting timestamp.
|
|
16
|
+
:rtype: :obj:`string`
|
|
17
|
+
"""
|
|
18
|
+
return self._query("server-time")[self.parameters["server_time"]]
|
|
19
|
+
|
|
20
|
+
def current_version(self):
|
|
21
|
+
"""Get version information about the running PuppetDB server.
|
|
22
|
+
|
|
23
|
+
:returns: A string representation of the PuppetDB version.
|
|
24
|
+
:rtype: :obj:`string`
|
|
25
|
+
"""
|
|
26
|
+
return self._query("version")["version"]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from pypuppetdb.api.base import BaseAPI
|
|
4
|
+
from pypuppetdb.errors import DoesNotComputeError
|
|
5
|
+
|
|
6
|
+
log = logging.getLogger(__name__)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MetricsAPI(BaseAPI):
|
|
10
|
+
"""This class provides methods that interact with the `metrics/*`
|
|
11
|
+
PuppetDB API endpoints.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def metric(self, metric=None, version=None):
|
|
15
|
+
"""Query for a specific metric.
|
|
16
|
+
|
|
17
|
+
:param metric: The name of the metric we want.
|
|
18
|
+
:type metric: :obj:`string`
|
|
19
|
+
:param version: The version of the metric API to query. Valid values: 'v1', 'v2'
|
|
20
|
+
If not specified, then the value of self.metric_api_version
|
|
21
|
+
will be used.
|
|
22
|
+
:type version: :obj:`string`
|
|
23
|
+
|
|
24
|
+
:returns: The return of :meth:`~pypuppetdb.api.BaseAPI._query`.
|
|
25
|
+
"""
|
|
26
|
+
version = version if version else self.metric_api_version
|
|
27
|
+
if version is None or version == "v2":
|
|
28
|
+
if metric is None:
|
|
29
|
+
res = self._query("metrics-list")
|
|
30
|
+
else:
|
|
31
|
+
res = self._query("metrics", path=self._escape_metric_name(metric))
|
|
32
|
+
|
|
33
|
+
if "error" in res:
|
|
34
|
+
raise DoesNotComputeError(res["error"])
|
|
35
|
+
return res["value"]
|
|
36
|
+
elif version == "v1":
|
|
37
|
+
return self._query("mbean", path=metric)
|
|
38
|
+
else:
|
|
39
|
+
raise ValueError(
|
|
40
|
+
"Version specified must be 'v1' or 'v2', was given: '{}'".format(
|
|
41
|
+
version
|
|
42
|
+
)
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
@staticmethod
|
|
46
|
+
def _escape_metric_name(metric):
|
|
47
|
+
"""Escapes metric names so they can be used in GET requests as part of the URL.
|
|
48
|
+
The new (as of v2) metrics API is backed by the Jolokia library.
|
|
49
|
+
The escpaing rules for Jolokia GET requests can be found here:
|
|
50
|
+
https://jolokia.org/reference/html/protocol.html#escape-rules
|
|
51
|
+
|
|
52
|
+
:param metric: The name of the metric we want to escape.
|
|
53
|
+
:type metric: :obj:`string`
|
|
54
|
+
|
|
55
|
+
:returns: The escaped version of the metric name, safe for use in metric GET queries.
|
|
56
|
+
"""
|
|
57
|
+
metric = metric.replace("!", r"!!")
|
|
58
|
+
metric = metric.replace("/", r"!/")
|
|
59
|
+
metric = metric.replace('"', r'!"')
|
|
60
|
+
return metric
|
pypuppetdb/api/pql.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import re
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
|
|
5
|
+
import pypuppetdb
|
|
6
|
+
from pypuppetdb.QueryBuilder import EqualsOperator
|
|
7
|
+
from pypuppetdb.api.base import BaseAPI
|
|
8
|
+
from pypuppetdb.errors import APIError
|
|
9
|
+
from pypuppetdb.types import Node, Report
|
|
10
|
+
|
|
11
|
+
log = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PqlAPI(BaseAPI):
|
|
15
|
+
"""This class provides methods that interact with the `pdb/query/v4`
|
|
16
|
+
PuppetDB API endpoint.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def _pql(self, pql, request_method="GET"):
|
|
20
|
+
"""This method prepares a PQL query to PuppetDB. Actual making
|
|
21
|
+
the HTTP request is done by _make_request().
|
|
22
|
+
|
|
23
|
+
:param pql: PQL query
|
|
24
|
+
:type pql: :obj:`string`
|
|
25
|
+
|
|
26
|
+
:param request_method: (optional) GET or POST, the default is GET
|
|
27
|
+
|
|
28
|
+
:raises: :class:`~pypuppetdb.errors.EmptyResponseError`
|
|
29
|
+
|
|
30
|
+
:returns: The decoded response from PuppetDB
|
|
31
|
+
:rtype: :obj:`dict` or :obj:`list`
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
log.debug(f"_pql called with pql={pql}, request_method={request_method}")
|
|
35
|
+
|
|
36
|
+
pql = pql.strip()
|
|
37
|
+
if not pql:
|
|
38
|
+
log.error("Non-empty PQL query is required!")
|
|
39
|
+
raise APIError
|
|
40
|
+
|
|
41
|
+
payload = {}
|
|
42
|
+
|
|
43
|
+
# PQL queries are made to the same endpoint regardless of the queried entities
|
|
44
|
+
url = self._url("pql")
|
|
45
|
+
payload["query"] = pql
|
|
46
|
+
|
|
47
|
+
return self._make_request(url, request_method, payload)
|
|
48
|
+
|
|
49
|
+
# TODO: deduplicate this - see QueryAPI.nodes()
|
|
50
|
+
def pql(self, pql, with_status=False, unreported=2, with_event_numbers=True):
|
|
51
|
+
"""Makes a PQL (Puppet Query Language) and tries to cast results
|
|
52
|
+
to a rich type. If it won't work, returns plain dicts.
|
|
53
|
+
|
|
54
|
+
:param pql: PQL query
|
|
55
|
+
:type pql: :obj:`string`
|
|
56
|
+
|
|
57
|
+
:param with_status: (optional, only for queries for nodes) include
|
|
58
|
+
the node status in the returned nodes
|
|
59
|
+
:type with_status: :bool:
|
|
60
|
+
:param unreported: (optional, only for queries for nodes) amount
|
|
61
|
+
of hours when a node gets marked as unreported
|
|
62
|
+
:type unreported: :obj:`None` or integer
|
|
63
|
+
:param with_event_numbers: (optional, only for queries for nodes)
|
|
64
|
+
include the exact number of
|
|
65
|
+
changed/unchanged/failed/noop events when
|
|
66
|
+
with_status is set to True. If set to False
|
|
67
|
+
only "some" string is provided if there are
|
|
68
|
+
resources with such status in the last report.
|
|
69
|
+
This provides performance benefits as potentially
|
|
70
|
+
slow event-counts query is omitted completely.
|
|
71
|
+
:type with_event_numbers: :bool:
|
|
72
|
+
|
|
73
|
+
:returns: A generator yielding elements of a rich type or plain dicts
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
type_class = self._get_type_from_query(pql)
|
|
77
|
+
|
|
78
|
+
if type_class == Node and (
|
|
79
|
+
with_status or unreported != 2 or not with_event_numbers
|
|
80
|
+
):
|
|
81
|
+
log.error(
|
|
82
|
+
"with_status, unreported and with_event_numbers are used only"
|
|
83
|
+
" for queries for nodes!"
|
|
84
|
+
)
|
|
85
|
+
raise APIError
|
|
86
|
+
|
|
87
|
+
for element in self._pql(pql=pql):
|
|
88
|
+
if type_class == Node:
|
|
89
|
+
# TODO: deduplicate this - see QueryAPI.nodes()
|
|
90
|
+
|
|
91
|
+
now = datetime.utcnow()
|
|
92
|
+
|
|
93
|
+
latest_events = None
|
|
94
|
+
if with_status and with_event_numbers:
|
|
95
|
+
latest_events = self._query(
|
|
96
|
+
"event-counts",
|
|
97
|
+
query=EqualsOperator("latest_report?", True),
|
|
98
|
+
summarize_by="certname",
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
yield Node.create_from_dict(
|
|
102
|
+
self,
|
|
103
|
+
element,
|
|
104
|
+
with_status,
|
|
105
|
+
with_event_numbers,
|
|
106
|
+
latest_events,
|
|
107
|
+
now,
|
|
108
|
+
unreported,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
elif type_class == Report:
|
|
112
|
+
yield Report.create_from_dict(self, element)
|
|
113
|
+
elif type_class:
|
|
114
|
+
yield type_class.create_from_dict(element)
|
|
115
|
+
else:
|
|
116
|
+
yield element
|
|
117
|
+
|
|
118
|
+
@staticmethod
|
|
119
|
+
def _get_type_from_query(pql):
|
|
120
|
+
"""Gets a rich type of the entities returned by the given
|
|
121
|
+
PQL query.
|
|
122
|
+
|
|
123
|
+
:param pql: PQL query
|
|
124
|
+
:type pql: :obj:`string`
|
|
125
|
+
|
|
126
|
+
:return: a rich type, if this library supports it
|
|
127
|
+
otherwise - None
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
pql = pql.strip()
|
|
131
|
+
if not pql:
|
|
132
|
+
log.error("Non-empty PQL query is required!")
|
|
133
|
+
raise APIError
|
|
134
|
+
|
|
135
|
+
# in PQL the beginning of the query is the type of returned entities
|
|
136
|
+
# but only if the projection is empty ([]) or there is no projection
|
|
137
|
+
pattern = re.compile(r"([a-z]*?)\s*(\[])?\s*{")
|
|
138
|
+
match = pattern.match(pql)
|
|
139
|
+
|
|
140
|
+
if match:
|
|
141
|
+
type_name_lowercase = match.group(1)
|
|
142
|
+
|
|
143
|
+
# class name is capitalized
|
|
144
|
+
type_name = type_name_lowercase.capitalize()
|
|
145
|
+
|
|
146
|
+
# depluralize - remove trailing "s"
|
|
147
|
+
if type_name.endswith("s"):
|
|
148
|
+
type_name_singular = type_name[:-1]
|
|
149
|
+
else:
|
|
150
|
+
type_name_singular = type_name
|
|
151
|
+
|
|
152
|
+
log.debug(f"Type name: {type_name_singular}")
|
|
153
|
+
try:
|
|
154
|
+
type_class = getattr(pypuppetdb.types, type_name_singular)
|
|
155
|
+
return type_class
|
|
156
|
+
except AttributeError:
|
|
157
|
+
log.debug(
|
|
158
|
+
f"PQL returns entities of a type {type_name_singular},"
|
|
159
|
+
f" but it is not supported by this library yet."
|
|
160
|
+
)
|
|
161
|
+
return None
|
|
162
|
+
else:
|
|
163
|
+
log.debug("No match!")
|
|
164
|
+
return None
|