INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Register a listener for audio group changes of cast uuid. On update will call: listener. added_to_multizone ( group_uuid ) The cast has been added to group uuid listener. removed_from_multizone ( group_uuid ) The cast has been removed from group uuid listener. multizone_new_media_status ( group_uuid media_status ) The ... | def register_listener(self, member_uuid, listener):
""" Register a listener for audio group changes of cast uuid.
On update will call:
listener.added_to_multizone(group_uuid)
The cast has been added to group uuid
listener.removed_from_multizone(group_uuid)
... |
Deregister listener for audio group changes of cast uuid. | def deregister_listener(self, member_uuid, listener):
""" Deregister listener for audio group changes of cast uuid."""
self._casts[str(member_uuid)]['listeners'].remove(listener) |
Called when a multizone message is received. | def receive_message(self, message, data): # noqa: E501 pylint: disable=too-many-return-statements
""" Called when a multizone message is received. """
if data[MESSAGE_TYPE] == TYPE_DEVICE_ADDED:
uuid = data['device']['deviceId']
name = data['device']['name']
self._ad... |
Creates a Chromecast object from a zeroconf host. | def _get_chromecast_from_host(host, tries=None, retry_wait=None, timeout=None,
blocking=True):
"""Creates a Chromecast object from a zeroconf host."""
# Build device status from the mDNS info, this information is
# the primary source and the remaining will be fetched
# late... |
Creates a Chromecast object from a zeroconf service. | def _get_chromecast_from_service(services, tries=None, retry_wait=None,
timeout=None, blocking=True):
"""Creates a Chromecast object from a zeroconf service."""
# Build device status from the mDNS service name info, this
# information is the primary source and the remaining ... |
Searches the network for chromecast devices. | def get_chromecasts(tries=None, retry_wait=None, timeout=None,
blocking=True, callback=None):
"""
Searches the network for chromecast devices.
If blocking = True, returns a list of discovered chromecast devices.
If blocking = False, triggers a callback for each discovered chromecast... |
Returns whether the CEC data should be ignored. | def ignore_cec(self):
""" Returns whether the CEC data should be ignored. """
return self.device is not None and \
any([fnmatch.fnmatchcase(self.device.friendly_name, pattern)
for pattern in IGNORE_CEC]) |
Returns if there is currently an app running. | def is_idle(self):
""" Returns if there is currently an app running. """
return (self.status is None or
self.app_id in (None, IDLE_APP_ID) or
(not self.status.is_active_input and not self.ignore_cec)) |
Called when a new status received from the Chromecast. | def new_cast_status(self, status):
""" Called when a new status received from the Chromecast. """
self.status = status
if status:
self.status_event.set() |
Start an app on the Chromecast. | def start_app(self, app_id, force_launch=False):
""" Start an app on the Chromecast. """
self.logger.info("Starting app %s", app_id)
self.socket_client.receiver_controller.launch_app(app_id, force_launch) |
Increment volume by 0. 1 ( or delta ) unless it is already maxed. Returns the new volume. | def volume_up(self, delta=0.1):
""" Increment volume by 0.1 (or delta) unless it is already maxed.
Returns the new volume.
"""
if delta <= 0:
raise ValueError(
"volume delta must be greater than zero, not {}".format(delta))
return self.set_volume(self... |
Decrement the volume by 0. 1 ( or delta ) unless it is already 0. Returns the new volume. | def volume_down(self, delta=0.1):
""" Decrement the volume by 0.1 (or delta) unless it is already 0.
Returns the new volume.
"""
if delta <= 0:
raise ValueError(
"volume delta must be greater than zero, not {}".format(delta))
return self.set_volume(sel... |
Waits until the cast device is ready for communication. The device is ready as soon a status message has been received. | def wait(self, timeout=None):
"""
Waits until the cast device is ready for communication. The device
is ready as soon a status message has been received.
If the worker thread is not already running, it will be started.
If the status has already been received then the method ret... |
Disconnects the chromecast and waits for it to terminate. | def disconnect(self, timeout=None, blocking=True):
"""
Disconnects the chromecast and waits for it to terminate.
:param timeout: a floating point number specifying a timeout for the
operation in seconds (or fractions thereof). Or None
to block for... |
Parses a PB2 message into JSON format. | def _json_from_message(message):
""" Parses a PB2 message into JSON format. """
try:
return json.loads(message.payload_utf8)
except ValueError:
logger = logging.getLogger(__name__)
logger.warning("Ignoring invalid json in namespace %s: %s",
message.namespace, m... |
Gives a string representation of a PB2 message. | def _message_to_string(message, data=None):
""" Gives a string representation of a PB2 message. """
if data is None:
data = _json_from_message(message)
return "Message {} from {} to {}: {}".format(
message.namespace, message.source_id, message.destination_id, data) |
Create a new socket with OS - specific parameters | def new_socket():
"""
Create a new socket with OS-specific parameters
Try to set SO_REUSEPORT for BSD-flavored systems if it's an option.
Catches errors if not.
"""
new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
... |
Initialize a socket to a Chromecast retrying as necessary. | def initialize_connection(self): # noqa: E501 pylint:disable=too-many-statements, too-many-branches
"""Initialize a socket to a Chromecast, retrying as necessary."""
tries = self.tries
if self.socket is not None:
self.socket.close()
self.socket = None
# Make su... |
Connect socket connection to Chromecast device. | def connect(self):
""" Connect socket connection to Chromecast device.
Must only be called if the worker thread will not be started.
"""
try:
self.initialize_connection()
except ChromecastConnectionError:
self._report_connection_status(
... |
Register a new namespace handler. | def register_handler(self, handler):
""" Register a new namespace handler. """
self._handlers[handler.namespace] = handler
handler.registered(self) |
Called when a new cast status has been received. | def new_cast_status(self, cast_status):
""" Called when a new cast status has been received. """
new_channel = self.destination_id != cast_status.transport_id
if new_channel:
self.disconnect_channel(self.destination_id)
self.app_namespaces = cast_status.namespaces
s... |
Connect to the cast and start polling the socket. | def run(self):
""" Connect to the cast and start polling the socket. """
try:
self.initialize_connection()
except ChromecastConnectionError:
self._report_connection_status(
ConnectionStatus(CONNECTION_STATUS_DISCONNECTED,
N... |
Use run_once () in your own main loop after you receive something on the socket ( get_socket () ). | def run_once(self):
"""
Use run_once() in your own main loop after you
receive something on the socket (get_socket()).
"""
# pylint: disable=too-many-branches, too-many-return-statements
try:
if not self._check_connection():
return 0
e... |
Checks if the connection is active and if not reconnect | def _check_connection(self):
"""
Checks if the connection is active, and if not reconnect
:return: True if the connection is active, False if the connection was
reset.
"""
# check if connection is expired
reset = False
if self._force_recon:
... |
Route message to any handlers on the message namespace | def _route_message(self, message, data):
""" Route message to any handlers on the message namespace """
# route message to handlers
if message.namespace in self._handlers:
# debug messages
if message.namespace != NS_HEARTBEAT:
self.logger.debug(
... |
Cleanup open channels and handlers | def _cleanup(self):
""" Cleanup open channels and handlers """
for channel in self._open_channels:
try:
self.disconnect_channel(channel)
except Exception: # pylint: disable=broad-except
pass
for handler in self._handlers.values():
... |
Report a change in the connection status to any listeners | def _report_connection_status(self, status):
""" Report a change in the connection status to any listeners """
for listener in self._connection_listeners:
try:
self.logger.debug("[%s:%s] connection listener: %x (%s)",
self.fn or self.host, se... |
Read bytes from the socket. | def _read_bytes_from_socket(self, msglen):
""" Read bytes from the socket. """
chunks = []
bytes_recd = 0
while bytes_recd < msglen:
if self.stop.is_set():
raise InterruptLoop("Stopped while reading from socket")
try:
chunk = self.s... |
Reads a message from the socket and converts it to a message. | def _read_message(self):
""" Reads a message from the socket and converts it to a message. """
# first 4 bytes is Big-Endian payload length
payload_info = self._read_bytes_from_socket(4)
read_len = unpack(">I", payload_info)[0]
# now read the payload
payload = self._read... |
Send a message to the Chromecast. | def send_message(self, destination_id, namespace, data,
inc_session_id=False, callback_function=False,
no_add_request_id=False, force=False):
""" Send a message to the Chromecast. """
# namespace is a string containing namespace
# data is a dict that wi... |
Helper method to send a message to the platform. | def send_platform_message(self, namespace, message, inc_session_id=False,
callback_function_param=False):
""" Helper method to send a message to the platform. """
return self.send_message(PLATFORM_DESTINATION_ID, namespace, message,
inc_sess... |
Helper method to send a message to current running app. | def send_app_message(self, namespace, message, inc_session_id=False,
callback_function_param=False):
""" Helper method to send a message to current running app. """
if namespace not in self.app_namespaces:
raise UnsupportedNamespace(
("Namespace {} is... |
Ensure we opened a channel to destination_id. | def _ensure_channel_connected(self, destination_id):
""" Ensure we opened a channel to destination_id. """
if destination_id not in self._open_channels:
self._open_channels.append(destination_id)
self.send_message(
destination_id, NS_CONNECTION,
{... |
Disconnect a channel with destination_id. | def disconnect_channel(self, destination_id):
""" Disconnect a channel with destination_id. """
if destination_id in self._open_channels:
try:
self.send_message(
destination_id, NS_CONNECTION,
{MESSAGE_TYPE: TYPE_CLOSE, 'origin': {}},
... |
Handles a channel being disconnected. | def handle_channel_disconnected(self):
""" Handles a channel being disconnected. """
for namespace in self.app_namespaces:
if namespace in self._handlers:
self._handlers[namespace].channel_disconnected()
self.app_namespaces = []
self.destination_id = None
... |
Called when a connection message is received. | def receive_message(self, message, data):
""" Called when a connection message is received. """
if self._socket_client.is_stopped:
return True
if data[MESSAGE_TYPE] == TYPE_CLOSE:
# The cast device is asking us to acknowledge closing this channel.
self._socke... |
Called when a heartbeat message is received. | def receive_message(self, message, data):
""" Called when a heartbeat message is received. """
if self._socket_client.is_stopped:
return True
if data[MESSAGE_TYPE] == TYPE_PING:
try:
self._socket_client.send_message(
PLATFORM_DESTINATI... |
Send a ping message. | def ping(self):
""" Send a ping message. """
self.last_ping = time.time()
try:
self.send_message({MESSAGE_TYPE: TYPE_PING})
except NotConnected:
self._socket_client.logger.error("Chromecast is disconnected. " +
"Cannot ... |
Indicates if connection has expired. | def is_expired(self):
""" Indicates if connection has expired. """
if time.time() - self.last_ping > HB_PING_TIME:
self.ping()
return (time.time() - self.last_pong) > HB_PING_TIME + HB_PONG_TIME |
Called when a receiver - message has been received. | def receive_message(self, message, data):
""" Called when a receiver-message has been received. """
if data[MESSAGE_TYPE] == TYPE_RECEIVER_STATUS:
self._process_get_status(data)
return True
elif data[MESSAGE_TYPE] == TYPE_LAUNCH_ERROR:
self._process_launch_e... |
Sends a message to the Chromecast to update the status. | def update_status(self, callback_function_param=False):
""" Sends a message to the Chromecast to update the status. """
self.logger.debug("Receiver:Updating status")
self.send_message({MESSAGE_TYPE: TYPE_GET_STATUS},
callback_function=callback_function_param) |
Launches an app on the Chromecast. | def launch_app(self, app_id, force_launch=False, callback_function=False):
""" Launches an app on the Chromecast.
Will only launch if it is not currently running unless
force_launch=True. """
if not force_launch and self.app_id is None:
self.update_status(lambda res... |
Stops the current running app on the Chromecast. | def stop_app(self, callback_function_param=False):
""" Stops the current running app on the Chromecast. """
self.logger.info("Receiver:Stopping current app '%s'", self.app_id)
return self.send_message(
{MESSAGE_TYPE: 'STOP'},
inc_session_id=True, callback_function=callbac... |
Allows to set volume. Should be value between 0.. 1. Returns the new volume. | def set_volume(self, volume):
""" Allows to set volume. Should be value between 0..1.
Returns the new volume.
"""
volume = min(max(0, volume), 1)
self.logger.info("Receiver:setting volume to %.1f", volume)
self.send_message({MESSAGE_TYPE: 'SET_VOLUME',
... |
Parses a STATUS message and returns a CastStatus object. | def _parse_status(data, cast_type):
"""
Parses a STATUS message and returns a CastStatus object.
:type data: dict
:param cast_type: Type of Chromecast.
:rtype: CastStatus
"""
data = data.get('status', {})
volume_data = data.get('volume', {})
try... |
Processes a received STATUS message and notifies listeners. | def _process_get_status(self, data):
""" Processes a received STATUS message and notifies listeners. """
status = self._parse_status(data, self.cast_type)
is_new_app = self.app_id != status.app_id and self.app_to_launch
self.status = status
self.logger.debug("Received status: %s... |
Reports the current status to all listeners. | def _report_status(self):
""" Reports the current status to all listeners. """
for listener in self._status_listeners:
try:
listener.new_cast_status(self.status)
except Exception: # pylint: disable=broad-except
self.logger.exception(
... |
Parses a LAUNCH_ERROR message and returns a LaunchFailure object. | def _parse_launch_error(data):
"""
Parses a LAUNCH_ERROR message and returns a LaunchFailure object.
:type data: dict
:rtype: LaunchFailure
"""
return LaunchFailure(
data.get(ERROR_REASON, None),
data.get(APP_ID),
data.get(REQUEST_ID),... |
Processes a received LAUNCH_ERROR message and notifies listeners. | def _process_launch_error(self, data):
"""
Processes a received LAUNCH_ERROR message and notifies listeners.
"""
launch_failure = self._parse_launch_error(data)
self.launch_failure = launch_failure
if self.app_to_launch:
self.app_to_launch = None
... |
Called when controller is destroyed. | def tear_down(self):
""" Called when controller is destroyed. """
super(ReceiverController, self).tear_down()
self.status = None
self.launch_failure = None
self.app_to_launch = None
self.app_launch_event.clear()
self._status_listeners[:] = [] |
Starts loading a URL with an optional reload time in seconds. | def load_url(self, url, force=False, reload_seconds=0,
callback_function=None):
"""
Starts loading a URL with an optional reload time
in seconds.
Setting force to True may load pages which block
iframe embedding, but will prevent reload from
working and ... |
: param host: Hostname or ip to fetch status from: type host: str: return: The device status as a named tuple.: rtype: pychromecast. dial. DeviceStatus or None | def _get_status(host, services, zconf, path):
"""
:param host: Hostname or ip to fetch status from
:type host: str
:return: The device status as a named tuple.
:rtype: pychromecast.dial.DeviceStatus or None
"""
if not host:
for service in services.copy():
service_info = ... |
: param host: Hostname or ip to fetch status from: type host: str: return: The device status as a named tuple.: rtype: pychromecast. dial. DeviceStatus or None | def get_device_status(host, services=None, zconf=None):
"""
:param host: Hostname or ip to fetch status from
:type host: str
:return: The device status as a named tuple.
:rtype: pychromecast.dial.DeviceStatus or None
"""
try:
status = _get_status(
host, services, zconf, ... |
: param host: Hostname or ip to fetch status from: type host: str: return: The multizone status as a named tuple.: rtype: pychromecast. dial. MultizoneStatus or None | def get_multizone_status(host, services=None, zconf=None):
"""
:param host: Hostname or ip to fetch status from
:type host: str
:return: The multizone status as a named tuple.
:rtype: pychromecast.dial.MultizoneStatus or None
"""
try:
status = status = _get_status(
host,... |
Starts a session it is not yet initialized. | def start_session_if_none(self):
"""
Starts a session it is not yet initialized.
"""
if not (self._screen_id and self._session):
self.update_screen_id()
self._session = YouTubeSession(screen_id=self._screen_id) |
Play video ( video_id ) now. This ignores the current play queue order.: param video_id: YouTube video id ( http:// youtube. com/ watch?v = video_id ): param playlist_id: youtube. com/ watch?v = video_id&list = playlist_id | def play_video(self, video_id, playlist_id=None):
"""
Play video(video_id) now. This ignores the current play queue order.
:param video_id: YouTube video id(http://youtube.com/watch?v=video_id)
:param playlist_id: youtube.com/watch?v=video_id&list=playlist_id
"""
self.sta... |
Sends a getMdxSessionStatus to get the screenId and waits for response. This function is blocking If connected we should always get a response ( send message will launch app if it is not running ). | def update_screen_id(self):
"""
Sends a getMdxSessionStatus to get the screenId and waits for response.
This function is blocking
If connected we should always get a response
(send message will launch app if it is not running).
"""
self.status_update_event.clear()... |
Called when a media message is received. | def receive_message(self, message, data):
""" Called when a media message is received. """
if data[MESSAGE_TYPE] == TYPE_STATUS:
self._process_status(data.get("data"))
return True
return False |
Process latest status update. | def _process_status(self, status):
""" Process latest status update. """
self._screen_id = status.get(ATTR_SCREEN_ID)
self.status_update_event.set() |
Start discovering chromecasts on the network. | def start_discovery(add_callback=None, remove_callback=None):
"""
Start discovering chromecasts on the network.
This method will start discovering chromecasts on a separate thread. When
a chromecast is discovered, the callback will be called with the
discovered chromecast's zeroconf name. This is t... |
Discover chromecasts on the network. | def discover_chromecasts(max_devices=None, timeout=DISCOVER_TIMEOUT):
""" Discover chromecasts on the network. """
from threading import Event
browser = False
try:
# pylint: disable=unused-argument
def callback(name):
"""Called when zeroconf has discovered a new chromecast.""... |
Resolve service_info from service. | def get_info_from_service(service, zconf):
""" Resolve service_info from service. """
service_info = None
try:
service_info = zconf.get_service_info('_googlecast._tcp.local.',
service)
if service_info:
_LOGGER.debug(
"... |
Get hostname or IP from service_info. | def get_host_from_service_info(service_info):
""" Get hostname or IP from service_info. """
host = None
port = None
if (service_info and service_info.port and
(service_info.server or service_info.address)):
if service_info.address:
host = socket.inet_ntoa(service_info.add... |
Remove a service from the collection. | def remove_service(self, zconf, typ, name):
""" Remove a service from the collection. """
_LOGGER.debug("remove_service %s, %s", typ, name)
service = self.services.pop(name, None)
if not service:
_LOGGER.debug("remove_service unknown %s, %s", typ, name)
return
... |
Add a service to the collection. | def add_service(self, zconf, typ, name):
""" Add a service to the collection. """
service = None
tries = 0
_LOGGER.debug("add_service %s, %s", typ, name)
while service is None and tries < 4:
try:
service = zconf.get_service_info(typ, name)
... |
Currently not doing anything with received messages. | def receive_message(self, message, data):
""" Currently not doing anything with received messages. """
if data['type'] == TYPE_RESPONSE_STATUS:
self.is_launched = True
return True |
Launch Spotify application. | def launch_app(self, timeout=10):
"""
Launch Spotify application.
Will raise a LaunchError exception if there is no response from the
Spotify app within timeout seconds.
"""
def callback():
"""Callback function"""
self.send_message({"type": TYPE_... |
If set launches app related to the controller. | def launch(self, callback_function=None):
""" If set, launches app related to the controller. """
self._check_registered()
self._socket_client.receiver_controller.launch_app(
self.supporting_app_id, callback_function=callback_function) |
Called when a controller is registered. | def registered(self, socket_client):
""" Called when a controller is registered. """
self._socket_client = socket_client
if self.target_platform:
self._message_func = self._socket_client.send_platform_message
else:
self._message_func = self._socket_client.send_ap... |
Send a message on this namespace to the Chromecast. | def send_message(self, data, inc_session_id=False,
callback_function=None):
"""
Send a message on this namespace to the Chromecast.
Will raise a NotConnected exception if not connected.
"""
self._check_registered()
if not self.target_platform and \
... |
Returns calculated current seek time of media in seconds | def adjusted_current_time(self):
""" Returns calculated current seek time of media in seconds """
if self.player_state == MEDIA_PLAYER_STATE_PLAYING:
# Add time since last update
return (self.current_time +
(datetime.utcnow() - self.last_updated).total_seconds... |
Return a list of MediaImage objects for this media. | def images(self):
""" Return a list of MediaImage objects for this media. """
return [
MediaImage(item.get('url'), item.get('height'), item.get('width'))
for item in self.media_metadata.get('images', [])
] |
New data will only contain the changed attributes. | def update(self, data):
""" New data will only contain the changed attributes. """
if not data.get('status', []):
return
status_data = data['status'][0]
media_data = status_data.get('media') or {}
volume_data = status_data.get('volume', {})
self.current_time... |
Called when a media message is received. | def receive_message(self, message, data):
""" Called when a media message is received. """
if data[MESSAGE_TYPE] == TYPE_MEDIA_STATUS:
self._process_media_status(data)
return True
return False |
Send a command to the Chromecast on media channel. | def _send_command(self, command):
""" Send a command to the Chromecast on media channel. """
if self.status is None or self.status.media_session_id is None:
self.logger.warning(
"%s command requested but no session is active.",
command[MESSAGE_TYPE])
... |
Deprecated as of June 8 2015. Use self. status. images. Return thumbnail url of current playing item. | def thumbnail(self):
""" Deprecated as of June 8, 2015. Use self.status.images.
Return thumbnail url of current playing item. """
if not self.status:
return None
images = self.status.images
return images[0].url if images else None |
Processes a STATUS message. | def _process_media_status(self, data):
""" Processes a STATUS message. """
self.status.update(data)
self.logger.debug("Media:Received status %s", data)
# Update session active threading event
if self.status.media_session_id is None:
self.session_active_event.clear()... |
Tells listeners of a changed status. | def _fire_status_changed(self):
""" Tells listeners of a changed status. """
for listener in self._status_listeners:
try:
listener.new_media_status(self.status)
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Exception thrown w... |
Plays media on the Chromecast. Start default media receiver if not already started. | def play_media(self, url, content_type, title=None, thumb=None,
current_time=0, autoplay=True,
stream_type=STREAM_TYPE_BUFFERED,
metadata=None, subtitles=None, subtitles_lang='en-US',
subtitles_mime='text/vtt', subtitle_id=1):
"""
... |
Returns all possible app ids. | def get_possible_app_ids():
""" Returns all possible app ids. """
try:
req = requests.get(
"https://clients3.google.com/cast/chromecast/device/baseconfig")
data = json.loads(req.text[4:])
return [app['app_id'] for app in data['applications']] + \
data["enabled_a... |
Get specific configuration for app_id. | def get_app_config(app_id):
""" Get specific configuration for 'app_id'. """
try:
req = requests.get(
("https://clients3.google.com/"
"cast/chromecast/device/app?a={}").format(app_id))
return json.loads(req.text[4:]) if req.status_code == 200 else {}
except ValueEr... |
Loads the contents of the file specified by path | def get_contents(self, path):
'''
Loads the contents of the file specified by path
Args:
path (string): The relative or absolute path to the file to
be loaded. If the path is relative, then it is combined
with the base_path to generate a full path st... |
Transform the path to an absolute path | def abspath(self, path):
'''
Transform the path to an absolute path
Args:
path (string): The path to transform to an absolute path
Returns:
string: The absolute path to the file
'''
if not path.startswith(os.path.sep) or path.startswith('~'):
... |
Load the file specified by path | def load_file(self, path, objtype=None, encoding='utf-8'):
'''
Load the file specified by path
This method will first try to load the file contents from cache and
if there is a cache miss, it will load the contents from disk
Args:
path (string): The full or relative... |
Performs basic checks and then properly invokes | def prepare(self):
"""
Performs basic checks and then properly invokes
- prepare_inventory
- prepare_env
- prepare_command
It's also responsible for wrapping the command with the proper ssh agent invocation
and setting early ANSIBLE_ environment variables.
... |
Prepares the inventory default under private_data_dir if it s not overridden by the constructor. | def prepare_inventory(self):
"""
Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor.
"""
if self.inventory is None:
self.inventory = os.path.join(self.private_data_dir, "inventory") |
Manages reading environment metadata files under private_data_dir and merging/ updating with existing values so the: py: class: ansible_runner. runner. Runner object can read and use them easily | def prepare_env(self):
"""
Manages reading environment metadata files under ``private_data_dir`` and merging/updating
with existing values so the :py:class:`ansible_runner.runner.Runner` object can read and use them easily
"""
try:
passwords = self.loader.load_file('e... |
Determines if the literal ansible or ansible - playbook commands are given and if not calls: py: meth: ansible_runner. runner_config. RunnerConfig. generate_ansible_command | def prepare_command(self):
"""
Determines if the literal ``ansible`` or ``ansible-playbook`` commands are given
and if not calls :py:meth:`ansible_runner.runner_config.RunnerConfig.generate_ansible_command`
"""
try:
cmdline_args = self.loader.load_file('args', string_... |
Given that the RunnerConfig preparation methods have been run to gather the inputs this method will generate the ansible or ansible - playbook command that will be used by the: py: class: ansible_runner. runner. Runner object to start the process | def generate_ansible_command(self):
"""
Given that the ``RunnerConfig`` preparation methods have been run to gather the inputs this method
will generate the ``ansible`` or ``ansible-playbook`` command that will be used by the
:py:class:`ansible_runner.runner.Runner` object to start the p... |
Create a temporary directory for process isolation to use. | def build_process_isolation_temp_dir(self):
'''
Create a temporary directory for process isolation to use.
'''
path = tempfile.mkdtemp(prefix='ansible_runner_pi_', dir=self.process_isolation_path)
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
atexit.register(... |
Wrap existing command line with bwrap to restrict access to: - self. process_isolation_path ( generally/ tmp ) ( except for own/ tmp files ) | def wrap_args_with_process_isolation(self, args):
'''
Wrap existing command line with bwrap to restrict access to:
- self.process_isolation_path (generally, /tmp) (except for own /tmp files)
'''
cwd = os.path.realpath(self.cwd)
pi_temp_dir = self.build_process_isolation_... |
Given an existing command line and parameterization this will return the same command line wrapped with the necessary calls to ssh - agent | def wrap_args_with_ssh_agent(self, args, ssh_key_path, ssh_auth_sock=None, silence_ssh_add=False):
"""
Given an existing command line and parameterization this will return the same command line wrapped with the
necessary calls to ``ssh-agent``
"""
if ssh_key_path:
ssh... |
Configures the logging facility | def configure():
'''
Configures the logging facility
This function will setup an initial logging facility for handling display
and debug outputs. The default facility will send display messages to
stdout and the default debug facility will do nothing.
:returns: None
'''
root_logger = ... |
Invoked for every Ansible event to collect stdout with the event data and store it for later use | def event_callback(self, event_data):
'''
Invoked for every Ansible event to collect stdout with the event data and store it for
later use
'''
self.last_stdout_update = time.time()
job_events_path = os.path.join(self.config.artifact_dir, 'job_events')
if not os.pa... |
Launch the Ansible task configured in self. config ( A RunnerConfig object ) returns once the invocation is complete | def run(self):
'''
Launch the Ansible task configured in self.config (A RunnerConfig object), returns once the
invocation is complete
'''
self.status_callback('starting')
stdout_filename = os.path.join(self.config.artifact_dir, 'stdout')
command_filename = os.path... |
Returns an open file handle to the stdout representing the Ansible run | def stdout(self):
'''
Returns an open file handle to the stdout representing the Ansible run
'''
stdout_path = os.path.join(self.config.artifact_dir, 'stdout')
if not os.path.exists(stdout_path):
raise AnsibleRunnerException("stdout missing")
return open(os.pa... |
A generator that will return all ansible job events in the order that they were emitted from Ansible | def events(self):
'''
A generator that will return all ansible job events in the order that they were emitted from Ansible
Example:
{
"event":"runner_on_ok",
"uuid":"00a50d9c-161a-4b74-b978-9f60becaf209",
"stdout":"ok: [localhost] => {\\... |
Returns the final high level stats from the Ansible run | def stats(self):
'''
Returns the final high level stats from the Ansible run
Example:
{'dark': {}, 'failures': {}, 'skipped': {}, 'ok': {u'localhost': 2}, 'processed': {u'localhost': 1}}
'''
last_event = list(filter(lambda x: 'event' in x and x['event'] == 'playbook_... |
Given a host name this will return all task events executed on that host | def host_events(self, host):
'''
Given a host name, this will return all task events executed on that host
'''
all_host_events = filter(lambda x: 'event_data' in x and 'host' in x['event_data'] and x['event_data']['host'] == host,
self.events)
ret... |
Internal method to terminate a subprocess spawned by pexpect representing an invocation of runner. | def handle_termination(cls, pid, is_cancel=True):
'''
Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner.
:param pid: the process id of the running the job.
:param is_cancel: flag showing whether this termination is caused by
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.