INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Returns:
If download over TUF and in-toto is successful, this function will
return the complete filepath to the desired target. | def download(self, target_relpath, download_in_toto_metadata=True):
'''
Returns:
If download over TUF and in-toto is successful, this function will
return the complete filepath to the desired target.
'''
return self.__get_target(target_relpath, download_in_toto_me... |
NOTE: We assume that all the public keys needed to verify any in-toto
root layout, or sublayout, metadata file has been directly signed by
the top-level TUF targets role using *OFFLINE* keys. This is a
reasonable assumption, as TUF does not offer meaningful security
guarantees if _ALL_ t... | def __update_in_toto_layout_pubkeys(self):
'''
NOTE: We assume that all the public keys needed to verify any in-toto
root layout, or sublayout, metadata file has been directly signed by
the top-level TUF targets role using *OFFLINE* keys. This is a
reasonable assumption, as TUF d... |
Fetch WMI metrics. | def check(self, instance):
"""
Fetch WMI metrics.
"""
# Connection information
host = instance.get('host', "localhost")
namespace = instance.get('namespace', "root\\cimv2")
provider = instance.get('provider')
username = instance.get('username', "")
... |
Remove all configuration for environments. | def prune(force):
"""Remove all configuration for environments."""
if not force:
echo_warning(
'Removing configuration of environments that may be in use will leave '
'them in a potentially unusable state. If you wish to proceed (e.g. you '
'have just restarted your m... |
Create a copy of the instance and set default values.
This is so the base class can create a scraper_config with the proper values. | def _create_kubelet_prometheus_instance(self, instance):
"""
Create a copy of the instance and set default values.
This is so the base class can create a scraper_config with the proper values.
"""
kubelet_instance = deepcopy(instance)
kubelet_instance.update(
... |
Perform and return a GET request against kubelet. Support auth and TLS validation. | def perform_kubelet_query(self, url, verbose=True, timeout=10, stream=False):
"""
Perform and return a GET request against kubelet. Support auth and TLS validation.
"""
return requests.get(
url,
timeout=timeout,
verify=self.kubelet_credentials.verify()... |
Looks up the agent's kubernetes_pod_expiration_duration option and returns either:
- None if expiration is disabled (set to 0)
- A (timezone aware) datetime object to compare against | def _compute_pod_expiration_datetime():
"""
Looks up the agent's kubernetes_pod_expiration_duration option and returns either:
- None if expiration is disabled (set to 0)
- A (timezone aware) datetime object to compare against
"""
try:
seconds = int(get_co... |
Reports the number of running pods on this node and the running
containers in pods, tagged by service and creator.
:param pods: pod list object
:param instance_tags: list of tags | def _report_pods_running(self, pods, instance_tags):
"""
Reports the number of running pods on this node and the running
containers in pods, tagged by service and creator.
:param pods: pod list object
:param instance_tags: list of tags
"""
pods_tag_counter = defa... |
Reports pod requests & limits by looking at pod specs. | def _report_container_spec_metrics(self, pod_list, instance_tags):
"""Reports pod requests & limits by looking at pod specs."""
for pod in pod_list['items']:
pod_name = pod.get('metadata', {}).get('name')
pod_phase = pod.get('status', {}).get('phase')
if self._should_... |
Reports container state & reasons by looking at container statuses | def _report_container_state_metrics(self, pod_list, instance_tags):
"""Reports container state & reasons by looking at container statuses"""
if pod_list.get('expired_count'):
self.gauge(self.NAMESPACE + '.pods.expired', pod_list.get('expired_count'), tags=instance_tags)
for pod in p... |
Parse quantity allows to convert the value in the resources spec like:
resources:
requests:
cpu: "100m"
memory": "200Mi"
limits:
memory: "300Mi"
:param string: str
:return: float | def parse_quantity(string):
"""
Parse quantity allows to convert the value in the resources spec like:
resources:
requests:
cpu: "100m"
memory": "200Mi"
limits:
memory: "300Mi"
:param string: str
:return: float
"""
... |
Convert a socket.error to ConnectionFailure and raise it. | def _raise_connection_failure(address, error):
"""Convert a socket.error to ConnectionFailure and raise it."""
host, port = address
# If connecting to a Unix socket, port will be None.
if port is not None:
msg = '%s:%d: %s' % (host, port, error)
else:
msg = '%s: %s' % (host, error)
... |
Given (host, port) and PoolOptions, connect and return a socket object.
Can raise socket.error.
This is a modified version of create_connection from CPython >= 2.6. | def _create_connection(address, options):
"""Given (host, port) and PoolOptions, connect and return a socket object.
Can raise socket.error.
This is a modified version of create_connection from CPython >= 2.6.
"""
host, port = address
# Check if dealing with a unix domain socket
if host.e... |
Given (host, port) and PoolOptions, return a configured socket.
Can raise socket.error, ConnectionFailure, or CertificateError.
Sets socket's SSL and timeout options. | def _configured_socket(address, options):
"""Given (host, port) and PoolOptions, return a configured socket.
Can raise socket.error, ConnectionFailure, or CertificateError.
Sets socket's SSL and timeout options.
"""
sock = _create_connection(address, options)
ssl_context = options.ssl_context
... |
Execute a command or raise ConnectionFailure or OperationFailure.
:Parameters:
- `dbname`: name of the database on which to run the command
- `spec`: a command document as a dict, SON, or mapping object
- `slave_ok`: whether to set the SlaveOkay wire protocol bit
- `read... | def command(self, dbname, spec, slave_ok=False,
read_preference=ReadPreference.PRIMARY,
codec_options=DEFAULT_CODEC_OPTIONS, check=True,
allowable_errors=None, check_keys=False,
read_concern=DEFAULT_READ_CONCERN,
write_concern=None,
... |
Send a raw BSON message or raise ConnectionFailure.
If a network exception is raised, the socket is closed. | def send_message(self, message, max_doc_size):
"""Send a raw BSON message or raise ConnectionFailure.
If a network exception is raised, the socket is closed.
"""
if (self.max_bson_size is not None
and max_doc_size > self.max_bson_size):
raise DocumentTooLarge... |
Receive a raw BSON message or raise ConnectionFailure.
If any exception is raised, the socket is closed. | def receive_message(self, operation, request_id):
"""Receive a raw BSON message or raise ConnectionFailure.
If any exception is raised, the socket is closed.
"""
try:
return receive_message(
self.sock, operation, request_id, self.max_message_size)
exc... |
Send OP_INSERT, etc., optionally returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, an OP_INSERT, OP_UPDATE, or OP_DELETE message,
perhaps with a getlasterror command appended.
- ... | def legacy_write(self, request_id, msg, max_doc_size, with_last_error):
"""Send OP_INSERT, etc., optionally returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, an OP_INSERT, OP_UPDATE, or OP_DEL... |
Send "insert" etc. command, returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, the command message. | def write_command(self, request_id, msg):
"""Send "insert" etc. command, returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, the command message.
"""
self.send_message(msg, 0)
... |
Update this socket's authentication.
Log in or out to bring this socket's credentials up to date with
those provided. Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `all_credentials`: dict, maps auth source to MongoCredential. | def check_auth(self, all_credentials):
"""Update this socket's authentication.
Log in or out to bring this socket's credentials up to date with
those provided. Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `all_credentials`: dict, maps auth source to MongoCr... |
Log in to the server and store these credentials in `authset`.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `credentials`: A MongoCredential. | def authenticate(self, credentials):
"""Log in to the server and store these credentials in `authset`.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `credentials`: A MongoCredential.
"""
auth.authenticate(credentials, self)
self.authset.add(c... |
Connect to Mongo and return a new SocketInfo.
Can raise ConnectionFailure or CertificateError.
Note that the pool does not keep a reference to the socket -- you
must call return_socket() when you're done with it. | def connect(self):
"""Connect to Mongo and return a new SocketInfo.
Can raise ConnectionFailure or CertificateError.
Note that the pool does not keep a reference to the socket -- you
must call return_socket() when you're done with it.
"""
sock = None
try:
... |
Get a socket from the pool. Use with a "with" statement.
Returns a :class:`SocketInfo` object wrapping a connected
:class:`socket.socket`.
This method should always be used in a with-statement::
with pool.get_socket(credentials, checkout) as socket_info:
socket_inf... | def get_socket(self, all_credentials, checkout=False):
"""Get a socket from the pool. Use with a "with" statement.
Returns a :class:`SocketInfo` object wrapping a connected
:class:`socket.socket`.
This method should always be used in a with-statement::
with pool.get_socket... |
Get or create a SocketInfo. Can raise ConnectionFailure. | def _get_socket_no_auth(self):
"""Get or create a SocketInfo. Can raise ConnectionFailure."""
# We use the pid here to avoid issues with fork / multiprocessing.
# See test.test_client:TestClient.test_fork for an example of
# what could go wrong otherwise
if self.pid != os.getpid(... |
Return the socket to the pool, or if it's closed discard it. | def return_socket(self, sock_info):
"""Return the socket to the pool, or if it's closed discard it."""
if self.pid != os.getpid():
self.reset()
else:
if sock_info.pool_id != self.pool_id:
sock_info.close()
elif not sock_info.closed:
... |
This side-effecty function checks if this socket has been idle for
for longer than the max idle time, or if the socket has been closed by
some external network error, and if so, attempts to create a new
socket. If this connection attempt fails we raise the
ConnectionFailure.
Che... | def _check(self, sock_info):
"""This side-effecty function checks if this socket has been idle for
for longer than the max idle time, or if the socket has been closed by
some external network error, and if so, attempts to create a new
socket. If this connection attempt fails we raise the... |
This filters `items` by a regular expression `whitelist` and/or
`blacklist`, with the `blacklist` taking precedence. An optional `key`
function can be provided that will be passed each item. | def pattern_filter(items, whitelist=None, blacklist=None, key=None):
"""This filters `items` by a regular expression `whitelist` and/or
`blacklist`, with the `blacklist` taking precedence. An optional `key`
function can be provided that will be passed each item.
"""
key = key or __return_self
if... |
Return an updated copy of a TopologyDescription.
:Parameters:
- `topology_description`: the current TopologyDescription
- `server_description`: a new ServerDescription that resulted from
an ismaster call
Called after attempting (successfully or not) to call ismaster on the
server at se... | def updated_topology_description(topology_description, server_description):
"""Return an updated copy of a TopologyDescription.
:Parameters:
- `topology_description`: the current TopologyDescription
- `server_description`: a new ServerDescription that resulted from
an ismaster call
Cal... |
Update topology description from a primary's ismaster response.
Pass in a dict of ServerDescriptions, current replica set name, the
ServerDescription we are processing, and the TopologyDescription's
max_set_version and max_election_id if any.
Returns (new topology type, new replica_set_name, new max_s... | def _update_rs_from_primary(
sds,
replica_set_name,
server_description,
max_set_version,
max_election_id):
"""Update topology description from a primary's ismaster response.
Pass in a dict of ServerDescriptions, current replica set name, the
ServerDescription we are ... |
RS with known primary. Process a response from a non-primary.
Pass in a dict of ServerDescriptions, current replica set name, and the
ServerDescription we are processing.
Returns new topology type. | def _update_rs_with_primary_from_member(
sds,
replica_set_name,
server_description):
"""RS with known primary. Process a response from a non-primary.
Pass in a dict of ServerDescriptions, current replica set name, and the
ServerDescription we are processing.
Returns new topolog... |
RS without known primary. Update from a non-primary's response.
Pass in a dict of ServerDescriptions, current replica set name, and the
ServerDescription we are processing.
Returns (new topology type, new replica_set_name). | def _update_rs_no_primary_from_member(
sds,
replica_set_name,
server_description):
"""RS without known primary. Update from a non-primary's response.
Pass in a dict of ServerDescriptions, current replica set name, and the
ServerDescription we are processing.
Returns (new topolo... |
Current topology type is ReplicaSetWithPrimary. Is primary still known?
Pass in a dict of ServerDescriptions.
Returns new topology type. | def _check_has_primary(sds):
"""Current topology type is ReplicaSetWithPrimary. Is primary still known?
Pass in a dict of ServerDescriptions.
Returns new topology type.
"""
for s in sds.values():
if s.server_type == SERVER_TYPE.RSPrimary:
return TOPOLOGY_TYPE.ReplicaSetWithPrim... |
A copy of this description, with all servers marked Unknown. | def reset(self):
"""A copy of this description, with all servers marked Unknown."""
if self._topology_type == TOPOLOGY_TYPE.ReplicaSetWithPrimary:
topology_type = TOPOLOGY_TYPE.ReplicaSetNoPrimary
else:
topology_type = self._topology_type
# The default ServerDesc... |
Minimum of all servers' max wire versions, or None. | def common_wire_version(self):
"""Minimum of all servers' max wire versions, or None."""
servers = self.known_servers
if servers:
return min(s.max_wire_version for s in self.known_servers)
return None |
Does this topology have any readable servers available matching the
given read preference?
:Parameters:
- `read_preference`: an instance of a read preference from
:mod:`~pymongo.read_preferences`. Defaults to
:attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
... | def has_readable_server(self, read_preference=ReadPreference.PRIMARY):
"""Does this topology have any readable servers available matching the
given read preference?
:Parameters:
- `read_preference`: an instance of a read preference from
:mod:`~pymongo.read_preferences`. De... |
Human-friendly OS name | def get_os():
"""
Human-friendly OS name
"""
if sys.platform == 'darwin':
return 'mac'
elif sys.platform.find('freebsd') != -1:
return 'freebsd'
elif sys.platform.find('linux') != -1:
return 'linux'
elif sys.platform.find('win32') != -1:
return 'windows'
e... |
Return true if this is a BSD like operating system. | def is_bsd(name=None):
""" Return true if this is a BSD like operating system. """
name = name or sys.platform
return Platform.is_darwin(name) or Platform.is_freebsd(name) |
Return true if the platform is a unix, False otherwise. | def is_unix(name=None):
""" Return true if the platform is a unix, False otherwise. """
name = name or sys.platform
return Platform.is_darwin(name) or Platform.is_linux(name) or Platform.is_freebsd(name) |
Run the given subprocess command and return its output. Raise an Exception
if an error occurs.
:param command: The command to run. Using a list of strings is recommended. The command
will be run in a subprocess without using a shell, as such shell features like
shell pip... | def get_subprocess_output(command, log, raise_on_empty_output=True, log_debug=True):
"""
Run the given subprocess command and return its output. Raise an Exception
if an error occurs.
:param command: The command to run. Using a list of strings is recommended. The command
will be run... |
Show changes since a specific date. | def changes(since, out_file, eager):
"""Show changes since a specific date."""
root = get_root()
history_data = defaultdict(lambda: {'lines': deque(), 'releasers': set()})
with chdir(root):
result = run_command(
(
'git log "--pretty=format:%H %s" --date-order --date=... |
Generates a markdown file containing the list of checks that changed for a
given Agent release. Agent version numbers are derived inspecting tags on
`integrations-core` so running this tool might provide unexpected results
if the repo is not up to date with the Agent release process.
If neither `--sinc... | def changelog(since, to, write, force):
"""
Generates a markdown file containing the list of checks that changed for a
given Agent release. Agent version numbers are derived inspecting tags on
`integrations-core` so running this tool might provide unexpected results
if the repo is not up to date wit... |
Create an empty instance if it doesn't exist.
If the instance already exists, this is a noop. | def init_instance(self, key):
"""
Create an empty instance if it doesn't exist.
If the instance already exists, this is a noop.
"""
with self._lock:
if key not in self._metadata:
self._metadata[key] = {}
self._metric_ids[key] = [] |
Return whether a counter_id is present for a given instance key.
If the key is not in the cache, raises a KeyError. | def contains(self, key, counter_id):
"""
Return whether a counter_id is present for a given instance key.
If the key is not in the cache, raises a KeyError.
"""
with self._lock:
return counter_id in self._metadata[key] |
Store the metadata for the given instance key. | def set_metadata(self, key, metadata):
"""
Store the metadata for the given instance key.
"""
with self._lock:
self._metadata[key] = metadata |
Store the list of metric IDs we will want to collect for the given instance key | def set_metric_ids(self, key, metric_ids):
"""
Store the list of metric IDs we will want to collect for the given instance key
"""
with self._lock:
self._metric_ids[key] = metric_ids |
Return the metadata for the metric identified by `counter_id` for the given instance key.
If the key is not in the cache, raises a KeyError.
If there's no metric with the given counter_id, raises a MetadataNotFoundError. | def get_metadata(self, key, counter_id):
"""
Return the metadata for the metric identified by `counter_id` for the given instance key.
If the key is not in the cache, raises a KeyError.
If there's no metric with the given counter_id, raises a MetadataNotFoundError.
"""
wi... |
Validate `manifest.json` files. | def manifest(fix, include_extras):
"""Validate `manifest.json` files."""
all_guids = {}
root = get_root()
root_name = basepath(get_root())
ok_checks = 0
failed_checks = 0
fixed_checks = 0
echo_info("Validating all manifest.json files...")
for check_name in sorted(os.listdir(root)):... |
Map log levels to strings | def _get_py_loglevel(lvl):
"""
Map log levels to strings
"""
if not lvl:
lvl = 'INFO'
return LOG_LEVEL_MAP.get(lvl.upper(), logging.DEBUG) |
Initialize logging (set up forwarding to Go backend and sane defaults) | def init_logging():
"""
Initialize logging (set up forwarding to Go backend and sane defaults)
"""
# Forward to Go backend
logging.addLevelName(TRACE_LEVEL, 'TRACE')
logging.setLoggerClass(AgentLogger)
rootLogger = logging.getLogger()
rootLogger.addHandler(AgentLogHandler())
rootLogg... |
Read line-by-line and run callback on each line.
line_by_line: yield each time a callback has returned True
move_end: start from the last line of the log | def tail(self, line_by_line=True, move_end=True):
"""Read line-by-line and run callback on each line.
line_by_line: yield each time a callback has returned True
move_end: start from the last line of the log"""
try:
self._open_file(move_end=move_end)
while True:
... |
This utility provides a convenient way to safely set up and tear down arbitrary types of environments.
:param up: A custom setup callable.
:type up: ``callable``
:param down: A custom tear down callable.
:type down: ``callable``
:param sleep: Number of seconds to wait before yielding.
:type sle... | def environment_run(up, down, sleep=None, endpoints=None, conditions=None, env_vars=None, wrapper=None):
"""This utility provides a convenient way to safely set up and tear down arbitrary types of environments.
:param up: A custom setup callable.
:type up: ``callable``
:param down: A custom tear down c... |
Returns an amended copy of the proxies dictionary - used by `requests`,
it will disable the proxy if the uri provided is to be reached directly.
:param proxies A dict with existing proxies: `https`, `http`, and `no` are potential keys.
:param uri URI to determine if a proxy is necessary or not.
:param s... | def config_proxy_skip(proxies, uri, skip_proxy=False):
"""
Returns an amended copy of the proxies dictionary - used by `requests`,
it will disable the proxy if the uri provided is to be reached directly.
:param proxies A dict with existing proxies: `https`, `http`, and `no` are potential keys.
:para... |
Clear the connection pool and stop the monitor.
Reconnect with open(). | def close(self):
"""Clear the connection pool and stop the monitor.
Reconnect with open().
"""
if self._publish:
self._events.put((self._listener.publish_server_closed,
(self._description.address, self._topology_id)))
self._monitor.close... |
Send an unacknowledged message to MongoDB.
Can raise ConnectionFailure.
:Parameters:
- `message`: (request_id, data).
- `all_credentials`: dict, maps auth source to MongoCredential. | def send_message(self, message, all_credentials):
"""Send an unacknowledged message to MongoDB.
Can raise ConnectionFailure.
:Parameters:
- `message`: (request_id, data).
- `all_credentials`: dict, maps auth source to MongoCredential.
"""
_, data, max_doc_si... |
Send a message to MongoDB and return a Response object.
Can raise ConnectionFailure.
:Parameters:
- `operation`: A _Query or _GetMore object.
- `set_slave_okay`: Pass to operation.get_message.
- `all_credentials`: dict, maps auth source to MongoCredential.
- `li... | def send_message_with_response(
self,
operation,
set_slave_okay,
all_credentials,
listeners,
exhaust=False):
"""Send a message to MongoDB and return a Response object.
Can raise ConnectionFailure.
:Parameters:
- ... |
Return request_id, data, max_doc_size.
:Parameters:
- `message`: (request_id, data, max_doc_size) or (request_id, data) | def _split_message(self, message):
"""Return request_id, data, max_doc_size.
:Parameters:
- `message`: (request_id, data, max_doc_size) or (request_id, data)
"""
if len(message) == 3:
return message
else:
# get_more and kill_cursors messages don... |
A map of operation index to the _id of the upserted document. | def upserted_ids(self):
"""A map of operation index to the _id of the upserted document."""
self._raise_if_unacknowledged("upserted_ids")
if self.__bulk_api_result:
return dict((upsert["index"], upsert["_id"])
for upsert in self.bulk_api_result["upserted"]) |
Show the contents of the config file. | def show(all_keys):
"""Show the contents of the config file."""
if not config_file_exists():
echo_info('No config file found! Please try `ddev config restore`.')
else:
if all_keys:
echo_info(read_config_file().rstrip())
else:
echo_info(read_config_file_scrubbe... |
Assigns values to config file entries. If the value is omitted,
you will be prompted, with the input hidden if it is sensitive.
\b
$ ddev config set github.user foo
New setting:
[github]
user = "foo" | def set_value(ctx, key, value):
"""Assigns values to config file entries. If the value is omitted,
you will be prompted, with the input hidden if it is sensitive.
\b
$ ddev config set github.user foo
New setting:
[github]
user = "foo"
"""
scrubbing = False
if value is None:
... |
Return this instance's socket to the connection pool. | def close(self):
"""Return this instance's socket to the connection pool.
"""
if not self.__closed:
self.__closed = True
self.pool.return_socket(self.sock)
self.sock, self.pool = None, None |
Rewind this cursor to its unevaluated state.
Reset this cursor if it has been partially or completely evaluated.
Any options that are present on the cursor will remain in effect.
Future iterating performed on this cursor will cause new queries to
be sent to the server, even if the resul... | def rewind(self):
"""Rewind this cursor to its unevaluated state.
Reset this cursor if it has been partially or completely evaluated.
Any options that are present on the cursor will remain in effect.
Future iterating performed on this cursor will cause new queries to
be sent to ... |
Internal clone helper. | def _clone(self, deepcopy=True):
"""Internal clone helper."""
clone = self._clone_base()
values_to_clone = ("spec", "projection", "skip", "limit",
"max_time_ms", "max_await_time_ms", "comment",
"max", "min", "ordering", "explain", "hint",
... |
Closes this cursor. | def __die(self, synchronous=False):
"""Closes this cursor.
"""
if self.__id and not self.__killed:
if self.__exhaust and self.__exhaust_mgr:
# If this is an exhaust cursor and we haven't completely
# exhausted the result set we *must* close the socket
... |
Get the spec to use for a query. | def __query_spec(self):
"""Get the spec to use for a query.
"""
operators = self.__modifiers.copy()
if self.__ordering:
operators["$orderby"] = self.__ordering
if self.__explain:
operators["$explain"] = True
if self.__hint:
operators["$... |
Set arbitrary query flags using a bitmask.
To set the tailable flag:
cursor.add_option(2) | def add_option(self, mask):
"""Set arbitrary query flags using a bitmask.
To set the tailable flag:
cursor.add_option(2)
"""
if not isinstance(mask, int):
raise TypeError("mask must be an int")
self.__check_okay_to_chain()
if mask & _QUERY_OPTIONS["e... |
Unset arbitrary query flags using a bitmask.
To unset the tailable flag:
cursor.remove_option(2) | def remove_option(self, mask):
"""Unset arbitrary query flags using a bitmask.
To unset the tailable flag:
cursor.remove_option(2)
"""
if not isinstance(mask, int):
raise TypeError("mask must be an int")
self.__check_okay_to_chain()
if mask & _QUERY_... |
Limits the number of results to be returned by this cursor.
Raises :exc:`TypeError` if `limit` is not an integer. Raises
:exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor`
has already been used. The last `limit` applied to this cursor
takes precedence. A limit of ``0`` is e... | def limit(self, limit):
"""Limits the number of results to be returned by this cursor.
Raises :exc:`TypeError` if `limit` is not an integer. Raises
:exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor`
has already been used. The last `limit` applied to this cursor
take... |
Skips the first `skip` results of this cursor.
Raises :exc:`TypeError` if `skip` is not an integer. Raises
:exc:`ValueError` if `skip` is less than ``0``. Raises
:exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has
already been used. The last `skip` applied to this cursor... | def skip(self, skip):
"""Skips the first `skip` results of this cursor.
Raises :exc:`TypeError` if `skip` is not an integer. Raises
:exc:`ValueError` if `skip` is less than ``0``. Raises
:exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has
already been used. The l... |
Specifies a time limit for a query operation. If the specified
time is exceeded, the operation will be aborted and
:exc:`~pymongo.errors.ExecutionTimeout` is raised. If `max_time_ms`
is ``None`` no limit is applied.
Raises :exc:`TypeError` if `max_time_ms` is not an integer or ``None``.... | def max_time_ms(self, max_time_ms):
"""Specifies a time limit for a query operation. If the specified
time is exceeded, the operation will be aborted and
:exc:`~pymongo.errors.ExecutionTimeout` is raised. If `max_time_ms`
is ``None`` no limit is applied.
Raises :exc:`TypeError` ... |
Specifies a time limit for a getMore operation on a
:attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other
types of cursor max_await_time_ms is ignored.
Raises :exc:`TypeError` if `max_await_time_ms` is not an integer or
``None``. Raises :exc:`~pymongo.errors.InvalidOpe... | def max_await_time_ms(self, max_await_time_ms):
"""Specifies a time limit for a getMore operation on a
:attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other
types of cursor max_await_time_ms is ignored.
Raises :exc:`TypeError` if `max_await_time_ms` is not an integer o... |
Adds `max` operator that specifies upper bound for specific index.
:Parameters:
- `spec`: a list of field, limit pairs specifying the exclusive
upper bound for all keys of a specific index in order.
.. versionadded:: 2.7 | def max(self, spec):
"""Adds `max` operator that specifies upper bound for specific index.
:Parameters:
- `spec`: a list of field, limit pairs specifying the exclusive
upper bound for all keys of a specific index in order.
.. versionadded:: 2.7
"""
if not ... |
Adds `min` operator that specifies lower bound for specific index.
:Parameters:
- `spec`: a list of field, limit pairs specifying the inclusive
lower bound for all keys of a specific index in order.
.. versionadded:: 2.7 | def min(self, spec):
"""Adds `min` operator that specifies lower bound for specific index.
:Parameters:
- `spec`: a list of field, limit pairs specifying the inclusive
lower bound for all keys of a specific index in order.
.. versionadded:: 2.7
"""
if not ... |
Sorts this cursor's results.
Pass a field name and a direction, either
:data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`::
for doc in collection.find().sort('field', pymongo.ASCENDING):
print(doc)
To sort by multiple fields, pass a list of (key, direction) ... | def sort(self, key_or_list, direction=None):
"""Sorts this cursor's results.
Pass a field name and a direction, either
:data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`::
for doc in collection.find().sort('field', pymongo.ASCENDING):
print(doc)
To s... |
Get the size of the results set for this query.
Returns the number of documents in the results set for this query. Does
not take :meth:`limit` and :meth:`skip` into account by default - set
`with_limit_and_skip` to ``True`` if that is the desired behavior.
Raises :class:`~pymongo.errors... | def count(self, with_limit_and_skip=False):
"""Get the size of the results set for this query.
Returns the number of documents in the results set for this query. Does
not take :meth:`limit` and :meth:`skip` into account by default - set
`with_limit_and_skip` to ``True`` if that is the d... |
Get a list of distinct values for `key` among all documents
in the result set of this query.
Raises :class:`TypeError` if `key` is not an instance of
:class:`basestring` (:class:`str` in python 3).
The :meth:`distinct` method obeys the
:attr:`~pymongo.collection.Collection.read... | def distinct(self, key):
"""Get a list of distinct values for `key` among all documents
in the result set of this query.
Raises :class:`TypeError` if `key` is not an instance of
:class:`basestring` (:class:`str` in python 3).
The :meth:`distinct` method obeys the
:attr:... |
Returns an explain plan record for this cursor.
.. mongodoc:: explain | def explain(self):
"""Returns an explain plan record for this cursor.
.. mongodoc:: explain
"""
c = self.clone()
c.__explain = True
# always use a hard limit for explains
if c.__limit:
c.__limit = -abs(c.__limit)
return next(c) |
Adds a $where clause to this query.
The `code` argument must be an instance of :class:`basestring`
(:class:`str` in python 3) or :class:`~bson.code.Code`
containing a JavaScript expression. This expression will be
evaluated for each document scanned. Only those documents
for whi... | def where(self, code):
"""Adds a $where clause to this query.
The `code` argument must be an instance of :class:`basestring`
(:class:`str` in python 3) or :class:`~bson.code.Code`
containing a JavaScript expression. This expression will be
evaluated for each document scanned. On... |
Adds a :class:`~pymongo.collation.Collation` to this query.
This option is only supported on MongoDB 3.4 and above.
Raises :exc:`TypeError` if `collation` is not an instance of
:class:`~pymongo.collation.Collation` or a ``dict``. Raises
:exc:`~pymongo.errors.InvalidOperation` if this :... | def collation(self, collation):
"""Adds a :class:`~pymongo.collation.Collation` to this query.
This option is only supported on MongoDB 3.4 and above.
Raises :exc:`TypeError` if `collation` is not an instance of
:class:`~pymongo.collation.Collation` or a ``dict``. Raises
:exc:`... |
Send a query or getmore operation and handles the response.
If operation is ``None`` this is an exhaust cursor, which reads
the next result batch off the exhaust socket instead of
sending getMore messages to the server.
Can raise ConnectionFailure. | def __send_message(self, operation):
"""Send a query or getmore operation and handles the response.
If operation is ``None`` this is an exhaust cursor, which reads
the next result batch off the exhaust socket instead of
sending getMore messages to the server.
Can raise Connecti... |
Refreshes the cursor with more data from Mongo.
Returns the length of self.__data after refresh. Will exit early if
self.__data is already non-empty. Raises OperationFailure when the
cursor cannot be refreshed due to an error on the query. | def _refresh(self):
"""Refreshes the cursor with more data from Mongo.
Returns the length of self.__data after refresh. Will exit early if
self.__data is already non-empty. Raises OperationFailure when the
cursor cannot be refreshed due to an error on the query.
"""
if l... |
Advance the cursor. | def next(self):
"""Advance the cursor."""
if self.__empty:
raise StopIteration
if len(self.__data) or self._refresh():
if self.__manipulate:
_db = self.__collection.database
return _db._fix_outgoing(self.__data.popleft(),
... |
Deepcopy helper for the data dictionary or list.
Regular expressions cannot be deep copied but as they are immutable we
don't have to copy them when cloning. | def _deepcopy(self, x, memo=None):
"""Deepcopy helper for the data dictionary or list.
Regular expressions cannot be deep copied but as they are immutable we
don't have to copy them when cloning.
"""
if not hasattr(x, 'items'):
y, is_list, iterator = [], True, enumer... |
Decorator to catch and print the exceptions that happen within async tasks.
Note: this should be applied to methods of VSphereCheck only! | def trace_method(method):
"""
Decorator to catch and print the exceptions that happen within async tasks.
Note: this should be applied to methods of VSphereCheck only!
"""
def wrapper(*args, **kwargs):
try:
method(*args, **kwargs)
except Exception:
args[0].pr... |
Print exceptions happening in separate threads
Prevent from logging a ton of them if a potentially big number of them fail the same way | def print_exception(self, msg):
""" Print exceptions happening in separate threads
Prevent from logging a ton of them if a potentially big number of them fail the same way
"""
if self.exception_printed < 10:
self.log.error(msg)
self.exception_printed += 1 |
Compare the available metrics for one MOR we have computed and intersect them
with the set of metrics we want to report | def _compute_needed_metrics(self, instance, available_metrics):
""" Compare the available metrics for one MOR we have computed and intersect them
with the set of metrics we want to report
"""
i_key = self._instance_key(instance)
if self.in_compatibility_mode(instance):
... |
Returns a list of tags for every host that is detected by the vSphere
integration.
Returns a list of pairs (hostname, {'SOURCE_TYPE: list_of_tags},) | def get_external_host_tags(self):
"""
Returns a list of tags for every host that is detected by the vSphere
integration.
Returns a list of pairs (hostname, {'SOURCE_TYPE: list_of_tags},)
"""
self.log.debug("Sending external_host_tags now")
external_host_tags = []... |
Explore vCenter infrastructure to discover hosts, virtual machines, etc.
and compute their associated tags.
Start at the vCenter `rootFolder`, so as to collect every objet.
Example topology:
```
rootFolder
- datacenter1
- compute_resou... | def _get_all_objs(
self, server_instance, regexes=None, include_only_marked=False, tags=None, use_guest_hostname=False
):
"""
Explore vCenter infrastructure to discover hosts, virtual machines, etc.
and compute their associated tags.
Start at the vCenter `rootFolder`, so as t... |
Return `True` if the given host or virtual machine is excluded by the user configuration,
i.e. violates any of the following rules:
* Do not match the corresponding `*_include_only` regular expressions
* Is "non-labeled" while `include_only_marked` is enabled (virtual machine only) | def _is_excluded(obj, properties, regexes, include_only_marked):
"""
Return `True` if the given host or virtual machine is excluded by the user configuration,
i.e. violates any of the following rules:
* Do not match the corresponding `*_include_only` regular expressions
* Is "non... |
Fill the Mor objects queue that will be asynchronously processed later.
Resolve the vCenter `rootFolder` and initiate hosts and virtual machines
discovery. | def _cache_morlist_raw(self, instance):
"""
Fill the Mor objects queue that will be asynchronously processed later.
Resolve the vCenter `rootFolder` and initiate hosts and virtual machines
discovery.
"""
i_key = self._instance_key(instance)
self.log.debug("Caching... |
Process a batch of items popped from the objects queue by querying the available
metrics for these MORs and then putting them in the Mor cache | def _process_mor_objects_queue_async(self, instance, mors):
"""
Process a batch of items popped from the objects queue by querying the available
metrics for these MORs and then putting them in the Mor cache
"""
t = time.time()
i_key = self._instance_key(instance)
... |
Pops `batch_morlist_size` items from the mor objects queue and run asynchronously
the _process_mor_objects_queue_async method to fill the Mor cache. | def _process_mor_objects_queue(self, instance):
"""
Pops `batch_morlist_size` items from the mor objects queue and run asynchronously
the _process_mor_objects_queue_async method to fill the Mor cache.
"""
i_key = self._instance_key(instance)
self.mor_cache.init_instance(i... |
Get all the performance counters metadata meaning name/group/description...
from the server instance, attached with the corresponding ID | def _cache_metrics_metadata(self, instance):
"""
Get all the performance counters metadata meaning name/group/description...
from the server instance, attached with the corresponding ID
"""
# ## <TEST-INSTRUMENTATION>
t = Timer()
# ## </TEST-INSTRUMENTATION>
... |
Given the counter_id, look up for the metrics metadata to check the vsphere
type of the counter and apply pre-reporting transformation if needed. | def _transform_value(self, instance, counter_id, value):
""" Given the counter_id, look up for the metrics metadata to check the vsphere
type of the counter and apply pre-reporting transformation if needed.
"""
i_key = self._instance_key(instance)
try:
metadata = self... |
Task that collects the metrics listed in the morlist for one MOR | def _collect_metrics_async(self, instance, query_specs):
""" Task that collects the metrics listed in the morlist for one MOR
"""
# ## <TEST-INSTRUMENTATION>
t = Timer()
# ## </TEST-INSTRUMENTATION>
i_key = self._instance_key(instance)
server_instance = self._get_... |
Calls asynchronously _collect_metrics_async on all MORs, as the
job queue is processed the Aggregator will receive the metrics. | def collect_metrics(self, instance):
"""
Calls asynchronously _collect_metrics_async on all MORs, as the
job queue is processed the Aggregator will receive the metrics.
"""
i_key = self._instance_key(instance)
if not self.mor_cache.contains(i_key):
self.log.de... |
Check if the database we're targeting actually exists
If not then we won't do any checks
This allows the same config to be installed on many servers but fail gracefully | def _check_db_exists(self, instance):
"""
Check if the database we're targeting actually exists
If not then we won't do any checks
This allows the same config to be installed on many servers but fail gracefully
"""
dsn, host, username, password, database, driver = self._... |
Store the list of metrics to collect by instance_key.
Will also create and cache cursors to query the db. | def _make_metric_list_to_collect(self, instance, custom_metrics):
"""
Store the list of metrics to collect by instance_key.
Will also create and cache cursors to query the db.
"""
metrics_to_collect = []
for name, counter_name, instance_name in self.METRICS:
t... |
Create the appropriate SqlServerMetric object, each implementing its method to
fetch the metrics properly.
If a `type` was specified in the config, it is used to report the value
directly fetched from SQLServer. Otherwise, it is decided based on the
sql_type, according to microsoft's doc... | def typed_metric(self, instance, cfg_inst, table, base_name, user_type, sql_type, column):
'''
Create the appropriate SqlServerMetric object, each implementing its method to
fetch the metrics properly.
If a `type` was specified in the config, it is used to report the value
direct... |
Convenience method to extract info from instance | def _get_access_info(self, instance, db_key, db_name=None):
''' Convenience method to extract info from instance
'''
dsn = instance.get('dsn')
host = instance.get('host')
username = instance.get('username')
password = instance.get('password')
database = instance.g... |
Return a key to use for the connection cache | def _conn_key(self, instance, db_key, db_name=None):
''' Return a key to use for the connection cache
'''
dsn, host, username, password, database, driver = self._get_access_info(instance, db_key, db_name)
return '{}:{}:{}:{}:{}:{}'.format(dsn, host, username, password, database, driver) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.