def describe_reserved_instances_offerings( self, context: RequestContext, describe_reserved_instances_offerings_request: DescribeReservedInstancesOfferingsRequest, ) -> DescribeReservedInstancesOfferingsResult: return DescribeReservedInstancesOfferingsResult( ReservedInstancesOfferings=[ ReservedInstancesOffering( AvailabilityZone="eu-central-1a", Duration=2628000, FixedPrice=0.0, InstanceType=InstanceType.t2_small, ProductDescription=RIProductDescription.Linux_UNIX, ReservedInstancesOfferingId=long_uid(), UsagePrice=0.0, CurrencyCode=CurrencyCodeValues.USD, InstanceTenancy=Tenancy.default, Marketplace=True, PricingDetails=[PricingDetail(Price=0.0, Count=3)], RecurringCharges=[ RecurringCharge( Amount=0.25, Frequency=RecurringChargeFrequency.Hourly) ], Scope=scope.Availability_Zone, ) ])
def create_grant( self, context: RequestContext, create_grant_request: CreateGrantRequest) -> CreateGrantResponse: self._validate_grant(create_grant_request) region_details = KMSBackend.get() grant = dict(create_grant_request) grant[GRANT_ID] = long_uid() grant[GRANT_TOKENS] = [long_uid()] if NAME not in grant: grant[NAME] = "" grant[CREATION_DATE] = time.time() region_details.grants[grant[GRANT_ID]] = grant return CreateGrantResponse(GrantId=grant[GRANT_ID], GrantToken=grant[GRANT_TOKENS][0])
def describe_reserved_instances( self, context: RequestContext, describe_reserved_instances_request: DescribeReservedInstancesRequest, ) -> DescribeReservedInstancesResult: return DescribeReservedInstancesResult(ReservedInstances=[ ReservedInstances( AvailabilityZone="eu-central-1a", Duration=2628000, End=datetime(2016, 6, 30, tzinfo=timezone.utc), FixedPrice=0.0, InstanceCount=2, InstanceType=InstanceType.t2_small, ProductDescription=RIProductDescription.Linux_UNIX, ReservedInstancesId=long_uid(), Start=datetime(2016, 1, 1, tzinfo=timezone.utc), State=ReservedInstanceState.active, UsagePrice=0.05, CurrencyCode=CurrencyCodeValues.USD, InstanceTenancy=Tenancy.default, OfferingClass=OfferingClassType.standard, OfferingType=OfferingTypeValues.Partial_Upfront, RecurringCharges=[ RecurringCharge(Amount=0.05, Frequency=RecurringChargeFrequency.Hourly) ], Scope=scope.Availability_Zone, ) ])
def purchase_reserved_instances_offering( self, context: RequestContext, purchase_reserved_instances_offerings_request: PurchaseReservedInstancesOfferingRequest, ) -> PurchaseReservedInstancesOfferingResult: return PurchaseReservedInstancesOfferingResult( ReservedInstancesId=long_uid(), )
def add_stack_event(self, resource_id: str, physical_res_id: str, status: str): event = { "EventId": long_uid(), "Timestamp": timestamp_millis(), "StackId": self.stack_id, "StackName": self.stack_name, "LogicalResourceId": resource_id, "PhysicalResourceId": physical_res_id, "ResourceStatus": status, "ResourceType": "AWS::CloudFormation::Stack", } self.events.insert(0, event)
def events_handler_put_events(self): entries = self._get_param("Entries") # keep track of events for local integration testing if config.is_local_test_mode(): TEST_EVENTS_CACHE.extend(entries) events = list(map(lambda event: {"event": event, "uuid": str(long_uid())}, entries)) _dump_events_to_files(events) event_rules = self.events_backend.rules for event_envelope in events: event = event_envelope["event"] event_bus = event.get("EventBusName") or DEFAULT_EVENT_BUS_NAME matchine_rules = [r for r in event_rules.values() if r.event_bus_name == event_bus] if not matchine_rules: continue formatted_event = { "version": "0", "id": event_envelope["uuid"], "detail-type": event.get("DetailType"), "source": event.get("Source"), "account": TEST_AWS_ACCOUNT_ID, "time": datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"), "region": self.region, "resources": event.get("Resources", []), "detail": json.loads(event.get("Detail", "{}")), } targets = [] for rule in matchine_rules: if filter_event_based_on_event_format(self, rule.name, formatted_event): targets.extend(self.events_backend.list_targets_by_rule(rule.name)["Targets"]) # process event process_events(formatted_event, targets) content = { "FailedEntryCount": 0, # TODO: dynamically set proper value when refactoring "Entries": list(map(lambda event: {"EventId": event["uuid"]}, events)), } self.response_headers.update( {"Content-Type": APPLICATION_AMZ_JSON_1_1, "x-amzn-RequestId": short_uid()} ) return json.dumps(content), self.response_headers
def get_identity_verification_attributes( self, context: RequestContext, identities: IdentityList ) -> GetIdentityVerificationAttributesResponse: attributes: VerificationAttributes = {} for identity in identities: if "@" in identity: attributes[identity] = IdentityVerificationAttributes( VerificationStatus=VerificationStatus.Success, ) else: attributes[identity] = IdentityVerificationAttributes( VerificationStatus=VerificationStatus.Success, VerificationToken=long_uid(), ) return GetIdentityVerificationAttributesResponse( VerificationAttributes=attributes, )
def lambda_result_to_destination( func_details: LambdaFunction, event: Dict, result: InvocationResult, is_async: bool, error: InvocationException, ): if not func_details.destination_enabled(): return payload = { "version": "1.0", "timestamp": timestamp_millis(), "requestContext": { "requestId": long_uid(), "functionArn": func_details.arn(), "condition": "RetriesExhausted", "approximateInvokeCount": 1, }, "requestPayload": event, "responseContext": { "statusCode": 200, "executedVersion": "$LATEST" }, "responsePayload": {}, } if result and result.result: try: payload["requestContext"]["condition"] = "Success" payload["responsePayload"] = json.loads(result.result) except Exception: payload["responsePayload"] = result.result if error: payload["responseContext"]["functionError"] = "Unhandled" # add the result in the response payload if error.result is not None: payload["responsePayload"] = json.loads(error.result) send_event_to_target(func_details.on_failed_invocation, payload) return if func_details.on_successful_invocation is not None: send_event_to_target(func_details.on_successful_invocation, payload)
def list_grants( self, context: RequestContext, list_grants_request: ListGrantsRequest) -> ListGrantsResponse: key_id = list_grants_request.get(KEY_ID) if not key_id: raise ValidationError( f"Required input parameter '{KEY_ID}' not specified") region_details = KMSBackend.get() self._verify_key_exists(key_id) limit = list_grants_request.get("Limit", 50) if "Marker" in list_grants_request: filtered = region_details.markers.get( list_grants_request["Marker"], []) else: filtered = [ grant for grant in region_details.grants.values() if grant[KEY_ID] == key_id and filter_grant_id(grant, list_grants_request) and filter_grantee_principal(grant, list_grants_request) ] # filter out attributes filtered = [ remove_attributes(dict(grant), ["GrantTokens"]) for grant in filtered ] if len(filtered) <= limit: return ListGrantsResponse(Grants=filtered, Truncated=False) in_limit = filtered[:limit] out_limit = filtered[limit:] marker_id = long_uid() region_details.markers[marker_id] = out_limit return ListGrantsResponse(Grants=in_limit, Truncated=True, NextMarker=marker_id)
def list_retirable_grants( self, context: RequestContext, retiring_principal: PrincipalIdType, limit: LimitType = None, marker: MarkerType = None, ) -> ListGrantsResponse: region_details = KMSBackend.get() grants = region_details.grants if not retiring_principal: raise ValidationError( f"Required input parameter '{RETIRING_PRINCIPAL}' not specified" ) limit = limit or 50 if marker: markers = region_details.markers filtered = markers.get(marker, []) else: filtered = [ grant for grant in grants.values() if RETIRING_PRINCIPAL in grant and grant[RETIRING_PRINCIPAL] == retiring_principal ] if len(filtered) <= limit: return ListGrantsResponse(Grants=filtered, Truncated=False) markers = region_details.markers in_limit = filtered[:limit] out_limit = filtered[limit:] marker_id = long_uid() markers[marker_id] = out_limit return ListGrantsResponse(Grants=in_limit, Truncated=True, NextMarker=marker_id)
def _generate_session_id() -> str: return long_uid()