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)
        max_records = parameter_pool.get_value(ParameterName.SubCommand)

        try:
            max_records = int(max_records[0]) if len(
                max_records) > 0 else ServiceDefault.EVENT_DEFAULT_NUM
        except ValueError:
            raise EBSCliException(
                GetEnvironmentEventsOpMessage.NotValidNumber.format(
                    max_records[0]))

        response = eb_client.describe_events(app_name,
                                             env_name,
                                             max_records=max_records)

        if len(response.result) > 0:
            for event in response.result:
                msg = u'{0}\t{1}\t{2}'.format(event.event_date, event.severity,
                                              event.message)
                prompt.plain(msg)

        ret_result = OperationResult(self, response.request_id, None,
                                     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)
        max_records = parameter_pool.get_value(ParameterName.SubCommand)

        try:
            max_records = int(max_records[0]) if len(max_records) > 0 else ServiceDefault.EVENT_DEFAULT_NUM
        except ValueError:
            raise EBSCliException(GetEnvironmentEventsOpMessage.NotValidNumber.format(max_records[0]))

        response = eb_client.describe_events(app_name, env_name, max_records=max_records)

        if len(response.result) > 0:
            for event in response.result:
                msg = "{0}\t{1}\t{2}".format(event.event_date, event.severity, event.message)
                prompt.plain(msg)

        ret_result = OperationResult(self, response.request_id, None, 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)
        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 #4
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 #5
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 = 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 #7
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