def _update_settings(self):
        try:
            admin = ConfigAdmin(logger=self._logger, context=self.context)
            settings = admin.update_config(
                default_timezone=self.default_timezone,
                scheduled_services=self.scheduled_services,
                schedule_clusters=self.schedule_clusters,
                create_rds_snapshot=self.create_rds_snapshot,
                tagname=self.tagname,
                regions=self.regions,
                cross_account_roles=self.cross_account_roles,
                schedule_lambda_account=self.schedule_lambda_account.lower() ==
                "true",
                use_metrics=self.use_metrics.lower() == "true",
                trace=self.trace.lower() == "true",
                started_tags=self.started_tags,
                stopped_tags=self.stopped_tags)

            self._logger.info(INF_CONFIG_SET, str(settings))

        except Exception as ex:
            self._logger.info(ERR_SETTING_CONFIG, ex)
            return False

        return True
Beispiel #2
0
    def handle_request(self):
        """
        Handles the event
        :return: result of handling the event, result send back to REST admin api
        """

        # Setup logging
        classname = self.__class__.__name__
        dt = datetime.utcnow()
        logstream = LOG_STREAM.format(classname, dt.year, dt.month, dt.day)
        self._logger = Logger(logstream=logstream, buffersize=20, context=self._context)

        with Logger(logstream=logstream, buffersize=20, context=self._context) as logger:

            logger.info("Handler {} : Received request {}", self.__class__.__name__, json.dumps(self._event))

            # get access to admin api
            admin = ConfigAdmin(logger=logger, context=self._context)

            # get api action and map it to a function in the admin API
            fn = getattr(admin, self.action)
            if fn is None:
                raise ValueError("Action {} does not exist".format(self.action))

            # build parameters for admin API call
            temp = self._event.get("params", {})
            params = {p: temp[p] for p in temp}
            if "name" in self._event:
                params["name"] = self._event["name"]
            logger.info("Calling \"{}\" with parameters {}", fn.__name__, params)
            # call the admin API
            result = fn(**params)
            logger.info("Call result is {}", result)
            return result
    def __init__(self, event, context):
        """
        Initializes instance
        :param event: CFN event
        :param context: Lambda context
        """
        CustomResource.__init__(self, event, context)
        self.number_of_periods = 0

        classname = self.__class__.__name__
        dt = datetime.utcnow()
        logstream = LOG_STREAM.format(classname, dt.year, dt.month, dt.day)
        self._logger = Logger(logstream=logstream, buffersize=20, context=context)

        self._admin = ConfigAdmin(logger=self._logger, context=context)
Beispiel #4
0
    def _create_sample_schemas(self):

        try:
            admin = ConfigAdmin(logger=self._logger, context=self.context)

            admin.create_period(**demo_data.PERIOD_WORKING_DAYS)
            admin.create_period(**demo_data.PERIOD_WEEKENDS)
            admin.create_period(**demo_data.PERIOD_OFFICE_HOURS)
            admin.create_period(**demo_data.PERIOD_FIRST_MONDAY_IN_QUARTER)

            admin.create_schedule(**demo_data.SCHEDULE_SEATTLE_OFFICE_HOURS)
            admin.create_schedule(**demo_data.SCHEDULE_UK_OFFICE_HOURS)
            admin.create_schedule(**demo_data.SCHEDULE_STOPPED)
            admin.create_schedule(**demo_data.SCHEDULE_RUNNING)
            admin.create_schedule(**demo_data.SCHEDULE_SCALING)

        except Exception as ex:
            self._logger.error("Error creating sample schedules and periods {}".format(ex))
Beispiel #5
0
    def handle_request(self):
        """
        Handles the event
        :return: result of handling the event, result send back to REST admin api
        """
        def snake_to_pascal_case(s):
            converted = ""
            s = s.strip("_").capitalize()
            i = 0

            while i < len(s):
                if s[i] == "_":
                    i += 1
                    converted += s[i].upper()
                else:
                    converted += s[i]
                i += 1

            return converted

        # noinspection PyShadowingNames
        def dict_to_pascal_case(d):

            d_result = {}

            if isinstance(d, dict):
                for i in d:
                    key = snake_to_pascal_case(i)
                    d_result[key] = dict_to_pascal_case(d[i])
                return d_result

            elif isinstance(d, list):
                return [dict_to_pascal_case(l) for l in d]

            return d

        try:
            self._logger.info("Handler {} : Received CLI request {}",
                              self.__class__.__name__, json.dumps(self._event))

            # get access to admin api
            admin = ConfigAdmin(logger=self._logger, context=self._context)

            # get api action and map it to a function in the admin API
            fn_name = self.commands.get(self.action, None)
            if fn_name is None:
                raise ValueError("Command {} does not exist".format(
                    self.action))
            fn = getattr(admin, fn_name)

            # calling the mapped admin api method
            self._logger.info("Calling \"{}\" with parameters {}", fn.__name__,
                              self.parameters)
            api_result = fn(**self.parameters)

            # convert to awscli PascalCase output format
            result = dict_to_pascal_case(api_result)

            # perform output transformation
            if fn_name in self.transformations:
                result = jmespath.search(self.transformations[fn_name], result)

            # log formatted result
            json_result = safe_json(result, 3)
            self._logger.info("Call result is {}", json_result)

            return result

        except Exception as ex:
            self._logger.info("Call failed, error is {}", str(ex))
            return {"Error": str(ex)}
        finally:
            self._logger.flush()