Assume only first container_definition to get the container info.
 Stack:arn:aws:cloudformation:... is in ROLLBACK_COMPLETE state and can not be updated.
552621
def handle_stack_error(e)
      case e.message
      when /is in ROLLBACK_COMPLETE state and can not be updated/
        puts "The #{@stack_name} stack is in #{"ROLLBACK_COMPLETE".color(:red)} and cannot be updated. Deleted the stack and try again."
        region = `aws configure get region`.strip rescue 'us-east-1'
        url = "https://console.aws.amazon.com/cloudformation/home?region=#{region}"
        puts "Here's the CloudFormation console url: #{url}"
        exit 1
      when /No updates are to be performed/
        puts "There are no updates to be performed. Exiting.".color(:yellow)
        exit 1
      else
        raise
      end
    end
733128
async def container(self, container=None, container_type=None, params=None):
        
        # Container versioning is a bit tricky, primitive type containers are not versioned.
        elem_type = x.container_elem_type(container_type, params)
        raw_container = container_is_raw(container_type, params)
        elem_elementary = TypeWrapper.is_elementary_type(elem_type)
        is_versioned = not elem_elementary and not raw_container
        version = None

        if is_versioned:
            version = await self.version(container_type, params, elem=container)
            if self.is_tracked():
                return self.get_tracked()

        if hasattr(container_type, 'boost_serialize'):
            container = container_type() if container is None else container
            self.pop_track(is_versioned)
            return await container.boost_serialize(self, elem=container, elem_type=container_type, params=params, version=version)

        # Container entry version + container
        if self.writing:
            self.pop_track(is_versioned)
            return await self.container_dump(container, container_type, params)
        else:
            obj = await self.container_load(container_type, params=params, container=container)
            return self.track_obj(obj, is_versioned)
309286
public static String getSerializedContainerInfo(CmsContainer container) throws Exception {

        return CmsGwtActionElement.serialize(I_CmsContainerpageService.class.getMethod("getContainerInfo"), container);
    }
3678
def _retrieve_stack_host_zone_name(awsclient, default_stack_name=None):
    
    global _host_zone_name

    if _host_zone_name is not None:
        return _host_zone_name

    env = get_env()

    if env is None:
        print("Please set environment...")
        # TODO: why is there a sys.exit in library code used by cloudformation!!!
        sys.exit()

    if default_stack_name is None:
        # TODO why 'dp-<env>'? - this should not be hardcoded!
        default_stack_name = 'dp-%s' % env
    default_stack_output = get_outputs_for_stack(awsclient, default_stack_name)

    if HOST_ZONE_NAME__STACK_OUTPUT_NAME not in default_stack_output:
        print("Please debug why default stack '{}' does not contain '{}'...".format(
                default_stack_name,
                HOST_ZONE_NAME__STACK_OUTPUT_NAME,
        ))
        # TODO: why is there a sys.exit in library code used by cloudformation!!!
        sys.exit()

    _host_zone_name = default_stack_output[HOST_ZONE_NAME__STACK_OUTPUT_NAME] + "."
    return _host_zone_name
756126
function _doesEventContainsNestedStackId(stack) {
    if (stack.ResourceType !== 'AWS::CloudFormation::Stack') {
        return false;
    }
    if (stack.ResourceStatusReason !== 'Resource creation Initiated') {
        return false;
    }
    if (stack.ResourceStatus !== 'CREATE_IN_PROGRESS') {
        return false;
    }
    if (_.isNil(stack.PhysicalResourceId)) {
        return false;
    }

    return _hasLabelNestedStackName(stack.PhysicalResourceId);
}
89224
def getstate(self):
        
        # the jobstore never existed
        if not os.path.exists(self.jobstorefile):
            logging.info('Workflow ' + self.run_id + ': QUEUED')
            return "QUEUED", -1

        # completed earlier
        if os.path.exists(self.statcompletefile):
            logging.info('Workflow ' + self.run_id + ': COMPLETE')
            return "COMPLETE", 0

        # errored earlier
        if os.path.exists(self.staterrorfile):
            logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR')
            return "EXECUTOR_ERROR", 255

        # the workflow is staged but has not run yet
        if not os.path.exists(self.errfile):
            logging.info('Workflow ' + self.run_id + ': INITIALIZING')
            return "INITIALIZING", -1

        # TODO: Query with "toil status"
        completed = False
        with open(self.errfile, 'r') as f:
            for line in f:
                if 'Traceback (most recent call last)' in line:
                    logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR')
                    open(self.staterrorfile, 'a').close()
                    return "EXECUTOR_ERROR", 255
                # run can complete successfully but fail to upload outputs to cloud buckets
                # so save the completed status and make sure there was no error elsewhere
                if 'Finished toil run successfully.' in line:
                    completed = True
        if completed:
            logging.info('Workflow ' + self.run_id + ': COMPLETE')
            open(self.statcompletefile, 'a').close()
            return "COMPLETE", 0

        logging.info('Workflow ' + self.run_id + ': RUNNING')
        return "RUNNING", -1
635734
def get_stack_info(self, stack):
        
        stack_name = stack['StackId']

        try:
            template = self.cloudformation.get_template(
                StackName=stack_name)['TemplateBody']
        except botocore.exceptions.ClientError as e:
            if "does not exist" not in str(e):
                raise
            raise exceptions.StackDoesNotExist(stack_name)

        parameters = self.params_as_dict(stack.get('Parameters', []))

        return [json.dumps(template), parameters]
586937
def delete_stack(awsclient, conf, feedback=True):
    
    client_cf = awsclient.get_client('cloudformation')
    stack_name = _get_stack_name(conf)
    last_event = _get_stack_events_last_timestamp(awsclient, stack_name)

    request = {}
    dict_selective_merge(request, conf['stack'], ['StackName', 'RoleARN'])

    response = client_cf.delete_stack(**request)

    if feedback:
        return _poll_stack_events(awsclient, stack_name, last_event)
782484
def check_for_completion
      return unless all_work_units_complete?
      set_next_status
      outs = gather_outputs_from_work_units
      return queue_for_workers([outs]) if merging?
      if complete?
        update_attributes(:outputs => outs, :time => time_taken)
        CloudCrowd.log "Job ##{id} (#{action}) #{display_status}." unless ENV['RACK_ENV'] == 'test'
        CloudCrowd.defer { fire_callback } if callback_url
      end
      self
    end
78462
def get(self, container):
        
        name = utils.get_name(container)
        uri = "/%s" % name
        resp, resp_body = self.api.method_head(uri)
        hdrs = resp.headers
        data = {"total_bytes": int(hdrs.get("x-container-bytes-used", "0")),
                "object_count": int(hdrs.get("x-container-object-count", "0")),
                "name": name}
        return Container(self, data, loaded=False)
900970
async def container(self, container=None, container_type=None, params=None, obj=None):
        
        if hasattr(container_type, 'kv_serialize'):
            container = container_type() if container is None else container
            return await container.kv_serialize(self, elem=container, elem_type=container_type, params=params, obj=obj)

        # Container entry version + container
        if self.writing:
            return await self.container_dump(container, container_type, params, obj=obj)
        else:
            return await self.container_load(container_type, params=params, container=container, obj=obj)
849032
def _get_current_deployment_label(self):
        '''
        
        '''
        deploymentId = self._get_current_deployment_id()
        deployment = __salt__['boto_apigateway.describe_api_deployment'](restApiId=self.restApiId,
                                                                         deploymentId=deploymentId,
                                                                         **self._common_aws_args).get('deployment')
        if deployment:
            return deployment.get('description')
        return None
777592
def _save_or_update(self):
        
        with self._resource_lock:
            if not self._config or not self._config._storage_path:
                raise Exception("self._config._storage path is undefined")
            if not self._config._base_name:
                raise Exception("self._config._base_name is undefined")
            if not os.path.exists(self._config._storage_path):
                os.makedirs(self._config._storage_path)
            path = self._get_cloud_provider_storage_path()
            with open(path, 'wb') as storage:
                pickle.dump(self._config, storage, pickle.HIGHEST_PROTOCOL)
                pickle.dump(self._subscriptions, storage,
                            pickle.HIGHEST_PROTOCOL)
1119816
def get_ec2_info(connection,
                 instance_id,
                 region,
                 username=None):
    
    instance = connection.get_only_instances(
        filters={'instance_id': instance_id}
        )[0]

    data = instance.__dict__
    data['state'] = instance.state
    data['cloud_type'] = 'ec2'

    try:
        volume = connection.get_all_volumes(
            filters={'attachment.instance-id': instance.id}
        )[0].id
        data['volume'] = volume
    except:
        data['volume'] = ''
    return data
852991
def get_containers():
        
        LOGGER.debug("ContainerService.get_containers")
        params = SessionService.complete_transactional_req(None)
        if params is None:
            if MappingService.driver_type != DriverFactory.DRIVER_REST:
                params = {'OPERATION': 'getContainers'}
                args = {'properties': params}
            else:
                args = {'http_operation': 'GET', 'operation_path': ''}
        else:
            if MappingService.driver_type != DriverFactory.DRIVER_REST:
                params["OPERATION"] = "getContainers"
                args = {'properties': params}
            else:
                args = {'http_operation': 'GET', 'operation_path': '', 'parameters': params}

        response = ContainerService.requester.call(args)

        if MappingService.driver_type != DriverFactory.DRIVER_REST:
            response = response.get()

        ret = None
        if response.rc == 0:
            ret = []
            for container in response.response_content['containers']:
                ret.append(Container.json_2_container(container))
        elif response.rc != 404:
            err_msg = 'ContainerService.get_containers - Problem while getting containers. ' \
                      'Reason: ' + str(response.response_content) + ' - ' + str(response.error_message) + \
                      " (" + str(response.rc) + ")"
            LOGGER.warning(err_msg)
            if response.rc == 500 and ArianeMappingOverloadError.ERROR_MSG in response.error_message:
                raise ArianeMappingOverloadError("ContainerService.get_containers",
                                                 ArianeMappingOverloadError.ERROR_MSG)
            # traceback.print_stack()
        return ret
636924
def create(definition: dict, version: str, parameter: tuple,
           region: str,
           disable_rollback: bool,
           dry_run: bool,
           force: bool,
           tag: List[str],
           timeout: int,
           keep_stacks: Optional[int],
           traffic: int,
           verbose: bool,
           remote: str,
           parameter_file: Optional[str]
           ):
    
    lizzy = setup_lizzy_client(remote)
    parameter = list(parameter) or []
    if parameter_file:
        parameter.extend(read_parameter_file(parameter_file))

    if not force:  # pragma: no cover
        # supporting artifact checking would imply copying a large amount of code
        # from senza, so it should be considered out of scope until senza
        # and lizzy client are merged
        warning("WARNING: "
                "Artifact checking is still not supported by lizzy-client.")

    with Action('Requesting new stack..') as action:
        new_stack, output = lizzy.new_stack(keep_stacks, traffic,
                                            definition, version,
                                            disable_rollback, parameter,
                                            region=region,
                                            dry_run=dry_run,
                                            tags=tag)

    stack_id = '{stack_name}-{version}'.format_map(new_stack)
    print(output)

    info('Stack ID: {}'.format(stack_id))

    if dry_run:
        info("Post deployment steps skipped")
        exit(0)

    with Action('Waiting for new stack...') as action:
        if verbose:
            print()  # ensure that new states will not be printed on the same line as the action

        last_state = None
        for state in lizzy.wait_for_deployment(stack_id, region=region):
            if state != last_state and verbose:
                click.echo(' {}'.format(state))
            else:
                action.progress()
            last_state = state

        # TODO be prepared to handle all final AWS CF states
        if last_state == 'ROLLBACK_COMPLETE':
            fatal_error(
                'Stack was rollback after deployment. Check your application log for possible reasons.')
        elif last_state != 'CREATE_COMPLETE':
            fatal_error('Deployment failed: {}'.format(last_state))

    info('Deployment Successful')

    if traffic is not None:
        with Action('Requesting traffic change..'):
            try:
                lizzy.traffic(stack_id, traffic, region=region)
            except requests.ConnectionError as e:
                connection_error(e, fatal=False)
            except requests.HTTPError as e:
                agent_error(e, fatal=False)

    # TODO unit test this
    if keep_stacks is not None:
        versions_to_keep = keep_stacks + 1
        stacks_to_remove_counter = 1
        end_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=timeout)
        while stacks_to_remove_counter > 0 and datetime.datetime.utcnow() <= end_time:
            try:
                all_stacks = lizzy.get_stacks([new_stack['stack_name']],
                                              region=region)
            except requests.ConnectionError as e:
                connection_error(e, fatal=False)
                error("Failed to fetch old stacks. "
                      "Old stacks WILL NOT BE DELETED")
                exit(1)
            except requests.HTTPError as e:
                agent_error(e, fatal=False)
                error("Failed to fetch old stacks. "
                      "Old stacks WILL NOT BE DELETED")
                exit(1)
            else:
                sorted_stacks = sorted(all_stacks,
                                       key=lambda stack: stack['creation_time'])
                stacks_to_remove = sorted_stacks[:-versions_to_keep]
                stacks_to_remove_counter = len(stacks_to_remove)
                with Action('Deleting old stacks..'):
                    print()
                    for old_stack in stacks_to_remove:
                        old_stack_id = '{stack_name}-{version}'.format_map(
                            old_stack)
                        if old_stack['status'] in COMPLETE_STATES:
                            click.echo(' {}'.format(old_stack_id))
                            try:
                                lizzy.delete(old_stack_id, region=region)
                                stacks_to_remove_counter -= 1
                            except requests.ConnectionError as e:
                                connection_error(e, fatal=False)
                            except requests.HTTPError as e:
                                agent_error(e, fatal=False)
                        else:
                            click.echo(' > {} current status is {} trying '
                                       'again later'.format(old_stack_id,
                                                            old_stack['status']))
                if stacks_to_remove_counter > 0:
                    time.sleep(5)

        if datetime.datetime.utcnow() > end_time:
            click.echo('Timeout waiting for related stacks to be ready.')
334176
def get_state(self, sls, saltenv, cachedir=None):
        '''
        
        '''
        if '.' in sls:
            sls = sls.replace('.', '/')
        sls_url = salt.utils.url.create(sls + '.sls')
        init_url = salt.utils.url.create(sls + '/init.sls')
        for path in [sls_url, init_url]:
            dest = self.cache_file(path, saltenv, cachedir=cachedir)
            if dest:
                return {'source': path, 'dest': dest}
        return {}