Exemplo n.º 1
0
 def create(self,
            request,
            tenant_pk=None,
            aws_env_pk=None,
            region_pk=None,
            service_pk=None,
            resource_pk=None):
     log = NarukoLogging(request)
     logger = log.get_logger(__name__)
     logger.info("START: create")
     try:
         aws_environment = AwsEnvironmentModel.objects.get(
             id=aws_env_pk, tenant_id=tenant_pk)
         resource = Resource.get_service_resource(region_pk, service_pk,
                                                  resource_pk)
         no_reboot = request.data["no_reboot"] if isinstance(resource,
                                                             Ec2) else None
         backup_id = ControlResourceUseCase(log).create_backup(
             request.user, aws_environment, resource, no_reboot)
     except (TypeError, ValueError, KeyError, ClientError,
             NarukoException) as e:
         # リクエストデータが不正
         logger.exception(e)
         return Response(status=status.HTTP_400_BAD_REQUEST)
     except ObjectDoesNotExist as e:
         # AWS環境が存在しない
         logger.exception(e)
         return Response(status=status.HTTP_404_NOT_FOUND)
     except Exception as e:
         logger.exception(e)
         raise
     else:
         logger.info("END: create")
         return Response(data={"backup_id": backup_id},
                         status=status.HTTP_201_CREATED)
        def __init__(self, alarm_message):
            """
            :param alarm_message: CloudWatchアラームからSNSへ送られた生のメッセージ
            """

            region = alarm_message["Region"]
            service_type = alarm_message["Trigger"]["Namespace"].replace(
                "AWS/", "")
            resource_id = alarm_message["Trigger"]["Dimensions"][0]["value"]
            level = alarm_message["AlarmName"].rsplit('-', 1)[1]
            time_str = alarm_message["StateChangeTime"]
            time_date = datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S.%f%z')
            # CloudWatchアラームからの時刻はUTC
            time_date += timedelta(hours=settings.TIME_DIFFERENCE)

            self.resource = Resource.get_service_resource(
                region, service_type, resource_id)
            self.metric = alarm_message["Trigger"]["MetricName"]
            # 発火後のアラームのステータスがALARMの場合は、該当するレベル
            # OKの場合は正常とする:正常の発火は警告用のアラームのみ
            self.level = self.LEVEL.get(
                level,
                level) if alarm_message["NewStateValue"] == "ALARM" else "正常"
            self.aws = AwsEnvironmentModel.objects.get(
                aws_account_id=alarm_message["AWSAccountId"])
            self.time = time_date.strftime('%Y{}%m{}%d{} %H{}%M{}%S{}').format(
                "年", "月", "日", "時", "分", "秒")
Exemplo n.º 3
0
    def fetch_schedules_by_resource(resource: Resource,
                                    aws: AwsEnvironmentModel):
        # DBから該当するリソースのスケジュールを取得
        database_data_list = ScheduleModel.objects.filter(
            resource_id=resource.resource_id,
            service=resource.get_service_name().lower(),
            region=resource.region,
            aws_environment=aws).filter(deleted=0)

        # AWSからCloudWatchEventを取得
        cloudwatchevents = Events().list_rules()

        response = []
        for database in database_data_list:
            name = EventRepository.NARUKO_EVENT_NAME.format(
                event_id=database.id)
            target_cloudwatchevent = [
                c for c in cloudwatchevents if c.name == name
            ]
            if target_cloudwatchevent:
                response.append(Schedule(database, target_cloudwatchevent[0]))
            else:
                # DBだけにあるデータは削除する
                database.delete()

        return response
Exemplo n.º 4
0
 def list(self,
          request,
          tenant_pk=None,
          aws_env_pk=None,
          region_pk=None,
          service_pk=None,
          resource_pk=None):
     log = NarukoLogging(request)
     logger = log.get_logger(__name__)
     logger.info("START: list")
     try:
         aws_environment = AwsEnvironmentModel.objects.get(
             id=aws_env_pk, tenant_id=tenant_pk)
         resource = Resource.get_service_resource(region_pk, service_pk,
                                                  resource_pk)
         backups = ControlResourceUseCase(log).fetch_backups(
             request.user, aws_environment, resource)
     except (TypeError, ValueError, KeyError, ClientError,
             NarukoException) as e:
         # リクエストデータが不正
         logger.exception(e)
         return Response(status=status.HTTP_400_BAD_REQUEST)
     except ObjectDoesNotExist as e:
         # AWS環境が存在しない
         logger.exception(e)
         return Response(status=status.HTTP_404_NOT_FOUND)
     except Exception as e:
         logger.exception(e)
         raise
     else:
         logger.info("END: list")
         return Response(data=[backup.serialize() for backup in backups],
                         status=status.HTTP_200_OK)
Exemplo n.º 5
0
 def retrieve(self,
              request,
              tenant_pk=None,
              aws_env_pk=None,
              region_pk=None,
              service_pk=None,
              pk=None):
     log = NarukoLogging(request)
     logger = log.get_logger(__name__)
     logger.info("START: retrieve")
     try:
         aws_environment = AwsEnvironmentModel.objects.get(
             id=aws_env_pk, tenant_id=tenant_pk)
         resource = ControlResourceUseCase(log).describe_resource(
             request.user, aws_environment,
             Resource.get_service_resource(region_pk, service_pk, pk))
     except (TypeError, ValueError, KeyError, NarukoException) as e:
         # リクエストデータが不正
         logger.exception(e)
         return Response(status=status.HTTP_400_BAD_REQUEST)
     except ObjectDoesNotExist as e:
         # AWS環境が存在しない
         logger.exception(e)
         return Response(status=status.HTTP_404_NOT_FOUND)
     except Exception as e:
         logger.exception(e)
         raise
     else:
         logger.info("END: retrieve")
         return Response(data=resource.serialize(aws_environment),
                         status=status.HTTP_200_OK)
Exemplo n.º 6
0
 def stop(self, request, tenant_pk=None, aws_env_pk=None,
          region_pk=None, service_pk=None, pk=None):
     log = NarukoLogging(request)
     logger = log.get_logger(__name__)
     logger.info("START: stop")
     aws_environment = AwsEnvironmentModel.objects.get(id=aws_env_pk, tenant_id=tenant_pk)
     resource = Resource.get_service_resource(region_pk, service_pk, pk)
     ControlResourceUseCase(log).stop_resource(request.user, aws_environment, resource)
     logger.info("END: stop")
     return Response(status=status.HTTP_200_OK)
Exemplo n.º 7
0
 def retrieve(self, request, tenant_pk=None, aws_env_pk=None,
              region_pk=None, service_pk=None, pk=None):
     log = NarukoLogging(request)
     logger = log.get_logger(__name__)
     logger.info("START: retrieve")
     aws_environment = AwsEnvironmentModel.objects.get(id=aws_env_pk, tenant_id=tenant_pk)
     resource = ControlResourceUseCase(log).describe_resource(
         request.user,
         aws_environment,
         Resource.get_service_resource(region_pk, service_pk, pk))
     logger.info("END: retrieve")
     return Response(data=resource.serialize(aws_environment),
                     status=status.HTTP_200_OK)
Exemplo n.º 8
0
 def run_command(self, request, tenant_pk=None, aws_env_pk=None,
                 region_pk=None, service_pk=None, pk=None):
     log = NarukoLogging(request)
     logger = log.get_logger(__name__)
     logger.info("START: run_command")
     aws_environment = AwsEnvironmentModel.objects.get(id=aws_env_pk, tenant_id=tenant_pk)
     resource = Resource.get_service_resource(region_pk, service_pk, pk)
     command = Command(
         Document(
             request.data["name"],
             [Parameter(**param) for param in request.data["parameters"]]),
         resource)
     command = ControlResourceUseCase(log).run_command(request.user, aws_environment, command)
     logger.info("END: run_command")
     return Response(status=status.HTTP_200_OK, data=command.serialize())
Exemplo n.º 9
0
        def __init__(self, alarm_message):
            region = alarm_message["Region"]
            service_type = alarm_message["Trigger"]["Namespace"].replace(
                "AWS/", "")
            resource_id = alarm_message["Trigger"]["Dimensions"][0]["value"]
            level = alarm_message["AlarmName"].rsplit('-', 1)[1]
            time_str = alarm_message["StateChangeTime"]
            time_date = datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S.%f%z')
            # CloudWatchアラームからの時刻はUTC
            time_date += timedelta(hours=settings.TIME_DIFFERENCE)

            self.resource = Resource.get_service_resource(
                region, service_type, resource_id)
            self.metric = alarm_message["Trigger"]["MetricName"]
            self.level = self.LEVEL.get(level, level)  # DANGER or CAUTION
            self.aws = AwsEnvironmentModel.objects.get(
                aws_account_id=alarm_message["AWSAccountId"])
            self.time = time_date.strftime('%Y{}%m{}%d{} %H{}%M{}%S{}').format(
                "年", "月", "日", "時", "分", "秒")
Exemplo n.º 10
0
 def list(self,
          request,
          tenant_pk=None,
          aws_env_pk=None,
          region_pk=None,
          service_pk=None,
          resource_pk=None):
     log = NarukoLogging(request)
     logger = log.get_logger(__name__)
     logger.info("START: list")
     aws_environment = AwsEnvironmentModel.objects.get(id=aws_env_pk,
                                                       tenant_id=tenant_pk)
     resource = Resource.get_service_resource(region_pk, service_pk,
                                              resource_pk)
     backups = ControlResourceUseCase(log).fetch_backups(
         request.user, aws_environment, resource)
     logger.info("END: list")
     return Response(data=[backup.serialize() for backup in backups],
                     status=status.HTTP_200_OK)
Exemplo n.º 11
0
 def create(self,
            request,
            tenant_pk=None,
            aws_env_pk=None,
            region_pk=None,
            service_pk=None,
            resource_pk=None):
     log = NarukoLogging(request)
     logger = log.get_logger(__name__)
     logger.info("START: create")
     aws_environment = AwsEnvironmentModel.objects.get(id=aws_env_pk,
                                                       tenant_id=tenant_pk)
     resource = Resource.get_service_resource(region_pk, service_pk,
                                              resource_pk)
     no_reboot = request.data["no_reboot"] if isinstance(resource,
                                                         Ec2) else None
     backup_id = ControlResourceUseCase(log).create_backup(
         request.user, aws_environment, resource, no_reboot)
     logger.info("END: create")
     return Response(data={"backup_id": backup_id},
                     status=status.HTTP_201_CREATED)