// presignURL will presign the request by using SoureRegion to sign with. SourceRegion is not // sent to the service, and is only used to not have the SDKs parsing ARNs. func presignURL(r *request.Request, sourceRegion *string, newParams interface{}) *string { cfg := r.Config.Copy(aws.NewConfig(). WithEndpoint(""). WithRegion(aws.StringValue(sourceRegion))) clientInfo := r.ClientInfo resolved, err := r.Config.EndpointResolver.EndpointFor( clientInfo.ServiceName, aws.StringValue(cfg.Region), func(opt *endpoints.Options) { opt.DisableSSL = aws.BoolValue(cfg.DisableSSL) opt.UseDualStack = aws.BoolValue(cfg.UseDualStack) }, ) if err != nil { r.Error = err return nil } clientInfo.Endpoint = resolved.URL clientInfo.SigningRegion = resolved.SigningRegion // Presign a request with modified params req := request.New(*cfg, clientInfo, r.Handlers, r.Retryer, r.Operation, newParams, r.Data) req.Operation.HTTPMethod = "GET" uri, err := req.Presign(5 * time.Minute) // 5 minutes should be enough. if err != nil { // bubble error back up to original request r.Error = err return nil } // We have our URL, set it on params return &uri }
func (s *Session) clientConfigWithErr(serviceName string, cfgs ...*aws.Config) (client.Config, error) { s = s.Copy(cfgs...) var resolved endpoints.ResolvedEndpoint var err error region := aws.StringValue(s.Config.Region) if endpoint := aws.StringValue(s.Config.Endpoint); len(endpoint) != 0 { resolved.URL = endpoints.AddScheme(endpoint, aws.BoolValue(s.Config.DisableSSL)) resolved.SigningRegion = region } else { resolved, err = s.Config.EndpointResolver.EndpointFor( serviceName, region, func(opt *endpoints.Options) { opt.DisableSSL = aws.BoolValue(s.Config.DisableSSL) opt.UseDualStack = aws.BoolValue(s.Config.UseDualStack) }, ) } return client.Config{ Config: s.Config, Handlers: s.Handlers, Endpoint: resolved.URL, SigningRegion: resolved.SigningRegion, SigningName: resolved.SigningName, }, err }
func launchSpecToMap( l *ec2.SpotFleetLaunchSpecification, rootDevName *string, ) map[string]interface{} { m := make(map[string]interface{}) m["root_block_device"] = rootBlockDeviceToSet(l.BlockDeviceMappings, rootDevName) m["ebs_block_device"] = ebsBlockDevicesToSet(l.BlockDeviceMappings, rootDevName) m["ephemeral_block_device"] = ephemeralBlockDevicesToSet(l.BlockDeviceMappings) if l.ImageId != nil { m["ami"] = aws.StringValue(l.ImageId) } if l.InstanceType != nil { m["instance_type"] = aws.StringValue(l.InstanceType) } if l.SpotPrice != nil { m["spot_price"] = aws.StringValue(l.SpotPrice) } if l.EbsOptimized != nil { m["ebs_optimized"] = aws.BoolValue(l.EbsOptimized) } if l.Monitoring != nil && l.Monitoring.Enabled != nil { m["monitoring"] = aws.BoolValue(l.Monitoring.Enabled) } if l.IamInstanceProfile != nil && l.IamInstanceProfile.Name != nil { m["iam_instance_profile"] = aws.StringValue(l.IamInstanceProfile.Name) } if l.UserData != nil { ud_dec, err := base64.StdEncoding.DecodeString(aws.StringValue(l.UserData)) if err == nil { m["user_data"] = string(ud_dec) } } if l.KeyName != nil { m["key_name"] = aws.StringValue(l.KeyName) } if l.Placement != nil { m["availability_zone"] = aws.StringValue(l.Placement.AvailabilityZone) } if l.SubnetId != nil { m["subnet_id"] = aws.StringValue(l.SubnetId) } if l.WeightedCapacity != nil { m["weighted_capacity"] = strconv.FormatFloat(*l.WeightedCapacity, 'f', 0, 64) } // m["security_groups"] = securityGroupsToSet(l.SecutiryGroups) return m }
func verifyVolumeFrom(t *testing.T, output *ecs.VolumeFrom, containerName string, readOnly bool) { if containerName != aws.StringValue(output.SourceContainer) { t.Errorf("Expected SourceContainer [%s] But was [%s]", containerName, aws.StringValue(output.SourceContainer)) } if readOnly != aws.BoolValue(output.ReadOnly) { t.Errorf("Expected ReadOnly [%t] But was [%t]", readOnly, aws.BoolValue(output.ReadOnly)) } }
func TestAddWithUsePreviousValueAndValidate(t *testing.T) { cfnParams := NewCfnStackParamsForUpdate() err := cfnParams.Validate() if err != nil { t.Error("Error validating params for update: ", err) } params := cfnParams.Get() if 0 == len(params) { t.Error("Got empty params list") } for _, param := range params { usePrevious := param.UsePreviousValue paramName := aws.StringValue(param.ParameterKey) if usePrevious == nil { t.Fatalf("usePrevious is not set for '%s' in params map", paramName) } if !aws.BoolValue(usePrevious) { t.Errorf("usePrevious value for '%s' is false, expected to be true", paramName) } } err = cfnParams.AddWithUsePreviousValue(ParameterKeyAsgMaxSize, false) if err != nil { t.Errorf("Error adding parameter with use previous value '%s': '%v'", ParameterKeyAsgMaxSize, err) } err = cfnParams.Validate() if err == nil { t.Errorf("Expected error for param '%s' when usePrevious is false and value is not set", ParameterKeyAsgMaxSize) } size := "3" err = cfnParams.Add(ParameterKeyAsgMaxSize, size) if err != nil { t.Errorf("Error adding parameter '%s': %v", ParameterKeyAsgMaxSize, err) } param, err := cfnParams.GetParameter(ParameterKeyAsgMaxSize) if err != nil { t.Errorf("Error getting parameter '%s': %v", ParameterKeyAsgMaxSize, err) } usePrevious := param.UsePreviousValue if usePrevious == nil { t.Fatalf("usePrevious is not set for '%s' in params map", ParameterKeyAsgMaxSize) } if aws.BoolValue(usePrevious) { t.Errorf("usePrevious value is true for '%s', expected false", ParameterKeyAsgMaxSize) } }
// Marshal parses the response from the aws sdk into an awsm Subnet func (s *Subnet) Marshal(subnet *ec2.Subnet, region string, vpcList *Vpcs) { s.Name = GetTagValue("Name", subnet.Tags) s.Class = GetTagValue("Class", subnet.Tags) s.SubnetID = aws.StringValue(subnet.SubnetId) s.VpcID = aws.StringValue(subnet.VpcId) s.VpcName = vpcList.GetVpcName(s.VpcID) s.State = aws.StringValue(subnet.State) s.AvailabilityZone = aws.StringValue(subnet.AvailabilityZone) s.Default = aws.BoolValue(subnet.DefaultForAz) s.CIDRBlock = aws.StringValue(subnet.CidrBlock) s.AvailableIPs = int(aws.Int64Value(subnet.AvailableIpAddressCount)) s.MapPublicIP = aws.BoolValue(subnet.MapPublicIpOnLaunch) s.Region = region }
// Request handler to automatically add the bucket name to the endpoint domain // if possible. This style of bucket is valid for all bucket names which are // DNS compatible and do not contain "." func updateEndpointForS3Config(r *request.Request) { forceHostStyle := aws.BoolValue(r.Config.S3ForcePathStyle) accelerate := aws.BoolValue(r.Config.S3UseAccelerate) if accelerate && accelerateOpBlacklist.Continue(r) { if forceHostStyle { if r.Config.Logger != nil { r.Config.Logger.Log("ERROR: aws.Config.S3UseAccelerate is not compatible with aws.Config.S3ForcePathStyle, ignoring S3ForcePathStyle.") } } updateEndpointForAccelerate(r) } else if !forceHostStyle && r.Operation.Name != opGetBucketLocation { updateEndpointForHostStyle(r) } }
func fillPresignedURL(r *request.Request) { if !r.ParamsFilled() { return } origParams := r.Params.(*CopySnapshotInput) // Stop if PresignedURL/DestinationRegion is set if origParams.PresignedUrl != nil || origParams.DestinationRegion != nil { return } origParams.DestinationRegion = r.Config.Region newParams := awsutil.CopyOf(r.Params).(*CopySnapshotInput) // Create a new request based on the existing request. We will use this to // presign the CopySnapshot request against the source region. cfg := r.Config.Copy(aws.NewConfig(). WithEndpoint(""). WithRegion(aws.StringValue(origParams.SourceRegion))) clientInfo := r.ClientInfo resolved, err := r.Config.EndpointResolver.EndpointFor( clientInfo.ServiceName, aws.StringValue(cfg.Region), func(opt *endpoints.Options) { opt.DisableSSL = aws.BoolValue(cfg.DisableSSL) opt.UseDualStack = aws.BoolValue(cfg.UseDualStack) }, ) if err != nil { r.Error = err return } clientInfo.Endpoint = resolved.URL clientInfo.SigningRegion = resolved.SigningRegion // Presign a CopySnapshot request with modified params req := request.New(*cfg, clientInfo, r.Handlers, r.Retryer, r.Operation, newParams, r.Data) url, err := req.Presign(5 * time.Minute) // 5 minutes should be enough. if err != nil { // bubble error back up to original request r.Error = err return } // We have our URL, set it on params origParams.PresignedUrl = &url }
func rootBlockDeviceToSet( bdm []*ec2.BlockDeviceMapping, rootDevName *string, ) *schema.Set { set := &schema.Set{F: hashRootBlockDevice} if rootDevName != nil { for _, val := range bdm { if aws.StringValue(val.DeviceName) == aws.StringValue(rootDevName) { m := make(map[string]interface{}) if val.Ebs.DeleteOnTermination != nil { m["delete_on_termination"] = aws.BoolValue(val.Ebs.DeleteOnTermination) } if val.Ebs.VolumeSize != nil { m["volume_size"] = aws.Int64Value(val.Ebs.VolumeSize) } if val.Ebs.VolumeType != nil { m["volume_type"] = aws.StringValue(val.Ebs.VolumeType) } if val.Ebs.Iops != nil { m["iops"] = aws.Int64Value(val.Ebs.Iops) } set.Add(m) } } } return set }
// nextPageTokens returns the tokens to use when asking for the next page of // data. func (r *Request) nextPageTokens() []interface{} { if r.Operation.Paginator == nil { return nil } if r.Operation.TruncationToken != "" { tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken) if len(tr) == 0 { return nil } switch v := tr[0].(type) { case *bool: if !aws.BoolValue(v) { return nil } case bool: if v == false { return nil } } } tokens := []interface{}{} for _, outToken := range r.Operation.OutputTokens { v, _ := awsutil.ValuesAtPath(r.Data, outToken) if len(v) > 0 { tokens = append(tokens, v[0]) } } return tokens }
// Initialize initializes the service. func (s *Service) Initialize() { if s.Config == nil { s.Config = &aws.Config{} } if s.Config.HTTPClient == nil { s.Config.HTTPClient = http.DefaultClient } if s.RetryRules == nil { s.RetryRules = retryRules } if s.ShouldRetry == nil { s.ShouldRetry = shouldRetry } s.DefaultMaxRetries = 3 s.Handlers.Validate.PushBack(ValidateEndpointHandler) s.Handlers.Build.PushBack(UserAgentHandler) s.Handlers.Sign.PushBack(BuildContentLength) s.Handlers.Send.PushBack(SendHandler) s.Handlers.AfterRetry.PushBack(AfterRetryHandler) s.Handlers.ValidateResponse.PushBack(ValidateResponseHandler) s.AddDebugHandlers() s.buildEndpoint() if !aws.BoolValue(s.Config.DisableParamValidation) { s.Handlers.Validate.PushBack(ValidateParameters) } }
// Initialize initializes the service. func (s *Service) Initialize() { if s.Config == nil { s.Config = &aws.Config{} } if s.Config.HTTPClient == nil { s.Config.HTTPClient = http.DefaultClient } if s.Config.SleepDelay == nil { s.Config.SleepDelay = time.Sleep } s.Retryer = DefaultRetryer{s} s.DefaultMaxRetries = 3 s.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) s.Handlers.Build.PushBackNamed(corehandlers.UserAgentHandler) s.Handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler) s.Handlers.Send.PushBackNamed(corehandlers.SendHandler) s.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) s.Handlers.ValidateResponse.PushBackNamed(corehandlers.ValidateResponseHandler) if !aws.BoolValue(s.Config.DisableParamValidation) { s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler) } s.AddDebugHandlers() s.buildEndpoint() }
func initHandlers(s *Session) { // Add the Validate parameter handler if it is not disabled. s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler) if !aws.BoolValue(s.Config.DisableParamValidation) { s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler) } }
func (s *CloudFormationStack) buildStackDetails(stack *cloudformation.Stack) StackDetails { stackDetails := StackDetails{ StackName: aws.StringValue(stack.StackName), Capabilities: aws.StringValueSlice(stack.Capabilities), DisableRollback: aws.BoolValue(stack.DisableRollback), Description: aws.StringValue(stack.Description), NotificationARNs: aws.StringValueSlice(stack.NotificationARNs), StackID: aws.StringValue(stack.StackId), StackStatus: s.stackStatus(aws.StringValue(stack.StackStatus)), TimeoutInMinutes: aws.Int64Value(stack.TimeoutInMinutes), } if stack.Parameters != nil && len(stack.Parameters) > 0 { stackDetails.Parameters = make(map[string]string) for _, parameter := range stack.Parameters { stackDetails.Parameters[aws.StringValue(parameter.ParameterKey)] = aws.StringValue(parameter.ParameterValue) } } if stack.Outputs != nil && len(stack.Outputs) > 0 { stackDetails.Outputs = make(map[string]string) for _, output := range stack.Outputs { stackDetails.Outputs[aws.StringValue(output.OutputKey)] = aws.StringValue(output.OutputValue) } } return stackDetails }
func resourceAwsSpotFleetRequestUpdate(d *schema.ResourceData, meta interface{}) error { // http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifySpotFleetRequest.html conn := meta.(*AWSClient).ec2conn d.Partial(true) req := &ec2.ModifySpotFleetRequestInput{ SpotFleetRequestId: aws.String(d.Id()), } if val, ok := d.GetOk("target_capacity"); ok { req.TargetCapacity = aws.Int64(int64(val.(int))) } if val, ok := d.GetOk("excess_capacity_termination_policy"); ok { req.ExcessCapacityTerminationPolicy = aws.String(val.(string)) } resp, err := conn.ModifySpotFleetRequest(req) if err == nil && aws.BoolValue(resp.Return) { // TODO: rollback to old values? } return nil }
func ebsBlockDevicesToSet(bdm []*ec2.BlockDeviceMapping, rootDevName *string) *schema.Set { set := &schema.Set{F: hashEphemeralBlockDevice} for _, val := range bdm { if val.Ebs != nil { m := make(map[string]interface{}) ebs := val.Ebs if val.DeviceName != nil { if aws.StringValue(rootDevName) == aws.StringValue(val.DeviceName) { continue } m["device_name"] = aws.StringValue(val.DeviceName) } if ebs.DeleteOnTermination != nil { m["delete_on_termination"] = aws.BoolValue(ebs.DeleteOnTermination) } if ebs.SnapshotId != nil { m["snapshot_id"] = aws.StringValue(ebs.SnapshotId) } if ebs.Encrypted != nil { m["encrypted"] = aws.BoolValue(ebs.Encrypted) } if ebs.VolumeSize != nil { m["volume_size"] = aws.Int64Value(ebs.VolumeSize) } if ebs.VolumeType != nil { m["volume_type"] = aws.StringValue(ebs.VolumeType) } if ebs.Iops != nil { m["iops"] = aws.Int64Value(ebs.Iops) } set.Add(m) } } return set }
func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers) { // Merge in user provided configuration cfg.MergeIn(userCfg) // Region if not already set by user if len(aws.StringValue(cfg.Region)) == 0 { if len(envCfg.Region) > 0 { cfg.WithRegion(envCfg.Region) } else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 { cfg.WithRegion(sharedCfg.Region) } } // Configure credentials if not already set if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil { if len(envCfg.Creds.AccessKeyID) > 0 { cfg.Credentials = credentials.NewStaticCredentialsFromCreds( envCfg.Creds, ) } else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil { cfgCp := *cfg cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds( sharedCfg.AssumeRoleSource.Creds, ) cfg.Credentials = stscreds.NewCredentials( &Session{ Config: &cfgCp, Handlers: handlers.Copy(), }, sharedCfg.AssumeRole.RoleARN, func(opt *stscreds.AssumeRoleProvider) { opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName if len(sharedCfg.AssumeRole.ExternalID) > 0 { opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID) } // MFA not supported }, ) } else if len(sharedCfg.Creds.AccessKeyID) > 0 { cfg.Credentials = credentials.NewStaticCredentialsFromCreds( sharedCfg.Creds, ) } else { // Fallback to default credentials provider, include mock errors // for the credential chain so user can identify why credentials // failed to be retrieved. cfg.Credentials = credentials.NewCredentials(&credentials.ChainProvider{ VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), Providers: []credentials.Provider{ &credProviderError{Err: awserr.New("EnvAccessKeyNotFound", "failed to find credentials in the environment.", nil)}, &credProviderError{Err: awserr.New("SharedCredsLoad", fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil)}, defaults.RemoteCredProvider(*cfg, handlers), }, }) } } }
// ClientConfig satisfies the client.ConfigProvider interface and is used to // configure the service client instances. Passing the Session to the service // client's constructor (New) will use this method to configure the client. func (s *Session) ClientConfig(serviceName string, cfgs ...*aws.Config) client.Config { s = s.Copy(cfgs...) endpoint, signingRegion := endpoints.NormalizeEndpoint( aws.StringValue(s.Config.Endpoint), serviceName, aws.StringValue(s.Config.Region), aws.BoolValue(s.Config.DisableSSL), aws.BoolValue(s.Config.UseDualStack), ) return client.Config{ Config: s.Config, Handlers: s.Handlers, Endpoint: endpoint, SigningRegion: signingRegion, } }
func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bool) { query := r.HTTPRequest.URL.Query() // Setup the raw path to match the base path pattern. This is needed // so that when the path is mutated a custom escaped version can be // stored in RawPath that will be used by the Go client. r.HTTPRequest.URL.RawPath = r.HTTPRequest.URL.Path for i := 0; i < v.NumField(); i++ { m := v.Field(i) if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) { continue } if m.IsValid() { field := v.Type().Field(i) name := field.Tag.Get("locationName") if name == "" { name = field.Name } if m.Kind() == reflect.Ptr { m = m.Elem() } if !m.IsValid() { continue } if field.Tag.Get("ignore") != "" { continue } var err error switch field.Tag.Get("location") { case "headers": // header maps err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag.Get("locationName")) case "header": err = buildHeader(&r.HTTPRequest.Header, m, name) case "uri": err = buildURI(r.HTTPRequest.URL, m, name) case "querystring": err = buildQueryString(query, m, name) default: if buildGETQuery { err = buildQueryString(query, m, name) } } r.Error = err } if r.Error != nil { return } } r.HTTPRequest.URL.RawQuery = query.Encode() if !aws.BoolValue(r.Config.DisableRestProtocolURICleaning) { cleanPath(r.HTTPRequest.URL) } }
// CredChain returns the default credential chain. // // Generally you shouldn't need to use this method directly, but // is available if you need to reset the credentials of an // existing service client or session's Config. func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials { return credentials.NewCredentials(&credentials.ChainProvider{ VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), Providers: []credentials.Provider{ &credentials.EnvProvider{}, &credentials.SharedCredentialsProvider{Filename: "", Profile: ""}, RemoteCredProvider(*cfg, handlers), }, }) }
// Marshal parses the response from the aws sdk into an awsm Vpc func (v *Vpc) Marshal(vpc *ec2.Vpc, region string) { v.Name = GetTagValue("Name", vpc.Tags) v.Class = GetTagValue("Class", vpc.Tags) v.VpcID = aws.StringValue(vpc.VpcId) v.State = aws.StringValue(vpc.State) v.Default = aws.BoolValue(vpc.IsDefault) v.CIDRBlock = aws.StringValue(vpc.CidrBlock) v.DHCPOptID = aws.StringValue(vpc.DhcpOptionsId) v.Tenancy = aws.StringValue(vpc.InstanceTenancy) v.Region = region }
func add100Continue(r *request.Request) { if aws.BoolValue(r.Config.S3Disable100Continue) { return } if r.HTTPRequest.ContentLength < 1024*1024*2 { // Ignore requests smaller than 2MB. This helps prevent delaying // requests unnecessarily. return } r.HTTPRequest.Header.Set("Expect", "100-Continue") }
// validateParams validates if a cloudformation Parameter is properly set. func validateParam(param *cloudformation.Parameter, key string) error { val := aws.StringValue(param.ParameterValue) if val == "" { // If value is not set, we expect UsePreviousValue to be set. usePrevious := param.UsePreviousValue if !aws.BoolValue(usePrevious) { // aws.BoolValue does the nil check for us. return fmt.Errorf("ParameterValue and UsePreviousValue not set for parameter key '%s'", key) } } return nil }
// Send will send the request returning error if errors are encountered. // // Send will sign the request prior to sending. All Send Handlers will // be executed in the order they were set. func (r *Request) Send() error { for { r.Sign() if r.Error != nil { return r.Error } if aws.BoolValue(r.Retryable) { // Re-seek the body back to the original point in for a retry so that // send will send the body's contents again in the upcoming request. r.Body.Seek(r.bodyStart, 0) } r.Retryable = nil r.Handlers.Send.Run(r) if r.Error != nil { r.Handlers.Retry.Run(r) r.Handlers.AfterRetry.Run(r) if r.Error != nil { return r.Error } continue } r.Handlers.UnmarshalMeta.Run(r) r.Handlers.ValidateResponse.Run(r) if r.Error != nil { r.Handlers.UnmarshalError.Run(r) r.Handlers.Retry.Run(r) r.Handlers.AfterRetry.Run(r) if r.Error != nil { return r.Error } continue } r.Handlers.Unmarshal.Run(r) if r.Error != nil { r.Handlers.Retry.Run(r) r.Handlers.AfterRetry.Run(r) if r.Error != nil { return r.Error } continue } break } return nil }
// hostStyleBucketName returns true if the request should put the bucket in // the host. This is false if S3ForcePathStyle is explicitly set or if the // bucket is not DNS compatible. func hostStyleBucketName(r *request.Request, bucket string) bool { if aws.BoolValue(r.Service.Config.S3ForcePathStyle) { return false } // Bucket might be DNS compatible but dots in the hostname will fail // certificate validation, so do not use host-style. if r.HTTPRequest.URL.Scheme == "https" && strings.Contains(bucket, ".") { return false } // Use host-style if the bucket is DNS compatible return dnsCompatibleBucketName(bucket) }
// Request handler to automatically add the bucket name to the endpoint domain // if possible. This style of bucket is valid for all bucket names which are // DNS compatible and do not contain "." func updateEndpointForS3Config(r *request.Request) { forceHostStyle := aws.BoolValue(r.Config.S3ForcePathStyle) accelerate := aws.BoolValue(r.Config.S3UseAccelerate) useDualStack := aws.BoolValue(r.Config.UseDualStack) if useDualStack && accelerate { r.Error = awserr.New("InvalidParameterException", fmt.Sprintf("configuration aws.Config.UseDualStack is not compatible with aws.Config.Accelerate"), nil) return } if accelerate && accelerateOpBlacklist.Continue(r) { if forceHostStyle { if r.Config.Logger != nil { r.Config.Logger.Log("ERROR: aws.Config.S3UseAccelerate is not compatible with aws.Config.S3ForcePathStyle, ignoring S3ForcePathStyle.") } } updateEndpointForAccelerate(r) } else if !forceHostStyle && r.Operation.Name != opGetBucketLocation { updateEndpointForHostStyle(r) } }
func setupChecksumValidation(r *request.Request) { if aws.BoolValue(r.Service.Config.DisableComputeChecksums) { return } switch r.Operation.Name { case opSendMessage: r.Handlers.Unmarshal.PushBack(verifySendMessage) case opSendMessageBatch: r.Handlers.Unmarshal.PushBack(verifySendMessageBatch) case opReceiveMessage: r.Handlers.Unmarshal.PushBack(verifyReceiveMessage) } }
// CredChain returns the default credential chain. // // Generally you shouldn't need to use this method directly, but // is available if you need to reset the credentials of an // existing service client or session's Config. func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials { endpoint, signingRegion := endpoints.EndpointForRegion(ec2metadata.ServiceName, *cfg.Region, true) return credentials.NewCredentials(&credentials.ChainProvider{ VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), Providers: []credentials.Provider{ &credentials.EnvProvider{}, &credentials.SharedCredentialsProvider{Filename: "", Profile: ""}, &ec2rolecreds.EC2RoleProvider{ Client: ec2metadata.NewClient(*cfg, handlers, endpoint, signingRegion), ExpiryWindow: 5 * time.Minute, }, }}) }
// buildEndpoint builds the endpoint values the service will use to make requests with. func (s *Service) buildEndpoint() { if aws.StringValue(s.Config.Endpoint) != "" { s.Endpoint = *s.Config.Endpoint } else if s.Endpoint == "" { s.Endpoint, s.SigningRegion = endpoints.EndpointForRegion(s.ServiceName, aws.StringValue(s.Config.Region)) } if s.Endpoint != "" && !schemeRE.MatchString(s.Endpoint) { scheme := "https" if aws.BoolValue(s.Config.DisableSSL) { scheme = "http" } s.Endpoint = scheme + "://" + s.Endpoint } }
func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bool) { query := r.HTTPRequest.URL.Query() for i := 0; i < v.NumField(); i++ { m := v.Field(i) if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) { continue } if m.IsValid() { field := v.Type().Field(i) name := field.Tag.Get("locationName") if name == "" { name = field.Name } if m.Kind() == reflect.Ptr { m = m.Elem() } if !m.IsValid() { continue } var err error switch field.Tag.Get("location") { case "headers": // header maps err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag.Get("locationName")) case "header": err = buildHeader(&r.HTTPRequest.Header, m, name) case "uri": err = buildURI(r.HTTPRequest.URL, m, name) case "querystring": err = buildQueryString(query, m, name) default: if buildGETQuery { err = buildQueryString(query, m, name) } } r.Error = err } if r.Error != nil { return } } r.HTTPRequest.URL.RawQuery = query.Encode() updatePath(r.HTTPRequest.URL, r.HTTPRequest.URL.Path, aws.BoolValue(r.Config.DisableRestProtocolURICleaning)) }