Example #1
0
    def execute(self, parameter_pool):
        create_eb_local_dir()

        app_name = parameter_pool.get_value(ParameterName.ApplicationName)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName)
        location = parameter_pool.get_value(ParameterName.OptionSettingFile)            

        prompt.action(SaveConfigurationSettingOpMessage.Start.format(env_name))
        
        try:
            option_settings = api_wrapper.retrieve_configuration_settings(parameter_pool,
                                                                          app_name,
                                                                          env_name)
            config_file.save_env_option_setting_file(location, option_settings)
        except Exception as ex:
            # Never fail. Just log event if any exception
            log.info(u'Cannot dump environment option settings before termination, because '.\
                     format(misc.to_unicode(ex)))
            option_settings = None
        else:
            log.info(SaveConfigurationSettingOpMessage.Succeed.format(location))
            prompt.info(SaveConfigurationSettingOpMessage.Succeed.format(location))
                   
        ret_result = OperationResult(self,
                                     None, 
                                     None,
                                     option_settings)
        return ret_result
Example #2
0
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName,
                                            False)

        try:
            response = eb_client.create_application(app_name)
            prompt.result(CreateApplicationOpMessage.Start.format(app_name))
        except AlreadyExistException:
            log.info(u'Application "{0}" already exists.'.format(app_name))
            prompt.result(
                CreateApplicationOpMessage.AlreadyExist.format(app_name))

            ret_result = OperationResult(
                self, None,
                CreateApplicationOpMessage.AlreadyExist.format(app_name), None)
        else:
            log.info(u'Received response for CreateApplication call.')
            prompt.info(CreateApplicationOpMessage.Succeed.format(app_name))
            self._log_api_result(self.__class__.__name__, u'CreateApplication',
                                 response.result)

            ret_result = OperationResult(
                self, response.request_id,
                CreateApplicationOpMessage.Succeed.format(app_name),
                response.result)

        return ret_result
Example #3
0
    def _request_with_retry(self, verb, url, headers, data, max_tries = 5):
    
        durations = _exponential_backoff(max_tries)
        
        for index, length in enumerate(durations):
            if length > 0:
                log.debug(u'Sleeping for %f seconds before retrying', length)
                time.sleep(length)
    
            try:
                if verb == HTTP_GET:
                    response = requests.get(url, headers = headers, verify=True)
                elif verb == HTTP_POST:
                    response = requests.post(url, data = data, headers = headers, verify=True)
                else:
                    raise AttributeError(u'Not supported HTTP action "{0}".'.format(verb))

                # check status code
                if response.status_code != 200:
                    http_code = response.status_code
                    try:
                        aws_code = response.json[u'Error'][u'Code']
                        message = response.json[u'Error'][u'Message']
                    except TypeError as ex:
                        raise AttributeError(u'HTTP {0}: {1}'.format(http_code, response.text))

                    if http_code < 500 and aws_code != AwsErrorCode.Throttling:
                        raise AwsServiceException(message, aws_code, http_code)
                    
                    elif AwsErrorCode.Throttling == aws_code or http_code == 503:
                        prompt.info(u'Request is throttled.')
                        _extend_backoff(durations)
                        
                    if index + 1 < len(durations):
                        prompt.info(u'Error {0}:{1}. Wait {2} seconds before retry.'.\
                                     format(aws_code, message, durations[index + 1]))
                    log.error(message + u' ' + aws_code)
                    last_message = message
                    
                else:
                    if response.json is None:
                        raise ValueError(u'Cannot parse response form {0}.'.format(response.url))
                    return response
            
            except requests.exceptions.SSLError as ex:
                log.error(u'SSL Error: %s', ex)
                raise
            
            except (requests.exceptions.HTTPError, 
                    requests.exceptions.ConnectionError,
                    requests.exceptions.Timeout) as ex:
                log.error(ex)
                last_message = ex
                
        else:
            if aws_code is None:
                aws_code = u''
            if http_code is None:
                http_code = u''
            raise AwsServiceException(last_message, aws_code, http_code)
    def execute(self, parameter_pool):
        eb_client = ElasticBeanstalkClient(parameter_pool.get_value(ParameterName.AwsAccessKeyId), 
                                           parameter_pool.get_value(ParameterName.AwsSecretAccessKey),
                                           parameter_pool.get_value(ParameterName.ServiceEndpoint))

        app_name = parameter_pool.get_value(ParameterName.ApplicationName)

        try:
            response = eb_client.create_application(app_name)
            prompt.result(CreateApplicationOpMessage.Start.format(app_name))
        except AlreadyExistException:
            log.info('Application "{0}" already exists.'.format(app_name))
            prompt.result(CreateApplicationOpMessage.AlreadyExist.format(app_name))
   
            ret_result = OperationResult(self,
                                         None, 
                                         CreateApplicationOpMessage.AlreadyExist.format(app_name),
                                         None)
        else:
            log.info('Received response for CreateApplication call.')
            prompt.info(CreateApplicationOpMessage.Succeed.format(app_name))
            self._log_api_result(self.__class__.__name__, 'CreateApplication', response.result)            
    
            ret_result = OperationResult(self,
                                         response.request_id, 
                                         CreateApplicationOpMessage.Succeed.format(app_name),
                                         response.result)
            
        return ret_result
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName, False)
        version_name = eb_utils.check_app_version(parameter_pool, eb_client)         
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName, False)
        stack_name = parameter_pool.get_value(ParameterName.SolutionStack, False)
        tier = parameter_pool.get_value(ParameterName.EnvironmentTier, False)

        spec = TemplateSpecification()
        
        # Try load option setting file if exist
        option_location = parameter_pool.get_value(ParameterName.OptionSettingFile, False)
        option_settings = config_file.load_env_option_setting_file(option_location,
                                                                   quiet = True)
        if option_settings is not None and len(option_settings) > 0:
            prompt.info(CreateEnvironmentOpMessage.UsingOptionSetting.format(option_location))
        else:
            option_settings = dict()

        option_remove = dict()
        
        # Process extensions first before we process options
        self._extension_handler(parameter_pool, spec, stack_name, option_settings, option_remove)
        
        # Process options
        self._option_setting_handler(parameter_pool, spec, stack_name, None, option_settings, option_remove)
                 
        prompt.action(CreateEnvironmentOpMessage.Start.format(env_name))
        try:
            response = eb_client.create_environment(application = app_name,
                                                    environment = env_name,
                                                    solution_stack = stack_name,
                                                    version_label = version_name,
                                                    option_settings = option_settings,
                                                    option_remove = option_remove,
                                                    template_specification = spec,
                                                    tier = tier)
        except AlreadyExistException:
            log.info(u'Environment "{0}" already exist.'.format(env_name))
            prompt.result(CreateEnvironmentOpMessage.AlreadyExist.format(env_name))
   
            ret_result = OperationResult(self, 
                                         None, 
                                        CreateEnvironmentOpMessage.AlreadyExist.format(env_name), 
                                         None)
        else:
            log.info(u'Received response for CreateEnvironemnt call.')
            prompt.info(CreateEnvironmentOpMessage.Succeed)
            prompt.result(CreateEnvironmentOpMessage.WaitAfterLaunch.format(env_name))
            self._log_api_result(self.__class__.__name__, u'CreateEnvironment', response.result)            
            
            parameter_pool.put(Parameter(ParameterName.CreateEnvironmentRequestID,
                                         response.request_id,
                                         ParameterSource.OperationOutput))
            
            ret_result = OperationResult(self,
                                         response.request_id, 
                                         CreateEnvironmentOpMessage.Succeed,
                                         response.result)
        return ret_result
Example #6
0
def _print_op_results(results):
    for index, result in enumerate(results):
        prompt.info(
            "------------ Operation {0}: {1}----------------".format(index + 1, result.operation.__class__.__name__)
        )
        _pprint(result.result, depth=3)
        print(result.message)
Example #7
0
    def execute(self, parameter_pool):
        eb_client = ElasticBeanstalkClient(
            parameter_pool.get_value(ParameterName.AwsAccessKeyId),
            parameter_pool.get_value(ParameterName.AwsSecretAccessKey),
            parameter_pool.get_value(ParameterName.ServiceEndpoint))

        app_name = parameter_pool.get_value(ParameterName.ApplicationName)

        try:
            response = eb_client.create_application(app_name)
            prompt.result(CreateApplicationOpMessage.Start.format(app_name))
        except AlreadyExistException:
            log.info('Application "{0}" already exists.'.format(app_name))
            prompt.result(
                CreateApplicationOpMessage.AlreadyExist.format(app_name))

            ret_result = OperationResult(
                self, None,
                CreateApplicationOpMessage.AlreadyExist.format(app_name), None)
        else:
            log.info('Received response for CreateApplication call.')
            prompt.info(CreateApplicationOpMessage.Succeed.format(app_name))
            self._log_api_result(self.__class__.__name__, 'CreateApplication',
                                 response.result)

            ret_result = OperationResult(
                self, response.request_id,
                CreateApplicationOpMessage.Succeed.format(app_name),
                response.result)

        return ret_result
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName, False)

        try:
            response = eb_client.create_application_version(app_name, ServiceDefault.DEFAULT_VERSION_NAME)
        except AlreadyExistException:
            log.info(
                u'Version "{0}" of Application "{1}" already exists.'.format(
                    ServiceDefault.DEFAULT_VERSION_NAME, app_name
                )
            )
            msg = CreateApplicationVersionOpMessage.AlreadyExist.format(ServiceDefault.DEFAULT_VERSION_NAME)
            prompt.info(msg)

            ret_result = OperationResult(self, None, msg, None)
        else:
            log.info(u"Received response for CreateApplicationVersion call.")
            self._log_api_result(self.__class__.__name__, u"CreateApplicationVersion", response.result)
            msg = CreateApplicationVersionOpMessage.Succeed.format(ServiceDefault.DEFAULT_VERSION_NAME)
            prompt.info(msg)

            ret_result = OperationResult(self, response.request_id, msg, response.result)

        return ret_result
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName, False)

        try:
            response = eb_client.create_application(app_name)
            prompt.result(CreateApplicationOpMessage.Start.format(app_name))
        except AlreadyExistException:
            log.info(u'Application "{0}" already exists.'.format(app_name))
            prompt.result(CreateApplicationOpMessage.AlreadyExist.format(app_name))
   
            ret_result = OperationResult(self,
                                         None, 
                                         CreateApplicationOpMessage.AlreadyExist.format(app_name),
                                         None)
        else:
            log.info(u'Received response for CreateApplication call.')
            prompt.info(CreateApplicationOpMessage.Succeed.format(app_name))
            self._log_api_result(self.__class__.__name__, u'CreateApplication', response.result)            
    
            ret_result = OperationResult(self,
                                         response.request_id, 
                                         CreateApplicationOpMessage.Succeed.format(app_name),
                                         response.result)
            
        return ret_result
Example #10
0
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName,
                                            False)

        try:
            response = eb_client.create_application_version(
                app_name, ServiceDefault.DEFAULT_VERSION_NAME)
        except AlreadyExistException:
            log.info(u'Version "{0}" of Application "{1}" already exists.'.\
                     format(ServiceDefault.DEFAULT_VERSION_NAME, app_name))
            msg = CreateApplicationVersionOpMessage.AlreadyExist.format(
                ServiceDefault.DEFAULT_VERSION_NAME)
            prompt.info(msg)

            ret_result = OperationResult(self, None, msg, None)
        else:
            log.info(u'Received response for CreateApplicationVersion call.')
            self._log_api_result(self.__class__.__name__,
                                 u'CreateApplicationVersion', response.result)
            msg = CreateApplicationVersionOpMessage.Succeed.format(
                ServiceDefault.DEFAULT_VERSION_NAME)
            prompt.info(msg)

            ret_result = OperationResult(self, response.request_id, msg,
                                         response.result)

        return ret_result
Example #11
0
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName,
                                            False)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName,
                                            False)

        response = eb_client.describe_environments(app_name,
                                                   env_name,
                                                   include_deleted=False)
        if len(response.result) > 0:  # If have result
            version_name = response.result[0].version_label
            log.info(
                'Retrieved application version {0} for environment {1}'.format(
                    version_name, env_name))
            prompt.info(
                RecordApplicationVersionOpMessage.Succeed.format(version_name))
            parameter_pool.put(
                Parameter(ParameterName.ApplicationVersionName, version_name,
                          ParameterSource.OperationOutput), True)

        ret_result = OperationResult(self, response.request_id, None,
                                     response.result)

        return ret_result
Example #12
0
    def _request_with_retry(self, verb, url, headers, data, max_tries = 5):
    
        durations = _exponential_backoff(max_tries)
        
        for index, length in enumerate(durations):
            if length > 0:
                log.debug('Sleeping for %f seconds before retrying', length)
                time.sleep(length)
    
            try:
                if verb == HTTP_GET:
                    response = requests.get(url, headers = headers, verify=True)
                elif verb == HTTP_POST:
                    response = requests.post(url, data = data, headers = headers, verify=True)
                else:
                    raise AttributeError('Not supported HTTP action "{0}".'.format(verb))

                # check status code
                if response.status_code != 200:
                    http_code = response.status_code
                    try:
                        aws_code = response.json['Error']['Code']
                        message = response.json['Error']['Message']
                    except TypeError as ex:
                        raise AttributeError('HTTP {0}: {1}'.format(http_code, response.text))

                    if http_code < 500 and aws_code != AwsErrorCode.Throttling:
                        raise AwsServiceException(message, aws_code, http_code)
                    
                    elif AwsErrorCode.Throttling == aws_code or http_code == 503:
                        prompt.info('Request is throttled.')
                        _extend_backoff(durations)
                        
                    if index + 1 < len(durations):
                        prompt.info('Error {0}:{1}. Wait {2} seconds before retry.'.\
                                     format(aws_code, message, durations[index + 1]))
                    log.error(message + ' ' + aws_code)
                    last_message = message
                    
                else:
                    if response.json is None:
                        raise ValueError('Cannot parse response form {0}.'.format(response.url))
                    return response
            
            except requests.exceptions.SSLError as ex:
                log.error('SSL Error: %s', ex)
                raise
            
            except (requests.exceptions.HTTPError, 
                    requests.exceptions.ConnectionError,
                    requests.exceptions.Timeout) as ex:
                log.error(ex)
                last_message = ex
                
        else:
            if aws_code is None:
                aws_code = ''
            if http_code is None:
                http_code = ''
            raise AwsServiceException(last_message, aws_code, http_code)
    def execute(self, parameter_pool):
        create_eb_local_dir()

        app_name = parameter_pool.get_value(ParameterName.ApplicationName)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName)
        location = parameter_pool.get_value(ParameterName.OptionSettingFile)            

        prompt.action(SaveConfigurationSettingOpMessage.Start.format(env_name))
        
        try:
            option_settings = api_wrapper.retrieve_configuration_settings(parameter_pool,
                                                                          app_name,
                                                                          env_name)
            config_file.save_env_option_setting_file(location, option_settings)
        except Exception as ex:
            # Never fail. Just log event if any exception
            log.info('Cannot dump environment option settings before termination, because '.\
                     format(misc.to_unicode(ex)))
            option_settings = None
        else:
            log.info(SaveConfigurationSettingOpMessage.Succeed.format(location))
            prompt.info(SaveConfigurationSettingOpMessage.Succeed.format(location))
                   
        ret_result = OperationResult(self,
                                     None, 
                                     None,
                                     option_settings)
        return ret_result
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName,
                                            False)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName,
                                            False)
        stack_name = parameter_pool.get_value(ParameterName.SolutionStack,
                                              False)
        prompt.action(
            UpdateEnvironmentOptionSettingOpMessage.Start.format(env_name))

        spec = TemplateSpecification()

        # Try load option setting file if exist
        option_location = parameter_pool.get_value(
            ParameterName.OptionSettingFile, False)
        option_settings = config_file.load_env_option_setting_file(
            option_location, quiet=True)
        if option_settings is not None and len(option_settings) > 0:
            prompt.info(
                UpdateEnvironmentOptionSettingOpMessage.UsingOptionSetting.
                format(option_location))
        else:
            option_settings = dict()

        option_remove = dict()
        self._option_setting_handler(parameter_pool, spec, stack_name,
                                     option_settings, option_remove)

        self._validate_change(parameter_pool, eb_client, app_name, env_name,
                              option_settings, option_remove, spec)

        try:
            response = eb_client.update_environment(
                env_name,
                option_settings=option_settings,
                option_remove=option_remove,
                template_specification=spec)
        except:
            raise
        else:
            log.info(u'Received response for UpdateEnvironemnt call.')
            prompt.result(
                UpdateEnvironmentOptionSettingOpMessage.Succeed.format(
                    env_name))

            self._log_api_result(self.__class__.__name__, u'UpdateEnvironment',
                                 response.result)

            parameter_pool.put(
                Parameter(ParameterName.UpdateEnvironmentRequestID,
                          response.request_id,
                          ParameterSource.OperationOutput))

            ret_result = OperationResult(
                self, response.request_id,
                UpdateEnvironmentOptionSettingOpMessage.Succeed.format(
                    env_name), response.result)
        return ret_result
Example #15
0
    def _request_with_retry(self, verb, url, headers, data, max_tries=5):

        durations = _exponential_backoff(max_tries)

        for index, length in enumerate(durations):
            if length > 0:
                log.debug("Sleeping for %f seconds before retrying", length)
                time.sleep(length)

            try:
                if verb == HTTP_GET:
                    response = requests.get(url, headers=headers, verify=True)
                elif verb == HTTP_POST:
                    response = requests.post(url, data=data, headers=headers, verify=True)
                else:
                    raise AttributeError('Not supported HTTP action "{0}".'.format(verb))

                # check status code
                if response.status_code != 200:
                    http_code = response.status_code
                    aws_code = response.json["Error"]["Code"]
                    message = response.json["Error"]["Message"]

                    if http_code < 500 and aws_code != AwsErrorCode.Throttling:
                        raise AwsServiceException(message, aws_code, http_code)

                    elif AwsErrorCode.Throttling == aws_code or http_code == 503:
                        _extend_backoff(durations)

                    if index + 1 < len(durations):
                        prompt.info(
                            "Error {0}:{1}. Wait {2} seconds before retry.".format(
                                aws_code, message, durations[index + 1]
                            )
                        )
                    log.error(message + " " + aws_code)
                    last_message = message

                else:
                    return response

            except requests.exceptions.SSLError as ex:
                log.error("SSL Error: %s", ex)
                raise

            except (
                requests.exceptions.HTTPError,
                requests.exceptions.ConnectionError,
                requests.exceptions.Timeout,
            ) as ex:
                last_message = ex

        else:
            if aws_code is None:
                aws_code = ""
            if http_code is None:
                http_code = ""
            raise AwsServiceException(last_message, aws_code, http_code)
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName, False)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName, False)
        stack_name = parameter_pool.get_value(ParameterName.SolutionStack, False)
        prompt.action(UpdateEnvironmentOptionSettingOpMessage.Start.format(env_name))
        tier = parameter_pool.get_value(ParameterName.EnvironmentTier, False)

        spec = TemplateSpecification()

        # Try load option setting file if exist
        option_location = parameter_pool.get_value(ParameterName.OptionSettingFile, False)
        option_settings = config_file.load_env_option_setting_file(option_location, quiet=True)
        if option_settings is not None and len(option_settings) > 0:
            prompt.info(UpdateEnvironmentOptionSettingOpMessage.UsingOptionSetting.format(option_location))
        else:
            option_settings = dict()

        option_remove = dict()

        # Process extensions first before we process options
        self._extension_handler(parameter_pool, spec, stack_name, option_settings, option_remove)

        # Process options
        self._option_setting_handler(parameter_pool, spec, stack_name, env_name, option_settings, option_remove)

        self._validate_change(parameter_pool, eb_client, app_name, env_name, option_settings, option_remove, spec)

        try:
            response = eb_client.update_environment(
                env_name,
                option_settings=option_settings,
                option_remove=option_remove,
                template_specification=spec,
                tier=tier,
            )
        except:
            raise
        else:
            log.info("Received response for UpdateEnvironemnt call.")
            prompt.result(UpdateEnvironmentOptionSettingOpMessage.Succeed.format(env_name))

            self._log_api_result(self.__class__.__name__, "UpdateEnvironment", response.result)

            parameter_pool.put(
                Parameter(
                    ParameterName.UpdateEnvironmentRequestID, response.request_id, ParameterSource.OperationOutput
                )
            )

            ret_result = OperationResult(
                self,
                response.request_id,
                UpdateEnvironmentOptionSettingOpMessage.Succeed.format(env_name),
                response.result,
            )
        return ret_result
    def execute(self, parameter_pool):
        eb_client = ElasticBeanstalkClient(
            parameter_pool.get_value(ParameterName.AwsAccessKeyId),
            parameter_pool.get_value(ParameterName.AwsSecretAccessKey),
            parameter_pool.get_value(ParameterName.ServiceEndpoint))
        app_name = parameter_pool.get_value(ParameterName.ApplicationName)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName)
        stack_name = parameter_pool.get_value(ParameterName.SolutionStack)
        prompt.action(
            UpdateEnvironmentOptionSettingOpMessage.Start.format(env_name))

        location = parameter_pool.get_value(ParameterName.OptionSettingFile)
        option_settings = config_file.load_env_option_setting_file(location,
                                                                   quiet=True)
        if option_settings is not None and len(option_settings) > 0:
            prompt.info(
                UpdateEnvironmentOptionSettingOpMessage.UsingOptionSetting.
                format(location))
        else:
            option_settings = []

        option_remove = set()
        spec = TemplateSpecification()
        rds_utils.rds_handler(parameter_pool, spec, stack_name,
                              option_settings, option_remove)
        self._option_setting_handler(option_settings, option_remove)

        self._validate_change(parameter_pool, eb_client, app_name, env_name,
                              option_settings, option_remove, spec)

        try:
            response = eb_client.update_environment(
                env_name,
                option_settings=option_settings,
                option_remove=option_remove,
                template_specification=spec)
        except:
            raise
        else:
            log.info('Received response for UpdateEnvironemnt call.')
            prompt.result(
                UpdateEnvironmentOptionSettingOpMessage.Succeed.format(
                    env_name))

            self._log_api_result(self.__class__.__name__, 'UpdateEnvironment',
                                 response.result)

            parameter_pool.put(
                Parameter(ParameterName.UpdateEnvironmentRequestID,
                          response.request_id,
                          ParameterSource.OperationOutput))

            ret_result = OperationResult(
                self, response.request_id,
                UpdateEnvironmentOptionSettingOpMessage.Succeed.format(
                    env_name), response.result)
        return ret_result
 def _set_parameter_value(cls, parameter_pool, name, value, source, force = False):
     # Set parameter value if not specified as before with higher priority
     if parameter_pool.has(name) \
             and Source.is_ahead(parameter_pool.get_source(name), Source.Terminal):
         value = parameter_pool.get_value(name, False)
     else:
         parameter_pool.put(Parameter(name, value, source), force)
     
     prompt.info(TerminalPromptSettingParameterMessage[name].format(value))        
Example #19
0
    def execute(self, parameter_pool):
        eb_client = ElasticBeanstalkClient(parameter_pool.get_value(ParameterName.AwsAccessKeyId), 
                                           parameter_pool.get_value(ParameterName.AwsSecretAccessKey),
                                           parameter_pool.get_value(ParameterName.ServiceEndpoint))
        app_name = parameter_pool.get_value(ParameterName.ApplicationName)
        version_name = parameter_pool.get_value(ParameterName.ApplicationVersionName)        
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName)
        stack_name = parameter_pool.get_value(ParameterName.SolutionStack)

        # Try load option setting file if exist
        option_file_location = parameter_pool.get_value(ParameterName.OptionSettingFile)             
        option_settings = config_file.load_env_option_setting_file(option_file_location,
                                                                   quiet = True)
        if option_settings is not None and len(option_settings) > 0:
            prompt.info(CreateEnvironmentOpMessage.UsingOptionSetting.format(option_file_location))
        else:
            option_settings = []

        option_remove = set()
        spec = TemplateSpecification()
        rds_utils.rds_handler(parameter_pool, spec, stack_name, option_settings, option_remove)
        self._option_setting_handler(option_settings, option_remove)
                 
        prompt.action(CreateEnvironmentOpMessage.Start.format(env_name))
        try:
            response = eb_client.create_environment(application = app_name,
                                                    environment = env_name,
                                                    solution_stack = stack_name,
                                                    version_label = version_name,
                                                    option_settings = option_settings,
                                                    option_remove = option_remove,
                                                    template_specification = spec,
                                                    )
        except AlreadyExistException:
            log.info(u'Environment "{0}" already exist.'.format(env_name))
            prompt.result(CreateEnvironmentOpMessage.AlreadyExist.format(env_name))
   
            ret_result = OperationResult(self, 
                                         None, 
                                        CreateEnvironmentOpMessage.AlreadyExist.format(env_name), 
                                         None)
        else:
            log.info(u'Received response for CreateEnvironemnt call.')
            prompt.info(CreateEnvironmentOpMessage.Succeed)
            prompt.result(CreateEnvironmentOpMessage.WaitAfterLaunch.format(env_name))
            self._log_api_result(self.__class__.__name__, u'CreateEnvironment', response.result)            
            
            parameter_pool.put(Parameter(ParameterName.CreateEnvironmentRequestID,
                                         response.request_id,
                                         ParameterSource.OperationOutput))
            
            ret_result = OperationResult(self,
                                         response.request_id, 
                                         CreateEnvironmentOpMessage.Succeed,
                                         response.result)
        return ret_result
    def execute(self, parameter_pool):
        eb_client = ElasticBeanstalkClient(
            parameter_pool.get_value(ParameterName.AwsAccessKeyId),
            parameter_pool.get_value(ParameterName.AwsSecretAccessKey),
            parameter_pool.get_value(ParameterName.ServiceEndpoint))

        env_name = parameter_pool.get_value(ParameterName.EnvironmentName)
        wait_timeout = parameter_pool.get_value(
            ParameterName.WaitForUpdateTimeout)
        poll_delay = parameter_pool.get_value(ParameterName.PollDelay)
        #        update_request_id = parameter_pool.get_value(ParameterName.UpdateEnvironmentRequestID)\
        #            if parameter_pool.has(ParameterName.UpdateEnvironmentRequestID) else None

        result = self._wait_for_env_operation_finish(
            eb_client=eb_client,
            env_name=env_name,
            original_request_id=None,
            pending_status=EnvironmentStatus.Updating,
            expected_health=EnvironmentHealth.Green,
            operation_name=self.__class__.__name__,
            action_name=WaitForUpdateEnvOptionSettingFinishOpMessage.Action,
            wait_timeout=wait_timeout,
            poll_delay=poll_delay,
            include_deleted='false',
            initial_delay=ServiceDefault.UPDATE_ENV_POLL_DELAY)

        # After polling
        status = result[0].status
        health = result[0].health
        cname = result[0].cname
        log.info('Stopped polling. Environment "{0}" is now {1}, health is {2}.\nURL is "{3}".'.\
                 format(env_name, status, health, cname))

        if status.lower() == EnvironmentStatus.Ready.lower() \
            and health.lower() == EnvironmentHealth.Green.lower():
            prompt.result(
                WaitForUpdateEnvOptionSettingFinishOpMessage.Succeed.format(
                    env_name))
        else:
            prompt.result(
                WaitForUpdateEnvOptionSettingFinishOpMessage.Timeout.format(
                    env_name))

        prompt.info(WaitForUpdateEnvOptionSettingFinishOpMessage.Result.\
                    format(cname, status, health))
        ret_result = OperationResult(self,
                                     None,
                                     WaitForUpdateEnvOptionSettingFinishOpMessage.Result.\
                                        format(cname, status, health),
                                     result)

        return ret_result
    def execute(self, parameter_pool):
        eb_client = ElasticBeanstalkClient(
            parameter_pool.get_value(ParameterName.AwsAccessKeyId),
            parameter_pool.get_value(ParameterName.AwsSecretAccessKey),
            parameter_pool.get_value(ParameterName.ServiceEndpoint),
        )

        env_name = parameter_pool.get_value(ParameterName.EnvironmentName)
        wait_timeout = parameter_pool.get_value(ParameterName.WaitForFinishTimeout)
        poll_delay = parameter_pool.get_value(ParameterName.PollDelay)
        create_request_id = (
            parameter_pool.get_value(ParameterName.CreateEnvironmentRequestID)
            if parameter_pool.has(ParameterName.CreateEnvironmentRequestID)
            else None
        )

        result = self._wait_for_env_operation_finish(
            eb_client=eb_client,
            env_name=env_name,
            original_request_id=create_request_id,
            pending_status=EnvironmentStatus.Launching,
            expected_health=None,
            operation_name=self.__class__.__name__,
            action_name=WaitForCreateEnvironmentFinishOpMessage.Action,
            wait_timeout=wait_timeout,
            poll_delay=poll_delay,
            include_deleted=u"false",
            initial_delay=0,
        )

        # After polling
        status = result[0].status
        health = result[0].health
        cname = result[0].cname
        log.info(
            u'Stopped polling. Environment "{0}" is now {1}, health is {2}.\nURL is "{3}".'.format(
                env_name, status, health, cname
            )
        )

        if status.lower() == EnvironmentStatus.Ready.lower() and health.lower() == EnvironmentHealth.Green.lower():
            prompt.info(WaitForCreateEnvironmentFinishOpMessage.Succeed.format(env_name))
            prompt.result(WaitForCreateEnvironmentFinishOpMessage.Result.format(cname))
        else:
            prompt.info(WaitForCreateEnvironmentFinishOpMessage.Timeout.format(env_name))

        ret_result = OperationResult(
            self, None, WaitForCreateEnvironmentFinishOpMessage.Result.format(cname, status, health), result
        )

        return ret_result
Example #22
0
    def _set_parameter_value(cls,
                             parameter_pool,
                             name,
                             value,
                             source,
                             force=False):
        # Set parameter value if not specified as before with higher priority
        if parameter_pool.has(name) \
                and Source.is_ahead(parameter_pool.get_source(name), Source.Terminal):
            value = parameter_pool.get_value(name)
        else:
            parameter_pool.put(Parameter(name, value, source), force)

        prompt.info(TerminalPromptSettingParameterMessage[name].format(value))
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName,
                                            False)
        wait_timeout = parameter_pool.get_value(
            ParameterName.WaitForFinishTimeout, False)
        poll_delay = parameter_pool.get_value(ParameterName.PollDelay, False)
        create_request_id = parameter_pool.get_value(
            ParameterName.CreateEnvironmentRequestID)

        result = self._wait_for_env_operation_finish(
            eb_client=eb_client,
            env_name=env_name,
            original_request_id=create_request_id,
            pending_status=EnvironmentStatus.Launching,
            expected_health=None,
            operation_name=self.__class__.__name__,
            action_name=WaitForCreateEnvironmentFinishOpMessage.Action,
            wait_timeout=wait_timeout,
            poll_delay=poll_delay,
            include_deleted=u'false',
            initial_delay=0)

        # After polling
        status = result[0].status
        health = result[0].health
        cname = result[0].cname
        log.info(u'Stopped polling. Environment "{0}" is now {1}, health is {2}.\nURL is "{3}".'.\
                 format(env_name, status, health, cname))

        if status.lower() == EnvironmentStatus.Ready.lower() \
            and health.lower() == EnvironmentHealth.Green.lower():
            prompt.info(
                WaitForCreateEnvironmentFinishOpMessage.Succeed.format(
                    env_name))
            prompt.result(
                WaitForCreateEnvironmentFinishOpMessage.Result.format(cname))
        else:
            prompt.info(
                WaitForCreateEnvironmentFinishOpMessage.Timeout.format(
                    env_name))

        ret_result = OperationResult(self,
                                     None,
                                     WaitForCreateEnvironmentFinishOpMessage.Result.\
                                        format(cname, status, health),
                                     result)

        return ret_result
    def execute(self, parameter_pool):
        eb_client = ElasticBeanstalkClient(
            parameter_pool.get_value(ParameterName.AwsAccessKeyId),
            parameter_pool.get_value(ParameterName.AwsSecretAccessKey),
            parameter_pool.get_value(ParameterName.ServiceEndpoint),
        )
        app_name = parameter_pool.get_value(ParameterName.ApplicationName)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName)
        stack_name = parameter_pool.get_value(ParameterName.SolutionStack)
        prompt.action(UpdateEnvironmentOptionSettingOpMessage.Start.format(env_name))

        location = parameter_pool.get_value(ParameterName.OptionSettingFile)
        option_settings = config_file.load_env_option_setting_file(location, quiet=True)
        if option_settings is not None and len(option_settings) > 0:
            prompt.info(UpdateEnvironmentOptionSettingOpMessage.UsingOptionSetting.format(location))
        else:
            option_settings = []

        option_remove = set()
        spec = rds_utils.rds_handler(parameter_pool, stack_name, option_settings, option_remove)
        self._validate_change(parameter_pool, eb_client, app_name, env_name, option_settings, option_remove, spec)

        try:
            response = eb_client.update_environment(
                env_name, option_settings=option_settings, option_remove=option_remove, template_specification=spec
            )
        except:
            raise
        else:
            log.info(u"Received response for UpdateEnvironemnt call.")
            prompt.result(UpdateEnvironmentOptionSettingOpMessage.Succeed.format(env_name))

            self._log_api_result(self.__class__.__name__, u"UpdateEnvironment", response.result)

            parameter_pool.put(
                Parameter(
                    ParameterName.UpdateEnvironmentRequestID, response.request_id, ParameterSource.OperationOutput
                )
            )

            ret_result = OperationResult(
                self,
                response.request_id,
                UpdateEnvironmentOptionSettingOpMessage.Succeed.format(env_name),
                response.result,
            )
        return ret_result
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName, False)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName, False)

        response = eb_client.describe_environments(app_name, env_name, include_deleted=False)
        if len(response.result) > 0:  # If have result
            version_name = response.result[0].version_label
            log.info(u"Retrieved application version {0} for environment {1}".format(version_name, env_name))
            prompt.info(RecordApplicationVersionOpMessage.Succeed.format(version_name))
            parameter_pool.put(
                Parameter(ParameterName.ApplicationVersionName, version_name, ParameterSource.OperationOutput), True
            )

        ret_result = OperationResult(self, response.request_id, None, response.result)

        return ret_result
Example #26
0
def rotate_file(location, max_retry=FileDefaultParameter.RotationMaxRetry):
    """ Rotate a file by adding a incremental postfix to filename"""
    if not os.path.exists(location):
        return

    filename = os.path.basename(location)
    path = os.path.dirname(location)
    for i in range(1, max_retry):
        new_location = os.path.join(path, (filename + "_{0}".format(i)))
        if not os.path.exists(new_location):
            log.info('Renamed file "{0}" to "{1}".'.format(location, new_location))
            prompt.info(GeneralFileMessage.RenameFile.format(location, new_location))
            os.rename(location, new_location)
            return
    else:
        log.error("Cannot rotate file {0} because all available names are used.".format(location))
        prompt.error(GeneralFileMessage.RotationNameNotAvailable.format(location))
        return
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName)
        wait_timeout = parameter_pool.get_value(ParameterName.WaitForUpdateTimeout)
        poll_delay = parameter_pool.get_value(ParameterName.PollDelay)
#        update_request_id = parameter_pool.get_value(ParameterName.UpdateEnvironmentRequestID)\
#            if parameter_pool.has(ParameterName.UpdateEnvironmentRequestID) else None

        result = self._wait_for_env_operation_finish(
                         eb_client = eb_client, 
                         env_name = env_name, 
                         original_request_id = None,
                         pending_status = EnvironmentStatus.Updating,
                         expected_health = EnvironmentHealth.Green,
                         operation_name = self.__class__.__name__, 
                         action_name = WaitForUpdateEnvOptionSettingFinishOpMessage.Action,
                         wait_timeout = wait_timeout, 
                         poll_delay = poll_delay, 
                         include_deleted = 'false',
                         initial_delay = ServiceDefault.UPDATE_ENV_POLL_DELAY)                                                     
                                                     
        # After polling
        status = result[0].status
        health = result[0].health
        cname = result[0].cname 
        log.info('Stopped polling. Environment "{0}" is now {1}, health is {2}.\nURL is "{3}".'.\
                 format(env_name, status, health, cname))
        
        if status.lower() == EnvironmentStatus.Ready.lower() \
            and health.lower() == EnvironmentHealth.Green.lower():
            prompt.result(WaitForUpdateEnvOptionSettingFinishOpMessage.Succeed.format(env_name))
        else:
            prompt.result(WaitForUpdateEnvOptionSettingFinishOpMessage.Timeout.format(env_name))

        prompt.info(WaitForUpdateEnvOptionSettingFinishOpMessage.Result.\
                    format(cname, status, health))
        ret_result = OperationResult(self,
                                     None,
                                     WaitForUpdateEnvOptionSettingFinishOpMessage.Result.\
                                        format(cname, status, health),
                                     result)

        return ret_result
        
Example #28
0
def rotate_file(location, max_retry = FileDefaultParameter.RotationMaxRetry):
    ''' Rotate a file by adding a incremental postfix to filename'''
    if not os.path.exists(location):
        return
     
    filename = os.path.basename(location)
    path = os.path.dirname(location)
    for i in range(1, max_retry):
        new_location = os.path.join(path, (filename + u'_{0}'.format(i)))
        if not os.path.exists(new_location):
            log.info(u'Renamed file "{0}" to "{1}".'.format(location, new_location))
            prompt.info(GeneralFileMessage.RenameFile.format(location, new_location))
            os.rename(location, new_location)
            return
    else:
        log.error(u'Cannot rotate file {0} because all available names are used.'.\
                  format(location))
        prompt.error(GeneralFileMessage.RotationNameNotAvailable.format(location))
        return
Example #29
0
    def execute(self, parameter_pool):
        create_eb_local_dir()

        app_name = parameter_pool.get_value(ParameterName.ApplicationName)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName)
        location = parameter_pool.get_value(ParameterName.OptionSettingFile)            

        prompt.action(SaveConfigurationSettingOpMessage.Start.format(env_name))
        
        option_settings = api_wrapper.retrieve_configuration_settings(parameter_pool,
                                                                      app_name,
                                                                      env_name)
        config_file.save_env_option_setting_file(location, option_settings)
           
        log.info(SaveConfigurationSettingOpMessage.Succeed.format(location))           
        prompt.info(SaveConfigurationSettingOpMessage.Succeed.format(location))
                   
        ret_result = OperationResult(self,
                                     None, 
                                     None,
                                     option_settings)
        return ret_result
Example #30
0
    def _urlopen_withretry(self,
                           request_or_url,
                           max_tries=5,
                           http_error_extractor=_extractAwsErrorMessage,
                           opener=_default_opener):
        """
        Exponentially retries up to max_tries to open request_or_url.
        Raises an IOError on failure
    
        http_error_extractor is a function that takes a urllib2.HTTPError and returns a tuple of
        (AWS error code, message)
        """
        durations = _exponential_backoff(max_tries)
        for index, length in enumerate(durations):
            if length > 0:
                log.debug(u'Sleeping for %f seconds before retrying', length)
                time.sleep(length)

            try:
                return opener.open(request_or_url)
            except urllib2.HTTPError as ex:
                http_code = ex.code
                aws_code, message = http_error_extractor(ex)

                if http_code < 500 and aws_code != AwsErrorCode.Throttling:
                    raise AwsServiceException(message, aws_code, http_code)
                elif AwsErrorCode.Throttling == aws_code or http_code == 503:
                    _extend_backoff(durations)

                if index + 1 < len(durations):
                    prompt.info(u'Error {0}:{1}. Wait {2} seconds before retry.'.\
                                 format(aws_code, message, durations[index + 1]))
                log.error(message + u' ' + aws_code)
                last_message = message
            except urllib2.URLError as url_ex:
                log.error(u'URLError: %s', url_ex.reason)
                raise
        else:
            raise AwsServiceException(last_message, aws_code, http_code)
Example #31
0
    def _urlopen_withretry(
        self, request_or_url, max_tries=5, http_error_extractor=_extractAwsErrorMessage, opener=_default_opener
    ):
        """
        Exponentially retries up to max_tries to open request_or_url.
        Raises an IOError on failure
    
        http_error_extractor is a function that takes a urllib2.HTTPError and returns a tuple of
        (AWS error code, message)
        """
        durations = _exponential_backoff(max_tries)
        for index, length in enumerate(durations):
            if length > 0:
                log.debug("Sleeping for %f seconds before retrying", length)
                time.sleep(length)

            try:
                return opener.open(request_or_url)
            except urllib.error.HTTPError as ex:
                http_code = ex.code
                aws_code, message = http_error_extractor(ex)

                if http_code < 500 and aws_code != AwsErrorCode.Throttling:
                    raise AwsServiceException(message, aws_code, http_code)
                elif AwsErrorCode.Throttling == aws_code or http_code == 503:
                    _extend_backoff(durations)

                if index + 1 < len(durations):
                    prompt.info(
                        "Error {0}:{1}. Wait {2} seconds before retry.".format(aws_code, message, durations[index + 1])
                    )
                log.error(message + " " + aws_code)
                last_message = message
            except urllib.error.URLError as url_ex:
                log.error("URLError: %s", url_ex.reason)
                raise
        else:
            raise AwsServiceException(last_message, aws_code, http_code)
    def execute(self, parameter_pool):
        eb_client = ElasticBeanstalkClient(
            parameter_pool.get_value(ParameterName.AwsAccessKeyId),
            parameter_pool.get_value(ParameterName.AwsSecretAccessKey),
            parameter_pool.get_value(ParameterName.ServiceEndpoint))
        app_name = parameter_pool.get_value(ParameterName.ApplicationName)
        version_name = parameter_pool.get_value(
            ParameterName.ApplicationVersionName)
        solution_stack = parameter_pool.get_value(ParameterName.SolutionStack)

        container_name = eb_utils.match_solution_stack(solution_stack)
        log.info('App container is "{0}".'.format(container_name))

        try:
            response = eb_client.create_application_version(
                app_name, version_name)
        except AlreadyExistException:
            log.info('Version "{0}" of Application "{1}" already exists.'.\
                     format(version_name, app_name))
            prompt.info(
                CreateApplicationVersionOpMessage.AlreadyExist.format(
                    version_name))

            ret_result = OperationResult(self,
                                         None,
                                         CreateApplicationVersionOpMessage.AlreadyExist.\
                                            format(version_name),
                                         None)
        else:
            log.info('Received response for CreateApplicationVersion call.')
            prompt.info(
                CreateApplicationVersionOpMessage.Succeed.format(version_name))
            self._log_api_result(self.__class__.__name__,
                                 'CreateApplicationVersion', response.result)

            ret_result = OperationResult(self,
                                         response.request_id,
                                         CreateApplicationVersionOpMessage.Succeed.\
                                            format(version_name),
                                         response.result)

        if eb_utils.has_default_app(parameter_pool, solution_stack):
            log.info('Solution stack "{0}" has default sample app.'.format(
                solution_stack))
            prompt.info(
                CreateApplicationVersionOpMessage.HasDefaultAppSource.format(
                    solution_stack))
        else:
            # Set version to None
            source = parameter_pool.get_source(
                ParameterName.ApplicationVersionName)
            parameter_pool.put(
                Parameter(ParameterName.ApplicationVersionName, None, source),
                True)

        return ret_result
    def execute(self, parameter_pool):
        eb_client = ElasticBeanstalkClient(parameter_pool.get_value(ParameterName.AwsAccessKeyId), 
                                           parameter_pool.get_value(ParameterName.AwsSecretAccessKey),
                                           parameter_pool.get_value(ParameterName.ServiceEndpoint))
        app_name = parameter_pool.get_value(ParameterName.ApplicationName)
        version_name = parameter_pool.get_value(ParameterName.ApplicationVersionName)
        solution_stack = parameter_pool.get_value(ParameterName.SolutionStack)

        container_name = eb_utils.match_solution_stack(solution_stack)
        log.info('App container is "{0}".'.format(container_name))

        try:
            response = eb_client.create_application_version(app_name, 
                                                            version_name)
        except AlreadyExistException:
            log.info('Version "{0}" of Application "{1}" already exists.'.\
                     format(version_name, app_name))
            prompt.info(CreateApplicationVersionOpMessage.AlreadyExist.format(version_name))
   
            ret_result = OperationResult(self,
                                         None, 
                                         CreateApplicationVersionOpMessage.AlreadyExist.\
                                            format(version_name),
                                         None)
        else:        
            log.info('Received response for CreateApplicationVersion call.')
            prompt.info(CreateApplicationVersionOpMessage.Succeed.format(version_name))
            self._log_api_result(self.__class__.__name__, 'CreateApplicationVersion', response.result)            

            ret_result = OperationResult(self,
                                         response.request_id, 
                                         CreateApplicationVersionOpMessage.Succeed.\
                                            format(version_name),
                                         response.result)

        if eb_utils.has_default_app(parameter_pool, solution_stack):
            log.info('Solution stack "{0}" has default sample app.'.format(solution_stack))
            prompt.info(CreateApplicationVersionOpMessage.HasDefaultAppSource.format(solution_stack))
        else:
            # Set version to None
            source = parameter_pool.get_source(ParameterName.ApplicationVersionName) 
            parameter_pool.put(Parameter(ParameterName.ApplicationVersionName, 
                                         None,
                                         source),
                               True)
            
        return ret_result
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName, False)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName, False)
        prompt.action(DescribeEnvironmentOpMessage.Start.format(env_name))

        response = eb_client.describe_environments(app_name, 
                                                   env_name, 
                                                   include_deleted = u'false')
        log.info(u'Received response for DescribeEnvironemnts call.')
        self._log_api_result(self.__class__.__name__, u'DescribeEnvironments', response.result)

        # Also look up environment resources for future use
        resources = None
        try:
            resources = api_wrapper.retrieve_environment_resources(parameter_pool, env_name)
        except InvalidParameterValueException:
            pass
        
        env_present = (len(response.result) > 0) and bool(resources)
        
        if env_present:    # If have result 
            env_info = response.result[0]
            
            message = DescribeEnvironmentOpMessage.Result.format(env_info.cname, 
                                                                 env_info.status, 
                                                                 env_info.health)
            prompt.result(message)
            
            # Display sqs queue info before environment detail
            if resources.queues:
                for queue in resources.queues:
                    message = DescribeEnvironmentOpMessage.QueueInfo.format(queue.name, queue.url)
                    prompt.result(message)
            
            tier_serialized = env_info.tier.to_serialized_string() if env_info.tier else u''
            prompt.info(DescribeEnvironmentOpMessage.Detail.format(env_info.environment_name, 
                                                                   env_info.environment_id,
                                                                   tier_serialized, 
                                                                   env_info.solution_stack_name,
                                                                   env_info.version_label, 
                                                                   env_info.date_created, 
                                                                   env_info.date_updated, 
                                                                   env_info.description if env_info.description else u''))

            # If not Green, pull the most recent warning and error events
            if env_info.health in [EnvironmentHealth.Red, EnvironmentHealth.Yellow] \
                or (env_info.status == EnvironmentStatus.Ready \
                    and env_info.health == EnvironmentHealth.Grey):
                events = eb_client.describe_events(app_name, 
                                                   env_name, 
                                                   max_records = ServiceDefault.STATUS_EVENT_MAX_NUM, 
                                                   severity = ServiceDefault.STATUS_EVENT_LEVEL)
                if len(events.result) > 0:
                    # Having one error event
                    for event in events.result:
                        msg = u'{0}\t{1}\t{2}'.format(event.event_date, 
                                                      event.severity, 
                                                      event.message)
                        log.info(u'Found last error event: {0}'.format(msg))
                        prompt.plain(msg)                
                        
            
            # Display RDS instance host info
            try:
                logical_id, rds_property = rds_utils.retrieve_rds_instance_property\
                                                        (parameter_pool, resources)
                if rds_property is not None:
                    prompt.result(DescribeEnvironmentOpMessage.RdsInfo.format\
                                  (logical_id, 
                                   rds_property.endpoint.address, 
                                   rds_property.endpoint.port))
                    prompt.info(DescribeEnvironmentOpMessage.RdsDetail.format\
                                  (rds_property.engine + u' ' + rds_property.engine_version, 
                                   rds_property.allocated_storage, 
                                   rds_property.db_instance_class, 
                                   rds_property.multi_az, 
                                   rds_property.master_username, 
                                   rds_property.instance_create_time, 
                                   rds_property.db_instance_status))
                        
            except BaseException as ex:
                log.error(u'Encountered error when retrieve environment resources: {0}.'.format(ex))
                raise

            # Subcommand
            _, subcommands = parameter_pool.command
            subcommand = subcommands[0].upper() if len(subcommands) > 0 else None
            if subcommand == SubCommandType.OPEN:
                urlpath = u''
                if len(subcommands) > 1:
                    urlpath = subcommands[1] if subcommands[1].startswith(u'/') else u'/' + subcommands[1]
                shell_utils.open_url(env_info.cname + urlpath, False)
                        
        else:
            # No result. Environment not exist.
            message = DescribeEnvironmentOpMessage.NoEnvironment.format(env_name) 
            prompt.result(message)
            
        ret_result = OperationResult(self, response.request_id, message, response.result)
        return ret_result
Example #35
0
    def _wait_for_env_operation_finish(self,
                                       eb_client,
                                       env_name,
                                       original_request_id,
                                       pending_status,
                                       expected_health,
                                       operation_name,
                                       action_name,
                                       wait_timeout,
                                       poll_delay,
                                       include_deleted='false',
                                       initial_delay=0,
                                       quiet=False):
        '''
        Loop polling environment status while it is in specified pending_status
        and/or health state, until status changes and/or health state meet expectation, 
        or reach wait_timeout threshold. While polling retrieve events related to 
        specified request_id or all recent events if not specified. 
        '''
        # Just return if not specify either pending status and health expectation
        if pending_status is None and expected_health is None:
            return

        if quiet:
            ori_prompt_level = prompt.get_level()
            prompt.set_level(OutputLevel.Quiet)

        prompt.action(BaseOpMessage.WaitForEnv.format(env_name, action_name))
        prompt.info(BaseOpMessage.UserCanInterrupt)
        _time.sleep(initial_delay)  # Wait before

        polling_start_time = _time.time()
        event_start_time = None if original_request_id is not None \
            else misc.unixtime_to_utc(_time.time())
        while _time.time() - polling_start_time < wait_timeout:

            # Retrieve related events
            log.info('Retrieving events for Environment "{0}" after UTC time {1}.'.\
                     format(env_name, event_start_time))

            event_response = eb_client.describe_events(
                None,
                env_name,
                request_id=original_request_id,
                start_time=event_start_time)

            self._log_api_result(operation_name, 'DescribeEvents',
                                 event_response.result)

            # Output events related to environment launch
            if len(event_response.result) > 0:
                # Having new events
                event_response.result.reverse()
                for event in event_response.result:
                    log.info('{0}\t{1}\t{2}'.format\
                             (event.event_date, event.severity, event.message))
                    prompt.plain('{0}\t{1}\t{2}'.format\
                                (event.event_date, event.severity, event.message))

                    event_start_time = misc.unixtime_to_utc(
                        event.event_date_raw + 0.001)


#            else:
#                prompt.action(BaseOpMessage.Running)

# Describe environment status
            env_response = eb_client.describe_environments(
                environment_names=env_name, include_deleted=include_deleted)
            if len(env_response.result) < 1:
                raise EnvironmentNotExistError(
                    BaseOpMessage.EnvNotExist.format(env_name))

            if pending_status is None:
                # No specified pending status
                if expected_health is not None \
                    and env_response.result[0].health.lower() == expected_health.lower():
                    # Meet with expected health, stop polling
                    break
            else:
                # Has specified pending status
                if env_response.result[0].status.lower(
                ) != pending_status.lower():
                    # Not in pending status
                    if expected_health is None:
                        # No expected health, stop polling
                        break
                    elif env_response.result[0].health.lower(
                    ) == expected_health.lower():
                        # Meet with expected health, stop polling
                        break

            log.info('Received response for DescribeEnvironemnts call.')
            self._log_api_result(operation_name, 'DescribeEnvironments',
                                 env_response.result)

            _time.sleep(poll_delay)
        else:
            log.error('Breach timeout threshold of waiting environment {0}.'.\
                      format(action_name))

        if quiet:
            prompt.set_level(ori_prompt_level)

        return env_response.result
Example #36
0
    def _wait_for_env_operation_finish(self, 
                                       eb_client, 
                                       env_name, 
                                       original_request_id,
                                       pending_status,
                                       expected_health,
                                       operation_name, 
                                       action_name,
                                       wait_timeout, 
                                       poll_delay, 
                                       include_deleted = u'false',
                                       initial_delay = 0,
                                       quiet = False
                                       ):
        '''
        Loop polling environment status while it is in specified pending_status
        and/or health state, until status changes and/or health state meet expectation, 
        or reach wait_timeout threshold. While polling retrieve events related to 
        specified request_id or all recent events if not specified. 
        '''
        # Just return if not specify either pending status and health expectation
        if pending_status is None and expected_health is None:
            return

        if quiet:
            ori_prompt_level = prompt.get_level()
            prompt.set_level(OutputLevel.Quiet)
        
        prompt.action(BaseOpMessage.WaitForEnv.format(env_name, action_name))
        prompt.info(BaseOpMessage.UserCanInterrupt)
        _time.sleep(initial_delay) # Wait before 
        
        polling_start_time = _time.time()
        event_start_time = None if original_request_id is not None \
            else misc.unixtime_to_utc(_time.time())
        while _time.time() - polling_start_time < wait_timeout:
            
            # Retrieve related events
            log.info(u'Retrieving events for Environment "{0}" after UTC time {1}.'.\
                     format(env_name, event_start_time))
            
            event_response = eb_client.describe_events(None, 
                                                       env_name, 
                                                       request_id = original_request_id, 
                                                       start_time = event_start_time)
                
            self._log_api_result(operation_name, u'DescribeEvents', event_response.result)
            
            # Output events related to environment launch
            if len(event_response.result) > 0:
                # Having new events
                event_response.result.reverse()
                for event in event_response.result:
                    log.info(u'{0}\t{1}\t{2}'.format\
                             (event.event_date, event.severity, event.message))
                    prompt.plain(u'{0}\t{1}\t{2}'.format\
                                (event.event_date, event.severity, event.message))
                    
                    event_start_time = misc.unixtime_to_utc(event.event_date_raw + 0.001)
#            else:
#                prompt.action(BaseOpMessage.Running)            
            
            # Describe environment status
            env_response = eb_client.describe_environments(environment_names = env_name, 
                                                           include_deleted = include_deleted)
            if len(env_response.result) < 1:
                raise EnvironmentNotExistError(BaseOpMessage.EnvNotExist.format(env_name))
            
            if pending_status is None:
                # No specified pending status
                if expected_health is not None \
                    and env_response.result[0].health.lower() == expected_health.lower():
                    # Meet with expected health, stop polling
                    break;
            else:
                # Has specified pending status
                if env_response.result[0].status.lower() != pending_status.lower():
                    # Not in pending status
                    if expected_health is None:
                        # No expected health, stop polling
                        break;
                    elif env_response.result[0].health.lower() == expected_health.lower():
                        # Meet with expected health, stop polling
                        break;
                    
            log.info(u'Received response for DescribeEnvironemnts call.')
            self._log_api_result(operation_name, u'DescribeEnvironments', env_response.result)
            
            _time.sleep(poll_delay)
        else:
            log.error(u'Breach timeout threshold of waiting environment {0}.'.\
                      format(action_name))
        
        if quiet:
            prompt.set_level(ori_prompt_level)
                    
        return env_response.result
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName, False)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName, False)
        prompt.action(DescribeEnvironmentOpMessage.Start.format(env_name))

        response = eb_client.describe_environments(app_name, 
                                                   env_name, 
                                                   include_deleted = 'false')
        log.info('Received response for DescribeEnvironemnts call.')
        self._log_api_result(self.__class__.__name__, 'DescribeEnvironments', response.result)            

        if len(response.result) > 0:    # If have result 
            env_info = response.result[0]
            message = DescribeEnvironmentOpMessage.Result.format(env_info.cname, 
                                                                 env_info.status, 
                                                                 env_info.health)          
            prompt.result(message)
            prompt.info(DescribeEnvironmentOpMessage.Detail.format(env_info.environment_name, 
                                                                   env_info.environment_id, 
                                                                   env_info.solution_stack_name, 
                                                                   env_info.version_label, 
                                                                   env_info.date_created, 
                                                                   env_info.date_updated, 
                                                                   env_info.description if env_info.description else ''))

            # If not Green, pull the most recent warning and error events
            if env_info.health in [EnvironmentHealth.Red, EnvironmentHealth.Yellow] \
                or (env_info.status == EnvironmentStatus.Ready \
                    and env_info.health == EnvironmentHealth.Grey):
                events = eb_client.describe_events(app_name, 
                                                   env_name, 
                                                   max_records = ServiceDefault.STATUS_EVENT_MAX_NUM, 
                                                   severity = ServiceDefault.STATUS_EVENT_LEVEL)
                if len(events.result) > 0:
                    # Having one error event
                    for event in events.result:
                        msg = '{0}\t{1}\t{2}'.format(event.event_date, 
                                                      event.severity, 
                                                      event.message)
                        log.info('Found last error event: {0}'.format(msg))
                        prompt.plain(msg)                
                        
                        
            # Display RDS instance host info
            try:
                logical_id, rds_property = rds_utils.retrieve_rds_instance_property\
                                                        (parameter_pool, env_name)
                if rds_property is not None:
                    prompt.result(DescribeEnvironmentOpMessage.RdsInfo.format\
                                  (logical_id, 
                                   rds_property.endpoint.address, 
                                   rds_property.endpoint.port))
                    prompt.info(DescribeEnvironmentOpMessage.RdsDetail.format\
                                  (rds_property.engine + ' ' + rds_property.engine_version, 
                                   rds_property.allocated_storage, 
                                   rds_property.db_instance_class, 
                                   rds_property.multi_az, 
                                   rds_property.master_username, 
                                   rds_property.instance_create_time, 
                                   rds_property.db_instance_status))
                        
            except BaseException as ex:
                log.error('Encountered error when retrieve environment resources: {0}.'.format(ex))
                raise
                        
        else:
            # No result. Environment not exist.
            message = DescribeEnvironmentOpMessage.NoEnvironment.format(env_name) 
            prompt.result(message)
            
        ret_result = OperationResult(self, response.request_id, message, response.result)
        return ret_result
Example #38
0
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName,
                                            False)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName,
                                            False)
        prompt.action(DescribeEnvironmentOpMessage.Start.format(env_name))

        response = eb_client.describe_environments(app_name,
                                                   env_name,
                                                   include_deleted=u'false')
        log.info(u'Received response for DescribeEnvironemnts call.')
        self._log_api_result(self.__class__.__name__, u'DescribeEnvironments',
                             response.result)

        # Also look up environment resources for future use
        resources = None
        try:
            resources = api_wrapper.retrieve_environment_resources(
                parameter_pool, env_name)
        except InvalidParameterValueException:
            pass

        env_present = (len(response.result) > 0) and bool(resources)

        if env_present:  # If have result
            env_info = response.result[0]

            message = DescribeEnvironmentOpMessage.Result.format(
                env_info.cname, env_info.status, env_info.health)
            prompt.result(message)

            # Display sqs queue info before environment detail
            if resources.queues:
                for queue in resources.queues:
                    message = DescribeEnvironmentOpMessage.QueueInfo.format(
                        queue.name, queue.url)
                    prompt.result(message)

            tier_serialized = env_info.tier.to_serialized_string(
            ) if env_info.tier else u''
            prompt.info(
                DescribeEnvironmentOpMessage.Detail.format(
                    env_info.environment_name, env_info.environment_id,
                    tier_serialized, env_info.solution_stack_name,
                    env_info.version_label, env_info.date_created,
                    env_info.date_updated,
                    env_info.description if env_info.description else u''))

            # If not Green, pull the most recent warning and error events
            if env_info.health in [EnvironmentHealth.Red, EnvironmentHealth.Yellow] \
                or (env_info.status == EnvironmentStatus.Ready \
                    and env_info.health == EnvironmentHealth.Grey):
                events = eb_client.describe_events(
                    app_name,
                    env_name,
                    max_records=ServiceDefault.STATUS_EVENT_MAX_NUM,
                    severity=ServiceDefault.STATUS_EVENT_LEVEL)
                if len(events.result) > 0:
                    # Having one error event
                    for event in events.result:
                        msg = u'{0}\t{1}\t{2}'.format(event.event_date,
                                                      event.severity,
                                                      event.message)
                        log.info(u'Found last error event: {0}'.format(msg))
                        prompt.plain(msg)

            # Display RDS instance host info
            try:
                logical_id, rds_property = rds_utils.retrieve_rds_instance_property\
                                                        (parameter_pool, resources)
                if rds_property is not None:
                    prompt.result(DescribeEnvironmentOpMessage.RdsInfo.format\
                                  (logical_id,
                                   rds_property.endpoint.address,
                                   rds_property.endpoint.port))
                    prompt.info(DescribeEnvironmentOpMessage.RdsDetail.format\
                                  (rds_property.engine + u' ' + rds_property.engine_version,
                                   rds_property.allocated_storage,
                                   rds_property.db_instance_class,
                                   rds_property.multi_az,
                                   rds_property.master_username,
                                   rds_property.instance_create_time,
                                   rds_property.db_instance_status))

            except BaseException as ex:
                log.error(
                    u'Encountered error when retrieve environment resources: {0}.'
                    .format(ex))
                raise

            # Subcommand
            _, subcommands = parameter_pool.command
            subcommand = subcommands[0].upper(
            ) if len(subcommands) > 0 else None
            if subcommand == SubCommandType.OPEN:
                urlpath = u''
                if len(subcommands) > 1:
                    urlpath = subcommands[1] if subcommands[1].startswith(
                        u'/') else u'/' + subcommands[1]
                shell_utils.open_url(env_info.cname + urlpath, False)

        else:
            # No result. Environment not exist.
            message = DescribeEnvironmentOpMessage.NoEnvironment.format(
                env_name)
            prompt.result(message)

        ret_result = OperationResult(self, response.request_id, message,
                                     response.result)
        return ret_result
Example #39
0
def _print_op_results(results):
    for index, result in enumerate(results):
        prompt.info('------------ Operation {0}: {1}----------------'.format\
                    (index + 1, result.operation.__class__.__name__))
        pprint(result.result, depth=3)
        print(result.message)
Example #40
0
    def execute(self, parameter_pool):
        eb_client = self._get_eb_client(parameter_pool)
        app_name = parameter_pool.get_value(ParameterName.ApplicationName,
                                            False)
        version_name = eb_utils.check_app_version(parameter_pool, eb_client)
        env_name = parameter_pool.get_value(ParameterName.EnvironmentName,
                                            False)
        stack_name = parameter_pool.get_value(ParameterName.SolutionStack,
                                              False)
        tier = parameter_pool.get_value(ParameterName.EnvironmentTier, False)

        spec = TemplateSpecification()

        # Try load option setting file if exist
        option_location = parameter_pool.get_value(
            ParameterName.OptionSettingFile, False)
        option_settings = config_file.load_env_option_setting_file(
            option_location, quiet=True)
        if option_settings is not None and len(option_settings) > 0:
            prompt.info(
                CreateEnvironmentOpMessage.UsingOptionSetting.format(
                    option_location))
        else:
            option_settings = dict()

        option_remove = dict()

        # Process extensions first before we process options
        self._extension_handler(parameter_pool, spec, stack_name,
                                option_settings, option_remove)

        # Process options
        self._option_setting_handler(parameter_pool, spec, stack_name, None,
                                     option_settings, option_remove)

        prompt.action(CreateEnvironmentOpMessage.Start.format(env_name))
        try:
            response = eb_client.create_environment(
                application=app_name,
                environment=env_name,
                solution_stack=stack_name,
                version_label=version_name,
                option_settings=option_settings,
                option_remove=option_remove,
                template_specification=spec,
                tier=tier)
        except AlreadyExistException:
            log.info(u'Environment "{0}" already exist.'.format(env_name))
            prompt.result(
                CreateEnvironmentOpMessage.AlreadyExist.format(env_name))

            ret_result = OperationResult(
                self, None,
                CreateEnvironmentOpMessage.AlreadyExist.format(env_name), None)
        else:
            log.info(u'Received response for CreateEnvironemnt call.')
            prompt.info(CreateEnvironmentOpMessage.Succeed)
            prompt.result(
                CreateEnvironmentOpMessage.WaitAfterLaunch.format(env_name))
            self._log_api_result(self.__class__.__name__, u'CreateEnvironment',
                                 response.result)

            parameter_pool.put(
                Parameter(ParameterName.CreateEnvironmentRequestID,
                          response.request_id,
                          ParameterSource.OperationOutput))

            ret_result = OperationResult(self, response.request_id,
                                         CreateEnvironmentOpMessage.Succeed,
                                         response.result)
        return ret_result