desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Writes data to stdout as bytes. :param b: data to write'
def write(self, b):
bytes_print(b, self._stdout)
':param message: An arbitrary string associated with the entry. This can be used to communicate the result of the task. :param error: Boolean indicating a failure. :param total_parts: The total number of parts for multipart transfers. :param warning: Boolean indicating a warning'
def __new__(cls, message, error=False, total_parts=None, warning=None):
return super(PrintTask, cls).__new__(cls, message, error, total_parts, warning)
'Map CLI params to PutObject request params'
@classmethod def map_put_object_params(cls, request_params, cli_params):
cls._set_general_object_params(request_params, cli_params) cls._set_metadata_params(request_params, cli_params) cls._set_sse_request_params(request_params, cli_params) cls._set_sse_c_request_params(request_params, cli_params)
'Map CLI params to GetObject request params'
@classmethod def map_get_object_params(cls, request_params, cli_params):
cls._set_sse_c_request_params(request_params, cli_params)
'Map CLI params to CopyObject request params'
@classmethod def map_copy_object_params(cls, request_params, cli_params):
cls._set_general_object_params(request_params, cli_params) cls._set_metadata_directive_param(request_params, cli_params) cls._set_metadata_params(request_params, cli_params) cls._auto_populate_metadata_directive(request_params) cls._set_sse_request_params(request_params, cli_params) cls._set_sse...
'Map CLI params to HeadObject request params'
@classmethod def map_head_object_params(cls, request_params, cli_params):
cls._set_sse_c_request_params(request_params, cli_params)
'Map CLI params to CreateMultipartUpload request params'
@classmethod def map_create_multipart_upload_params(cls, request_params, cli_params):
cls._set_general_object_params(request_params, cli_params) cls._set_sse_request_params(request_params, cli_params) cls._set_sse_c_request_params(request_params, cli_params) cls._set_metadata_params(request_params, cli_params)
'Map CLI params to UploadPart request params'
@classmethod def map_upload_part_params(cls, request_params, cli_params):
cls._set_sse_c_request_params(request_params, cli_params)
'Map CLI params to UploadPartCopy request params'
@classmethod def map_upload_part_copy_params(cls, request_params, cli_params):
cls._set_sse_c_and_copy_source_request_params(request_params, cli_params)
'Determines if a file info object is glacier compatible Operations will fail if the S3 object has a storage class of GLACIER and it involves copying from S3 to S3, downloading from S3, or moving where S3 is the source (the delete will actually succeed, but we do not want fail to transfer the file and then successfully ...
def is_glacier_compatible(self):
if self._is_glacier_object(self.associated_response_data): if (self.operation_name in ['copy', 'download']): return False elif (self.operation_name == 'move'): if (self.src_type == 's3'): return False return True
'This function formats the source and destination path to the proper form for a file generator. Note that a file is designated as an s3 file if it begins with s3:// :param src: The path of the source :type src: string :param dest: The path of the dest :type dest: string :param parameters: A dictionary that will be form...
def format(self, src, dest, parameters):
(src_type, src_path) = self.identify_type(src) (dest_type, dest_path) = self.identify_type(dest) format_table = {'s3': self.s3_format, 'local': self.local_format} dir_op = parameters['dir_op'] src_path = format_table[src_type](src_path, dir_op)[0] (dest_path, use_src_name) = format_table[dest_ty...
'This function formats the path of local files and returns whether the destination will keep its own name or take the source\'s name along with the editted path. Formatting Rules: 1) If a destination file is taking on a source name, it must end with the apporpriate operating system seperator General Options: 1) If the ...
def local_format(self, path, dir_op):
full_path = os.path.abspath(path) if ((os.path.exists(full_path) and os.path.isdir(full_path)) or dir_op): full_path += os.sep return (full_path, True) elif path.endswith(os.sep): full_path += os.sep return (full_path, True) else: return (full_path, False)
'This function formats the path of source files and returns whether the destination will keep its own name or take the source\'s name along with the edited path. Formatting Rules: 1) If a destination file is taking on a source name, it must end with a forward slash. General Options: 1) If the operation is on objects un...
def s3_format(self, path, dir_op):
if dir_op: if (not path.endswith('/')): path += '/' return (path, True) elif (not path.endswith('/')): return (path, False) else: return (path, True)
'It identifies whether the path is from local or s3. Returns the adjusted pathname and a string stating whether the file is from local or s3. If from s3 it strips off the s3:// from the beginnning of the path'
def identify_type(self, path):
if path.startswith('s3://'): return ('s3', path[5:]) else: return ('local', path)
'This function creates the last modified time string whenever objects or buckets are being listed'
def _make_last_mod_str(self, last_mod):
last_mod = parse(last_mod) last_mod = last_mod.astimezone(tzlocal()) last_mod_tup = (str(last_mod.year), str(last_mod.month).zfill(2), str(last_mod.day).zfill(2), str(last_mod.hour).zfill(2), str(last_mod.minute).zfill(2), str(last_mod.second).zfill(2)) last_mod_str = ('%s-%s-%s %s:%s:%s' % last_mod_...
'This function creates the size string when objects are being listed.'
def _make_size_str(self, size):
if self._human_readable: size_str = human_readable_size(size) else: size_str = str(size) return size_str.rjust(10, ' ')
'This function prints a summary of total objects and total bytes'
def _print_summary(self):
print_str = str(self._total_objects) uni_print((('\nTotal Objects: '.rjust(15, ' ') + print_str) + '\n')) if self._human_readable: print_str = human_readable_size(self._size_accumulator) else: print_str = str(self._size_accumulator) uni_print((('Total Size: '.rjust(15,...
'This takes all of the commands in the name space and puts them into a dictionary'
def _build_call_parameters(self, args, command_params):
for (name, value) in vars(args).items(): command_params[name] = value return command_params
'Calls rm --recursive on the given path.'
def _force(self, path, parsed_globals):
rm = RmCommand(self._session) rc = rm([path, '--recursive'], parsed_globals) if (rc != 0): raise RuntimeError('remove_bucket failed: Unable to delete all objects in the bucket, bucket will not be deleted.')
'This function creates the instructions based on the command name and extra parameters. Note that all commands must have an s3_handler instruction in the instructions and must be at the end of the instruction list because it sends the request to S3 and does not yield anything.'
def create_instructions(self):
if self.needs_filegenerator(): self.instructions.append('file_generator') if self.parameters.get('filters'): self.instructions.append('filters') if (self.cmd == 'sync'): self.instructions.append('comparator') self.instructions.append('file_info_builder') s...
'Determines the sync strategy for the command. It defaults to the default sync strategies but a customizable sync strategy can overide the default strategy if it returns the instance of its self when the event is emitted.'
def choose_sync_strategies(self):
sync_strategies = {} sync_strategies['file_at_src_and_dest_sync_strategy'] = SizeAndLastModifiedSync() sync_strategies['file_not_at_dest_sync_strategy'] = MissingFileSync() sync_strategies['file_not_at_src_sync_strategy'] = NeverSync() responses = self.session.emit('choosing-s3-sync-strategy', param...
'This function wires together all of the generators and completes the command. First a dictionary is created that is indexed first by the command name. Then using the instruction, another dictionary can be indexed to obtain the objects corresponding to the particular instruction for that command. To begin the wiring...
def run(self):
src = self.parameters['src'] dest = self.parameters['dest'] paths_type = self.parameters['paths_type'] files = FileFormat().format(src, dest, self.parameters) rev_files = FileFormat().format(dest, src, self.parameters) cmd_translation = {'locals3': 'upload', 's3s3': 'copy', 's3local': 'download'...
'Stores command name and parameters. Ensures that the ``dir_op`` flag is true if a certain command is being used. :param cmd: The name of the command, e.g. "rm". :param parameters: A dictionary of parameters. :param usage: A usage string'
def __init__(self, cmd, parameters, usage):
self.cmd = cmd self.parameters = parameters self.usage = usage if ('dir_op' not in parameters): self.parameters['dir_op'] = False if ('follow_symlinks' not in parameters): self.parameters['follow_symlinks'] = True if ('source_region' not in parameters): self.parameters['s...
'Reformats the parameters dictionary by including a key and value for the source and the destination. If a destination is not used the destination is the same as the source to ensure the destination always have some value.'
def add_paths(self, paths):
self.check_path_type(paths) self._normalize_s3_trailing_slash(paths) src_path = paths[0] self.parameters['src'] = src_path if (len(paths) == 2): self.parameters['dest'] = paths[1] elif (len(paths) == 1): self.parameters['dest'] = paths[0] self._validate_streaming_paths() ...
'This initial check ensures that the path types for the specified command is correct.'
def check_path_type(self, paths):
template_type = {'s3s3': ['cp', 'sync', 'mv'], 's3local': ['cp', 'sync', 'mv'], 'locals3': ['cp', 'sync', 'mv'], 's3': ['mb', 'rb', 'rm'], 'local': [], 'locallocal': []} paths_type = '' usage = ('usage: aws s3 %s %s' % (self.cmd, self.usage)) for i in range(len(paths)): if paths[i].s...
'Adds endpoint_url to the parameters.'
def add_endpoint_url(self, parsed_globals):
if ('endpoint_url' in parsed_globals): self.parameters['endpoint_url'] = getattr(parsed_globals, 'endpoint_url') else: self.parameters['endpoint_url'] = None
'This is the generalized function to yield the ``FileInfo`` objects. ``dir_op`` and ``use_src_name`` flags affect which files are used and ensure the proper destination paths and compare keys are formed.'
def call(self, files):
function_table = {'s3': self.list_objects, 'local': self.list_files} source = files['src']['path'] src_type = files['src']['type'] dest_type = files['dest']['type'] file_iterator = function_table[src_type](source, files['dir_op']) for (src_path, extra_information) in file_iterator: (dest...
'This function yields the appropriate local file or local files under a directory depending on if the operation is on a directory. For directories a depth first search is implemented in order to follow the same sorted pattern as a s3 list objects operation outputs. It yields the file\'s source path, size, and last upd...
def list_files(self, path, dir_op):
(join, isdir, isfile) = (os.path.join, os.path.isdir, os.path.isfile) (error, listdir) = (os.error, os.listdir) if (not self.should_ignore_file(path)): if (not dir_op): stats = self._safely_get_file_stats(path) if stats: (yield stats) else: ...
'The purpose of this function is to ensure that the same path seperator is used when sorting. In windows, the path operator is a backslash as opposed to a forward slash which can lead to differences in sorting between s3 and a windows machine.'
def normalize_sort(self, names, os_sep, character):
names.sort(key=(lambda item: item.replace(os_sep, character)))
'We can get a UnicodeDecodeError if we try to listdir(<unicode>) and can\'t decode the contents with sys.getfilesystemencoding(). In this case listdir() returns the bytestring, which means that join(<unicode>, <str>) could raise a UnicodeDecodeError. When this happens we warn using a FileDecodingError that provides m...
def should_ignore_file_with_decoding_warnings(self, dirname, filename):
if (not isinstance(filename, six.text_type)): decoding_error = FileDecodingError(dirname, filename) warning = create_warning(repr(filename), decoding_error.error_message) self.result_queue.put(warning) return True path = os.path.join(dirname, filename) return self.should_igno...
'This function checks whether a file should be ignored in the file generation process. This includes symlinks that are not to be followed and files that generate warnings.'
def should_ignore_file(self, path):
if (not self.follow_symlinks): if (os.path.isdir(path) and path.endswith(os.sep)): path = path[:(-1)] if os.path.islink(path): return True warning_triggered = self.triggers_warning(path) if warning_triggered: return True return False
'This function checks the specific types and properties of a file. If the file would cause trouble, the function adds a warning to the result queue to be printed out and returns a boolean value notify whether the file caused a warning to be generated. Files that generate warnings are skipped. Currently, this function ...
def triggers_warning(self, path):
if (not os.path.exists(path)): warning = create_warning(path, 'File does not exist.') self.result_queue.put(warning) return True if is_special_file(path): warning = create_warning(path, 'File is character special device, block special device, FIFO...
'This function yields the appropriate object or objects under a common prefix depending if the operation is on objects under a common prefix. It yields the file\'s source path, size, and last update.'
def list_objects(self, s3_path, dir_op):
(bucket, prefix) = find_bucket_key(s3_path) if ((not dir_op) and prefix): (yield self._list_single_object(s3_path)) else: lister = BucketLister(self._client) for key in lister.list_objects(bucket=bucket, prefix=prefix, page_size=self.page_size): (source_path, response_dat...
':type sync_type: string :param sync_type: This determines where the sync strategy will be used. There are three strings to choose from: \'file_at_src_and_dest\': apply sync strategy on a file that exists both at the source and the destination. \'file_not_at_dest\': apply sync strategy on a file that exists at the sour...
def __init__(self, sync_type='file_at_src_and_dest'):
self._check_sync_type(sync_type) self._sync_type = sync_type
'Registers the sync strategy class to the given session.'
def register_strategy(self, session):
session.register('building-arg-table.sync', self.add_sync_argument) session.register('choosing-s3-sync-strategy', self.use_sync_strategy)
'Subclasses should implement this method. This function takes two ``FileStat`` objects (one from the source and one from the destination). Then makes a decision on whether a given operation (e.g. a upload, copy, download) should be allowed to take place. The function currently raises a ``NotImplementedError``. So thi...
def determine_should_sync(self, src_file, dest_file):
raise NotImplementedError('determine_should_sync')
'timedelta\'s time_seconds() function for python 2.6 users :param td: The difference between two datetime objects.'
def total_seconds(self, td):
return ((td.microseconds + ((td.seconds + ((td.days * 24) * 3600)) * (10 ** 6))) / (10 ** 6))
':returns: True if the sizes are the same. False otherwise.'
def compare_size(self, src_file, dest_file):
return (src_file.size == dest_file.size)
':returns: True if the file does not need updating based on time of last modification and type of operation. False if the file does need updating based on the time of last modification and type of operation.'
def compare_time(self, src_file, dest_file):
src_time = src_file.last_update dest_time = dest_file.last_update delta = (dest_time - src_time) cmd = src_file.operation_name if ((cmd == 'upload') or (cmd == 'copy')): if (self.total_seconds(delta) >= 0): return True else: return False elif (cmd == 'down...
':var patterns: A list of patterns. A pattern consits of a list whose first member is a string \'exclude\' or \'include\'. The second member is the actual rule. :var rootdir: The root directory where the patterns are evaluated. This will generally be the directory of the source location. :var dst_rootdir: The destinati...
def __init__(self, patterns, rootdir, dst_rootdir):
self._original_patterns = patterns self.patterns = self._full_path_patterns(patterns, rootdir) self.dst_patterns = self._full_path_patterns(patterns, dst_rootdir)
'This function iterates over through the yielded file_info objects. It determines the type of the file and applies pattern matching to determine if the rule applies. While iterating though the patterns the file is assigned a boolean flag to determine if a file should be yielded on past the filer. Anything identified...
def call(self, file_infos):
for file_info in file_infos: file_path = file_info.src file_status = (file_info, True) for (pattern, dst_pattern) in zip(self.patterns, self.dst_patterns): current_file_status = self._match_pattern(pattern, file_info) if (current_file_status is not None): ...
'This function preforms the actual comparisons. The parameters it takes are the generated files for both the source and the destination. The key concept in this function is that no matter the type of where the files are coming from, they are listed in the same order, least to greatest in collation order. This allows...
def call(self, src_files, dest_files):
src_done = False dest_done = False src_take = True dest_take = True while True: try: if ((not src_done) and src_take): src_file = advance_iterator(src_files) except StopIteration: src_file = None src_done = True try: ...
'Determines if the source compare_key is less than, equal to, or greater than the destination compare_key'
def compare_comp_key(self, src_file, dest_file):
src_comp_key = src_file.compare_key dest_comp_key = dest_file.compare_key if (src_comp_key == dest_comp_key): return 'equal' elif (src_comp_key < dest_comp_key): return 'less_than' else: return 'greater_than'
'Factory for S3TransferHandlers :type cli_params: dict :param cli_params: The parameters provide to the CLI command :type runtime_config: RuntimeConfig :param runtime_config: The runtime config for the CLI command being run'
def __init__(self, cli_params, runtime_config):
self._cli_params = cli_params self._runtime_config = runtime_config
'Creates a S3TransferHandler instance :type client: botocore.client.Client :param client: The client to power the S3TransferHandler :type result_queue: queue.Queue :param result_queue: The result queue to be used to process results for the S3TransferHandler :returns: A S3TransferHandler instance'
def __call__(self, client, result_queue):
transfer_config = create_transfer_config_from_runtime_config(self._runtime_config) transfer_config.max_in_memory_upload_chunks = self.MAX_IN_MEMORY_CHUNKS transfer_config.max_in_memory_download_chunks = self.MAX_IN_MEMORY_CHUNKS transfer_manager = TransferManager(client, transfer_config) LOGGER.debu...
'Backend for performing S3 transfers :type transfer_manager: s3transfer.manager.TransferManager :param transfer_manager: Transfer manager to use for transfers :type cli_params: dict :param cli_params: The parameters passed to the CLI command in the form of a dictionary :type result_command_recorder: ResultCommandRecord...
def __init__(self, transfer_manager, cli_params, result_command_recorder):
self._transfer_manager = transfer_manager self._result_command_recorder = result_command_recorder submitter_args = (self._transfer_manager, self._result_command_recorder.result_queue, cli_params) self._submitters = [UploadStreamRequestSubmitter(*submitter_args), DownloadStreamRequestSubmitter(*submitter...
'Process iterable of FileInfos for transfer :type fileinfos: iterable of FileInfos param fileinfos: Set of FileInfos to submit to underlying transfer request submitters to make transfer API calls to S3 :rtype: CommandResult :returns: The result of the command that specifies the number of failures and warnings encounter...
def call(self, fileinfos):
with self._result_command_recorder: with self._transfer_manager: total_submissions = 0 for fileinfo in fileinfos: for submitter in self._submitters: if submitter.can_submit(fileinfo): if submitter.submit(fileinfo): ...
'Submits transfer requests to the TransferManager Given a FileInfo object and provided CLI parameters, it will add the necessary extra arguments and subscribers in making a call to the TransferManager. :type transfer_manager: s3transfer.manager.TransferManager :param transfer_manager: The underlying transfer manager :t...
def __init__(self, transfer_manager, result_queue, cli_params):
self._transfer_manager = transfer_manager self._result_queue = result_queue self._cli_params = cli_params
'Submits a transfer request based on the FileInfo provided There is no guarantee that the transfer request will be made on behalf of the fileinfo as a fileinfo may be skipped based on circumstances in which the transfer is not possible. :type fileinfo: awscli.customizations.s3.fileinfo.FileInfo :param fileinfo: The Fil...
def submit(self, fileinfo):
should_skip = self._warn_and_signal_if_skip(fileinfo) if (not should_skip): return self._do_submit(fileinfo)
'Checks whether it can submit a particular FileInfo :type fileinfo: awscli.customizations.s3.fileinfo.FileInfo :param fileinfo: The FileInfo to check if the transfer request submitter can handle. :returns: True if it can use the provided FileInfo to make a transfer request to the underlying transfer manager. False, oth...
def can_submit(self, fileinfo):
raise NotImplementedError('can_submit()')
'Returns formatted versions of a fileinfos source and destination.'
def _format_src_dest(self, fileinfo):
raise NotImplementedError('_format_src_dest')
'Create and convert a runtime config dictionary. This method will merge and convert S3 runtime configuration data into a single dictionary that can then be passed to classes that use this runtime config. :param kwargs: Any key in the ``DEFAULTS`` dict. :return: A dictionary of the merged and converted values.'
def build_config(self, **kwargs):
runtime_config = DEFAULTS.copy() if kwargs: runtime_config.update(kwargs) self._convert_human_readable_sizes(runtime_config) self._validate_config(runtime_config) return runtime_config
'Subscriber to send result notifications during transfer process :param result_queue: The queue to place results to be processed later on.'
def __init__(self, result_queue, transfer_type=None):
self._result_queue = result_queue self._result_kwargs_cache = {} self._transfer_type = transfer_type if (transfer_type is None): self._transfer_type = self.TRANSFER_TYPE
'Record the result of an individual Result object'
def __call__(self, result):
self._result_handler_map.get(type(result), self._record_noop)(result=result)
'Prints status of ongoing transfer :type result_recorder: ResultRecorder :param result_recorder: The associated result recorder :type out_file: file-like obj :param out_file: Location to write progress and success statements. By default, the location is sys.stdout. :type error_file: file-like obj :param error_file: Loc...
def __init__(self, result_recorder, out_file=None, error_file=None):
self._result_recorder = result_recorder self._out_file = out_file if (self._out_file is None): self._out_file = sys.stdout self._error_file = error_file if (self._error_file is None): self._error_file = sys.stderr self._progress_length = 0 self._result_handler_map = {Progress...
'Print the progress of the ongoing transfer based on a result'
def __call__(self, result):
self._result_handler_map.get(type(result), self._print_noop)(result=result)
'Thread to process results from result queue This includes recording statistics and printing transfer status :param result_queue: The result queue to process results from :param result_handlers: A list of callables that take a result in as a parameter to process the result for that handler.'
def __init__(self, result_queue, result_handlers=None):
threading.Thread.__init__(self) self._result_queue = result_queue self._result_handlers = result_handlers if (self._result_handlers is None): self._result_handlers = [] self._result_handlers_enabled = True
'Records the result for an entire command It will fully process all results in a result queue and determine a CommandResult representing the entire command. :type result_queue: queue.Queue :param result_queue: The result queue in which results are placed on and processed from :type result_recorder: ResultRecorder :para...
def __init__(self, result_queue, result_recorder, result_processor):
self.result_queue = result_queue self._result_recorder = result_recorder self._result_processor = result_processor
'Get the CommandResult representing the result of a command :rtype: CommandResult :returns: The CommandResult representing the total result from running a particular command'
def get_command_result(self):
return CommandResult((self._result_recorder.files_failed + self._result_recorder.errors), self._result_recorder.files_warned)
'Hydrate the original structure with the value of this flattened argument. TODO: This does not hydrate nested structures (``XmlName1.XmlName2``)! To do this for now you must provide your own ``hydrate`` method.'
def add_to_params(self, parameters, value):
container = self._container.argument_model.name cli_type = self._container.cli_type_name key = self._property LOG.debug('Hydrating {0}[{1}]'.format(container, key)) if (value is not None): if (self.type == 'boolean'): value = (not (value.lower() == 'false')) elif (self...
'Register with a CLI instance, listening for events that build the argument table for operations in the configuration dict.'
def register(self, cli):
service = self.service_name for operation in self.configs: cli.register('building-argument-table.{0}.{1}'.format(service, operation), self.flatten_args)
'Find and return a nested argument, if it exists. If no nested argument is requested then the original argument is returned. If the nested argument cannot be found, then a ValueError is raised.'
def _find_nested_arg(self, argument, name):
if (SEP in name): LOG.debug('Finding nested argument in {0}'.format(name)) for piece in name.split(SEP)[:(-1)]: for (member_name, member) in argument.members.items(): if (member_name == piece): argument = member break ...
'Merges an existing config taken from the configuration dict with an existing member of an existing argument object. This pulls in attributes like ``required`` and ``help_text`` if they have not been overridden in the configuration dict. Modifies the config in-place.'
def _merge_member_config(self, argument, name, config):
for (member_name, member) in argument.members.items(): if (member_name == name.split(SEP)[(-1)]): if ('help_text' not in config): config['help_text'] = member.documentation if ('required' not in config): config['required'] = (member_name in argument.re...
'Saves the result of a JMESPath expression to a file. This method only saves the query data if the response code of the parsed result is < 300.'
def save_query(self, parsed, **kwargs):
if is_parsed_result_successful(parsed): contents = jmespath.search(self.query, parsed) with open(self.value, 'w') as fp: if (contents is None): fp.write('') else: fp.write(contents) os.chmod(self.value, self.perm)
'Creates an S3 client that can work with the given bucket name'
def get_client(self, bucket_name):
region_name = self._get_bucket_region(bucket_name) return self._create_client(region_name)
'Returns the region of a bucket'
def _get_bucket_region(self, bucket_name):
if (bucket_name not in self._region_cache): client = self._create_client(self._get_bucket_location_region) result = client.get_bucket_location(Bucket=bucket_name) region = (result['LocationConstraint'] or 'us-east-1') self._region_cache[bucket_name] = region return self._region_c...
'Creates an Amazon S3 client for the given region name'
def _create_client(self, region_name):
if (region_name not in self._client_cache): client = self._session.create_client('s3', region_name) self._client_cache[region_name] = client return self._client_cache[region_name]
'Loads public keys in a date range into a returned dict. :type start_date: datetime :param start_date: Start date of a date range. :type end_date: datetime :param end_date: End date of a date range. :rtype: dict :return: Returns a dict where each key is the fingerprint of the public key, and each value is a dict of pub...
def get_public_keys(self, start_date, end_date):
public_keys = self._cloudtrail_client.list_public_keys(StartTime=start_date, EndTime=end_date) public_keys_in_range = public_keys['PublicKeyList'] LOG.debug('Loaded public keys in range: %s', public_keys_in_range) return dict(((key['Fingerprint'], key) for key in public_keys_in_range))
'Returns a list of digest keys in the date range. This method uses a list_objects API call and provides a Marker parameter that is calculated based on the start_date provided. Amazon S3 then returns all keys in the bucket that start after the given key (non-inclusive). We then iterate over the keys until the date extra...
def load_digest_keys_in_range(self, bucket, prefix, start_date, end_date):
digests = [] marker = self._create_digest_key(start_date, prefix) client = self._client_provider.get_client(bucket) paginator = client.get_paginator('list_objects') page_iterator = paginator.paginate(Bucket=bucket, Marker=marker) key_filter = page_iterator.search('Contents[*].Key') target_st...
'Loads a digest by key from S3. Returns the JSON decode data and GZIP inflated raw content.'
def fetch_digest(self, bucket, key):
client = self._client_provider.get_client(bucket) result = client.get_object(Bucket=bucket, Key=key) try: digest = zlib.decompress(result['Body'].read(), (zlib.MAX_WBITS | 16)) digest_data = json.loads(digest.decode()) except (ValueError, ZLibError): raise InvalidDigestFormat(buc...
'Computes an Amazon S3 key based on the provided data. The computed is what would have been placed in the S3 bucket if a log digest were created at a specific time. This computed key does not have to actually exist as it will only be used to as a Marker parameter in a list_objects call. :return: Returns a computed key ...
def _create_digest_key(self, start_date, key_prefix):
date = (start_date - timedelta(minutes=1)) template = 'AWSLogs/{account}/CloudTrail-Digest/{source_region}/{ymd}/{account}_CloudTrail-Digest_{source_region}_{name}_{home_region}_{date}.json.gz' key = template.format(account=self.account_id, date=format_date(date), ymd=date.strftime('%Y/%m/%d'), source_regio...
'Creates a regular expression used to match against S3 keys'
def _create_digest_key_regex(self, key_prefix):
template = 'AWSLogs/{account}/CloudTrail\\-Digest/{source_region}/\\d+/\\d+/\\d+/{account}_CloudTrail\\-Digest_{source_region}_{name}_{home_region}_.+\\.json\\.gz' key = template.format(account=re.escape(self.account_id), source_region=re.escape(self.trail_source_region), home_region=re.escape(self.trail_home_r...
':type digest_provider: DigestProvider :param digest_provider: DigestProvider object :param starting_bucket: S3 bucket where the digests are stored. :param starting_prefix: An optional prefix applied to each S3 key. :param public_key_provider: Provides public keys for a range. :param digest_validator: Validates digest ...
def __init__(self, digest_provider, starting_bucket, starting_prefix, public_key_provider, digest_validator=None, on_invalid=None, on_gap=None, on_missing=None):
self.starting_bucket = starting_bucket self.starting_prefix = starting_prefix self.digest_provider = digest_provider self._public_key_provider = public_key_provider self._on_gap = on_gap self._on_invalid = on_invalid self._on_missing = on_missing if (digest_validator is None): di...
'Creates and returns a generator that yields validated digest data. Each yielded digest dictionary contains information about the digest and the log file associated with the digest. Digest files are validated before they are yielded. Whether or not the digest is successfully validated is stated in the "isValid" key val...
def traverse(self, start_date, end_date=None):
if (end_date is None): end_date = datetime.utcnow() end_date = normalize_date(end_date) start_date = normalize_date(start_date) bucket = self.starting_bucket prefix = self.starting_prefix digests = self._load_digests(bucket, prefix, start_date, end_date) public_keys = self._load_publ...
'Finds the next digest in the bucket and invokes any callback.'
def _find_next_digest(self, digests, bucket, last_key, last_start_date, cb=None, is_cb_conditional=False, message=None):
(next_key, next_end_date) = self._get_last_digest(digests, last_key) if (cb and ((not is_cb_conditional) or next_key)): cb(bucket=bucket, next_key=next_key, last_key=last_key, next_end_date=next_end_date, last_start_date=last_start_date, message=message) return (next_key, next_end_date)
'Finds the previous digest key (either the last or before before_key) If no key is provided, the last digest is used. If a digest is found, the end date of the provider is adjusted to match the found key\'s end date.'
def _get_last_digest(self, digests, before_key=None):
if (not digests): return (None, None) elif (before_key is None): next_key = digests.pop() next_key_date = normalize_date(parse_date(extract_digest_key_date(next_key))) return (next_key, next_key_date) before_key_date = parse_date(extract_digest_key_date(before_key)) while...
'Loads and validates a digest from S3. :param public_keys: Public key dictionary of fingerprint to dict. :return: Returns a tuple of the digest data as a dict and end_date :rtype: tuple'
def _load_and_validate_digest(self, public_keys, bucket, key):
(digest_data, digest) = self.digest_provider.fetch_digest(bucket, key) for required_key in self.required_digest_keys: if (required_key not in digest_data): raise InvalidDigestFormat(bucket, key) if ((digest_data['digestS3Bucket'] != bucket) or (digest_data['digestS3Object'] != key)): ...
'Validates a digest file. Throws a DigestError when the digest is invalid. :param bucket: Bucket of the digest file :param key: Key of the digest file :param public_key: Public key bytes. :param digest_data: Dict of digest data returned when JSON decoding a manifest. :param inflated_digest: Inflated digest file content...
def validate(self, bucket, key, public_key, digest_data, inflated_digest):
try: decoded_key = base64.b64decode(public_key) public_key = rsa.PublicKey.load_pkcs1(decoded_key, format='DER') to_sign = self._create_string_to_sign(digest_data, inflated_digest) signature_bytes = binascii.unhexlify(digest_data['_signature']) rsa.verify(to_sign, signature_b...
'Download a log, decompress, and compare SHA256 checksums'
def _download_log(self, log):
try: client = self.s3_client_provider.get_client(log['s3Bucket']) response = client.get_object(Bucket=log['s3Bucket'], Key=log['s3Object']) gzip_inflater = zlib.decompressobj((zlib.MAX_WBITS | 16)) rolling_hash = hashlib.sha256() for chunk in iter((lambda : response['Body'].r...
'Run the command. Calls various services based on input options and outputs the final CloudTrail configuration.'
def _call(self, options, parsed_globals):
gse = options.include_global_service_events if gse: if (gse.lower() == 'true'): gse = True elif (gse.lower() == 'false'): gse = False else: raise ValueError('You must pass either true or false to --include-global-service-events....
'Creates a new S3 bucket with an appropriate policy to let CloudTrail write to the prefix path.'
def setup_new_bucket(self, bucket, prefix, custom_policy=None):
sys.stdout.write('Setting up new S3 bucket {bucket}...\n'.format(bucket=bucket)) account_id = get_account_id(self.sts) if (prefix and (not prefix.endswith('/'))): prefix += '/' if (custom_policy is not None): policy = custom_policy else: policy = self._get_poli...
'Creates a new SNS topic with an appropriate policy to let CloudTrail post messages to the topic.'
def setup_new_topic(self, topic, custom_policy=None):
sys.stdout.write('Setting up new SNS topic {topic}...\n'.format(topic=topic)) account_id = get_account_id(self.sts) try: topics = self.sns.list_topics()['Topics'] except Exception: topics = [] LOG.warn('Unable to list topics, continuing...') if [t f...
'Merge two SNS topic policy documents. The id information from ``left`` is used in the final document, and the statements from ``right`` are merged into ``left``. http://docs.aws.amazon.com/sns/latest/dg/BasicStructure.html :type left: string :param left: First policy JSON document :type right: string :param right: Sec...
def merge_sns_policy(self, left, right):
left_parsed = json.loads(left) right_parsed = json.loads(right) left_parsed['Statement'] += right_parsed['Statement'] return json.dumps(left_parsed)
'Either create or update the CloudTrail configuration depending on whether this command is a create or update command.'
def upsert_cloudtrail_config(self, name, bucket, prefix, topic, gse):
sys.stdout.write('Creating/updating CloudTrail configuration...\n') config = {'Name': name} if (bucket is not None): config['S3BucketName'] = bucket if (prefix is not None): config['S3KeyPrefix'] = prefix if (topic is not None): config['SnsTopicName'] = topic if (gs...
'Start the CloudTrail service, which begins logging.'
def start_cloudtrail(self, name):
sys.stdout.write('Starting CloudTrail service...\n') return self.cloudtrail.start_logging(Name=name)
'This gets called with the value of our ``--priv-launch-key`` if it is specified. It needs to determine if the path provided is valid and, if it is, it stores it in the instance variable ``_key_path`` for use by the decrypt routine.'
def add_to_params(self, parameters, value):
if value: path = os.path.expandvars(value) path = os.path.expanduser(path) if os.path.isfile(path): self._key_path = path endpoint_prefix = self._operation_model.service_model.endpoint_prefix event = ('after-call.%s.%s' % (endpoint_prefix, self._operation_...
'This handler gets called after the GetPasswordData command has been executed. It is called with the and the ``parsed`` data. It checks to see if a private launch key was specified on the command. If it was, it tries to use that private key to decrypt the password data and replace it in the returned data dictionary....
def _decrypt_password_data(self, parsed, **kwargs):
if (self._key_path is not None): logger.debug('Decrypting password data using: %s', self._key_path) value = parsed.get('PasswordData') if (not value): return try: with open(self._key_path) as pk_file: pk_contents = pk_file.read() ...
'Register `inject` for each target operation.'
def register(self, event_emitter):
event_template = 'calling-command.ec2.%s' for operation in self.TARGET_OPERATIONS: event = (event_template % operation) event_emitter.register_last(event, self.inject)
'Conditionally inject PageSize.'
def inject(self, event_name, parsed_globals, call_parameters, **kwargs):
if (not parsed_globals.paginate): return pagination_config = call_parameters.get('PaginationConfig', {}) if ('PageSize' in pagination_config): return operation_name = event_name.split('.')[(-1)] whitelisted_params = self.TARGET_OPERATIONS.get(operation_name) if (whitelisted_param...
'Retrieve value from a cache key.'
def __getitem__(self, cache_key):
actual_key = self._convert_cache_key(cache_key) try: with open(actual_key) as f: return json.load(f) except (OSError, ValueError, IOError): raise KeyError(cache_key)
'Validates command line arguments before doing anything else.'
def prevalidate_arguments(self, args):
if ((not args.target) and (not args.local)): raise ValueError('One of target or --local is required.') elif (args.target and args.local): raise ValueError('Arguments target and --local are mutually exclusive.') if (args.local and (platform.system() != 'Lin...
'Retrieves the stack from the API, thereby ensures that it exists. Provides `self._stack`, `self._prov_params`, `self._use_address`, and `self._ec2_instance`.'
def retrieve_stack(self, args):
LOG.debug('Retrieving stack and provisioning parameters') self._stack = self.opsworks.describe_stacks(StackIds=[args.stack_id])['Stacks'][0] self._prov_params = self.opsworks.describe_stack_provisioning_parameters(StackId=self._stack['StackId']) if ((args.infrastructure_class == 'ec2') and (...
'Validates command line arguments using the retrieved information.'
def validate_arguments(self, args):
if args.hostname: instances = self.opsworks.describe_instances(StackId=self._stack['StackId'])['Instances'] if any(((args.hostname.lower() == instance['Hostname']) for instance in instances)): raise ValueError(("Invalid hostname: '%s'. Hostnames must be unique within...
'Determine details (like the address to connect to and the hostname to use) from the given arguments and the retrieved data. Provides `self._use_address` (if not provided already), `self._use_hostname` and `self._name_for_iam`.'
def determine_details(self, args):
if (not self._use_address): if args.local: pass elif (args.infrastructure_class == 'ec2'): if ('PublicIpAddress' in self._ec2_instance): self._use_address = self._ec2_instance['PublicIpAddress'] elif ('PrivateIpAddress' in self._ec2_instance): ...
'Creates an IAM group, user and corresponding credentials. Provides `self.access_key`.'
def create_iam_entities(self, args):
if args.use_instance_profile: LOG.debug('Skipping IAM entity creation') self.access_key = None return LOG.debug('Creating the IAM group if necessary') group_name = ('OpsWorks-%s' % clean_for_iam(self._stack['StackId'])) try: self.iam.create_group(G...
'Setups the target machine by copying over the credentials and starting the installation process.'
def setup_target_machine(self, args):
remote_script = (REMOTE_SCRIPT % {'agent_installer_url': self._prov_params['AgentInstallerUrl'], 'preconfig': self._to_ruby_yaml(self._pre_config_document(args)), 'assets_download_bucket': self._prov_params['Parameters']['assets_download_bucket']}) if args.local: LOG.debug('Running the installer ...
'Runs a (sh) script on a remote machine via SSH.'
def ssh(self, args, remote_script):
if (platform.system() == 'Windows'): try: script_file = tempfile.NamedTemporaryFile('wt', delete=False) script_file.write(remote_script) script_file.close() if args.ssh: call = args.ssh else: call = 'plink' ...
'Checks if a CloudFormation stack with given name exists :param stack_name: Name or ID of the stack :return: True if stack exists. False otherwise'
def has_stack(self, stack_name):
try: resp = self._client.describe_stacks(StackName=stack_name) if (len(resp['Stacks']) != 1): return False stack = resp['Stacks'][0] return (stack['StackStatus'] != 'REVIEW_IN_PROGRESS') except botocore.exceptions.ClientError as e: msg = str(e) if ('St...
'Call Cloudformation to create a changeset and wait for it to complete :param stack_name: Name or ID of stack :param cfn_template: CloudFormation template string :param parameter_values: Template parameters object :param capabilities: Array of capabilities passed to CloudFormation :return:'
def create_changeset(self, stack_name, cfn_template, parameter_values, capabilities):
now = datetime.utcnow().isoformat() description = 'Created by AWS CLI at {0} UTC'.format(now) changeset_name = (self.changeset_prefix + str(int(time.time()))) changeset_type = 'UPDATE' if (not self.has_stack(stack_name)): changeset_type = 'CREATE' parameter_values =...
'Waits until the changeset creation completes :param changeset_id: ID or name of the changeset :param stack_name: Stack name :return: Latest status of the create-change-set operation'
def wait_for_changeset(self, changeset_id, stack_name):
sys.stdout.write('Waiting for changeset to be created..\n') sys.stdout.flush() waiter = self._client.get_waiter('change_set_create_complete') waiter.config.delay = 5 try: waiter.wait(ChangeSetName=changeset_id, StackName=stack_name) except botocore.exceptions.WaiterError a...