partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
_V2ProtobufEncoder.fits
Checks if the new span fits in the max payload size.
py_zipkin/encoding/_encoders.py
def fits(self, current_count, current_size, max_size, new_span): """Checks if the new span fits in the max payload size.""" return current_size + len(new_span) <= max_size
def fits(self, current_count, current_size, max_size, new_span): """Checks if the new span fits in the max payload size.""" return current_size + len(new_span) <= max_size
[ "Checks", "if", "the", "new", "span", "fits", "in", "the", "max", "payload", "size", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_encoders.py#L309-L311
[ "def", "fits", "(", "self", ",", "current_count", ",", "current_size", ",", "max_size", ",", "new_span", ")", ":", "return", "current_size", "+", "len", "(", "new_span", ")", "<=", "max_size" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
_V2ProtobufEncoder.encode_span
Encodes a single span to protobuf.
py_zipkin/encoding/_encoders.py
def encode_span(self, span): """Encodes a single span to protobuf.""" if not protobuf.installed(): raise ZipkinError( 'protobuf encoding requires installing the protobuf\'s extra ' 'requirements. Use py-zipkin[protobuf] in your requirements.txt.' ) pb_span = protobuf.create_protobuf_span(span) return protobuf.encode_pb_list([pb_span])
def encode_span(self, span): """Encodes a single span to protobuf.""" if not protobuf.installed(): raise ZipkinError( 'protobuf encoding requires installing the protobuf\'s extra ' 'requirements. Use py-zipkin[protobuf] in your requirements.txt.' ) pb_span = protobuf.create_protobuf_span(span) return protobuf.encode_pb_list([pb_span])
[ "Encodes", "a", "single", "span", "to", "protobuf", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_encoders.py#L313-L322
[ "def", "encode_span", "(", "self", ",", "span", ")", ":", "if", "not", "protobuf", ".", "installed", "(", ")", ":", "raise", "ZipkinError", "(", "'protobuf encoding requires installing the protobuf\\'s extra '", "'requirements. Use py-zipkin[protobuf] in your requirements.txt.'", ")", "pb_span", "=", "protobuf", ".", "create_protobuf_span", "(", "span", ")", "return", "protobuf", ".", "encode_pb_list", "(", "[", "pb_span", "]", ")" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
get_decoder
Creates encoder object for the given encoding. :param encoding: desired output encoding protocol :type encoding: Encoding :return: corresponding IEncoder object :rtype: IEncoder
py_zipkin/encoding/_decoders.py
def get_decoder(encoding): """Creates encoder object for the given encoding. :param encoding: desired output encoding protocol :type encoding: Encoding :return: corresponding IEncoder object :rtype: IEncoder """ if encoding == Encoding.V1_THRIFT: return _V1ThriftDecoder() if encoding == Encoding.V1_JSON: raise NotImplementedError( '{} decoding not yet implemented'.format(encoding)) if encoding == Encoding.V2_JSON: raise NotImplementedError( '{} decoding not yet implemented'.format(encoding)) raise ZipkinError('Unknown encoding: {}'.format(encoding))
def get_decoder(encoding): """Creates encoder object for the given encoding. :param encoding: desired output encoding protocol :type encoding: Encoding :return: corresponding IEncoder object :rtype: IEncoder """ if encoding == Encoding.V1_THRIFT: return _V1ThriftDecoder() if encoding == Encoding.V1_JSON: raise NotImplementedError( '{} decoding not yet implemented'.format(encoding)) if encoding == Encoding.V2_JSON: raise NotImplementedError( '{} decoding not yet implemented'.format(encoding)) raise ZipkinError('Unknown encoding: {}'.format(encoding))
[ "Creates", "encoder", "object", "for", "the", "given", "encoding", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L25-L41
[ "def", "get_decoder", "(", "encoding", ")", ":", "if", "encoding", "==", "Encoding", ".", "V1_THRIFT", ":", "return", "_V1ThriftDecoder", "(", ")", "if", "encoding", "==", "Encoding", ".", "V1_JSON", ":", "raise", "NotImplementedError", "(", "'{} decoding not yet implemented'", ".", "format", "(", "encoding", ")", ")", "if", "encoding", "==", "Encoding", ".", "V2_JSON", ":", "raise", "NotImplementedError", "(", "'{} decoding not yet implemented'", ".", "format", "(", "encoding", ")", ")", "raise", "ZipkinError", "(", "'Unknown encoding: {}'", ".", "format", "(", "encoding", ")", ")" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
_V1ThriftDecoder.decode_spans
Decodes an encoded list of spans. :param spans: encoded list of spans :type spans: bytes :return: list of spans :rtype: list of Span
py_zipkin/encoding/_decoders.py
def decode_spans(self, spans): """Decodes an encoded list of spans. :param spans: encoded list of spans :type spans: bytes :return: list of spans :rtype: list of Span """ decoded_spans = [] transport = TMemoryBuffer(spans) if six.byte2int(spans) == TType.STRUCT: _, size = read_list_begin(transport) else: size = 1 for _ in range(size): span = zipkin_core.Span() span.read(TBinaryProtocol(transport)) decoded_spans.append(self._decode_thrift_span(span)) return decoded_spans
def decode_spans(self, spans): """Decodes an encoded list of spans. :param spans: encoded list of spans :type spans: bytes :return: list of spans :rtype: list of Span """ decoded_spans = [] transport = TMemoryBuffer(spans) if six.byte2int(spans) == TType.STRUCT: _, size = read_list_begin(transport) else: size = 1 for _ in range(size): span = zipkin_core.Span() span.read(TBinaryProtocol(transport)) decoded_spans.append(self._decode_thrift_span(span)) return decoded_spans
[ "Decodes", "an", "encoded", "list", "of", "spans", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L60-L80
[ "def", "decode_spans", "(", "self", ",", "spans", ")", ":", "decoded_spans", "=", "[", "]", "transport", "=", "TMemoryBuffer", "(", "spans", ")", "if", "six", ".", "byte2int", "(", "spans", ")", "==", "TType", ".", "STRUCT", ":", "_", ",", "size", "=", "read_list_begin", "(", "transport", ")", "else", ":", "size", "=", "1", "for", "_", "in", "range", "(", "size", ")", ":", "span", "=", "zipkin_core", ".", "Span", "(", ")", "span", ".", "read", "(", "TBinaryProtocol", "(", "transport", ")", ")", "decoded_spans", ".", "append", "(", "self", ".", "_decode_thrift_span", "(", "span", ")", ")", "return", "decoded_spans" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
_V1ThriftDecoder._convert_from_thrift_endpoint
Accepts a thrift decoded endpoint and converts it to an Endpoint. :param thrift_endpoint: thrift encoded endpoint :type thrift_endpoint: thrift endpoint :returns: decoded endpoint :rtype: Encoding
py_zipkin/encoding/_decoders.py
def _convert_from_thrift_endpoint(self, thrift_endpoint): """Accepts a thrift decoded endpoint and converts it to an Endpoint. :param thrift_endpoint: thrift encoded endpoint :type thrift_endpoint: thrift endpoint :returns: decoded endpoint :rtype: Encoding """ ipv4 = None ipv6 = None port = struct.unpack('H', struct.pack('h', thrift_endpoint.port))[0] if thrift_endpoint.ipv4 != 0: ipv4 = socket.inet_ntop( socket.AF_INET, struct.pack('!i', thrift_endpoint.ipv4), ) if thrift_endpoint.ipv6: ipv6 = socket.inet_ntop(socket.AF_INET6, thrift_endpoint.ipv6) return Endpoint( service_name=thrift_endpoint.service_name, ipv4=ipv4, ipv6=ipv6, port=port, )
def _convert_from_thrift_endpoint(self, thrift_endpoint): """Accepts a thrift decoded endpoint and converts it to an Endpoint. :param thrift_endpoint: thrift encoded endpoint :type thrift_endpoint: thrift endpoint :returns: decoded endpoint :rtype: Encoding """ ipv4 = None ipv6 = None port = struct.unpack('H', struct.pack('h', thrift_endpoint.port))[0] if thrift_endpoint.ipv4 != 0: ipv4 = socket.inet_ntop( socket.AF_INET, struct.pack('!i', thrift_endpoint.ipv4), ) if thrift_endpoint.ipv6: ipv6 = socket.inet_ntop(socket.AF_INET6, thrift_endpoint.ipv6) return Endpoint( service_name=thrift_endpoint.service_name, ipv4=ipv4, ipv6=ipv6, port=port, )
[ "Accepts", "a", "thrift", "decoded", "endpoint", "and", "converts", "it", "to", "an", "Endpoint", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L82-L108
[ "def", "_convert_from_thrift_endpoint", "(", "self", ",", "thrift_endpoint", ")", ":", "ipv4", "=", "None", "ipv6", "=", "None", "port", "=", "struct", ".", "unpack", "(", "'H'", ",", "struct", ".", "pack", "(", "'h'", ",", "thrift_endpoint", ".", "port", ")", ")", "[", "0", "]", "if", "thrift_endpoint", ".", "ipv4", "!=", "0", ":", "ipv4", "=", "socket", ".", "inet_ntop", "(", "socket", ".", "AF_INET", ",", "struct", ".", "pack", "(", "'!i'", ",", "thrift_endpoint", ".", "ipv4", ")", ",", ")", "if", "thrift_endpoint", ".", "ipv6", ":", "ipv6", "=", "socket", ".", "inet_ntop", "(", "socket", ".", "AF_INET6", ",", "thrift_endpoint", ".", "ipv6", ")", "return", "Endpoint", "(", "service_name", "=", "thrift_endpoint", ".", "service_name", ",", "ipv4", "=", "ipv4", ",", "ipv6", "=", "ipv6", ",", "port", "=", "port", ",", ")" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
_V1ThriftDecoder._decode_thrift_annotations
Accepts a thrift annotation and converts it to a v1 annotation. :param thrift_annotations: list of thrift annotations. :type thrift_annotations: list of zipkin_core.Span.Annotation :returns: (annotations, local_endpoint, kind)
py_zipkin/encoding/_decoders.py
def _decode_thrift_annotations(self, thrift_annotations): """Accepts a thrift annotation and converts it to a v1 annotation. :param thrift_annotations: list of thrift annotations. :type thrift_annotations: list of zipkin_core.Span.Annotation :returns: (annotations, local_endpoint, kind) """ local_endpoint = None kind = Kind.LOCAL all_annotations = {} timestamp = None duration = None for thrift_annotation in thrift_annotations: all_annotations[thrift_annotation.value] = thrift_annotation.timestamp if thrift_annotation.host: local_endpoint = self._convert_from_thrift_endpoint( thrift_annotation.host, ) if 'cs' in all_annotations and 'sr' not in all_annotations: kind = Kind.CLIENT timestamp = all_annotations['cs'] duration = all_annotations['cr'] - all_annotations['cs'] elif 'cs' not in all_annotations and 'sr' in all_annotations: kind = Kind.SERVER timestamp = all_annotations['sr'] duration = all_annotations['ss'] - all_annotations['sr'] annotations = { name: self.seconds(ts) for name, ts in all_annotations.items() if name not in _DROP_ANNOTATIONS } return annotations, local_endpoint, kind, timestamp, duration
def _decode_thrift_annotations(self, thrift_annotations): """Accepts a thrift annotation and converts it to a v1 annotation. :param thrift_annotations: list of thrift annotations. :type thrift_annotations: list of zipkin_core.Span.Annotation :returns: (annotations, local_endpoint, kind) """ local_endpoint = None kind = Kind.LOCAL all_annotations = {} timestamp = None duration = None for thrift_annotation in thrift_annotations: all_annotations[thrift_annotation.value] = thrift_annotation.timestamp if thrift_annotation.host: local_endpoint = self._convert_from_thrift_endpoint( thrift_annotation.host, ) if 'cs' in all_annotations and 'sr' not in all_annotations: kind = Kind.CLIENT timestamp = all_annotations['cs'] duration = all_annotations['cr'] - all_annotations['cs'] elif 'cs' not in all_annotations and 'sr' in all_annotations: kind = Kind.SERVER timestamp = all_annotations['sr'] duration = all_annotations['ss'] - all_annotations['sr'] annotations = { name: self.seconds(ts) for name, ts in all_annotations.items() if name not in _DROP_ANNOTATIONS } return annotations, local_endpoint, kind, timestamp, duration
[ "Accepts", "a", "thrift", "annotation", "and", "converts", "it", "to", "a", "v1", "annotation", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L110-L144
[ "def", "_decode_thrift_annotations", "(", "self", ",", "thrift_annotations", ")", ":", "local_endpoint", "=", "None", "kind", "=", "Kind", ".", "LOCAL", "all_annotations", "=", "{", "}", "timestamp", "=", "None", "duration", "=", "None", "for", "thrift_annotation", "in", "thrift_annotations", ":", "all_annotations", "[", "thrift_annotation", ".", "value", "]", "=", "thrift_annotation", ".", "timestamp", "if", "thrift_annotation", ".", "host", ":", "local_endpoint", "=", "self", ".", "_convert_from_thrift_endpoint", "(", "thrift_annotation", ".", "host", ",", ")", "if", "'cs'", "in", "all_annotations", "and", "'sr'", "not", "in", "all_annotations", ":", "kind", "=", "Kind", ".", "CLIENT", "timestamp", "=", "all_annotations", "[", "'cs'", "]", "duration", "=", "all_annotations", "[", "'cr'", "]", "-", "all_annotations", "[", "'cs'", "]", "elif", "'cs'", "not", "in", "all_annotations", "and", "'sr'", "in", "all_annotations", ":", "kind", "=", "Kind", ".", "SERVER", "timestamp", "=", "all_annotations", "[", "'sr'", "]", "duration", "=", "all_annotations", "[", "'ss'", "]", "-", "all_annotations", "[", "'sr'", "]", "annotations", "=", "{", "name", ":", "self", ".", "seconds", "(", "ts", ")", "for", "name", ",", "ts", "in", "all_annotations", ".", "items", "(", ")", "if", "name", "not", "in", "_DROP_ANNOTATIONS", "}", "return", "annotations", ",", "local_endpoint", ",", "kind", ",", "timestamp", ",", "duration" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
_V1ThriftDecoder._convert_from_thrift_binary_annotations
Accepts a thrift decoded binary annotation and converts it to a v1 binary annotation.
py_zipkin/encoding/_decoders.py
def _convert_from_thrift_binary_annotations(self, thrift_binary_annotations): """Accepts a thrift decoded binary annotation and converts it to a v1 binary annotation. """ tags = {} local_endpoint = None remote_endpoint = None for binary_annotation in thrift_binary_annotations: if binary_annotation.key == 'sa': remote_endpoint = self._convert_from_thrift_endpoint( thrift_endpoint=binary_annotation.host, ) else: key = binary_annotation.key annotation_type = binary_annotation.annotation_type value = binary_annotation.value if annotation_type == zipkin_core.AnnotationType.BOOL: tags[key] = "true" if value == 1 else "false" elif annotation_type == zipkin_core.AnnotationType.STRING: tags[key] = str(value) else: log.warning('Only STRING and BOOL binary annotations are ' 'supported right now and can be properly decoded.') if binary_annotation.host: local_endpoint = self._convert_from_thrift_endpoint( thrift_endpoint=binary_annotation.host, ) return tags, local_endpoint, remote_endpoint
def _convert_from_thrift_binary_annotations(self, thrift_binary_annotations): """Accepts a thrift decoded binary annotation and converts it to a v1 binary annotation. """ tags = {} local_endpoint = None remote_endpoint = None for binary_annotation in thrift_binary_annotations: if binary_annotation.key == 'sa': remote_endpoint = self._convert_from_thrift_endpoint( thrift_endpoint=binary_annotation.host, ) else: key = binary_annotation.key annotation_type = binary_annotation.annotation_type value = binary_annotation.value if annotation_type == zipkin_core.AnnotationType.BOOL: tags[key] = "true" if value == 1 else "false" elif annotation_type == zipkin_core.AnnotationType.STRING: tags[key] = str(value) else: log.warning('Only STRING and BOOL binary annotations are ' 'supported right now and can be properly decoded.') if binary_annotation.host: local_endpoint = self._convert_from_thrift_endpoint( thrift_endpoint=binary_annotation.host, ) return tags, local_endpoint, remote_endpoint
[ "Accepts", "a", "thrift", "decoded", "binary", "annotation", "and", "converts", "it", "to", "a", "v1", "binary", "annotation", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L146-L178
[ "def", "_convert_from_thrift_binary_annotations", "(", "self", ",", "thrift_binary_annotations", ")", ":", "tags", "=", "{", "}", "local_endpoint", "=", "None", "remote_endpoint", "=", "None", "for", "binary_annotation", "in", "thrift_binary_annotations", ":", "if", "binary_annotation", ".", "key", "==", "'sa'", ":", "remote_endpoint", "=", "self", ".", "_convert_from_thrift_endpoint", "(", "thrift_endpoint", "=", "binary_annotation", ".", "host", ",", ")", "else", ":", "key", "=", "binary_annotation", ".", "key", "annotation_type", "=", "binary_annotation", ".", "annotation_type", "value", "=", "binary_annotation", ".", "value", "if", "annotation_type", "==", "zipkin_core", ".", "AnnotationType", ".", "BOOL", ":", "tags", "[", "key", "]", "=", "\"true\"", "if", "value", "==", "1", "else", "\"false\"", "elif", "annotation_type", "==", "zipkin_core", ".", "AnnotationType", ".", "STRING", ":", "tags", "[", "key", "]", "=", "str", "(", "value", ")", "else", ":", "log", ".", "warning", "(", "'Only STRING and BOOL binary annotations are '", "'supported right now and can be properly decoded.'", ")", "if", "binary_annotation", ".", "host", ":", "local_endpoint", "=", "self", ".", "_convert_from_thrift_endpoint", "(", "thrift_endpoint", "=", "binary_annotation", ".", "host", ",", ")", "return", "tags", ",", "local_endpoint", ",", "remote_endpoint" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
_V1ThriftDecoder._decode_thrift_span
Decodes a thrift span. :param thrift_span: thrift span :type thrift_span: thrift Span object :returns: span builder representing this span :rtype: Span
py_zipkin/encoding/_decoders.py
def _decode_thrift_span(self, thrift_span): """Decodes a thrift span. :param thrift_span: thrift span :type thrift_span: thrift Span object :returns: span builder representing this span :rtype: Span """ parent_id = None local_endpoint = None annotations = {} tags = {} kind = Kind.LOCAL remote_endpoint = None timestamp = None duration = None if thrift_span.parent_id: parent_id = self._convert_unsigned_long_to_lower_hex( thrift_span.parent_id, ) if thrift_span.annotations: annotations, local_endpoint, kind, timestamp, duration = \ self._decode_thrift_annotations(thrift_span.annotations) if thrift_span.binary_annotations: tags, local_endpoint, remote_endpoint = \ self._convert_from_thrift_binary_annotations( thrift_span.binary_annotations, ) trace_id = self._convert_trace_id_to_string( thrift_span.trace_id, thrift_span.trace_id_high, ) return Span( trace_id=trace_id, name=thrift_span.name, parent_id=parent_id, span_id=self._convert_unsigned_long_to_lower_hex(thrift_span.id), kind=kind, timestamp=self.seconds(timestamp or thrift_span.timestamp), duration=self.seconds(duration or thrift_span.duration), local_endpoint=local_endpoint, remote_endpoint=remote_endpoint, shared=(kind == Kind.SERVER and thrift_span.timestamp is None), annotations=annotations, tags=tags, )
def _decode_thrift_span(self, thrift_span): """Decodes a thrift span. :param thrift_span: thrift span :type thrift_span: thrift Span object :returns: span builder representing this span :rtype: Span """ parent_id = None local_endpoint = None annotations = {} tags = {} kind = Kind.LOCAL remote_endpoint = None timestamp = None duration = None if thrift_span.parent_id: parent_id = self._convert_unsigned_long_to_lower_hex( thrift_span.parent_id, ) if thrift_span.annotations: annotations, local_endpoint, kind, timestamp, duration = \ self._decode_thrift_annotations(thrift_span.annotations) if thrift_span.binary_annotations: tags, local_endpoint, remote_endpoint = \ self._convert_from_thrift_binary_annotations( thrift_span.binary_annotations, ) trace_id = self._convert_trace_id_to_string( thrift_span.trace_id, thrift_span.trace_id_high, ) return Span( trace_id=trace_id, name=thrift_span.name, parent_id=parent_id, span_id=self._convert_unsigned_long_to_lower_hex(thrift_span.id), kind=kind, timestamp=self.seconds(timestamp or thrift_span.timestamp), duration=self.seconds(duration or thrift_span.duration), local_endpoint=local_endpoint, remote_endpoint=remote_endpoint, shared=(kind == Kind.SERVER and thrift_span.timestamp is None), annotations=annotations, tags=tags, )
[ "Decodes", "a", "thrift", "span", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L185-L235
[ "def", "_decode_thrift_span", "(", "self", ",", "thrift_span", ")", ":", "parent_id", "=", "None", "local_endpoint", "=", "None", "annotations", "=", "{", "}", "tags", "=", "{", "}", "kind", "=", "Kind", ".", "LOCAL", "remote_endpoint", "=", "None", "timestamp", "=", "None", "duration", "=", "None", "if", "thrift_span", ".", "parent_id", ":", "parent_id", "=", "self", ".", "_convert_unsigned_long_to_lower_hex", "(", "thrift_span", ".", "parent_id", ",", ")", "if", "thrift_span", ".", "annotations", ":", "annotations", ",", "local_endpoint", ",", "kind", ",", "timestamp", ",", "duration", "=", "self", ".", "_decode_thrift_annotations", "(", "thrift_span", ".", "annotations", ")", "if", "thrift_span", ".", "binary_annotations", ":", "tags", ",", "local_endpoint", ",", "remote_endpoint", "=", "self", ".", "_convert_from_thrift_binary_annotations", "(", "thrift_span", ".", "binary_annotations", ",", ")", "trace_id", "=", "self", ".", "_convert_trace_id_to_string", "(", "thrift_span", ".", "trace_id", ",", "thrift_span", ".", "trace_id_high", ",", ")", "return", "Span", "(", "trace_id", "=", "trace_id", ",", "name", "=", "thrift_span", ".", "name", ",", "parent_id", "=", "parent_id", ",", "span_id", "=", "self", ".", "_convert_unsigned_long_to_lower_hex", "(", "thrift_span", ".", "id", ")", ",", "kind", "=", "kind", ",", "timestamp", "=", "self", ".", "seconds", "(", "timestamp", "or", "thrift_span", ".", "timestamp", ")", ",", "duration", "=", "self", ".", "seconds", "(", "duration", "or", "thrift_span", ".", "duration", ")", ",", "local_endpoint", "=", "local_endpoint", ",", "remote_endpoint", "=", "remote_endpoint", ",", "shared", "=", "(", "kind", "==", "Kind", ".", "SERVER", "and", "thrift_span", ".", "timestamp", "is", "None", ")", ",", "annotations", "=", "annotations", ",", "tags", "=", "tags", ",", ")" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
_V1ThriftDecoder._convert_trace_id_to_string
Converts the provided traceId hex value with optional high bits to a string. :param trace_id: the value of the trace ID :type trace_id: int :param trace_id_high: the high bits of the trace ID :type trace_id: int :returns: trace_id_high + trace_id as a string
py_zipkin/encoding/_decoders.py
def _convert_trace_id_to_string(self, trace_id, trace_id_high=None): """ Converts the provided traceId hex value with optional high bits to a string. :param trace_id: the value of the trace ID :type trace_id: int :param trace_id_high: the high bits of the trace ID :type trace_id: int :returns: trace_id_high + trace_id as a string """ if trace_id_high is not None: result = bytearray(32) self._write_hex_long(result, 0, trace_id_high) self._write_hex_long(result, 16, trace_id) return result.decode("utf8") result = bytearray(16) self._write_hex_long(result, 0, trace_id) return result.decode("utf8")
def _convert_trace_id_to_string(self, trace_id, trace_id_high=None): """ Converts the provided traceId hex value with optional high bits to a string. :param trace_id: the value of the trace ID :type trace_id: int :param trace_id_high: the high bits of the trace ID :type trace_id: int :returns: trace_id_high + trace_id as a string """ if trace_id_high is not None: result = bytearray(32) self._write_hex_long(result, 0, trace_id_high) self._write_hex_long(result, 16, trace_id) return result.decode("utf8") result = bytearray(16) self._write_hex_long(result, 0, trace_id) return result.decode("utf8")
[ "Converts", "the", "provided", "traceId", "hex", "value", "with", "optional", "high", "bits", "to", "a", "string", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L237-L256
[ "def", "_convert_trace_id_to_string", "(", "self", ",", "trace_id", ",", "trace_id_high", "=", "None", ")", ":", "if", "trace_id_high", "is", "not", "None", ":", "result", "=", "bytearray", "(", "32", ")", "self", ".", "_write_hex_long", "(", "result", ",", "0", ",", "trace_id_high", ")", "self", ".", "_write_hex_long", "(", "result", ",", "16", ",", "trace_id", ")", "return", "result", ".", "decode", "(", "\"utf8\"", ")", "result", "=", "bytearray", "(", "16", ")", "self", ".", "_write_hex_long", "(", "result", ",", "0", ",", "trace_id", ")", "return", "result", ".", "decode", "(", "\"utf8\"", ")" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
_V1ThriftDecoder._convert_unsigned_long_to_lower_hex
Converts the provided unsigned long value to a hex string. :param value: the value to convert :type value: unsigned long :returns: value as a hex string
py_zipkin/encoding/_decoders.py
def _convert_unsigned_long_to_lower_hex(self, value): """ Converts the provided unsigned long value to a hex string. :param value: the value to convert :type value: unsigned long :returns: value as a hex string """ result = bytearray(16) self._write_hex_long(result, 0, value) return result.decode("utf8")
def _convert_unsigned_long_to_lower_hex(self, value): """ Converts the provided unsigned long value to a hex string. :param value: the value to convert :type value: unsigned long :returns: value as a hex string """ result = bytearray(16) self._write_hex_long(result, 0, value) return result.decode("utf8")
[ "Converts", "the", "provided", "unsigned", "long", "value", "to", "a", "hex", "string", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L258-L268
[ "def", "_convert_unsigned_long_to_lower_hex", "(", "self", ",", "value", ")", ":", "result", "=", "bytearray", "(", "16", ")", "self", ".", "_write_hex_long", "(", "result", ",", "0", ",", "value", ")", "return", "result", ".", "decode", "(", "\"utf8\"", ")" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
_V1ThriftDecoder._write_hex_long
Writes an unsigned long value across a byte array. :param data: the buffer to write the value to :type data: bytearray :param pos: the starting position :type pos: int :param value: the value to write :type value: unsigned long
py_zipkin/encoding/_decoders.py
def _write_hex_long(self, data, pos, value): """ Writes an unsigned long value across a byte array. :param data: the buffer to write the value to :type data: bytearray :param pos: the starting position :type pos: int :param value: the value to write :type value: unsigned long """ self._write_hex_byte(data, pos + 0, (value >> 56) & 0xff) self._write_hex_byte(data, pos + 2, (value >> 48) & 0xff) self._write_hex_byte(data, pos + 4, (value >> 40) & 0xff) self._write_hex_byte(data, pos + 6, (value >> 32) & 0xff) self._write_hex_byte(data, pos + 8, (value >> 24) & 0xff) self._write_hex_byte(data, pos + 10, (value >> 16) & 0xff) self._write_hex_byte(data, pos + 12, (value >> 8) & 0xff) self._write_hex_byte(data, pos + 14, (value & 0xff))
def _write_hex_long(self, data, pos, value): """ Writes an unsigned long value across a byte array. :param data: the buffer to write the value to :type data: bytearray :param pos: the starting position :type pos: int :param value: the value to write :type value: unsigned long """ self._write_hex_byte(data, pos + 0, (value >> 56) & 0xff) self._write_hex_byte(data, pos + 2, (value >> 48) & 0xff) self._write_hex_byte(data, pos + 4, (value >> 40) & 0xff) self._write_hex_byte(data, pos + 6, (value >> 32) & 0xff) self._write_hex_byte(data, pos + 8, (value >> 24) & 0xff) self._write_hex_byte(data, pos + 10, (value >> 16) & 0xff) self._write_hex_byte(data, pos + 12, (value >> 8) & 0xff) self._write_hex_byte(data, pos + 14, (value & 0xff))
[ "Writes", "an", "unsigned", "long", "value", "across", "a", "byte", "array", "." ]
Yelp/py_zipkin
python
https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L270-L288
[ "def", "_write_hex_long", "(", "self", ",", "data", ",", "pos", ",", "value", ")", ":", "self", ".", "_write_hex_byte", "(", "data", ",", "pos", "+", "0", ",", "(", "value", ">>", "56", ")", "&", "0xff", ")", "self", ".", "_write_hex_byte", "(", "data", ",", "pos", "+", "2", ",", "(", "value", ">>", "48", ")", "&", "0xff", ")", "self", ".", "_write_hex_byte", "(", "data", ",", "pos", "+", "4", ",", "(", "value", ">>", "40", ")", "&", "0xff", ")", "self", ".", "_write_hex_byte", "(", "data", ",", "pos", "+", "6", ",", "(", "value", ">>", "32", ")", "&", "0xff", ")", "self", ".", "_write_hex_byte", "(", "data", ",", "pos", "+", "8", ",", "(", "value", ">>", "24", ")", "&", "0xff", ")", "self", ".", "_write_hex_byte", "(", "data", ",", "pos", "+", "10", ",", "(", "value", ">>", "16", ")", "&", "0xff", ")", "self", ".", "_write_hex_byte", "(", "data", ",", "pos", "+", "12", ",", "(", "value", ">>", "8", ")", "&", "0xff", ")", "self", ".", "_write_hex_byte", "(", "data", ",", "pos", "+", "14", ",", "(", "value", "&", "0xff", ")", ")" ]
0944d9a3fb1f1798dbb276694aeed99f2b4283ba
test
date_fixup_pre_processor
Replace illegal February 29, 30 dates with the last day of February. German banks use a variant of the 30/360 interest rate calculation, where each month has always 30 days even February. Python's datetime module won't accept such dates.
mt940/processors.py
def date_fixup_pre_processor(transactions, tag, tag_dict, *args): """ Replace illegal February 29, 30 dates with the last day of February. German banks use a variant of the 30/360 interest rate calculation, where each month has always 30 days even February. Python's datetime module won't accept such dates. """ if tag_dict['month'] == '02': year = int(tag_dict['year'], 10) _, max_month_day = calendar.monthrange(year, 2) if int(tag_dict['day'], 10) > max_month_day: tag_dict['day'] = str(max_month_day) return tag_dict
def date_fixup_pre_processor(transactions, tag, tag_dict, *args): """ Replace illegal February 29, 30 dates with the last day of February. German banks use a variant of the 30/360 interest rate calculation, where each month has always 30 days even February. Python's datetime module won't accept such dates. """ if tag_dict['month'] == '02': year = int(tag_dict['year'], 10) _, max_month_day = calendar.monthrange(year, 2) if int(tag_dict['day'], 10) > max_month_day: tag_dict['day'] = str(max_month_day) return tag_dict
[ "Replace", "illegal", "February", "29", "30", "dates", "with", "the", "last", "day", "of", "February", "." ]
WoLpH/mt940
python
https://github.com/WoLpH/mt940/blob/fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb/mt940/processors.py#L17-L31
[ "def", "date_fixup_pre_processor", "(", "transactions", ",", "tag", ",", "tag_dict", ",", "*", "args", ")", ":", "if", "tag_dict", "[", "'month'", "]", "==", "'02'", ":", "year", "=", "int", "(", "tag_dict", "[", "'year'", "]", ",", "10", ")", "_", ",", "max_month_day", "=", "calendar", ".", "monthrange", "(", "year", ",", "2", ")", "if", "int", "(", "tag_dict", "[", "'day'", "]", ",", "10", ")", ">", "max_month_day", ":", "tag_dict", "[", "'day'", "]", "=", "str", "(", "max_month_day", ")", "return", "tag_dict" ]
fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb
test
mBank_set_transaction_code
mBank Collect uses transaction code 911 to distinguish icoming mass payments transactions, adding transaction_code may be helpful in further processing
mt940/processors.py
def mBank_set_transaction_code(transactions, tag, tag_dict, *args): """ mBank Collect uses transaction code 911 to distinguish icoming mass payments transactions, adding transaction_code may be helpful in further processing """ tag_dict['transaction_code'] = int( tag_dict[tag.slug].split(';')[0].split(' ', 1)[0]) return tag_dict
def mBank_set_transaction_code(transactions, tag, tag_dict, *args): """ mBank Collect uses transaction code 911 to distinguish icoming mass payments transactions, adding transaction_code may be helpful in further processing """ tag_dict['transaction_code'] = int( tag_dict[tag.slug].split(';')[0].split(' ', 1)[0]) return tag_dict
[ "mBank", "Collect", "uses", "transaction", "code", "911", "to", "distinguish", "icoming", "mass", "payments", "transactions", "adding", "transaction_code", "may", "be", "helpful", "in", "further", "processing" ]
WoLpH/mt940
python
https://github.com/WoLpH/mt940/blob/fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb/mt940/processors.py#L41-L50
[ "def", "mBank_set_transaction_code", "(", "transactions", ",", "tag", ",", "tag_dict", ",", "*", "args", ")", ":", "tag_dict", "[", "'transaction_code'", "]", "=", "int", "(", "tag_dict", "[", "tag", ".", "slug", "]", ".", "split", "(", "';'", ")", "[", "0", "]", ".", "split", "(", "' '", ",", "1", ")", "[", "0", "]", ")", "return", "tag_dict" ]
fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb
test
mBank_set_iph_id
mBank Collect uses ID IPH to distinguish between virtual accounts, adding iph_id may be helpful in further processing
mt940/processors.py
def mBank_set_iph_id(transactions, tag, tag_dict, *args): """ mBank Collect uses ID IPH to distinguish between virtual accounts, adding iph_id may be helpful in further processing """ matches = iph_id_re.search(tag_dict[tag.slug]) if matches: # pragma no branch tag_dict['iph_id'] = matches.groupdict()['iph_id'] return tag_dict
def mBank_set_iph_id(transactions, tag, tag_dict, *args): """ mBank Collect uses ID IPH to distinguish between virtual accounts, adding iph_id may be helpful in further processing """ matches = iph_id_re.search(tag_dict[tag.slug]) if matches: # pragma no branch tag_dict['iph_id'] = matches.groupdict()['iph_id'] return tag_dict
[ "mBank", "Collect", "uses", "ID", "IPH", "to", "distinguish", "between", "virtual", "accounts", "adding", "iph_id", "may", "be", "helpful", "in", "further", "processing" ]
WoLpH/mt940
python
https://github.com/WoLpH/mt940/blob/fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb/mt940/processors.py#L56-L66
[ "def", "mBank_set_iph_id", "(", "transactions", ",", "tag", ",", "tag_dict", ",", "*", "args", ")", ":", "matches", "=", "iph_id_re", ".", "search", "(", "tag_dict", "[", "tag", ".", "slug", "]", ")", "if", "matches", ":", "# pragma no branch", "tag_dict", "[", "'iph_id'", "]", "=", "matches", ".", "groupdict", "(", ")", "[", "'iph_id'", "]", "return", "tag_dict" ]
fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb
test
mBank_set_tnr
mBank Collect states TNR in transaction details as unique id for transactions, that may be used to identify the same transactions in different statement files eg. partial mt942 and full mt940 Information about tnr uniqueness has been obtained from mBank support, it lacks in mt940 mBank specification.
mt940/processors.py
def mBank_set_tnr(transactions, tag, tag_dict, *args): """ mBank Collect states TNR in transaction details as unique id for transactions, that may be used to identify the same transactions in different statement files eg. partial mt942 and full mt940 Information about tnr uniqueness has been obtained from mBank support, it lacks in mt940 mBank specification. """ matches = tnr_re.search(tag_dict[tag.slug]) if matches: # pragma no branch tag_dict['tnr'] = matches.groupdict()['tnr'] return tag_dict
def mBank_set_tnr(transactions, tag, tag_dict, *args): """ mBank Collect states TNR in transaction details as unique id for transactions, that may be used to identify the same transactions in different statement files eg. partial mt942 and full mt940 Information about tnr uniqueness has been obtained from mBank support, it lacks in mt940 mBank specification. """ matches = tnr_re.search(tag_dict[tag.slug]) if matches: # pragma no branch tag_dict['tnr'] = matches.groupdict()['tnr'] return tag_dict
[ "mBank", "Collect", "states", "TNR", "in", "transaction", "details", "as", "unique", "id", "for", "transactions", "that", "may", "be", "used", "to", "identify", "the", "same", "transactions", "in", "different", "statement", "files", "eg", ".", "partial", "mt942", "and", "full", "mt940", "Information", "about", "tnr", "uniqueness", "has", "been", "obtained", "from", "mBank", "support", "it", "lacks", "in", "mt940", "mBank", "specification", "." ]
WoLpH/mt940
python
https://github.com/WoLpH/mt940/blob/fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb/mt940/processors.py#L73-L87
[ "def", "mBank_set_tnr", "(", "transactions", ",", "tag", ",", "tag_dict", ",", "*", "args", ")", ":", "matches", "=", "tnr_re", ".", "search", "(", "tag_dict", "[", "tag", ".", "slug", "]", ")", "if", "matches", ":", "# pragma no branch", "tag_dict", "[", "'tnr'", "]", "=", "matches", ".", "groupdict", "(", ")", "[", "'tnr'", "]", "return", "tag_dict" ]
fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb
test
Transactions.parse
Parses mt940 data, expects a string with data Args: data (str): The MT940 data Returns: :py:class:`list` of :py:class:`Transaction`
mt940/models.py
def parse(self, data): '''Parses mt940 data, expects a string with data Args: data (str): The MT940 data Returns: :py:class:`list` of :py:class:`Transaction` ''' # Remove extraneous whitespace and such data = '\n'.join(self.strip(data.split('\n'))) # The pattern is a bit annoying to match by regex, even with a greedy # match it's difficult to get both the beginning and the end so we're # working around it in a safer way to get everything. tag_re = re.compile( r'^:\n?(?P<full_tag>(?P<tag>[0-9]{2}|NS)(?P<sub_tag>[A-Z])?):', re.MULTILINE) matches = list(tag_re.finditer(data)) # identify valid matches valid_matches = list(self.sanatize_tag_id_matches(matches)) for i, match in enumerate(valid_matches): tag_id = self.normalize_tag_id(match.group('tag')) # get tag instance corresponding to tag id tag = self.tags.get(match.group('full_tag')) \ or self.tags[tag_id] # Nice trick to get all the text that is part of this tag, python # regex matches have a `end()` and `start()` to indicate the start # and end index of the match. if valid_matches[i + 1:]: tag_data = \ data[match.end():valid_matches[i + 1].start()].strip() else: tag_data = data[match.end():].strip() tag_dict = tag.parse(self, tag_data) # Preprocess data before creating the object for processor in self.processors.get('pre_%s' % tag.slug, []): tag_dict = processor(self, tag, tag_dict) result = tag(self, tag_dict) # Postprocess the object for processor in self.processors.get('post_%s' % tag.slug, []): result = processor(self, tag, tag_dict, result) # Creating a new transaction for :20: and :61: tags allows the # tags from :20: to :61: to be captured as part of the transaction. if isinstance(tag, mt940.tags.Statement): # Transactions only get a Transaction Reference Code ID from a # :61: tag which is why a new transaction is created if the # 'id' has a value. if not self.transactions: transaction = Transaction(self) self.transactions.append(transaction) if transaction.data.get('id'): transaction = Transaction(self, result) self.transactions.append(transaction) else: transaction.data.update(result) elif issubclass(tag.scope, Transaction) and self.transactions: # Combine multiple results together as one string, Rabobank has # multiple :86: tags for a single transaction for k, v in _compat.iteritems(result): if k in transaction.data and hasattr(v, 'strip'): transaction.data[k] += '\n%s' % v.strip() else: transaction.data[k] = v elif issubclass(tag.scope, Transactions): # pragma: no branch self.data.update(result) return self.transactions
def parse(self, data): '''Parses mt940 data, expects a string with data Args: data (str): The MT940 data Returns: :py:class:`list` of :py:class:`Transaction` ''' # Remove extraneous whitespace and such data = '\n'.join(self.strip(data.split('\n'))) # The pattern is a bit annoying to match by regex, even with a greedy # match it's difficult to get both the beginning and the end so we're # working around it in a safer way to get everything. tag_re = re.compile( r'^:\n?(?P<full_tag>(?P<tag>[0-9]{2}|NS)(?P<sub_tag>[A-Z])?):', re.MULTILINE) matches = list(tag_re.finditer(data)) # identify valid matches valid_matches = list(self.sanatize_tag_id_matches(matches)) for i, match in enumerate(valid_matches): tag_id = self.normalize_tag_id(match.group('tag')) # get tag instance corresponding to tag id tag = self.tags.get(match.group('full_tag')) \ or self.tags[tag_id] # Nice trick to get all the text that is part of this tag, python # regex matches have a `end()` and `start()` to indicate the start # and end index of the match. if valid_matches[i + 1:]: tag_data = \ data[match.end():valid_matches[i + 1].start()].strip() else: tag_data = data[match.end():].strip() tag_dict = tag.parse(self, tag_data) # Preprocess data before creating the object for processor in self.processors.get('pre_%s' % tag.slug, []): tag_dict = processor(self, tag, tag_dict) result = tag(self, tag_dict) # Postprocess the object for processor in self.processors.get('post_%s' % tag.slug, []): result = processor(self, tag, tag_dict, result) # Creating a new transaction for :20: and :61: tags allows the # tags from :20: to :61: to be captured as part of the transaction. if isinstance(tag, mt940.tags.Statement): # Transactions only get a Transaction Reference Code ID from a # :61: tag which is why a new transaction is created if the # 'id' has a value. if not self.transactions: transaction = Transaction(self) self.transactions.append(transaction) if transaction.data.get('id'): transaction = Transaction(self, result) self.transactions.append(transaction) else: transaction.data.update(result) elif issubclass(tag.scope, Transaction) and self.transactions: # Combine multiple results together as one string, Rabobank has # multiple :86: tags for a single transaction for k, v in _compat.iteritems(result): if k in transaction.data and hasattr(v, 'strip'): transaction.data[k] += '\n%s' % v.strip() else: transaction.data[k] = v elif issubclass(tag.scope, Transactions): # pragma: no branch self.data.update(result) return self.transactions
[ "Parses", "mt940", "data", "expects", "a", "string", "with", "data" ]
WoLpH/mt940
python
https://github.com/WoLpH/mt940/blob/fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb/mt940/models.py#L375-L458
[ "def", "parse", "(", "self", ",", "data", ")", ":", "# Remove extraneous whitespace and such", "data", "=", "'\\n'", ".", "join", "(", "self", ".", "strip", "(", "data", ".", "split", "(", "'\\n'", ")", ")", ")", "# The pattern is a bit annoying to match by regex, even with a greedy", "# match it's difficult to get both the beginning and the end so we're", "# working around it in a safer way to get everything.", "tag_re", "=", "re", ".", "compile", "(", "r'^:\\n?(?P<full_tag>(?P<tag>[0-9]{2}|NS)(?P<sub_tag>[A-Z])?):'", ",", "re", ".", "MULTILINE", ")", "matches", "=", "list", "(", "tag_re", ".", "finditer", "(", "data", ")", ")", "# identify valid matches", "valid_matches", "=", "list", "(", "self", ".", "sanatize_tag_id_matches", "(", "matches", ")", ")", "for", "i", ",", "match", "in", "enumerate", "(", "valid_matches", ")", ":", "tag_id", "=", "self", ".", "normalize_tag_id", "(", "match", ".", "group", "(", "'tag'", ")", ")", "# get tag instance corresponding to tag id", "tag", "=", "self", ".", "tags", ".", "get", "(", "match", ".", "group", "(", "'full_tag'", ")", ")", "or", "self", ".", "tags", "[", "tag_id", "]", "# Nice trick to get all the text that is part of this tag, python", "# regex matches have a `end()` and `start()` to indicate the start", "# and end index of the match.", "if", "valid_matches", "[", "i", "+", "1", ":", "]", ":", "tag_data", "=", "data", "[", "match", ".", "end", "(", ")", ":", "valid_matches", "[", "i", "+", "1", "]", ".", "start", "(", ")", "]", ".", "strip", "(", ")", "else", ":", "tag_data", "=", "data", "[", "match", ".", "end", "(", ")", ":", "]", ".", "strip", "(", ")", "tag_dict", "=", "tag", ".", "parse", "(", "self", ",", "tag_data", ")", "# Preprocess data before creating the object", "for", "processor", "in", "self", ".", "processors", ".", "get", "(", "'pre_%s'", "%", "tag", ".", "slug", ",", "[", "]", ")", ":", "tag_dict", "=", "processor", "(", "self", ",", "tag", ",", "tag_dict", ")", "result", "=", "tag", "(", "self", ",", "tag_dict", ")", "# Postprocess the object", "for", "processor", "in", "self", ".", "processors", ".", "get", "(", "'post_%s'", "%", "tag", ".", "slug", ",", "[", "]", ")", ":", "result", "=", "processor", "(", "self", ",", "tag", ",", "tag_dict", ",", "result", ")", "# Creating a new transaction for :20: and :61: tags allows the", "# tags from :20: to :61: to be captured as part of the transaction.", "if", "isinstance", "(", "tag", ",", "mt940", ".", "tags", ".", "Statement", ")", ":", "# Transactions only get a Transaction Reference Code ID from a", "# :61: tag which is why a new transaction is created if the", "# 'id' has a value.", "if", "not", "self", ".", "transactions", ":", "transaction", "=", "Transaction", "(", "self", ")", "self", ".", "transactions", ".", "append", "(", "transaction", ")", "if", "transaction", ".", "data", ".", "get", "(", "'id'", ")", ":", "transaction", "=", "Transaction", "(", "self", ",", "result", ")", "self", ".", "transactions", ".", "append", "(", "transaction", ")", "else", ":", "transaction", ".", "data", ".", "update", "(", "result", ")", "elif", "issubclass", "(", "tag", ".", "scope", ",", "Transaction", ")", "and", "self", ".", "transactions", ":", "# Combine multiple results together as one string, Rabobank has", "# multiple :86: tags for a single transaction", "for", "k", ",", "v", "in", "_compat", ".", "iteritems", "(", "result", ")", ":", "if", "k", "in", "transaction", ".", "data", "and", "hasattr", "(", "v", ",", "'strip'", ")", ":", "transaction", ".", "data", "[", "k", "]", "+=", "'\\n%s'", "%", "v", ".", "strip", "(", ")", "else", ":", "transaction", ".", "data", "[", "k", "]", "=", "v", "elif", "issubclass", "(", "tag", ".", "scope", ",", "Transactions", ")", ":", "# pragma: no branch", "self", ".", "data", ".", "update", "(", "result", ")", "return", "self", ".", "transactions" ]
fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb
test
parse
Parses mt940 data and returns transactions object :param src: file handler to read, filename to read or raw data as string :return: Collection of transactions :rtype: Transactions
mt940/parser.py
def parse(src, encoding=None): ''' Parses mt940 data and returns transactions object :param src: file handler to read, filename to read or raw data as string :return: Collection of transactions :rtype: Transactions ''' def safe_is_file(filename): try: return os.path.isfile(src) except ValueError: # pragma: no cover return False if hasattr(src, 'read'): # pragma: no branch data = src.read() elif safe_is_file(src): with open(src, 'rb') as fh: data = fh.read() else: # pragma: no cover data = src if hasattr(data, 'decode'): # pragma: no branch exception = None encodings = [encoding, 'utf-8', 'cp852', 'iso8859-15', 'latin1'] for encoding in encodings: # pragma: no cover if not encoding: continue try: data = data.decode(encoding) break except UnicodeDecodeError as e: exception = e except UnicodeEncodeError: break else: raise exception # pragma: no cover transactions = mt940.models.Transactions() transactions.parse(data) return transactions
def parse(src, encoding=None): ''' Parses mt940 data and returns transactions object :param src: file handler to read, filename to read or raw data as string :return: Collection of transactions :rtype: Transactions ''' def safe_is_file(filename): try: return os.path.isfile(src) except ValueError: # pragma: no cover return False if hasattr(src, 'read'): # pragma: no branch data = src.read() elif safe_is_file(src): with open(src, 'rb') as fh: data = fh.read() else: # pragma: no cover data = src if hasattr(data, 'decode'): # pragma: no branch exception = None encodings = [encoding, 'utf-8', 'cp852', 'iso8859-15', 'latin1'] for encoding in encodings: # pragma: no cover if not encoding: continue try: data = data.decode(encoding) break except UnicodeDecodeError as e: exception = e except UnicodeEncodeError: break else: raise exception # pragma: no cover transactions = mt940.models.Transactions() transactions.parse(data) return transactions
[ "Parses", "mt940", "data", "and", "returns", "transactions", "object" ]
WoLpH/mt940
python
https://github.com/WoLpH/mt940/blob/fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb/mt940/parser.py#L34-L78
[ "def", "parse", "(", "src", ",", "encoding", "=", "None", ")", ":", "def", "safe_is_file", "(", "filename", ")", ":", "try", ":", "return", "os", ".", "path", ".", "isfile", "(", "src", ")", "except", "ValueError", ":", "# pragma: no cover", "return", "False", "if", "hasattr", "(", "src", ",", "'read'", ")", ":", "# pragma: no branch", "data", "=", "src", ".", "read", "(", ")", "elif", "safe_is_file", "(", "src", ")", ":", "with", "open", "(", "src", ",", "'rb'", ")", "as", "fh", ":", "data", "=", "fh", ".", "read", "(", ")", "else", ":", "# pragma: no cover", "data", "=", "src", "if", "hasattr", "(", "data", ",", "'decode'", ")", ":", "# pragma: no branch", "exception", "=", "None", "encodings", "=", "[", "encoding", ",", "'utf-8'", ",", "'cp852'", ",", "'iso8859-15'", ",", "'latin1'", "]", "for", "encoding", "in", "encodings", ":", "# pragma: no cover", "if", "not", "encoding", ":", "continue", "try", ":", "data", "=", "data", ".", "decode", "(", "encoding", ")", "break", "except", "UnicodeDecodeError", "as", "e", ":", "exception", "=", "e", "except", "UnicodeEncodeError", ":", "break", "else", ":", "raise", "exception", "# pragma: no cover", "transactions", "=", "mt940", ".", "models", ".", "Transactions", "(", ")", "transactions", ".", "parse", "(", "data", ")", "return", "transactions" ]
fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb
test
join_lines
Join strings together and strip whitespace in between if needed
mt940/utils.py
def join_lines(string, strip=Strip.BOTH): ''' Join strings together and strip whitespace in between if needed ''' lines = [] for line in string.splitlines(): if strip & Strip.RIGHT: line = line.rstrip() if strip & Strip.LEFT: line = line.lstrip() lines.append(line) return ''.join(lines)
def join_lines(string, strip=Strip.BOTH): ''' Join strings together and strip whitespace in between if needed ''' lines = [] for line in string.splitlines(): if strip & Strip.RIGHT: line = line.rstrip() if strip & Strip.LEFT: line = line.lstrip() lines.append(line) return ''.join(lines)
[ "Join", "strings", "together", "and", "strip", "whitespace", "in", "between", "if", "needed" ]
WoLpH/mt940
python
https://github.com/WoLpH/mt940/blob/fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb/mt940/utils.py#L28-L43
[ "def", "join_lines", "(", "string", ",", "strip", "=", "Strip", ".", "BOTH", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "string", ".", "splitlines", "(", ")", ":", "if", "strip", "&", "Strip", ".", "RIGHT", ":", "line", "=", "line", ".", "rstrip", "(", ")", "if", "strip", "&", "Strip", ".", "LEFT", ":", "line", "=", "line", ".", "lstrip", "(", ")", "lines", ".", "append", "(", "line", ")", "return", "''", ".", "join", "(", "lines", ")" ]
fd71c88f7ec8372f4194f831f4c29c6f9bd9d0eb
test
json_or_text
Turns response into a properly formatted json or text object
dbl/http.py
async def json_or_text(response): """Turns response into a properly formatted json or text object""" text = await response.text() if response.headers['Content-Type'] == 'application/json; charset=utf-8': return json.loads(text) return text
async def json_or_text(response): """Turns response into a properly formatted json or text object""" text = await response.text() if response.headers['Content-Type'] == 'application/json; charset=utf-8': return json.loads(text) return text
[ "Turns", "response", "into", "a", "properly", "formatted", "json", "or", "text", "object" ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/http.py#L42-L47
[ "async", "def", "json_or_text", "(", "response", ")", ":", "text", "=", "await", "response", ".", "text", "(", ")", "if", "response", ".", "headers", "[", "'Content-Type'", "]", "==", "'application/json; charset=utf-8'", ":", "return", "json", ".", "loads", "(", "text", ")", "return", "text" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
limited
Handles the message shown when we are ratelimited
dbl/http.py
async def limited(until): """Handles the message shown when we are ratelimited""" duration = int(round(until - time.time())) mins = duration / 60 fmt = 'We have exhausted a ratelimit quota. Retrying in %.2f seconds (%.3f minutes).' log.warn(fmt, duration, mins)
async def limited(until): """Handles the message shown when we are ratelimited""" duration = int(round(until - time.time())) mins = duration / 60 fmt = 'We have exhausted a ratelimit quota. Retrying in %.2f seconds (%.3f minutes).' log.warn(fmt, duration, mins)
[ "Handles", "the", "message", "shown", "when", "we", "are", "ratelimited" ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/http.py#L200-L205
[ "async", "def", "limited", "(", "until", ")", ":", "duration", "=", "int", "(", "round", "(", "until", "-", "time", ".", "time", "(", ")", ")", ")", "mins", "=", "duration", "/", "60", "fmt", "=", "'We have exhausted a ratelimit quota. Retrying in %.2f seconds (%.3f minutes).'", "log", ".", "warn", "(", "fmt", ",", "duration", ",", "mins", ")" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
HTTPClient.request
Handles requests to the API
dbl/http.py
async def request(self, method, url, **kwargs): """Handles requests to the API""" rate_limiter = RateLimiter(max_calls=59, period=60, callback=limited) # handles ratelimits. max_calls is set to 59 because current implementation will retry in 60s after 60 calls is reached. DBL has a 1h block so obviously this doesn't work well, as it will get a 429 when 60 is reached. async with rate_limiter: # this works but doesn't 'save' over restart. need a better implementation. if not self.token: raise UnauthorizedDetected('UnauthorizedDetected (status code: 401): No TOKEN provided') headers = { 'User-Agent': self.user_agent, 'Content-Type': 'application/json' } if 'json' in kwargs: kwargs['data'] = to_json(kwargs.pop('json')) kwargs['headers'] = headers headers['Authorization'] = self.token for tries in range(5): async with self.session.request(method, url, **kwargs) as resp: log.debug('%s %s with %s has returned %s', method, url, kwargs.get('data'), resp.status) data = await json_or_text(resp) if 300 > resp.status >= 200: return data if resp.status == 429: # we are being ratelimited fmt = 'We are being rate limited. Retrying in %.2f seconds (%.3f minutes).' # sleep a bit retry_after = json.loads(resp.headers.get('Retry-After')) mins = retry_after / 60 log.warning(fmt, retry_after, mins) # check if it's a global rate limit (True as only 1 ratelimit atm - /api/bots) is_global = True # is_global = data.get('global', False) if is_global: self._global_over.clear() await asyncio.sleep(retry_after, loop=self.loop) log.debug('Done sleeping for the rate limit. Retrying...') # release the global lock now that the # global rate limit has passed if is_global: self._global_over.set() log.debug('Global rate limit is now over.') continue if resp.status == 400: raise HTTPException(resp, data) elif resp.status == 401: raise Unauthorized(resp, data) elif resp.status == 403: raise Forbidden(resp, data) elif resp.status == 404: raise NotFound(resp, data) else: raise HTTPException(resp, data) # We've run out of retries, raise. raise HTTPException(resp, data)
async def request(self, method, url, **kwargs): """Handles requests to the API""" rate_limiter = RateLimiter(max_calls=59, period=60, callback=limited) # handles ratelimits. max_calls is set to 59 because current implementation will retry in 60s after 60 calls is reached. DBL has a 1h block so obviously this doesn't work well, as it will get a 429 when 60 is reached. async with rate_limiter: # this works but doesn't 'save' over restart. need a better implementation. if not self.token: raise UnauthorizedDetected('UnauthorizedDetected (status code: 401): No TOKEN provided') headers = { 'User-Agent': self.user_agent, 'Content-Type': 'application/json' } if 'json' in kwargs: kwargs['data'] = to_json(kwargs.pop('json')) kwargs['headers'] = headers headers['Authorization'] = self.token for tries in range(5): async with self.session.request(method, url, **kwargs) as resp: log.debug('%s %s with %s has returned %s', method, url, kwargs.get('data'), resp.status) data = await json_or_text(resp) if 300 > resp.status >= 200: return data if resp.status == 429: # we are being ratelimited fmt = 'We are being rate limited. Retrying in %.2f seconds (%.3f minutes).' # sleep a bit retry_after = json.loads(resp.headers.get('Retry-After')) mins = retry_after / 60 log.warning(fmt, retry_after, mins) # check if it's a global rate limit (True as only 1 ratelimit atm - /api/bots) is_global = True # is_global = data.get('global', False) if is_global: self._global_over.clear() await asyncio.sleep(retry_after, loop=self.loop) log.debug('Done sleeping for the rate limit. Retrying...') # release the global lock now that the # global rate limit has passed if is_global: self._global_over.set() log.debug('Global rate limit is now over.') continue if resp.status == 400: raise HTTPException(resp, data) elif resp.status == 401: raise Unauthorized(resp, data) elif resp.status == 403: raise Forbidden(resp, data) elif resp.status == 404: raise NotFound(resp, data) else: raise HTTPException(resp, data) # We've run out of retries, raise. raise HTTPException(resp, data)
[ "Handles", "requests", "to", "the", "API" ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/http.py#L78-L148
[ "async", "def", "request", "(", "self", ",", "method", ",", "url", ",", "*", "*", "kwargs", ")", ":", "rate_limiter", "=", "RateLimiter", "(", "max_calls", "=", "59", ",", "period", "=", "60", ",", "callback", "=", "limited", ")", "# handles ratelimits. max_calls is set to 59 because current implementation will retry in 60s after 60 calls is reached. DBL has a 1h block so obviously this doesn't work well, as it will get a 429 when 60 is reached.", "async", "with", "rate_limiter", ":", "# this works but doesn't 'save' over restart. need a better implementation.", "if", "not", "self", ".", "token", ":", "raise", "UnauthorizedDetected", "(", "'UnauthorizedDetected (status code: 401): No TOKEN provided'", ")", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", ",", "'Content-Type'", ":", "'application/json'", "}", "if", "'json'", "in", "kwargs", ":", "kwargs", "[", "'data'", "]", "=", "to_json", "(", "kwargs", ".", "pop", "(", "'json'", ")", ")", "kwargs", "[", "'headers'", "]", "=", "headers", "headers", "[", "'Authorization'", "]", "=", "self", ".", "token", "for", "tries", "in", "range", "(", "5", ")", ":", "async", "with", "self", ".", "session", ".", "request", "(", "method", ",", "url", ",", "*", "*", "kwargs", ")", "as", "resp", ":", "log", ".", "debug", "(", "'%s %s with %s has returned %s'", ",", "method", ",", "url", ",", "kwargs", ".", "get", "(", "'data'", ")", ",", "resp", ".", "status", ")", "data", "=", "await", "json_or_text", "(", "resp", ")", "if", "300", ">", "resp", ".", "status", ">=", "200", ":", "return", "data", "if", "resp", ".", "status", "==", "429", ":", "# we are being ratelimited", "fmt", "=", "'We are being rate limited. Retrying in %.2f seconds (%.3f minutes).'", "# sleep a bit", "retry_after", "=", "json", ".", "loads", "(", "resp", ".", "headers", ".", "get", "(", "'Retry-After'", ")", ")", "mins", "=", "retry_after", "/", "60", "log", ".", "warning", "(", "fmt", ",", "retry_after", ",", "mins", ")", "# check if it's a global rate limit (True as only 1 ratelimit atm - /api/bots)", "is_global", "=", "True", "# is_global = data.get('global', False)", "if", "is_global", ":", "self", ".", "_global_over", ".", "clear", "(", ")", "await", "asyncio", ".", "sleep", "(", "retry_after", ",", "loop", "=", "self", ".", "loop", ")", "log", ".", "debug", "(", "'Done sleeping for the rate limit. Retrying...'", ")", "# release the global lock now that the", "# global rate limit has passed", "if", "is_global", ":", "self", ".", "_global_over", ".", "set", "(", ")", "log", ".", "debug", "(", "'Global rate limit is now over.'", ")", "continue", "if", "resp", ".", "status", "==", "400", ":", "raise", "HTTPException", "(", "resp", ",", "data", ")", "elif", "resp", ".", "status", "==", "401", ":", "raise", "Unauthorized", "(", "resp", ",", "data", ")", "elif", "resp", ".", "status", "==", "403", ":", "raise", "Forbidden", "(", "resp", ",", "data", ")", "elif", "resp", ".", "status", "==", "404", ":", "raise", "NotFound", "(", "resp", ",", "data", ")", "else", ":", "raise", "HTTPException", "(", "resp", ",", "data", ")", "# We've run out of retries, raise.", "raise", "HTTPException", "(", "resp", ",", "data", ")" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
HTTPClient.get_bot_info
Gets the information of the given Bot ID
dbl/http.py
async def get_bot_info(self, bot_id): '''Gets the information of the given Bot ID''' resp = await self.request('GET', '{}/bots/{}'.format(self.BASE, bot_id)) resp['date'] = datetime.strptime(resp['date'], '%Y-%m-%dT%H:%M:%S.%fZ') for k in resp: if resp[k] == '': resp[k] = None return resp
async def get_bot_info(self, bot_id): '''Gets the information of the given Bot ID''' resp = await self.request('GET', '{}/bots/{}'.format(self.BASE, bot_id)) resp['date'] = datetime.strptime(resp['date'], '%Y-%m-%dT%H:%M:%S.%fZ') for k in resp: if resp[k] == '': resp[k] = None return resp
[ "Gets", "the", "information", "of", "the", "given", "Bot", "ID" ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/http.py#L177-L184
[ "async", "def", "get_bot_info", "(", "self", ",", "bot_id", ")", ":", "resp", "=", "await", "self", ".", "request", "(", "'GET'", ",", "'{}/bots/{}'", ".", "format", "(", "self", ".", "BASE", ",", "bot_id", ")", ")", "resp", "[", "'date'", "]", "=", "datetime", ".", "strptime", "(", "resp", "[", "'date'", "]", ",", "'%Y-%m-%dT%H:%M:%S.%fZ'", ")", "for", "k", "in", "resp", ":", "if", "resp", "[", "k", "]", "==", "''", ":", "resp", "[", "k", "]", "=", "None", "return", "resp" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
HTTPClient.get_bots
Gets an object of bots on DBL
dbl/http.py
async def get_bots(self, limit, offset): '''Gets an object of bots on DBL''' if limit > 500: limit = 50 return await self.request('GET', '{}/bots?limit={}&offset={}'.format(self.BASE, limit, offset))
async def get_bots(self, limit, offset): '''Gets an object of bots on DBL''' if limit > 500: limit = 50 return await self.request('GET', '{}/bots?limit={}&offset={}'.format(self.BASE, limit, offset))
[ "Gets", "an", "object", "of", "bots", "on", "DBL" ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/http.py#L190-L194
[ "async", "def", "get_bots", "(", "self", ",", "limit", ",", "offset", ")", ":", "if", "limit", ">", "500", ":", "limit", "=", "50", "return", "await", "self", ".", "request", "(", "'GET'", ",", "'{}/bots?limit={}&offset={}'", ".", "format", "(", "self", ".", "BASE", ",", "limit", ",", "offset", ")", ")" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Client.guild_count
Gets the guild count from the Client/Bot object
dbl/client.py
def guild_count(self): """Gets the guild count from the Client/Bot object""" try: return len(self.bot.guilds) except AttributeError: return len(self.bot.servers)
def guild_count(self): """Gets the guild count from the Client/Bot object""" try: return len(self.bot.guilds) except AttributeError: return len(self.bot.servers)
[ "Gets", "the", "guild", "count", "from", "the", "Client", "/", "Bot", "object" ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L76-L81
[ "def", "guild_count", "(", "self", ")", ":", "try", ":", "return", "len", "(", "self", ".", "bot", ".", "guilds", ")", "except", "AttributeError", ":", "return", "len", "(", "self", ".", "bot", ".", "servers", ")" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Client.post_guild_count
This function is a coroutine. Posts the guild count to discordbots.org .. _0 based indexing : https://en.wikipedia.org/wiki/Zero-based_numbering Parameters ========== shard_count: int[Optional] The total number of shards. shard_no: int[Optional] The index of the current shard. DBL uses `0 based indexing`_ for shards.
dbl/client.py
async def post_guild_count( self, shard_count: int = None, shard_no: int = None ): """This function is a coroutine. Posts the guild count to discordbots.org .. _0 based indexing : https://en.wikipedia.org/wiki/Zero-based_numbering Parameters ========== shard_count: int[Optional] The total number of shards. shard_no: int[Optional] The index of the current shard. DBL uses `0 based indexing`_ for shards. """ await self.http.post_guild_count(self.bot_id, self.guild_count(), shard_count, shard_no)
async def post_guild_count( self, shard_count: int = None, shard_no: int = None ): """This function is a coroutine. Posts the guild count to discordbots.org .. _0 based indexing : https://en.wikipedia.org/wiki/Zero-based_numbering Parameters ========== shard_count: int[Optional] The total number of shards. shard_no: int[Optional] The index of the current shard. DBL uses `0 based indexing`_ for shards. """ await self.http.post_guild_count(self.bot_id, self.guild_count(), shard_count, shard_no)
[ "This", "function", "is", "a", "coroutine", "." ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L96-L115
[ "async", "def", "post_guild_count", "(", "self", ",", "shard_count", ":", "int", "=", "None", ",", "shard_no", ":", "int", "=", "None", ")", ":", "await", "self", ".", "http", ".", "post_guild_count", "(", "self", ".", "bot_id", ",", "self", ".", "guild_count", "(", ")", ",", "shard_count", ",", "shard_no", ")" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Client.get_guild_count
This function is a coroutine. Gets a guild count from discordbots.org Parameters ========== bot_id: int[Optional] The bot_id of the bot you want to lookup. Defaults to the Bot provided in Client init Returns ======= stats: dict The guild count and shards of a bot. The date object is returned in a datetime.datetime object
dbl/client.py
async def get_guild_count(self, bot_id: int=None): """This function is a coroutine. Gets a guild count from discordbots.org Parameters ========== bot_id: int[Optional] The bot_id of the bot you want to lookup. Defaults to the Bot provided in Client init Returns ======= stats: dict The guild count and shards of a bot. The date object is returned in a datetime.datetime object """ if bot_id is None: bot_id = self.bot_id return await self.http.get_guild_count(bot_id)
async def get_guild_count(self, bot_id: int=None): """This function is a coroutine. Gets a guild count from discordbots.org Parameters ========== bot_id: int[Optional] The bot_id of the bot you want to lookup. Defaults to the Bot provided in Client init Returns ======= stats: dict The guild count and shards of a bot. The date object is returned in a datetime.datetime object """ if bot_id is None: bot_id = self.bot_id return await self.http.get_guild_count(bot_id)
[ "This", "function", "is", "a", "coroutine", "." ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L117-L139
[ "async", "def", "get_guild_count", "(", "self", ",", "bot_id", ":", "int", "=", "None", ")", ":", "if", "bot_id", "is", "None", ":", "bot_id", "=", "self", ".", "bot_id", "return", "await", "self", ".", "http", ".", "get_guild_count", "(", "bot_id", ")" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Client.get_bot_info
This function is a coroutine. Gets information about a bot from discordbots.org Parameters ========== bot_id: int[Optional] The bot_id of the bot you want to lookup. Returns ======= bot_info: dict Information on the bot you looked up. https://discordbots.org/api/docs#bots
dbl/client.py
async def get_bot_info(self, bot_id: int = None): """This function is a coroutine. Gets information about a bot from discordbots.org Parameters ========== bot_id: int[Optional] The bot_id of the bot you want to lookup. Returns ======= bot_info: dict Information on the bot you looked up. https://discordbots.org/api/docs#bots """ if bot_id is None: bot_id = self.bot_id return await self.http.get_bot_info(bot_id)
async def get_bot_info(self, bot_id: int = None): """This function is a coroutine. Gets information about a bot from discordbots.org Parameters ========== bot_id: int[Optional] The bot_id of the bot you want to lookup. Returns ======= bot_info: dict Information on the bot you looked up. https://discordbots.org/api/docs#bots """ if bot_id is None: bot_id = self.bot_id return await self.http.get_bot_info(bot_id)
[ "This", "function", "is", "a", "coroutine", "." ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L159-L179
[ "async", "def", "get_bot_info", "(", "self", ",", "bot_id", ":", "int", "=", "None", ")", ":", "if", "bot_id", "is", "None", ":", "bot_id", "=", "self", ".", "bot_id", "return", "await", "self", ".", "http", ".", "get_bot_info", "(", "bot_id", ")" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Client.get_bots
This function is a coroutine. Gets information about listed bots on discordbots.org Parameters ========== limit: int[Optional] The number of results you wish to lookup. Defaults to 50. Max 500. offset: int[Optional] The amount of bots to skip. Defaults to 0. Returns ======= bots: dict Returns info on the bots on DBL. https://discordbots.org/api/docs#bots
dbl/client.py
async def get_bots(self, limit: int = 50, offset: int = 0): """This function is a coroutine. Gets information about listed bots on discordbots.org Parameters ========== limit: int[Optional] The number of results you wish to lookup. Defaults to 50. Max 500. offset: int[Optional] The amount of bots to skip. Defaults to 0. Returns ======= bots: dict Returns info on the bots on DBL. https://discordbots.org/api/docs#bots """ return await self.http.get_bots(limit, offset)
async def get_bots(self, limit: int = 50, offset: int = 0): """This function is a coroutine. Gets information about listed bots on discordbots.org Parameters ========== limit: int[Optional] The number of results you wish to lookup. Defaults to 50. Max 500. offset: int[Optional] The amount of bots to skip. Defaults to 0. Returns ======= bots: dict Returns info on the bots on DBL. https://discordbots.org/api/docs#bots """ return await self.http.get_bots(limit, offset)
[ "This", "function", "is", "a", "coroutine", "." ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L181-L201
[ "async", "def", "get_bots", "(", "self", ",", "limit", ":", "int", "=", "50", ",", "offset", ":", "int", "=", "0", ")", ":", "return", "await", "self", ".", "http", ".", "get_bots", "(", "limit", ",", "offset", ")" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Client.generate_widget_large
This function is a coroutine. Generates a custom large widget. Do not add `#` to the color codes (e.g. #FF00FF become FF00FF). Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. top: str The hex color code of the top bar. mid: str The hex color code of the main section. user: str The hex color code of the username text. cert: str The hex color code of the certified text (if applicable). data: str The hex color code of the statistics (numbers only e.g. 44) of the bot. label: str The hex color code of the description (text e.g. guild count) of the statistics. highlight: str The hex color code of the data boxes. Returns ======= URL of the widget: str
dbl/client.py
async def generate_widget_large( self, bot_id: int = None, top: str = '2C2F33', mid: str = '23272A', user: str = 'FFFFFF', cert: str = 'FFFFFF', data: str = 'FFFFFF', label: str = '99AAB5', highlight: str = '2C2F33' ): """This function is a coroutine. Generates a custom large widget. Do not add `#` to the color codes (e.g. #FF00FF become FF00FF). Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. top: str The hex color code of the top bar. mid: str The hex color code of the main section. user: str The hex color code of the username text. cert: str The hex color code of the certified text (if applicable). data: str The hex color code of the statistics (numbers only e.g. 44) of the bot. label: str The hex color code of the description (text e.g. guild count) of the statistics. highlight: str The hex color code of the data boxes. Returns ======= URL of the widget: str """ url = 'https://discordbots.org/api/widget/{0}.png?topcolor={1}&middlecolor={2}&usernamecolor={3}&certifiedcolor={4}&datacolor={5}&labelcolor={6}&highlightcolor={7}' if bot_id is None: bot_id = self.bot_id url = url.format(bot_id, top, mid, user, cert, data, label, highlight) return url
async def generate_widget_large( self, bot_id: int = None, top: str = '2C2F33', mid: str = '23272A', user: str = 'FFFFFF', cert: str = 'FFFFFF', data: str = 'FFFFFF', label: str = '99AAB5', highlight: str = '2C2F33' ): """This function is a coroutine. Generates a custom large widget. Do not add `#` to the color codes (e.g. #FF00FF become FF00FF). Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. top: str The hex color code of the top bar. mid: str The hex color code of the main section. user: str The hex color code of the username text. cert: str The hex color code of the certified text (if applicable). data: str The hex color code of the statistics (numbers only e.g. 44) of the bot. label: str The hex color code of the description (text e.g. guild count) of the statistics. highlight: str The hex color code of the data boxes. Returns ======= URL of the widget: str """ url = 'https://discordbots.org/api/widget/{0}.png?topcolor={1}&middlecolor={2}&usernamecolor={3}&certifiedcolor={4}&datacolor={5}&labelcolor={6}&highlightcolor={7}' if bot_id is None: bot_id = self.bot_id url = url.format(bot_id, top, mid, user, cert, data, label, highlight) return url
[ "This", "function", "is", "a", "coroutine", "." ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L223-L267
[ "async", "def", "generate_widget_large", "(", "self", ",", "bot_id", ":", "int", "=", "None", ",", "top", ":", "str", "=", "'2C2F33'", ",", "mid", ":", "str", "=", "'23272A'", ",", "user", ":", "str", "=", "'FFFFFF'", ",", "cert", ":", "str", "=", "'FFFFFF'", ",", "data", ":", "str", "=", "'FFFFFF'", ",", "label", ":", "str", "=", "'99AAB5'", ",", "highlight", ":", "str", "=", "'2C2F33'", ")", ":", "url", "=", "'https://discordbots.org/api/widget/{0}.png?topcolor={1}&middlecolor={2}&usernamecolor={3}&certifiedcolor={4}&datacolor={5}&labelcolor={6}&highlightcolor={7}'", "if", "bot_id", "is", "None", ":", "bot_id", "=", "self", ".", "bot_id", "url", "=", "url", ".", "format", "(", "bot_id", ",", "top", ",", "mid", ",", "user", ",", "cert", ",", "data", ",", "label", ",", "highlight", ")", "return", "url" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Client.get_widget_large
This function is a coroutine. Generates the default large widget. Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. Returns ======= URL of the widget: str
dbl/client.py
async def get_widget_large(self, bot_id: int = None): """This function is a coroutine. Generates the default large widget. Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. Returns ======= URL of the widget: str """ if bot_id is None: bot_id = self.bot_id url = 'https://discordbots.org/api/widget/{0}.png'.format(bot_id) return url
async def get_widget_large(self, bot_id: int = None): """This function is a coroutine. Generates the default large widget. Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. Returns ======= URL of the widget: str """ if bot_id is None: bot_id = self.bot_id url = 'https://discordbots.org/api/widget/{0}.png'.format(bot_id) return url
[ "This", "function", "is", "a", "coroutine", "." ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L269-L288
[ "async", "def", "get_widget_large", "(", "self", ",", "bot_id", ":", "int", "=", "None", ")", ":", "if", "bot_id", "is", "None", ":", "bot_id", "=", "self", ".", "bot_id", "url", "=", "'https://discordbots.org/api/widget/{0}.png'", ".", "format", "(", "bot_id", ")", "return", "url" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Client.generate_widget_small
This function is a coroutine. Generates a custom large widget. Do not add `#` to the color codes (e.g. #FF00FF become FF00FF). Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. avabg: str The hex color code of the background of the avatar (if the avatar has transparency). lcol: str The hex color code of the left background color. rcol: str The hex color code of the right background color. ltxt: str The hex color code of the left text. rtxt: str The hex color code of the right text. Returns ======= URL of the widget: str
dbl/client.py
async def generate_widget_small( self, bot_id: int = None, avabg: str = '2C2F33', lcol: str = '23272A', rcol: str = '2C2F33', ltxt: str = 'FFFFFF', rtxt: str = 'FFFFFF' ): """This function is a coroutine. Generates a custom large widget. Do not add `#` to the color codes (e.g. #FF00FF become FF00FF). Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. avabg: str The hex color code of the background of the avatar (if the avatar has transparency). lcol: str The hex color code of the left background color. rcol: str The hex color code of the right background color. ltxt: str The hex color code of the left text. rtxt: str The hex color code of the right text. Returns ======= URL of the widget: str """ url = 'https://discordbots.org/api/widget/lib/{0}.png?avatarbg={1}&lefttextcolor={2}&righttextcolor={3}&leftcolor={4}&rightcolor={5}' if bot_id is None: bot_id = self.bot_id url = url.format(bot_id, avabg, ltxt, rtxt, lcol, rcol) return url
async def generate_widget_small( self, bot_id: int = None, avabg: str = '2C2F33', lcol: str = '23272A', rcol: str = '2C2F33', ltxt: str = 'FFFFFF', rtxt: str = 'FFFFFF' ): """This function is a coroutine. Generates a custom large widget. Do not add `#` to the color codes (e.g. #FF00FF become FF00FF). Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. avabg: str The hex color code of the background of the avatar (if the avatar has transparency). lcol: str The hex color code of the left background color. rcol: str The hex color code of the right background color. ltxt: str The hex color code of the left text. rtxt: str The hex color code of the right text. Returns ======= URL of the widget: str """ url = 'https://discordbots.org/api/widget/lib/{0}.png?avatarbg={1}&lefttextcolor={2}&righttextcolor={3}&leftcolor={4}&rightcolor={5}' if bot_id is None: bot_id = self.bot_id url = url.format(bot_id, avabg, ltxt, rtxt, lcol, rcol) return url
[ "This", "function", "is", "a", "coroutine", "." ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L290-L328
[ "async", "def", "generate_widget_small", "(", "self", ",", "bot_id", ":", "int", "=", "None", ",", "avabg", ":", "str", "=", "'2C2F33'", ",", "lcol", ":", "str", "=", "'23272A'", ",", "rcol", ":", "str", "=", "'2C2F33'", ",", "ltxt", ":", "str", "=", "'FFFFFF'", ",", "rtxt", ":", "str", "=", "'FFFFFF'", ")", ":", "url", "=", "'https://discordbots.org/api/widget/lib/{0}.png?avatarbg={1}&lefttextcolor={2}&righttextcolor={3}&leftcolor={4}&rightcolor={5}'", "if", "bot_id", "is", "None", ":", "bot_id", "=", "self", ".", "bot_id", "url", "=", "url", ".", "format", "(", "bot_id", ",", "avabg", ",", "ltxt", ",", "rtxt", ",", "lcol", ",", "rcol", ")", "return", "url" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Client.get_widget_small
This function is a coroutine. Generates the default small widget. Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. Returns ======= URL of the widget: str
dbl/client.py
async def get_widget_small(self, bot_id: int = None): """This function is a coroutine. Generates the default small widget. Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. Returns ======= URL of the widget: str """ if bot_id is None: bot_id = self.bot_id url = 'https://discordbots.org/api/widget/lib/{0}.png'.format(bot_id) return url
async def get_widget_small(self, bot_id: int = None): """This function is a coroutine. Generates the default small widget. Parameters ========== bot_id: int The bot_id of the bot you wish to make a widget for. Returns ======= URL of the widget: str """ if bot_id is None: bot_id = self.bot_id url = 'https://discordbots.org/api/widget/lib/{0}.png'.format(bot_id) return url
[ "This", "function", "is", "a", "coroutine", "." ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L330-L349
[ "async", "def", "get_widget_small", "(", "self", ",", "bot_id", ":", "int", "=", "None", ")", ":", "if", "bot_id", "is", "None", ":", "bot_id", "=", "self", ".", "bot_id", "url", "=", "'https://discordbots.org/api/widget/lib/{0}.png'", ".", "format", "(", "bot_id", ")", "return", "url" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Client.close
This function is a coroutine. Closes all connections.
dbl/client.py
async def close(self): """This function is a coroutine. Closes all connections.""" if self._is_closed: return else: await self.http.close() self._is_closed = True
async def close(self): """This function is a coroutine. Closes all connections.""" if self._is_closed: return else: await self.http.close() self._is_closed = True
[ "This", "function", "is", "a", "coroutine", "." ]
DiscordBotList/DBL-Python-Library
python
https://github.com/DiscordBotList/DBL-Python-Library/blob/c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa/dbl/client.py#L351-L359
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "_is_closed", ":", "return", "else", ":", "await", "self", ".", "http", ".", "close", "(", ")", "self", ".", "_is_closed", "=", "True" ]
c1461ae0acc644cdeedef8fd6b5e36f76d81c1aa
test
Port.read
Read incoming message.
priv/python3/erlport/erlproto.py
def read(self): """Read incoming message.""" packet = self.packet with self.__read_lock: buffer = self.__buffer while len(buffer) < packet: buffer += self._read_data() length = self.__unpack(buffer[:packet])[0] + packet while len(buffer) < length: buffer += self._read_data() term, self.__buffer = decode(buffer[packet:]) return term
def read(self): """Read incoming message.""" packet = self.packet with self.__read_lock: buffer = self.__buffer while len(buffer) < packet: buffer += self._read_data() length = self.__unpack(buffer[:packet])[0] + packet while len(buffer) < length: buffer += self._read_data() term, self.__buffer = decode(buffer[packet:]) return term
[ "Read", "incoming", "message", "." ]
hdima/erlport
python
https://github.com/hdima/erlport/blob/246b7722d62b87b48be66d9a871509a537728962/priv/python3/erlport/erlproto.py#L84-L95
[ "def", "read", "(", "self", ")", ":", "packet", "=", "self", ".", "packet", "with", "self", ".", "__read_lock", ":", "buffer", "=", "self", ".", "__buffer", "while", "len", "(", "buffer", ")", "<", "packet", ":", "buffer", "+=", "self", ".", "_read_data", "(", ")", "length", "=", "self", ".", "__unpack", "(", "buffer", "[", ":", "packet", "]", ")", "[", "0", "]", "+", "packet", "while", "len", "(", "buffer", ")", "<", "length", ":", "buffer", "+=", "self", ".", "_read_data", "(", ")", "term", ",", "self", ".", "__buffer", "=", "decode", "(", "buffer", "[", "packet", ":", "]", ")", "return", "term" ]
246b7722d62b87b48be66d9a871509a537728962
test
Port.write
Write outgoing message.
priv/python3/erlport/erlproto.py
def write(self, message): """Write outgoing message.""" data = encode(message, compressed=self.compressed) length = len(data) data = self.__pack(length) + data with self.__write_lock: while data: try: n = os.write(self.out_d, data) except OSError as why: if why.errno in (errno.EPIPE, errno.EINVAL): raise EOFError() raise if not n: raise EOFError() data = data[n:] return length + self.packet
def write(self, message): """Write outgoing message.""" data = encode(message, compressed=self.compressed) length = len(data) data = self.__pack(length) + data with self.__write_lock: while data: try: n = os.write(self.out_d, data) except OSError as why: if why.errno in (errno.EPIPE, errno.EINVAL): raise EOFError() raise if not n: raise EOFError() data = data[n:] return length + self.packet
[ "Write", "outgoing", "message", "." ]
hdima/erlport
python
https://github.com/hdima/erlport/blob/246b7722d62b87b48be66d9a871509a537728962/priv/python3/erlport/erlproto.py#L97-L113
[ "def", "write", "(", "self", ",", "message", ")", ":", "data", "=", "encode", "(", "message", ",", "compressed", "=", "self", ".", "compressed", ")", "length", "=", "len", "(", "data", ")", "data", "=", "self", ".", "__pack", "(", "length", ")", "+", "data", "with", "self", ".", "__write_lock", ":", "while", "data", ":", "try", ":", "n", "=", "os", ".", "write", "(", "self", ".", "out_d", ",", "data", ")", "except", "OSError", "as", "why", ":", "if", "why", ".", "errno", "in", "(", "errno", ".", "EPIPE", ",", "errno", ".", "EINVAL", ")", ":", "raise", "EOFError", "(", ")", "raise", "if", "not", "n", ":", "raise", "EOFError", "(", ")", "data", "=", "data", "[", "n", ":", "]", "return", "length", "+", "self", ".", "packet" ]
246b7722d62b87b48be66d9a871509a537728962
test
Port.close
Close port.
priv/python3/erlport/erlproto.py
def close(self): """Close port.""" os.close(self.in_d) os.close(self.out_d)
def close(self): """Close port.""" os.close(self.in_d) os.close(self.out_d)
[ "Close", "port", "." ]
hdima/erlport
python
https://github.com/hdima/erlport/blob/246b7722d62b87b48be66d9a871509a537728962/priv/python3/erlport/erlproto.py#L115-L118
[ "def", "close", "(", "self", ")", ":", "os", ".", "close", "(", "self", ".", "in_d", ")", "os", ".", "close", "(", "self", ".", "out_d", ")" ]
246b7722d62b87b48be66d9a871509a537728962
test
decode
Decode Erlang external term.
priv/python3/erlport/erlterms.py
def decode(string): """Decode Erlang external term.""" if not string: raise IncompleteData(string) if string[0] != 131: raise ValueError("unknown protocol version: %r" % string[0]) if string[1:2] == b'P': # compressed term if len(string) < 16: raise IncompleteData(string) d = decompressobj() term_string = d.decompress(string[6:]) + d.flush() uncompressed_size, = _int4_unpack(string[2:6]) if len(term_string) != uncompressed_size: raise ValueError( "invalid compressed tag, " "%d bytes but got %d" % (uncompressed_size, len(term_string))) # tail data returned by decode_term() can be simple ignored term, _tail = decode_term(term_string) return term, d.unused_data return decode_term(string[1:])
def decode(string): """Decode Erlang external term.""" if not string: raise IncompleteData(string) if string[0] != 131: raise ValueError("unknown protocol version: %r" % string[0]) if string[1:2] == b'P': # compressed term if len(string) < 16: raise IncompleteData(string) d = decompressobj() term_string = d.decompress(string[6:]) + d.flush() uncompressed_size, = _int4_unpack(string[2:6]) if len(term_string) != uncompressed_size: raise ValueError( "invalid compressed tag, " "%d bytes but got %d" % (uncompressed_size, len(term_string))) # tail data returned by decode_term() can be simple ignored term, _tail = decode_term(term_string) return term, d.unused_data return decode_term(string[1:])
[ "Decode", "Erlang", "external", "term", "." ]
hdima/erlport
python
https://github.com/hdima/erlport/blob/246b7722d62b87b48be66d9a871509a537728962/priv/python3/erlport/erlterms.py#L168-L188
[ "def", "decode", "(", "string", ")", ":", "if", "not", "string", ":", "raise", "IncompleteData", "(", "string", ")", "if", "string", "[", "0", "]", "!=", "131", ":", "raise", "ValueError", "(", "\"unknown protocol version: %r\"", "%", "string", "[", "0", "]", ")", "if", "string", "[", "1", ":", "2", "]", "==", "b'P'", ":", "# compressed term", "if", "len", "(", "string", ")", "<", "16", ":", "raise", "IncompleteData", "(", "string", ")", "d", "=", "decompressobj", "(", ")", "term_string", "=", "d", ".", "decompress", "(", "string", "[", "6", ":", "]", ")", "+", "d", ".", "flush", "(", ")", "uncompressed_size", ",", "=", "_int4_unpack", "(", "string", "[", "2", ":", "6", "]", ")", "if", "len", "(", "term_string", ")", "!=", "uncompressed_size", ":", "raise", "ValueError", "(", "\"invalid compressed tag, \"", "\"%d bytes but got %d\"", "%", "(", "uncompressed_size", ",", "len", "(", "term_string", ")", ")", ")", "# tail data returned by decode_term() can be simple ignored", "term", ",", "_tail", "=", "decode_term", "(", "term_string", ")", "return", "term", ",", "d", ".", "unused_data", "return", "decode_term", "(", "string", "[", "1", ":", "]", ")" ]
246b7722d62b87b48be66d9a871509a537728962
test
encode
Encode Erlang external term.
priv/python3/erlport/erlterms.py
def encode(term, compressed=False): """Encode Erlang external term.""" encoded_term = encode_term(term) # False and 0 do not attempt compression. if compressed: if compressed is True: # default compression level of 6 compressed = 6 elif compressed < 0 or compressed > 9: raise ValueError("invalid compression level: %r" % (compressed,)) zlib_term = compress(encoded_term, compressed) ln = len(encoded_term) if len(zlib_term) + 5 <= ln: # Compressed term should be smaller return b"\x83P" + _int4_pack(ln) + zlib_term return b"\x83" + encoded_term
def encode(term, compressed=False): """Encode Erlang external term.""" encoded_term = encode_term(term) # False and 0 do not attempt compression. if compressed: if compressed is True: # default compression level of 6 compressed = 6 elif compressed < 0 or compressed > 9: raise ValueError("invalid compression level: %r" % (compressed,)) zlib_term = compress(encoded_term, compressed) ln = len(encoded_term) if len(zlib_term) + 5 <= ln: # Compressed term should be smaller return b"\x83P" + _int4_pack(ln) + zlib_term return b"\x83" + encoded_term
[ "Encode", "Erlang", "external", "term", "." ]
hdima/erlport
python
https://github.com/hdima/erlport/blob/246b7722d62b87b48be66d9a871509a537728962/priv/python3/erlport/erlterms.py#L317-L332
[ "def", "encode", "(", "term", ",", "compressed", "=", "False", ")", ":", "encoded_term", "=", "encode_term", "(", "term", ")", "# False and 0 do not attempt compression.", "if", "compressed", ":", "if", "compressed", "is", "True", ":", "# default compression level of 6", "compressed", "=", "6", "elif", "compressed", "<", "0", "or", "compressed", ">", "9", ":", "raise", "ValueError", "(", "\"invalid compression level: %r\"", "%", "(", "compressed", ",", ")", ")", "zlib_term", "=", "compress", "(", "encoded_term", ",", "compressed", ")", "ln", "=", "len", "(", "encoded_term", ")", "if", "len", "(", "zlib_term", ")", "+", "5", "<=", "ln", ":", "# Compressed term should be smaller", "return", "b\"\\x83P\"", "+", "_int4_pack", "(", "ln", ")", "+", "zlib_term", "return", "b\"\\x83\"", "+", "encoded_term" ]
246b7722d62b87b48be66d9a871509a537728962
test
SdSecureClient.get_default_falco_rules_files
**Description** Get the set of falco rules files from the backend. The _files programs and endpoints are a replacement for the system_file endpoints and allow for publishing multiple files instead of a single file as well as publishing multiple variants of a given file that are compatible with different agent versions. **Arguments** - None **Success Return Value** A dict with the following keys: - tag: A string used to uniquely identify this set of rules. It is recommended that this tag change every time the set of rules is updated. - files: An array of dicts. Each dict has the following keys: - name: the name of the file - variants: An array of dicts with the following keys: - requiredEngineVersion: the minimum falco engine version that can read this file - content: the falco rules content An example would be: {'tag': 'v1.5.9', 'files': [ { 'name': 'falco_rules.yaml', 'variants': [ { 'content': '- required_engine_version: 29\n\n- list: foo\n', 'requiredEngineVersion': 29 }, { 'content': '- required_engine_version: 1\n\n- list: foo\n', 'requiredEngineVersion': 1 } ] }, { 'name': 'k8s_audit_rules.yaml', 'variants': [ { 'content': '# some comment\n', 'requiredEngineVersion': 0 } ] } ] } **Example** `examples/get_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_default_falco_rules_files.py>`_
sdcclient/_secure.py
def get_default_falco_rules_files(self): '''**Description** Get the set of falco rules files from the backend. The _files programs and endpoints are a replacement for the system_file endpoints and allow for publishing multiple files instead of a single file as well as publishing multiple variants of a given file that are compatible with different agent versions. **Arguments** - None **Success Return Value** A dict with the following keys: - tag: A string used to uniquely identify this set of rules. It is recommended that this tag change every time the set of rules is updated. - files: An array of dicts. Each dict has the following keys: - name: the name of the file - variants: An array of dicts with the following keys: - requiredEngineVersion: the minimum falco engine version that can read this file - content: the falco rules content An example would be: {'tag': 'v1.5.9', 'files': [ { 'name': 'falco_rules.yaml', 'variants': [ { 'content': '- required_engine_version: 29\n\n- list: foo\n', 'requiredEngineVersion': 29 }, { 'content': '- required_engine_version: 1\n\n- list: foo\n', 'requiredEngineVersion': 1 } ] }, { 'name': 'k8s_audit_rules.yaml', 'variants': [ { 'content': '# some comment\n', 'requiredEngineVersion': 0 } ] } ] } **Example** `examples/get_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_default_falco_rules_files.py>`_ ''' res = self._get_falco_rules_files("default") if not res[0]: return res else: res_obj = res[1]["defaultFalcoRulesFiles"] # Copy only the tag and files over ret = {} if "tag" in res_obj: ret["tag"] = res_obj["tag"] if "files" in res_obj: ret["files"] = res_obj["files"] return [True, ret]
def get_default_falco_rules_files(self): '''**Description** Get the set of falco rules files from the backend. The _files programs and endpoints are a replacement for the system_file endpoints and allow for publishing multiple files instead of a single file as well as publishing multiple variants of a given file that are compatible with different agent versions. **Arguments** - None **Success Return Value** A dict with the following keys: - tag: A string used to uniquely identify this set of rules. It is recommended that this tag change every time the set of rules is updated. - files: An array of dicts. Each dict has the following keys: - name: the name of the file - variants: An array of dicts with the following keys: - requiredEngineVersion: the minimum falco engine version that can read this file - content: the falco rules content An example would be: {'tag': 'v1.5.9', 'files': [ { 'name': 'falco_rules.yaml', 'variants': [ { 'content': '- required_engine_version: 29\n\n- list: foo\n', 'requiredEngineVersion': 29 }, { 'content': '- required_engine_version: 1\n\n- list: foo\n', 'requiredEngineVersion': 1 } ] }, { 'name': 'k8s_audit_rules.yaml', 'variants': [ { 'content': '# some comment\n', 'requiredEngineVersion': 0 } ] } ] } **Example** `examples/get_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_default_falco_rules_files.py>`_ ''' res = self._get_falco_rules_files("default") if not res[0]: return res else: res_obj = res[1]["defaultFalcoRulesFiles"] # Copy only the tag and files over ret = {} if "tag" in res_obj: ret["tag"] = res_obj["tag"] if "files" in res_obj: ret["files"] = res_obj["files"] return [True, ret]
[ "**", "Description", "**", "Get", "the", "set", "of", "falco", "rules", "files", "from", "the", "backend", ".", "The", "_files", "programs", "and", "endpoints", "are", "a", "replacement", "for", "the", "system_file", "endpoints", "and", "allow", "for", "publishing", "multiple", "files", "instead", "of", "a", "single", "file", "as", "well", "as", "publishing", "multiple", "variants", "of", "a", "given", "file", "that", "are", "compatible", "with", "different", "agent", "versions", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L112-L178
[ "def", "get_default_falco_rules_files", "(", "self", ")", ":", "res", "=", "self", ".", "_get_falco_rules_files", "(", "\"default\"", ")", "if", "not", "res", "[", "0", "]", ":", "return", "res", "else", ":", "res_obj", "=", "res", "[", "1", "]", "[", "\"defaultFalcoRulesFiles\"", "]", "# Copy only the tag and files over", "ret", "=", "{", "}", "if", "\"tag\"", "in", "res_obj", ":", "ret", "[", "\"tag\"", "]", "=", "res_obj", "[", "\"tag\"", "]", "if", "\"files\"", "in", "res_obj", ":", "ret", "[", "\"files\"", "]", "=", "res_obj", "[", "\"files\"", "]", "return", "[", "True", ",", "ret", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.save_default_falco_rules_files
**Description** Given a dict returned from get_default_falco_rules_files, save those files to a set of files below save_dir. The first level below save_dir is a directory with the tag name. The second level is a directory per file. The third level is a directory per variant. Finally the files are at the lowest level, in a file called "content". For example, using the example dict in get_default_falco_rules_files(), the directory layout would look like: save_dir/ v1.5.9/ falco_rules.yaml/ 29/ content: a file containing "- required_engine_version: 29\n\n- list: foo\n" 1/ content: a file containing "- required_engine_version: 1\n\n- list: foo\n" k8s_audit_rules.yaml/ 0/ content: a file containing "# some comment" **Arguments** - fsobj: a python dict matching the structure returned by get_default_falco_rules_files() - save_dir: a directory path under which to save the files. If the path already exists, it will be removed first. **Success Return Value** - None **Example** `examples/get_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_default_falco_rules_files.py>`_
sdcclient/_secure.py
def save_default_falco_rules_files(self, fsobj, save_dir): '''**Description** Given a dict returned from get_default_falco_rules_files, save those files to a set of files below save_dir. The first level below save_dir is a directory with the tag name. The second level is a directory per file. The third level is a directory per variant. Finally the files are at the lowest level, in a file called "content". For example, using the example dict in get_default_falco_rules_files(), the directory layout would look like: save_dir/ v1.5.9/ falco_rules.yaml/ 29/ content: a file containing "- required_engine_version: 29\n\n- list: foo\n" 1/ content: a file containing "- required_engine_version: 1\n\n- list: foo\n" k8s_audit_rules.yaml/ 0/ content: a file containing "# some comment" **Arguments** - fsobj: a python dict matching the structure returned by get_default_falco_rules_files() - save_dir: a directory path under which to save the files. If the path already exists, it will be removed first. **Success Return Value** - None **Example** `examples/get_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_default_falco_rules_files.py>`_ ''' if os.path.exists(save_dir): try: if os.path.isdir(save_dir): shutil.rmtree(save_dir) else: os.unlink(save_dir) except Exception as e: return [False, "Could not remove existing save dir {}: {}".format(save_dir, str(e))] prefix = os.path.join(save_dir, fsobj["tag"]) try: os.makedirs(prefix) except Exception as e: return [False, "Could not create tag directory {}: {}".format(prefix, str(e))] if "files" in fsobj: for fobj in fsobj["files"]: fprefix = os.path.join(prefix, fobj["name"]) try: os.makedirs(fprefix) except Exception as e: return [False, "Could not create file directory {}: {}".format(fprefix, str(e))] for variant in fobj["variants"]: vprefix = os.path.join(fprefix, str(variant["requiredEngineVersion"])) try: os.makedirs(vprefix) except Exception as e: return [False, "Could not create variant directory {}: {}".format(vprefix, str(e))] cpath = os.path.join(vprefix, "content") try: with open(cpath, "w") as cfile: cfile.write(variant["content"]) except Exception as e: return [False, "Could not write content to {}: {}".format(cfile, str(e))] return [True, None]
def save_default_falco_rules_files(self, fsobj, save_dir): '''**Description** Given a dict returned from get_default_falco_rules_files, save those files to a set of files below save_dir. The first level below save_dir is a directory with the tag name. The second level is a directory per file. The third level is a directory per variant. Finally the files are at the lowest level, in a file called "content". For example, using the example dict in get_default_falco_rules_files(), the directory layout would look like: save_dir/ v1.5.9/ falco_rules.yaml/ 29/ content: a file containing "- required_engine_version: 29\n\n- list: foo\n" 1/ content: a file containing "- required_engine_version: 1\n\n- list: foo\n" k8s_audit_rules.yaml/ 0/ content: a file containing "# some comment" **Arguments** - fsobj: a python dict matching the structure returned by get_default_falco_rules_files() - save_dir: a directory path under which to save the files. If the path already exists, it will be removed first. **Success Return Value** - None **Example** `examples/get_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_default_falco_rules_files.py>`_ ''' if os.path.exists(save_dir): try: if os.path.isdir(save_dir): shutil.rmtree(save_dir) else: os.unlink(save_dir) except Exception as e: return [False, "Could not remove existing save dir {}: {}".format(save_dir, str(e))] prefix = os.path.join(save_dir, fsobj["tag"]) try: os.makedirs(prefix) except Exception as e: return [False, "Could not create tag directory {}: {}".format(prefix, str(e))] if "files" in fsobj: for fobj in fsobj["files"]: fprefix = os.path.join(prefix, fobj["name"]) try: os.makedirs(fprefix) except Exception as e: return [False, "Could not create file directory {}: {}".format(fprefix, str(e))] for variant in fobj["variants"]: vprefix = os.path.join(fprefix, str(variant["requiredEngineVersion"])) try: os.makedirs(vprefix) except Exception as e: return [False, "Could not create variant directory {}: {}".format(vprefix, str(e))] cpath = os.path.join(vprefix, "content") try: with open(cpath, "w") as cfile: cfile.write(variant["content"]) except Exception as e: return [False, "Could not write content to {}: {}".format(cfile, str(e))] return [True, None]
[ "**", "Description", "**", "Given", "a", "dict", "returned", "from", "get_default_falco_rules_files", "save", "those", "files", "to", "a", "set", "of", "files", "below", "save_dir", ".", "The", "first", "level", "below", "save_dir", "is", "a", "directory", "with", "the", "tag", "name", ".", "The", "second", "level", "is", "a", "directory", "per", "file", ".", "The", "third", "level", "is", "a", "directory", "per", "variant", ".", "Finally", "the", "files", "are", "at", "the", "lowest", "level", "in", "a", "file", "called", "content", ".", "For", "example", "using", "the", "example", "dict", "in", "get_default_falco_rules_files", "()", "the", "directory", "layout", "would", "look", "like", ":", "save_dir", "/", "v1", ".", "5", ".", "9", "/", "falco_rules", ".", "yaml", "/", "29", "/", "content", ":", "a", "file", "containing", "-", "required_engine_version", ":", "29", "\\", "n", "\\", "n", "-", "list", ":", "foo", "\\", "n", "1", "/", "content", ":", "a", "file", "containing", "-", "required_engine_version", ":", "1", "\\", "n", "\\", "n", "-", "list", ":", "foo", "\\", "n", "k8s_audit_rules", ".", "yaml", "/", "0", "/", "content", ":", "a", "file", "containing", "#", "some", "comment", "**", "Arguments", "**", "-", "fsobj", ":", "a", "python", "dict", "matching", "the", "structure", "returned", "by", "get_default_falco_rules_files", "()", "-", "save_dir", ":", "a", "directory", "path", "under", "which", "to", "save", "the", "files", ".", "If", "the", "path", "already", "exists", "it", "will", "be", "removed", "first", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L180-L241
[ "def", "save_default_falco_rules_files", "(", "self", ",", "fsobj", ",", "save_dir", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "save_dir", ")", ":", "try", ":", "if", "os", ".", "path", ".", "isdir", "(", "save_dir", ")", ":", "shutil", ".", "rmtree", "(", "save_dir", ")", "else", ":", "os", ".", "unlink", "(", "save_dir", ")", "except", "Exception", "as", "e", ":", "return", "[", "False", ",", "\"Could not remove existing save dir {}: {}\"", ".", "format", "(", "save_dir", ",", "str", "(", "e", ")", ")", "]", "prefix", "=", "os", ".", "path", ".", "join", "(", "save_dir", ",", "fsobj", "[", "\"tag\"", "]", ")", "try", ":", "os", ".", "makedirs", "(", "prefix", ")", "except", "Exception", "as", "e", ":", "return", "[", "False", ",", "\"Could not create tag directory {}: {}\"", ".", "format", "(", "prefix", ",", "str", "(", "e", ")", ")", "]", "if", "\"files\"", "in", "fsobj", ":", "for", "fobj", "in", "fsobj", "[", "\"files\"", "]", ":", "fprefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "fobj", "[", "\"name\"", "]", ")", "try", ":", "os", ".", "makedirs", "(", "fprefix", ")", "except", "Exception", "as", "e", ":", "return", "[", "False", ",", "\"Could not create file directory {}: {}\"", ".", "format", "(", "fprefix", ",", "str", "(", "e", ")", ")", "]", "for", "variant", "in", "fobj", "[", "\"variants\"", "]", ":", "vprefix", "=", "os", ".", "path", ".", "join", "(", "fprefix", ",", "str", "(", "variant", "[", "\"requiredEngineVersion\"", "]", ")", ")", "try", ":", "os", ".", "makedirs", "(", "vprefix", ")", "except", "Exception", "as", "e", ":", "return", "[", "False", ",", "\"Could not create variant directory {}: {}\"", ".", "format", "(", "vprefix", ",", "str", "(", "e", ")", ")", "]", "cpath", "=", "os", ".", "path", ".", "join", "(", "vprefix", ",", "\"content\"", ")", "try", ":", "with", "open", "(", "cpath", ",", "\"w\"", ")", "as", "cfile", ":", "cfile", ".", "write", "(", "variant", "[", "\"content\"", "]", ")", "except", "Exception", "as", "e", ":", "return", "[", "False", ",", "\"Could not write content to {}: {}\"", ".", "format", "(", "cfile", ",", "str", "(", "e", ")", ")", "]", "return", "[", "True", ",", "None", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.load_default_falco_rules_files
**Description** Given a file and directory layout as described in save_default_falco_rules_files(), load those files and return a dict representing the contents. This dict is suitable for passing to set_default_falco_rules_files(). **Arguments** - save_dir: a directory path from which to load the files. **Success Return Value** - A dict matching the format described in get_default_falco_rules_files. **Example** `examples/set_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/set_default_falco_rules_files.py>`_
sdcclient/_secure.py
def load_default_falco_rules_files(self, save_dir): '''**Description** Given a file and directory layout as described in save_default_falco_rules_files(), load those files and return a dict representing the contents. This dict is suitable for passing to set_default_falco_rules_files(). **Arguments** - save_dir: a directory path from which to load the files. **Success Return Value** - A dict matching the format described in get_default_falco_rules_files. **Example** `examples/set_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/set_default_falco_rules_files.py>`_ ''' tags = os.listdir(save_dir) if len(tags) != 1: return [False, "Directory {} did not contain exactly 1 entry".format(save_dir)] tpath = os.path.join(save_dir, tags[0]) if not os.path.isdir(tpath): return [False, "Tag path {} is not a directory".format(tpath)] ret = {"tag": os.path.basename(tpath), "files": []} for fdir in os.listdir(tpath): fpath = os.path.join(tpath, fdir) if not os.path.isdir(fpath): return [False, "File path {} is not a directory".format(fpath)] fobj = {"name": os.path.basename(fpath), "variants": []} for vdir in os.listdir(fpath): vpath = os.path.join(fpath, vdir) if not os.path.isdir(vpath): return [False, "Variant path {} is not a directory".format(vpath)] cpath = os.path.join(vpath, "content") try: with open(cpath, 'r') as content_file: try: required_engine_version = int(os.path.basename(vpath)) if vpath < 0: return [False, "Variant directory {} must be a positive number".format(vpath)] fobj["variants"].append({ "requiredEngineVersion": required_engine_version, "content": content_file.read() }) except ValueError: return [False, "Variant directory {} must be a number".format(vpath)] except Exception as e: return [False, "Could not read content at {}: {}".format(cpath, str(e))] ret["files"].append(fobj) return [True, ret]
def load_default_falco_rules_files(self, save_dir): '''**Description** Given a file and directory layout as described in save_default_falco_rules_files(), load those files and return a dict representing the contents. This dict is suitable for passing to set_default_falco_rules_files(). **Arguments** - save_dir: a directory path from which to load the files. **Success Return Value** - A dict matching the format described in get_default_falco_rules_files. **Example** `examples/set_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/set_default_falco_rules_files.py>`_ ''' tags = os.listdir(save_dir) if len(tags) != 1: return [False, "Directory {} did not contain exactly 1 entry".format(save_dir)] tpath = os.path.join(save_dir, tags[0]) if not os.path.isdir(tpath): return [False, "Tag path {} is not a directory".format(tpath)] ret = {"tag": os.path.basename(tpath), "files": []} for fdir in os.listdir(tpath): fpath = os.path.join(tpath, fdir) if not os.path.isdir(fpath): return [False, "File path {} is not a directory".format(fpath)] fobj = {"name": os.path.basename(fpath), "variants": []} for vdir in os.listdir(fpath): vpath = os.path.join(fpath, vdir) if not os.path.isdir(vpath): return [False, "Variant path {} is not a directory".format(vpath)] cpath = os.path.join(vpath, "content") try: with open(cpath, 'r') as content_file: try: required_engine_version = int(os.path.basename(vpath)) if vpath < 0: return [False, "Variant directory {} must be a positive number".format(vpath)] fobj["variants"].append({ "requiredEngineVersion": required_engine_version, "content": content_file.read() }) except ValueError: return [False, "Variant directory {} must be a number".format(vpath)] except Exception as e: return [False, "Could not read content at {}: {}".format(cpath, str(e))] ret["files"].append(fobj) return [True, ret]
[ "**", "Description", "**", "Given", "a", "file", "and", "directory", "layout", "as", "described", "in", "save_default_falco_rules_files", "()", "load", "those", "files", "and", "return", "a", "dict", "representing", "the", "contents", ".", "This", "dict", "is", "suitable", "for", "passing", "to", "set_default_falco_rules_files", "()", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L281-L334
[ "def", "load_default_falco_rules_files", "(", "self", ",", "save_dir", ")", ":", "tags", "=", "os", ".", "listdir", "(", "save_dir", ")", "if", "len", "(", "tags", ")", "!=", "1", ":", "return", "[", "False", ",", "\"Directory {} did not contain exactly 1 entry\"", ".", "format", "(", "save_dir", ")", "]", "tpath", "=", "os", ".", "path", ".", "join", "(", "save_dir", ",", "tags", "[", "0", "]", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "tpath", ")", ":", "return", "[", "False", ",", "\"Tag path {} is not a directory\"", ".", "format", "(", "tpath", ")", "]", "ret", "=", "{", "\"tag\"", ":", "os", ".", "path", ".", "basename", "(", "tpath", ")", ",", "\"files\"", ":", "[", "]", "}", "for", "fdir", "in", "os", ".", "listdir", "(", "tpath", ")", ":", "fpath", "=", "os", ".", "path", ".", "join", "(", "tpath", ",", "fdir", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "fpath", ")", ":", "return", "[", "False", ",", "\"File path {} is not a directory\"", ".", "format", "(", "fpath", ")", "]", "fobj", "=", "{", "\"name\"", ":", "os", ".", "path", ".", "basename", "(", "fpath", ")", ",", "\"variants\"", ":", "[", "]", "}", "for", "vdir", "in", "os", ".", "listdir", "(", "fpath", ")", ":", "vpath", "=", "os", ".", "path", ".", "join", "(", "fpath", ",", "vdir", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "vpath", ")", ":", "return", "[", "False", ",", "\"Variant path {} is not a directory\"", ".", "format", "(", "vpath", ")", "]", "cpath", "=", "os", ".", "path", ".", "join", "(", "vpath", ",", "\"content\"", ")", "try", ":", "with", "open", "(", "cpath", ",", "'r'", ")", "as", "content_file", ":", "try", ":", "required_engine_version", "=", "int", "(", "os", ".", "path", ".", "basename", "(", "vpath", ")", ")", "if", "vpath", "<", "0", ":", "return", "[", "False", ",", "\"Variant directory {} must be a positive number\"", ".", "format", "(", "vpath", ")", "]", "fobj", "[", "\"variants\"", "]", ".", "append", "(", "{", "\"requiredEngineVersion\"", ":", "required_engine_version", ",", "\"content\"", ":", "content_file", ".", "read", "(", ")", "}", ")", "except", "ValueError", ":", "return", "[", "False", ",", "\"Variant directory {} must be a number\"", ".", "format", "(", "vpath", ")", "]", "except", "Exception", "as", "e", ":", "return", "[", "False", ",", "\"Could not read content at {}: {}\"", ".", "format", "(", "cpath", ",", "str", "(", "e", ")", ")", "]", "ret", "[", "\"files\"", "]", ".", "append", "(", "fobj", ")", "return", "[", "True", ",", "ret", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.get_policy_events_duration
**Description** Fetch all policy events that occurred in the last duration_sec seconds. This method is used in conjunction with :func:`~sdcclient.SdSecureClient.get_more_policy_events` to provide paginated access to policy events. **Arguments** - duration_sec: Fetch all policy events that have occurred in the last *duration_sec* seconds. - sampling: Sample all policy events using *sampling* interval. - aggregations: When present it specifies how to aggregate events (sampling does not need to be specified, because when it's present it automatically means events will be aggregated). This field can either be a list of scope metrics or a list of policyEvents fields but (currently) not a mix of the two. When policy events fields are specified, only these can be used= severity, agentId, containerId, policyId, ruleType. - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container). - event_filter: this is a SysdigMonitor-like filter (e.g. policyEvent.policyId=3). When provided, events are filtered by some of their properties. Currently the supported set of filters is policyEvent.all(which can be used just with matches, policyEvent.policyId, policyEvent.id, policyEvent.severity, policyEvent.ruleTye, policyEvent.ruleSubtype. **Success Return Value** An array containing: - A context object that should be passed to later calls to get_more_policy_events. - An array of policy events, in JSON format. See :func:`~sdcclient.SdSecureClient.get_more_policy_events` for details on the contents of policy events. **Example** `examples/get_secure_policy_events.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_secure_policy_events.py>`_
sdcclient/_secure.py
def get_policy_events_duration(self, duration_sec, sampling=None, aggregations=None, scope_filter=None, event_filter=None): '''**Description** Fetch all policy events that occurred in the last duration_sec seconds. This method is used in conjunction with :func:`~sdcclient.SdSecureClient.get_more_policy_events` to provide paginated access to policy events. **Arguments** - duration_sec: Fetch all policy events that have occurred in the last *duration_sec* seconds. - sampling: Sample all policy events using *sampling* interval. - aggregations: When present it specifies how to aggregate events (sampling does not need to be specified, because when it's present it automatically means events will be aggregated). This field can either be a list of scope metrics or a list of policyEvents fields but (currently) not a mix of the two. When policy events fields are specified, only these can be used= severity, agentId, containerId, policyId, ruleType. - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container). - event_filter: this is a SysdigMonitor-like filter (e.g. policyEvent.policyId=3). When provided, events are filtered by some of their properties. Currently the supported set of filters is policyEvent.all(which can be used just with matches, policyEvent.policyId, policyEvent.id, policyEvent.severity, policyEvent.ruleTye, policyEvent.ruleSubtype. **Success Return Value** An array containing: - A context object that should be passed to later calls to get_more_policy_events. - An array of policy events, in JSON format. See :func:`~sdcclient.SdSecureClient.get_more_policy_events` for details on the contents of policy events. **Example** `examples/get_secure_policy_events.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_secure_policy_events.py>`_ ''' epoch = datetime.datetime.utcfromtimestamp(0) to_ts = (datetime.datetime.utcnow() - epoch).total_seconds() * 1000 * 1000 from_ts = to_ts - (int(duration_sec) * 1000 * 1000) options = {"to": to_ts, "from": from_ts, "offset": 0, "limit": 1000, "sampling": sampling, "aggregations": aggregations, "scopeFilter": scope_filter, "eventFilter": event_filter} ctx = {k: v for k, v in options.items() if v is not None} return self._get_policy_events_int(ctx)
def get_policy_events_duration(self, duration_sec, sampling=None, aggregations=None, scope_filter=None, event_filter=None): '''**Description** Fetch all policy events that occurred in the last duration_sec seconds. This method is used in conjunction with :func:`~sdcclient.SdSecureClient.get_more_policy_events` to provide paginated access to policy events. **Arguments** - duration_sec: Fetch all policy events that have occurred in the last *duration_sec* seconds. - sampling: Sample all policy events using *sampling* interval. - aggregations: When present it specifies how to aggregate events (sampling does not need to be specified, because when it's present it automatically means events will be aggregated). This field can either be a list of scope metrics or a list of policyEvents fields but (currently) not a mix of the two. When policy events fields are specified, only these can be used= severity, agentId, containerId, policyId, ruleType. - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container). - event_filter: this is a SysdigMonitor-like filter (e.g. policyEvent.policyId=3). When provided, events are filtered by some of their properties. Currently the supported set of filters is policyEvent.all(which can be used just with matches, policyEvent.policyId, policyEvent.id, policyEvent.severity, policyEvent.ruleTye, policyEvent.ruleSubtype. **Success Return Value** An array containing: - A context object that should be passed to later calls to get_more_policy_events. - An array of policy events, in JSON format. See :func:`~sdcclient.SdSecureClient.get_more_policy_events` for details on the contents of policy events. **Example** `examples/get_secure_policy_events.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_secure_policy_events.py>`_ ''' epoch = datetime.datetime.utcfromtimestamp(0) to_ts = (datetime.datetime.utcnow() - epoch).total_seconds() * 1000 * 1000 from_ts = to_ts - (int(duration_sec) * 1000 * 1000) options = {"to": to_ts, "from": from_ts, "offset": 0, "limit": 1000, "sampling": sampling, "aggregations": aggregations, "scopeFilter": scope_filter, "eventFilter": event_filter} ctx = {k: v for k, v in options.items() if v is not None} return self._get_policy_events_int(ctx)
[ "**", "Description", "**", "Fetch", "all", "policy", "events", "that", "occurred", "in", "the", "last", "duration_sec", "seconds", ".", "This", "method", "is", "used", "in", "conjunction", "with", ":", "func", ":", "~sdcclient", ".", "SdSecureClient", ".", "get_more_policy_events", "to", "provide", "paginated", "access", "to", "policy", "events", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L391-L426
[ "def", "get_policy_events_duration", "(", "self", ",", "duration_sec", ",", "sampling", "=", "None", ",", "aggregations", "=", "None", ",", "scope_filter", "=", "None", ",", "event_filter", "=", "None", ")", ":", "epoch", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "0", ")", "to_ts", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "-", "epoch", ")", ".", "total_seconds", "(", ")", "*", "1000", "*", "1000", "from_ts", "=", "to_ts", "-", "(", "int", "(", "duration_sec", ")", "*", "1000", "*", "1000", ")", "options", "=", "{", "\"to\"", ":", "to_ts", ",", "\"from\"", ":", "from_ts", ",", "\"offset\"", ":", "0", ",", "\"limit\"", ":", "1000", ",", "\"sampling\"", ":", "sampling", ",", "\"aggregations\"", ":", "aggregations", ",", "\"scopeFilter\"", ":", "scope_filter", ",", "\"eventFilter\"", ":", "event_filter", "}", "ctx", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "options", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "return", "self", ".", "_get_policy_events_int", "(", "ctx", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.get_policy_events_id_range
**Description** Fetch all policy events with id that occurred in the time range [from_sec:to_sec]. This method is used in conjunction with :func:`~sdcclient.SdSecureClient.get_more_policy_events` to provide paginated access to policy events. **Arguments** - id: the id of the policy events to fetch. - from_sec: the start of the timerange for which to get events - end_sec: the end of the timerange for which to get events - sampling: sample all policy events using *sampling* interval. - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container). - event_filter: this is a SysdigMonitor-like filter (e.g. policyEvent.policyId=3). When provided, events are filtered by some of their properties. Currently the supported set of filters is policyEvent.all(which can be used just with matches, policyEvent.policyId, policyEvent.id, policyEvent.severity, policyEvent.ruleTye, policyEvent.ruleSubtype. - aggregations: When present it specifies how to aggregate events (sampling does not need to be specified, because when it's present it automatically means events will be aggregated). This field can either be a list of scope metrics or a list of policyEvents fields but (currently) not a mix of the two. When policy events fields are specified, only these can be used= severity, agentId, containerId, policyId, ruleType. **Success Return Value** An array containing: - A context object that should be passed to later calls to get_more_policy_events. - An array of policy events, in JSON format. See :func:`~sdcclient.SdSecureClient.get_more_policy_events` for details on the contents of policy events. **Example** `examples/get_secure_policy_events.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_secure_policy_events.py>`_
sdcclient/_secure.py
def get_policy_events_id_range(self, id, from_sec, to_sec, sampling=None, aggregations=None, scope_filter=None, event_filter=None): '''**Description** Fetch all policy events with id that occurred in the time range [from_sec:to_sec]. This method is used in conjunction with :func:`~sdcclient.SdSecureClient.get_more_policy_events` to provide paginated access to policy events. **Arguments** - id: the id of the policy events to fetch. - from_sec: the start of the timerange for which to get events - end_sec: the end of the timerange for which to get events - sampling: sample all policy events using *sampling* interval. - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container). - event_filter: this is a SysdigMonitor-like filter (e.g. policyEvent.policyId=3). When provided, events are filtered by some of their properties. Currently the supported set of filters is policyEvent.all(which can be used just with matches, policyEvent.policyId, policyEvent.id, policyEvent.severity, policyEvent.ruleTye, policyEvent.ruleSubtype. - aggregations: When present it specifies how to aggregate events (sampling does not need to be specified, because when it's present it automatically means events will be aggregated). This field can either be a list of scope metrics or a list of policyEvents fields but (currently) not a mix of the two. When policy events fields are specified, only these can be used= severity, agentId, containerId, policyId, ruleType. **Success Return Value** An array containing: - A context object that should be passed to later calls to get_more_policy_events. - An array of policy events, in JSON format. See :func:`~sdcclient.SdSecureClient.get_more_policy_events` for details on the contents of policy events. **Example** `examples/get_secure_policy_events.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_secure_policy_events.py>`_ ''' options = {"id": id, "from": int(from_sec) * 1000000, "to": int(to_sec) * 1000000, "offset": 0, "limit": 1000, "sampling": sampling, "aggregations": aggregations, "scopeFilter": scope_filter, "eventFilter": event_filter} ctx = {k: v for k, v in options.items() if v is not None} return self._get_policy_events_int(ctx)
def get_policy_events_id_range(self, id, from_sec, to_sec, sampling=None, aggregations=None, scope_filter=None, event_filter=None): '''**Description** Fetch all policy events with id that occurred in the time range [from_sec:to_sec]. This method is used in conjunction with :func:`~sdcclient.SdSecureClient.get_more_policy_events` to provide paginated access to policy events. **Arguments** - id: the id of the policy events to fetch. - from_sec: the start of the timerange for which to get events - end_sec: the end of the timerange for which to get events - sampling: sample all policy events using *sampling* interval. - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container). - event_filter: this is a SysdigMonitor-like filter (e.g. policyEvent.policyId=3). When provided, events are filtered by some of their properties. Currently the supported set of filters is policyEvent.all(which can be used just with matches, policyEvent.policyId, policyEvent.id, policyEvent.severity, policyEvent.ruleTye, policyEvent.ruleSubtype. - aggregations: When present it specifies how to aggregate events (sampling does not need to be specified, because when it's present it automatically means events will be aggregated). This field can either be a list of scope metrics or a list of policyEvents fields but (currently) not a mix of the two. When policy events fields are specified, only these can be used= severity, agentId, containerId, policyId, ruleType. **Success Return Value** An array containing: - A context object that should be passed to later calls to get_more_policy_events. - An array of policy events, in JSON format. See :func:`~sdcclient.SdSecureClient.get_more_policy_events` for details on the contents of policy events. **Example** `examples/get_secure_policy_events.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_secure_policy_events.py>`_ ''' options = {"id": id, "from": int(from_sec) * 1000000, "to": int(to_sec) * 1000000, "offset": 0, "limit": 1000, "sampling": sampling, "aggregations": aggregations, "scopeFilter": scope_filter, "eventFilter": event_filter} ctx = {k: v for k, v in options.items() if v is not None} return self._get_policy_events_int(ctx)
[ "**", "Description", "**", "Fetch", "all", "policy", "events", "with", "id", "that", "occurred", "in", "the", "time", "range", "[", "from_sec", ":", "to_sec", "]", ".", "This", "method", "is", "used", "in", "conjunction", "with", ":", "func", ":", "~sdcclient", ".", "SdSecureClient", ".", "get_more_policy_events", "to", "provide", "paginated", "access", "to", "policy", "events", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L428-L462
[ "def", "get_policy_events_id_range", "(", "self", ",", "id", ",", "from_sec", ",", "to_sec", ",", "sampling", "=", "None", ",", "aggregations", "=", "None", ",", "scope_filter", "=", "None", ",", "event_filter", "=", "None", ")", ":", "options", "=", "{", "\"id\"", ":", "id", ",", "\"from\"", ":", "int", "(", "from_sec", ")", "*", "1000000", ",", "\"to\"", ":", "int", "(", "to_sec", ")", "*", "1000000", ",", "\"offset\"", ":", "0", ",", "\"limit\"", ":", "1000", ",", "\"sampling\"", ":", "sampling", ",", "\"aggregations\"", ":", "aggregations", ",", "\"scopeFilter\"", ":", "scope_filter", ",", "\"eventFilter\"", ":", "event_filter", "}", "ctx", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "options", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "return", "self", ".", "_get_policy_events_int", "(", "ctx", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.create_default_policies
**Description** Create a set of default policies using the current system falco rules file as a reference. For every falco rule in the system falco rules file, one policy will be created. The policy will take the name and description from the name and description of the corresponding falco rule. If a policy already exists with the same name, no policy is added or modified. Existing policies will be unchanged. **Arguments** - None **Success Return Value** JSON containing details on any new policies that were added. **Example** `examples/create_default_policies.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_default_policies.py>`_
sdcclient/_secure.py
def create_default_policies(self): '''**Description** Create a set of default policies using the current system falco rules file as a reference. For every falco rule in the system falco rules file, one policy will be created. The policy will take the name and description from the name and description of the corresponding falco rule. If a policy already exists with the same name, no policy is added or modified. Existing policies will be unchanged. **Arguments** - None **Success Return Value** JSON containing details on any new policies that were added. **Example** `examples/create_default_policies.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_default_policies.py>`_ ''' res = requests.post(self.url + '/api/policies/createDefault', headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def create_default_policies(self): '''**Description** Create a set of default policies using the current system falco rules file as a reference. For every falco rule in the system falco rules file, one policy will be created. The policy will take the name and description from the name and description of the corresponding falco rule. If a policy already exists with the same name, no policy is added or modified. Existing policies will be unchanged. **Arguments** - None **Success Return Value** JSON containing details on any new policies that were added. **Example** `examples/create_default_policies.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_default_policies.py>`_ ''' res = requests.post(self.url + '/api/policies/createDefault', headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Create", "a", "set", "of", "default", "policies", "using", "the", "current", "system", "falco", "rules", "file", "as", "a", "reference", ".", "For", "every", "falco", "rule", "in", "the", "system", "falco", "rules", "file", "one", "policy", "will", "be", "created", ".", "The", "policy", "will", "take", "the", "name", "and", "description", "from", "the", "name", "and", "description", "of", "the", "corresponding", "falco", "rule", ".", "If", "a", "policy", "already", "exists", "with", "the", "same", "name", "no", "policy", "is", "added", "or", "modified", ".", "Existing", "policies", "will", "be", "unchanged", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L533-L551
[ "def", "create_default_policies", "(", "self", ")", ":", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/policies/createDefault'", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.delete_all_policies
**Description** Delete all existing policies. The falco rules file is unchanged. **Arguments** - None **Success Return Value** The string "Policies Deleted" **Example** `examples/delete_all_policies.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_all_policies.py>`_
sdcclient/_secure.py
def delete_all_policies(self): '''**Description** Delete all existing policies. The falco rules file is unchanged. **Arguments** - None **Success Return Value** The string "Policies Deleted" **Example** `examples/delete_all_policies.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_all_policies.py>`_ ''' res = requests.post(self.url + '/api/policies/deleteAll', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, "Policies Deleted"]
def delete_all_policies(self): '''**Description** Delete all existing policies. The falco rules file is unchanged. **Arguments** - None **Success Return Value** The string "Policies Deleted" **Example** `examples/delete_all_policies.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_all_policies.py>`_ ''' res = requests.post(self.url + '/api/policies/deleteAll', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, "Policies Deleted"]
[ "**", "Description", "**", "Delete", "all", "existing", "policies", ".", "The", "falco", "rules", "file", "is", "unchanged", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L553-L571
[ "def", "delete_all_policies", "(", "self", ")", ":", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/policies/deleteAll'", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "return", "[", "True", ",", "\"Policies Deleted\"", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.set_policy_priorities
**Description** Change the policy evaluation order **Arguments** - priorities_json: a description of the new policy order. **Success Return Value** A JSON object representing the updated list of policy ids. **Example** `examples/set_policy_order.py <https://github.com/draios/python-sdc-client/blob/master/examples/set_policy_order.py>`_
sdcclient/_secure.py
def set_policy_priorities(self, priorities_json): '''**Description** Change the policy evaluation order **Arguments** - priorities_json: a description of the new policy order. **Success Return Value** A JSON object representing the updated list of policy ids. **Example** `examples/set_policy_order.py <https://github.com/draios/python-sdc-client/blob/master/examples/set_policy_order.py>`_ ''' try: json.loads(priorities_json) except Exception as e: return [False, "priorities json is not valid json: {}".format(str(e))] res = requests.put(self.url + '/api/policies/priorities', headers=self.hdrs, data=priorities_json, verify=self.ssl_verify) return self._request_result(res)
def set_policy_priorities(self, priorities_json): '''**Description** Change the policy evaluation order **Arguments** - priorities_json: a description of the new policy order. **Success Return Value** A JSON object representing the updated list of policy ids. **Example** `examples/set_policy_order.py <https://github.com/draios/python-sdc-client/blob/master/examples/set_policy_order.py>`_ ''' try: json.loads(priorities_json) except Exception as e: return [False, "priorities json is not valid json: {}".format(str(e))] res = requests.put(self.url + '/api/policies/priorities', headers=self.hdrs, data=priorities_json, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Change", "the", "policy", "evaluation", "order" ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L608-L629
[ "def", "set_policy_priorities", "(", "self", ",", "priorities_json", ")", ":", "try", ":", "json", ".", "loads", "(", "priorities_json", ")", "except", "Exception", "as", "e", ":", "return", "[", "False", ",", "\"priorities json is not valid json: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", "]", "res", "=", "requests", ".", "put", "(", "self", ".", "url", "+", "'/api/policies/priorities'", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "priorities_json", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.get_policy
**Description** Find the policy with name <name> and return its json description. **Arguments** - name: the name of the policy to fetch **Success Return Value** A JSON object containing the description of the policy. If there is no policy with the given name, returns False. **Example** `examples/get_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_policy.py>`_
sdcclient/_secure.py
def get_policy(self, name): '''**Description** Find the policy with name <name> and return its json description. **Arguments** - name: the name of the policy to fetch **Success Return Value** A JSON object containing the description of the policy. If there is no policy with the given name, returns False. **Example** `examples/get_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_policy.py>`_ ''' res = requests.get(self.url + '/api/policies', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] policies = res.json()["policies"] # Find the policy with the given name and return it. for policy in policies: if policy["name"] == name: return [True, policy] return [False, "No policy with name {}".format(name)]
def get_policy(self, name): '''**Description** Find the policy with name <name> and return its json description. **Arguments** - name: the name of the policy to fetch **Success Return Value** A JSON object containing the description of the policy. If there is no policy with the given name, returns False. **Example** `examples/get_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_policy.py>`_ ''' res = requests.get(self.url + '/api/policies', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] policies = res.json()["policies"] # Find the policy with the given name and return it. for policy in policies: if policy["name"] == name: return [True, policy] return [False, "No policy with name {}".format(name)]
[ "**", "Description", "**", "Find", "the", "policy", "with", "name", "<name", ">", "and", "return", "its", "json", "description", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L631-L657
[ "def", "get_policy", "(", "self", ",", "name", ")", ":", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/policies'", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "policies", "=", "res", ".", "json", "(", ")", "[", "\"policies\"", "]", "# Find the policy with the given name and return it.", "for", "policy", "in", "policies", ":", "if", "policy", "[", "\"name\"", "]", "==", "name", ":", "return", "[", "True", ",", "policy", "]", "return", "[", "False", ",", "\"No policy with name {}\"", ".", "format", "(", "name", ")", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.add_policy
**Description** Add a new policy using the provided json. **Arguments** - policy_json: a description of the new policy **Success Return Value** The string "OK" **Example** `examples/add_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/add_policy.py>`_
sdcclient/_secure.py
def add_policy(self, policy_json): '''**Description** Add a new policy using the provided json. **Arguments** - policy_json: a description of the new policy **Success Return Value** The string "OK" **Example** `examples/add_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/add_policy.py>`_ ''' try: policy_obj = json.loads(policy_json) except Exception as e: return [False, "policy json is not valid json: {}".format(str(e))] body = {"policy": policy_obj} res = requests.post(self.url + '/api/policies', headers=self.hdrs, data=json.dumps(body), verify=self.ssl_verify) return self._request_result(res)
def add_policy(self, policy_json): '''**Description** Add a new policy using the provided json. **Arguments** - policy_json: a description of the new policy **Success Return Value** The string "OK" **Example** `examples/add_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/add_policy.py>`_ ''' try: policy_obj = json.loads(policy_json) except Exception as e: return [False, "policy json is not valid json: {}".format(str(e))] body = {"policy": policy_obj} res = requests.post(self.url + '/api/policies', headers=self.hdrs, data=json.dumps(body), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Add", "a", "new", "policy", "using", "the", "provided", "json", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L659-L681
[ "def", "add_policy", "(", "self", ",", "policy_json", ")", ":", "try", ":", "policy_obj", "=", "json", ".", "loads", "(", "policy_json", ")", "except", "Exception", "as", "e", ":", "return", "[", "False", ",", "\"policy json is not valid json: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", "]", "body", "=", "{", "\"policy\"", ":", "policy_obj", "}", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/policies'", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "body", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.delete_policy_name
**Description** Delete the policy with the given name. **Arguments** - name: the name of the policy to delete **Success Return Value** The JSON object representing the now-deleted policy. **Example** `examples/delete_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_policy.py>`_
sdcclient/_secure.py
def delete_policy_name(self, name): '''**Description** Delete the policy with the given name. **Arguments** - name: the name of the policy to delete **Success Return Value** The JSON object representing the now-deleted policy. **Example** `examples/delete_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_policy.py>`_ ''' res = requests.get(self.url + '/api/policies', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] # Find the policy with the given name and delete it for policy in res.json()["policies"]: if policy["name"] == name: return self.delete_policy_id(policy["id"]) return [False, "No policy with name {}".format(name)]
def delete_policy_name(self, name): '''**Description** Delete the policy with the given name. **Arguments** - name: the name of the policy to delete **Success Return Value** The JSON object representing the now-deleted policy. **Example** `examples/delete_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_policy.py>`_ ''' res = requests.get(self.url + '/api/policies', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] # Find the policy with the given name and delete it for policy in res.json()["policies"]: if policy["name"] == name: return self.delete_policy_id(policy["id"]) return [False, "No policy with name {}".format(name)]
[ "**", "Description", "**", "Delete", "the", "policy", "with", "the", "given", "name", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L712-L735
[ "def", "delete_policy_name", "(", "self", ",", "name", ")", ":", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/policies'", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "# Find the policy with the given name and delete it", "for", "policy", "in", "res", ".", "json", "(", ")", "[", "\"policies\"", "]", ":", "if", "policy", "[", "\"name\"", "]", "==", "name", ":", "return", "self", ".", "delete_policy_id", "(", "policy", "[", "\"id\"", "]", ")", "return", "[", "False", ",", "\"No policy with name {}\"", ".", "format", "(", "name", ")", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.delete_policy_id
**Description** Delete the policy with the given id **Arguments** - id: the id of the policy to delete **Success Return Value** The JSON object representing the now-deleted policy. **Example** `examples/delete_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_policy.py>`_
sdcclient/_secure.py
def delete_policy_id(self, id): '''**Description** Delete the policy with the given id **Arguments** - id: the id of the policy to delete **Success Return Value** The JSON object representing the now-deleted policy. **Example** `examples/delete_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_policy.py>`_ ''' res = requests.delete(self.url + '/api/policies/{}'.format(id), headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def delete_policy_id(self, id): '''**Description** Delete the policy with the given id **Arguments** - id: the id of the policy to delete **Success Return Value** The JSON object representing the now-deleted policy. **Example** `examples/delete_policy.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_policy.py>`_ ''' res = requests.delete(self.url + '/api/policies/{}'.format(id), headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Delete", "the", "policy", "with", "the", "given", "id" ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L737-L752
[ "def", "delete_policy_id", "(", "self", ",", "id", ")", ":", "res", "=", "requests", ".", "delete", "(", "self", ".", "url", "+", "'/api/policies/{}'", ".", "format", "(", "id", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.add_compliance_task
**Description** Add a new compliance task. **Arguments** - name: The name of the task e.g. 'Check Docker Compliance'. - module_name: The name of the module that implements this task. Separate from task name in case you want to use the same module to run separate tasks with different scopes or schedules. [ 'docker-bench-security', 'kube-bench' ] - schedule: The frequency at which this task should run. Expressed as an `ISO 8601 Duration <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_ - scope: The agent will only run the task on hosts matching this scope or on hosts where containers match this scope. - enabled: Whether this task should actually run as defined by its schedule. **Success Return Value** A JSON representation of the compliance task.
sdcclient/_secure.py
def add_compliance_task(self, name, module_name='docker-bench-security', schedule='06:00:00Z/PT12H', scope=None, enabled=True): '''**Description** Add a new compliance task. **Arguments** - name: The name of the task e.g. 'Check Docker Compliance'. - module_name: The name of the module that implements this task. Separate from task name in case you want to use the same module to run separate tasks with different scopes or schedules. [ 'docker-bench-security', 'kube-bench' ] - schedule: The frequency at which this task should run. Expressed as an `ISO 8601 Duration <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_ - scope: The agent will only run the task on hosts matching this scope or on hosts where containers match this scope. - enabled: Whether this task should actually run as defined by its schedule. **Success Return Value** A JSON representation of the compliance task. ''' task = { "id": None, "name": name, "moduleName": module_name, "enabled": enabled, "scope": scope, "schedule": schedule } res = requests.post(self.url + '/api/complianceTasks', data=json.dumps(task), headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def add_compliance_task(self, name, module_name='docker-bench-security', schedule='06:00:00Z/PT12H', scope=None, enabled=True): '''**Description** Add a new compliance task. **Arguments** - name: The name of the task e.g. 'Check Docker Compliance'. - module_name: The name of the module that implements this task. Separate from task name in case you want to use the same module to run separate tasks with different scopes or schedules. [ 'docker-bench-security', 'kube-bench' ] - schedule: The frequency at which this task should run. Expressed as an `ISO 8601 Duration <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_ - scope: The agent will only run the task on hosts matching this scope or on hosts where containers match this scope. - enabled: Whether this task should actually run as defined by its schedule. **Success Return Value** A JSON representation of the compliance task. ''' task = { "id": None, "name": name, "moduleName": module_name, "enabled": enabled, "scope": scope, "schedule": schedule } res = requests.post(self.url + '/api/complianceTasks', data=json.dumps(task), headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Add", "a", "new", "compliance", "task", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L754-L777
[ "def", "add_compliance_task", "(", "self", ",", "name", ",", "module_name", "=", "'docker-bench-security'", ",", "schedule", "=", "'06:00:00Z/PT12H'", ",", "scope", "=", "None", ",", "enabled", "=", "True", ")", ":", "task", "=", "{", "\"id\"", ":", "None", ",", "\"name\"", ":", "name", ",", "\"moduleName\"", ":", "module_name", ",", "\"enabled\"", ":", "enabled", ",", "\"scope\"", ":", "scope", ",", "\"schedule\"", ":", "schedule", "}", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/complianceTasks'", ",", "data", "=", "json", ".", "dumps", "(", "task", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.list_compliance_tasks
**Description** Get the list of all compliance tasks. **Arguments** - None **Success Return Value** A JSON list with the representation of each compliance task.
sdcclient/_secure.py
def list_compliance_tasks(self): '''**Description** Get the list of all compliance tasks. **Arguments** - None **Success Return Value** A JSON list with the representation of each compliance task. ''' res = requests.get(self.url + '/api/complianceTasks', headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def list_compliance_tasks(self): '''**Description** Get the list of all compliance tasks. **Arguments** - None **Success Return Value** A JSON list with the representation of each compliance task. ''' res = requests.get(self.url + '/api/complianceTasks', headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Get", "the", "list", "of", "all", "compliance", "tasks", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L779-L790
[ "def", "list_compliance_tasks", "(", "self", ")", ":", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/complianceTasks'", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.get_compliance_task
**Description** Get a compliance task. **Arguments** - id: the id of the compliance task to get. **Success Return Value** A JSON representation of the compliance task.
sdcclient/_secure.py
def get_compliance_task(self, id): '''**Description** Get a compliance task. **Arguments** - id: the id of the compliance task to get. **Success Return Value** A JSON representation of the compliance task. ''' res = requests.get(self.url + '/api/complianceTasks/{}'.format(id), headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def get_compliance_task(self, id): '''**Description** Get a compliance task. **Arguments** - id: the id of the compliance task to get. **Success Return Value** A JSON representation of the compliance task. ''' res = requests.get(self.url + '/api/complianceTasks/{}'.format(id), headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Get", "a", "compliance", "task", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L792-L803
[ "def", "get_compliance_task", "(", "self", ",", "id", ")", ":", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/complianceTasks/{}'", ".", "format", "(", "id", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.update_compliance_task
**Description** Update an existing compliance task. **Arguments** - id: the id of the compliance task to be updated. - name: The name of the task e.g. 'Check Docker Compliance'. - module_name: The name of the module that implements this task. Separate from task name in case you want to use the same module to run separate tasks with different scopes or schedules. [ 'docker-bench-security', 'kube-bench' ] - schedule: The frequency at which this task should run. Expressed as an `ISO 8601 Duration <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_ - scope: The agent will only run the task on hosts matching this scope or on hosts where containers match this scope. - enabled: Whether this task should actually run as defined by its schedule. **Success Return Value** A JSON representation of the compliance task.
sdcclient/_secure.py
def update_compliance_task(self, id, name=None, module_name=None, schedule=None, scope=None, enabled=None): '''**Description** Update an existing compliance task. **Arguments** - id: the id of the compliance task to be updated. - name: The name of the task e.g. 'Check Docker Compliance'. - module_name: The name of the module that implements this task. Separate from task name in case you want to use the same module to run separate tasks with different scopes or schedules. [ 'docker-bench-security', 'kube-bench' ] - schedule: The frequency at which this task should run. Expressed as an `ISO 8601 Duration <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_ - scope: The agent will only run the task on hosts matching this scope or on hosts where containers match this scope. - enabled: Whether this task should actually run as defined by its schedule. **Success Return Value** A JSON representation of the compliance task. ''' ok, res = self.get_compliance_task(id) if not ok: return ok, res task = res options = { 'name': name, 'moduleName': module_name, 'schedule': schedule, 'scope': scope, 'enabled': enabled } task.update({k: v for k, v in options.items() if v is not None}) res = requests.put(self.url + '/api/complianceTasks/{}'.format(id), data=json.dumps(task), headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def update_compliance_task(self, id, name=None, module_name=None, schedule=None, scope=None, enabled=None): '''**Description** Update an existing compliance task. **Arguments** - id: the id of the compliance task to be updated. - name: The name of the task e.g. 'Check Docker Compliance'. - module_name: The name of the module that implements this task. Separate from task name in case you want to use the same module to run separate tasks with different scopes or schedules. [ 'docker-bench-security', 'kube-bench' ] - schedule: The frequency at which this task should run. Expressed as an `ISO 8601 Duration <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_ - scope: The agent will only run the task on hosts matching this scope or on hosts where containers match this scope. - enabled: Whether this task should actually run as defined by its schedule. **Success Return Value** A JSON representation of the compliance task. ''' ok, res = self.get_compliance_task(id) if not ok: return ok, res task = res options = { 'name': name, 'moduleName': module_name, 'schedule': schedule, 'scope': scope, 'enabled': enabled } task.update({k: v for k, v in options.items() if v is not None}) res = requests.put(self.url + '/api/complianceTasks/{}'.format(id), data=json.dumps(task), headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Update", "an", "existing", "compliance", "task", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L805-L834
[ "def", "update_compliance_task", "(", "self", ",", "id", ",", "name", "=", "None", ",", "module_name", "=", "None", ",", "schedule", "=", "None", ",", "scope", "=", "None", ",", "enabled", "=", "None", ")", ":", "ok", ",", "res", "=", "self", ".", "get_compliance_task", "(", "id", ")", "if", "not", "ok", ":", "return", "ok", ",", "res", "task", "=", "res", "options", "=", "{", "'name'", ":", "name", ",", "'moduleName'", ":", "module_name", ",", "'schedule'", ":", "schedule", ",", "'scope'", ":", "scope", ",", "'enabled'", ":", "enabled", "}", "task", ".", "update", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "options", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", ")", "res", "=", "requests", ".", "put", "(", "self", ".", "url", "+", "'/api/complianceTasks/{}'", ".", "format", "(", "id", ")", ",", "data", "=", "json", ".", "dumps", "(", "task", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.delete_compliance_task
**Description** Delete the compliance task with the given id **Arguments** - id: the id of the compliance task to delete
sdcclient/_secure.py
def delete_compliance_task(self, id): '''**Description** Delete the compliance task with the given id **Arguments** - id: the id of the compliance task to delete ''' res = requests.delete(self.url + '/api/complianceTasks/{}'.format(id), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return False, self.lasterr return True, None
def delete_compliance_task(self, id): '''**Description** Delete the compliance task with the given id **Arguments** - id: the id of the compliance task to delete ''' res = requests.delete(self.url + '/api/complianceTasks/{}'.format(id), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return False, self.lasterr return True, None
[ "**", "Description", "**", "Delete", "the", "compliance", "task", "with", "the", "given", "id" ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L836-L847
[ "def", "delete_compliance_task", "(", "self", ",", "id", ")", ":", "res", "=", "requests", ".", "delete", "(", "self", ".", "url", "+", "'/api/complianceTasks/{}'", ".", "format", "(", "id", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "False", ",", "self", ".", "lasterr", "return", "True", ",", "None" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.list_compliance_results
**Description** Get the list of all compliance tasks runs. **Arguments** - limit: Maximum number of alerts in the response. - direction: the direction (PREV or NEXT) that determines which results to return in relation to cursor. - cursor: An opaque string representing the current position in the list of alerts. It's provided in the 'responseMetadata' of the list_alerts response. - filter: an optional case insensitive filter used to match against the completed task name and return matching results. **Success Return Value** A JSON list with the representation of each compliance task run.
sdcclient/_secure.py
def list_compliance_results(self, limit=50, direction=None, cursor=None, filter=""): '''**Description** Get the list of all compliance tasks runs. **Arguments** - limit: Maximum number of alerts in the response. - direction: the direction (PREV or NEXT) that determines which results to return in relation to cursor. - cursor: An opaque string representing the current position in the list of alerts. It's provided in the 'responseMetadata' of the list_alerts response. - filter: an optional case insensitive filter used to match against the completed task name and return matching results. **Success Return Value** A JSON list with the representation of each compliance task run. ''' url = "{url}/api/complianceResults?cursor{cursor}&filter={filter}&limit={limit}{direction}".format( url=self.url, limit=limit, direction="&direction=%s" % direction if direction else "", cursor="=%d" % cursor if cursor is not None else "", filter=filter) res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def list_compliance_results(self, limit=50, direction=None, cursor=None, filter=""): '''**Description** Get the list of all compliance tasks runs. **Arguments** - limit: Maximum number of alerts in the response. - direction: the direction (PREV or NEXT) that determines which results to return in relation to cursor. - cursor: An opaque string representing the current position in the list of alerts. It's provided in the 'responseMetadata' of the list_alerts response. - filter: an optional case insensitive filter used to match against the completed task name and return matching results. **Success Return Value** A JSON list with the representation of each compliance task run. ''' url = "{url}/api/complianceResults?cursor{cursor}&filter={filter}&limit={limit}{direction}".format( url=self.url, limit=limit, direction="&direction=%s" % direction if direction else "", cursor="=%d" % cursor if cursor is not None else "", filter=filter) res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Get", "the", "list", "of", "all", "compliance", "tasks", "runs", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L849-L869
[ "def", "list_compliance_results", "(", "self", ",", "limit", "=", "50", ",", "direction", "=", "None", ",", "cursor", "=", "None", ",", "filter", "=", "\"\"", ")", ":", "url", "=", "\"{url}/api/complianceResults?cursor{cursor}&filter={filter}&limit={limit}{direction}\"", ".", "format", "(", "url", "=", "self", ".", "url", ",", "limit", "=", "limit", ",", "direction", "=", "\"&direction=%s\"", "%", "direction", "if", "direction", "else", "\"\"", ",", "cursor", "=", "\"=%d\"", "%", "cursor", "if", "cursor", "is", "not", "None", "else", "\"\"", ",", "filter", "=", "filter", ")", "res", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.get_compliance_results_csv
**Description** Retrieve the details for a specific compliance task run result in csv. **Arguments** - id: the id of the compliance task run to get. **Success Return Value** A CSV representation of the compliance task run result.
sdcclient/_secure.py
def get_compliance_results_csv(self, id): '''**Description** Retrieve the details for a specific compliance task run result in csv. **Arguments** - id: the id of the compliance task run to get. **Success Return Value** A CSV representation of the compliance task run result. ''' res = requests.get(self.url + '/api/complianceResults/{}/csv'.format(id), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return False, self.lasterr return True, res.text
def get_compliance_results_csv(self, id): '''**Description** Retrieve the details for a specific compliance task run result in csv. **Arguments** - id: the id of the compliance task run to get. **Success Return Value** A CSV representation of the compliance task run result. ''' res = requests.get(self.url + '/api/complianceResults/{}/csv'.format(id), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return False, self.lasterr return True, res.text
[ "**", "Description", "**", "Retrieve", "the", "details", "for", "a", "specific", "compliance", "task", "run", "result", "in", "csv", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L884-L898
[ "def", "get_compliance_results_csv", "(", "self", ",", "id", ")", ":", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/complianceResults/{}/csv'", ".", "format", "(", "id", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "False", ",", "self", ".", "lasterr", "return", "True", ",", "res", ".", "text" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.list_commands_audit
**Description** List the commands audit. **Arguments** - from_sec: the start of the timerange for which to get commands audit. - end_sec: the end of the timerange for which to get commands audit. - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, commands are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only commands that have happened on an ubuntu container). - command_filter: this is a SysdigMonitor-like filter (e.g. command.comm="touch"). When provided, commands are filtered by some of their properties. Currently the supported set of filters is command.comm, command.cwd, command.pid, command.ppid, command.uid, command.loginshell.id, command.loginshell.distance - limit: Maximum number of commands in the response. - metrics: A list of metric values to include in the return. **Success Return Value** A JSON representation of the commands audit.
sdcclient/_secure.py
def list_commands_audit(self, from_sec=None, to_sec=None, scope_filter=None, command_filter=None, limit=100, offset=0, metrics=[]): '''**Description** List the commands audit. **Arguments** - from_sec: the start of the timerange for which to get commands audit. - end_sec: the end of the timerange for which to get commands audit. - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, commands are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only commands that have happened on an ubuntu container). - command_filter: this is a SysdigMonitor-like filter (e.g. command.comm="touch"). When provided, commands are filtered by some of their properties. Currently the supported set of filters is command.comm, command.cwd, command.pid, command.ppid, command.uid, command.loginshell.id, command.loginshell.distance - limit: Maximum number of commands in the response. - metrics: A list of metric values to include in the return. **Success Return Value** A JSON representation of the commands audit. ''' if to_sec is None: to_sec = time.time() if from_sec is None: from_sec = to_sec - (24 * 60 * 60) # 1 day url = "{url}/api/commands?from={frm}&to={to}&offset={offset}&limit={limit}{scope}{commandFilter}{metrics}".format( url=self.url, offset=offset, limit=limit, frm=int(from_sec * 10**6), to=int(to_sec * 10**6), scope="&scopeFilter=" + scope_filter if scope_filter else "", commandFilter="&commandFilter=" + command_filter if command_filter else "", metrics="&metrics=" + json.dumps(metrics) if metrics else "") res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def list_commands_audit(self, from_sec=None, to_sec=None, scope_filter=None, command_filter=None, limit=100, offset=0, metrics=[]): '''**Description** List the commands audit. **Arguments** - from_sec: the start of the timerange for which to get commands audit. - end_sec: the end of the timerange for which to get commands audit. - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, commands are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only commands that have happened on an ubuntu container). - command_filter: this is a SysdigMonitor-like filter (e.g. command.comm="touch"). When provided, commands are filtered by some of their properties. Currently the supported set of filters is command.comm, command.cwd, command.pid, command.ppid, command.uid, command.loginshell.id, command.loginshell.distance - limit: Maximum number of commands in the response. - metrics: A list of metric values to include in the return. **Success Return Value** A JSON representation of the commands audit. ''' if to_sec is None: to_sec = time.time() if from_sec is None: from_sec = to_sec - (24 * 60 * 60) # 1 day url = "{url}/api/commands?from={frm}&to={to}&offset={offset}&limit={limit}{scope}{commandFilter}{metrics}".format( url=self.url, offset=offset, limit=limit, frm=int(from_sec * 10**6), to=int(to_sec * 10**6), scope="&scopeFilter=" + scope_filter if scope_filter else "", commandFilter="&commandFilter=" + command_filter if command_filter else "", metrics="&metrics=" + json.dumps(metrics) if metrics else "") res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "List", "the", "commands", "audit", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L900-L930
[ "def", "list_commands_audit", "(", "self", ",", "from_sec", "=", "None", ",", "to_sec", "=", "None", ",", "scope_filter", "=", "None", ",", "command_filter", "=", "None", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "metrics", "=", "[", "]", ")", ":", "if", "to_sec", "is", "None", ":", "to_sec", "=", "time", ".", "time", "(", ")", "if", "from_sec", "is", "None", ":", "from_sec", "=", "to_sec", "-", "(", "24", "*", "60", "*", "60", ")", "# 1 day", "url", "=", "\"{url}/api/commands?from={frm}&to={to}&offset={offset}&limit={limit}{scope}{commandFilter}{metrics}\"", ".", "format", "(", "url", "=", "self", ".", "url", ",", "offset", "=", "offset", ",", "limit", "=", "limit", ",", "frm", "=", "int", "(", "from_sec", "*", "10", "**", "6", ")", ",", "to", "=", "int", "(", "to_sec", "*", "10", "**", "6", ")", ",", "scope", "=", "\"&scopeFilter=\"", "+", "scope_filter", "if", "scope_filter", "else", "\"\"", ",", "commandFilter", "=", "\"&commandFilter=\"", "+", "command_filter", "if", "command_filter", "else", "\"\"", ",", "metrics", "=", "\"&metrics=\"", "+", "json", ".", "dumps", "(", "metrics", ")", "if", "metrics", "else", "\"\"", ")", "res", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdSecureClient.get_command_audit
**Description** Get a command audit. **Arguments** - id: the id of the command audit to get. **Success Return Value** A JSON representation of the command audit.
sdcclient/_secure.py
def get_command_audit(self, id, metrics=[]): '''**Description** Get a command audit. **Arguments** - id: the id of the command audit to get. **Success Return Value** A JSON representation of the command audit. ''' url = "{url}/api/commands/{id}?from=0&to={to}{metrics}".format( url=self.url, id=id, to=int(time.time() * 10**6), metrics="&metrics=" + json.dumps(metrics) if metrics else "") res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def get_command_audit(self, id, metrics=[]): '''**Description** Get a command audit. **Arguments** - id: the id of the command audit to get. **Success Return Value** A JSON representation of the command audit. ''' url = "{url}/api/commands/{id}?from=0&to={to}{metrics}".format( url=self.url, id=id, to=int(time.time() * 10**6), metrics="&metrics=" + json.dumps(metrics) if metrics else "") res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Get", "a", "command", "audit", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L932-L948
[ "def", "get_command_audit", "(", "self", ",", "id", ",", "metrics", "=", "[", "]", ")", ":", "url", "=", "\"{url}/api/commands/{id}?from=0&to={to}{metrics}\"", ".", "format", "(", "url", "=", "self", ".", "url", ",", "id", "=", "id", ",", "to", "=", "int", "(", "time", ".", "time", "(", ")", "*", "10", "**", "6", ")", ",", "metrics", "=", "\"&metrics=\"", "+", "json", ".", "dumps", "(", "metrics", ")", "if", "metrics", "else", "\"\"", ")", "res", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.get_notifications
**Description** Returns the list of Sysdig Monitor alert notifications. **Arguments** - **from_ts**: filter events by start time. Timestamp format is in UTC (seconds). - **to_ts**: filter events by start time. Timestamp format is in UTC (seconds). - **state**: filter events by alert state. Supported values are ``OK`` and ``ACTIVE``. - **resolved**: filter events by resolution status. Supported values are ``True`` and ``False``. **Success Return Value** A dictionary containing the list of notifications. **Example** `examples/list_alert_notifications.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_alert_notifications.py>`_
sdcclient/_monitor.py
def get_notifications(self, from_ts, to_ts, state=None, resolved=None): '''**Description** Returns the list of Sysdig Monitor alert notifications. **Arguments** - **from_ts**: filter events by start time. Timestamp format is in UTC (seconds). - **to_ts**: filter events by start time. Timestamp format is in UTC (seconds). - **state**: filter events by alert state. Supported values are ``OK`` and ``ACTIVE``. - **resolved**: filter events by resolution status. Supported values are ``True`` and ``False``. **Success Return Value** A dictionary containing the list of notifications. **Example** `examples/list_alert_notifications.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_alert_notifications.py>`_ ''' params = {} if from_ts is not None: params['from'] = from_ts * 1000000 if to_ts is not None: params['to'] = to_ts * 1000000 if state is not None: params['state'] = state if resolved is not None: params['resolved'] = resolved res = requests.get(self.url + '/api/notifications', headers=self.hdrs, params=params, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, res.json()]
def get_notifications(self, from_ts, to_ts, state=None, resolved=None): '''**Description** Returns the list of Sysdig Monitor alert notifications. **Arguments** - **from_ts**: filter events by start time. Timestamp format is in UTC (seconds). - **to_ts**: filter events by start time. Timestamp format is in UTC (seconds). - **state**: filter events by alert state. Supported values are ``OK`` and ``ACTIVE``. - **resolved**: filter events by resolution status. Supported values are ``True`` and ``False``. **Success Return Value** A dictionary containing the list of notifications. **Example** `examples/list_alert_notifications.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_alert_notifications.py>`_ ''' params = {} if from_ts is not None: params['from'] = from_ts * 1000000 if to_ts is not None: params['to'] = to_ts * 1000000 if state is not None: params['state'] = state if resolved is not None: params['resolved'] = resolved res = requests.get(self.url + '/api/notifications', headers=self.hdrs, params=params, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, res.json()]
[ "**", "Description", "**", "Returns", "the", "list", "of", "Sysdig", "Monitor", "alert", "notifications", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L36-L69
[ "def", "get_notifications", "(", "self", ",", "from_ts", ",", "to_ts", ",", "state", "=", "None", ",", "resolved", "=", "None", ")", ":", "params", "=", "{", "}", "if", "from_ts", "is", "not", "None", ":", "params", "[", "'from'", "]", "=", "from_ts", "*", "1000000", "if", "to_ts", "is", "not", "None", ":", "params", "[", "'to'", "]", "=", "to_ts", "*", "1000000", "if", "state", "is", "not", "None", ":", "params", "[", "'state'", "]", "=", "state", "if", "resolved", "is", "not", "None", ":", "params", "[", "'resolved'", "]", "=", "resolved", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/notifications'", ",", "headers", "=", "self", ".", "hdrs", ",", "params", "=", "params", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "return", "[", "True", ",", "res", ".", "json", "(", ")", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.update_notification_resolution
**Description** Updates the resolution status of an alert notification. **Arguments** - **notification**: notification object as returned by :func:`~SdcClient.get_notifications`. - **resolved**: new resolution status. Supported values are ``True`` and ``False``. **Success Return Value** The updated notification. **Example** `examples/resolve_alert_notifications.py <https://github.com/draios/python-sdc-client/blob/master/examples/resolve_alert_notifications.py>`_
sdcclient/_monitor.py
def update_notification_resolution(self, notification, resolved): '''**Description** Updates the resolution status of an alert notification. **Arguments** - **notification**: notification object as returned by :func:`~SdcClient.get_notifications`. - **resolved**: new resolution status. Supported values are ``True`` and ``False``. **Success Return Value** The updated notification. **Example** `examples/resolve_alert_notifications.py <https://github.com/draios/python-sdc-client/blob/master/examples/resolve_alert_notifications.py>`_ ''' if 'id' not in notification: return [False, 'Invalid notification format'] notification['resolved'] = resolved data = {'notification': notification} res = requests.put(self.url + '/api/notifications/' + str(notification['id']), headers=self.hdrs, data=json.dumps(data), verify=self.ssl_verify) return self._request_result(res)
def update_notification_resolution(self, notification, resolved): '''**Description** Updates the resolution status of an alert notification. **Arguments** - **notification**: notification object as returned by :func:`~SdcClient.get_notifications`. - **resolved**: new resolution status. Supported values are ``True`` and ``False``. **Success Return Value** The updated notification. **Example** `examples/resolve_alert_notifications.py <https://github.com/draios/python-sdc-client/blob/master/examples/resolve_alert_notifications.py>`_ ''' if 'id' not in notification: return [False, 'Invalid notification format'] notification['resolved'] = resolved data = {'notification': notification} res = requests.put(self.url + '/api/notifications/' + str(notification['id']), headers=self.hdrs, data=json.dumps(data), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Updates", "the", "resolution", "status", "of", "an", "alert", "notification", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L71-L92
[ "def", "update_notification_resolution", "(", "self", ",", "notification", ",", "resolved", ")", ":", "if", "'id'", "not", "in", "notification", ":", "return", "[", "False", ",", "'Invalid notification format'", "]", "notification", "[", "'resolved'", "]", "=", "resolved", "data", "=", "{", "'notification'", ":", "notification", "}", "res", "=", "requests", ".", "put", "(", "self", ".", "url", "+", "'/api/notifications/'", "+", "str", "(", "notification", "[", "'id'", "]", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.create_alert
**Description** Create a threshold-based alert. **Arguments** - **name**: the alert name. This will appear in the Sysdig Monitor UI and in notification emails. - **description**: the alert description. This will appear in the Sysdig Monitor UI and in notification emails. - **severity**: syslog-encoded alert severity. This is a number from 0 to 7 where 0 means 'emergency' and 7 is 'debug'. - **for_atleast_s**: the number of consecutive seconds the condition must be satisfied for the alert to fire. - **condition**: the alert condition, as described here https://app.sysdigcloud.com/apidocs/#!/Alerts/post_api_alerts - **segmentby**: a list of Sysdig Monitor segmentation criteria that can be used to apply the alert to multiple entities. For example, segmenting a CPU alert by ['host.mac', 'proc.name'] allows to apply it to any process in any machine. - **segment_condition**: When *segmentby* is specified (and therefore the alert will cover multiple entities) this field is used to determine when it will fire. In particular, you have two options for *segment_condition*: **ANY** (the alert will fire when at least one of the monitored entities satisfies the condition) and **ALL** (the alert will fire when all of the monitored entities satisfy the condition). - **user_filter**: a boolean expression combining Sysdig Monitor segmentation criteria that makes it possible to reduce the scope of the alert. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **notify**: the type of notification you want this alert to generate. Options are *EMAIL*, *SNS*, *PAGER_DUTY*, *SYSDIG_DUMP*. - **enabled**: if True, the alert will be enabled when created. - **annotations**: an optional dictionary of custom properties that you can associate to this alert for automation or management reasons - **alert_obj**: an optional fully-formed Alert object of the format returned in an "alerts" list by :func:`~SdcClient.get_alerts` This is an alternative to creating the Alert using the individual parameters listed above. **Success Return Value** A dictionary describing the just created alert, with the format described at `this link <https://app.sysdigcloud.com/apidocs/#!/Alerts/post_api_alerts>`__ **Example** `examples/create_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_alert.py>`_
sdcclient/_monitor.py
def create_alert(self, name=None, description=None, severity=None, for_atleast_s=None, condition=None, segmentby=[], segment_condition='ANY', user_filter='', notify=None, enabled=True, annotations={}, alert_obj=None): '''**Description** Create a threshold-based alert. **Arguments** - **name**: the alert name. This will appear in the Sysdig Monitor UI and in notification emails. - **description**: the alert description. This will appear in the Sysdig Monitor UI and in notification emails. - **severity**: syslog-encoded alert severity. This is a number from 0 to 7 where 0 means 'emergency' and 7 is 'debug'. - **for_atleast_s**: the number of consecutive seconds the condition must be satisfied for the alert to fire. - **condition**: the alert condition, as described here https://app.sysdigcloud.com/apidocs/#!/Alerts/post_api_alerts - **segmentby**: a list of Sysdig Monitor segmentation criteria that can be used to apply the alert to multiple entities. For example, segmenting a CPU alert by ['host.mac', 'proc.name'] allows to apply it to any process in any machine. - **segment_condition**: When *segmentby* is specified (and therefore the alert will cover multiple entities) this field is used to determine when it will fire. In particular, you have two options for *segment_condition*: **ANY** (the alert will fire when at least one of the monitored entities satisfies the condition) and **ALL** (the alert will fire when all of the monitored entities satisfy the condition). - **user_filter**: a boolean expression combining Sysdig Monitor segmentation criteria that makes it possible to reduce the scope of the alert. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **notify**: the type of notification you want this alert to generate. Options are *EMAIL*, *SNS*, *PAGER_DUTY*, *SYSDIG_DUMP*. - **enabled**: if True, the alert will be enabled when created. - **annotations**: an optional dictionary of custom properties that you can associate to this alert for automation or management reasons - **alert_obj**: an optional fully-formed Alert object of the format returned in an "alerts" list by :func:`~SdcClient.get_alerts` This is an alternative to creating the Alert using the individual parameters listed above. **Success Return Value** A dictionary describing the just created alert, with the format described at `this link <https://app.sysdigcloud.com/apidocs/#!/Alerts/post_api_alerts>`__ **Example** `examples/create_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_alert.py>`_ ''' # # Get the list of alerts from the server # res = requests.get(self.url + '/api/alerts', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] res.json() if alert_obj is None: if None in (name, description, severity, for_atleast_s, condition): return [False, 'Must specify a full Alert object or all parameters: name, description, severity, for_atleast_s, condition'] else: # # Populate the alert information # alert_json = { 'alert': { 'type': 'MANUAL', 'name': name, 'description': description, 'enabled': enabled, 'severity': severity, 'timespan': for_atleast_s * 1000000, 'condition': condition, 'filter': user_filter } } if segmentby != None and segmentby != []: alert_json['alert']['segmentBy'] = segmentby alert_json['alert']['segmentCondition'] = {'type': segment_condition} if annotations != None and annotations != {}: alert_json['alert']['annotations'] = annotations if notify != None: alert_json['alert']['notificationChannelIds'] = notify else: # The REST API enforces "Alert ID and version must be null", so remove them if present, # since these would have been there in a dump from the list_alerts.py example. alert_obj.pop('id', None) alert_obj.pop('version', None) alert_json = { 'alert': alert_obj } # # Create the new alert # res = requests.post(self.url + '/api/alerts', headers=self.hdrs, data=json.dumps(alert_json), verify=self.ssl_verify) return self._request_result(res)
def create_alert(self, name=None, description=None, severity=None, for_atleast_s=None, condition=None, segmentby=[], segment_condition='ANY', user_filter='', notify=None, enabled=True, annotations={}, alert_obj=None): '''**Description** Create a threshold-based alert. **Arguments** - **name**: the alert name. This will appear in the Sysdig Monitor UI and in notification emails. - **description**: the alert description. This will appear in the Sysdig Monitor UI and in notification emails. - **severity**: syslog-encoded alert severity. This is a number from 0 to 7 where 0 means 'emergency' and 7 is 'debug'. - **for_atleast_s**: the number of consecutive seconds the condition must be satisfied for the alert to fire. - **condition**: the alert condition, as described here https://app.sysdigcloud.com/apidocs/#!/Alerts/post_api_alerts - **segmentby**: a list of Sysdig Monitor segmentation criteria that can be used to apply the alert to multiple entities. For example, segmenting a CPU alert by ['host.mac', 'proc.name'] allows to apply it to any process in any machine. - **segment_condition**: When *segmentby* is specified (and therefore the alert will cover multiple entities) this field is used to determine when it will fire. In particular, you have two options for *segment_condition*: **ANY** (the alert will fire when at least one of the monitored entities satisfies the condition) and **ALL** (the alert will fire when all of the monitored entities satisfy the condition). - **user_filter**: a boolean expression combining Sysdig Monitor segmentation criteria that makes it possible to reduce the scope of the alert. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **notify**: the type of notification you want this alert to generate. Options are *EMAIL*, *SNS*, *PAGER_DUTY*, *SYSDIG_DUMP*. - **enabled**: if True, the alert will be enabled when created. - **annotations**: an optional dictionary of custom properties that you can associate to this alert for automation or management reasons - **alert_obj**: an optional fully-formed Alert object of the format returned in an "alerts" list by :func:`~SdcClient.get_alerts` This is an alternative to creating the Alert using the individual parameters listed above. **Success Return Value** A dictionary describing the just created alert, with the format described at `this link <https://app.sysdigcloud.com/apidocs/#!/Alerts/post_api_alerts>`__ **Example** `examples/create_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_alert.py>`_ ''' # # Get the list of alerts from the server # res = requests.get(self.url + '/api/alerts', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] res.json() if alert_obj is None: if None in (name, description, severity, for_atleast_s, condition): return [False, 'Must specify a full Alert object or all parameters: name, description, severity, for_atleast_s, condition'] else: # # Populate the alert information # alert_json = { 'alert': { 'type': 'MANUAL', 'name': name, 'description': description, 'enabled': enabled, 'severity': severity, 'timespan': for_atleast_s * 1000000, 'condition': condition, 'filter': user_filter } } if segmentby != None and segmentby != []: alert_json['alert']['segmentBy'] = segmentby alert_json['alert']['segmentCondition'] = {'type': segment_condition} if annotations != None and annotations != {}: alert_json['alert']['annotations'] = annotations if notify != None: alert_json['alert']['notificationChannelIds'] = notify else: # The REST API enforces "Alert ID and version must be null", so remove them if present, # since these would have been there in a dump from the list_alerts.py example. alert_obj.pop('id', None) alert_obj.pop('version', None) alert_json = { 'alert': alert_obj } # # Create the new alert # res = requests.post(self.url + '/api/alerts', headers=self.hdrs, data=json.dumps(alert_json), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Create", "a", "threshold", "-", "based", "alert", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L94-L170
[ "def", "create_alert", "(", "self", ",", "name", "=", "None", ",", "description", "=", "None", ",", "severity", "=", "None", ",", "for_atleast_s", "=", "None", ",", "condition", "=", "None", ",", "segmentby", "=", "[", "]", ",", "segment_condition", "=", "'ANY'", ",", "user_filter", "=", "''", ",", "notify", "=", "None", ",", "enabled", "=", "True", ",", "annotations", "=", "{", "}", ",", "alert_obj", "=", "None", ")", ":", "#", "# Get the list of alerts from the server", "#", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/alerts'", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "res", ".", "json", "(", ")", "if", "alert_obj", "is", "None", ":", "if", "None", "in", "(", "name", ",", "description", ",", "severity", ",", "for_atleast_s", ",", "condition", ")", ":", "return", "[", "False", ",", "'Must specify a full Alert object or all parameters: name, description, severity, for_atleast_s, condition'", "]", "else", ":", "#", "# Populate the alert information", "#", "alert_json", "=", "{", "'alert'", ":", "{", "'type'", ":", "'MANUAL'", ",", "'name'", ":", "name", ",", "'description'", ":", "description", ",", "'enabled'", ":", "enabled", ",", "'severity'", ":", "severity", ",", "'timespan'", ":", "for_atleast_s", "*", "1000000", ",", "'condition'", ":", "condition", ",", "'filter'", ":", "user_filter", "}", "}", "if", "segmentby", "!=", "None", "and", "segmentby", "!=", "[", "]", ":", "alert_json", "[", "'alert'", "]", "[", "'segmentBy'", "]", "=", "segmentby", "alert_json", "[", "'alert'", "]", "[", "'segmentCondition'", "]", "=", "{", "'type'", ":", "segment_condition", "}", "if", "annotations", "!=", "None", "and", "annotations", "!=", "{", "}", ":", "alert_json", "[", "'alert'", "]", "[", "'annotations'", "]", "=", "annotations", "if", "notify", "!=", "None", ":", "alert_json", "[", "'alert'", "]", "[", "'notificationChannelIds'", "]", "=", "notify", "else", ":", "# The REST API enforces \"Alert ID and version must be null\", so remove them if present,", "# since these would have been there in a dump from the list_alerts.py example.", "alert_obj", ".", "pop", "(", "'id'", ",", "None", ")", "alert_obj", ".", "pop", "(", "'version'", ",", "None", ")", "alert_json", "=", "{", "'alert'", ":", "alert_obj", "}", "#", "# Create the new alert", "#", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/alerts'", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "alert_json", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.update_alert
**Description** Update a modified threshold-based alert. **Arguments** - **alert**: one modified alert object of the same format as those in the list returned by :func:`~SdcClient.get_alerts`. **Success Return Value** The updated alert. **Example** `examples/update_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/update_alert.py>`_
sdcclient/_monitor.py
def update_alert(self, alert): '''**Description** Update a modified threshold-based alert. **Arguments** - **alert**: one modified alert object of the same format as those in the list returned by :func:`~SdcClient.get_alerts`. **Success Return Value** The updated alert. **Example** `examples/update_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/update_alert.py>`_ ''' if 'id' not in alert: return [False, "Invalid alert format"] res = requests.put(self.url + '/api/alerts/' + str(alert['id']), headers=self.hdrs, data=json.dumps({"alert": alert}), verify=self.ssl_verify) return self._request_result(res)
def update_alert(self, alert): '''**Description** Update a modified threshold-based alert. **Arguments** - **alert**: one modified alert object of the same format as those in the list returned by :func:`~SdcClient.get_alerts`. **Success Return Value** The updated alert. **Example** `examples/update_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/update_alert.py>`_ ''' if 'id' not in alert: return [False, "Invalid alert format"] res = requests.put(self.url + '/api/alerts/' + str(alert['id']), headers=self.hdrs, data=json.dumps({"alert": alert}), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Update", "a", "modified", "threshold", "-", "based", "alert", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L172-L189
[ "def", "update_alert", "(", "self", ",", "alert", ")", ":", "if", "'id'", "not", "in", "alert", ":", "return", "[", "False", ",", "\"Invalid alert format\"", "]", "res", "=", "requests", ".", "put", "(", "self", ".", "url", "+", "'/api/alerts/'", "+", "str", "(", "alert", "[", "'id'", "]", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "{", "\"alert\"", ":", "alert", "}", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.delete_alert
**Description** Deletes an alert. **Arguments** - **alert**: the alert dictionary as returned by :func:`~SdcClient.get_alerts`. **Success Return Value** ``None``. **Example** `examples/delete_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_alert.py>`_
sdcclient/_monitor.py
def delete_alert(self, alert): '''**Description** Deletes an alert. **Arguments** - **alert**: the alert dictionary as returned by :func:`~SdcClient.get_alerts`. **Success Return Value** ``None``. **Example** `examples/delete_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_alert.py>`_ ''' if 'id' not in alert: return [False, 'Invalid alert format'] res = requests.delete(self.url + '/api/alerts/' + str(alert['id']), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, None]
def delete_alert(self, alert): '''**Description** Deletes an alert. **Arguments** - **alert**: the alert dictionary as returned by :func:`~SdcClient.get_alerts`. **Success Return Value** ``None``. **Example** `examples/delete_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_alert.py>`_ ''' if 'id' not in alert: return [False, 'Invalid alert format'] res = requests.delete(self.url + '/api/alerts/' + str(alert['id']), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, None]
[ "**", "Description", "**", "Deletes", "an", "alert", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L191-L211
[ "def", "delete_alert", "(", "self", ",", "alert", ")", ":", "if", "'id'", "not", "in", "alert", ":", "return", "[", "False", ",", "'Invalid alert format'", "]", "res", "=", "requests", ".", "delete", "(", "self", ".", "url", "+", "'/api/alerts/'", "+", "str", "(", "alert", "[", "'id'", "]", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "return", "[", "True", ",", "None", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.get_explore_grouping_hierarchy
**Description** Return the user's current grouping hierarchy as visible in the Explore tab of Sysdig Monitor. **Success Return Value** A list containing the list of the user's Explore grouping criteria. **Example** `examples/print_explore_grouping.py <https://github.com/draios/python-sdc-client/blob/master/examples/print_explore_grouping.py>`_
sdcclient/_monitor.py
def get_explore_grouping_hierarchy(self): '''**Description** Return the user's current grouping hierarchy as visible in the Explore tab of Sysdig Monitor. **Success Return Value** A list containing the list of the user's Explore grouping criteria. **Example** `examples/print_explore_grouping.py <https://github.com/draios/python-sdc-client/blob/master/examples/print_explore_grouping.py>`_ ''' res = requests.get(self.url + '/api/groupConfigurations', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] data = res.json() if 'groupConfigurations' not in data: return [False, 'corrupted groupConfigurations API response'] gconfs = data['groupConfigurations'] for gconf in gconfs: if gconf['id'] == 'explore': res = [] items = gconf['groups'][0]['groupBy'] for item in items: res.append(item['metric']) return [True, res] return [False, 'corrupted groupConfigurations API response, missing "explore" entry']
def get_explore_grouping_hierarchy(self): '''**Description** Return the user's current grouping hierarchy as visible in the Explore tab of Sysdig Monitor. **Success Return Value** A list containing the list of the user's Explore grouping criteria. **Example** `examples/print_explore_grouping.py <https://github.com/draios/python-sdc-client/blob/master/examples/print_explore_grouping.py>`_ ''' res = requests.get(self.url + '/api/groupConfigurations', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] data = res.json() if 'groupConfigurations' not in data: return [False, 'corrupted groupConfigurations API response'] gconfs = data['groupConfigurations'] for gconf in gconfs: if gconf['id'] == 'explore': res = [] items = gconf['groups'][0]['groupBy'] for item in items: res.append(item['metric']) return [True, res] return [False, 'corrupted groupConfigurations API response, missing "explore" entry']
[ "**", "Description", "**", "Return", "the", "user", "s", "current", "grouping", "hierarchy", "as", "visible", "in", "the", "Explore", "tab", "of", "Sysdig", "Monitor", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L213-L244
[ "def", "get_explore_grouping_hierarchy", "(", "self", ")", ":", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/groupConfigurations'", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "data", "=", "res", ".", "json", "(", ")", "if", "'groupConfigurations'", "not", "in", "data", ":", "return", "[", "False", ",", "'corrupted groupConfigurations API response'", "]", "gconfs", "=", "data", "[", "'groupConfigurations'", "]", "for", "gconf", "in", "gconfs", ":", "if", "gconf", "[", "'id'", "]", "==", "'explore'", ":", "res", "=", "[", "]", "items", "=", "gconf", "[", "'groups'", "]", "[", "0", "]", "[", "'groupBy'", "]", "for", "item", "in", "items", ":", "res", ".", "append", "(", "item", "[", "'metric'", "]", ")", "return", "[", "True", ",", "res", "]", "return", "[", "False", ",", "'corrupted groupConfigurations API response, missing \"explore\" entry'", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.set_explore_grouping_hierarchy
**Description** Changes the grouping hierarchy in the Explore panel of the current user. **Arguments** - **new_hierarchy**: a list of sysdig segmentation metrics indicating the new grouping hierarchy.
sdcclient/_monitor.py
def set_explore_grouping_hierarchy(self, new_hierarchy): '''**Description** Changes the grouping hierarchy in the Explore panel of the current user. **Arguments** - **new_hierarchy**: a list of sysdig segmentation metrics indicating the new grouping hierarchy. ''' body = { 'id': 'explore', 'groups': [{'groupBy': []}] } for item in new_hierarchy: body['groups'][0]['groupBy'].append({'metric': item}) res = requests.put(self.url + '/api/groupConfigurations/explore', headers=self.hdrs, data=json.dumps(body), verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] else: return [True, None]
def set_explore_grouping_hierarchy(self, new_hierarchy): '''**Description** Changes the grouping hierarchy in the Explore panel of the current user. **Arguments** - **new_hierarchy**: a list of sysdig segmentation metrics indicating the new grouping hierarchy. ''' body = { 'id': 'explore', 'groups': [{'groupBy': []}] } for item in new_hierarchy: body['groups'][0]['groupBy'].append({'metric': item}) res = requests.put(self.url + '/api/groupConfigurations/explore', headers=self.hdrs, data=json.dumps(body), verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] else: return [True, None]
[ "**", "Description", "**", "Changes", "the", "grouping", "hierarchy", "in", "the", "Explore", "panel", "of", "the", "current", "user", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L246-L266
[ "def", "set_explore_grouping_hierarchy", "(", "self", ",", "new_hierarchy", ")", ":", "body", "=", "{", "'id'", ":", "'explore'", ",", "'groups'", ":", "[", "{", "'groupBy'", ":", "[", "]", "}", "]", "}", "for", "item", "in", "new_hierarchy", ":", "body", "[", "'groups'", "]", "[", "0", "]", "[", "'groupBy'", "]", ".", "append", "(", "{", "'metric'", ":", "item", "}", ")", "res", "=", "requests", ".", "put", "(", "self", ".", "url", "+", "'/api/groupConfigurations/explore'", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "body", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "else", ":", "return", "[", "True", ",", "None", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.get_dashboards
**Description** Return the list of dashboards available under the given user account. This includes the dashboards created by the user and the ones shared with her by other users. **Success Return Value** A dictionary containing the list of available sampling intervals. **Example** `examples/list_dashboards.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_dashboards.py>`_
sdcclient/_monitor.py
def get_dashboards(self): '''**Description** Return the list of dashboards available under the given user account. This includes the dashboards created by the user and the ones shared with her by other users. **Success Return Value** A dictionary containing the list of available sampling intervals. **Example** `examples/list_dashboards.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_dashboards.py>`_ ''' res = requests.get(self.url + self._dashboards_api_endpoint, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def get_dashboards(self): '''**Description** Return the list of dashboards available under the given user account. This includes the dashboards created by the user and the ones shared with her by other users. **Success Return Value** A dictionary containing the list of available sampling intervals. **Example** `examples/list_dashboards.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_dashboards.py>`_ ''' res = requests.get(self.url + self._dashboards_api_endpoint, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Return", "the", "list", "of", "dashboards", "available", "under", "the", "given", "user", "account", ".", "This", "includes", "the", "dashboards", "created", "by", "the", "user", "and", "the", "ones", "shared", "with", "her", "by", "other", "users", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L296-L307
[ "def", "get_dashboards", "(", "self", ")", ":", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "self", ".", "_dashboards_api_endpoint", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.find_dashboard_by
**Description** Finds dashboards with the specified name. You can then delete the dashboard (with :func:`~SdcClient.delete_dashboard`) or edit panels (with :func:`~SdcClient.add_dashboard_panel` and :func:`~SdcClient.remove_dashboard_panel`) **Arguments** - **name**: the name of the dashboards to find. **Success Return Value** A list of dictionaries of dashboards matching the specified name. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_
sdcclient/_monitor.py
def find_dashboard_by(self, name=None): '''**Description** Finds dashboards with the specified name. You can then delete the dashboard (with :func:`~SdcClient.delete_dashboard`) or edit panels (with :func:`~SdcClient.add_dashboard_panel` and :func:`~SdcClient.remove_dashboard_panel`) **Arguments** - **name**: the name of the dashboards to find. **Success Return Value** A list of dictionaries of dashboards matching the specified name. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_ ''' res = self.get_dashboards() if res[0] is False: return res else: def filter_fn(configuration): return configuration['name'] == name def create_item(configuration): return {'dashboard': configuration} dashboards = list(map(create_item, list(filter(filter_fn, res[1]['dashboards'])))) return [True, dashboards]
def find_dashboard_by(self, name=None): '''**Description** Finds dashboards with the specified name. You can then delete the dashboard (with :func:`~SdcClient.delete_dashboard`) or edit panels (with :func:`~SdcClient.add_dashboard_panel` and :func:`~SdcClient.remove_dashboard_panel`) **Arguments** - **name**: the name of the dashboards to find. **Success Return Value** A list of dictionaries of dashboards matching the specified name. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_ ''' res = self.get_dashboards() if res[0] is False: return res else: def filter_fn(configuration): return configuration['name'] == name def create_item(configuration): return {'dashboard': configuration} dashboards = list(map(create_item, list(filter(filter_fn, res[1]['dashboards'])))) return [True, dashboards]
[ "**", "Description", "**", "Finds", "dashboards", "with", "the", "specified", "name", ".", "You", "can", "then", "delete", "the", "dashboard", "(", "with", ":", "func", ":", "~SdcClient", ".", "delete_dashboard", ")", "or", "edit", "panels", "(", "with", ":", "func", ":", "~SdcClient", ".", "add_dashboard_panel", "and", ":", "func", ":", "~SdcClient", ".", "remove_dashboard_panel", ")" ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L309-L333
[ "def", "find_dashboard_by", "(", "self", ",", "name", "=", "None", ")", ":", "res", "=", "self", ".", "get_dashboards", "(", ")", "if", "res", "[", "0", "]", "is", "False", ":", "return", "res", "else", ":", "def", "filter_fn", "(", "configuration", ")", ":", "return", "configuration", "[", "'name'", "]", "==", "name", "def", "create_item", "(", "configuration", ")", ":", "return", "{", "'dashboard'", ":", "configuration", "}", "dashboards", "=", "list", "(", "map", "(", "create_item", ",", "list", "(", "filter", "(", "filter_fn", ",", "res", "[", "1", "]", "[", "'dashboards'", "]", ")", ")", ")", ")", "return", "[", "True", ",", "dashboards", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.remove_dashboard_panel
**Description** Removes a panel from the dashboard. The panel to remove is identified by the specified ``name``. **Arguments** - **name**: name of the panel to find and remove **Success Return Value** A dictionary showing the details of the edited dashboard. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_
sdcclient/_monitor.py
def remove_dashboard_panel(self, dashboard, panel_name): '''**Description** Removes a panel from the dashboard. The panel to remove is identified by the specified ``name``. **Arguments** - **name**: name of the panel to find and remove **Success Return Value** A dictionary showing the details of the edited dashboard. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_ ''' # # Clone existing dashboard... # dashboard_configuration = copy.deepcopy(dashboard) # # ... find the panel # def filter_fn(panel): return panel['name'] == panel_name panels = list(filter(filter_fn, dashboard_configuration['widgets'])) if len(panels) > 0: # # ... and remove it # for panel in panels: dashboard_configuration['widgets'].remove(panel) # # Update dashboard # res = requests.put(self.url + self._dashboards_api_endpoint + '/' + str(dashboard['id']), headers=self.hdrs, data=json.dumps({'dashboard': dashboard_configuration}), verify=self.ssl_verify) return self._request_result(res) else: return [False, 'Not found']
def remove_dashboard_panel(self, dashboard, panel_name): '''**Description** Removes a panel from the dashboard. The panel to remove is identified by the specified ``name``. **Arguments** - **name**: name of the panel to find and remove **Success Return Value** A dictionary showing the details of the edited dashboard. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_ ''' # # Clone existing dashboard... # dashboard_configuration = copy.deepcopy(dashboard) # # ... find the panel # def filter_fn(panel): return panel['name'] == panel_name panels = list(filter(filter_fn, dashboard_configuration['widgets'])) if len(panels) > 0: # # ... and remove it # for panel in panels: dashboard_configuration['widgets'].remove(panel) # # Update dashboard # res = requests.put(self.url + self._dashboards_api_endpoint + '/' + str(dashboard['id']), headers=self.hdrs, data=json.dumps({'dashboard': dashboard_configuration}), verify=self.ssl_verify) return self._request_result(res) else: return [False, 'Not found']
[ "**", "Description", "**", "Removes", "a", "panel", "from", "the", "dashboard", ".", "The", "panel", "to", "remove", "is", "identified", "by", "the", "specified", "name", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L521-L560
[ "def", "remove_dashboard_panel", "(", "self", ",", "dashboard", ",", "panel_name", ")", ":", "#", "# Clone existing dashboard...", "#", "dashboard_configuration", "=", "copy", ".", "deepcopy", "(", "dashboard", ")", "#", "# ... find the panel", "#", "def", "filter_fn", "(", "panel", ")", ":", "return", "panel", "[", "'name'", "]", "==", "panel_name", "panels", "=", "list", "(", "filter", "(", "filter_fn", ",", "dashboard_configuration", "[", "'widgets'", "]", ")", ")", "if", "len", "(", "panels", ")", ">", "0", ":", "#", "# ... and remove it", "#", "for", "panel", "in", "panels", ":", "dashboard_configuration", "[", "'widgets'", "]", ".", "remove", "(", "panel", ")", "#", "# Update dashboard", "#", "res", "=", "requests", ".", "put", "(", "self", ".", "url", "+", "self", ".", "_dashboards_api_endpoint", "+", "'/'", "+", "str", "(", "dashboard", "[", "'id'", "]", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "{", "'dashboard'", ":", "dashboard_configuration", "}", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")", "else", ":", "return", "[", "False", ",", "'Not found'", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.create_dashboard_from_view
**Description** Create a new dasboard using one of the Sysdig Monitor views as a template. You will be able to define the scope of the new dashboard. **Arguments** - **newdashname**: the name of the dashboard that will be created. - **viewname**: the name of the view to use as the template for the new dashboard. This corresponds to the name that the view has in the Explore page. - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria that defines what the new dasboard will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **shared**: if set to True, the new dashboard will be a shared one. - **public**: if set to True, the new dashboard will be shared with public token. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/create_dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_dashboard.py>`_
sdcclient/_monitor.py
def create_dashboard_from_view(self, newdashname, viewname, filter, shared=False, public=False): '''**Description** Create a new dasboard using one of the Sysdig Monitor views as a template. You will be able to define the scope of the new dashboard. **Arguments** - **newdashname**: the name of the dashboard that will be created. - **viewname**: the name of the view to use as the template for the new dashboard. This corresponds to the name that the view has in the Explore page. - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria that defines what the new dasboard will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **shared**: if set to True, the new dashboard will be a shared one. - **public**: if set to True, the new dashboard will be shared with public token. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/create_dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_dashboard.py>`_ ''' # # Find our template view # gvres = self.get_view(viewname) if gvres[0] is False: return gvres view = gvres[1]['defaultDashboard'] view['timeMode'] = {'mode': 1} view['time'] = {'last': 2 * 60 * 60 * 1000000, 'sampling': 2 * 60 * 60 * 1000000} # # Create the new dashboard # return self.create_dashboard_from_template(newdashname, view, filter, shared, public)
def create_dashboard_from_view(self, newdashname, viewname, filter, shared=False, public=False): '''**Description** Create a new dasboard using one of the Sysdig Monitor views as a template. You will be able to define the scope of the new dashboard. **Arguments** - **newdashname**: the name of the dashboard that will be created. - **viewname**: the name of the view to use as the template for the new dashboard. This corresponds to the name that the view has in the Explore page. - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria that defines what the new dasboard will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **shared**: if set to True, the new dashboard will be a shared one. - **public**: if set to True, the new dashboard will be shared with public token. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/create_dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_dashboard.py>`_ ''' # # Find our template view # gvres = self.get_view(viewname) if gvres[0] is False: return gvres view = gvres[1]['defaultDashboard'] view['timeMode'] = {'mode': 1} view['time'] = {'last': 2 * 60 * 60 * 1000000, 'sampling': 2 * 60 * 60 * 1000000} # # Create the new dashboard # return self.create_dashboard_from_template(newdashname, view, filter, shared, public)
[ "**", "Description", "**", "Create", "a", "new", "dasboard", "using", "one", "of", "the", "Sysdig", "Monitor", "views", "as", "a", "template", ".", "You", "will", "be", "able", "to", "define", "the", "scope", "of", "the", "new", "dashboard", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L619-L651
[ "def", "create_dashboard_from_view", "(", "self", ",", "newdashname", ",", "viewname", ",", "filter", ",", "shared", "=", "False", ",", "public", "=", "False", ")", ":", "#", "# Find our template view", "#", "gvres", "=", "self", ".", "get_view", "(", "viewname", ")", "if", "gvres", "[", "0", "]", "is", "False", ":", "return", "gvres", "view", "=", "gvres", "[", "1", "]", "[", "'defaultDashboard'", "]", "view", "[", "'timeMode'", "]", "=", "{", "'mode'", ":", "1", "}", "view", "[", "'time'", "]", "=", "{", "'last'", ":", "2", "*", "60", "*", "60", "*", "1000000", ",", "'sampling'", ":", "2", "*", "60", "*", "60", "*", "1000000", "}", "#", "# Create the new dashboard", "#", "return", "self", ".", "create_dashboard_from_template", "(", "newdashname", ",", "view", ",", "filter", ",", "shared", ",", "public", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.create_dashboard_from_dashboard
**Description** Create a new dasboard using one of the existing dashboards as a template. You will be able to define the scope of the new dasboard. **Arguments** - **newdashname**: the name of the dashboard that will be created. - **viewname**: the name of the dasboard to use as the template, as it appears in the Sysdig Monitor dashboard page. - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria defines what the new dasboard will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **shared**: if set to True, the new dashboard will be a shared one. - **public**: if set to True, the new dashboard will be shared with public token. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/create_dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_dashboard.py>`_
sdcclient/_monitor.py
def create_dashboard_from_dashboard(self, newdashname, templatename, filter, shared=False, public=False): '''**Description** Create a new dasboard using one of the existing dashboards as a template. You will be able to define the scope of the new dasboard. **Arguments** - **newdashname**: the name of the dashboard that will be created. - **viewname**: the name of the dasboard to use as the template, as it appears in the Sysdig Monitor dashboard page. - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria defines what the new dasboard will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **shared**: if set to True, the new dashboard will be a shared one. - **public**: if set to True, the new dashboard will be shared with public token. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/create_dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_dashboard.py>`_ ''' # # Get the list of dashboards from the server # res = requests.get(self.url + self._dashboards_api_endpoint, headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] j = res.json() # # Find our template dashboard # dboard = None for db in j['dashboards']: if db['name'] == templatename: dboard = db break if dboard is None: self.lasterr = 'can\'t find dashboard ' + templatename + ' to use as a template' return [False, self.lasterr] # # Create the dashboard # return self.create_dashboard_from_template(newdashname, dboard, filter, shared, public)
def create_dashboard_from_dashboard(self, newdashname, templatename, filter, shared=False, public=False): '''**Description** Create a new dasboard using one of the existing dashboards as a template. You will be able to define the scope of the new dasboard. **Arguments** - **newdashname**: the name of the dashboard that will be created. - **viewname**: the name of the dasboard to use as the template, as it appears in the Sysdig Monitor dashboard page. - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria defines what the new dasboard will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **shared**: if set to True, the new dashboard will be a shared one. - **public**: if set to True, the new dashboard will be shared with public token. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/create_dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_dashboard.py>`_ ''' # # Get the list of dashboards from the server # res = requests.get(self.url + self._dashboards_api_endpoint, headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] j = res.json() # # Find our template dashboard # dboard = None for db in j['dashboards']: if db['name'] == templatename: dboard = db break if dboard is None: self.lasterr = 'can\'t find dashboard ' + templatename + ' to use as a template' return [False, self.lasterr] # # Create the dashboard # return self.create_dashboard_from_template(newdashname, dboard, filter, shared, public)
[ "**", "Description", "**", "Create", "a", "new", "dasboard", "using", "one", "of", "the", "existing", "dashboards", "as", "a", "template", ".", "You", "will", "be", "able", "to", "define", "the", "scope", "of", "the", "new", "dasboard", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L653-L696
[ "def", "create_dashboard_from_dashboard", "(", "self", ",", "newdashname", ",", "templatename", ",", "filter", ",", "shared", "=", "False", ",", "public", "=", "False", ")", ":", "#", "# Get the list of dashboards from the server", "#", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "self", ".", "_dashboards_api_endpoint", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "j", "=", "res", ".", "json", "(", ")", "#", "# Find our template dashboard", "#", "dboard", "=", "None", "for", "db", "in", "j", "[", "'dashboards'", "]", ":", "if", "db", "[", "'name'", "]", "==", "templatename", ":", "dboard", "=", "db", "break", "if", "dboard", "is", "None", ":", "self", ".", "lasterr", "=", "'can\\'t find dashboard '", "+", "templatename", "+", "' to use as a template'", "return", "[", "False", ",", "self", ".", "lasterr", "]", "#", "# Create the dashboard", "#", "return", "self", ".", "create_dashboard_from_template", "(", "newdashname", ",", "dboard", ",", "filter", ",", "shared", ",", "public", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.create_dashboard_from_file
**Description** Create a new dasboard using a dashboard template saved to disk. See :func:`~SdcClient.save_dashboard_to_file` to use the file to create a dashboard (usefl to create and restore backups). The file can contain the following JSON formats: 1. dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` 2. JSON object with the following properties: * version: dashboards API version (e.g. 'v2') * dashboard: dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` **Arguments** - **dashboard_name**: the name of the dashboard that will be created. - **filename**: name of a file containing a JSON object - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria defines what the new dasboard will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **shared**: if set to True, the new dashboard will be a shared one. - **public**: if set to True, the new dashboard will be shared with public token. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/dashboard_save_load.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard_save_load.py>`_
sdcclient/_monitor.py
def create_dashboard_from_file(self, dashboard_name, filename, filter, shared=False, public=False): ''' **Description** Create a new dasboard using a dashboard template saved to disk. See :func:`~SdcClient.save_dashboard_to_file` to use the file to create a dashboard (usefl to create and restore backups). The file can contain the following JSON formats: 1. dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` 2. JSON object with the following properties: * version: dashboards API version (e.g. 'v2') * dashboard: dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` **Arguments** - **dashboard_name**: the name of the dashboard that will be created. - **filename**: name of a file containing a JSON object - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria defines what the new dasboard will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **shared**: if set to True, the new dashboard will be a shared one. - **public**: if set to True, the new dashboard will be shared with public token. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/dashboard_save_load.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard_save_load.py>`_ ''' # # Load the Dashboard # with open(filename) as data_file: loaded_object = json.load(data_file) # # Handle old files # if 'dashboard' not in loaded_object: loaded_object = { 'version': 'v1', 'dashboard': loaded_object } dashboard = loaded_object['dashboard'] if loaded_object['version'] != self._dashboards_api_version: # # Convert the dashboard (if possible) # conversion_result, dashboard = self._convert_dashboard_to_current_version(dashboard, loaded_object['version']) if conversion_result == False: return conversion_result, dashboard # # Create the new dashboard # return self.create_dashboard_from_template(dashboard_name, dashboard, filter, shared, public)
def create_dashboard_from_file(self, dashboard_name, filename, filter, shared=False, public=False): ''' **Description** Create a new dasboard using a dashboard template saved to disk. See :func:`~SdcClient.save_dashboard_to_file` to use the file to create a dashboard (usefl to create and restore backups). The file can contain the following JSON formats: 1. dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` 2. JSON object with the following properties: * version: dashboards API version (e.g. 'v2') * dashboard: dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` **Arguments** - **dashboard_name**: the name of the dashboard that will be created. - **filename**: name of a file containing a JSON object - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria defines what the new dasboard will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **shared**: if set to True, the new dashboard will be a shared one. - **public**: if set to True, the new dashboard will be shared with public token. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/dashboard_save_load.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard_save_load.py>`_ ''' # # Load the Dashboard # with open(filename) as data_file: loaded_object = json.load(data_file) # # Handle old files # if 'dashboard' not in loaded_object: loaded_object = { 'version': 'v1', 'dashboard': loaded_object } dashboard = loaded_object['dashboard'] if loaded_object['version'] != self._dashboards_api_version: # # Convert the dashboard (if possible) # conversion_result, dashboard = self._convert_dashboard_to_current_version(dashboard, loaded_object['version']) if conversion_result == False: return conversion_result, dashboard # # Create the new dashboard # return self.create_dashboard_from_template(dashboard_name, dashboard, filter, shared, public)
[ "**", "Description", "**", "Create", "a", "new", "dasboard", "using", "a", "dashboard", "template", "saved", "to", "disk", ".", "See", ":", "func", ":", "~SdcClient", ".", "save_dashboard_to_file", "to", "use", "the", "file", "to", "create", "a", "dashboard", "(", "usefl", "to", "create", "and", "restore", "backups", ")", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L698-L751
[ "def", "create_dashboard_from_file", "(", "self", ",", "dashboard_name", ",", "filename", ",", "filter", ",", "shared", "=", "False", ",", "public", "=", "False", ")", ":", "#", "# Load the Dashboard", "#", "with", "open", "(", "filename", ")", "as", "data_file", ":", "loaded_object", "=", "json", ".", "load", "(", "data_file", ")", "#", "# Handle old files", "#", "if", "'dashboard'", "not", "in", "loaded_object", ":", "loaded_object", "=", "{", "'version'", ":", "'v1'", ",", "'dashboard'", ":", "loaded_object", "}", "dashboard", "=", "loaded_object", "[", "'dashboard'", "]", "if", "loaded_object", "[", "'version'", "]", "!=", "self", ".", "_dashboards_api_version", ":", "#", "# Convert the dashboard (if possible)", "#", "conversion_result", ",", "dashboard", "=", "self", ".", "_convert_dashboard_to_current_version", "(", "dashboard", ",", "loaded_object", "[", "'version'", "]", ")", "if", "conversion_result", "==", "False", ":", "return", "conversion_result", ",", "dashboard", "#", "# Create the new dashboard", "#", "return", "self", ".", "create_dashboard_from_template", "(", "dashboard_name", ",", "dashboard", ",", "filter", ",", "shared", ",", "public", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.save_dashboard_to_file
**Description** Save a dashboard to disk. See :func:`~SdcClient.create_dashboard_from_file` to use the file to create a dashboard (usefl to create and restore backups). The file will contain a JSON object with the following properties: * version: dashboards API version (e.g. 'v2') * dashboard: dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` **Arguments** - **dashboard**: dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` - **filename**: name of a file that will contain a JSON object **Example** `examples/dashboard_save_load.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard_save_load.py>`_
sdcclient/_monitor.py
def save_dashboard_to_file(self, dashboard, filename): ''' **Description** Save a dashboard to disk. See :func:`~SdcClient.create_dashboard_from_file` to use the file to create a dashboard (usefl to create and restore backups). The file will contain a JSON object with the following properties: * version: dashboards API version (e.g. 'v2') * dashboard: dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` **Arguments** - **dashboard**: dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` - **filename**: name of a file that will contain a JSON object **Example** `examples/dashboard_save_load.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard_save_load.py>`_ ''' with open(filename, 'w') as outf: json.dump({ 'version': self._dashboards_api_version, 'dashboard': dashboard }, outf)
def save_dashboard_to_file(self, dashboard, filename): ''' **Description** Save a dashboard to disk. See :func:`~SdcClient.create_dashboard_from_file` to use the file to create a dashboard (usefl to create and restore backups). The file will contain a JSON object with the following properties: * version: dashboards API version (e.g. 'v2') * dashboard: dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` **Arguments** - **dashboard**: dashboard object in the format of an array element returned by :func:`~SdcClient.get_dashboards` - **filename**: name of a file that will contain a JSON object **Example** `examples/dashboard_save_load.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard_save_load.py>`_ ''' with open(filename, 'w') as outf: json.dump({ 'version': self._dashboards_api_version, 'dashboard': dashboard }, outf)
[ "**", "Description", "**", "Save", "a", "dashboard", "to", "disk", ".", "See", ":", "func", ":", "~SdcClient", ".", "create_dashboard_from_file", "to", "use", "the", "file", "to", "create", "a", "dashboard", "(", "usefl", "to", "create", "and", "restore", "backups", ")", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L753-L773
[ "def", "save_dashboard_to_file", "(", "self", ",", "dashboard", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "outf", ":", "json", ".", "dump", "(", "{", "'version'", ":", "self", ".", "_dashboards_api_version", ",", "'dashboard'", ":", "dashboard", "}", ",", "outf", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.delete_dashboard
**Description** Deletes a dashboard. **Arguments** - **dashboard**: the dashboard object as returned by :func:`~SdcClient.get_dashboards`. **Success Return Value** `None`. **Example** `examples/delete_dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_dashboard.py>`_
sdcclient/_monitor.py
def delete_dashboard(self, dashboard): '''**Description** Deletes a dashboard. **Arguments** - **dashboard**: the dashboard object as returned by :func:`~SdcClient.get_dashboards`. **Success Return Value** `None`. **Example** `examples/delete_dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_dashboard.py>`_ ''' if 'id' not in dashboard: return [False, "Invalid dashboard format"] res = requests.delete(self.url + self._dashboards_api_endpoint + '/' + str(dashboard['id']), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, None]
def delete_dashboard(self, dashboard): '''**Description** Deletes a dashboard. **Arguments** - **dashboard**: the dashboard object as returned by :func:`~SdcClient.get_dashboards`. **Success Return Value** `None`. **Example** `examples/delete_dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_dashboard.py>`_ ''' if 'id' not in dashboard: return [False, "Invalid dashboard format"] res = requests.delete(self.url + self._dashboards_api_endpoint + '/' + str(dashboard['id']), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, None]
[ "**", "Description", "**", "Deletes", "a", "dashboard", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L775-L795
[ "def", "delete_dashboard", "(", "self", ",", "dashboard", ")", ":", "if", "'id'", "not", "in", "dashboard", ":", "return", "[", "False", ",", "\"Invalid dashboard format\"", "]", "res", "=", "requests", ".", "delete", "(", "self", ".", "url", "+", "self", ".", "_dashboards_api_endpoint", "+", "'/'", "+", "str", "(", "dashboard", "[", "'id'", "]", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "return", "[", "True", ",", "None", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClient.convert_scope_string_to_expression
**Description** Internal function to convert a filter string to a filter object to be used with dashboards.
sdcclient/_monitor.py
def convert_scope_string_to_expression(scope): '''**Description** Internal function to convert a filter string to a filter object to be used with dashboards. ''' # # NOTE: The supported grammar is not perfectly aligned with the grammar supported by the Sysdig backend. # Proper grammar implementation will happen soon. # For practical purposes, the parsing will have equivalent results. # if scope is None or not scope: return [True, []] expressions = [] string_expressions = scope.strip(' \t\n\r').split(' and ') expression_re = re.compile('^(?P<not>not )?(?P<operand>[^ ]+) (?P<operator>=|!=|in|contains|starts with) (?P<value>(:?"[^"]+"|\'[^\']+\'|\(.+\)|.+))$') for string_expression in string_expressions: matches = expression_re.match(string_expression) if matches is None: return [False, 'invalid scope format'] is_not_operator = matches.group('not') is not None if matches.group('operator') == 'in': list_value = matches.group('value').strip(' ()') value_matches = re.findall('(:?\'[^\',]+\')|(:?"[^",]+")|(:?[,]+)', list_value) if len(value_matches) == 0: return [False, 'invalid scope value list format'] value_matches = map(lambda v: v[0] if v[0] else v[1], value_matches) values = map(lambda v: v.strip(' "\''), value_matches) else: values = [matches.group('value').strip('"\'')] operator_parse_dict = { 'in': 'in' if not is_not_operator else 'notIn', '=': 'equals' if not is_not_operator else 'notEquals', '!=': 'notEquals' if not is_not_operator else 'equals', 'contains': 'contains' if not is_not_operator else 'notContains', 'starts with': 'startsWith' } operator = operator_parse_dict.get(matches.group('operator'), None) if operator is None: return [False, 'invalid scope operator'] expressions.append({ 'operand': matches.group('operand'), 'operator': operator, 'value': values }) return [True, expressions]
def convert_scope_string_to_expression(scope): '''**Description** Internal function to convert a filter string to a filter object to be used with dashboards. ''' # # NOTE: The supported grammar is not perfectly aligned with the grammar supported by the Sysdig backend. # Proper grammar implementation will happen soon. # For practical purposes, the parsing will have equivalent results. # if scope is None or not scope: return [True, []] expressions = [] string_expressions = scope.strip(' \t\n\r').split(' and ') expression_re = re.compile('^(?P<not>not )?(?P<operand>[^ ]+) (?P<operator>=|!=|in|contains|starts with) (?P<value>(:?"[^"]+"|\'[^\']+\'|\(.+\)|.+))$') for string_expression in string_expressions: matches = expression_re.match(string_expression) if matches is None: return [False, 'invalid scope format'] is_not_operator = matches.group('not') is not None if matches.group('operator') == 'in': list_value = matches.group('value').strip(' ()') value_matches = re.findall('(:?\'[^\',]+\')|(:?"[^",]+")|(:?[,]+)', list_value) if len(value_matches) == 0: return [False, 'invalid scope value list format'] value_matches = map(lambda v: v[0] if v[0] else v[1], value_matches) values = map(lambda v: v.strip(' "\''), value_matches) else: values = [matches.group('value').strip('"\'')] operator_parse_dict = { 'in': 'in' if not is_not_operator else 'notIn', '=': 'equals' if not is_not_operator else 'notEquals', '!=': 'notEquals' if not is_not_operator else 'equals', 'contains': 'contains' if not is_not_operator else 'notContains', 'starts with': 'startsWith' } operator = operator_parse_dict.get(matches.group('operator'), None) if operator is None: return [False, 'invalid scope operator'] expressions.append({ 'operand': matches.group('operand'), 'operator': operator, 'value': values }) return [True, expressions]
[ "**", "Description", "**", "Internal", "function", "to", "convert", "a", "filter", "string", "to", "a", "filter", "object", "to", "be", "used", "with", "dashboards", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L811-L866
[ "def", "convert_scope_string_to_expression", "(", "scope", ")", ":", "#", "# NOTE: The supported grammar is not perfectly aligned with the grammar supported by the Sysdig backend.", "# Proper grammar implementation will happen soon.", "# For practical purposes, the parsing will have equivalent results.", "#", "if", "scope", "is", "None", "or", "not", "scope", ":", "return", "[", "True", ",", "[", "]", "]", "expressions", "=", "[", "]", "string_expressions", "=", "scope", ".", "strip", "(", "' \\t\\n\\r'", ")", ".", "split", "(", "' and '", ")", "expression_re", "=", "re", ".", "compile", "(", "'^(?P<not>not )?(?P<operand>[^ ]+) (?P<operator>=|!=|in|contains|starts with) (?P<value>(:?\"[^\"]+\"|\\'[^\\']+\\'|\\(.+\\)|.+))$'", ")", "for", "string_expression", "in", "string_expressions", ":", "matches", "=", "expression_re", ".", "match", "(", "string_expression", ")", "if", "matches", "is", "None", ":", "return", "[", "False", ",", "'invalid scope format'", "]", "is_not_operator", "=", "matches", ".", "group", "(", "'not'", ")", "is", "not", "None", "if", "matches", ".", "group", "(", "'operator'", ")", "==", "'in'", ":", "list_value", "=", "matches", ".", "group", "(", "'value'", ")", ".", "strip", "(", "' ()'", ")", "value_matches", "=", "re", ".", "findall", "(", "'(:?\\'[^\\',]+\\')|(:?\"[^\",]+\")|(:?[,]+)'", ",", "list_value", ")", "if", "len", "(", "value_matches", ")", "==", "0", ":", "return", "[", "False", ",", "'invalid scope value list format'", "]", "value_matches", "=", "map", "(", "lambda", "v", ":", "v", "[", "0", "]", "if", "v", "[", "0", "]", "else", "v", "[", "1", "]", ",", "value_matches", ")", "values", "=", "map", "(", "lambda", "v", ":", "v", ".", "strip", "(", "' \"\\''", ")", ",", "value_matches", ")", "else", ":", "values", "=", "[", "matches", ".", "group", "(", "'value'", ")", ".", "strip", "(", "'\"\\''", ")", "]", "operator_parse_dict", "=", "{", "'in'", ":", "'in'", "if", "not", "is_not_operator", "else", "'notIn'", ",", "'='", ":", "'equals'", "if", "not", "is_not_operator", "else", "'notEquals'", ",", "'!='", ":", "'notEquals'", "if", "not", "is_not_operator", "else", "'equals'", ",", "'contains'", ":", "'contains'", "if", "not", "is_not_operator", "else", "'notContains'", ",", "'starts with'", ":", "'startsWith'", "}", "operator", "=", "operator_parse_dict", ".", "get", "(", "matches", ".", "group", "(", "'operator'", ")", ",", "None", ")", "if", "operator", "is", "None", ":", "return", "[", "False", ",", "'invalid scope operator'", "]", "expressions", ".", "append", "(", "{", "'operand'", ":", "matches", ".", "group", "(", "'operand'", ")", ",", "'operator'", ":", "operator", ",", "'value'", ":", "values", "}", ")", "return", "[", "True", ",", "expressions", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.get_notification_ids
**Description** Get an array of all configured Notification Channel IDs, or a filtered subset of them. **Arguments** - **channels**: an optional array of dictionaries to limit the set of Notification Channel IDs returned. If not specified, IDs for all configured Notification Channels are returned. Each dictionary contains a ``type`` field that can be one of the available types of Notification Channel (``EMAIL``, ``SNS``, ``PAGER_DUTY``, ``SLACK``, ``OPSGENIE``, ``VICTOROPS``, ``WEBHOOK``) as well as additional elements specific to each channel type. **Success Return Value** An array of Notification Channel IDs (integers). **Examples** - `examples/create_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_alert.py>`_ - `examples/restore_alerts.py <https://github.com/draios/python-sdc-client/blob/master/examples/restore_alerts.py>`_
sdcclient/_common.py
def get_notification_ids(self, channels=None): '''**Description** Get an array of all configured Notification Channel IDs, or a filtered subset of them. **Arguments** - **channels**: an optional array of dictionaries to limit the set of Notification Channel IDs returned. If not specified, IDs for all configured Notification Channels are returned. Each dictionary contains a ``type`` field that can be one of the available types of Notification Channel (``EMAIL``, ``SNS``, ``PAGER_DUTY``, ``SLACK``, ``OPSGENIE``, ``VICTOROPS``, ``WEBHOOK``) as well as additional elements specific to each channel type. **Success Return Value** An array of Notification Channel IDs (integers). **Examples** - `examples/create_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_alert.py>`_ - `examples/restore_alerts.py <https://github.com/draios/python-sdc-client/blob/master/examples/restore_alerts.py>`_ ''' res = requests.get(self.url + '/api/notificationChannels', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return False, self.lasterr ids = [] # If no array of channel types/names was provided to filter by, # just return them all. if channels is None: for ch in res.json()["notificationChannels"]: ids.append(ch['id']) return [True, ids] # Return the filtered set of channels based on the provided types/names array. # Should try and improve this M * N lookup for c in channels: found = False for ch in res.json()["notificationChannels"]: if c['type'] == ch['type']: if c['type'] == 'SNS': opt = ch['options'] if set(opt['snsTopicARNs']) == set(c['snsTopicARNs']): found = True ids.append(ch['id']) elif c['type'] == 'EMAIL': opt = ch['options'] if 'emailRecipients' in c: if set(c['emailRecipients']) == set(opt['emailRecipients']): found = True ids.append(ch['id']) elif 'name' in c: if c['name'] == ch.get('name'): found = True ids.append(ch['id']) elif c['type'] == 'PAGER_DUTY': opt = ch['options'] if opt['account'] == c['account'] and opt['serviceName'] == c['serviceName']: found = True ids.append(ch['id']) elif c['type'] == 'SLACK': opt = ch['options'] if 'channel' in opt and opt['channel'] == c['channel']: found = True ids.append(ch['id']) elif c['type'] == 'OPSGENIE': if 'name' in c: if c['name'] == ch.get('name'): found = True ids.append(ch['id']) elif c['type'] == 'VICTOROPS': if 'name' in c: if c['name'] == ch.get('name'): found = True ids.append(ch['id']) elif c['type'] == 'WEBHOOK': if 'name' in c: if c['name'] == ch.get('name'): found = True ids.append(ch['id']) if not found: return False, "Channel not found: " + str(c) return True, ids
def get_notification_ids(self, channels=None): '''**Description** Get an array of all configured Notification Channel IDs, or a filtered subset of them. **Arguments** - **channels**: an optional array of dictionaries to limit the set of Notification Channel IDs returned. If not specified, IDs for all configured Notification Channels are returned. Each dictionary contains a ``type`` field that can be one of the available types of Notification Channel (``EMAIL``, ``SNS``, ``PAGER_DUTY``, ``SLACK``, ``OPSGENIE``, ``VICTOROPS``, ``WEBHOOK``) as well as additional elements specific to each channel type. **Success Return Value** An array of Notification Channel IDs (integers). **Examples** - `examples/create_alert.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_alert.py>`_ - `examples/restore_alerts.py <https://github.com/draios/python-sdc-client/blob/master/examples/restore_alerts.py>`_ ''' res = requests.get(self.url + '/api/notificationChannels', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return False, self.lasterr ids = [] # If no array of channel types/names was provided to filter by, # just return them all. if channels is None: for ch in res.json()["notificationChannels"]: ids.append(ch['id']) return [True, ids] # Return the filtered set of channels based on the provided types/names array. # Should try and improve this M * N lookup for c in channels: found = False for ch in res.json()["notificationChannels"]: if c['type'] == ch['type']: if c['type'] == 'SNS': opt = ch['options'] if set(opt['snsTopicARNs']) == set(c['snsTopicARNs']): found = True ids.append(ch['id']) elif c['type'] == 'EMAIL': opt = ch['options'] if 'emailRecipients' in c: if set(c['emailRecipients']) == set(opt['emailRecipients']): found = True ids.append(ch['id']) elif 'name' in c: if c['name'] == ch.get('name'): found = True ids.append(ch['id']) elif c['type'] == 'PAGER_DUTY': opt = ch['options'] if opt['account'] == c['account'] and opt['serviceName'] == c['serviceName']: found = True ids.append(ch['id']) elif c['type'] == 'SLACK': opt = ch['options'] if 'channel' in opt and opt['channel'] == c['channel']: found = True ids.append(ch['id']) elif c['type'] == 'OPSGENIE': if 'name' in c: if c['name'] == ch.get('name'): found = True ids.append(ch['id']) elif c['type'] == 'VICTOROPS': if 'name' in c: if c['name'] == ch.get('name'): found = True ids.append(ch['id']) elif c['type'] == 'WEBHOOK': if 'name' in c: if c['name'] == ch.get('name'): found = True ids.append(ch['id']) if not found: return False, "Channel not found: " + str(c) return True, ids
[ "**", "Description", "**", "Get", "an", "array", "of", "all", "configured", "Notification", "Channel", "IDs", "or", "a", "filtered", "subset", "of", "them", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L126-L204
[ "def", "get_notification_ids", "(", "self", ",", "channels", "=", "None", ")", ":", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/notificationChannels'", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "False", ",", "self", ".", "lasterr", "ids", "=", "[", "]", "# If no array of channel types/names was provided to filter by,", "# just return them all.", "if", "channels", "is", "None", ":", "for", "ch", "in", "res", ".", "json", "(", ")", "[", "\"notificationChannels\"", "]", ":", "ids", ".", "append", "(", "ch", "[", "'id'", "]", ")", "return", "[", "True", ",", "ids", "]", "# Return the filtered set of channels based on the provided types/names array.", "# Should try and improve this M * N lookup", "for", "c", "in", "channels", ":", "found", "=", "False", "for", "ch", "in", "res", ".", "json", "(", ")", "[", "\"notificationChannels\"", "]", ":", "if", "c", "[", "'type'", "]", "==", "ch", "[", "'type'", "]", ":", "if", "c", "[", "'type'", "]", "==", "'SNS'", ":", "opt", "=", "ch", "[", "'options'", "]", "if", "set", "(", "opt", "[", "'snsTopicARNs'", "]", ")", "==", "set", "(", "c", "[", "'snsTopicARNs'", "]", ")", ":", "found", "=", "True", "ids", ".", "append", "(", "ch", "[", "'id'", "]", ")", "elif", "c", "[", "'type'", "]", "==", "'EMAIL'", ":", "opt", "=", "ch", "[", "'options'", "]", "if", "'emailRecipients'", "in", "c", ":", "if", "set", "(", "c", "[", "'emailRecipients'", "]", ")", "==", "set", "(", "opt", "[", "'emailRecipients'", "]", ")", ":", "found", "=", "True", "ids", ".", "append", "(", "ch", "[", "'id'", "]", ")", "elif", "'name'", "in", "c", ":", "if", "c", "[", "'name'", "]", "==", "ch", ".", "get", "(", "'name'", ")", ":", "found", "=", "True", "ids", ".", "append", "(", "ch", "[", "'id'", "]", ")", "elif", "c", "[", "'type'", "]", "==", "'PAGER_DUTY'", ":", "opt", "=", "ch", "[", "'options'", "]", "if", "opt", "[", "'account'", "]", "==", "c", "[", "'account'", "]", "and", "opt", "[", "'serviceName'", "]", "==", "c", "[", "'serviceName'", "]", ":", "found", "=", "True", "ids", ".", "append", "(", "ch", "[", "'id'", "]", ")", "elif", "c", "[", "'type'", "]", "==", "'SLACK'", ":", "opt", "=", "ch", "[", "'options'", "]", "if", "'channel'", "in", "opt", "and", "opt", "[", "'channel'", "]", "==", "c", "[", "'channel'", "]", ":", "found", "=", "True", "ids", ".", "append", "(", "ch", "[", "'id'", "]", ")", "elif", "c", "[", "'type'", "]", "==", "'OPSGENIE'", ":", "if", "'name'", "in", "c", ":", "if", "c", "[", "'name'", "]", "==", "ch", ".", "get", "(", "'name'", ")", ":", "found", "=", "True", "ids", ".", "append", "(", "ch", "[", "'id'", "]", ")", "elif", "c", "[", "'type'", "]", "==", "'VICTOROPS'", ":", "if", "'name'", "in", "c", ":", "if", "c", "[", "'name'", "]", "==", "ch", ".", "get", "(", "'name'", ")", ":", "found", "=", "True", "ids", ".", "append", "(", "ch", "[", "'id'", "]", ")", "elif", "c", "[", "'type'", "]", "==", "'WEBHOOK'", ":", "if", "'name'", "in", "c", ":", "if", "c", "[", "'name'", "]", "==", "ch", ".", "get", "(", "'name'", ")", ":", "found", "=", "True", "ids", ".", "append", "(", "ch", "[", "'id'", "]", ")", "if", "not", "found", ":", "return", "False", ",", "\"Channel not found: \"", "+", "str", "(", "c", ")", "return", "True", ",", "ids" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.post_event
**Description** Send an event to Sysdig Monitor. The events you post are available in the Events tab in the Sysdig Monitor UI and can be overlied to charts. **Arguments** - **name**: the name of the new event. - **description**: a longer description offering detailed information about the event. - **severity**: syslog style from 0 (high) to 7 (low). - **event_filter**: metadata, in Sysdig Monitor format, of nodes to associate with the event, e.g. ``host.hostName = 'ip-10-1-1-1' and container.name = 'foo'``. - **tags**: a list of key-value dictionaries that can be used to tag the event. Can be used for filtering/segmenting purposes in Sysdig Monitor. **Success Return Value** A dictionary describing the new event. **Examples** - `examples/post_event_simple.py <https://github.com/draios/python-sdc-client/blob/master/examples/post_event_simple.py>`_ - `examples/post_event.py <https://github.com/draios/python-sdc-client/blob/master/examples/post_event.py>`_
sdcclient/_common.py
def post_event(self, name, description=None, severity=None, event_filter=None, tags=None): '''**Description** Send an event to Sysdig Monitor. The events you post are available in the Events tab in the Sysdig Monitor UI and can be overlied to charts. **Arguments** - **name**: the name of the new event. - **description**: a longer description offering detailed information about the event. - **severity**: syslog style from 0 (high) to 7 (low). - **event_filter**: metadata, in Sysdig Monitor format, of nodes to associate with the event, e.g. ``host.hostName = 'ip-10-1-1-1' and container.name = 'foo'``. - **tags**: a list of key-value dictionaries that can be used to tag the event. Can be used for filtering/segmenting purposes in Sysdig Monitor. **Success Return Value** A dictionary describing the new event. **Examples** - `examples/post_event_simple.py <https://github.com/draios/python-sdc-client/blob/master/examples/post_event_simple.py>`_ - `examples/post_event.py <https://github.com/draios/python-sdc-client/blob/master/examples/post_event.py>`_ ''' options = { 'name': name, 'description': description, 'severity': severity, 'filter': event_filter, 'tags': tags } edata = { 'event': {k: v for k, v in options.items() if v is not None} } res = requests.post(self.url + '/api/events/', headers=self.hdrs, data=json.dumps(edata), verify=self.ssl_verify) return self._request_result(res)
def post_event(self, name, description=None, severity=None, event_filter=None, tags=None): '''**Description** Send an event to Sysdig Monitor. The events you post are available in the Events tab in the Sysdig Monitor UI and can be overlied to charts. **Arguments** - **name**: the name of the new event. - **description**: a longer description offering detailed information about the event. - **severity**: syslog style from 0 (high) to 7 (low). - **event_filter**: metadata, in Sysdig Monitor format, of nodes to associate with the event, e.g. ``host.hostName = 'ip-10-1-1-1' and container.name = 'foo'``. - **tags**: a list of key-value dictionaries that can be used to tag the event. Can be used for filtering/segmenting purposes in Sysdig Monitor. **Success Return Value** A dictionary describing the new event. **Examples** - `examples/post_event_simple.py <https://github.com/draios/python-sdc-client/blob/master/examples/post_event_simple.py>`_ - `examples/post_event.py <https://github.com/draios/python-sdc-client/blob/master/examples/post_event.py>`_ ''' options = { 'name': name, 'description': description, 'severity': severity, 'filter': event_filter, 'tags': tags } edata = { 'event': {k: v for k, v in options.items() if v is not None} } res = requests.post(self.url + '/api/events/', headers=self.hdrs, data=json.dumps(edata), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Send", "an", "event", "to", "Sysdig", "Monitor", ".", "The", "events", "you", "post", "are", "available", "in", "the", "Events", "tab", "in", "the", "Sysdig", "Monitor", "UI", "and", "can", "be", "overlied", "to", "charts", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L350-L379
[ "def", "post_event", "(", "self", ",", "name", ",", "description", "=", "None", ",", "severity", "=", "None", ",", "event_filter", "=", "None", ",", "tags", "=", "None", ")", ":", "options", "=", "{", "'name'", ":", "name", ",", "'description'", ":", "description", ",", "'severity'", ":", "severity", ",", "'filter'", ":", "event_filter", ",", "'tags'", ":", "tags", "}", "edata", "=", "{", "'event'", ":", "{", "k", ":", "v", "for", "k", ",", "v", "in", "options", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "}", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/events/'", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "edata", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.get_events
**Description** Returns the list of Sysdig Monitor events. **Arguments** - **name**: filter events by name. - **from_ts**: filter events by start time. Timestamp format is in UTC (seconds). - **to_ts**: filter events by end time. Timestamp format is in UTC (seconds). - **tags**: filter events by tags. Can be, for example ``tag1 = 'value1'``. **Success Return Value** A dictionary containing the list of events. **Example** `examples/list_events.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_events.py>`_
sdcclient/_common.py
def get_events(self, name=None, from_ts=None, to_ts=None, tags=None): '''**Description** Returns the list of Sysdig Monitor events. **Arguments** - **name**: filter events by name. - **from_ts**: filter events by start time. Timestamp format is in UTC (seconds). - **to_ts**: filter events by end time. Timestamp format is in UTC (seconds). - **tags**: filter events by tags. Can be, for example ``tag1 = 'value1'``. **Success Return Value** A dictionary containing the list of events. **Example** `examples/list_events.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_events.py>`_ ''' options = { 'name': name, 'from': from_ts, 'to': to_ts, 'tags': tags } params = {k: v for k, v in options.items() if v is not None} res = requests.get(self.url + '/api/events/', headers=self.hdrs, params=params, verify=self.ssl_verify) return self._request_result(res)
def get_events(self, name=None, from_ts=None, to_ts=None, tags=None): '''**Description** Returns the list of Sysdig Monitor events. **Arguments** - **name**: filter events by name. - **from_ts**: filter events by start time. Timestamp format is in UTC (seconds). - **to_ts**: filter events by end time. Timestamp format is in UTC (seconds). - **tags**: filter events by tags. Can be, for example ``tag1 = 'value1'``. **Success Return Value** A dictionary containing the list of events. **Example** `examples/list_events.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_events.py>`_ ''' options = { 'name': name, 'from': from_ts, 'to': to_ts, 'tags': tags } params = {k: v for k, v in options.items() if v is not None} res = requests.get(self.url + '/api/events/', headers=self.hdrs, params=params, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Returns", "the", "list", "of", "Sysdig", "Monitor", "events", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L381-L405
[ "def", "get_events", "(", "self", ",", "name", "=", "None", ",", "from_ts", "=", "None", ",", "to_ts", "=", "None", ",", "tags", "=", "None", ")", ":", "options", "=", "{", "'name'", ":", "name", ",", "'from'", ":", "from_ts", ",", "'to'", ":", "to_ts", ",", "'tags'", ":", "tags", "}", "params", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "options", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/events/'", ",", "headers", "=", "self", ".", "hdrs", ",", "params", "=", "params", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.delete_event
**Description** Deletes an event. **Arguments** - **event**: the event object as returned by :func:`~SdcClient.get_events`. **Success Return Value** `None`. **Example** `examples/delete_event.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_event.py>`_
sdcclient/_common.py
def delete_event(self, event): '''**Description** Deletes an event. **Arguments** - **event**: the event object as returned by :func:`~SdcClient.get_events`. **Success Return Value** `None`. **Example** `examples/delete_event.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_event.py>`_ ''' if 'id' not in event: return [False, "Invalid event format"] res = requests.delete(self.url + '/api/events/' + str(event['id']), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, None]
def delete_event(self, event): '''**Description** Deletes an event. **Arguments** - **event**: the event object as returned by :func:`~SdcClient.get_events`. **Success Return Value** `None`. **Example** `examples/delete_event.py <https://github.com/draios/python-sdc-client/blob/master/examples/delete_event.py>`_ ''' if 'id' not in event: return [False, "Invalid event format"] res = requests.delete(self.url + '/api/events/' + str(event['id']), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, None]
[ "**", "Description", "**", "Deletes", "an", "event", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L407-L426
[ "def", "delete_event", "(", "self", ",", "event", ")", ":", "if", "'id'", "not", "in", "event", ":", "return", "[", "False", ",", "\"Invalid event format\"", "]", "res", "=", "requests", ".", "delete", "(", "self", ".", "url", "+", "'/api/events/'", "+", "str", "(", "event", "[", "'id'", "]", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "return", "[", "True", ",", "None", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.get_data
**Description** Export metric data (both time-series and table-based). **Arguments** - **metrics**: a list of dictionaries, specifying the metrics and grouping keys that the query will return. A metric is any of the entries that can be found in the *Metrics* section of the Explore page in Sysdig Monitor. Metric entries require an *aggregations* section specifying how to aggregate the metric across time and containers/hosts. A grouping key is any of the entries that can be found in the *Show* or *Segment By* sections of the Explore page in Sysdig Monitor. These entries are used to apply single or hierarchical segmentation to the returned data and don't require the aggregations section. Refer to the Example link below for ready-to-use code snippets. - **start_ts**: the UTC time (in seconds) of the beginning of the data window. A negative value can be optionally used to indicate a relative time in the past from now. For example, -3600 means "one hour ago". - **end_ts**: the UTC time (in seconds) of the end of the data window, or 0 to indicate "now". A negative value can also be optionally used to indicate a relative time in the past from now. For example, -3600 means "one hour ago". - **sampling_s**: the duration of the samples that will be returned. 0 means that the whole data will be returned as a single sample. - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria that defines what the query will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **datasource_type**: specify the metric source for the request, can be ``container`` or ``host``. Most metrics, for example ``cpu.used.percent`` or ``memory.bytes.used``, are reported by both hosts and containers. By default, host metrics are used, but if the request contains a container-specific grouping key in the metric list/filter (e.g. ``container.name``), then the container source is used. In cases where grouping keys are missing or apply to both hosts and containers (e.g. ``tag.Name``), *datasource_type* can be explicitly set to avoid any ambiguity and allow the user to select precisely what kind of data should be used for the request. `examples/get_data_datasource.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_datasource.py>`_ contains a few examples that should clarify the use of this argument. - **paging**: if segmentation of the query generates values for several different entities (e.g. containers/hosts), this parameter specifies which to include in the returned result. It's specified as a dictionary of inclusive values for ``from`` and ``to`` with the default being ``{ "from": 0, "to": 9 }``, which will return values for the "top 10" entities. The meaning of "top" is query-dependent, based on points having been sorted via the specified group aggregation, with the results sorted in ascending order if the group aggregation is ``min`` or ``none``, and descending order otherwise. **Success Return Value** A dictionary with the requested data. Data is organized in a list of time samples, each of which includes a UTC timestamp and a list of values, whose content and order reflect what was specified in the *metrics* argument. **Examples** - `examples/get_data_simple.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_simple.py>`_ - `examples/get_data_advanced.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_advanced.py>`_ - `examples/list_hosts.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_hosts.py>`_ - `examples/get_data_datasource.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_datasource.py>`_
sdcclient/_common.py
def get_data(self, metrics, start_ts, end_ts=0, sampling_s=0, filter='', datasource_type='host', paging=None): '''**Description** Export metric data (both time-series and table-based). **Arguments** - **metrics**: a list of dictionaries, specifying the metrics and grouping keys that the query will return. A metric is any of the entries that can be found in the *Metrics* section of the Explore page in Sysdig Monitor. Metric entries require an *aggregations* section specifying how to aggregate the metric across time and containers/hosts. A grouping key is any of the entries that can be found in the *Show* or *Segment By* sections of the Explore page in Sysdig Monitor. These entries are used to apply single or hierarchical segmentation to the returned data and don't require the aggregations section. Refer to the Example link below for ready-to-use code snippets. - **start_ts**: the UTC time (in seconds) of the beginning of the data window. A negative value can be optionally used to indicate a relative time in the past from now. For example, -3600 means "one hour ago". - **end_ts**: the UTC time (in seconds) of the end of the data window, or 0 to indicate "now". A negative value can also be optionally used to indicate a relative time in the past from now. For example, -3600 means "one hour ago". - **sampling_s**: the duration of the samples that will be returned. 0 means that the whole data will be returned as a single sample. - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria that defines what the query will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **datasource_type**: specify the metric source for the request, can be ``container`` or ``host``. Most metrics, for example ``cpu.used.percent`` or ``memory.bytes.used``, are reported by both hosts and containers. By default, host metrics are used, but if the request contains a container-specific grouping key in the metric list/filter (e.g. ``container.name``), then the container source is used. In cases where grouping keys are missing or apply to both hosts and containers (e.g. ``tag.Name``), *datasource_type* can be explicitly set to avoid any ambiguity and allow the user to select precisely what kind of data should be used for the request. `examples/get_data_datasource.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_datasource.py>`_ contains a few examples that should clarify the use of this argument. - **paging**: if segmentation of the query generates values for several different entities (e.g. containers/hosts), this parameter specifies which to include in the returned result. It's specified as a dictionary of inclusive values for ``from`` and ``to`` with the default being ``{ "from": 0, "to": 9 }``, which will return values for the "top 10" entities. The meaning of "top" is query-dependent, based on points having been sorted via the specified group aggregation, with the results sorted in ascending order if the group aggregation is ``min`` or ``none``, and descending order otherwise. **Success Return Value** A dictionary with the requested data. Data is organized in a list of time samples, each of which includes a UTC timestamp and a list of values, whose content and order reflect what was specified in the *metrics* argument. **Examples** - `examples/get_data_simple.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_simple.py>`_ - `examples/get_data_advanced.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_advanced.py>`_ - `examples/list_hosts.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_hosts.py>`_ - `examples/get_data_datasource.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_datasource.py>`_ ''' reqbody = { 'metrics': metrics, 'dataSourceType': datasource_type, } if start_ts < 0: reqbody['last'] = -start_ts elif start_ts == 0: return [False, "start_ts cannot be 0"] else: reqbody['start'] = start_ts reqbody['end'] = end_ts if filter != '': reqbody['filter'] = filter if paging is not None: reqbody['paging'] = paging if sampling_s != 0: reqbody['sampling'] = sampling_s res = requests.post(self.url + '/api/data/', headers=self.hdrs, data=json.dumps(reqbody), verify=self.ssl_verify) return self._request_result(res)
def get_data(self, metrics, start_ts, end_ts=0, sampling_s=0, filter='', datasource_type='host', paging=None): '''**Description** Export metric data (both time-series and table-based). **Arguments** - **metrics**: a list of dictionaries, specifying the metrics and grouping keys that the query will return. A metric is any of the entries that can be found in the *Metrics* section of the Explore page in Sysdig Monitor. Metric entries require an *aggregations* section specifying how to aggregate the metric across time and containers/hosts. A grouping key is any of the entries that can be found in the *Show* or *Segment By* sections of the Explore page in Sysdig Monitor. These entries are used to apply single or hierarchical segmentation to the returned data and don't require the aggregations section. Refer to the Example link below for ready-to-use code snippets. - **start_ts**: the UTC time (in seconds) of the beginning of the data window. A negative value can be optionally used to indicate a relative time in the past from now. For example, -3600 means "one hour ago". - **end_ts**: the UTC time (in seconds) of the end of the data window, or 0 to indicate "now". A negative value can also be optionally used to indicate a relative time in the past from now. For example, -3600 means "one hour ago". - **sampling_s**: the duration of the samples that will be returned. 0 means that the whole data will be returned as a single sample. - **filter**: a boolean expression combining Sysdig Monitor segmentation criteria that defines what the query will be applied to. For example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **datasource_type**: specify the metric source for the request, can be ``container`` or ``host``. Most metrics, for example ``cpu.used.percent`` or ``memory.bytes.used``, are reported by both hosts and containers. By default, host metrics are used, but if the request contains a container-specific grouping key in the metric list/filter (e.g. ``container.name``), then the container source is used. In cases where grouping keys are missing or apply to both hosts and containers (e.g. ``tag.Name``), *datasource_type* can be explicitly set to avoid any ambiguity and allow the user to select precisely what kind of data should be used for the request. `examples/get_data_datasource.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_datasource.py>`_ contains a few examples that should clarify the use of this argument. - **paging**: if segmentation of the query generates values for several different entities (e.g. containers/hosts), this parameter specifies which to include in the returned result. It's specified as a dictionary of inclusive values for ``from`` and ``to`` with the default being ``{ "from": 0, "to": 9 }``, which will return values for the "top 10" entities. The meaning of "top" is query-dependent, based on points having been sorted via the specified group aggregation, with the results sorted in ascending order if the group aggregation is ``min`` or ``none``, and descending order otherwise. **Success Return Value** A dictionary with the requested data. Data is organized in a list of time samples, each of which includes a UTC timestamp and a list of values, whose content and order reflect what was specified in the *metrics* argument. **Examples** - `examples/get_data_simple.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_simple.py>`_ - `examples/get_data_advanced.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_advanced.py>`_ - `examples/list_hosts.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_hosts.py>`_ - `examples/get_data_datasource.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_data_datasource.py>`_ ''' reqbody = { 'metrics': metrics, 'dataSourceType': datasource_type, } if start_ts < 0: reqbody['last'] = -start_ts elif start_ts == 0: return [False, "start_ts cannot be 0"] else: reqbody['start'] = start_ts reqbody['end'] = end_ts if filter != '': reqbody['filter'] = filter if paging is not None: reqbody['paging'] = paging if sampling_s != 0: reqbody['sampling'] = sampling_s res = requests.post(self.url + '/api/data/', headers=self.hdrs, data=json.dumps(reqbody), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Export", "metric", "data", "(", "both", "time", "-", "series", "and", "table", "-", "based", ")", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L428-L474
[ "def", "get_data", "(", "self", ",", "metrics", ",", "start_ts", ",", "end_ts", "=", "0", ",", "sampling_s", "=", "0", ",", "filter", "=", "''", ",", "datasource_type", "=", "'host'", ",", "paging", "=", "None", ")", ":", "reqbody", "=", "{", "'metrics'", ":", "metrics", ",", "'dataSourceType'", ":", "datasource_type", ",", "}", "if", "start_ts", "<", "0", ":", "reqbody", "[", "'last'", "]", "=", "-", "start_ts", "elif", "start_ts", "==", "0", ":", "return", "[", "False", ",", "\"start_ts cannot be 0\"", "]", "else", ":", "reqbody", "[", "'start'", "]", "=", "start_ts", "reqbody", "[", "'end'", "]", "=", "end_ts", "if", "filter", "!=", "''", ":", "reqbody", "[", "'filter'", "]", "=", "filter", "if", "paging", "is", "not", "None", ":", "reqbody", "[", "'paging'", "]", "=", "paging", "if", "sampling_s", "!=", "0", ":", "reqbody", "[", "'sampling'", "]", "=", "sampling_s", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/data/'", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "reqbody", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.get_sysdig_captures
**Description** Returns the list of sysdig captures for the user. **Arguments** - from_sec: the start of the timerange for which to get the captures - end_sec: the end of the timerange for which to get the captures - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container). **Success Return Value** A dictionary containing the list of captures. **Example** `examples/list_sysdig_captures.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_sysdig_captures.py>`_
sdcclient/_common.py
def get_sysdig_captures(self, from_sec=None, to_sec=None, scope_filter=None): '''**Description** Returns the list of sysdig captures for the user. **Arguments** - from_sec: the start of the timerange for which to get the captures - end_sec: the end of the timerange for which to get the captures - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container). **Success Return Value** A dictionary containing the list of captures. **Example** `examples/list_sysdig_captures.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_sysdig_captures.py>`_ ''' url = '{url}/api/sysdig?source={source}{frm}{to}{scopeFilter}'.format( url=self.url, source=self.product, frm="&from=%d" % (from_sec * 10**6) if from_sec else "", to="&to=%d" % (to_sec * 10**6) if to_sec else "", scopeFilter="&scopeFilter=%s" % scope_filter if scope_filter else "") res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def get_sysdig_captures(self, from_sec=None, to_sec=None, scope_filter=None): '''**Description** Returns the list of sysdig captures for the user. **Arguments** - from_sec: the start of the timerange for which to get the captures - end_sec: the end of the timerange for which to get the captures - scope_filter: this is a SysdigMonitor-like filter (e.g 'container.image=ubuntu'). When provided, events are filtered by their scope, so only a subset will be returned (e.g. 'container.image=ubuntu' will provide only events that have happened on an ubuntu container). **Success Return Value** A dictionary containing the list of captures. **Example** `examples/list_sysdig_captures.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_sysdig_captures.py>`_ ''' url = '{url}/api/sysdig?source={source}{frm}{to}{scopeFilter}'.format( url=self.url, source=self.product, frm="&from=%d" % (from_sec * 10**6) if from_sec else "", to="&to=%d" % (to_sec * 10**6) if to_sec else "", scopeFilter="&scopeFilter=%s" % scope_filter if scope_filter else "") res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Returns", "the", "list", "of", "sysdig", "captures", "for", "the", "user", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L476-L498
[ "def", "get_sysdig_captures", "(", "self", ",", "from_sec", "=", "None", ",", "to_sec", "=", "None", ",", "scope_filter", "=", "None", ")", ":", "url", "=", "'{url}/api/sysdig?source={source}{frm}{to}{scopeFilter}'", ".", "format", "(", "url", "=", "self", ".", "url", ",", "source", "=", "self", ".", "product", ",", "frm", "=", "\"&from=%d\"", "%", "(", "from_sec", "*", "10", "**", "6", ")", "if", "from_sec", "else", "\"\"", ",", "to", "=", "\"&to=%d\"", "%", "(", "to_sec", "*", "10", "**", "6", ")", "if", "to_sec", "else", "\"\"", ",", "scopeFilter", "=", "\"&scopeFilter=%s\"", "%", "scope_filter", "if", "scope_filter", "else", "\"\"", ")", "res", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.poll_sysdig_capture
**Description** Fetch the updated state of a sysdig capture. Can be used to poll the status of a capture that has been previously created and started with :func:`~SdcClient.create_sysdig_capture`. **Arguments** - **capture**: the capture object as returned by :func:`~SdcClient.get_sysdig_captures` or :func:`~SdcClient.create_sysdig_capture`. **Success Return Value** A dictionary showing the updated details of the capture. Use the ``status`` field to check the progress of a capture. **Example** `examples/create_sysdig_capture.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_sysdig_capture.py>`_
sdcclient/_common.py
def poll_sysdig_capture(self, capture): '''**Description** Fetch the updated state of a sysdig capture. Can be used to poll the status of a capture that has been previously created and started with :func:`~SdcClient.create_sysdig_capture`. **Arguments** - **capture**: the capture object as returned by :func:`~SdcClient.get_sysdig_captures` or :func:`~SdcClient.create_sysdig_capture`. **Success Return Value** A dictionary showing the updated details of the capture. Use the ``status`` field to check the progress of a capture. **Example** `examples/create_sysdig_capture.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_sysdig_capture.py>`_ ''' if 'id' not in capture: return [False, 'Invalid capture format'] url = '{url}/api/sysdig/{id}?source={source}'.format( url=self.url, id=capture['id'], source=self.product) res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
def poll_sysdig_capture(self, capture): '''**Description** Fetch the updated state of a sysdig capture. Can be used to poll the status of a capture that has been previously created and started with :func:`~SdcClient.create_sysdig_capture`. **Arguments** - **capture**: the capture object as returned by :func:`~SdcClient.get_sysdig_captures` or :func:`~SdcClient.create_sysdig_capture`. **Success Return Value** A dictionary showing the updated details of the capture. Use the ``status`` field to check the progress of a capture. **Example** `examples/create_sysdig_capture.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_sysdig_capture.py>`_ ''' if 'id' not in capture: return [False, 'Invalid capture format'] url = '{url}/api/sysdig/{id}?source={source}'.format( url=self.url, id=capture['id'], source=self.product) res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Fetch", "the", "updated", "state", "of", "a", "sysdig", "capture", ".", "Can", "be", "used", "to", "poll", "the", "status", "of", "a", "capture", "that", "has", "been", "previously", "created", "and", "started", "with", ":", "func", ":", "~SdcClient", ".", "create_sysdig_capture", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L500-L519
[ "def", "poll_sysdig_capture", "(", "self", ",", "capture", ")", ":", "if", "'id'", "not", "in", "capture", ":", "return", "[", "False", ",", "'Invalid capture format'", "]", "url", "=", "'{url}/api/sysdig/{id}?source={source}'", ".", "format", "(", "url", "=", "self", ".", "url", ",", "id", "=", "capture", "[", "'id'", "]", ",", "source", "=", "self", ".", "product", ")", "res", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.create_sysdig_capture
**Description** Create a new sysdig capture. The capture will be immediately started. **Arguments** - **hostname**: the hostname of the instrumented host where the capture will be taken. - **capture_name**: the name of the capture. - **duration**: the duration of the capture, in seconds. - **capture_filter**: a sysdig filter expression. - **folder**: directory in the S3 bucket where the capture will be saved. **Success Return Value** A dictionary showing the details of the new capture. **Example** `examples/create_sysdig_capture.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_sysdig_capture.py>`_
sdcclient/_common.py
def create_sysdig_capture(self, hostname, capture_name, duration, capture_filter='', folder='/'): '''**Description** Create a new sysdig capture. The capture will be immediately started. **Arguments** - **hostname**: the hostname of the instrumented host where the capture will be taken. - **capture_name**: the name of the capture. - **duration**: the duration of the capture, in seconds. - **capture_filter**: a sysdig filter expression. - **folder**: directory in the S3 bucket where the capture will be saved. **Success Return Value** A dictionary showing the details of the new capture. **Example** `examples/create_sysdig_capture.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_sysdig_capture.py>`_ ''' res = self.get_connected_agents() if not res[0]: return res capture_agent = None for agent in res[1]: if hostname == agent['hostName']: capture_agent = agent break if capture_agent is None: return [False, hostname + ' not found'] data = { 'agent': capture_agent, 'name': capture_name, 'duration': duration, 'folder': folder, 'filters': capture_filter, 'bucketName': '', 'source': self.product } res = requests.post(self.url + '/api/sysdig', headers=self.hdrs, data=json.dumps(data), verify=self.ssl_verify) return self._request_result(res)
def create_sysdig_capture(self, hostname, capture_name, duration, capture_filter='', folder='/'): '''**Description** Create a new sysdig capture. The capture will be immediately started. **Arguments** - **hostname**: the hostname of the instrumented host where the capture will be taken. - **capture_name**: the name of the capture. - **duration**: the duration of the capture, in seconds. - **capture_filter**: a sysdig filter expression. - **folder**: directory in the S3 bucket where the capture will be saved. **Success Return Value** A dictionary showing the details of the new capture. **Example** `examples/create_sysdig_capture.py <https://github.com/draios/python-sdc-client/blob/master/examples/create_sysdig_capture.py>`_ ''' res = self.get_connected_agents() if not res[0]: return res capture_agent = None for agent in res[1]: if hostname == agent['hostName']: capture_agent = agent break if capture_agent is None: return [False, hostname + ' not found'] data = { 'agent': capture_agent, 'name': capture_name, 'duration': duration, 'folder': folder, 'filters': capture_filter, 'bucketName': '', 'source': self.product } res = requests.post(self.url + '/api/sysdig', headers=self.hdrs, data=json.dumps(data), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Create", "a", "new", "sysdig", "capture", ".", "The", "capture", "will", "be", "immediately", "started", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L521-L563
[ "def", "create_sysdig_capture", "(", "self", ",", "hostname", ",", "capture_name", ",", "duration", ",", "capture_filter", "=", "''", ",", "folder", "=", "'/'", ")", ":", "res", "=", "self", ".", "get_connected_agents", "(", ")", "if", "not", "res", "[", "0", "]", ":", "return", "res", "capture_agent", "=", "None", "for", "agent", "in", "res", "[", "1", "]", ":", "if", "hostname", "==", "agent", "[", "'hostName'", "]", ":", "capture_agent", "=", "agent", "break", "if", "capture_agent", "is", "None", ":", "return", "[", "False", ",", "hostname", "+", "' not found'", "]", "data", "=", "{", "'agent'", ":", "capture_agent", ",", "'name'", ":", "capture_name", ",", "'duration'", ":", "duration", ",", "'folder'", ":", "folder", ",", "'filters'", ":", "capture_filter", ",", "'bucketName'", ":", "''", ",", "'source'", ":", "self", ".", "product", "}", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/sysdig'", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.download_sysdig_capture
**Description** Download a sysdig capture by id. **Arguments** - **capture_id**: the capture id to download. **Success Return Value** The bytes of the scap
sdcclient/_common.py
def download_sysdig_capture(self, capture_id): '''**Description** Download a sysdig capture by id. **Arguments** - **capture_id**: the capture id to download. **Success Return Value** The bytes of the scap ''' url = '{url}/api/sysdig/{id}/download?_product={product}'.format( url=self.url, id=capture_id, product=self.product) res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return False, self.lasterr return True, res.content
def download_sysdig_capture(self, capture_id): '''**Description** Download a sysdig capture by id. **Arguments** - **capture_id**: the capture id to download. **Success Return Value** The bytes of the scap ''' url = '{url}/api/sysdig/{id}/download?_product={product}'.format( url=self.url, id=capture_id, product=self.product) res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return False, self.lasterr return True, res.content
[ "**", "Description", "**", "Download", "a", "sysdig", "capture", "by", "id", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L565-L581
[ "def", "download_sysdig_capture", "(", "self", ",", "capture_id", ")", ":", "url", "=", "'{url}/api/sysdig/{id}/download?_product={product}'", ".", "format", "(", "url", "=", "self", ".", "url", ",", "id", "=", "capture_id", ",", "product", "=", "self", ".", "product", ")", "res", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "False", ",", "self", ".", "lasterr", "return", "True", ",", "res", ".", "content" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.create_user_invite
**Description** Invites a new user to use Sysdig Monitor. This should result in an email notification to the specified address. **Arguments** - **user_email**: the email address of the user that will be invited to use Sysdig Monitor - **first_name**: the first name of the user being invited - **last_name**: the last name of the user being invited - **system_role**: system-wide privilege level for this user regardless of team. specify 'ROLE_CUSTOMER' to create an Admin. if not specified, default is a non-Admin ('ROLE_USER'). **Success Return Value** The newly created user. **Examples** - `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ - `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_
sdcclient/_common.py
def create_user_invite(self, user_email, first_name=None, last_name=None, system_role=None): '''**Description** Invites a new user to use Sysdig Monitor. This should result in an email notification to the specified address. **Arguments** - **user_email**: the email address of the user that will be invited to use Sysdig Monitor - **first_name**: the first name of the user being invited - **last_name**: the last name of the user being invited - **system_role**: system-wide privilege level for this user regardless of team. specify 'ROLE_CUSTOMER' to create an Admin. if not specified, default is a non-Admin ('ROLE_USER'). **Success Return Value** The newly created user. **Examples** - `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ - `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_ ''' # Look up the list of users to see if this exists, do not create if one exists res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] data = res.json() for user in data['users']: if user['username'] == user_email: return [False, 'user ' + user_email + ' already exists'] # Create the user options = {'username': user_email, 'firstName': first_name, 'lastName': last_name, 'systemRole': system_role} user_json = {k: v for k, v in options.items() if v is not None} res = requests.post(self.url + '/api/users', headers=self.hdrs, data=json.dumps(user_json), verify=self.ssl_verify) return self._request_result(res)
def create_user_invite(self, user_email, first_name=None, last_name=None, system_role=None): '''**Description** Invites a new user to use Sysdig Monitor. This should result in an email notification to the specified address. **Arguments** - **user_email**: the email address of the user that will be invited to use Sysdig Monitor - **first_name**: the first name of the user being invited - **last_name**: the last name of the user being invited - **system_role**: system-wide privilege level for this user regardless of team. specify 'ROLE_CUSTOMER' to create an Admin. if not specified, default is a non-Admin ('ROLE_USER'). **Success Return Value** The newly created user. **Examples** - `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ - `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_ ''' # Look up the list of users to see if this exists, do not create if one exists res = requests.get(self.url + '/api/users', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] data = res.json() for user in data['users']: if user['username'] == user_email: return [False, 'user ' + user_email + ' already exists'] # Create the user options = {'username': user_email, 'firstName': first_name, 'lastName': last_name, 'systemRole': system_role} user_json = {k: v for k, v in options.items() if v is not None} res = requests.post(self.url + '/api/users', headers=self.hdrs, data=json.dumps(user_json), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Invites", "a", "new", "user", "to", "use", "Sysdig", "Monitor", ".", "This", "should", "result", "in", "an", "email", "notification", "to", "the", "specified", "address", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L583-L618
[ "def", "create_user_invite", "(", "self", ",", "user_email", ",", "first_name", "=", "None", ",", "last_name", "=", "None", ",", "system_role", "=", "None", ")", ":", "# Look up the list of users to see if this exists, do not create if one exists", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/users'", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "data", "=", "res", ".", "json", "(", ")", "for", "user", "in", "data", "[", "'users'", "]", ":", "if", "user", "[", "'username'", "]", "==", "user_email", ":", "return", "[", "False", ",", "'user '", "+", "user_email", "+", "' already exists'", "]", "# Create the user", "options", "=", "{", "'username'", ":", "user_email", ",", "'firstName'", ":", "first_name", ",", "'lastName'", ":", "last_name", ",", "'systemRole'", ":", "system_role", "}", "user_json", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "options", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/users'", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "user_json", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.delete_user
**Description** Deletes a user from Sysdig Monitor. **Arguments** - **user_email**: the email address of the user that will be deleted from Sysdig Monitor **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_
sdcclient/_common.py
def delete_user(self, user_email): '''**Description** Deletes a user from Sysdig Monitor. **Arguments** - **user_email**: the email address of the user that will be deleted from Sysdig Monitor **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ ''' res = self.get_user_ids([user_email]) if res[0] == False: return res userid = res[1][0] res = requests.delete(self.url + '/api/users/' + str(userid), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, None]
def delete_user(self, user_email): '''**Description** Deletes a user from Sysdig Monitor. **Arguments** - **user_email**: the email address of the user that will be deleted from Sysdig Monitor **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ ''' res = self.get_user_ids([user_email]) if res[0] == False: return res userid = res[1][0] res = requests.delete(self.url + '/api/users/' + str(userid), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, None]
[ "**", "Description", "**", "Deletes", "a", "user", "from", "Sysdig", "Monitor", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L620-L637
[ "def", "delete_user", "(", "self", ",", "user_email", ")", ":", "res", "=", "self", ".", "get_user_ids", "(", "[", "user_email", "]", ")", "if", "res", "[", "0", "]", "==", "False", ":", "return", "res", "userid", "=", "res", "[", "1", "]", "[", "0", "]", "res", "=", "requests", ".", "delete", "(", "self", ".", "url", "+", "'/api/users/'", "+", "str", "(", "userid", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "return", "[", "True", ",", "None", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.get_teams
**Description** Return the set of teams that match the filter specified. The *team_filter* should be a substring of the names of the teams to be returned. **Arguments** - **team_filter**: the team filter to match when returning the list of teams **Success Return Value** The teams that match the filter.
sdcclient/_common.py
def get_teams(self, team_filter=''): '''**Description** Return the set of teams that match the filter specified. The *team_filter* should be a substring of the names of the teams to be returned. **Arguments** - **team_filter**: the team filter to match when returning the list of teams **Success Return Value** The teams that match the filter. ''' res = requests.get(self.url + '/api/teams', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] ret = [t for t in res.json()['teams'] if team_filter in t['name']] return [True, ret]
def get_teams(self, team_filter=''): '''**Description** Return the set of teams that match the filter specified. The *team_filter* should be a substring of the names of the teams to be returned. **Arguments** - **team_filter**: the team filter to match when returning the list of teams **Success Return Value** The teams that match the filter. ''' res = requests.get(self.url + '/api/teams', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] ret = [t for t in res.json()['teams'] if team_filter in t['name']] return [True, ret]
[ "**", "Description", "**", "Return", "the", "set", "of", "teams", "that", "match", "the", "filter", "specified", ".", "The", "*", "team_filter", "*", "should", "be", "a", "substring", "of", "the", "names", "of", "the", "teams", "to", "be", "returned", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L687-L701
[ "def", "get_teams", "(", "self", ",", "team_filter", "=", "''", ")", ":", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "'/api/teams'", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "ret", "=", "[", "t", "for", "t", "in", "res", ".", "json", "(", ")", "[", "'teams'", "]", "if", "team_filter", "in", "t", "[", "'name'", "]", "]", "return", "[", "True", ",", "ret", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.get_team
**Description** Return the team with the specified team name, if it is present. **Arguments** - **name**: the name of the team to return **Success Return Value** The requested team. **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_
sdcclient/_common.py
def get_team(self, name): '''**Description** Return the team with the specified team name, if it is present. **Arguments** - **name**: the name of the team to return **Success Return Value** The requested team. **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ ''' res = self.get_teams(name) if res[0] == False: return res for t in res[1]: if t['name'] == name: return [True, t] return [False, 'Could not find team']
def get_team(self, name): '''**Description** Return the team with the specified team name, if it is present. **Arguments** - **name**: the name of the team to return **Success Return Value** The requested team. **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ ''' res = self.get_teams(name) if res[0] == False: return res for t in res[1]: if t['name'] == name: return [True, t] return [False, 'Could not find team']
[ "**", "Description", "**", "Return", "the", "team", "with", "the", "specified", "team", "name", "if", "it", "is", "present", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L703-L722
[ "def", "get_team", "(", "self", ",", "name", ")", ":", "res", "=", "self", ".", "get_teams", "(", "name", ")", "if", "res", "[", "0", "]", "==", "False", ":", "return", "res", "for", "t", "in", "res", "[", "1", "]", ":", "if", "t", "[", "'name'", "]", "==", "name", ":", "return", "[", "True", ",", "t", "]", "return", "[", "False", ",", "'Could not find team'", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.create_team
**Description** Creates a new team **Arguments** - **name**: the name of the team to create. - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships of the team. - **filter**: the scope that this team is able to access within Sysdig Monitor. - **description**: describes the team that will be created. - **show**: possible values are *host*, *container*. - **theme**: the color theme that Sysdig Monitor will use when displaying the team. - **perm_capture**: if True, this team will be allowed to take sysdig captures. - **perm_custom_events**: if True, this team will be allowed to view all custom events from every user and agent. - **perm_aws_data**: if True, this team will have access to all AWS metrics and tags, regardless of the team's scope. **Success Return Value** The newly created team. **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_
sdcclient/_common.py
def create_team(self, name, memberships=None, filter='', description='', show='host', theme='#7BB0B2', perm_capture=False, perm_custom_events=False, perm_aws_data=False): ''' **Description** Creates a new team **Arguments** - **name**: the name of the team to create. - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships of the team. - **filter**: the scope that this team is able to access within Sysdig Monitor. - **description**: describes the team that will be created. - **show**: possible values are *host*, *container*. - **theme**: the color theme that Sysdig Monitor will use when displaying the team. - **perm_capture**: if True, this team will be allowed to take sysdig captures. - **perm_custom_events**: if True, this team will be allowed to view all custom events from every user and agent. - **perm_aws_data**: if True, this team will have access to all AWS metrics and tags, regardless of the team's scope. **Success Return Value** The newly created team. **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ ''' reqbody = { 'name': name, 'description': description, 'theme': theme, 'show': show, 'canUseSysdigCapture': perm_capture, 'canUseCustomEvents': perm_custom_events, 'canUseAwsMetrics': perm_aws_data, } # Map user-names to IDs if memberships != None and len(memberships) != 0: res = self._get_user_id_dict(list(memberships.keys())) if res[0] == False: return [False, 'Could not fetch IDs for user names'] reqbody['userRoles'] = [ { 'userId': user_id, 'role': memberships[user_name] } for (user_name, user_id) in res[1].items() ] else: reqbody['users'] = [] if filter != '': reqbody['filter'] = filter res = requests.post(self.url + '/api/teams', headers=self.hdrs, data=json.dumps(reqbody), verify=self.ssl_verify) return self._request_result(res)
def create_team(self, name, memberships=None, filter='', description='', show='host', theme='#7BB0B2', perm_capture=False, perm_custom_events=False, perm_aws_data=False): ''' **Description** Creates a new team **Arguments** - **name**: the name of the team to create. - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships of the team. - **filter**: the scope that this team is able to access within Sysdig Monitor. - **description**: describes the team that will be created. - **show**: possible values are *host*, *container*. - **theme**: the color theme that Sysdig Monitor will use when displaying the team. - **perm_capture**: if True, this team will be allowed to take sysdig captures. - **perm_custom_events**: if True, this team will be allowed to view all custom events from every user and agent. - **perm_aws_data**: if True, this team will have access to all AWS metrics and tags, regardless of the team's scope. **Success Return Value** The newly created team. **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ ''' reqbody = { 'name': name, 'description': description, 'theme': theme, 'show': show, 'canUseSysdigCapture': perm_capture, 'canUseCustomEvents': perm_custom_events, 'canUseAwsMetrics': perm_aws_data, } # Map user-names to IDs if memberships != None and len(memberships) != 0: res = self._get_user_id_dict(list(memberships.keys())) if res[0] == False: return [False, 'Could not fetch IDs for user names'] reqbody['userRoles'] = [ { 'userId': user_id, 'role': memberships[user_name] } for (user_name, user_id) in res[1].items() ] else: reqbody['users'] = [] if filter != '': reqbody['filter'] = filter res = requests.post(self.url + '/api/teams', headers=self.hdrs, data=json.dumps(reqbody), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Creates", "a", "new", "team" ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L752-L804
[ "def", "create_team", "(", "self", ",", "name", ",", "memberships", "=", "None", ",", "filter", "=", "''", ",", "description", "=", "''", ",", "show", "=", "'host'", ",", "theme", "=", "'#7BB0B2'", ",", "perm_capture", "=", "False", ",", "perm_custom_events", "=", "False", ",", "perm_aws_data", "=", "False", ")", ":", "reqbody", "=", "{", "'name'", ":", "name", ",", "'description'", ":", "description", ",", "'theme'", ":", "theme", ",", "'show'", ":", "show", ",", "'canUseSysdigCapture'", ":", "perm_capture", ",", "'canUseCustomEvents'", ":", "perm_custom_events", ",", "'canUseAwsMetrics'", ":", "perm_aws_data", ",", "}", "# Map user-names to IDs", "if", "memberships", "!=", "None", "and", "len", "(", "memberships", ")", "!=", "0", ":", "res", "=", "self", ".", "_get_user_id_dict", "(", "list", "(", "memberships", ".", "keys", "(", ")", ")", ")", "if", "res", "[", "0", "]", "==", "False", ":", "return", "[", "False", ",", "'Could not fetch IDs for user names'", "]", "reqbody", "[", "'userRoles'", "]", "=", "[", "{", "'userId'", ":", "user_id", ",", "'role'", ":", "memberships", "[", "user_name", "]", "}", "for", "(", "user_name", ",", "user_id", ")", "in", "res", "[", "1", "]", ".", "items", "(", ")", "]", "else", ":", "reqbody", "[", "'users'", "]", "=", "[", "]", "if", "filter", "!=", "''", ":", "reqbody", "[", "'filter'", "]", "=", "filter", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "'/api/teams'", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "reqbody", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.edit_team
**Description** Edits an existing team. All arguments are optional. Team settings for any arguments unspecified will remain at their current settings. **Arguments** - **name**: the name of the team to edit. - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships of the team. - **filter**: the scope that this team is able to access within Sysdig Monitor. - **description**: describes the team that will be created. - **show**: possible values are *host*, *container*. - **theme**: the color theme that Sysdig Monitor will use when displaying the team. - **perm_capture**: if True, this team will be allowed to take sysdig captures. - **perm_custom_events**: if True, this team will be allowed to view all custom events from every user and agent. - **perm_aws_data**: if True, this team will have access to all AWS metrics and tags, regardless of the team's scope. **Success Return Value** The edited team. **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_
sdcclient/_common.py
def edit_team(self, name, memberships=None, filter=None, description=None, show=None, theme=None, perm_capture=None, perm_custom_events=None, perm_aws_data=None): ''' **Description** Edits an existing team. All arguments are optional. Team settings for any arguments unspecified will remain at their current settings. **Arguments** - **name**: the name of the team to edit. - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships of the team. - **filter**: the scope that this team is able to access within Sysdig Monitor. - **description**: describes the team that will be created. - **show**: possible values are *host*, *container*. - **theme**: the color theme that Sysdig Monitor will use when displaying the team. - **perm_capture**: if True, this team will be allowed to take sysdig captures. - **perm_custom_events**: if True, this team will be allowed to view all custom events from every user and agent. - **perm_aws_data**: if True, this team will have access to all AWS metrics and tags, regardless of the team's scope. **Success Return Value** The edited team. **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ ''' res = self.get_team(name) if res[0] == False: return res t = res[1] reqbody = { 'name': name, 'theme': theme if theme else t['theme'], 'show': show if show else t['show'], 'canUseSysdigCapture': perm_capture if perm_capture else t['canUseSysdigCapture'], 'canUseCustomEvents': perm_custom_events if perm_custom_events else t['canUseCustomEvents'], 'canUseAwsMetrics': perm_aws_data if perm_aws_data else t['canUseAwsMetrics'], 'id': t['id'], 'version': t['version'] } # Handling team description if description is not None: reqbody['description'] = description elif 'description' in list(t.keys()): reqbody['description'] = t['description'] # Handling for users to map (user-name, team-role) pairs to memberships if memberships != None: res = self._get_user_id_dict(list(memberships.keys())) if res[0] == False: return [False, 'Could not convert user names to IDs'] reqbody['userRoles'] = [ { 'userId': user_id, 'role': memberships[user_name] } for (user_name, user_id) in res[1].items() ] elif 'userRoles' in list(t.keys()): reqbody['userRoles'] = t['userRoles'] else: reqbody['userRoles'] = [] # Special handling for filters since we don't support blank filters if filter != None: reqbody['filter'] = filter elif 'filter' in list(t.keys()): reqbody['filter'] = t['filter'] res = requests.put(self.url + '/api/teams/' + str(t['id']), headers=self.hdrs, data=json.dumps(reqbody), verify=self.ssl_verify) return self._request_result(res)
def edit_team(self, name, memberships=None, filter=None, description=None, show=None, theme=None, perm_capture=None, perm_custom_events=None, perm_aws_data=None): ''' **Description** Edits an existing team. All arguments are optional. Team settings for any arguments unspecified will remain at their current settings. **Arguments** - **name**: the name of the team to edit. - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships of the team. - **filter**: the scope that this team is able to access within Sysdig Monitor. - **description**: describes the team that will be created. - **show**: possible values are *host*, *container*. - **theme**: the color theme that Sysdig Monitor will use when displaying the team. - **perm_capture**: if True, this team will be allowed to take sysdig captures. - **perm_custom_events**: if True, this team will be allowed to view all custom events from every user and agent. - **perm_aws_data**: if True, this team will have access to all AWS metrics and tags, regardless of the team's scope. **Success Return Value** The edited team. **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ ''' res = self.get_team(name) if res[0] == False: return res t = res[1] reqbody = { 'name': name, 'theme': theme if theme else t['theme'], 'show': show if show else t['show'], 'canUseSysdigCapture': perm_capture if perm_capture else t['canUseSysdigCapture'], 'canUseCustomEvents': perm_custom_events if perm_custom_events else t['canUseCustomEvents'], 'canUseAwsMetrics': perm_aws_data if perm_aws_data else t['canUseAwsMetrics'], 'id': t['id'], 'version': t['version'] } # Handling team description if description is not None: reqbody['description'] = description elif 'description' in list(t.keys()): reqbody['description'] = t['description'] # Handling for users to map (user-name, team-role) pairs to memberships if memberships != None: res = self._get_user_id_dict(list(memberships.keys())) if res[0] == False: return [False, 'Could not convert user names to IDs'] reqbody['userRoles'] = [ { 'userId': user_id, 'role': memberships[user_name] } for (user_name, user_id) in res[1].items() ] elif 'userRoles' in list(t.keys()): reqbody['userRoles'] = t['userRoles'] else: reqbody['userRoles'] = [] # Special handling for filters since we don't support blank filters if filter != None: reqbody['filter'] = filter elif 'filter' in list(t.keys()): reqbody['filter'] = t['filter'] res = requests.put(self.url + '/api/teams/' + str(t['id']), headers=self.hdrs, data=json.dumps(reqbody), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Edits", "an", "existing", "team", ".", "All", "arguments", "are", "optional", ".", "Team", "settings", "for", "any", "arguments", "unspecified", "will", "remain", "at", "their", "current", "settings", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L806-L875
[ "def", "edit_team", "(", "self", ",", "name", ",", "memberships", "=", "None", ",", "filter", "=", "None", ",", "description", "=", "None", ",", "show", "=", "None", ",", "theme", "=", "None", ",", "perm_capture", "=", "None", ",", "perm_custom_events", "=", "None", ",", "perm_aws_data", "=", "None", ")", ":", "res", "=", "self", ".", "get_team", "(", "name", ")", "if", "res", "[", "0", "]", "==", "False", ":", "return", "res", "t", "=", "res", "[", "1", "]", "reqbody", "=", "{", "'name'", ":", "name", ",", "'theme'", ":", "theme", "if", "theme", "else", "t", "[", "'theme'", "]", ",", "'show'", ":", "show", "if", "show", "else", "t", "[", "'show'", "]", ",", "'canUseSysdigCapture'", ":", "perm_capture", "if", "perm_capture", "else", "t", "[", "'canUseSysdigCapture'", "]", ",", "'canUseCustomEvents'", ":", "perm_custom_events", "if", "perm_custom_events", "else", "t", "[", "'canUseCustomEvents'", "]", ",", "'canUseAwsMetrics'", ":", "perm_aws_data", "if", "perm_aws_data", "else", "t", "[", "'canUseAwsMetrics'", "]", ",", "'id'", ":", "t", "[", "'id'", "]", ",", "'version'", ":", "t", "[", "'version'", "]", "}", "# Handling team description", "if", "description", "is", "not", "None", ":", "reqbody", "[", "'description'", "]", "=", "description", "elif", "'description'", "in", "list", "(", "t", ".", "keys", "(", ")", ")", ":", "reqbody", "[", "'description'", "]", "=", "t", "[", "'description'", "]", "# Handling for users to map (user-name, team-role) pairs to memberships", "if", "memberships", "!=", "None", ":", "res", "=", "self", ".", "_get_user_id_dict", "(", "list", "(", "memberships", ".", "keys", "(", ")", ")", ")", "if", "res", "[", "0", "]", "==", "False", ":", "return", "[", "False", ",", "'Could not convert user names to IDs'", "]", "reqbody", "[", "'userRoles'", "]", "=", "[", "{", "'userId'", ":", "user_id", ",", "'role'", ":", "memberships", "[", "user_name", "]", "}", "for", "(", "user_name", ",", "user_id", ")", "in", "res", "[", "1", "]", ".", "items", "(", ")", "]", "elif", "'userRoles'", "in", "list", "(", "t", ".", "keys", "(", ")", ")", ":", "reqbody", "[", "'userRoles'", "]", "=", "t", "[", "'userRoles'", "]", "else", ":", "reqbody", "[", "'userRoles'", "]", "=", "[", "]", "# Special handling for filters since we don't support blank filters", "if", "filter", "!=", "None", ":", "reqbody", "[", "'filter'", "]", "=", "filter", "elif", "'filter'", "in", "list", "(", "t", ".", "keys", "(", ")", ")", ":", "reqbody", "[", "'filter'", "]", "=", "t", "[", "'filter'", "]", "res", "=", "requests", ".", "put", "(", "self", ".", "url", "+", "'/api/teams/'", "+", "str", "(", "t", "[", "'id'", "]", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "reqbody", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.delete_team
**Description** Deletes a team from Sysdig Monitor. **Arguments** - **name**: the name of the team that will be deleted from Sysdig Monitor **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_
sdcclient/_common.py
def delete_team(self, name): '''**Description** Deletes a team from Sysdig Monitor. **Arguments** - **name**: the name of the team that will be deleted from Sysdig Monitor **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ ''' res = self.get_team(name) if res[0] == False: return res t = res[1] res = requests.delete(self.url + '/api/teams/' + str(t['id']), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, None]
def delete_team(self, name): '''**Description** Deletes a team from Sysdig Monitor. **Arguments** - **name**: the name of the team that will be deleted from Sysdig Monitor **Example** `examples/user_team_mgmt.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt.py>`_ ''' res = self.get_team(name) if res[0] == False: return res t = res[1] res = requests.delete(self.url + '/api/teams/' + str(t['id']), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, None]
[ "**", "Description", "**", "Deletes", "a", "team", "from", "Sysdig", "Monitor", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L877-L895
[ "def", "delete_team", "(", "self", ",", "name", ")", ":", "res", "=", "self", ".", "get_team", "(", "name", ")", "if", "res", "[", "0", "]", "==", "False", ":", "return", "res", "t", "=", "res", "[", "1", "]", "res", "=", "requests", ".", "delete", "(", "self", ".", "url", "+", "'/api/teams/'", "+", "str", "(", "t", "[", "'id'", "]", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "return", "[", "True", ",", "None", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.list_memberships
**Description** List all memberships for specified team. **Arguments** - **team**: the name of the team for which we want to see memberships **Result** Dictionary of (user-name, team-role) pairs that should describe memberships of the team. **Example** `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_
sdcclient/_common.py
def list_memberships(self, team): ''' **Description** List all memberships for specified team. **Arguments** - **team**: the name of the team for which we want to see memberships **Result** Dictionary of (user-name, team-role) pairs that should describe memberships of the team. **Example** `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_ ''' res = self.get_team(team) if res[0] == False: return res raw_memberships = res[1]['userRoles'] user_ids = [m['userId'] for m in raw_memberships] res = self._get_id_user_dict(user_ids) if res[0] == False: return [False, 'Could not fetch IDs for user names'] else: id_user_dict = res[1] return [True, dict([(id_user_dict[m['userId']], m['role']) for m in raw_memberships])]
def list_memberships(self, team): ''' **Description** List all memberships for specified team. **Arguments** - **team**: the name of the team for which we want to see memberships **Result** Dictionary of (user-name, team-role) pairs that should describe memberships of the team. **Example** `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_ ''' res = self.get_team(team) if res[0] == False: return res raw_memberships = res[1]['userRoles'] user_ids = [m['userId'] for m in raw_memberships] res = self._get_id_user_dict(user_ids) if res[0] == False: return [False, 'Could not fetch IDs for user names'] else: id_user_dict = res[1] return [True, dict([(id_user_dict[m['userId']], m['role']) for m in raw_memberships])]
[ "**", "Description", "**", "List", "all", "memberships", "for", "specified", "team", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L897-L924
[ "def", "list_memberships", "(", "self", ",", "team", ")", ":", "res", "=", "self", ".", "get_team", "(", "team", ")", "if", "res", "[", "0", "]", "==", "False", ":", "return", "res", "raw_memberships", "=", "res", "[", "1", "]", "[", "'userRoles'", "]", "user_ids", "=", "[", "m", "[", "'userId'", "]", "for", "m", "in", "raw_memberships", "]", "res", "=", "self", ".", "_get_id_user_dict", "(", "user_ids", ")", "if", "res", "[", "0", "]", "==", "False", ":", "return", "[", "False", ",", "'Could not fetch IDs for user names'", "]", "else", ":", "id_user_dict", "=", "res", "[", "1", "]", "return", "[", "True", ",", "dict", "(", "[", "(", "id_user_dict", "[", "m", "[", "'userId'", "]", "]", ",", "m", "[", "'role'", "]", ")", "for", "m", "in", "raw_memberships", "]", ")", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.save_memberships
**Description** Create new user team memberships or update existing ones. **Arguments** - **team**: the name of the team for which we are creating new memberships - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships **Example** `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_
sdcclient/_common.py
def save_memberships(self, team, memberships): ''' **Description** Create new user team memberships or update existing ones. **Arguments** - **team**: the name of the team for which we are creating new memberships - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships **Example** `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_ ''' res = self.list_memberships(team) if res[0] is False: return res full_memberships = res[1] full_memberships.update(memberships) res = self.edit_team(team, full_memberships) if res[0] is False: return res else: return [True, None]
def save_memberships(self, team, memberships): ''' **Description** Create new user team memberships or update existing ones. **Arguments** - **team**: the name of the team for which we are creating new memberships - **memberships**: dictionary of (user-name, team-role) pairs that should describe new memberships **Example** `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_ ''' res = self.list_memberships(team) if res[0] is False: return res full_memberships = res[1] full_memberships.update(memberships) res = self.edit_team(team, full_memberships) if res[0] is False: return res else: return [True, None]
[ "**", "Description", "**", "Create", "new", "user", "team", "memberships", "or", "update", "existing", "ones", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L926-L952
[ "def", "save_memberships", "(", "self", ",", "team", ",", "memberships", ")", ":", "res", "=", "self", ".", "list_memberships", "(", "team", ")", "if", "res", "[", "0", "]", "is", "False", ":", "return", "res", "full_memberships", "=", "res", "[", "1", "]", "full_memberships", ".", "update", "(", "memberships", ")", "res", "=", "self", ".", "edit_team", "(", "team", ",", "full_memberships", ")", "if", "res", "[", "0", "]", "is", "False", ":", "return", "res", "else", ":", "return", "[", "True", ",", "None", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
_SdcCommon.remove_memberships
**Description** Remove user memberships from specified team. **Arguments** - **team**: the name of the team from which user memberships are removed - **users**: list of usernames which should be removed from team **Example** `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_
sdcclient/_common.py
def remove_memberships(self, team, users): ''' **Description** Remove user memberships from specified team. **Arguments** - **team**: the name of the team from which user memberships are removed - **users**: list of usernames which should be removed from team **Example** `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_ ''' res = self.list_memberships(team) if res[0] is False: return res old_memberships = res[1] new_memberships = {k: v for k, v in old_memberships.items() if k not in users} res = self.edit_team(team, new_memberships) if res[0] is False: return res else: return [True, None]
def remove_memberships(self, team, users): ''' **Description** Remove user memberships from specified team. **Arguments** - **team**: the name of the team from which user memberships are removed - **users**: list of usernames which should be removed from team **Example** `examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_ ''' res = self.list_memberships(team) if res[0] is False: return res old_memberships = res[1] new_memberships = {k: v for k, v in old_memberships.items() if k not in users} res = self.edit_team(team, new_memberships) if res[0] is False: return res else: return [True, None]
[ "**", "Description", "**", "Remove", "user", "memberships", "from", "specified", "team", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L954-L980
[ "def", "remove_memberships", "(", "self", ",", "team", ",", "users", ")", ":", "res", "=", "self", ".", "list_memberships", "(", "team", ")", "if", "res", "[", "0", "]", "is", "False", ":", "return", "res", "old_memberships", "=", "res", "[", "1", "]", "new_memberships", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "old_memberships", ".", "items", "(", ")", "if", "k", "not", "in", "users", "}", "res", "=", "self", ".", "edit_team", "(", "team", ",", "new_memberships", ")", "if", "res", "[", "0", "]", "is", "False", ":", "return", "res", "else", ":", "return", "[", "True", ",", "None", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClientV1.create_dashboard
**Description** Creates an empty dashboard. You can then add panels by using ``add_dashboard_panel``. **Arguments** - **name**: the name of the dashboard that will be created. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_
sdcclient/_monitor_v1.py
def create_dashboard(self, name): ''' **Description** Creates an empty dashboard. You can then add panels by using ``add_dashboard_panel``. **Arguments** - **name**: the name of the dashboard that will be created. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_ ''' dashboard_configuration = { 'name': name, 'schema': 2, 'items': [] } # # Create the new dashboard # res = requests.post(self.url + self._dashboards_api_endpoint, headers=self.hdrs, data=json.dumps({'dashboard': dashboard_configuration}), verify=self.ssl_verify) return self._request_result(res)
def create_dashboard(self, name): ''' **Description** Creates an empty dashboard. You can then add panels by using ``add_dashboard_panel``. **Arguments** - **name**: the name of the dashboard that will be created. **Success Return Value** A dictionary showing the details of the new dashboard. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_ ''' dashboard_configuration = { 'name': name, 'schema': 2, 'items': [] } # # Create the new dashboard # res = requests.post(self.url + self._dashboards_api_endpoint, headers=self.hdrs, data=json.dumps({'dashboard': dashboard_configuration}), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Creates", "an", "empty", "dashboard", ".", "You", "can", "then", "add", "panels", "by", "using", "add_dashboard_panel", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor_v1.py#L81-L106
[ "def", "create_dashboard", "(", "self", ",", "name", ")", ":", "dashboard_configuration", "=", "{", "'name'", ":", "name", ",", "'schema'", ":", "2", ",", "'items'", ":", "[", "]", "}", "#", "# Create the new dashboard", "#", "res", "=", "requests", ".", "post", "(", "self", ".", "url", "+", "self", ".", "_dashboards_api_endpoint", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "{", "'dashboard'", ":", "dashboard_configuration", "}", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdMonitorClientV1.add_dashboard_panel
**Description** Adds a panel to the dashboard. A panel can be a time series, or a top chart (i.e. bar chart), or a number panel. **Arguments** - **dashboard**: dashboard to edit - **name**: name of the new panel - **panel_type**: type of the new panel. Valid values are: ``timeSeries``, ``top``, ``number`` - **metrics**: a list of dictionaries, specifying the metrics to show in the panel, and optionally, if there is only one metric, a grouping key to segment that metric by. A metric is any of the entries that can be found in the *Metrics* section of the Explore page in Sysdig Monitor. Metric entries require an *aggregations* section specifying how to aggregate the metric across time and groups of containers/hosts. A grouping key is any of the entries that can be found in the *Show* or *Segment By* sections of the Explore page in Sysdig Monitor. Refer to the examples section below for ready to use code snippets. Note, certain panels allow certain combinations of metrics and grouping keys: - ``timeSeries``: 1 or more metrics OR 1 metric + 1 grouping key - ``top``: 1 or more metrics OR 1 metric + 1 grouping key - ``number``: 1 metric only - **scope**: filter to apply to the panel; must be based on metadata available in Sysdig Monitor; Example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **sort_by**: Data sorting; The parameter is optional and it's a dictionary of ``metric`` and ``mode`` (it can be ``desc`` or ``asc``) - **limit**: This parameter sets the limit on the number of lines/bars shown in a ``timeSeries`` or ``top`` panel. In the case of more entities being available than the limit, the top entities according to the sort will be shown. The default value is 10 for ``top`` panels (for ``timeSeries`` the default is defined by Sysdig Monitor itself). Note that increasing the limit above 10 is not officially supported and may cause performance and rendering issues - **layout**: Size and position of the panel. The dashboard layout is defined by a grid of 12 columns, each row height is equal to the column height. For example, say you want to show 2 panels at the top: one panel might be 6 x 3 (half the width, 3 rows height) located in row 1 and column 1 (top-left corner of the viewport), the second panel might be 6 x 3 located in row 1 and position 7. The location is specified by a dictionary of ``row`` (row position), ``col`` (column position), ``size_x`` (width), ``size_y`` (height). **Success Return Value** A dictionary showing the details of the edited dashboard. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_
sdcclient/_monitor_v1.py
def add_dashboard_panel(self, dashboard, name, panel_type, metrics, scope=None, sort_by=None, limit=None, layout=None): """**Description** Adds a panel to the dashboard. A panel can be a time series, or a top chart (i.e. bar chart), or a number panel. **Arguments** - **dashboard**: dashboard to edit - **name**: name of the new panel - **panel_type**: type of the new panel. Valid values are: ``timeSeries``, ``top``, ``number`` - **metrics**: a list of dictionaries, specifying the metrics to show in the panel, and optionally, if there is only one metric, a grouping key to segment that metric by. A metric is any of the entries that can be found in the *Metrics* section of the Explore page in Sysdig Monitor. Metric entries require an *aggregations* section specifying how to aggregate the metric across time and groups of containers/hosts. A grouping key is any of the entries that can be found in the *Show* or *Segment By* sections of the Explore page in Sysdig Monitor. Refer to the examples section below for ready to use code snippets. Note, certain panels allow certain combinations of metrics and grouping keys: - ``timeSeries``: 1 or more metrics OR 1 metric + 1 grouping key - ``top``: 1 or more metrics OR 1 metric + 1 grouping key - ``number``: 1 metric only - **scope**: filter to apply to the panel; must be based on metadata available in Sysdig Monitor; Example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **sort_by**: Data sorting; The parameter is optional and it's a dictionary of ``metric`` and ``mode`` (it can be ``desc`` or ``asc``) - **limit**: This parameter sets the limit on the number of lines/bars shown in a ``timeSeries`` or ``top`` panel. In the case of more entities being available than the limit, the top entities according to the sort will be shown. The default value is 10 for ``top`` panels (for ``timeSeries`` the default is defined by Sysdig Monitor itself). Note that increasing the limit above 10 is not officially supported and may cause performance and rendering issues - **layout**: Size and position of the panel. The dashboard layout is defined by a grid of 12 columns, each row height is equal to the column height. For example, say you want to show 2 panels at the top: one panel might be 6 x 3 (half the width, 3 rows height) located in row 1 and column 1 (top-left corner of the viewport), the second panel might be 6 x 3 located in row 1 and position 7. The location is specified by a dictionary of ``row`` (row position), ``col`` (column position), ``size_x`` (width), ``size_y`` (height). **Success Return Value** A dictionary showing the details of the edited dashboard. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_ """ panel_configuration = { 'name': name, 'showAs': None, 'showAsType': None, 'metrics': [], 'gridConfiguration': { 'col': 1, 'row': 1, 'size_x': 12, 'size_y': 6 } } if panel_type == 'timeSeries': # # In case of a time series, the current dashboard implementation # requires the timestamp to be explicitly specified as "key". # However, this function uses the same abstraction of the data API # that doesn't require to specify a timestamp key (you only need to # specify time window and sampling) # metrics = copy.copy(metrics) metrics.insert(0, {'id': 'timestamp'}) # # Convert list of metrics to format used by Sysdig Monitor # property_names = {} k_count = 0 v_count = 0 for i, metric in enumerate(metrics): property_name = 'v' if 'aggregations' in metric else 'k' if property_name == 'k': i = k_count k_count += 1 else: i = v_count v_count += 1 property_names[metric['id']] = property_name + str(i) panel_configuration['metrics'].append({ 'metricId': metric['id'], 'aggregation': metric['aggregations']['time'] if 'aggregations' in metric else None, 'groupAggregation': metric['aggregations']['group'] if 'aggregations' in metric else None, 'propertyName': property_name + str(i) }) panel_configuration['scope'] = scope # if chart scope is equal to dashboard scope, set it as non override panel_configuration['overrideFilter'] = ('scope' in dashboard and dashboard['scope'] != scope) or ('scope' not in dashboard and scope != None) # # Configure panel type # if panel_type == 'timeSeries': panel_configuration['showAs'] = 'timeSeries' panel_configuration['showAsType'] = 'line' if limit != None: panel_configuration['paging'] = { 'from': 0, 'to': limit - 1 } elif panel_type == 'number': panel_configuration['showAs'] = 'summary' panel_configuration['showAsType'] = 'summary' elif panel_type == 'top': panel_configuration['showAs'] = 'top' panel_configuration['showAsType'] = 'bars' if sort_by is None: panel_configuration['sorting'] = [{ 'id': 'v0', 'mode': 'desc' }] else: panel_configuration['sorting'] = [{ 'id': property_names[sort_by['metric']], 'mode': sort_by['mode'] }] if limit is None: panel_configuration['paging'] = { 'from': 0, 'to': 10 } else: panel_configuration['paging'] = { 'from': 0, 'to': limit - 1 } # # Configure layout # if layout != None: panel_configuration['gridConfiguration'] = layout # # Clone existing dashboard... # dashboard_configuration = copy.deepcopy(dashboard) dashboard_configuration['id'] = None # # ... and add the new panel # dashboard_configuration['items'].append(panel_configuration) # # Update dashboard # res = requests.put(self.url + self._dashboards_api_endpoint + '/' + str(dashboard['id']), headers=self.hdrs, data=json.dumps({'dashboard': dashboard_configuration}), verify=self.ssl_verify) return self._request_result(res)
def add_dashboard_panel(self, dashboard, name, panel_type, metrics, scope=None, sort_by=None, limit=None, layout=None): """**Description** Adds a panel to the dashboard. A panel can be a time series, or a top chart (i.e. bar chart), or a number panel. **Arguments** - **dashboard**: dashboard to edit - **name**: name of the new panel - **panel_type**: type of the new panel. Valid values are: ``timeSeries``, ``top``, ``number`` - **metrics**: a list of dictionaries, specifying the metrics to show in the panel, and optionally, if there is only one metric, a grouping key to segment that metric by. A metric is any of the entries that can be found in the *Metrics* section of the Explore page in Sysdig Monitor. Metric entries require an *aggregations* section specifying how to aggregate the metric across time and groups of containers/hosts. A grouping key is any of the entries that can be found in the *Show* or *Segment By* sections of the Explore page in Sysdig Monitor. Refer to the examples section below for ready to use code snippets. Note, certain panels allow certain combinations of metrics and grouping keys: - ``timeSeries``: 1 or more metrics OR 1 metric + 1 grouping key - ``top``: 1 or more metrics OR 1 metric + 1 grouping key - ``number``: 1 metric only - **scope**: filter to apply to the panel; must be based on metadata available in Sysdig Monitor; Example: *kubernetes.namespace.name='production' and container.image='nginx'*. - **sort_by**: Data sorting; The parameter is optional and it's a dictionary of ``metric`` and ``mode`` (it can be ``desc`` or ``asc``) - **limit**: This parameter sets the limit on the number of lines/bars shown in a ``timeSeries`` or ``top`` panel. In the case of more entities being available than the limit, the top entities according to the sort will be shown. The default value is 10 for ``top`` panels (for ``timeSeries`` the default is defined by Sysdig Monitor itself). Note that increasing the limit above 10 is not officially supported and may cause performance and rendering issues - **layout**: Size and position of the panel. The dashboard layout is defined by a grid of 12 columns, each row height is equal to the column height. For example, say you want to show 2 panels at the top: one panel might be 6 x 3 (half the width, 3 rows height) located in row 1 and column 1 (top-left corner of the viewport), the second panel might be 6 x 3 located in row 1 and position 7. The location is specified by a dictionary of ``row`` (row position), ``col`` (column position), ``size_x`` (width), ``size_y`` (height). **Success Return Value** A dictionary showing the details of the edited dashboard. **Example** `examples/dashboard.py <https://github.com/draios/python-sdc-client/blob/master/examples/dashboard.py>`_ """ panel_configuration = { 'name': name, 'showAs': None, 'showAsType': None, 'metrics': [], 'gridConfiguration': { 'col': 1, 'row': 1, 'size_x': 12, 'size_y': 6 } } if panel_type == 'timeSeries': # # In case of a time series, the current dashboard implementation # requires the timestamp to be explicitly specified as "key". # However, this function uses the same abstraction of the data API # that doesn't require to specify a timestamp key (you only need to # specify time window and sampling) # metrics = copy.copy(metrics) metrics.insert(0, {'id': 'timestamp'}) # # Convert list of metrics to format used by Sysdig Monitor # property_names = {} k_count = 0 v_count = 0 for i, metric in enumerate(metrics): property_name = 'v' if 'aggregations' in metric else 'k' if property_name == 'k': i = k_count k_count += 1 else: i = v_count v_count += 1 property_names[metric['id']] = property_name + str(i) panel_configuration['metrics'].append({ 'metricId': metric['id'], 'aggregation': metric['aggregations']['time'] if 'aggregations' in metric else None, 'groupAggregation': metric['aggregations']['group'] if 'aggregations' in metric else None, 'propertyName': property_name + str(i) }) panel_configuration['scope'] = scope # if chart scope is equal to dashboard scope, set it as non override panel_configuration['overrideFilter'] = ('scope' in dashboard and dashboard['scope'] != scope) or ('scope' not in dashboard and scope != None) # # Configure panel type # if panel_type == 'timeSeries': panel_configuration['showAs'] = 'timeSeries' panel_configuration['showAsType'] = 'line' if limit != None: panel_configuration['paging'] = { 'from': 0, 'to': limit - 1 } elif panel_type == 'number': panel_configuration['showAs'] = 'summary' panel_configuration['showAsType'] = 'summary' elif panel_type == 'top': panel_configuration['showAs'] = 'top' panel_configuration['showAsType'] = 'bars' if sort_by is None: panel_configuration['sorting'] = [{ 'id': 'v0', 'mode': 'desc' }] else: panel_configuration['sorting'] = [{ 'id': property_names[sort_by['metric']], 'mode': sort_by['mode'] }] if limit is None: panel_configuration['paging'] = { 'from': 0, 'to': 10 } else: panel_configuration['paging'] = { 'from': 0, 'to': limit - 1 } # # Configure layout # if layout != None: panel_configuration['gridConfiguration'] = layout # # Clone existing dashboard... # dashboard_configuration = copy.deepcopy(dashboard) dashboard_configuration['id'] = None # # ... and add the new panel # dashboard_configuration['items'].append(panel_configuration) # # Update dashboard # res = requests.put(self.url + self._dashboards_api_endpoint + '/' + str(dashboard['id']), headers=self.hdrs, data=json.dumps({'dashboard': dashboard_configuration}), verify=self.ssl_verify) return self._request_result(res)
[ "**", "Description", "**", "Adds", "a", "panel", "to", "the", "dashboard", ".", "A", "panel", "can", "be", "a", "time", "series", "or", "a", "top", "chart", "(", "i", ".", "e", ".", "bar", "chart", ")", "or", "a", "number", "panel", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor_v1.py#L108-L247
[ "def", "add_dashboard_panel", "(", "self", ",", "dashboard", ",", "name", ",", "panel_type", ",", "metrics", ",", "scope", "=", "None", ",", "sort_by", "=", "None", ",", "limit", "=", "None", ",", "layout", "=", "None", ")", ":", "panel_configuration", "=", "{", "'name'", ":", "name", ",", "'showAs'", ":", "None", ",", "'showAsType'", ":", "None", ",", "'metrics'", ":", "[", "]", ",", "'gridConfiguration'", ":", "{", "'col'", ":", "1", ",", "'row'", ":", "1", ",", "'size_x'", ":", "12", ",", "'size_y'", ":", "6", "}", "}", "if", "panel_type", "==", "'timeSeries'", ":", "#", "# In case of a time series, the current dashboard implementation", "# requires the timestamp to be explicitly specified as \"key\".", "# However, this function uses the same abstraction of the data API", "# that doesn't require to specify a timestamp key (you only need to", "# specify time window and sampling)", "#", "metrics", "=", "copy", ".", "copy", "(", "metrics", ")", "metrics", ".", "insert", "(", "0", ",", "{", "'id'", ":", "'timestamp'", "}", ")", "#", "# Convert list of metrics to format used by Sysdig Monitor", "#", "property_names", "=", "{", "}", "k_count", "=", "0", "v_count", "=", "0", "for", "i", ",", "metric", "in", "enumerate", "(", "metrics", ")", ":", "property_name", "=", "'v'", "if", "'aggregations'", "in", "metric", "else", "'k'", "if", "property_name", "==", "'k'", ":", "i", "=", "k_count", "k_count", "+=", "1", "else", ":", "i", "=", "v_count", "v_count", "+=", "1", "property_names", "[", "metric", "[", "'id'", "]", "]", "=", "property_name", "+", "str", "(", "i", ")", "panel_configuration", "[", "'metrics'", "]", ".", "append", "(", "{", "'metricId'", ":", "metric", "[", "'id'", "]", ",", "'aggregation'", ":", "metric", "[", "'aggregations'", "]", "[", "'time'", "]", "if", "'aggregations'", "in", "metric", "else", "None", ",", "'groupAggregation'", ":", "metric", "[", "'aggregations'", "]", "[", "'group'", "]", "if", "'aggregations'", "in", "metric", "else", "None", ",", "'propertyName'", ":", "property_name", "+", "str", "(", "i", ")", "}", ")", "panel_configuration", "[", "'scope'", "]", "=", "scope", "# if chart scope is equal to dashboard scope, set it as non override", "panel_configuration", "[", "'overrideFilter'", "]", "=", "(", "'scope'", "in", "dashboard", "and", "dashboard", "[", "'scope'", "]", "!=", "scope", ")", "or", "(", "'scope'", "not", "in", "dashboard", "and", "scope", "!=", "None", ")", "#", "# Configure panel type", "#", "if", "panel_type", "==", "'timeSeries'", ":", "panel_configuration", "[", "'showAs'", "]", "=", "'timeSeries'", "panel_configuration", "[", "'showAsType'", "]", "=", "'line'", "if", "limit", "!=", "None", ":", "panel_configuration", "[", "'paging'", "]", "=", "{", "'from'", ":", "0", ",", "'to'", ":", "limit", "-", "1", "}", "elif", "panel_type", "==", "'number'", ":", "panel_configuration", "[", "'showAs'", "]", "=", "'summary'", "panel_configuration", "[", "'showAsType'", "]", "=", "'summary'", "elif", "panel_type", "==", "'top'", ":", "panel_configuration", "[", "'showAs'", "]", "=", "'top'", "panel_configuration", "[", "'showAsType'", "]", "=", "'bars'", "if", "sort_by", "is", "None", ":", "panel_configuration", "[", "'sorting'", "]", "=", "[", "{", "'id'", ":", "'v0'", ",", "'mode'", ":", "'desc'", "}", "]", "else", ":", "panel_configuration", "[", "'sorting'", "]", "=", "[", "{", "'id'", ":", "property_names", "[", "sort_by", "[", "'metric'", "]", "]", ",", "'mode'", ":", "sort_by", "[", "'mode'", "]", "}", "]", "if", "limit", "is", "None", ":", "panel_configuration", "[", "'paging'", "]", "=", "{", "'from'", ":", "0", ",", "'to'", ":", "10", "}", "else", ":", "panel_configuration", "[", "'paging'", "]", "=", "{", "'from'", ":", "0", ",", "'to'", ":", "limit", "-", "1", "}", "#", "# Configure layout", "#", "if", "layout", "!=", "None", ":", "panel_configuration", "[", "'gridConfiguration'", "]", "=", "layout", "#", "# Clone existing dashboard...", "#", "dashboard_configuration", "=", "copy", ".", "deepcopy", "(", "dashboard", ")", "dashboard_configuration", "[", "'id'", "]", "=", "None", "#", "# ... and add the new panel", "#", "dashboard_configuration", "[", "'items'", "]", ".", "append", "(", "panel_configuration", ")", "#", "# Update dashboard", "#", "res", "=", "requests", ".", "put", "(", "self", ".", "url", "+", "self", ".", "_dashboards_api_endpoint", "+", "'/'", "+", "str", "(", "dashboard", "[", "'id'", "]", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "data", "=", "json", ".", "dumps", "(", "{", "'dashboard'", ":", "dashboard_configuration", "}", ")", ",", "verify", "=", "self", ".", "ssl_verify", ")", "return", "self", ".", "_request_result", "(", "res", ")" ]
47f83415842048778939b90944f64386a3bcb205
test
SdScanningClient.add_image
**Description** Add an image to the scanner **Arguments** - image: Input image can be in the following formats: registry/repo:tag - dockerfile: The contents of the dockerfile as a str. - annotations: A dictionary of annotations {str: str}. - autosubscribe: Should active the subscription to this image? **Success Return Value** A JSON object representing the image that was added.
sdcclient/_scanning.py
def add_image(self, image, force=False, dockerfile=None, annotations={}, autosubscribe=True): '''**Description** Add an image to the scanner **Arguments** - image: Input image can be in the following formats: registry/repo:tag - dockerfile: The contents of the dockerfile as a str. - annotations: A dictionary of annotations {str: str}. - autosubscribe: Should active the subscription to this image? **Success Return Value** A JSON object representing the image that was added. ''' itype = self._discover_inputimage_format(image) if itype != 'tag': return [False, "can only add a tag"] payload = {} if dockerfile: payload['dockerfile'] = base64.b64encode(dockerfile.encode()).decode("utf-8") payload['tag'] = image if annotations: payload['annotations'] = annotations url = "{base_url}/api/scanning/v1/anchore/images?autosubscribe={autosubscribe}{force}".format( base_url=self.url, autosubscribe=str(autosubscribe), force="&force=true" if force else "") res = requests.post(url, data=json.dumps(payload), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, res.json()]
def add_image(self, image, force=False, dockerfile=None, annotations={}, autosubscribe=True): '''**Description** Add an image to the scanner **Arguments** - image: Input image can be in the following formats: registry/repo:tag - dockerfile: The contents of the dockerfile as a str. - annotations: A dictionary of annotations {str: str}. - autosubscribe: Should active the subscription to this image? **Success Return Value** A JSON object representing the image that was added. ''' itype = self._discover_inputimage_format(image) if itype != 'tag': return [False, "can only add a tag"] payload = {} if dockerfile: payload['dockerfile'] = base64.b64encode(dockerfile.encode()).decode("utf-8") payload['tag'] = image if annotations: payload['annotations'] = annotations url = "{base_url}/api/scanning/v1/anchore/images?autosubscribe={autosubscribe}{force}".format( base_url=self.url, autosubscribe=str(autosubscribe), force="&force=true" if force else "") res = requests.post(url, data=json.dumps(payload), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, res.json()]
[ "**", "Description", "**", "Add", "an", "image", "to", "the", "scanner" ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_scanning.py#L22-L55
[ "def", "add_image", "(", "self", ",", "image", ",", "force", "=", "False", ",", "dockerfile", "=", "None", ",", "annotations", "=", "{", "}", ",", "autosubscribe", "=", "True", ")", ":", "itype", "=", "self", ".", "_discover_inputimage_format", "(", "image", ")", "if", "itype", "!=", "'tag'", ":", "return", "[", "False", ",", "\"can only add a tag\"", "]", "payload", "=", "{", "}", "if", "dockerfile", ":", "payload", "[", "'dockerfile'", "]", "=", "base64", ".", "b64encode", "(", "dockerfile", ".", "encode", "(", ")", ")", ".", "decode", "(", "\"utf-8\"", ")", "payload", "[", "'tag'", "]", "=", "image", "if", "annotations", ":", "payload", "[", "'annotations'", "]", "=", "annotations", "url", "=", "\"{base_url}/api/scanning/v1/anchore/images?autosubscribe={autosubscribe}{force}\"", ".", "format", "(", "base_url", "=", "self", ".", "url", ",", "autosubscribe", "=", "str", "(", "autosubscribe", ")", ",", "force", "=", "\"&force=true\"", "if", "force", "else", "\"\"", ")", "res", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "payload", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "return", "[", "True", ",", "res", ".", "json", "(", ")", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdScanningClient.import_image
**Description** Import an image from the scanner export **Arguments** - image_data: A JSON with the image information. **Success Return Value** A JSON object representing the image that was imported.
sdcclient/_scanning.py
def import_image(self, image_data): '''**Description** Import an image from the scanner export **Arguments** - image_data: A JSON with the image information. **Success Return Value** A JSON object representing the image that was imported. ''' url = self.url + "/api/scanning/v1/anchore/imageimport" res = requests.post(url, data=json.dumps(image_data), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, res.json()]
def import_image(self, image_data): '''**Description** Import an image from the scanner export **Arguments** - image_data: A JSON with the image information. **Success Return Value** A JSON object representing the image that was imported. ''' url = self.url + "/api/scanning/v1/anchore/imageimport" res = requests.post(url, data=json.dumps(image_data), headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, res.json()]
[ "**", "Description", "**", "Import", "an", "image", "from", "the", "scanner", "export" ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_scanning.py#L57-L72
[ "def", "import_image", "(", "self", ",", "image_data", ")", ":", "url", "=", "self", ".", "url", "+", "\"/api/scanning/v1/anchore/imageimport\"", "res", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "image_data", ")", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "return", "[", "True", ",", "res", ".", "json", "(", ")", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdScanningClient.get_image
**Description** Find the image with the tag <image> and return its json description **Arguments** - image: Input image can be in the following formats: registry/repo:tag **Success Return Value** A JSON object representing the image.
sdcclient/_scanning.py
def get_image(self, image, show_history=False): '''**Description** Find the image with the tag <image> and return its json description **Arguments** - image: Input image can be in the following formats: registry/repo:tag **Success Return Value** A JSON object representing the image. ''' itype = self._discover_inputimage_format(image) if itype not in ['tag', 'imageid', 'imageDigest']: return [False, "cannot use input image string: no discovered imageDigest"] params = {} params['history'] = str(show_history and itype not in ['imageid', 'imageDigest']).lower() if itype == 'tag': params['fulltag'] = image url = self.url + "/api/scanning/v1/anchore/images" url += { 'imageid': '/by_id/{}'.format(image), 'imageDigest': '/{}'.format(image) }.get(itype, '') res = requests.get(url, params=params, headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, res.json()]
def get_image(self, image, show_history=False): '''**Description** Find the image with the tag <image> and return its json description **Arguments** - image: Input image can be in the following formats: registry/repo:tag **Success Return Value** A JSON object representing the image. ''' itype = self._discover_inputimage_format(image) if itype not in ['tag', 'imageid', 'imageDigest']: return [False, "cannot use input image string: no discovered imageDigest"] params = {} params['history'] = str(show_history and itype not in ['imageid', 'imageDigest']).lower() if itype == 'tag': params['fulltag'] = image url = self.url + "/api/scanning/v1/anchore/images" url += { 'imageid': '/by_id/{}'.format(image), 'imageDigest': '/{}'.format(image) }.get(itype, '') res = requests.get(url, params=params, headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, res.json()]
[ "**", "Description", "**", "Find", "the", "image", "with", "the", "tag", "<image", ">", "and", "return", "its", "json", "description" ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_scanning.py#L74-L103
[ "def", "get_image", "(", "self", ",", "image", ",", "show_history", "=", "False", ")", ":", "itype", "=", "self", ".", "_discover_inputimage_format", "(", "image", ")", "if", "itype", "not", "in", "[", "'tag'", ",", "'imageid'", ",", "'imageDigest'", "]", ":", "return", "[", "False", ",", "\"cannot use input image string: no discovered imageDigest\"", "]", "params", "=", "{", "}", "params", "[", "'history'", "]", "=", "str", "(", "show_history", "and", "itype", "not", "in", "[", "'imageid'", ",", "'imageDigest'", "]", ")", ".", "lower", "(", ")", "if", "itype", "==", "'tag'", ":", "params", "[", "'fulltag'", "]", "=", "image", "url", "=", "self", ".", "url", "+", "\"/api/scanning/v1/anchore/images\"", "url", "+=", "{", "'imageid'", ":", "'/by_id/{}'", ".", "format", "(", "image", ")", ",", "'imageDigest'", ":", "'/{}'", ".", "format", "(", "image", ")", "}", ".", "get", "(", "itype", ",", "''", ")", "res", "=", "requests", ".", "get", "(", "url", ",", "params", "=", "params", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "if", "not", "self", ".", "_checkResponse", "(", "res", ")", ":", "return", "[", "False", ",", "self", ".", "lasterr", "]", "return", "[", "True", ",", "res", ".", "json", "(", ")", "]" ]
47f83415842048778939b90944f64386a3bcb205
test
SdScanningClient.query_image_content
**Description** Find the image with the tag <image> and return its content. **Arguments** - image: Input image can be in the following formats: registry/repo:tag - content_type: The content type can be one of the following types: - os: Operating System Packages - npm: Node.JS NPM Module - gem: Ruby GEM - files: Files **Success Return Value** A JSON object representing the image content.
sdcclient/_scanning.py
def query_image_content(self, image, content_type=""): '''**Description** Find the image with the tag <image> and return its content. **Arguments** - image: Input image can be in the following formats: registry/repo:tag - content_type: The content type can be one of the following types: - os: Operating System Packages - npm: Node.JS NPM Module - gem: Ruby GEM - files: Files **Success Return Value** A JSON object representing the image content. ''' return self._query_image(image, query_group='content', query_type=content_type)
def query_image_content(self, image, content_type=""): '''**Description** Find the image with the tag <image> and return its content. **Arguments** - image: Input image can be in the following formats: registry/repo:tag - content_type: The content type can be one of the following types: - os: Operating System Packages - npm: Node.JS NPM Module - gem: Ruby GEM - files: Files **Success Return Value** A JSON object representing the image content. ''' return self._query_image(image, query_group='content', query_type=content_type)
[ "**", "Description", "**", "Find", "the", "image", "with", "the", "tag", "<image", ">", "and", "return", "its", "content", "." ]
draios/python-sdc-client
python
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_scanning.py#L122-L137
[ "def", "query_image_content", "(", "self", ",", "image", ",", "content_type", "=", "\"\"", ")", ":", "return", "self", ".", "_query_image", "(", "image", ",", "query_group", "=", "'content'", ",", "query_type", "=", "content_type", ")" ]
47f83415842048778939b90944f64386a3bcb205