forked from census-instrumentation/opencensus-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource.py
More file actions
224 lines (175 loc) · 6.31 KB
/
resource.py
File metadata and controls
224 lines (175 loc) · 6.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# Copyright 2019 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from copy import copy
import logging
import os
import re
logger = logging.getLogger(__name__)
OC_RESOURCE_TYPE = 'OC_RESOURCE_TYPE'
OC_RESOURCE_LABELS = 'OC_RESOURCE_LABELS'
# Matches anything outside ASCII 32-126 inclusive
_NON_PRINTABLE_ASCII = re.compile(
r'[^ !"#$%&\'()*+,\-./:;<=>?@\[\\\]^_`{|}~0-9a-zA-Z]')
# Label key/value tokens, may be quoted
_WORD_RES = r'(\'[^\']*\'|"[^"]*"|[^\s,=]+)'
_KV_RE = re.compile(r"""
\s* # ignore leading spaces
(?P<key>{word_re}) # capture the key word
\s*=\s*
(?P<val>{word_re}) # capture the value word
\s* # ignore trailing spaces
""".format(word_re=_WORD_RES), re.VERBOSE)
_LABELS_RE = re.compile(r"""
^\s*{word_re}\s*=\s*{word_re}\s* # _KV_RE without the named groups
(,\s*{word_re}\s*=\s*{word_re}\s*)* # more KV pairs, comma delimited
$
""".format(word_re=_WORD_RES), re.VERBOSE)
_UNQUOTE_RE = re.compile(r'^([\'"]?)([^\1]*)(\1)$')
def merge_resources(r1, *rest):
"""Merge multiple resources to get a new resource.
Resources earlier in the list take precedence: if multiple resources share
a label key, use the value from the first resource in the list with that
key. The combined resource's type will be the first non-null type in the
list.
:type r1: class:`Resource`
:param r1: The first of one or more resources to merge.
:type *rest: list(:class:`Resource`)
:param *rest: The rest of the resources to merge.
:rtype: :class:`Resource`
:return: The new combined resource.
"""
if not r1:
raise ValueError
if not rest:
return r1
rtype = r1.type
for rr in rest:
if rr.type:
rtype = rr.type
break
labels = copy(r1.labels)
for rr in reversed(rest):
labels.update(rr.labels)
return Resource(rtype, labels)
def check_ascii_256(string):
"""Check that `string` is printable ASCII and at most 256 chars.
Raise a `ValueError` if this check fails. Note that `string` itself doesn't
have to be ASCII-encoded.
:type string: str
:param string: The string to check.
"""
if string is None:
return
if len(string) > 256:
raise ValueError("Value is longer than 256 characters")
bad_char = _NON_PRINTABLE_ASCII.search(string)
if bad_char:
raise ValueError(u'Character "{}" at position {} is not printable '
'ASCII'
.format(
string[bad_char.start():bad_char.end()],
bad_char.start()))
class Resource(object):
"""A description of the entity for which signals are reported.
`type_` and `labels`' keys and values should contain only printable ASCII
and should be at most 256 characters.
See:
https://github.com/census-instrumentation/opencensus-specs/blob/master/resource/Resource.md
:type type_: str
:param type_: The resource type identifier.
:type labels: dict
:param labels: Key-value pairs that describe the entity.
""" # noqa
def __init__(self, type_=None, labels=None):
if type_ is not None and not type_:
raise ValueError("Resource type must not be empty")
check_ascii_256(type_)
if labels is None:
labels = {}
for key, value in labels.items():
if not key:
raise ValueError("Resource key must not be null or empty")
if value is None:
raise ValueError("Resource value must not be null")
check_ascii_256(key)
check_ascii_256(value)
self.type = type_
self.labels = copy(labels)
def get_type(self):
"""Get this resource's type.
:rtype: str
:return: The resource's type.
"""
return self.type
def get_labels(self):
"""Get this resource's labels.
:rtype: dict
:return: The resource's label dict.
"""
return copy(self.labels)
def merge(self, other):
"""Get a copy of this resource combined with another resource.
The combined resource will have the union of both resources' labels,
keeping this resource's label values if they conflict.
:type other: :class:`Resource`
:param other: The other resource to merge.
:rtype: :class:`Resource`
:return: The new combined resource.
"""
return merge_resources(self, other)
def unquote(string):
"""Strip quotes surrounding `string` if they exist.
>>> unquote('abc')
'abc'
>>> unquote('"abc"')
'abc'
>>> unquote("'abc'")
'abc'
>>> unquote('"a\\'b\\'c"')
"a'b'c"
"""
return _UNQUOTE_RE.sub(r'\2', string)
def parse_labels(labels_str):
"""Parse label keys and values following the Resource spec.
>>> parse_labels("k=v")
{'k': 'v'}
>>> parse_labels("k1=v1, k2=v2")
{'k1': 'v1', 'k2': 'v2'}
>>> parse_labels("k1='v1,=z1'")
{'k1': 'v1,=z1'}
"""
if not _LABELS_RE.match(labels_str):
return None
labels = {}
for kv in _KV_RE.finditer(labels_str):
gd = kv.groupdict()
key = unquote(gd['key'])
if key in labels:
logger.warning('Duplicate label key "%s"', key)
labels[key] = unquote(gd['val'])
return labels
def get_from_env():
"""Get a Resource from environment variables.
:rtype: :class:`Resource`
:return: A resource with type and labels from the environment.
"""
type_env = os.getenv(OC_RESOURCE_TYPE)
if type_env is None:
return None
type_env = type_env.strip()
labels_env = os.getenv(OC_RESOURCE_LABELS)
if labels_env is None:
return Resource(type_env)
labels = parse_labels(labels_env)
return Resource(type_env, labels)