PK!aa"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.') 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.update() if watcher.is_finished(): logger.info( 'Deployment {} is already finished, displaying past logs'.format( d_id)) watcher.display() else: logger.info( 'Deployment {} is in progress, following logs'.format(d_id)) while True: watcher.follow() if watcher.is_finished(): break time.sleep(5) if watcher.status != 'Succeeded': logger.error( 'Deployment {} finished with failed status: {}'.format( d_id, watcher.status)) sys.exit(1) logger.info('Deployment {} finished successfully'.format(d_id)) PK! aws_codedeploy_watcher/deploy.pyfrom __future__ import print_function import sys import pendulum from .logs import LogWatcher 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._target_ids = None self._target_lifecycle_events = {} self._targets = None self._log_watcher = LogWatcher(session, out_file=out_file) self._last_update_time = None self._complete_time = None def is_finished(self): return self.status in ('Succeeded', '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 self._target_ids = list(_get_target_ids()) return self._target_ids def get_targets(self, types): target_ids = self.get_target_ids() 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 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'))) def display(self): assert self.is_finished() 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): self.update() new_update_time = self._last_update_time fresh_events = [] for target_id, target in self._targets.items(): updated_at = 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): message = event.get('diagnostics', {}).get('message', '') if message == event['status']: message = '' if message: message = '- ' + message msg = '{} ({}): [{}] {}: {} {}'.format( self.deployment_id, target_id, event_time.to_datetime_string(), event['lifecycleEventName'], event['status'], message) print(msg, file=self._out_file) def print_log_messages(self): events = sorted(self._log_watcher.follow()) for event_time, group_name, event in events: target_id = event['logStreamName'] msg = '{} ({}): [{}] {}'.format( self.deployment_id, target_id, event_time.to_datetime_string(), event['message']) print(msg, file=self._out_file) PK!J aws_codedeploy_watcher/logs.pyimport logging import re import sys import pendulum import botocore.exceptions 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._client = session.client('logs') self._log_streams = {} self._group_timestamps = {} self._out_file = out_file 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.datetime(start_time) self._group_timestamps[group_name] = \ int(start_time.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 try: logger.debug('Calling filter_log_events: {}'.format(dict( logGroupName=group_name, logStreamNames=list(stream_names), startTime=last_ts, endTime=end_ts))) event_batches = self._filter_log_events( logGroupName=group_name, logStreamNames=list(stream_names), startTime=last_ts, endTime=end_ts) 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 botocore.exceptions.ClientError as e: if e.response['Error']['Code'] != '404': raise self._group_timestamps[group_name] = last_ts PK!HjR9F7aws_codedeploy_watcher-0.1.3.dist-info/entry_points.txtN+I/N.,()J,/MOIMI-ɯ-O,IH- #Vy\\PK!{.aws_codedeploy_watcher-0.1.3.dist-info/LICENSECopyright (C) 2017 Cobli 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.3.dist-info/WHEEL A н#Z;/" bFF]xzwK;<*mTֻ0*Ri.4Vm0[H, JPK!H*</aws_codedeploy_watcher-0.1.3.dist-info/METADATAOO@)ƛJlH Ўecwn-`Log~/&3,{'cVgs3}X[2LvC*Ds`dv Fgԏ$UXĎؓ嘺 ob=gS0aYl`JP3aP%x,{$Qd$o Ӫc- }Ǻ~mꇼ[O"8(CkŇ 7"j<7zGIwNѩA)Ja*-z_TД݆)o;;;w [DхzC%"ֆj.S9JYQPK!Hawa-aws_codedeploy_watcher-0.1.3.dist-info/RECORDK0}@sYo(†  BTwb'KRCH (H@?>V|ΝjnnUHvt33V7hcw>2~+v~dW+in9P] 7~.@UUVDYTżP3Ĕ}ְN/=Cwv:NfPcoBc8{x ݚ7~Z'ML6tfn}-MyTb'hIËYgz_IxvY$O6SK%ymig4ۉ,NJp{#vGS9GENbOy‰:|PK!aa"aws_codedeploy_watcher/__init__.pyPK! aws_codedeploy_watcher/deploy.pyPK!J "aws_codedeploy_watcher/logs.pyPK!HjR9F70aws_codedeploy_watcher-0.1.3.dist-info/entry_points.txtPK!{.0aws_codedeploy_watcher-0.1.3.dist-info/LICENSEPK!H|n-WY,5aws_codedeploy_watcher-0.1.3.dist-info/WHEELPK!H*</5aws_codedeploy_watcher-0.1.3.dist-info/METADATAPK!Hawa-97aws_codedeploy_watcher-0.1.3.dist-info/RECORDPK9