PK!S"aws_codedeploy_watcher/__init__.pyimport logging import re import sys import time from argparse import ArgumentParser import boto3.session from .deploy import DeploymentWatcher from .logs import find_log_groups logger = logging.getLogger(__name__) def main(): logging.basicConfig() logging.getLogger().setLevel(logging.INFO) logging.getLogger('aws-codedeploy-watcher').setLevel(logging.DEBUG) argp = ArgumentParser(description='Observe Codedeploy deployments') argp.add_argument( '--deployment-id', required=True, help='ID of the Codedeploy deployment to watch') argp.add_argument( '--log-group-prefix', help='Prefix of the Cloudwatch log group names to follow') argp.add_argument( '--log-group-pattern', type=re.compile, help='Regular expression for matching the Cloudwatch log group names ' 'to follow. Use it only for selections that can\'t be done with ' 'just the prefix, as this will require loading all the groups and' 'filtering locally.') argp.add_argument( '--start-timeout', type=float, metavar='SECONDS', default=60, help='How long to wait for a Pending deployment to start') argp.add_argument( '--stop-on-interrupt', action='store_true', help='Cancel deployment if the program is inter') args = argp.parse_args() session = boto3.session.Session() log_group_names = list(find_log_groups(session, args.log_group_prefix, args.log_group_pattern)) logger.info('Found log groups: {}'.format(', '.join(log_group_names))) d_id = args.deployment_id watcher = DeploymentWatcher( session, d_id, log_group_names, out_file=sys.stderr) watcher.wait_started(args.start_timeout) try: while not watcher.is_finished(): watcher.follow() time.sleep(1) except Exception: if args.stop_on_interrupt: watcher.stop_deployment() raise watcher.display() if watcher.failed(): logger.error( 'Deployment {} finished with failed status: {}'.format( d_id, watcher.status)) sys.exit(1) logger.info('Deployment {} finished successfully'.format(d_id)) PK!g aws_codedeploy_watcher/deploy.pyfrom __future__ import print_function import logging import sys import time import pendulum from .logs import LogWatcher logger = logging.getLogger(__name__) class DeploymentWatcher(object): def __init__(self, session, deployment_id, log_group_names=None, out_file=sys.stderr): self.deployment_id = deployment_id self.status = None self.log_group_names = log_group_names or [] self._client = session.client('codedeploy') self._list_deployment_targets = \ self._client.get_paginator('list_deployment_targets').paginate self._out_file = out_file self._deploy_info = None self._target_ids = None self._target_lifecycle_events = {} self._targets = None self._log_watcher = LogWatcher(session, out_file=out_file) self._last_update_time = pendulum.from_timestamp(0) self._complete_time = None def is_started(self): return self.status != 'Pending' def is_finished(self): return self.status in ('Succeeded', 'Failed') def failed(self): return self.status == 'Failed' def is_target_active(self, target): return target['status'] == 'InProgress' def is_target_finished(self, target): return target['status'] in ('Succeeded', 'Failed', 'Skipped', 'Ready') def get_target_ids(self): if self._target_ids is None: def _get_target_ids(): targets = self._list_deployment_targets( deploymentId=self.deployment_id) for response in targets: for target_id in response['targetIds']: yield target_id try: self._target_ids = list(_get_target_ids()) except self._client.exceptions.DeploymentNotStartedException: return None return self._target_ids def get_targets(self, types): target_ids = self.get_target_ids() if target_ids is None: return response = self._client.batch_get_deployment_targets( deploymentId=self.deployment_id, targetIds=target_ids) for target in response['deploymentTargets']: target_type = target['deploymentTargetType'] if target_type not in types: continue if target_type == 'InstanceTarget': target_info = target['instanceTarget'] elif target_type == 'ECSTarget': target_info = target['ecsTarget'] elif target_type == 'LambdaTarget': target_info = target['lambdaTarget'] else: continue yield target_info['targetId'], target_info def enable_log_target(self, target_id, start_time=None): for group_name in self.log_group_names: self._log_watcher.add_log_stream(group_name, target_id, start_time=start_time) def disable_log_target(self, target_id): for group_name in self.log_group_names: self._log_watcher.remove_log_stream(group_name, target_id) def _event_time(self, event): start_time = event.get('startTime') end_time = event.get('endTime') if end_time: return pendulum.instance(end_time) elif start_time: return pendulum.instance(start_time) elif self._complete_time: return self._complete_time else: return pendulum.now() def get_updated_lifecycle_events(self, target_id, events): target_events = self._target_lifecycle_events.setdefault(target_id, {}) for event in events: event_name = event['lifecycleEventName'] prev_event = target_events.get(event_name) if not prev_event or event != prev_event: # Accumulate entries for the events with the respective # times so they can be printed in order event_entry = (self._event_time(event), target_id, event) yield event_entry target_events[event_name] = event def wait_started(self, sleep=time.sleep, timeout=None): if self.is_started(): return logger.info('Deployment {} is pending, waiting for start'.format(self.deployment_id)) deadline = time.time() + timeout if timeout else float('inf') while not self.update() and time.time() < deadline: sleep(1) if not self.is_started(): raise RuntimeError( 'Deployment {} timed out while starting'.format(self.deployment_id)) def update(self): response = \ self._client.get_deployment(deploymentId=self.deployment_id) self._deploy_info = response['deploymentInfo'] self.status = self._deploy_info['status'] if not self._complete_time and self.is_finished(): self._complete_time = \ pendulum.instance(self._deploy_info['completeTime']) self._targets = dict( self.get_targets(types=('InstanceTarget', 'ECSTarget'))) if not self._targets: logger.info('Deployment {} has no targets yet, waiting'.format( self.deployment_id)) return False return True def display(self): if not self.update(): return create_time = self._deploy_info.get('createTime') start_time = self._deploy_info.get('startTime') self._log_watcher.set_time_range( start=start_time or create_time, end=self._complete_time) for target_id in self._targets.keys(): self.enable_log_target(target_id) self.print_log_messages() def follow(self): if not self.update(): return new_update_time = self._last_update_time fresh_events = [] for target_id, target in self._targets.items(): updated_at = pendulum.instance(target['lastUpdatedAt']) if updated_at <= self._last_update_time: continue new_update_time = max(new_update_time, updated_at) events = self.get_updated_lifecycle_events( target_id, target['lifecycleEvents']) fresh_events.extend(events) if not self.is_finished(): if self.is_target_active(target): self.enable_log_target(target_id, self._last_update_time) elif self.is_target_finished(target): self.disable_log_target(target_id) self._last_update_time = new_update_time self.print_lifecycle_events(fresh_events) self.print_log_messages() def print_lifecycle_events(self, events): for event_time, target_id, event in sorted(events): self.print_lifecycle_event(event_time, target_id, event) def print_lifecycle_event(self, event_time, target_id, event): event_message = event.get('diagnostics', {}).get('message', '') if event_message == event['status']: event_message = '' if event_message: event_message = '- ' + event_message msg = '{id} ({target_id}): [{time}] {name}: {status} {msg}'.format( id=self.deployment_id, target_id=target_id, time=event_time.to_datetime_string(), name=event['lifecycleEventName'], status=event['status'], msg=event_message) print(msg, file=self._out_file) def print_log_messages(self): def sort_key(t): event_time, group_name, _ = t return event_time, group_name events = sorted(self._log_watcher.follow(), key=sort_key) for event_time, group_name, event in events: target_id = event['logStreamName'] msg = '{id} ({target_id}): [{time}] {msg}'.format( id=self.deployment_id, target_id=target_id, time=event_time.to_datetime_string(), msg=event['message']) print(msg, file=self._out_file) def stop_deployment(self): if self.is_started(): self._client.stop_deployment( deploymentId=self.deployment_id, autoRollbackEnabled=True) PK!l[  aws_codedeploy_watcher/logs.pyimport logging import re import sys import pendulum from botocore.config import Config logger = logging.getLogger(__name__) def find_log_groups(session, prefix, pattern): compiled_pat = re.compile(pattern) client = session.client('logs') describe_log_groups = client.get_paginator('describe_log_groups').paginate for groups in describe_log_groups(logGroupNamePrefix=prefix): for group in groups['logGroups']: group_name = group['logGroupName'] assert group_name.startswith(prefix) group_suffix = group_name[len(prefix):] if compiled_pat.search(group_suffix): yield group_name class LogWatcher(object): def __init__(self, session, out_file=sys.stderr): self._log_streams = {} self._group_timestamps = {} self._out_file = out_file # Ensure we can handle throttling from fetching the logs config = Config(retries=dict(max_attempts=10)) self._client = session.client('logs', config=config) self._filter_log_events = \ self._client.get_paginator('filter_log_events').paginate self._start_ts = None self._end_ts = None def add_log_stream(self, group_name, stream_name, start_time=None): stream_names = self._log_streams.setdefault(group_name, set()) stream_names.add(stream_name) if start_time: start_time = pendulum.instance(start_time) self._group_timestamps[group_name] = \ int(start_time.float_timestamp * 1000) def remove_log_stream(self, group_name, stream_name): stream_names = self._log_streams.setdefault(group_name, set()) stream_names.discard(stream_name) def set_time_range(self, start=None, end=None): if start: start = pendulum.instance(start) self._start_ts = int(start.float_timestamp * 1000) else: self._start_ts = None if end: end = pendulum.instance(end) self._end_ts = int(end.float_timestamp * 1000) else: self._end_ts = None def _event_time(self, event): event_ts = event.get('timestamp') or event['ingestionTime'] return pendulum.from_timestamp(event_ts / 1000) def follow(self): for group_name, stream_names in self._log_streams.items(): if not stream_names: continue last_ts = self._group_timestamps.get(group_name, self._start_ts) end_ts = self._end_ts filter_args = dict( logGroupName=group_name, logStreamNames=list(stream_names), startTime=last_ts) if end_ts: filter_args['endTime'] = end_ts logger.debug('Calling filter_log_events: {}'.format( filter_args)) try: event_batches = self._filter_log_events(**filter_args) for batch in event_batches: for event in batch['events']: yield self._event_time(event), group_name, event last_ts = max(last_ts, event['ingestionTime']) except self._client.exceptions.ResourceNotFoundException: pass self._group_timestamps[group_name] = last_ts PK!HjR9F7aws_codedeploy_watcher-0.1.7.dist-info/entry_points.txtN+I/N.,()J,/MOIMI-ɯ-O,IH- #Vy\\PK!"".aws_codedeploy_watcher-0.1.7.dist-info/LICENSECopyright (C) 2019 Daniel Miranda Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!H|n-WY,aws_codedeploy_watcher-0.1.7.dist-info/WHEEL A н#Z;/" bFF]xzwK;<*mTֻ0*Ri.4Vm0[H, JPK!H=/aws_codedeploy_watcher-0.1.7.dist-info/METADATAOO@)ƛJlH Ўecwn-`Log~/fwF&XN "()[/ %gdؙpw٪!ƒ +mPTa!;bOZc&͟MELʺlʆe&1*ĀADE6?1xL d/U C[o?$Bb cN %;YF*)tU|RAS=m3Gؔ緍wݿ [DхzC%"ֆj.S9JYQPK!Htu-aws_codedeploy_watcher-0.1.7.dist-info/RECORDɎP}= P ,z,`2m2$ OߋI%&<;9'(,[9">l)~E"&[f|PVܭݭeQڻ#-8쌐$O*hM͋{nL'W-+Bȼ 7u`nF_v3+Nn>IP}Q#0 KqB6>v֨vi^Jpg.T %Z zn~:ƞrbt [|!!^Ǽuh(lj9QiWb2]pO5CwESa-WApGpnuct' :;B{(::K:&IlF7sN,5a_&I D޴ PK!S"aws_codedeploy_watcher/__init__.pyPK!g  aws_codedeploy_watcher/deploy.pyPK!l[  *aws_codedeploy_watcher/logs.pyPK!HjR9F7U7aws_codedeploy_watcher-0.1.7.dist-info/entry_points.txtPK!"".7aws_codedeploy_watcher-0.1.7.dist-info/LICENSEPK!H|n-WY,Q<aws_codedeploy_watcher-0.1.7.dist-info/WHEELPK!H=/<aws_codedeploy_watcher-0.1.7.dist-info/METADATAPK!Htu-|>aws_codedeploy_watcher-0.1.7.dist-info/RECORDPKc@