diff --git a/Gopkg.lock b/Gopkg.lock index f8eacca5..f8c2217c 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -4,7 +4,6 @@ [[projects]] name = "github.com/aws/aws-lambda-go" packages = [ - "events", "lambda", "lambda/messages", "lambdacontext" @@ -48,7 +47,28 @@ "service/ec2/ec2iface", "service/sts" ] - revision = "f14473920f7d16e3157d10453a6009b915621f34" + revision = "912c6e5c014481c67811e4da911845a8e93c498d" + +[[projects]] + name = "github.com/aws/aws-xray-sdk-go" + packages = [ + "header", + "internal/plugins", + "pattern", + "resources", + "strategy/ctxmissing", + "strategy/exception", + "strategy/sampling", + "xray" + ] + revision = "9aa851be74b8ccb817f886c4c43cf8da3b0fc61e" + version = "v1.0.0-rc.5" + +[[projects]] + name = "github.com/cihub/seelog" + packages = ["."] + revision = "d2c6e5aa9fbfdd1c624e140287063c7730654115" + version = "v2.6" [[projects]] branch = "master" @@ -91,6 +111,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "599003886305d66092780cfcd1c549fdf532dc5d044e2700cc10ecaf60ab4418" + inputs-digest = "71b29e5eb83896c8888d45179b5914832a902d35163ed23984595fce67e42b17" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index c025978b..555f817f 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -20,6 +20,7 @@ # name = "github.com/x/y" # version = "2.4.0" +ignored = ["github.com/cristim/autospotting/core"] [[constraint]] name = "github.com/aws/aws-sdk-go" @@ -37,6 +38,10 @@ name = "github.com/namsral/flag" branch = "master" +[[constraint]] + name = "github.com/aws/aws-xray-sdk-go" + version = "1.0.0-rc.5" + [prune] go-tests = true non-go = true diff --git a/autospotting.go b/autospotting.go index 28c3fc51..ab652140 100644 --- a/autospotting.go +++ b/autospotting.go @@ -1,13 +1,15 @@ package main import ( + "context" "fmt" "log" "os" - "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go/aws/endpoints" + "github.com/aws/aws-xray-sdk-go/strategy/ctxmissing" + "github.com/aws/aws-xray-sdk-go/xray" "github.com/cristim/autospotting/core" "github.com/cristim/ec2-instances-info" "github.com/namsral/flag" @@ -26,12 +28,11 @@ func main() { if os.Getenv("AWS_LAMBDA_FUNCTION_NAME") != "" { lambda.Start(Handler) } else { - run() + run(context.Background()) } } -func run() { - +func run(ctx context.Context) { log.Println("Starting autospotting agent, build", Version) log.Printf("Parsed command line flags: "+ @@ -45,7 +46,8 @@ func run() { "bidding_policy=%s "+ "tag_filters=%s "+ "tag_filter_mode=%s "+ - "spot_product_description=%v", + "spot_product_description=%v "+ + "xray_log_level=%s", conf.Regions, conf.MinOnDemandNumber, conf.MinOnDemandPercentage, @@ -56,9 +58,14 @@ func run() { conf.BiddingPolicy, conf.FilterByTags, conf.TagFilteringMode, - conf.SpotProductDescription) - - autospotting.Run(conf.Config) + conf.SpotProductDescription, + conf.XRayLogLevel) + + xray.Configure(xray.Config{ + ContextMissingStrategy: ctxmissing.NewDefaultLogErrorStrategy(), + LogLevel: conf.XRayLogLevel, + }) + autospotting.Run(ctx, conf.Config) log.Println("Execution completed, nothing left to do") } @@ -87,8 +94,8 @@ func init() { } // Handler implements the AWS Lambda handler -func Handler(request events.APIGatewayProxyRequest) { - run() +func Handler(ctx context.Context) { + run(ctx) } // Configuration handling @@ -146,6 +153,8 @@ func (c *cfgData) parseCommandLineFlags() { "\tDefault if no value is set will be the equivalent of -tag_filters 'spot-enabled=true'\n"+ "\tIn case the tag_filtering_mode is set to opt-out, it defaults to 'spot-enabled=false'\n"+ "\tExample: ./autospotting --tag_filters 'spot-enabled=true,Environment=dev,Team=vision'\n") + flag.StringVar(&c.XRayLogLevel, "xray_log_level", "error", "\n\tSet log level for X-Ray SDK\n"+ + "\tValue \"error\" is set by default. See https://github.com/cihub/seelog/blob/master/common_loglevel.go#L41 for all available values\n") v := flag.Bool("version", false, "Print version number and exit.\n") flag.Parse() printVersion(v) diff --git a/core/autoscaling.go b/core/autoscaling.go index c6d8e949..b3315416 100644 --- a/core/autoscaling.go +++ b/core/autoscaling.go @@ -1,8 +1,8 @@ package autospotting import ( + "context" "errors" - "math" "strconv" "strings" @@ -249,7 +249,7 @@ func (a *autoScalingGroup) loadDefaultConfig() bool { return done } -func (a *autoScalingGroup) loadLaunchConfiguration() error { +func (a *autoScalingGroup) loadLaunchConfiguration(ctx context.Context) error { //already done if a.launchConfiguration != nil { return nil @@ -266,7 +266,7 @@ func (a *autoScalingGroup) loadLaunchConfiguration() error { params := &autoscaling.DescribeLaunchConfigurationsInput{ LaunchConfigurationNames: []*string{lcName}, } - resp, err := svc.DescribeLaunchConfigurations(params) + resp, err := svc.DescribeLaunchConfigurationsWithContext(ctx, params) if err != nil { logger.Println(err.Error()) @@ -279,7 +279,7 @@ func (a *autoScalingGroup) loadLaunchConfiguration() error { return nil } -func (a *autoScalingGroup) needReplaceOnDemandInstances() bool { +func (a *autoScalingGroup) needReplaceOnDemandInstances(ctx context.Context) bool { onDemandRunning, totalRunning := a.alreadyRunningInstanceCount(false, "") if onDemandRunning > a.minOnDemand { logger.Println("Currently more than enough OnDemand instances running") @@ -298,7 +298,7 @@ func (a *autoScalingGroup) needReplaceOnDemandInstances() bool { } else { logger.Println("Terminating a random spot instance", *randomSpot.Instance.InstanceId) - randomSpot.terminate() + randomSpot.terminate(ctx) } } } @@ -310,7 +310,7 @@ func (a *autoScalingGroup) allInstanceRunning() bool { return totalRunning == a.instances.count64() } -func (a *autoScalingGroup) process() { +func (a *autoScalingGroup) process(ctx context.Context) { var spotInstanceID string a.scanInstances() a.loadDefaultConfig() @@ -331,7 +331,7 @@ func (a *autoScalingGroup) process() { "No running on-demand instances were found, nothing to do here...") return } - a.loadLaunchConfiguration() + a.loadLaunchConfiguration(ctx) err := onDemandInstance.launchSpotReplacement() if err != nil { logger.Printf("Could not launch cheapest spot instance: %s", err) @@ -341,7 +341,7 @@ func (a *autoScalingGroup) process() { spotInstanceID = *spotInstance.InstanceId - if !a.needReplaceOnDemandInstances() || !spotInstance.isReadyToAttach(a) { + if !a.needReplaceOnDemandInstances(ctx) || !spotInstance.isReadyToAttach(a) { logger.Println("Waiting for next run while processing", a.name) return } @@ -349,7 +349,7 @@ func (a *autoScalingGroup) process() { logger.Println(a.region.name, "Found spot instance:", spotInstanceID, "Attaching it to", a.name) - a.replaceOnDemandInstanceWithSpot(spotInstanceID) + a.replaceOnDemandInstanceWithSpot(ctx, spotInstanceID) } @@ -385,7 +385,7 @@ func (a *autoScalingGroup) scanInstances() instances { return a.instances } -func (a *autoScalingGroup) replaceOnDemandInstanceWithSpot( +func (a *autoScalingGroup) replaceOnDemandInstanceWithSpot(ctx context.Context, spotInstanceID string) error { minSize, maxSize := *a.MinSize, *a.MaxSize @@ -394,8 +394,8 @@ func (a *autoScalingGroup) replaceOnDemandInstanceWithSpot( // temporarily increase AutoScaling group in case it's of static size if minSize == maxSize { logger.Println(a.name, "Temporarily increasing MaxSize") - a.setAutoScalingMaxSize(maxSize + 1) - defer a.setAutoScalingMaxSize(maxSize) + a.setAutoScalingMaxSize(ctx, maxSize+1) + defer a.setAutoScalingMaxSize(ctx, maxSize) } // get the details of our spot instance so we can see its AZ @@ -416,24 +416,24 @@ func (a *autoScalingGroup) replaceOnDemandInstanceWithSpot( logger.Println(a.name, "found no on-demand instances that could be", "replaced with the new spot instance", *spotInst.InstanceId, "terminating the spot instance.") - spotInst.terminate() + spotInst.terminate(ctx) return errors.New("couldn't find ondemand instance to replace") } logger.Println(a.name, "found on-demand instance", *odInst.InstanceId, "replacing with new spot instance", *spotInst.InstanceId) // revert attach/detach order when running on minimum capacity if desiredCapacity == minSize { - attachErr := a.attachSpotInstance(spotInstanceID) + attachErr := a.attachSpotInstance(ctx, spotInstanceID) if attachErr != nil { logger.Println(a.name, "skipping detaching on-demand due to failure to", "attach the new spot instance", *spotInst.InstanceId) return nil } } else { - defer a.attachSpotInstance(spotInstanceID) + defer a.attachSpotInstance(ctx, spotInstanceID) } - return a.detachAndTerminateOnDemandInstance(odInst.InstanceId) + return a.detachAndTerminateOnDemandInstance(ctx, odInst.InstanceId) } // Returns the information about the first running instance found in @@ -558,10 +558,11 @@ func (a *autoScalingGroup) getDisallowedInstanceTypes(baseInstance *instance) [] }) } -func (a *autoScalingGroup) setAutoScalingMaxSize(maxSize int64) error { +func (a *autoScalingGroup) setAutoScalingMaxSize(ctx context.Context, maxSize int64) error { svc := a.region.services.autoScaling - _, err := svc.UpdateAutoScalingGroup( + _, err := svc.UpdateAutoScalingGroupWithContext( + ctx, &autoscaling.UpdateAutoScalingGroupInput{ AutoScalingGroupName: aws.String(a.name), MaxSize: aws.Int64(maxSize), @@ -576,7 +577,7 @@ func (a *autoScalingGroup) setAutoScalingMaxSize(maxSize int64) error { return nil } -func (a *autoScalingGroup) attachSpotInstance(spotInstanceID string) error { +func (a *autoScalingGroup) attachSpotInstance(ctx context.Context, spotInstanceID string) error { svc := a.region.services.autoScaling @@ -587,7 +588,7 @@ func (a *autoScalingGroup) attachSpotInstance(spotInstanceID string) error { }, } - resp, err := svc.AttachInstances(¶ms) + resp, err := svc.AttachInstancesWithContext(ctx, ¶ms) if err != nil { logger.Println(err.Error()) @@ -600,7 +601,7 @@ func (a *autoScalingGroup) attachSpotInstance(spotInstanceID string) error { // Terminates an on-demand instance from the group, // but only after it was detached from the autoscaling group -func (a *autoScalingGroup) detachAndTerminateOnDemandInstance( +func (a *autoScalingGroup) detachAndTerminateOnDemandInstance(ctx context.Context, instanceID *string) error { logger.Println(a.region.name, a.name, @@ -617,7 +618,7 @@ func (a *autoScalingGroup) detachAndTerminateOnDemandInstance( asSvc := a.region.services.autoScaling - if _, err := asSvc.DetachInstances(&detachParams); err != nil { + if _, err := asSvc.DetachInstancesWithContext(ctx, &detachParams); err != nil { logger.Println(err.Error()) return err } @@ -625,7 +626,7 @@ func (a *autoScalingGroup) detachAndTerminateOnDemandInstance( // Wait till detachment initialize is complete before terminate instance time.Sleep(20 * time.Second * a.region.conf.SleepMultiplier) - return a.instances.get(*instanceID).terminate() + return a.instances.get(*instanceID).terminate(ctx) } // Counts the number of already running instances on-demand or spot, in any or a specific AZ. diff --git a/core/autoscaling_test.go b/core/autoscaling_test.go index 7ad6d11d..3af7743d 100644 --- a/core/autoscaling_test.go +++ b/core/autoscaling_test.go @@ -1,6 +1,7 @@ package autospotting import ( + "context" "errors" "reflect" "testing" @@ -1380,7 +1381,7 @@ func TestNeedReplaceOnDemandInstances(t *testing.T) { a.DesiredCapacity = tt.desiredCapacity a.instances = tt.asgInstances a.minOnDemand = tt.minOnDemand - shouldRun := a.needReplaceOnDemandInstances() + shouldRun := a.needReplaceOnDemandInstances(context.Background()) if tt.expectedRun != shouldRun { t.Errorf("needReplaceOnDemandInstances returned: %t expected %t", shouldRun, tt.expectedRun) @@ -1518,7 +1519,7 @@ func TestDetachAndTerminateOnDemandInstance(t *testing.T) { region: tt.regionASG, instances: tt.instancesASG, } - err := a.detachAndTerminateOnDemandInstance(tt.instanceID) + err := a.detachAndTerminateOnDemandInstance(context.Background(), tt.instanceID) CheckErrors(t, err, tt.expected) }) } @@ -1558,7 +1559,7 @@ func TestAttachSpotInstance(t *testing.T) { name: "testASG", region: tt.regionASG, } - err := a.attachSpotInstance(tt.instanceID) + err := a.attachSpotInstance(context.Background(), tt.instanceID) CheckErrors(t, err, tt.expected) }) } @@ -1629,7 +1630,7 @@ func TestLoadLaunchConfiguration(t *testing.T) { LaunchConfigurationName: tt.nameLC, }, } - err := a.loadLaunchConfiguration() + err := a.loadLaunchConfiguration(context.Background()) lc := a.launchConfiguration if !reflect.DeepEqual(tt.expectedErr, err) { @@ -1681,7 +1682,7 @@ func TestSetAutoScalingMaxSize(t *testing.T) { name: "testASG", region: tt.regionASG, } - err := a.setAutoScalingMaxSize(tt.maxSize) + err := a.setAutoScalingMaxSize(context.Background(), tt.maxSize) CheckErrors(t, err, tt.expected) }) } @@ -2572,7 +2573,7 @@ func TestReplaceOnDemandInstanceWithSpot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - returned := tt.asg.replaceOnDemandInstanceWithSpot(tt.spotID) + returned := tt.asg.replaceOnDemandInstanceWithSpot(context.Background(), tt.spotID) CheckErrors(t, returned, tt.expected) }) } diff --git a/core/config.go b/core/config.go index 43b58765..b0a97418 100644 --- a/core/config.go +++ b/core/config.go @@ -42,4 +42,8 @@ type Config struct { // Controls how are the tags used to filter the groups. // Available options: 'opt-in' and 'opt-out', default: 'opt-in' TagFilteringMode string + + // Log level for X-Ray SDK + // See https://github.com/cihub/seelog/blob/master/common_loglevel.go#L41 for available options, it's used internally by X-Ray SDK + XRayLogLevel string } diff --git a/core/connections.go b/core/connections.go index 96cb42f3..99c487ac 100644 --- a/core/connections.go +++ b/core/connections.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go/service/autoscaling/autoscalingiface" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-xray-sdk-go/xray" ) type connections struct { @@ -35,8 +36,16 @@ func (c *connections) connect(region string) { asConn := make(chan *autoscaling.AutoScaling) ec2Conn := make(chan *ec2.EC2) - go func() { asConn <- autoscaling.New(c.session) }() - go func() { ec2Conn <- ec2.New(c.session) }() + go func() { + c := autoscaling.New(c.session) + xray.AWS(c.Client) + asConn <- c + }() + go func() { + c := ec2.New(c.session) + xray.AWS(c.Client) + ec2Conn <- c + }() c.autoScaling, c.ec2, c.region = <-asConn, <-ec2Conn, region diff --git a/core/instance.go b/core/instance.go index 9365f5d3..3ccb3908 100644 --- a/core/instance.go +++ b/core/instance.go @@ -1,6 +1,7 @@ package autospotting import ( + "context" "fmt" "math" "path/filepath" @@ -143,10 +144,10 @@ func (i *instance) canTerminate() bool { *i.State.Name != ec2.InstanceStateNameShuttingDown } -func (i *instance) terminate() error { +func (i *instance) terminate(ctx context.Context) error { svc := i.region.services.ec2 if i.canTerminate() { - _, err := svc.TerminateInstances(&ec2.TerminateInstancesInput{ + _, err := svc.TerminateInstancesWithContext(ctx, &ec2.TerminateInstancesInput{ InstanceIds: []*string{i.InstanceId}, }) if err != nil { diff --git a/core/instance_test.go b/core/instance_test.go index 52884c1d..cb336c46 100644 --- a/core/instance_test.go +++ b/core/instance_test.go @@ -7,6 +7,8 @@ import ( "testing" "time" + "context" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/ec2" @@ -1163,7 +1165,7 @@ func TestTerminate(t *testing.T) { }, } for _, tt := range tests { - ret := tt.inst.terminate() + ret := tt.inst.terminate(context.Background()) if ret != nil && ret.Error() != tt.expected.Error() { t.Errorf("error actual: %s, expected: %s", ret.Error(), tt.expected.Error()) } diff --git a/core/main.go b/core/main.go index 76e04f7c..c342f229 100644 --- a/core/main.go +++ b/core/main.go @@ -7,10 +7,13 @@ import ( "strings" "sync" + "context" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-xray-sdk-go/xray" ) var logger, debug *log.Logger @@ -18,7 +21,7 @@ var logger, debug *log.Logger // Run starts processing all AWS regions looking for AutoScaling groups // enabled and taking action by replacing more pricy on-demand instances with // compatible and cheaper spot instances. -func Run(cfg *Config) { +func Run(ctx context.Context, cfg *Config) { setupLogging(cfg) @@ -26,18 +29,19 @@ func Run(cfg *Config) { // use this only to list all the other regions ec2Conn := connectEC2(cfg.MainRegion) + xray.AWS(ec2Conn.Client) addDefaultFilteringMode(cfg) addDefaultFilter(cfg) - allRegions, err := getRegions(ec2Conn) + allRegions, err := getRegions(ctx, ec2Conn) if err != nil { logger.Println(err.Error()) return } - processRegions(allRegions, cfg) + processRegions(ctx, allRegions, cfg) } @@ -80,7 +84,7 @@ func setupLogging(cfg *Config) { // processAllRegions iterates all regions in parallel, and replaces instances // for each of the ASGs tagged with tags as specified by slice represented by cfg.FilterByTags // by default this is all asg with the tag 'spot-enabled=true'. -func processRegions(regions []string, cfg *Config) { +func processRegions(ctx context.Context, regions []string, cfg *Config) { var wg sync.WaitGroup @@ -93,7 +97,7 @@ func processRegions(regions []string, cfg *Config) { if r.enabled() { logger.Printf("Enabled to run in %s, processing region.\n", r.name) - r.processRegion() + r.processRegion(ctx) } else { debug.Println("Not enabled to run in", r.name) debug.Println("List of enabled regions:", cfg.Regions) @@ -117,12 +121,12 @@ func connectEC2(region string) *ec2.EC2 { } // getRegions generates a list of AWS regions. -func getRegions(ec2conn ec2iface.EC2API) ([]string, error) { +func getRegions(ctx context.Context, ec2conn ec2iface.EC2API) ([]string, error) { var output []string logger.Println("Scanning for available AWS regions") - resp, err := ec2conn.DescribeRegions(&ec2.DescribeRegionsInput{}) + resp, err := ec2conn.DescribeRegionsWithContext(ctx, &ec2.DescribeRegionsInput{}) if err != nil { logger.Println(err.Error()) diff --git a/core/main_test.go b/core/main_test.go index 95b38a02..37a7d7d7 100644 --- a/core/main_test.go +++ b/core/main_test.go @@ -5,6 +5,8 @@ import ( "reflect" "testing" + "context" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" ) @@ -48,7 +50,7 @@ func Test_getRegions(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := getRegions(tt.ec2conn) + got, err := getRegions(context.Background(), tt.ec2conn) CheckErrors(t, err, tt.wantErr) if !reflect.DeepEqual(got, tt.want) { diff --git a/core/mock_test.go b/core/mock_test.go index a7637195..c058d1ba 100644 --- a/core/mock_test.go +++ b/core/mock_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/autoscaling/autoscalingiface" "github.com/aws/aws-sdk-go/service/ec2" @@ -44,6 +45,10 @@ func (m mockEC2) DescribeSpotPriceHistory(in *ec2.DescribeSpotPriceHistoryInput) return m.dspho, m.dspherr } +func (m mockEC2) DescribeSpotPriceHistoryWithContext(ctx aws.Context, in *ec2.DescribeSpotPriceHistoryInput, options ...request.Option) (*ec2.DescribeSpotPriceHistoryOutput, error) { + return m.DescribeSpotPriceHistory(in) +} + func (m mockEC2) DescribeInstancesPages(in *ec2.DescribeInstancesInput, fn func(*ec2.DescribeInstancesOutput, bool) bool) error { return m.diperr } @@ -52,10 +57,18 @@ func (m mockEC2) TerminateInstances(*ec2.TerminateInstancesInput) (*ec2.Terminat return m.tio, m.tierr } +func (m mockEC2) TerminateInstancesWithContext(ctx aws.Context, in *ec2.TerminateInstancesInput, options ...request.Option) (*ec2.TerminateInstancesOutput, error) { + return m.TerminateInstances(in) +} + func (m mockEC2) DescribeRegions(*ec2.DescribeRegionsInput) (*ec2.DescribeRegionsOutput, error) { return m.dro, m.drerr } +func (m mockEC2) DescribeRegionsWithContext(ctx aws.Context, in *ec2.DescribeRegionsInput, options ...request.Option) (*ec2.DescribeRegionsOutput, error) { + return m.DescribeRegions(in) +} + // For testing we "convert" the SecurityGroupIDs/SecurityGroupNames by // prefixing the original name/id with "sg-" if not present already. We // also fill up the rest of the string to the length of a typical ID with @@ -123,18 +136,34 @@ func (m mockASG) DetachInstances(*autoscaling.DetachInstancesInput) (*autoscalin return m.dio, m.dierr } +func (m mockASG) DetachInstancesWithContext(ctx aws.Context, in *autoscaling.DetachInstancesInput, options ...request.Option) (*autoscaling.DetachInstancesOutput, error) { + return m.DetachInstances(in) +} + func (m mockASG) AttachInstances(*autoscaling.AttachInstancesInput) (*autoscaling.AttachInstancesOutput, error) { return m.aio, m.aierr } +func (m mockASG) AttachInstancesWithContext(ctx aws.Context, in *autoscaling.AttachInstancesInput, options ...request.Option) (*autoscaling.AttachInstancesOutput, error) { + return m.AttachInstances(in) +} + func (m mockASG) DescribeLaunchConfigurations(*autoscaling.DescribeLaunchConfigurationsInput) (*autoscaling.DescribeLaunchConfigurationsOutput, error) { return m.dlco, m.dlcerr } +func (m mockASG) DescribeLaunchConfigurationsWithContext(ctx aws.Context, in *autoscaling.DescribeLaunchConfigurationsInput, opts ...request.Option) (*autoscaling.DescribeLaunchConfigurationsOutput, error) { + return m.DescribeLaunchConfigurations(in) +} + func (m mockASG) UpdateAutoScalingGroup(*autoscaling.UpdateAutoScalingGroupInput) (*autoscaling.UpdateAutoScalingGroupOutput, error) { return m.uasgo, m.uasgerr } +func (m mockASG) UpdateAutoScalingGroupWithContext(ctx aws.Context, in *autoscaling.UpdateAutoScalingGroupInput, opts ...request.Option) (*autoscaling.UpdateAutoScalingGroupOutput, error) { + return m.UpdateAutoScalingGroup(in) +} + func (m mockASG) DescribeTagsPages(input *autoscaling.DescribeTagsInput, function func(*autoscaling.DescribeTagsOutput, bool) bool) error { function(m.dto, true) return nil @@ -144,3 +173,7 @@ func (m mockASG) DescribeAutoScalingGroupsPages(input *autoscaling.DescribeAutoS function(m.dasgo, true) return nil } + +func (m mockASG) DescribeAutoScalingGroupsPagesWithContext(ctx aws.Context, input *autoscaling.DescribeAutoScalingGroupsInput, function func(*autoscaling.DescribeAutoScalingGroupsOutput, bool) bool, options ...request.Option) error { + return m.DescribeAutoScalingGroupsPages(input, function) +} diff --git a/core/region.go b/core/region.go index 121abdd9..0035e422 100644 --- a/core/region.go +++ b/core/region.go @@ -7,6 +7,8 @@ import ( "strings" "sync" + "context" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/ec2" @@ -69,7 +71,7 @@ func (r *region) enabled() bool { return false } -func (r *region) processRegion() { +func (r *region) processRegion(ctx context.Context) { logger.Println("Creating connections to the required AWS services in", r.name) r.services.connect(r.name) @@ -79,25 +81,25 @@ func (r *region) processRegion() { r.setupAsgFilters() logger.Println("Scanning for enabled AutoScaling groups in ", r.name) - r.scanForEnabledAutoScalingGroups() + r.scanForEnabledAutoScalingGroups(ctx) // only process further the region if there are any enabled autoscaling groups // within it if r.hasEnabledAutoScalingGroups() { logger.Println("Scanning full instance information in", r.name) - r.determineInstanceTypeInformation(r.conf) + r.determineInstanceTypeInformation(ctx, r.conf) debug.Println(spew.Sdump(r.instanceTypeInformation)) logger.Println("Scanning instances in", r.name) - err := r.scanInstances() + err := r.scanInstances(ctx) if err != nil { logger.Printf("Failed to scan instances in %s error: %s\n", r.name, err) } logger.Println("Processing enabled AutoScaling groups in", r.name) - r.processEnabledAutoScalingGroups() + r.processEnabledAutoScalingGroups(ctx) } else { logger.Println(r.name, "has no enabled AutoScaling groups") } @@ -136,7 +138,7 @@ func splitTagAndValue(value string) *Tag { return nil } -func (r *region) scanInstances() error { +func (r *region) scanInstances(ctx context.Context) error { svc := r.services.ec2 input := &ec2.DescribeInstancesInput{ Filters: []*ec2.Filter{ @@ -153,7 +155,8 @@ func (r *region) scanInstances() error { r.instances = makeInstances() pageNum := 0 - err := svc.DescribeInstancesPages( + err := svc.DescribeInstancesPagesWithContext( + ctx, input, func(page *ec2.DescribeInstancesOutput, lastPage bool) bool { pageNum++ @@ -190,7 +193,7 @@ func (r *region) addInstance(inst *ec2.Instance) { }) } -func (r *region) determineInstanceTypeInformation(cfg *Config) { +func (r *region) determineInstanceTypeInformation(ctx context.Context, cfg *Config) { r.instanceTypeInformation = make(map[string]instanceTypeInformation) @@ -237,20 +240,20 @@ func (r *region) determineInstanceTypeInformation(cfg *Config) { // return entries about the available instance types, so no invalid instance // types would be returned - if err := r.requestSpotPrices(); err != nil { + if err := r.requestSpotPrices(ctx); err != nil { logger.Println(err.Error()) } debug.Println(spew.Sdump(r.instanceTypeInformation)) } -func (r *region) requestSpotPrices() error { +func (r *region) requestSpotPrices(ctx context.Context) error { s := spotPrices{conn: r.services} // Retrieve all current spot prices from the current region. // TODO: add support for other OSes - err := s.fetch(r.conf.SpotProductDescription, 0, nil, nil) + err := s.fetch(ctx, r.conf.SpotProductDescription, 0, nil, nil) if err != nil { return errors.New("Couldn't fetch spot prices in " + r.name) @@ -340,12 +343,13 @@ func (r *region) findMatchingASGsInPageOfResults(groups []*autoscaling.Group, return asgs } -func (r *region) scanForEnabledAutoScalingGroups() { +func (r *region) scanForEnabledAutoScalingGroups(ctx context.Context) { svc := r.services.autoScaling pageNum := 0 - err := svc.DescribeAutoScalingGroupsPages( + err := svc.DescribeAutoScalingGroupsPagesWithContext( + ctx, &autoscaling.DescribeAutoScalingGroupsInput{}, func(page *autoscaling.DescribeAutoScalingGroupsOutput, lastPage bool) bool { pageNum++ @@ -368,11 +372,11 @@ func (r *region) hasEnabledAutoScalingGroups() bool { } -func (r *region) processEnabledAutoScalingGroups() { +func (r *region) processEnabledAutoScalingGroups(ctx context.Context) { for _, asg := range r.enabledASGs { r.wg.Add(1) go func(a autoScalingGroup) { - a.process() + a.process(ctx) r.wg.Done() }(asg) } diff --git a/core/region_test.go b/core/region_test.go index b7e74ea5..5d6a2c3e 100644 --- a/core/region_test.go +++ b/core/region_test.go @@ -5,6 +5,8 @@ import ( "reflect" "testing" + "context" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/ec2" @@ -196,7 +198,7 @@ func TestOnDemandPriceMultiplier(t *testing.T) { dspherr: nil, }, }} - r.determineInstanceTypeInformation(cfg) + r.determineInstanceTypeInformation(context.Background(), cfg) actualPrice := r.instanceTypeInformation["m1.small"].pricing.onDemand if math.Abs(actualPrice-tt.want) > 0.000001 { @@ -498,7 +500,7 @@ func TestFilterAsgs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r := tt.tregion - r.scanForEnabledAutoScalingGroups() + r.scanForEnabledAutoScalingGroups(context.Background()) var asgNames []string for _, name := range r.enabledASGs { asgNames = append(asgNames, name.name) diff --git a/core/spot_price.go b/core/spot_price.go index 888d90f9..f5703765 100644 --- a/core/spot_price.go +++ b/core/spot_price.go @@ -3,6 +3,8 @@ package autospotting import ( "time" + "context" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" ) @@ -13,7 +15,9 @@ type spotPrices struct { } // fetch queries all spot prices in the current region -func (s *spotPrices) fetch(product string, +func (s *spotPrices) fetch( + ctx context.Context, + product string, duration time.Duration, availabilityZone *string, instanceTypes []*string) error { @@ -31,7 +35,7 @@ func (s *spotPrices) fetch(product string, InstanceTypes: instanceTypes, } - resp, err := ec2Conn.DescribeSpotPriceHistory(params) + resp, err := ec2Conn.DescribeSpotPriceHistoryWithContext(ctx, params) if err != nil { logger.Println(s.conn.region, "Failed requesting spot prices:", err.Error()) diff --git a/core/spot_price_test.go b/core/spot_price_test.go index 04490844..9fdb197f 100644 --- a/core/spot_price_test.go +++ b/core/spot_price_test.go @@ -6,6 +6,8 @@ import ( "testing" "time" + "context" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" ) @@ -65,7 +67,7 @@ func Test_fetch(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - err := tc.config.fetch(tc.product, tc.duration, tc.availabilityZone, tc.instanceTypes) + err := tc.config.fetch(context.Background(), tc.product, tc.duration, tc.availabilityZone, tc.instanceTypes) if len(tc.data) != len(tc.config.data) { t.Errorf("Price data actual: %v\nexpected: %v", tc.config.data, tc.data) } diff --git a/vendor/github.com/aws/aws-lambda-go/.travis.yml b/vendor/github.com/aws/aws-lambda-go/.travis.yml deleted file mode 100644 index aa68fc70..00000000 --- a/vendor/github.com/aws/aws-lambda-go/.travis.yml +++ /dev/null @@ -1,35 +0,0 @@ -language: go - -go: - - 1.9 - - tip - -before_install: - - curl -L -s https://github.com/golang/dep/releases/download/v0.4.1/dep-linux-amd64 -o $GOPATH/bin/dep - - chmod +x $GOPATH/bin/dep - -install: - - dep ensure - - go get github.com/golang/lint/golint - - go get github.com/haya14busa/goverage - -matrix: - allow_failures: - - go: tip - fast_finish: true - -notifications: - email: false - -before_script: - - PKGS=$(go list ./...) - - LINT_PKGS=$(go list ./... | grep -Ev 'aws-lambda-go/lambda') - -script: - - diff -u <(echo -n) <(gofmt -d ./) # Fail if a .go file hasn't been formatted with gofmt - - goverage -v -covermode=atomic -coverprofile=coverage.txt $PKGS # Run all tests with coverage - - go vet -v ./... # static analyisis - - golint $LINT_PKGS # lint - ignore failures for now - -after_success: - - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/aws/aws-lambda-go/Gopkg.lock b/vendor/github.com/aws/aws-lambda-go/Gopkg.lock deleted file mode 100644 index a4928310..00000000 --- a/vendor/github.com/aws/aws-lambda-go/Gopkg.lock +++ /dev/null @@ -1,33 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - name = "github.com/davecgh/go-spew" - packages = ["spew"] - revision = "346938d642f2ec3594ed81d874461961cd0faa76" - version = "v1.1.0" - -[[projects]] - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - name = "github.com/stretchr/testify" - packages = ["assert"] - revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" - version = "v1.2.1" - -[[projects]] - name = "gopkg.in/urfave/cli.v1" - packages = ["."] - revision = "cfb38830724cc34fedffe9a2a29fb54fa9169cd1" - version = "v1.20.0" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "21bf02839d69eb4ab638d20ad48614cf2e71753b2005ef5fa2b05cb9704ab5d2" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/aws/aws-lambda-go/Gopkg.toml b/vendor/github.com/aws/aws-lambda-go/Gopkg.toml deleted file mode 100644 index 323002ca..00000000 --- a/vendor/github.com/aws/aws-lambda-go/Gopkg.toml +++ /dev/null @@ -1,21 +0,0 @@ - -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" diff --git a/vendor/github.com/aws/aws-lambda-go/README.md b/vendor/github.com/aws/aws-lambda-go/README.md deleted file mode 100644 index 9cc2eae4..00000000 --- a/vendor/github.com/aws/aws-lambda-go/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# aws-lambda-go - -Libraries, samples and tools to help Go developers develop AWS Lambda functions. - -To learn more about writing AWS Lambda functions in Go, go to [the offical documentation](https://docs.aws.amazon.com/lambda/latest/dg/go-programming-model.html) - -[![GoDoc][1]][2] -[![GoCard][3]][4] -[![Build Status][5]][6] -[![codecov][7]][8] - -[1]: https://godoc.org/github.com/aws/aws-lambda-go?status.svg -[2]: https://godoc.org/github.com/aws/aws-lambda-go -[3]: https://goreportcard.com/badge/github.com/aws/aws-lambda-go -[4]: https://goreportcard.com/report/github.com/aws/aws-lambda-go -[5]: https://travis-ci.org/aws/aws-lambda-go.svg?branch=master -[6]: https://travis-ci.org/aws/aws-lambda-go -[7]: https://codecov.io/gh/aws/aws-lambda-go/branch/master/graph/badge.svg -[8]: https://codecov.io/gh/aws/aws-lambda-go - -# Getting Started - -``` Go -// main.go -package main - -import ( - "github.com/aws/aws-lambda-go/lambda" -) - -func hello() (string, error) { - return "Hello ƛ!", nil -} - -func main() { - // Make the handler available for Remote Procedure Call by AWS Lambda - lambda.Start(hello) -} -``` - -# Building your function - -Preparing a binary to deploy to AWS Lambda requires that it is compiled for Linux and placed into a .zip file. - -## For developers on Linux and macOS -``` shell -# Remember to build your handler executable for Linux! -GOOS=linux GOARCH=amd64 go build -o main main.go -zip main.zip main -``` - -## For developers on Windows - -Windows developers may have trouble producing a zip file that marks the binary as exectuable on Linux. To create a .zip that will work on AWS Lambda, the `build-lambda-zip` tool may be helpful. - -Get the tool -``` shell -go.exe get -u github.com/aws/aws-lambda-go/cmd/build-lambda-zip -``` - -Use the tool from your `GOPATH`. If you have a default installation of Go, the tool will be in `%USERPROFILE%\Go\bin`. - -in cmd.exe: -``` bat -set GOOS=linux -set GOARCH=amd64 -go build -o main main.go -%USERPROFILE%\Go\bin\build-lambda-zip.exe -o main.zip main -``` - -in Powershell: -``` posh -$env:GOOS = "linux" -$env:GOARCH = "amd64" -go build -o main main.go -~\Go\Bin\build-lambda-zip.exe -o main.zip main -``` -# Deploying your functions - -To deploy your function, refer to the offical documentation for [deploying using the AWS CLI, AWS Cloudformation, and AWS SAM](https://docs.aws.amazon.com/lambda/latest/dg/deploying-lambda-apps.html). - -# Event Integrations - -The [event models](https://github.com/aws/aws-lambda-go/tree/master/events) can be used to model AWS event sources. The offical documentation has [detailed walkthroughs](https://docs.aws.amazon.com/lambda/latest/dg/use-cases.html). - diff --git a/vendor/github.com/aws/aws-lambda-go/events/README.md b/vendor/github.com/aws/aws-lambda-go/events/README.md deleted file mode 100644 index 7821a28b..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Overview - -[![GoDoc](https://godoc.org/github.com/aws/aws-lambda-go/events?status.svg)](https://godoc.org/github.com/aws/aws-lambda-go/events) - -This package provides input types for Lambda functions that process AWS events. - -# Samples - -[API Gateway](README_ApiGatewayEvent.md) - -[API Gateway Custom Authorizer](README_ApiGatewayCustomAuthorizer.md) - -[CloudFormation Events](../cfn/README.md) - -[Code Commit Events](README_CodeCommit.md) - -[Cognito Events](README_Cognito.md) - -[Config Events](README_Config.md) - -[DynamoDB Events](README_DynamoDB.md) - -[Kinesis Events](README_Kinesis.md) - -[Kinesis Firehose Events](README_KinesisFirehose.md) - -[S3 Events](README_S3.md) - -[SNS Events](README_SNS.md) diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_ApiGatewayCustomAuthorizer.md b/vendor/github.com/aws/aws-lambda-go/events/README_ApiGatewayCustomAuthorizer.md deleted file mode 100644 index adb86078..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_ApiGatewayCustomAuthorizer.md +++ /dev/null @@ -1,67 +0,0 @@ -# Sample Function - -The following is a simple TOKEN authorizer example to demonstrate how to use an authorization -token to allow or deny a request. In this example, the caller named "user" is allowed to invoke -a request if the client-supplied token value is "allow". The caller is not allowed to invoke -the request if the token value is "deny". If the token value is "Unauthorized", the function -returns the "Unauthorized" error with an HTTP status code of 401. For any other token value, -the authorizer returns an "Invalid token" error. - -This example is based on the [JavaScript sample](https://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-token-lambda-function-create) from the API Gateway documentation - -```go -package main - -import ( - "context" - "errors" - "strings" - - "github.com/aws/aws-lambda-go/events" - "github.com/aws/aws-lambda-go/lambda" -) - -// Help function to generate an IAM policy -func generatePolicy(principalId, effect, resource string) events.APIGatewayCustomAuthorizerResponse { - authResponse := events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalId} - - if effect != "" && resource != "" { - authResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{ - Version: "2012-10-17", - Statement: []events.IAMPolicyStatement{ - { - Action: []string{"execute-api:Invoke"}, - Effect: effect, - Resource: []string{resource}, - }, - }, - } - } - - // Optional output with custom properties of the String, Number or Boolean type. - authResponse.Context = map[string]interface{}{ - "stringKey": "stringval", - "numberKey": 123, - "booleanKey": true, - } - return authResponse -} - -func handleRequest(ctx context.Context, event events.APIGatewayCustomAuthorizerRequest) (events.APIGatewayCustomAuthorizerResponse, error) { - token := event.AuthorizationToken - switch strings.ToLower(token) { - case "allow": - return generatePolicy("user", "Allow", event.MethodArn), nil - case "deny": - return generatePolicy("user", "Deny", event.MethodArn), nil - case "unauthorized": - return events.APIGatewayCustomAuthorizerResponse{}, errors.New("Unauthorized") // Return a 401 Unauthorized response - default: - return events.APIGatewayCustomAuthorizerResponse{}, errors.New("Error: Invalid token") - } -} - -func main() { - lambda.Start(handleRequest) -} -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_ApiGatewayEvent.md b/vendor/github.com/aws/aws-lambda-go/events/README_ApiGatewayEvent.md deleted file mode 100644 index 65ceabce..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_ApiGatewayEvent.md +++ /dev/null @@ -1,36 +0,0 @@ -# Overview - -API Gateway events consist of a request that was routed to a Lambda function by API Gateway. When this happens, API Gateway expects the result of the function to be the response that API Gateway should respond with. - -# Sample Function - -The following is a sample class and Lambda function that receives Amazon API Gateway event record data as an input, writes some of the record data to CloudWatch Logs, and responds with a 200 status and the same body as the request. (Note that by default anything written to Console will be logged as CloudWatch Logs events.) - -```go - -package main - -import ( - "context" - "fmt" - - "github.com/aws/aws-lambda-go/events" - "github.com/aws/aws-lambda-go/lambda" -) - -func handleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { - fmt.Printf("Processing request data for request %s.\n", request.RequestContext.RequestID) - fmt.Printf("Body size = %d.\n", len(request.Body)) - - fmt.Println("Headers:") - for key, value := range request.Headers { - fmt.Printf(" %s: %s\n", key, value) - } - - return events.APIGatewayProxyResponse{Body: request.Body, StatusCode: 200}, nil -} - -func main() { - lambda.Start(handleRequest) -} -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_AutoScaling.md b/vendor/github.com/aws/aws-lambda-go/events/README_AutoScaling.md deleted file mode 100644 index 18a0ec45..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_AutoScaling.md +++ /dev/null @@ -1,16 +0,0 @@ -# Sample Function - -The following is a sample class and Lambda function that receives Amazon S3 event record data as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.) - -```go - -import ( - "strings" - "github.com/aws/aws-lambda-go/events") - -func handler(ctx context.Context, autoScalingEvent events.AutoScalingEvent) { - fmt.Printf("Instance-Id available in event is %s \n",autoScalingEvent.Detail["EC2InstanceId"]) - } -} - -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_CodeCommit.md b/vendor/github.com/aws/aws-lambda-go/events/README_CodeCommit.md deleted file mode 100644 index aea1d703..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_CodeCommit.md +++ /dev/null @@ -1,17 +0,0 @@ -# Sample Function - -The following is a sample Lambda function that receives Amazon CodeCommit event -records input and prints them to `os.Stdout`.) - -```go -import ( - "fmt" - "github.com/aws/aws-lambda-go/events" -) - -func handleRequest(evt events.CodeCommitEvent) { - for _, record := range evt.Records { - fmt.Println(record) - } -} -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_Cognito.md b/vendor/github.com/aws/aws-lambda-go/events/README_Cognito.md deleted file mode 100644 index a8ee5867..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_Cognito.md +++ /dev/null @@ -1,32 +0,0 @@ -# Sample Function - -The following is a sample Lambda function that receives Amazon Cognito Sync event record data as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.) - -```go - -package main - -import ( - "fmt" - - "github.com/aws/aws-lambda-go/lambda" - "github.com/aws/aws-lambda-go/events" -) - -func handler(cognitoEvent events.CognitoEvent) error { - for datasetName, datasetRecord := range cognitoEvent.DatasetRecords { - fmt.Printf("[%s -- %s] %s -> %s -> %s \n", - cognitoEvent.EventType, - datasetName, - datasetRecord.OldValue, - datasetRecord.Op, - datasetRecord.NewValue) - } - return nil -} - -func main() { - lambda.Start(handler) -} - -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PostConfirmation.md b/vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PostConfirmation.md deleted file mode 100644 index 34718374..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PostConfirmation.md +++ /dev/null @@ -1,25 +0,0 @@ -# Sample Function - -The following is a sample Lambda function that receives Amazon Cognito User Pools post-confirmation event as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.) - -Please see instructions for setting up the Cognito triggers at https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html . - -```go -package main - -import ( - "fmt" - - "github.com/aws/aws-lambda-go/lambda" - "github.com/aws/aws-lambda-go/events" -) - -func handler(event events.CognitoEventUserPoolsPostConfirmation) (events.CognitoEventUserPoolsPostConfirmation, error) { - fmt.Printf("PostConfirmation for user: %s\n", event.UserName) - return event, nil -} - -func main() { - lambda.Start(handler) -} -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PreSignup.md b/vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PreSignup.md deleted file mode 100644 index 9e782fcc..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PreSignup.md +++ /dev/null @@ -1,26 +0,0 @@ -# Sample Function - -The following is a sample Lambda function that receives Amazon Cognito User Pools pre-signup event as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.) - -Please see instructions for setting up the Cognito triggers at https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html . - -```go -package main - -import ( - "fmt" - - "github.com/aws/aws-lambda-go/lambda" - "github.com/aws/aws-lambda-go/events" -) - -func handler(event events.CognitoEventUserPoolsPreSignup) (events.CognitoEventUserPoolsPreSignup, error) { - fmt.Printf("PreSignup of user: %s\n", event.UserName) - event.Response.AutoConfirmUser = true - return event, nil -} - -func main() { - lambda.Start(handler) -} -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_Config.md b/vendor/github.com/aws/aws-lambda-go/events/README_Config.md deleted file mode 100644 index e2d217a9..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_Config.md +++ /dev/null @@ -1,18 +0,0 @@ -# Sample Function - -The following is a sample Lambda function that receives Amazon Config event record data as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.) - -```go - -import ( - "strings" - "github.com/aws/aws-lambda-go/events" -) - -func handleRequest(ctx context.Context, configEvent events.ConfigEvent) { - fmt.Printf("AWS Config rule: %s\n", configEvent.ConfigRuleName) - fmt.Printf("Invoking event JSON: %s\n", configEvent.InvokingEvent) - fmt.Printf("Event version: %s\n", configEvent.Version) -} - -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_DynamoDB.md b/vendor/github.com/aws/aws-lambda-go/events/README_DynamoDB.md deleted file mode 100644 index a01201ff..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_DynamoDB.md +++ /dev/null @@ -1,80 +0,0 @@ -# Sample Function - -The following is a sample Lambda function that receives DynamoDB event data as input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs.) - -```go -import ( - "context" - "fmt" - - "github.com/aws/aws-lambda-go/events" -) - -func handleRequest(ctx context.Context, e events.DynamoDBEvent) { - - for _, record := range e.Records { - fmt.Printf("Processing request data for event ID %s, type %s.\n", record.EventID, record.EventName) - - // Print new values for attributes of type String - for name, value := range record.Change.NewImage { - if value.DataType() == events.DataTypeString { - fmt.Printf("Attribute name: %s, value: %s\n", name, value.String()) - } - } - } -} -``` - -# Reading attribute values - -Stream notifications are delivered to the Lambda handler whenever data in the DynamoDB table is modified. -Depending on the Stream settings, a StreamRecord may contain the following data: - -* Keys: key attributes of the modified item. -* NewImage: the entire item, as it appears after it was modified. -* OldImage: the entire item, as it appeared before it was modified. - -The values for the attributes can be accessed using the AttributeValue type. For each type -supported natively by DynamoDB, there is a corresponding accessor method: - -DynamoDB type | AttributeValue accessor method | Return type | DataType constant ----------------|--------------------------------|---------------------------|------------------ -B (Binary) | Binary() | []byte | DataTypeBinary -BOOL (Boolean) | Boolean() | bool | DataTypeBoolean -BS (Binary Set)| BinarySet() | [][]byte | DataTypeBinarySet -L (List) | List() | []AttributeValue | DataTypeList -M (Map) | Map() | map[string]AttributeValue | DataTypeMap -N (Number) | Number() / Integer() / Float() | string / int64 / float64 | DataTypeNumber -NS (Number Set)| NumberSet() | []string | DataTypeNumberSet -NULL (Null) | IsNull() | bool | DataTypeNull -S (String) | String() | string | DataTypeString -SS (String Set)| StringSet() | []string | DataTypeStringSet - -Calling the accessor method for the incorrect type will result in a panic. If the type needs to -be discovered in runtime, the method DataType() can be used in order to determine the correct accessor. - -More information about DynamoDB data types can be seen [in this documentation](http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html). - -The following example reads values of attributes name and age, for which types are known to be String and Number: - -```go -import ( - "context" - "fmt" - - "github.com/aws/aws-lambda-go/events" -) - -func handleRequest(ctx context.Context, e events.DynamoDBEvent) { - - for _, record := range e.Records { - fmt.Printf("Processing request data for event ID %s, type %s.\n", record.EventID, record.EventName) - - // Print new values for attributes name and age - name := record.Change.NewImage["name"].String() - age, _ := record.Change.NewImage["age"].Integer() - - fmt.Printf("Name: %s, age: %d\n", name, age) - } -} -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_Kinesis.md b/vendor/github.com/aws/aws-lambda-go/events/README_Kinesis.md deleted file mode 100644 index 4dd23b20..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_Kinesis.md +++ /dev/null @@ -1,33 +0,0 @@ -# Sample Function - -The following is a sample class and Lambda function that receives Amazon Kinesis event record data as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.) - -```go - -package main - -import ( - "context" - "fmt" - - "github.com/aws/aws-lambda-go/events" - "github.com/aws/aws-lambda-go/lambda" -) - -func handler(ctx context.Context, kinesisEvent events.KinesisEvent) error { - for _, record := range kinesisEvent.Records { - kinesisRecord := record.Kinesis - dataBytes := kinesisRecord.Data - dataText := string(dataBytes) - - fmt.Printf("%s Data = %s \n", record.EventName, dataText) - } - - return nil -} - -func main() { - lambda.Start(handler) -} - -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_KinesisFirehose.md b/vendor/github.com/aws/aws-lambda-go/events/README_KinesisFirehose.md deleted file mode 100644 index ac7d85c4..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_KinesisFirehose.md +++ /dev/null @@ -1,45 +0,0 @@ -# Sample Function - -The following is a sample Lambda function that transforms Kinesis Firehose records by doing a ToUpper on the data. - -```go - -package main - -import ( - "fmt" - "strings" - - "github.com/aws/aws-lambda-go/events" - "github.com/aws/aws-lambda-go/lambda" -) - -func handleRequest(evnt events.KinesisFirehoseEvent) (events.KinesisFirehoseResponse, error) { - - fmt.Printf("InvocationID: %s\n", evnt.InvocationID) - fmt.Printf("DeliveryStreamArn: %s\n", evnt.DeliveryStreamArn) - fmt.Printf("Region: %s\n", evnt.Region) - - var response events.KinesisFirehoseResponse - - for _, record := range evnt.Records { - fmt.Printf("RecordID: %s\n", record.RecordID) - fmt.Printf("ApproximateArrivalTimestamp: %s\n", record.ApproximateArrivalTimestamp) - - // Transform data: ToUpper the data - var transformedRecord events.KinesisFirehoseResponseRecord - transformedRecord.RecordID = record.RecordID - transformedRecord.Result = events.KinesisFirehoseTransformedStateOk - transformedRecord.Data = []byte(strings.ToUpper(string(record.Data))) - - response.Records = append(response.Records, transformedRecord) - } - - return response, nil -} - -func main() { - lambda.Start(handleRequest) -} - -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_S3.md b/vendor/github.com/aws/aws-lambda-go/events/README_S3.md deleted file mode 100644 index a8f746f7..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_S3.md +++ /dev/null @@ -1,20 +0,0 @@ -# Sample Function - -The following is a sample class and Lambda function that receives Amazon S3 event record data as an input and writes some of the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.) - -```go - -import ( - "fmt" - "context" - "github.com/aws/aws-lambda-go/events" -) - -func handler(ctx context.Context, s3Event events.S3Event) { - for _, record := range s3Event.Records { - s3 := record.S3 - fmt.Printf("[%s - %s] Bucket = %s, Key = %s \n", record.EventSource, record.EventTime, s3.Bucket.Name, s3.Object.Key) - } -} - -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/README_SNS.md b/vendor/github.com/aws/aws-lambda-go/events/README_SNS.md deleted file mode 100644 index f198793d..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/README_SNS.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Sample Function - -The following is a sample class and Lambda function that receives Amazon SNS event record data as input, writes some of the record data to CloudWatch Logs, and responds with a 200 status and the same body as the request. (Note that by default anything written to Console will be logged as CloudWatch Logs events.) - -```go -import ( - "context" - "fmt" - - "github.com/aws/aws-lambda-go/events" -) - -func handler(ctx context.Context, snsEvent events.SNSEvent) { - for _, record := range snsEvent.Records { - snsRecord := record.SNS - - fmt.Printf("[%s %s] Message = %s \n", record.EventSource, snsRecord.Timestamp, snsRecord.Message) - } -} -``` diff --git a/vendor/github.com/aws/aws-lambda-go/events/apigw.go b/vendor/github.com/aws/aws-lambda-go/events/apigw.go deleted file mode 100644 index e77753dd..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/apigw.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -// APIGatewayProxyRequest contains data coming from the API Gateway proxy -type APIGatewayProxyRequest struct { - Resource string `json:"resource"` // The resource path defined in API Gateway - Path string `json:"path"` // The url path for the caller - HTTPMethod string `json:"httpMethod"` - Headers map[string]string `json:"headers"` - QueryStringParameters map[string]string `json:"queryStringParameters"` - PathParameters map[string]string `json:"pathParameters"` - StageVariables map[string]string `json:"stageVariables"` - RequestContext APIGatewayProxyRequestContext `json:"requestContext"` - Body string `json:"body"` - IsBase64Encoded bool `json:"isBase64Encoded,omitempty"` -} - -// APIGatewayProxyResponse configures the response to be returned by API Gateway for the request -type APIGatewayProxyResponse struct { - StatusCode int `json:"statusCode"` - Headers map[string]string `json:"headers"` - Body string `json:"body"` - IsBase64Encoded bool `json:"isBase64Encoded,omitempty"` -} - -// APIGatewayProxyRequestContext contains the information to identify the AWS account and resources invoking the -// Lambda function. It also includes Cognito identity information for the caller. -type APIGatewayProxyRequestContext struct { - AccountID string `json:"accountId"` - ResourceID string `json:"resourceId"` - Stage string `json:"stage"` - RequestID string `json:"requestId"` - Identity APIGatewayRequestIdentity `json:"identity"` - ResourcePath string `json:"resourcePath"` - Authorizer map[string]interface{} `json:"authorizer"` - HTTPMethod string `json:"httpMethod"` - APIID string `json:"apiId"` // The API Gateway rest API Id -} - -// APIGatewayRequestIdentity contains identity information for the request caller. -type APIGatewayRequestIdentity struct { - CognitoIdentityPoolID string `json:"cognitoIdentityPoolId"` - AccountID string `json:"accountId"` - CognitoIdentityID string `json:"cognitoIdentityId"` - Caller string `json:"caller"` - APIKey string `json:"apiKey"` - SourceIP string `json:"sourceIp"` - CognitoAuthenticationType string `json:"cognitoAuthenticationType"` - CognitoAuthenticationProvider string `json:"cognitoAuthenticationProvider"` - UserArn string `json:"userArn"` - UserAgent string `json:"userAgent"` - User string `json:"user"` -} - -// APIGatewayCustomAuthorizerRequestTypeRequestIdentity contains identity information for the request caller. -type APIGatewayCustomAuthorizerRequestTypeRequestIdentity struct { - APIKey string `json:"apiKey"` - SourceIP string `json:"sourceIp"` -} - -// APIGatewayCustomAuthorizerContext represents the expected format of an API Gateway custom authorizer response. -// Deprecated. Code should be updated to use the Authorizer map from APIGatewayRequestIdentity. Ex: Authorizer["principalId"] -type APIGatewayCustomAuthorizerContext struct { - PrincipalID *string `json:"principalId"` - StringKey *string `json:"stringKey,omitempty"` - NumKey *int `json:"numKey,omitempty"` - BoolKey *bool `json:"boolKey,omitempty"` -} - -// APIGatewayCustomAuthorizerRequestTypeRequestContext represents the expected format of an API Gateway custom authorizer response. -type APIGatewayCustomAuthorizerRequestTypeRequestContext struct { - Path string `json:"path"` - AccountID string `json:"accountId"` - ResourceID string `json:"resourceId"` - Stage string `json:"stage"` - RequestID string `json:"requestId"` - Identity APIGatewayCustomAuthorizerRequestTypeRequestIdentity `json:"identity"` - ResourcePath string `json:"resourcePath"` - HTTPMethod string `json:"httpMethod"` - APIID string `json:"apiId"` -} - -// APIGatewayCustomAuthorizerRequest contains data coming in to a custom API Gateway authorizer function. -type APIGatewayCustomAuthorizerRequest struct { - Type string `json:"type"` - AuthorizationToken string `json:"authorizationToken"` - MethodArn string `json:"methodArn"` -} - -// APIGatewayCustomAuthorizerRequestTypeRequest contains data coming in to a custom API Gateway authorizer function. -type APIGatewayCustomAuthorizerRequestTypeRequest struct { - Type string `json:"type"` - MethodArn string `json:"methodArn"` - Resource string `json:"resource"` - Path string `json:"path"` - HTTPMethod string `json:"httpMethod"` - Headers map[string]string `json:"headers"` - QueryStringParameters map[string]string `json:"queryStringParameters"` - PathParameters map[string]string `json:"pathParameters"` - StageVariables map[string]string `json:"stageVariables"` - RequestContext APIGatewayCustomAuthorizerRequestTypeRequestContext `json:"requestContext"` -} - -// APIGatewayCustomAuthorizerResponse represents the expected format of an API Gateway authorization response. -type APIGatewayCustomAuthorizerResponse struct { - PrincipalID string `json:"principalId"` - PolicyDocument APIGatewayCustomAuthorizerPolicy `json:"policyDocument"` - Context map[string]interface{} `json:"context,omitempty"` - UsageIdentifierKey string `json:"usageIdentifierKey,omitempty"` -} - -// APIGatewayCustomAuthorizerPolicy represents an IAM policy -type APIGatewayCustomAuthorizerPolicy struct { - Version string - Statement []IAMPolicyStatement -} - -type IAMPolicyStatement struct { - Action []string - Effect string - Resource []string -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/apigw_test.go b/vendor/github.com/aws/aws-lambda-go/events/apigw_test.go deleted file mode 100644 index 99ba366a..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/apigw_test.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -import ( - "encoding/json" - "io/ioutil" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestApiGatewayRequestMarshaling(t *testing.T) { - - // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-request.json") - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - // de-serialize into Go object - var inputEvent APIGatewayProxyRequest - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // validate custom authorizer context - authContext := inputEvent.RequestContext.Authorizer - if authContext["principalId"] != "admin" || - authContext["clientId"] != 1.0 || - authContext["clientName"] != "Exata" { - t.Errorf("could not extract authorizer context: %v", authContext) - } - - // serialize to json - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestApiGatewayRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayProxyRequest{}) -} - -func TestApiGatewayResponseMarshaling(t *testing.T) { - - // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-response.json") - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - // de-serialize into Go object - var inputEvent APIGatewayProxyResponse - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // serialize to json - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestApiGatewayResponseMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayProxyResponse{}) -} - -func TestApiGatewayCustomAuthorizerRequestMarshaling(t *testing.T) { - - // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-custom-auth-request.json") - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - // de-serialize into Go object - var inputEvent APIGatewayCustomAuthorizerRequest - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // serialize to json - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestApiGatewayCustomAuthorizerRequestTypeRequestMarshaling(t *testing.T) { - - // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-custom-auth-request-type-request.json") - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - // de-serialize into Go object - var inputEvent APIGatewayCustomAuthorizerRequestTypeRequest - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // serialize to json - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestApiGatewayCustomAuthorizerRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayCustomAuthorizerRequest{}) -} - -func TestApiGatewayCustomAuthorizerRequestTypeRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayCustomAuthorizerRequestTypeRequest{}) -} - -func TestApiGatewayCustomAuthorizerResponseMarshaling(t *testing.T) { - - // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/apigw-custom-auth-response.json") - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - // de-serialize into Go object - var inputEvent APIGatewayCustomAuthorizerResponse - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // serialize to json - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestApiGatewayCustomAuthorizerResponseMalformedJson(t *testing.T) { - test.TestMalformedJson(t, APIGatewayCustomAuthorizerResponse{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/attributevalue.go b/vendor/github.com/aws/aws-lambda-go/events/attributevalue.go deleted file mode 100644 index 530f54db..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/attributevalue.go +++ /dev/null @@ -1,520 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "strconv" -) - -// DynamoDBAttributeValue provides convenient access for a value stored in DynamoDB. -// For more information, please see http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html -type DynamoDBAttributeValue struct { - value anyValue - dataType DynamoDBDataType -} - -// Binary provides access to an attribute of type Binary. -// Method panics if the attribute is not of type Binary. -func (av DynamoDBAttributeValue) Binary() []byte { - av.ensureType(DataTypeBinary) - return av.value.([]byte) -} - -// Boolean provides access to an attribute of type Boolean. -// Method panics if the attribute is not of type Boolean. -func (av DynamoDBAttributeValue) Boolean() bool { - av.ensureType(DataTypeBoolean) - return av.value.(bool) -} - -// BinarySet provides access to an attribute of type Binary Set. -// Method panics if the attribute is not of type BinarySet. -func (av DynamoDBAttributeValue) BinarySet() [][]byte { - av.ensureType(DataTypeBinarySet) - return av.value.([][]byte) -} - -// List provides access to an attribute of type List. Each element -// of the list is an DynamoDBAttributeValue itself. -// Method panics if the attribute is not of type List. -func (av DynamoDBAttributeValue) List() []DynamoDBAttributeValue { - av.ensureType(DataTypeList) - return av.value.([]DynamoDBAttributeValue) -} - -// Map provides access to an attribute of type Map. They Keys are strings -// and the values are DynamoDBAttributeValue instances. -// Method panics if the attribute is not of type Map. -func (av DynamoDBAttributeValue) Map() map[string]DynamoDBAttributeValue { - av.ensureType(DataTypeMap) - return av.value.(map[string]DynamoDBAttributeValue) -} - -// Number provides access to an attribute of type Number. -// DynamoDB sends the values as strings. For convenience please see also -// the methods Integer() and Float(). -// Method panics if the attribute is not of type Number. -func (av DynamoDBAttributeValue) Number() string { - av.ensureType(DataTypeNumber) - return av.value.(string) -} - -// Integer provides access to an attribute of type Number. -// DynamoDB sends the values as strings. For convenience this method -// provides conversion to int. If the value cannot be represented by -// a signed integer, err.Err = ErrRange and the returned value is the maximum magnitude integer -// of an int64 of the appropriate sign. -// Method panics if the attribute is not of type Number. -func (av DynamoDBAttributeValue) Integer() (int64, error) { - s, err := strconv.ParseFloat(av.Number(), 64) - return int64(s), err -} - -// Float provides access to an attribute of type Number. -// DynamoDB sends the values as strings. For convenience this method -// provides conversion to float64. -// The returned value is the nearest floating point number rounded using IEEE754 unbiased rounding. -// If the number is more than 1/2 ULP away from the largest floating point number of the given size, -// the value returned is ±Inf, err.Err = ErrRange. -// Method panics if the attribute is not of type Number. -func (av DynamoDBAttributeValue) Float() (float64, error) { - s, err := strconv.ParseFloat(av.Number(), 64) - return s, err -} - -// NumberSet provides access to an attribute of type Number Set. -// DynamoDB sends the numbers as strings. -// Method panics if the attribute is not of type Number. -func (av DynamoDBAttributeValue) NumberSet() []string { - av.ensureType(DataTypeNumberSet) - return av.value.([]string) -} - -// String provides access to an attribute of type String. -// Method panics if the attribute is not of type String. -func (av DynamoDBAttributeValue) String() string { - av.ensureType(DataTypeString) - return av.value.(string) -} - -// StringSet provides access to an attribute of type String Set. -// Method panics if the attribute is not of type String Set. -func (av DynamoDBAttributeValue) StringSet() []string { - av.ensureType(DataTypeStringSet) - return av.value.([]string) -} - -// IsNull returns true if the attribute is of type Null. -func (av DynamoDBAttributeValue) IsNull() bool { - return av.value == nil -} - -// DataType provides access to the DynamoDB type of the attribute -func (av DynamoDBAttributeValue) DataType() DynamoDBDataType { - return av.dataType -} - -// NewBinaryAttribute creates an DynamoDBAttributeValue containing a Binary -func NewBinaryAttribute(value []byte) DynamoDBAttributeValue { - var av DynamoDBAttributeValue - av.value = value - av.dataType = DataTypeBinary - return av -} - -// NewBooleanAttribute creates an DynamoDBAttributeValue containing a Boolean -func NewBooleanAttribute(value bool) DynamoDBAttributeValue { - var av DynamoDBAttributeValue - av.value = value - av.dataType = DataTypeBoolean - return av -} - -// NewBinarySetAttribute creates an DynamoDBAttributeValue containing a BinarySet -func NewBinarySetAttribute(value [][]byte) DynamoDBAttributeValue { - var av DynamoDBAttributeValue - av.value = value - av.dataType = DataTypeBinarySet - return av -} - -// NewListAttribute creates an DynamoDBAttributeValue containing a List -func NewListAttribute(value []DynamoDBAttributeValue) DynamoDBAttributeValue { - var av DynamoDBAttributeValue - av.value = value - av.dataType = DataTypeList - return av -} - -// NewMapAttribute creates an DynamoDBAttributeValue containing a Map -func NewMapAttribute(value map[string]DynamoDBAttributeValue) DynamoDBAttributeValue { - var av DynamoDBAttributeValue - av.value = value - av.dataType = DataTypeMap - return av -} - -// NewNumberAttribute creates an DynamoDBAttributeValue containing a Number -func NewNumberAttribute(value string) DynamoDBAttributeValue { - var av DynamoDBAttributeValue - av.value = value - av.dataType = DataTypeNumber - return av -} - -// NewNullAttribute creates an DynamoDBAttributeValue containing a Null -func NewNullAttribute() DynamoDBAttributeValue { - var av DynamoDBAttributeValue - av.dataType = DataTypeNull - return av -} - -// NewStringAttribute creates an DynamoDBAttributeValue containing a String -func NewStringAttribute(value string) DynamoDBAttributeValue { - var av DynamoDBAttributeValue - av.value = value - av.dataType = DataTypeString - return av -} - -// NewStringSetAttribute creates an DynamoDBAttributeValue containing a StringSet -func NewStringSetAttribute(value []string) DynamoDBAttributeValue { - var av DynamoDBAttributeValue - av.value = value - av.dataType = DataTypeStringSet - return av -} - -// DynamoDBDataType specifies the type supported natively by DynamoDB for an attribute -type DynamoDBDataType int - -const ( - DataTypeBinary DynamoDBDataType = iota - DataTypeBoolean - DataTypeBinarySet - DataTypeList - DataTypeMap - DataTypeNumber - DataTypeNumberSet - DataTypeNull - DataTypeString - DataTypeStringSet -) - -type anyValue interface{} - -// UnsupportedDynamoDBTypeError is the error returned when trying to unmarshal a DynamoDB Attribute type not recognized by this library -type UnsupportedDynamoDBTypeError struct { - Type string -} - -func (e UnsupportedDynamoDBTypeError) Error() string { - return fmt.Sprintf("unsupported DynamoDB attribute type, %v", e.Type) -} - -// IncompatibleDynamoDBTypeError is the error passed in a panic when calling an accessor for an incompatible type -type IncompatibleDynamoDBTypeError struct { - Requested DynamoDBDataType - Actual DynamoDBDataType -} - -func (e IncompatibleDynamoDBTypeError) Error() string { - return fmt.Sprintf("accessor called for incompatible type, requested type %v but actual type was %v", e.Requested, e.Actual) -} - -func (av *DynamoDBAttributeValue) ensureType(expectedType DynamoDBDataType) { - if av.dataType != expectedType { - panic(IncompatibleDynamoDBTypeError{Requested: expectedType, Actual: av.dataType}) - } -} - -// MarshalJSON implements custom marshaling to be used by the standard json/encoding package -func (av DynamoDBAttributeValue) MarshalJSON() ([]byte, error) { - - var buff bytes.Buffer - var err error - var b []byte - - switch av.dataType { - case DataTypeBinary: - buff.WriteString(`{ "B":`) - b, err = json.Marshal(av.value.([]byte)) - buff.Write(b) - - case DataTypeBoolean: - buff.WriteString(`{ "BOOL":`) - b, err = json.Marshal(av.value.(bool)) - buff.Write(b) - - case DataTypeBinarySet: - buff.WriteString(`{ "BS":`) - b, err = json.Marshal(av.value.([][]byte)) - buff.Write(b) - - case DataTypeList: - buff.WriteString(`{ "L":`) - b, err = json.Marshal(av.value.([]DynamoDBAttributeValue)) - buff.Write(b) - - case DataTypeMap: - buff.WriteString(`{ "M":`) - b, err = json.Marshal(av.value.(map[string]DynamoDBAttributeValue)) - buff.Write(b) - - case DataTypeNumber: - buff.WriteString(`{ "N":`) - b, err = json.Marshal(av.value.(string)) - buff.Write(b) - - case DataTypeNumberSet: - buff.WriteString(`{ "NS":`) - b, err = json.Marshal(av.value.([]string)) - buff.Write(b) - - case DataTypeNull: - buff.WriteString(`{ "NULL": true `) - - case DataTypeString: - buff.WriteString(`{ "S":`) - b, err = json.Marshal(av.value.(string)) - buff.Write(b) - - case DataTypeStringSet: - buff.WriteString(`{ "SS":`) - b, err = json.Marshal(av.value.([]string)) - buff.Write(b) - } - - buff.WriteString(`}`) - return buff.Bytes(), err -} - -func unmarshalNull(target *DynamoDBAttributeValue) error { - target.value = nil - target.dataType = DataTypeNull - return nil -} - -func unmarshalString(target *DynamoDBAttributeValue, value interface{}) error { - var ok bool - target.value, ok = value.(string) - target.dataType = DataTypeString - if !ok { - return errors.New("DynamoDBAttributeValue: S type should contain a string") - } - return nil -} - -func unmarshalBinary(target *DynamoDBAttributeValue, value interface{}) error { - stringValue, ok := value.(string) - if !ok { - return errors.New("DynamoDBAttributeValue: B type should contain a base64 string") - } - - binaryValue, err := base64.StdEncoding.DecodeString(stringValue) - if err != nil { - return err - } - - target.value = binaryValue - target.dataType = DataTypeBinary - return nil -} - -func unmarshalBoolean(target *DynamoDBAttributeValue, value interface{}) error { - booleanValue, ok := value.(bool) - if !ok { - return errors.New("DynamoDBAttributeValue: BOOL type should contain a boolean") - } - - target.value = booleanValue - target.dataType = DataTypeBoolean - return nil -} - -func unmarshalBinarySet(target *DynamoDBAttributeValue, value interface{}) error { - list, ok := value.([]interface{}) - if !ok { - return errors.New("DynamoDBAttributeValue: BS type should contain a list of base64 strings") - } - - binarySet := make([][]byte, len(list)) - - for index, element := range list { - var err error - elementString := element.(string) - binarySet[index], err = base64.StdEncoding.DecodeString(elementString) - if err != nil { - return err - } - } - - target.value = binarySet - target.dataType = DataTypeBinarySet - return nil -} - -func unmarshalList(target *DynamoDBAttributeValue, value interface{}) error { - list, ok := value.([]interface{}) - if !ok { - return errors.New("DynamoDBAttributeValue: L type should contain a list") - } - - DynamoDBAttributeValues := make([]DynamoDBAttributeValue, len(list)) - for index, element := range list { - - elementMap, ok := element.(map[string]interface{}) - if !ok { - return errors.New("DynamoDBAttributeValue: element of a list is not an DynamoDBAttributeValue") - } - - var elementDynamoDBAttributeValue DynamoDBAttributeValue - err := unmarshalDynamoDBAttributeValueMap(&elementDynamoDBAttributeValue, elementMap) - if err != nil { - return errors.New("DynamoDBAttributeValue: unmarshal of child DynamoDBAttributeValue failed") - } - DynamoDBAttributeValues[index] = elementDynamoDBAttributeValue - } - target.value = DynamoDBAttributeValues - target.dataType = DataTypeList - return nil -} - -func unmarshalMap(target *DynamoDBAttributeValue, value interface{}) error { - m, ok := value.(map[string]interface{}) - if !ok { - return errors.New("DynamoDBAttributeValue: M type should contain a map") - } - - DynamoDBAttributeValues := make(map[string]DynamoDBAttributeValue) - for k, v := range m { - - elementMap, ok := v.(map[string]interface{}) - if !ok { - return errors.New("DynamoDBAttributeValue: element of a map is not an DynamoDBAttributeValue") - } - - var elementDynamoDBAttributeValue DynamoDBAttributeValue - err := unmarshalDynamoDBAttributeValueMap(&elementDynamoDBAttributeValue, elementMap) - if err != nil { - return errors.New("DynamoDBAttributeValue: unmarshal of child DynamoDBAttributeValue failed") - } - DynamoDBAttributeValues[k] = elementDynamoDBAttributeValue - } - target.value = DynamoDBAttributeValues - target.dataType = DataTypeMap - return nil -} - -func unmarshalNumber(target *DynamoDBAttributeValue, value interface{}) error { - var ok bool - target.value, ok = value.(string) - target.dataType = DataTypeNumber - if !ok { - return errors.New("DynamoDBAttributeValue: N type should contain a string") - } - return nil -} - -func unmarshalNumberSet(target *DynamoDBAttributeValue, value interface{}) error { - list, ok := value.([]interface{}) - if !ok { - return errors.New("DynamoDBAttributeValue: NS type should contain a list of strings") - } - - numberSet := make([]string, len(list)) - - for index, element := range list { - numberSet[index], ok = element.(string) - if !ok { - return errors.New("DynamoDBAttributeValue: NS type should contain a list of strings") - } - } - - target.value = numberSet - target.dataType = DataTypeNumberSet - return nil -} - -func unmarshalStringSet(target *DynamoDBAttributeValue, value interface{}) error { - list, ok := value.([]interface{}) - if !ok { - return errors.New("DynamoDBAttributeValue: SS type should contain a list of strings") - } - - stringSet := make([]string, len(list)) - - for index, element := range list { - stringSet[index], ok = element.(string) - if !ok { - return errors.New("DynamoDBAttributeValue: SS type should contain a list of strings") - } - } - - target.value = stringSet - target.dataType = DataTypeStringSet - return nil -} - -func unmarshalDynamoDBAttributeValue(target *DynamoDBAttributeValue, typeLabel string, jsonValue interface{}) error { - - switch typeLabel { - case "NULL": - return unmarshalNull(target) - case "B": - return unmarshalBinary(target, jsonValue) - case "BOOL": - return unmarshalBoolean(target, jsonValue) - case "BS": - return unmarshalBinarySet(target, jsonValue) - case "L": - return unmarshalList(target, jsonValue) - case "M": - return unmarshalMap(target, jsonValue) - case "N": - return unmarshalNumber(target, jsonValue) - case "NS": - return unmarshalNumberSet(target, jsonValue) - case "S": - return unmarshalString(target, jsonValue) - case "SS": - return unmarshalStringSet(target, jsonValue) - default: - target.value = nil - target.dataType = DataTypeNull - return UnsupportedDynamoDBTypeError{typeLabel} - } -} - -// UnmarshalJSON unmarshals a JSON description of this DynamoDBAttributeValue -func (av *DynamoDBAttributeValue) UnmarshalJSON(b []byte) error { - var m map[string]interface{} - - err := json.Unmarshal(b, &m) - if err != nil { - return err - } - - return unmarshalDynamoDBAttributeValueMap(av, m) -} - -func unmarshalDynamoDBAttributeValueMap(target *DynamoDBAttributeValue, m map[string]interface{}) error { - if m == nil { - return errors.New("DynamoDBAttributeValue: does not contain a map") - } - - if len(m) != 1 { - return errors.New("DynamoDBAttributeValue: map must contain a single type") - } - - for k, v := range m { - return unmarshalDynamoDBAttributeValue(target, k, v) - } - - return nil -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/attributevalue_test.go b/vendor/github.com/aws/aws-lambda-go/events/attributevalue_test.go deleted file mode 100644 index 7b298c25..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/attributevalue_test.go +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -import ( - "encoding/base64" - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestUnmarshalBinary(t *testing.T) { - input := []byte(`{ "B": "AAEqQQ=="}`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeBinary, av.DataType()) - assert.Equal(t, "AAEqQQ==", base64.StdEncoding.EncodeToString(av.Binary())) -} - -func TestUnmarshalBoolean(t *testing.T) { - input := []byte(`{ "BOOL": true}`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeBoolean, av.DataType()) - assert.Equal(t, true, av.Boolean()) -} - -func TestUnmarshalBinarySet(t *testing.T) { - input := []byte(`{ "BS": ["AAEqQQ==", "AAEqQQ=="] }`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeBinarySet, av.DataType()) - assert.Equal(t, 2, len(av.BinarySet())) - assert.Equal(t, "AAEqQQ==", base64.StdEncoding.EncodeToString(av.BinarySet()[1])) -} - -func TestUnmarshalList(t *testing.T) { - input := []byte(`{ "L": [ - { "S": "Cookies"}, - { "S": "Coffee"}, - { "N": "3.14159" } - ] }`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeList, av.DataType()) - assert.Equal(t, 3, len(av.List())) - assert.Equal(t, "Cookies", av.List()[0].String()) - assert.Equal(t, "3.14159", av.List()[2].Number()) -} - -func TestUnmarshalMap(t *testing.T) { - input := []byte(` - { "M": - { - "Name": { "S": "Joe" }, - "Age": { "N": "35" } - } - }`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeMap, av.DataType()) - assert.Equal(t, 2, len(av.Map())) - assert.Equal(t, "Joe", av.Map()["Name"].String()) - assert.Equal(t, "35", av.Map()["Age"].Number()) -} - -func TestUnmarshalNumber(t *testing.T) { - input := []byte(`{ "N": "123.45"}`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeNumber, av.DataType()) - assert.Equal(t, "123.45", av.Number()) -} - -func TestUnmarshalInteger(t *testing.T) { - input := []byte(`{ "N": "123"}`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - - var i int64 - i, err = av.Integer() - assert.Nil(t, err) - assert.Equal(t, int64(123), i) -} - -func TestUnmarshalFloat(t *testing.T) { - input := []byte(`{ "N": "123.45"}`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - assert.Nil(t, err) - - var f float64 - f, err = av.Float() - - assert.Nil(t, err) - assert.Equal(t, 123.45, f) -} - -func TestUnmarshalIntContainingAFloatString(t *testing.T) { - input := []byte(`{ "N": "123.45"}`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - - var i int64 - i, err = av.Integer() - assert.Nil(t, err) - assert.Equal(t, int64(123), i) -} - -func TestUnmarshalNumberSet(t *testing.T) { - input := []byte(`{ "NS": ["1234", "567.8"] }`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeNumberSet, av.DataType()) - assert.Equal(t, 2, len(av.NumberSet())) - assert.Equal(t, "1234", av.NumberSet()[0]) - assert.Equal(t, "567.8", av.NumberSet()[1]) -} - -func TestUnmarshalNull(t *testing.T) { - input := []byte(`{ "NULL": true}`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeNull, av.DataType()) - assert.True(t, av.IsNull()) -} - -func TestUnmarshalString(t *testing.T) { - input := []byte(`{ "S": "Hello"}`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeString, av.DataType()) - assert.Equal(t, "Hello", av.String()) -} - -func TestUnmarshalStringSet(t *testing.T) { - input := []byte(`{ "SS": [ "Giraffe", "Zebra" ] }`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, 2, len(av.StringSet())) - assert.Equal(t, DataTypeStringSet, av.DataType()) - assert.Equal(t, "Giraffe", av.StringSet()[0]) - assert.Equal(t, "Zebra", av.StringSet()[1]) -} - -func TestUnmarshalEmptyStringSet(t *testing.T) { - input := []byte(`{ "SS": [ ] }`) - - var av DynamoDBAttributeValue - err := json.Unmarshal(input, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeStringSet, av.DataType()) - assert.Equal(t, 0, len(av.StringSet())) -} - -func TestAccessWithWrongTypePanics(t *testing.T) { - testCases := []struct { - input string - accessor func(av DynamoDBAttributeValue) - expectedError IncompatibleDynamoDBTypeError - }{ - {`{ "B": "AAEqQQ=="}`, func(av DynamoDBAttributeValue) { av.Number() }, IncompatibleDynamoDBTypeError{Requested: DataTypeNumber, Actual: DataTypeBinary}}, - {`{ "BOOL": true}`, func(av DynamoDBAttributeValue) { av.Number() }, IncompatibleDynamoDBTypeError{Requested: DataTypeNumber, Actual: DataTypeBoolean}}, - {`{ "BS": ["AAEqQQ==", "AAEqQQ=="] }`, func(av DynamoDBAttributeValue) { av.Number() }, IncompatibleDynamoDBTypeError{Requested: DataTypeNumber, Actual: DataTypeBinarySet}}, - {`{ "L": [ { "S": "Cookies"} ] }`, func(av DynamoDBAttributeValue) { av.Number() }, IncompatibleDynamoDBTypeError{Requested: DataTypeNumber, Actual: DataTypeList}}, - {`{ "M": { "Name": { "S": "Joe" } } }`, func(av DynamoDBAttributeValue) { av.Number() }, IncompatibleDynamoDBTypeError{Requested: DataTypeNumber, Actual: DataTypeMap}}, - {`{ "N": "123.45"}`, func(av DynamoDBAttributeValue) { av.Boolean() }, IncompatibleDynamoDBTypeError{Requested: DataTypeBoolean, Actual: DataTypeNumber}}, - {`{ "NS": ["1234", "567.8"] }`, func(av DynamoDBAttributeValue) { av.Boolean() }, IncompatibleDynamoDBTypeError{Requested: DataTypeBoolean, Actual: DataTypeNumberSet}}, - {`{ "NULL": true}`, func(av DynamoDBAttributeValue) { av.Number() }, IncompatibleDynamoDBTypeError{Requested: DataTypeNumber, Actual: DataTypeNull}}, - {`{ "S": "Hello"}`, func(av DynamoDBAttributeValue) { av.Number() }, IncompatibleDynamoDBTypeError{Requested: DataTypeNumber, Actual: DataTypeString}}, - {`{ "SS": [ "Giraffe", "Zebra" ] }`, func(av DynamoDBAttributeValue) { av.Number() }, IncompatibleDynamoDBTypeError{Requested: DataTypeNumber, Actual: DataTypeStringSet}}, - } - - for _, testCase := range testCases { - var av DynamoDBAttributeValue - err := json.Unmarshal([]byte(testCase.input), &av) - assert.Nil(t, err) - // may use PanicsWithValue(expectedError) when it is available - assertPanicsWithValue(t, testCase.expectedError, func() { testCase.accessor(av) }) - } -} - -func assertPanicsWithValue(t *testing.T, expected error, action func()) { - defer func() { - r := recover() - if r == nil { - t.Errorf("Should have panicked") - } - if r != expected { - t.Errorf("should have panicked with value %v but panicked with value %v", expected, r) - } - }() - - action() -} - -func TestMarshalAndUnmarshalString(t *testing.T) { - const inputString = "INPUT STRING" - inputValue := NewStringAttribute(inputString) - marshaled, err := json.Marshal(inputValue) - assert.Nil(t, err) - - var av DynamoDBAttributeValue - err = json.Unmarshal(marshaled, &av) - - assert.Nil(t, err) - assert.Equal(t, DataTypeString, av.DataType()) - assert.Equal(t, inputString, av.String()) -} - -func Test_DynamoDBAttributeValue_NewAttribute(t *testing.T) { - { - av := NewBinaryAttribute([]byte{1, 2, 3}) - assert.Equal(t, DataTypeBinary, av.DataType()) - assert.Equal(t, []byte{1, 2, 3}, av.Binary()) - } - { - av := NewBooleanAttribute(true) - assert.Equal(t, DataTypeBoolean, av.DataType()) - assert.Equal(t, true, av.Boolean()) - } - { - av := NewBinarySetAttribute([][]byte{[]byte{1, 2, 3}}) - assert.Equal(t, DataTypeBinarySet, av.DataType()) - assert.Equal(t, [][]byte{[]byte{1, 2, 3}}, av.BinarySet()) - } - { - av := NewListAttribute([]DynamoDBAttributeValue{ - NewNumberAttribute("1"), - NewStringAttribute("test"), - }) - assert.Equal(t, DataTypeList, av.DataType()) - assert.Equal(t, 2, len(av.List())) - } - { - value := map[string]DynamoDBAttributeValue{ - "n": NewNumberAttribute("1"), - "s": NewStringAttribute("test"), - } - av := NewMapAttribute(value) - assert.Equal(t, DataTypeMap, av.DataType()) - assert.Equal(t, 2, len(av.Map())) - } - { - av := NewNumberAttribute("1") - assert.Equal(t, DataTypeNumber, av.DataType()) - assert.Equal(t, "1", av.Number()) - v, err := av.Integer() - assert.Nil(t, err) - assert.Equal(t, int64(1), v) - } - { - av := NewNumberAttribute("1.1") - assert.Equal(t, DataTypeNumber, av.DataType()) - assert.Equal(t, "1.1", av.Number()) - v, err := av.Float() - assert.Nil(t, err) - assert.Equal(t, float64(1.1), v) - } - { - av := NewNullAttribute() - assert.Equal(t, DataTypeNull, av.DataType()) - assert.Equal(t, true, av.IsNull()) - } - { - av := NewStringAttribute("test") - assert.Equal(t, DataTypeString, av.DataType()) - assert.Equal(t, "test", av.String()) - } - { - av := NewStringSetAttribute([]string{"test", "test"}) - assert.Equal(t, DataTypeStringSet, av.DataType()) - assert.Equal(t, []string{"test", "test"}, av.StringSet()) - } -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/autoscaling.go b/vendor/github.com/aws/aws-lambda-go/events/autoscaling.go deleted file mode 100644 index a50d9cc1..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/autoscaling.go +++ /dev/null @@ -1,18 +0,0 @@ -package events - -import ( - "time" -) - -// AutoScalingEvent struct is used to parse the json for auto scaling event types // -type AutoScalingEvent struct { - Version string `json:"version"` // The version of event data - ID string `json:"id"` // The unique ID of the event - DetailType string `json:"detail-type"` //Details about event type - Source string `json:"source"` //Source of the event - AccountID string `json:"account"` //AccountId - Time time.Time `json:"time"` //Event timestamp - Region string `json:"region"` //Region of event - Resources []string `json:"resources"` //Information about resources impacted by event - Detail map[string]interface{} `json:"detail"` -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/autoscaling_test.go b/vendor/github.com/aws/aws-lambda-go/events/autoscaling_test.go deleted file mode 100644 index 5ac82123..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/autoscaling_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package events - -import ( - "encoding/json" - "github.com/aws/aws-lambda-go/events/test" - "testing" -) - -func TestAutoScalingEventMarshaling(t *testing.T) { - - var sampleFileList = []string{"autoscaling-event-launch-successful.json", "autoscaling-event-launch-unsuccessful.json", "autoscaling-event-lifecycle-action.json", - "autoscaling-event-terminate-action.json", "autoscaling-event-terminate-successful.json", "autoscaling-event-terminate-unsuccessful.json"} - - // Loop over list and test each file individually // - for _, sampleFile := range sampleFileList { - - t.Logf("Running test for %s\n", sampleFile) - // 1. read JSON from file - inputJson := readJsonFromFile(t, "./testdata/"+sampleFile) - - // 2. de-serialize into Go object - var inputEvent AutoScalingEvent - if err := json.Unmarshal(inputJson, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - // 3. serialize to JSON - outputJson, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - // 4. check result - test.AssertJsonsEqual(t, inputJson, outputJson) - } - -} - -func TestAutoScalingMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, AutoScalingEvent{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_events.go b/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_events.go deleted file mode 100644 index e3201fdb..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_events.go +++ /dev/null @@ -1,20 +0,0 @@ -package events - -import ( - "encoding/json" - "time" -) - -// CloudWatchEvent is the outer structure of an event sent via CloudWatch Events. -// For examples of events that come via CloudWatch Events, see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html -type CloudWatchEvent struct { - Version string `json:"version"` - ID string `json:"id"` - DetailType string `json:"detail-type"` - Source string `json:"source"` - AccountID string `json:"account"` - Time time.Time `json:"time"` - Region string `json:"region"` - Resources []string `json:"resources"` - Detail json.RawMessage `json:"detail"` -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_events_test.go b/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_events_test.go deleted file mode 100644 index 8fb02340..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_events_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package events - -import ( - "encoding/json" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestCloudwatchScheduledEventIdempotency(t *testing.T) { - inputJSON := []byte( - "{\"version\":\"0\",\"id\":\"890abcde-f123-4567-890a-bcdef1234567\"," + - "\"detail-type\":\"Scheduled Event\",\"source\":\"aws.events\"," + - "\"account\":\"123456789012\",\"time\":\"2016-12-30T18:44:49Z\"," + - "\"region\":\"us-east-1\"," + - "\"resources\":[\"arn:aws:events:us-east-1:123456789012:rule/SampleRule\"]," + - "\"detail\":{}}") - - var inputEvent CloudWatchEvent - err := json.Unmarshal(inputJSON, &inputEvent) - if err != nil { - t.Errorf("Could not unmarshal scheduled event: %v", err) - } - - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("Could not marshal scheduled event: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestCloudwatchScheduledEventRequestMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CloudWatchEvent{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_logs.go b/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_logs.go deleted file mode 100644 index 447cbd5f..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_logs.go +++ /dev/null @@ -1,55 +0,0 @@ -package events - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "encoding/json" -) - -// CloudwatchLogsEvent represents raw data from a cloudwatch logs event -type CloudwatchLogsEvent struct { - AWSLogs CloudwatchLogsRawData `json:"awslogs"` -} - -// CloudwatchLogsRawData contains gzipped base64 json representing the bulk -// of a cloudwatch logs event -type CloudwatchLogsRawData struct { - Data string `json:"data"` -} - -// Parse returns a struct representing a usable CloudwatchLogs event -func (c CloudwatchLogsRawData) Parse() (d CloudwatchLogsData, err error) { - data, err := base64.StdEncoding.DecodeString(c.Data) - if err != nil { - return - } - - zr, err := gzip.NewReader(bytes.NewBuffer(data)) - if err != nil { - return - } - - buf := &bytes.Buffer{} - buf.ReadFrom(zr) - - err = json.Unmarshal(buf.Bytes(), &d) - return -} - -// CloudwatchLogsData is an unmarshal'd, ungzip'd, cloudwatch logs event -type CloudwatchLogsData struct { - Owner string `json:"owner"` - LogGroup string `json:"logGroup"` - LogStream string `json:"logStream"` - SubscriptionFilters []string `json:"subscriptionFilters"` - MessageType string `json:"messageType"` - LogEvents []CloudwatchLogsLogEvent `json:"logEvents"` -} - -// LogEvent represents a log entry from cloudwatch logs -type CloudwatchLogsLogEvent struct { - ID string `json:"id"` - Timestamp int64 `json:"timestamp"` - Message string `json:"message"` -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_logs_test.go b/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_logs_test.go deleted file mode 100644 index 961c779a..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/cloudwatch_logs_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package events - -import ( - "encoding/json" - "reflect" - "testing" -) - -func TestCloudwatchLogs(t *testing.T) { - for _, test := range []struct { - name string - eventJson string - expectError bool - expectCloudwatchEventData CloudwatchLogsEvent - }{ - {"Well formed cloudwatch event", - "./testdata/cloudwatch-logs-event.json", - false, - CloudwatchLogsEvent{ - AWSLogs: CloudwatchLogsRawData{ - Data: "H4sIAAAAAAAAAHWPwQqCQBCGX0Xm7EFtK+smZBEUgXoLCdMhFtKV3akI8d0bLYmibvPPN3wz00CJxmQnTO41whwWQRIctmEcB6sQbFC3CjW3XW8kxpOpP+OC22d1Wml1qZkQGtoMsScxaczKN3plG8zlaHIta5KqWsozoTYw3/djzwhpLwivWFGHGpAFe7DL68JlBUk+l7KSN7tCOEJ4M3/qOI49vMHj+zCKdlFqLaU2ZHV2a4Ct/an0/ivdX8oYc1UVX860fQDQiMdxRQEAAA==", - }, - }, - }, - } { - t.Run(test.name, func(t *testing.T) { - inputJson := readJsonFromFile(t, test.eventJson) - - var inputEvent CloudwatchLogsEvent - err := json.Unmarshal(inputJson, &inputEvent) - - if err != nil && !test.expectError { - t.Errorf("could not unmarshal event. details: %v", err) - } - - if err == nil && test.expectError { - t.Errorf("expected parse error") - } - - if !reflect.DeepEqual(test.expectCloudwatchEventData, inputEvent) { - t.Errorf("expected: %+v, received: %v", test.expectCloudwatchEventData, inputEvent) - } - }) - } -} - -func TestCloudwatchLogsParse(t *testing.T) { - for _, test := range []struct { - name string - eventJson string - expectError bool - expectCloudwatchLogsData CloudwatchLogsData - }{ - {"Well formed cloudwatch event", - "./testdata/cloudwatch-logs-event.json", - false, - CloudwatchLogsData{ - Owner: "123456789123", - LogGroup: "testLogGroup", - LogStream: "testLogStream", - SubscriptionFilters: []string{ - "testFilter", - }, - MessageType: "DATA_MESSAGE", - LogEvents: []CloudwatchLogsLogEvent{ - {ID: "eventId1", Timestamp: 1440442987000, Message: "[ERROR] First test message"}, - {ID: "eventId2", Timestamp: 1440442987001, Message: "[ERROR], Second test message"}, - }, - }, - }, - } { - t.Run(test.name, func(t *testing.T) { - inputJson := readJsonFromFile(t, test.eventJson) - - var inputEvent CloudwatchLogsEvent - if err := json.Unmarshal(inputJson, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - d, err := inputEvent.AWSLogs.Parse() - if err != nil { - if !test.expectError { - t.Errorf("unexpected error: %+v", err) - } - - if !reflect.DeepEqual(test.expectCloudwatchLogsData, d) { - t.Errorf("expected: %+v, received: %v", test.expectCloudwatchLogsData, d) - } - } - - if err == nil && test.expectError { - t.Errorf("expected error") - } - }) - } -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/code_commit.go b/vendor/github.com/aws/aws-lambda-go/events/code_commit.go deleted file mode 100644 index 47eefa66..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/code_commit.go +++ /dev/null @@ -1,100 +0,0 @@ -package events - -import ( - "errors" - "fmt" - "time" -) - -// CodeCommitEvent represents a CodeCommit event -type CodeCommitEvent struct { - Records []CodeCommitRecord `json:"Records"` -} - -// String returns a string representation of this object. -// Useful for testing and debugging. -func (e CodeCommitEvent) String() string { - return fmt.Sprintf("{Records: %v}", e.Records) -} - -type CodeCommitEventTime time.Time - -// https://golang.org/pkg/time/#Parse -const codeCommitEventTimeReference = "\"2006-01-2T15:04:05.000-0700\"" - -func (t *CodeCommitEventTime) MarshalJSON() ([]byte, error) { - if t == nil { - return nil, errors.New("CodeCommitEventTime cannot be nil") - } - - gt := time.Time(*t) - return []byte(gt.Format(codeCommitEventTimeReference)), nil -} - -func (t *CodeCommitEventTime) UnmarshalJSON(data []byte) error { - if t == nil { - return errors.New("CodeCommitEventTime cannot be nil") - } - - pt, err := time.Parse(codeCommitEventTimeReference, string(data)) - if err == nil { - *t = CodeCommitEventTime(pt) - } - return err -} - -// represents a CodeCommit record -type CodeCommitRecord struct { - EventID string `json:"eventId"` - EventVersion string `json:"eventVersion"` - EventTime CodeCommitEventTime `json:"eventTime"` - EventTriggerName string `json:"eventTriggerName"` - EventPartNumber uint64 `json:"eventPartNumber"` - CodeCommit CodeCommitCodeCommit `json:"codecommit"` - EventName string `json:"eventName"` - EventTriggerConfigId string `json:"eventTriggerConfigId"` - EventSourceARN string `json:"eventSourceARN"` - UserIdentityARN string `json:"userIdentityARN"` - EventSource string `json:"eventSource"` - AWSRegion string `json:"awsRegion"` - EventTotalParts uint64 `json:"eventTotalParts"` -} - -// String returns a string representation of this object. -// Useful for testing and debugging. -func (r CodeCommitRecord) String() string { - return fmt.Sprintf( - "{eventId: %v, eventVersion: %v, eventTime: %v, eventTriggerName: %v, "+ - "eventPartNumber: %v, codeCommit: %v, eventName: %v, "+ - "eventTriggerConfigId: %v, eventSourceARN: %v, userIdentityARN: %v, "+ - "eventSource: %v, awsRegion: %v, eventTotalParts: %v}", - r.EventID, r.EventVersion, r.EventTime, r.EventTriggerName, - r.EventPartNumber, r.CodeCommit, r.EventName, - r.EventTriggerConfigId, r.EventSourceARN, r.UserIdentityARN, - r.EventSource, r.AWSRegion, r.EventTotalParts) -} - -// CodeCommitCodeCommit represents a CodeCommit object in a record -type CodeCommitCodeCommit struct { - References []CodeCommitReference `json:"references"` -} - -// String returns a string representation of this object. -// Useful for testing and debugging. -func (c CodeCommitCodeCommit) String() string { - return fmt.Sprintf("{references: %v}", c.References) -} - -// CodeCommitReference represents a Reference object in a CodeCommit object -type CodeCommitReference struct { - Commit string `json:"commit"` - Ref string `json:"ref"` - Created bool `json:"created,omitempty"` -} - -// String returns a string representation of this object. -// Useful for testing and debugging. -func (r CodeCommitReference) String() string { - return fmt.Sprintf( - "{commit: %v, ref: %v, created: %v}", r.Commit, r.Ref, r.Created) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/code_commit_test.go b/vendor/github.com/aws/aws-lambda-go/events/code_commit_test.go deleted file mode 100644 index eedfa068..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/code_commit_test.go +++ /dev/null @@ -1,134 +0,0 @@ -package events - -import ( - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestCodeCommitReference(t *testing.T) { - cases := []struct { - Name string - Input []byte - }{ - { - Name: "CodeCommitReference", - Input: []byte(` - { - "commit": "5c4ef1049f1d27deadbeeff313e0730018be182b", - "ref": "refs/heads/master" - } - `), - }, - { - Name: "Created CodeCommitReference", - Input: []byte(` - { - "commit": "5c4ef1049f1d27deadbeeff313e0730018be182b", - "ref": "refs/heads/master", - "created": true - } - `), - }, - } - - for _, c := range cases { - t.Run(c.Name, func(t *testing.T) { - test.AssertJsonBytes(t, c.Input, &CodeCommitReference{}) - }) - } -} - -func TestCodeCommitCodeCommit(t *testing.T) { - cases := []struct { - Name string - Input []byte - }{ - { - Name: "Empty CodeCommitReferences", - Input: []byte(`{"references": []}`), - }, - { - Name: "CodeCommitCodeCommit", - Input: []byte(` - { - "references": [ - { - "commit": "5c4ef1049f1d27deadbeeff313e0730018be182b", - "ref": "refs/heads/master" - }, - { - "commit": "5c4ef1049f1d27deadbeeff313e0730018be182b", - "ref": "refs/heads/master", - "created": true - } - ] - } - `), - }, - } - - for _, c := range cases { - t.Run(c.Name, func(t *testing.T) { - test.AssertJsonBytes(t, c.Input, &CodeCommitCodeCommit{}) - }) - } -} - -func TestCodeCommitRecord(t *testing.T) { - cases := []struct { - Name string - Input []byte - }{ - { - Name: "CodeCommitRecord", - Input: []byte(` - { - "eventId": "5a824061-17ca-46a9-bbf9-114edeadbeef", - "eventVersion": "1.0", - "eventTime": "2018-01-22T15:58:33.475+0000", - "eventTriggerName": "my-trigger", - "eventPartNumber": 1, - "codecommit": { - "references": [] - }, - "eventName": "TriggerEventTest", - "eventTriggerConfigId": "5a824061-17ca-46a9-bbf9-114edeadbeef", - "eventSourceARN": "arn:aws:codecommit:us-east-1:123456789012:my-repo", - "userIdentityARN": "arn:aws:iam::123456789012:root", - "eventSource": "aws:codecommit", - "awsRegion": "us-east-1", - "eventTotalParts": 1 - } - `), - }, - } - - for _, c := range cases { - t.Run(c.Name, func(t *testing.T) { - test.AssertJsonBytes(t, c.Input, &CodeCommitRecord{}) - }) - } -} - -func TestCodeCommitEventFile(t *testing.T) { - test.AssertJsonFile(t, "./testdata/code-commit-event.json", &CodeCommitEvent{}) -} - -func TestCodeCommitEvent(t *testing.T) { - cases := []struct { - Name string - Input []byte - }{ - { - Name: "Empty CodeCommitRecord", - Input: []byte(`{"Records": []}`), - }, - } - - for _, c := range cases { - t.Run(c.Name, func(t *testing.T) { - test.AssertJsonBytes(t, c.Input, &CodeCommitEvent{}) - }) - } -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/codepipeline_job.go b/vendor/github.com/aws/aws-lambda-go/events/codepipeline_job.go deleted file mode 100644 index 68f96344..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/codepipeline_job.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -// CodePipelineEvent contains data from an event sent from AWS Codepipeline -type CodePipelineEvent struct { - CodePipelineJob CodePipelineJob `json:"CodePipeline.job"` -} - -// CodePipelineJob represents a job from an AWS CodePipeline event -type CodePipelineJob struct { - ID string `json:"id"` - AccountID string `json:"accountId"` - Data CodePipelineData `json:"data"` -} - -// CodePipelineData represents a job from an AWS CodePipeline event -type CodePipelineData struct { - ActionConfiguration CodePipelineActionConfiguration `json:"actionConfiguration"` - InputArtifacts []CodePipelineInputArtifact `json:"inputArtifacts"` - OutPutArtifacts []CodePipelineOutputArtifact `json:"outputArtifacts"` - ArtifactCredentials CodePipelineArtifactCredentials `json:"artifactCredentials"` - ContinuationToken string `json:"continuationToken"` -} - -// CodePipelineActionConfiguration represents an Action Configuration -type CodePipelineActionConfiguration struct { - Configuration CodePipelineConfiguration `json:"configuration"` -} - -// CodePipelineConfiguration represents a configuration for an Action Configuration -type CodePipelineConfiguration struct { - FunctionName string `json:"FunctionName"` - UserParameters string `json:"UserParameters"` -} - -// CodePipelineInputArtifact represents an input artifact -type CodePipelineInputArtifact struct { - Location CodePipelineInputLocation `json:"location"` - Revision *string `json:"revision"` - Name string `json:"name"` -} - -// CodePipelineInputLocation represents a input location -type CodePipelineInputLocation struct { - S3Location CodePipelineS3Location `json:"s3Location"` - LocationType string `json:"type"` -} - -// CodePipelineS3Location represents an s3 input location -type CodePipelineS3Location struct { - BucketName string `json:"bucketName"` - ObjectKey string `json:"objectKey"` -} - -// CodePipelineOutputArtifact represents an output artifact -type CodePipelineOutputArtifact struct { - Location CodePipelineInputLocation `json:"location"` - Revision *string `json:"revision"` - Name string `json:"name"` -} - -// CodePipelineOutputLocation represents a output location -type CodePipelineOutputLocation struct { - S3Location CodePipelineS3Location `json:"s3Location"` - LocationType string `json:"type"` -} - -// CodePipelineArtifactCredentials represents CodePipeline artifact credentials -type CodePipelineArtifactCredentials struct { - SecretAccessKey string `json:"secretAccessKey"` - SessionToken string `json:"sessionToken"` - AccessKeyID string `json:"accessKeyId"` -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/codepipeline_test.go b/vendor/github.com/aws/aws-lambda-go/events/codepipeline_test.go deleted file mode 100644 index e1c1e17c..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/codepipeline_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. -package events - -import ( - "encoding/json" - "io/ioutil" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestCodePipeLineEventMarshaling(t *testing.T) { - - // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/codepipline-event.json") - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - // de-serialize into CognitoEvent - var inputEvent CodePipelineEvent - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // serialize to json - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestCodePipelineEventMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CodePipelineEvent{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/cognito.go b/vendor/github.com/aws/aws-lambda-go/events/cognito.go deleted file mode 100644 index 81903482..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/cognito.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -// CognitoEvent contains data from an event sent from AWS Cognito Sync -type CognitoEvent struct { - DatasetName string `json:"datasetName"` - DatasetRecords map[string]CognitoDatasetRecord `json:"datasetRecords"` - EventType string `json:"eventType"` - IdentityID string `json:"identityId"` - IdentityPoolID string `json:"identityPoolId"` - Region string `json:"region"` - Version int `json:"version"` -} - -// CognitoDatasetRecord represents a record from an AWS Cognito Sync event -type CognitoDatasetRecord struct { - NewValue string `json:"newValue"` - OldValue string `json:"oldValue"` - Op string `json:"op"` -} - -// CognitoEventUserPoolsPreSignup is sent by AWS Cognito User Pools when a user attempts to register -// (sign up), allowing a Lambda to perform custom validation to accept or deny the registration request -type CognitoEventUserPoolsPreSignup struct { - CognitoEventUserPoolsHeader - Request CognitoEventUserPoolsPreSignupRequest `json:"request"` - Response CognitoEventUserPoolsPreSignupResponse `json:"response"` -} - -// CognitoEventUserPoolsPostConfirmation is sent by AWS Cognito User Pools after a user is confirmed, -// allowing the Lambda to send custom messages or add custom logic. -type CognitoEventUserPoolsPostConfirmation struct { - CognitoEventUserPoolsHeader - Request CognitoEventUserPoolsPostConfirmationRequest `json:"request"` - Response CognitoEventUserPoolsPostConfirmationResponse `json:"response"` -} - -// CognitoEventUserPoolsCallerContext contains information about the caller -type CognitoEventUserPoolsCallerContext struct { - AWSSDKVersion string `json:"awsSdkVersion"` - ClientID string `json:"clientId"` -} - -// CognitoEventUserPoolsHeader contains common data from events sent by AWS Cognito User Pools -type CognitoEventUserPoolsHeader struct { - Version string `json:"version"` - TriggerSource string `json:"triggerSource"` - Region string `json:"region"` - UserPoolID string `json:"userPoolId"` - CallerContext CognitoEventUserPoolsCallerContext `json:"callerContext"` - UserName string `json:"userName"` -} - -// CognitoEventUserPoolsPreSignupRequest contains the request portion of a PreSignup event -type CognitoEventUserPoolsPreSignupRequest struct { - UserAttributes map[string]string `json:"userAttributes"` - ValidationData map[string]string `json:"validationData"` -} - -// CognitoEventUserPoolsPreSignupResponse contains the response portion of a PreSignup event -type CognitoEventUserPoolsPreSignupResponse struct { - AutoConfirmUser bool `json:"autoConfirmUser"` - AutoVerifyEmail bool `json:"autoVerifyEmail"` - AutoVerifyPhone bool `json:"autoVerifyPhone"` -} - -// CognitoEventUserPoolsPostConfirmationRequest contains the request portion of a PostConfirmation event -type CognitoEventUserPoolsPostConfirmationRequest struct { - UserAttributes map[string]string `json:"userAttributes"` -} - -// CognitoEventUserPoolsPostConfirmationResponse contains the response portion of a PostConfirmation event -type CognitoEventUserPoolsPostConfirmationResponse struct { -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/cognito_test.go b/vendor/github.com/aws/aws-lambda-go/events/cognito_test.go deleted file mode 100644 index 9ef77831..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/cognito_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. -package events - -import ( - "encoding/json" - "io/ioutil" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestCognitoEventMarshaling(t *testing.T) { - - // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event.json") - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - // de-serialize into CognitoEvent - var inputEvent CognitoEvent - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // serialize to json - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestCognitoMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEvent{}) -} - -func TestCognitoEventUserPoolsPreSignupMarshaling(t *testing.T) { - - // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-presignup.json") - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - // de-serialize into CognitoEvent - var inputEvent CognitoEventUserPoolsPreSignup - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // serialize to json - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestCognitoUserPoolsPreSignupMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, CognitoEventUserPoolsPreSignup{}) -} - -func TestCognitoEventUserPoolsPostConfirmationMarshaling(t *testing.T) { - - // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/cognito-event-userpools-postconfirmation.json") - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - // de-serialize into CognitoEvent - var inputEvent CognitoEventUserPoolsPostConfirmation - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // serialize to json - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/config.go b/vendor/github.com/aws/aws-lambda-go/events/config.go deleted file mode 100644 index 951809c7..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/config.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -// ConfigEvent contains data from an event sent from AWS Config -type ConfigEvent struct { - AccountID string `json:"accountId"` // The ID of the AWS account that owns the rule - ConfigRuleArn string `json:"configRuleArn"` // The ARN that AWS Config assigned to the rule - ConfigRuleID string `json:"configRuleId"` - ConfigRuleName string `json:"configRuleName"` // The name that you assigned to the rule that caused AWS Config to publish the event - EventLeftScope bool `json:"eventLeftScope"` // A boolean value that indicates whether the AWS resource to be evaluated has been removed from the rule's scope - ExecutionRoleArn string `json:"executionRoleArn"` - InvokingEvent string `json:"invokingEvent"` // If the event is published in response to a resource configuration change, this value contains a JSON configuration item - ResultToken string `json:"resultToken"` // A token that the function must pass to AWS Config with the PutEvaluations call - RuleParameters string `json:"ruleParameters"` // Key/value pairs that the function processes as part of its evaluation logic - Version string `json:"version"` -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/config_test.go b/vendor/github.com/aws/aws-lambda-go/events/config_test.go deleted file mode 100644 index 721ab262..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/config_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. -package events - -import ( - "encoding/json" - "io/ioutil" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestConfigEventMarshaling(t *testing.T) { - // read json from file - inputJSON, err := ioutil.ReadFile("./testdata/config-event.json") - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - // de-serialize into Go object - var inputEvent ConfigEvent - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // serialize to json - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestConfigMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, ConfigEvent{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/dynamodb.go b/vendor/github.com/aws/aws-lambda-go/events/dynamodb.go deleted file mode 100644 index 09fcd34c..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/dynamodb.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -// The DynamoDBEvent stream event handled to Lambda -// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-ddb-update -type DynamoDBEvent struct { - Records []DynamoDBEventRecord `json:"Records"` -} - -// DynamoDbEventRecord stores information about each record of a DynamoDb stream event -type DynamoDBEventRecord struct { - // The region in which the GetRecords request was received. - AWSRegion string `json:"awsRegion"` - - // The main body of the stream record, containing all of the DynamoDB-specific - // fields. - Change DynamoDBStreamRecord `json:"dynamodb"` - - // A globally unique identifier for the event that was recorded in this stream - // record. - EventID string `json:"eventID"` - - // The type of data modification that was performed on the DynamoDB table: - // - // * INSERT - a new item was added to the table. - // - // * MODIFY - one or more of an existing item's attributes were modified. - // - // * REMOVE - the item was deleted from the table - EventName string `json:"eventName"` - - // The AWS service from which the stream record originated. For DynamoDB Streams, - // this is aws:dynamodb. - EventSource string `json:"eventSource"` - - // The version number of the stream record format. This number is updated whenever - // the structure of Record is modified. - // - // Client applications must not assume that eventVersion will remain at a particular - // value, as this number is subject to change at any time. In general, eventVersion - // will only increase as the low-level DynamoDB Streams API evolves. - EventVersion string `json:"eventVersion"` - - // The event source ARN of DynamoDB - EventSourceArn string `json:"eventSourceARN"` - - // Items that are deleted by the Time to Live process after expiration have - // the following fields: - // - // * Records[].userIdentity.type - // - // "Service" - // - // * Records[].userIdentity.principalId - // - // "dynamodb.amazonaws.com" - UserIdentity *DynamoDBUserIdentity `json:"userIdentity,omitempty"` -} - -type DynamoDBUserIdentity struct { - Type string `json:"type"` - PrincipalID string `json:"principalId"` -} - -// A description of a single data modification that was performed on an item -// in a DynamoDB table. -type DynamoDBStreamRecord struct { - - // The approximate date and time when the stream record was created, in UNIX - // epoch time (http://www.epochconverter.com/) format. - ApproximateCreationDateTime SecondsEpochTime `json:"ApproximateCreationDateTime,omitempty"` - - // The primary key attribute(s) for the DynamoDB item that was modified. - Keys map[string]DynamoDBAttributeValue `json:"Keys,omitempty"` - - // The item in the DynamoDB table as it appeared after it was modified. - NewImage map[string]DynamoDBAttributeValue `json:"NewImage,omitempty"` - - // The item in the DynamoDB table as it appeared before it was modified. - OldImage map[string]DynamoDBAttributeValue `json:"OldImage,omitempty"` - - // The sequence number of the stream record. - SequenceNumber string `json:"SequenceNumber"` - - // The size of the stream record, in bytes. - SizeBytes int64 `json:"SizeBytes"` - - // The type of data from the modified DynamoDB item that was captured in this - // stream record. - StreamViewType string `json:"StreamViewType"` -} - -type DynamoDBKeyType string - -const ( - DynamoDBKeyTypeHash DynamoDBKeyType = "HASH" - DynamoDBKeyTypeRange DynamoDBKeyType = "RANGE" -) - -type DynamoDBOperationType string - -const ( - DynamoDBOperationTypeInsert DynamoDBOperationType = "INSERT" - DynamoDBOperationTypeModify DynamoDBOperationType = "MODIFY" - DynamoDBOperationTypeRemove DynamoDBOperationType = "REMOVE" -) - -type DynamoDBSharedIteratorType string - -const ( - DynamoDBShardIteratorTypeTrimHorizon DynamoDBSharedIteratorType = "TRIM_HORIZON" - DynamoDBShardIteratorTypeLatest DynamoDBSharedIteratorType = "LATEST" - DynamoDBShardIteratorTypeAtSequenceNumber DynamoDBSharedIteratorType = "AT_SEQUENCE_NUMBER" - DynamoDBShardIteratorTypeAfterSequenceNumber DynamoDBSharedIteratorType = "AFTER_SEQUENCE_NUMBER" -) - -type DynamoDBStreamStatus string - -const ( - DynamoDBStreamStatusEnabling DynamoDBStreamStatus = "ENABLING" - DynamoDBStreamStatusEnabled DynamoDBStreamStatus = "ENABLED" - DynamoDBStreamStatusDisabling DynamoDBStreamStatus = "DISABLING" - DynamoDBStreamStatusDisabled DynamoDBStreamStatus = "DISABLED" -) - -type DynamoDBStreamViewType string - -const ( - DynamoDBStreamViewTypeNewImage DynamoDBStreamViewType = "NEW_IMAGE" // the entire item, as it appeared after it was modified. - DynamoDBStreamViewTypeOldImage DynamoDBStreamViewType = "OLD_IMAGE" // the entire item, as it appeared before it was modified. - DynamoDBStreamViewTypeNewAndOldImages DynamoDBStreamViewType = "NEW_AND_OLD_IMAGES" // both the new and the old item images of the item. - DynamoDBStreamViewTypeKeysOnly DynamoDBStreamViewType = "KEYS_ONLY" // only the key attributes of the modified item. -) diff --git a/vendor/github.com/aws/aws-lambda-go/events/dynamodb_test.go b/vendor/github.com/aws/aws-lambda-go/events/dynamodb_test.go deleted file mode 100644 index 3840bb3b..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/dynamodb_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -import ( - "encoding/json" - "io/ioutil" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestDynamoDBEventMarshaling(t *testing.T) { - - // 1. read JSON from file - inputJson := readJsonFromFile(t, "./testdata/dynamodb-event.json") - - // 2. de-serialize into Go object - var inputEvent DynamoDBEvent - if err := json.Unmarshal(inputJson, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // 3. serialize to JSON - outputJson, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - // 4. check result - test.AssertJsonsEqual(t, inputJson, outputJson) -} - -func TestDynamoDBEventMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, DynamoDBEvent{}) -} - -func readJsonFromFile(t *testing.T, inputFile string) []byte { - inputJson, err := ioutil.ReadFile(inputFile) - if err != nil { - t.Errorf("could not open test file. details: %v", err) - } - - return inputJson -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/epoch_time.go b/vendor/github.com/aws/aws-lambda-go/events/epoch_time.go deleted file mode 100644 index b0e48a0e..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/epoch_time.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -import ( - "encoding/json" - "time" -) - -// SecondsEpochTime serializes a time.Time in JSON as a UNIX epoch time in seconds -type SecondsEpochTime struct { - time.Time -} - -// MilliSecondsEpochTime serializes a time.Time in JSON as a UNIX epoch time in milliseconds. -type MilliSecondsEpochTime struct { - time.Time -} - -const secondsToNanoSecondsFactor = 1000000000 -const milliSecondsToNanoSecondsFactor = 1000000 - -func (e SecondsEpochTime) MarshalJSON() ([]byte, error) { - // UnixNano() returns the epoch in nanoseconds - unixTime := float64(e.UnixNano()) / float64(secondsToNanoSecondsFactor) - return json.Marshal(unixTime) -} - -func (e *SecondsEpochTime) UnmarshalJSON(b []byte) error { - var epoch float64 - err := json.Unmarshal(b, &epoch) - if err != nil { - return err - } - - epochSec := int64(epoch) - epochNano := int64((epoch - float64(epochSec)) * float64(secondsToNanoSecondsFactor)) - - // time.Unix(sec, nsec) expects the epoch integral seconds in the first parameter - // and remaining nanoseconds in the second parameter - *e = SecondsEpochTime{time.Unix(epochSec, epochNano)} - return nil -} - -func (e MilliSecondsEpochTime) MarshalJSON() ([]byte, error) { - // UnixNano() returns the epoch in nanoseconds - unixTimeMs := e.UnixNano() / milliSecondsToNanoSecondsFactor - return json.Marshal(unixTimeMs) -} - -func (e *MilliSecondsEpochTime) UnmarshalJSON(b []byte) error { - var epoch int64 - err := json.Unmarshal(b, &epoch) - if err != nil { - return err - } - *e = MilliSecondsEpochTime{time.Unix(epoch/1000, (epoch%1000)*1000000)} - return nil -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/epoch_time_test.go b/vendor/github.com/aws/aws-lambda-go/events/epoch_time_test.go deleted file mode 100644 index 50cc0007..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/epoch_time_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. -package events - -import ( - "encoding/json" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func TestUnmarshalSecondsEpochTime(t *testing.T) { - - input := []byte("1480641523.476") - - var epoch SecondsEpochTime - if err := json.Unmarshal(input, &epoch); err != nil { - t.Errorf("unmarshal failed. details: %v", err) - } - - utc := epoch.UTC() - assert.Equal(t, 2016, utc.Year()) - assert.Equal(t, time.Month(12), utc.Month()) - assert.Equal(t, 2, utc.Day()) - assert.Equal(t, 1, utc.Hour()) - assert.Equal(t, 18, utc.Minute()) - assert.Equal(t, 43, utc.Second()) - assert.Equal(t, 476, utc.Nanosecond()/1000000) -} - -func TestMarshalSecondsEpochTime(t *testing.T) { - timestamp := SecondsEpochTime{time.Date(2016, time.Month(12), 2, 1, 18, 43, 476*1000000, time.UTC)} - - marshaled, err := json.Marshal(timestamp) - if err != nil { - t.Errorf("marshal failed. details: %v", err) - } - - assert.Equal(t, "1480641523.476", string(marshaled)) -} - -func TestUnmarshalMilliSecondsEpochTime(t *testing.T) { - - input := []byte("1480641523476") - - var epoch MilliSecondsEpochTime - if err := json.Unmarshal(input, &epoch); err != nil { - t.Errorf("unmarshal failed. details: %v", err) - } - - utc := epoch.UTC() - assert.Equal(t, 2016, utc.Year()) - assert.Equal(t, time.Month(12), utc.Month()) - assert.Equal(t, 2, utc.Day()) - assert.Equal(t, 1, utc.Hour()) - assert.Equal(t, 18, utc.Minute()) - assert.Equal(t, 43, utc.Second()) - assert.Equal(t, 476, utc.Nanosecond()/1000000) -} - -func TestMarshalMilliSecondsEpochTime(t *testing.T) { - timestamp := MilliSecondsEpochTime{time.Date(2016, time.Month(12), 2, 1, 18, 43, 476*1000000, time.UTC)} - - marshaled, err := json.Marshal(timestamp) - if err != nil { - t.Errorf("marshal failed. details: %v", err) - } - - assert.Equal(t, "1480641523476", string(marshaled)) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/firehose.go b/vendor/github.com/aws/aws-lambda-go/events/firehose.go deleted file mode 100644 index 293974e7..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/firehose.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -// KinesisFirehoseEvent represents the input event from Amazon Kinesis Firehose. It is used as the input parameter. -type KinesisFirehoseEvent struct { - InvocationID string `json:"invocationId"` - DeliveryStreamArn string `json:"deliveryStreamArn"` - Region string `json:"region"` - Records []KinesisFirehoseEventRecord `json:"records"` -} - -type KinesisFirehoseEventRecord struct { - RecordID string `json:"recordId"` - ApproximateArrivalTimestamp MilliSecondsEpochTime `json:"approximateArrivalTimestamp"` - Data []byte `json:"data"` -} - -// Constants used for describing the transformation result -const ( - KinesisFirehoseTransformedStateOk = "Ok" - KinesisFirehoseTransformedStateDropped = "Dropped" - KinesisFirehoseTransformedStateProcessingFailed = "ProcessingFailed" -) - -type KinesisFirehoseResponse struct { - Records []KinesisFirehoseResponseRecord `json:"records"` -} - -type KinesisFirehoseResponseRecord struct { - RecordID string `json:"recordId"` - Result string `json:"result"` // The status of the transformation. May be TransformedStateOk, TransformedStateDropped or TransformedStateProcessingFailed - Data []byte `json:"data"` -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/firehose_test.go b/vendor/github.com/aws/aws-lambda-go/events/firehose_test.go deleted file mode 100644 index 8aa06c06..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/firehose_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. -package events - -import ( - "context" - "encoding/json" - "strings" - "testing" - - "github.com/aws/aws-lambda-go/events/test" - "github.com/stretchr/testify/assert" -) - -func testFirehoseEventMarshaling(t *testing.T) { - testMarshaling(t, "./testdata/kinesis-firehose-event.json") -} - -func testFirehoseResponseMarshaling(t *testing.T) { - testMarshaling(t, "./testdata/kinesis-firehose-response.json") -} - -func testMarshaling(t *testing.T, jsonFile string) { - - // 1. read JSON from file - inputJson := readJsonFromFile(t, jsonFile) - - // 2. de-serialize into Go object - var inputEvent KinesisFirehoseEvent - if err := json.Unmarshal(inputJson, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // 3. serialize to JSON - outputJson, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - // 4. check result - test.AssertJsonsEqual(t, inputJson, outputJson) -} - -func TestSampleTransformation(t *testing.T) { - - inputJson := readJsonFromFile(t, "./testdata/kinesis-firehose-event.json") - - // de-serialize into Go object - var inputEvent KinesisFirehoseEvent - if err := json.Unmarshal(inputJson, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - response := toUpperHandler(context.TODO(), inputEvent) - - inputString := string(inputEvent.Records[0].Data) - expectedString := strings.ToUpper(inputString) - actualString := string(response.Records[0].Data) - assert.Equal(t, actualString, expectedString) -} - -func toUpperHandler(ctx context.Context, evnt KinesisFirehoseEvent) KinesisFirehoseResponse { - var response KinesisFirehoseResponse - - for _, record := range evnt.Records { - // Transform data: ToUpper the data - var transformedRecord KinesisFirehoseResponseRecord - transformedRecord.RecordID = record.RecordID - transformedRecord.Result = KinesisFirehoseTransformedStateOk - transformedRecord.Data = []byte(strings.ToUpper(string(record.Data))) - - response.Records = append(response.Records, transformedRecord) - } - - return response -} - -func TestKinesisFirehoseMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, KinesisFirehoseEvent{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/kinesis.go b/vendor/github.com/aws/aws-lambda-go/events/kinesis.go deleted file mode 100644 index 2b65d76c..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/kinesis.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -type KinesisEvent struct { - Records []KinesisEventRecord `json:"Records"` -} - -type KinesisEventRecord struct { - AwsRegion string `json:"awsRegion"` - EventID string `json:"eventID"` - EventName string `json:"eventName"` - EventSource string `json:"eventSource"` - EventSourceArn string `json:"eventSourceARN"` - EventVersion string `json:"eventVersion"` - InvokeIdentityArn string `json:"invokeIdentityArn"` - Kinesis KinesisRecord `json:"kinesis"` -} - -type KinesisRecord struct { - ApproximateArrivalTimestamp SecondsEpochTime `json:"approximateArrivalTimestamp"` - Data []byte `json:"data"` - EncryptionType string `json:"encryptionType,omitempty"` - PartitionKey string `json:"partitionKey"` - SequenceNumber string `json:"sequenceNumber"` - KinesisSchemaVersion string `json:"kinesisSchemaVersion"` -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/kinesis_test.go b/vendor/github.com/aws/aws-lambda-go/events/kinesis_test.go deleted file mode 100644 index a79b230d..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/kinesis_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. -package events - -import ( - "encoding/json" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestKinesisEventMarshaling(t *testing.T) { - - // 1. read JSON from file - inputJson := readJsonFromFile(t, "./testdata/kinesis-event.json") - - // 2. de-serialize into Go object - var inputEvent KinesisEvent - if err := json.Unmarshal(inputJson, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // 3. serialize to JSON - outputJson, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - // 4. check result - test.AssertJsonsEqual(t, inputJson, outputJson) -} - -func TestKinesisMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, KinesisEvent{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/lex.go b/vendor/github.com/aws/aws-lambda-go/events/lex.go deleted file mode 100644 index 4255b77b..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/lex.go +++ /dev/null @@ -1,64 +0,0 @@ -package events - -type LexEvent struct { - MessageVersion string `json:"messageVersion,omitempty"` - InvocationSource string `json:"invocationSource,omitempty"` - UserID string `json:"userId,omitempty"` - InputTranscript string `json:"inputTranscript,omitempty"` - SessionAttributes map[string]string `json:"sessionAttributes,omitempty"` - RequestAttributes map[string]string `json:"requestAttributes,omitempty"` - Bot *LexBot `json:"bot,omitempty"` - OutputDialogMode string `json:"outputDialogMode,omitempty"` - CurrentIntent *LexCurrentIntent `json:"currentIntent,omitempty"` - DialogAction *LexDialogAction `json:"dialogAction,omitempty"` -} - -type LexBot struct { - Name string `json:"name,omitempty"` - Alias string `json:"alias,omitempty"` - Version string `json:"version,omitempty"` -} - -type LexCurrentIntent struct { - Name string `json:"name,omitempty"` - Slots Slots `json:"slots,omitempty"` - SlotDetails map[string]SlotDetail `json:"slotDetails,omitempty"` - ConfirmationStatus string `json:"confirmationStatus,omitempty"` -} - -type SlotDetail struct { - Resolutions []map[string]string `json:"resolutions,omitempty"` - OriginalValue string `json:"originalValue,omitempty"` -} - -type LexDialogAction struct { - Type string `json:"type,omitempty"` - FulfillmentState string `json:"fulfillmentState,omitempty"` - Message map[string]string `json:"message,omitempty"` - IntentName string `json:"intentName,omitempty"` - Slots Slots `json:"slots,omitempty"` - SlotToElicit string `json:"slotToElicit,omitempty"` - ResponseCard LexResponseCard `json:"responseCard,omitempty"` -} - -type Slots map[string]string - -type LexResponseCard struct { - Version int64 `json:"version,omitempty"` - ContentType string `json:"contentType,omitempty"` - GenericAttachments []Attachment `json:"genericAttachments,omitempty"` -} - -type Attachment struct { - Title string `json:"title,omitempty"` - SubTitle string `json:"subTitle,omitempty"` - ImageURL string `json:"imageUrl,omitempty"` - AttachmentLinkURL string `json:"attachmentLinkUrl,omitempty"` - Buttons []map[string]string `json:"buttons,omitempty"` -} - -func (h *LexEvent) Clear() { - h.Bot = nil - h.CurrentIntent = nil - h.DialogAction = nil -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/lex_test.go b/vendor/github.com/aws/aws-lambda-go/events/lex_test.go deleted file mode 100644 index a1d64e36..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/lex_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package events - -import ( - "encoding/json" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestLexEventMarshaling(t *testing.T) { - tests := []struct { - filePath string - }{{"./testdata/lex-response.json"}, {"./testdata/lex-event.json"}} - - for _, te := range tests { - inputJSON := readJsonFromFile(t, te.filePath) - - var inputEvent LexEvent - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) - } -} - -func TestLexMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, LexEvent{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/s3.go b/vendor/github.com/aws/aws-lambda-go/events/s3.go deleted file mode 100644 index a0641a3f..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/s3.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -import ( - "time" -) - -type S3Event struct { - Records []S3EventRecord `json:"Records"` -} - -type S3EventRecord struct { - EventVersion string `json:"eventVersion"` - EventSource string `json:"eventSource"` - AWSRegion string `json:"awsRegion"` - EventTime time.Time `json:"eventTime"` - EventName string `json:"eventName"` - PrincipalID S3UserIdentity `json:"userIdentity"` - RequestParameters S3RequestParameters `json:"requestParameters"` - ResponseElements map[string]string `json:"responseElements"` - S3 S3Entity `json:"s3"` -} - -type S3UserIdentity struct { - PrincipalID string `json:"principalId"` -} - -type S3RequestParameters struct { - SourceIPAddress string `json:"sourceIPAddress"` -} - -type S3Entity struct { - SchemaVersion string `json:"s3SchemaVersion"` - ConfigurationID string `json:"configurationId"` - Bucket S3Bucket `json:"bucket"` - Object S3Object `json:"object"` -} - -type S3Bucket struct { - Name string `json:"name"` - OwnerIdentity S3UserIdentity `json:"ownerIdentity"` - Arn string `json:"arn"` -} - -type S3Object struct { - Key string `json:"key"` - Size int64 `json:"size"` - URLDecodedKey string `json:"urlDecodedKey"` - VersionID string `json:"versionId"` - ETag string `json:"eTag"` - Sequencer string `json:"sequencer"` -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/s3_test.go b/vendor/github.com/aws/aws-lambda-go/events/s3_test.go deleted file mode 100644 index e2a72386..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/s3_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. -package events - -import ( - "encoding/json" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestS3EventMarshaling(t *testing.T) { - - // 1. read JSON from file - inputJson := readJsonFromFile(t, "./testdata/s3-event.json") - - // 2. de-serialize into Go object - var inputEvent S3Event - if err := json.Unmarshal(inputJson, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // 3. serialize to JSON - outputJson, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - // 4. check result - test.AssertJsonsEqual(t, inputJson, outputJson) -} - -func TestS3MarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, S3Event{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/ses.go b/vendor/github.com/aws/aws-lambda-go/events/ses.go deleted file mode 100644 index 8f811700..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/ses.go +++ /dev/null @@ -1,64 +0,0 @@ -package events - -import "time" - -// SimpleEmailEvent is the outer structure of an event sent via SES. -type SimpleEmailEvent struct { - Records []SimpleEmailRecord `json:"Records"` -} - -type SimpleEmailRecord struct { - EventVersion string `json:"eventVersion"` - EventSource string `json:"eventSource"` - SES SimpleEmailService `json:"ses"` -} - -type SimpleEmailService struct { - Mail SimpleEmailMessage `json:"mail"` - Receipt SimpleEmailReceipt `json:"receipt"` -} - -type SimpleEmailMessage struct { - CommonHeaders SimpleEmailCommonHeaders `json:"commonHeaders"` - Source string `json:"source"` - Timestamp time.Time `json:"timestamp"` - Destination []string `json:"destination"` - Headers []SimpleEmailHeader `json:"headers"` - HeadersTruncated bool `json:"headersTruncated"` - MessageID string `json:"messageId"` -} - -type SimpleEmailReceipt struct { - Recipients []string `json:"recipients"` - Timestamp time.Time `json:"timestamp"` - SpamVerdict SimpleEmailVerdict `json:"spamVerdict"` - DKIMVerdict SimpleEmailVerdict `json:"dkimVerdict"` - SPFVerdict SimpleEmailVerdict `json:"spfVerdict"` - VirusVerdict SimpleEmailVerdict `json:"virusVerdict"` - Action SimpleEmailReceiptAction `json:"action"` - ProcessingTimeMillis int64 `json:"processingTimeMillis"` -} - -type SimpleEmailHeader struct { - Name string `json:"name"` - Value string `json:"value"` -} - -type SimpleEmailCommonHeaders struct { - From []string `json:"from"` - To []string `json:"to"` - ReturnPath string `json:"returnPath"` - MessageID string `json:"messageId"` - Date string `json:"date"` - Subject string `json:"subject"` -} - -type SimpleEmailReceiptAction struct { - Type string `json:"type"` - InvocationType string `json:"invocationType"` - FunctionArn string `json:"functionArn"` -} - -type SimpleEmailVerdict struct { - Status string `json:"status"` -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/ses_test.go b/vendor/github.com/aws/aws-lambda-go/events/ses_test.go deleted file mode 100644 index b2d5baa9..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/ses_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package events - -import ( - "encoding/json" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestSESEventMarshaling(t *testing.T) { - inputJSON := readJsonFromFile(t, "./testdata/ses-event.json") - - var inputEvent SimpleEmailEvent - if err := json.Unmarshal(inputJSON, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - outputJSON, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - test.AssertJsonsEqual(t, inputJSON, outputJSON) -} - -func TestSESMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, SimpleEmailEvent{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/sns.go b/vendor/github.com/aws/aws-lambda-go/events/sns.go deleted file mode 100644 index 9b00bd2e..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/sns.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package events - -import ( - "time" -) - -type SNSEvent struct { - Records []SNSEventRecord `json:"Records"` -} - -type SNSEventRecord struct { - EventVersion string `json:"EventVersion"` - EventSubscriptionArn string `json:"EventSubscriptionArn"` - EventSource string `json:"EventSource"` - SNS SNSEntity `json:"Sns"` -} - -type SNSEntity struct { - Signature string `json:"Signature"` - MessageID string `json:"MessageId"` - Type string `json:"Type"` - TopicArn string `json:"TopicArn"` - MessageAttributes map[string]interface{} `json:"MessageAttributes"` - SignatureVersion string `json:"SignatureVersion"` - Timestamp time.Time `json:"Timestamp"` - SigningCertURL string `json:"SigningCertUrl"` - Message string `json:"Message"` - UnsubscribeURL string `json:"UnsubscribeUrl"` - Subject string `json:"Subject"` -} diff --git a/vendor/github.com/aws/aws-lambda-go/events/sns_test.go b/vendor/github.com/aws/aws-lambda-go/events/sns_test.go deleted file mode 100644 index 83c03fe6..00000000 --- a/vendor/github.com/aws/aws-lambda-go/events/sns_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. -package events - -import ( - "encoding/json" - "testing" - - "github.com/aws/aws-lambda-go/events/test" -) - -func TestSnsEventMarshaling(t *testing.T) { - - // 1. read JSON from file - inputJson := readJsonFromFile(t, "./testdata/sns-event.json") - - // 2. de-serialize into Go object - var inputEvent SNSEvent - if err := json.Unmarshal(inputJson, &inputEvent); err != nil { - t.Errorf("could not unmarshal event. details: %v", err) - } - - // 3. serialize to JSON - outputJson, err := json.Marshal(inputEvent) - if err != nil { - t.Errorf("could not marshal event. details: %v", err) - } - - // 4. check result - test.AssertJsonsEqual(t, inputJson, outputJson) -} - -func TestSnsMarshalingMalformedJson(t *testing.T) { - test.TestMalformedJson(t, SNSEvent{}) -} diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/README.md b/vendor/github.com/aws/aws-lambda-go/lambda/README.md deleted file mode 100644 index 76f8679b..00000000 --- a/vendor/github.com/aws/aws-lambda-go/lambda/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Overview - -[![GoDoc](https://godoc.org/github.com/aws/aws-lambda-go/lambda?status.svg)](https://godoc.org/github.com/aws/aws-lambda-go/lambda) diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/function_test.go b/vendor/github.com/aws/aws-lambda-go/lambda/function_test.go deleted file mode 100644 index 1ef64a4c..00000000 --- a/vendor/github.com/aws/aws-lambda-go/lambda/function_test.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package lambda - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "testing" - "time" - - "github.com/aws/aws-lambda-go/lambda/messages" - "github.com/aws/aws-lambda-go/lambdacontext" - "github.com/stretchr/testify/assert" -) - -type testWrapperHandler func(ctx context.Context, input []byte) (interface{}, error) - -func (h testWrapperHandler) Invoke(ctx context.Context, payload []byte) ([]byte, error) { - response, err := h(ctx, payload) - if err != nil { - return nil, err - } - - responseBytes, err := json.Marshal(response) - if err != nil { - return nil, err - } - - return responseBytes, nil -} - -// verify testWrapperHandler implements Handler -var _ Handler = (testWrapperHandler)(nil) - -func TestInvoke(t *testing.T) { - srv := &Function{handler: testWrapperHandler( - func(ctx context.Context, input []byte) (interface{}, error) { - if deadline, ok := ctx.Deadline(); ok { - return deadline.UnixNano(), nil - } - return nil, errors.New("!?!?!?!?!") - }, - )} - deadline := time.Now() - var response messages.InvokeResponse - err := srv.Invoke(&messages.InvokeRequest{ - Deadline: messages.InvokeRequest_Timestamp{ - Seconds: deadline.Unix(), - Nanos: int64(deadline.Nanosecond()), - }}, &response) - assert.NoError(t, err) - var responseValue int64 - assert.NoError(t, json.Unmarshal(response.Payload, &responseValue)) - assert.Equal(t, deadline.UnixNano(), responseValue) -} - -type CustomError struct{} - -func (e CustomError) Error() string { return fmt.Sprintf("Something bad happened!") } - -func TestCustomError(t *testing.T) { - - srv := &Function{handler: testWrapperHandler( - func(ctx context.Context, input []byte) (interface{}, error) { - return nil, CustomError{} - }, - )} - var response messages.InvokeResponse - err := srv.Invoke(&messages.InvokeRequest{}, &response) - assert.NoError(t, err) - assert.Nil(t, response.Payload) - assert.Equal(t, "Something bad happened!", response.Error.Message) - assert.Equal(t, "CustomError", response.Error.Type) -} - -type CustomError2 struct{} - -func (e *CustomError2) Error() string { return fmt.Sprintf("Something bad happened!") } - -func TestCustomErrorRef(t *testing.T) { - - srv := &Function{handler: testWrapperHandler( - func(ctx context.Context, input []byte) (interface{}, error) { - return nil, &CustomError2{} - }, - )} - var response messages.InvokeResponse - err := srv.Invoke(&messages.InvokeRequest{}, &response) - assert.NoError(t, err) - assert.Nil(t, response.Payload) - assert.Equal(t, "Something bad happened!", response.Error.Message) - assert.Equal(t, "CustomError2", response.Error.Type) -} - -func TestContextPlumbing(t *testing.T) { - srv := &Function{handler: testWrapperHandler( - func(ctx context.Context, input []byte) (interface{}, error) { - lc, _ := lambdacontext.FromContext(ctx) - return lc, nil - }, - )} - var response messages.InvokeResponse - err := srv.Invoke(&messages.InvokeRequest{ - CognitoIdentityId: "dummyident", - CognitoIdentityPoolId: "dummypool", - ClientContext: []byte(`{ - "Client": { - "app_title": "dummytitle", - "installation_id": "dummyinstallid", - "app_version_code": "dummycode", - "app_package_name": "dummyname" - } - }`), - RequestId: "dummyid", - InvokedFunctionArn: "dummyarn", - }, &response) - assert.NoError(t, err) - assert.NotNil(t, response.Payload) - expected := ` - { - "AwsRequestID": "dummyid", - "InvokedFunctionArn": "dummyarn", - "Identity": { - "CognitoIdentityID": "dummyident", - "CognitoIdentityPoolID": "dummypool" - }, - "ClientContext": { - "Client": { - "installation_id": "dummyinstallid", - "app_title": "dummytitle", - "app_version_code": "dummycode", - "app_package_name": "dummyname" - }, - "env": null, - "custom": null - } - } - ` - assert.JSONEq(t, expected, string(response.Payload)) -} diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/handler_test.go b/vendor/github.com/aws/aws-lambda-go/lambda/handler_test.go deleted file mode 100644 index 2e29aa10..00000000 --- a/vendor/github.com/aws/aws-lambda-go/lambda/handler_test.go +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package lambda - -import ( - "context" - "errors" - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestInvalidHandlers(t *testing.T) { - - testCases := []struct { - name string - handler interface{} - expected error - }{ - { - name: "nil handler", - expected: errors.New("handler is nil"), - handler: nil, - }, - { - name: "handler is not a function", - expected: errors.New("handler kind struct is not func"), - handler: struct{}{}, - }, - { - name: "handler declares too many arguments", - expected: errors.New("handlers may not take more than two arguments, but handler takes 3"), - handler: func(n context.Context, x string, y string) error { - return nil - }, - }, - { - name: "two argument handler does not context as first argument", - expected: errors.New("handler takes two arguments, but the first is not Context. got string"), - handler: func(a string, x context.Context) error { - return nil - }, - }, - { - name: "handler returns too many values", - expected: errors.New("handler may not return more than two values"), - handler: func() (error, error, error) { - return nil, nil, nil - }, - }, - { - name: "handler returning two values does not declare error as the second return value", - expected: errors.New("handler returns two values, but the second does not implement error"), - handler: func() (error, string) { - return nil, "hello" - }, - }, - { - name: "handler returning a single value does not implement error", - expected: errors.New("handler returns a single value, but it does not implement error"), - handler: func() string { - return "hello" - }, - }, - { - name: "no return value should not result in error", - expected: nil, - handler: func() { - }, - }, - } - for i, testCase := range testCases { - t.Run(fmt.Sprintf("testCase[%d] %s", i, testCase.name), func(t *testing.T) { - lambdaHandler := newHandler(testCase.handler) - _, err := lambdaHandler.Invoke(context.TODO(), make([]byte, 0)) - assert.Equal(t, testCase.expected, err) - }) - } -} - -type expected struct { - val string - err error -} - -func TestInvokes(t *testing.T) { - hello := func(s string) string { - return fmt.Sprintf("Hello %s!", s) - } - hellop := func(s *string) *string { - v := hello(*s) - return &v - } - - testCases := []struct { - name string - input string - expected expected - handler interface{} - }{ - { - input: `"Lambda"`, - expected: expected{`"Hello Lambda!"`, nil}, - handler: func(name string) (string, error) { - return hello(name), nil - }, - }, - { - input: `"Lambda"`, - expected: expected{`"Hello Lambda!"`, nil}, - handler: func(name string) (string, error) { - return hello(name), nil - }, - }, - { - input: `"Lambda"`, - expected: expected{`"Hello Lambda!"`, nil}, - handler: func(ctx context.Context, name string) (string, error) { - return hello(name), nil - }, - }, - { - input: `"Lambda"`, - expected: expected{`"Hello Lambda!"`, nil}, - handler: func(name *string) (*string, error) { - return hellop(name), nil - }, - }, - { - input: `"Lambda"`, - expected: expected{`"Hello Lambda!"`, nil}, - handler: func(name *string) (*string, error) { - return hellop(name), nil - }, - }, - { - input: `"Lambda"`, - expected: expected{`"Hello Lambda!"`, nil}, - handler: func(ctx context.Context, name *string) (*string, error) { - return hellop(name), nil - }, - }, - { - input: `"Lambda"`, - expected: expected{"", errors.New("bad stuff")}, - handler: func() error { - return errors.New("bad stuff") - }, - }, - { - input: `"Lambda"`, - expected: expected{"", errors.New("bad stuff")}, - handler: func() (interface{}, error) { - return nil, errors.New("bad stuff") - }, - }, - { - input: `"Lambda"`, - expected: expected{"", errors.New("bad stuff")}, - handler: func(e interface{}) (interface{}, error) { - return nil, errors.New("bad stuff") - }, - }, - { - input: `"Lambda"`, - expected: expected{"", errors.New("bad stuff")}, - handler: func(ctx context.Context, e interface{}) (interface{}, error) { - return nil, errors.New("bad stuff") - }, - }, - { - name: "basic input struct serialization", - input: `{"custom":9001}`, - expected: expected{`9001`, nil}, - handler: func(event struct{ Custom int }) (int, error) { - return event.Custom, nil - }, - }, - { - name: "basic output struct serialization", - input: `9001`, - expected: expected{`{"Number":9001}`, nil}, - handler: func(event int) (struct{ Number int }, error) { - return struct{ Number int }{event}, nil - }, - }, - } - for i, testCase := range testCases { - t.Run(fmt.Sprintf("testCase[%d] %s", i, testCase.name), func(t *testing.T) { - lambdaHandler := newHandler(testCase.handler) - response, err := lambdaHandler.Invoke(context.TODO(), []byte(testCase.input)) - if testCase.expected.err != nil { - assert.Equal(t, testCase.expected.err, err) - } else { - assert.NoError(t, err) - assert.Equal(t, testCase.expected.val, string(response)) - } - }) - } -} - -func TestInvalidJsonInput(t *testing.T) { - lambdaHandler := newHandler(func(s string) error { return nil }) - _, err := lambdaHandler.Invoke(context.TODO(), []byte(`{"invalid json`)) - assert.Equal(t, "unexpected end of JSON input", err.Error()) - -} diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/messages/README.md b/vendor/github.com/aws/aws-lambda-go/lambda/messages/README.md deleted file mode 100644 index 8bf6ef4b..00000000 --- a/vendor/github.com/aws/aws-lambda-go/lambda/messages/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Overview - -[![GoDoc](https://godoc.org/github.com/aws/aws-lambda-go/lambda/messages?status.svg)](https://godoc.org/github.com/aws/aws-lambda-go/lambda/messages) diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/panic_test.go b/vendor/github.com/aws/aws-lambda-go/lambda/panic_test.go deleted file mode 100644 index bdc6b797..00000000 --- a/vendor/github.com/aws/aws-lambda-go/lambda/panic_test.go +++ /dev/null @@ -1,136 +0,0 @@ -package lambda - -import ( - "os" - "runtime" - "strings" - "testing" - - "github.com/stretchr/testify/assert" -) - -func assertPanicMessage(t *testing.T, panicFunc func(), expectedMessage string) { - defer func() { - if err := recover(); err != nil { - panicInfo := getPanicInfo(err) - assert.NotNil(t, panicInfo) - assert.NotNil(t, panicInfo.Message) - assert.Equal(t, expectedMessage, panicInfo.Message) - assert.NotNil(t, panicInfo.StackTrace) - } - }() - - panicFunc() - t.Errorf("Should have exited due to panic") -} - -func TestPanicFormattingStringValue(t *testing.T) { - assertPanicMessage(t, func() { panic("Panic time!") }, "Panic time!") -} - -func TestPanicFormattingIntValue(t *testing.T) { - assertPanicMessage(t, func() { panic(1234) }, "1234") -} - -func TestPanicFormattingCustomError(t *testing.T) { - customError := &CustomError{} - assertPanicMessage(t, func() { panic(customError) }, customError.Error()) -} - -func TestFormatFrame(t *testing.T) { - var tests = []struct { - inputPath string - inputLine int32 - inputLabel string - expectedPath string - expectedLine int32 - expectedLabel string - }{ - { - inputPath: "/Volumes/Unix/workspace/LambdaGoLang/src/GoAmzn-Github-Aws-AwsLambdaGo/src/github.com/aws/aws-lambda-go/lambda/panic_test.go", - inputLine: 42, - inputLabel: "github.com/aws/aws-lambda-go/lambda.printStack", - expectedPath: "github.com/aws/aws-lambda-go/lambda/panic_test.go", - expectedLine: 42, - expectedLabel: "printStack", - }, - { - inputPath: "/home/user/src/pkg/sub/file.go", - inputLine: 42, - inputLabel: "pkg/sub.Type.Method", - expectedPath: "pkg/sub/file.go", - expectedLine: 42, - expectedLabel: "Type.Method", - }, - { - inputPath: "/home/user/src/pkg/sub/sub2/file.go", - inputLine: 42, - inputLabel: "pkg/sub/sub2.Type.Method", - expectedPath: "pkg/sub/sub2/file.go", - expectedLine: 42, - expectedLabel: "Type.Method", - }, - { - inputPath: "/home/user/src/pkg/file.go", - inputLine: 101, - inputLabel: "pkg.Type.Method", - expectedPath: "pkg/file.go", - expectedLine: 101, - expectedLabel: "Type.Method", - }, - } - - for _, test := range tests { - inputFrame := runtime.Frame{ - File: test.inputPath, - Line: int(test.inputLine), - Function: test.inputLabel, - } - - actual := formatFrame(inputFrame) - assert.Equal(t, test.expectedPath, actual.Path) - assert.Equal(t, test.expectedLine, actual.Line) - assert.Equal(t, test.expectedLabel, actual.Label) - } -} - -func TestRuntimeStackTrace(t *testing.T) { - // implementing the test in the inner function to simulate an - // additional stack frame that would exist in real life due to the - // defer function. - testRuntimeStackTrace(t) -} - -func testRuntimeStackTrace(t *testing.T) { - panicInfo := getPanicInfo("Panic time!") - - assert.NotNil(t, panicInfo) - assert.NotNil(t, panicInfo.StackTrace) - assert.True(t, len(panicInfo.StackTrace) > 0) - - packagePath, err := getPackagePath() - assert.NoError(t, err) - - frame := panicInfo.StackTrace[0] - assert.Equal(t, packagePath+"/panic_test.go", frame.Path) - assert.True(t, frame.Line > 0) - assert.Equal(t, "testRuntimeStackTrace", frame.Label) -} - -func getPackagePath() (string, error) { - fullPath, err := os.Getwd() - if err != nil { - return "", err - } - - basePath := os.Getenv("GOPATH") - if basePath == "" { - if runtime.GOOS == "windows" { - basePath = os.Getenv("USERPROFILE") + "/go" - } else { - basePath = os.Getenv("HOME") + "/go" - } - } - - return strings.Replace(fullPath, basePath+"/src/", "", 1), nil -} diff --git a/vendor/github.com/aws/aws-lambda-go/lambdacontext/README.md b/vendor/github.com/aws/aws-lambda-go/lambdacontext/README.md deleted file mode 100644 index 44d648a5..00000000 --- a/vendor/github.com/aws/aws-lambda-go/lambdacontext/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Overview - -[![GoDoc](https://godoc.org/github.com/aws/aws-lambda-go/lambdacontext?status.svg)](https://godoc.org/github.com/aws/aws-lambda-go/lambdacontext) diff --git a/vendor/github.com/aws/aws-sdk-go/.gitignore b/vendor/github.com/aws/aws-sdk-go/.gitignore deleted file mode 100644 index fb11ceca..00000000 --- a/vendor/github.com/aws/aws-sdk-go/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -dist -/doc -/doc-staging -.yardoc -Gemfile.lock -awstesting/integration/smoke/**/importmarker__.go -awstesting/integration/smoke/_test/ -/vendor/bin/ -/vendor/pkg/ -/vendor/src/ -/private/model/cli/gen-api/gen-api diff --git a/vendor/github.com/aws/aws-sdk-go/.godoc_config b/vendor/github.com/aws/aws-sdk-go/.godoc_config deleted file mode 100644 index 0c6400bc..00000000 --- a/vendor/github.com/aws/aws-sdk-go/.godoc_config +++ /dev/null @@ -1,14 +0,0 @@ -{ - "PkgHandler": { - "Pattern": "/sdk-for-go/api/", - "StripPrefix": "/sdk-for-go/api", - "Include": ["/src/github.com/aws/aws-sdk-go/aws", "/src/github.com/aws/aws-sdk-go/service"], - "Exclude": ["/src/cmd", "/src/github.com/aws/aws-sdk-go/awstesting", "/src/github.com/aws/aws-sdk-go/awsmigrate", "/src/github.com/aws/aws-sdk-go/private"], - "IgnoredSuffixes": ["iface"] - }, - "Github": { - "Tag": "master", - "Repo": "/aws/aws-sdk-go", - "UseGithub": true - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/.travis.yml b/vendor/github.com/aws/aws-sdk-go/.travis.yml deleted file mode 100644 index 0b34640d..00000000 --- a/vendor/github.com/aws/aws-sdk-go/.travis.yml +++ /dev/null @@ -1,48 +0,0 @@ -language: go - -matrix: - allow_failures: - - go: tip - - go: 1.6.x - os: linux - include: - - os: linux - sudo: required - go: 1.5.x - # Use Go 1.5's vendoring experiment for 1.5 tests. - env: GO15VENDOREXPERIMENT=1 - - os: linux - sudo: required - go: 1.6.x - - os: linux - sudo: required - go: 1.7.x - - os: linux - sudo: required - go: 1.8.x - - os: linux - sudo: required - go: 1.9.x - - os: linux - sudo: required - go: 1.10.x - - os: linux - sudo: required - go: tip - - os: osx - go: 1.7.x - - os: osx - go: 1.8.x - - os: osx - go: 1.9.x - - os: osx - go: 1.10.x - - os: osx - go: tip - -script: - - make ci-test - -branches: - only: - - master diff --git a/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md deleted file mode 100644 index cffaa543..00000000 --- a/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md +++ /dev/null @@ -1,3529 +0,0 @@ -Release v1.14.7 (2018-06-14) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Support for PRIVATE endpoint configuration type -* `service/dynamodb`: Updates service API and documentation - * Added two new fields SSEType and KMSMasterKeyArn to SSEDescription block in describe-table output. -* `service/iotanalytics`: Updates service API and documentation - -Release v1.14.6 (2018-06-13) -=== - -### Service Client Updates -* `service/servicecatalog`: Updates service API - * Introduced new length limitations for few of the product fields. -* `service/ssm`: Updates service API and documentation - * Added support for new parameter, CloudWatchOutputConfig, for SendCommand API. Users can now have RunCommand output sent to CloudWatchLogs. - -Release v1.14.5 (2018-06-12) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * Adding VPCEndpoint support for Remote access. Allows customers to be able to access their private endpoints/services running in their VPC during remote access. -* `service/ecs`: Updates service API and documentation - * Introduces daemon scheduling capability to deploy one task per instance on selected instances in a cluster. Adds a "force" flag to the DeleteService API to delete a service without requiring to scale down the number of tasks to zero. - -### SDK Enhancements -* `service/rds/rdsutils`: Clean up the rdsutils package and adds a new builder to construct connection strings ([#1985](https://github.com/aws/aws-sdk-go/pull/1985)) - * Rewords documentation to be more useful and provides links to prior setup needed to support authentication tokens. Introduces a builder that allows for building connection strings - -### SDK Bugs -* `aws/signer/v4`: Fix X-Amz-Content-Sha256 being in to query for presign ([#1976](https://github.com/aws/aws-sdk-go/pull/1976)) - * Fixes the bug which would allow the X-Amz-Content-Sha256 header to be promoted to the query string when presigning a S3 request. This bug also was preventing users from setting their own sha256 value for a presigned URL. Presigned requests generated with the custom sha256 would of always failed with invalid signature. - * Fixes [#1974](https://github.com/aws/aws-sdk-go/pull/1974) -Release v1.14.4 (2018-06-11) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Amazon Cloud Directory now supports optional attributes on Typed Links, giving users the ability to associate and manage data on Typed Links. -* `service/rds`: Updates service documentation - * Changed lists of valid EngineVersion values to links to the RDS User Guide. -* `service/storagegateway`: Updates service API and documentation - * AWS Storage Gateway now enables you to create cached volumes and tapes with AWS KMS support. - -Release v1.14.3 (2018-06-08) -=== - -### Service Client Updates -* `service/mediatailor`: Updates service API - -Release v1.14.2 (2018-06-07) -=== - -### Service Client Updates -* `service/medialive`: Updates service API, documentation, and paginators - * AWS Elemental MediaLive now makes channel log information available through Amazon CloudWatch Logs. You can set up each MediaLive channel with a logging level; when the channel is run, logs will automatically be published to your account on Amazon CloudWatch Logs - -Release v1.14.1 (2018-06-05) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/polly`: Updates service API and documentation - * Amazon Polly adds new French voice - "Lea" -* `service/rds`: Updates service API and documentation - * This release adds customizable processor features for RDS instances. -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager -* `service/shield`: Updates service API and documentation - * DDoS Response Team access management for AWS Shield - -Release v1.14.0 (2018-06-04) -=== - -### Service Client Updates -* `service/AWSMigrationHub`: Updates service documentation -* `service/appstream`: Updates service API and documentation - * Amazon AppStream 2.0 adds support for Google Drive for G Suite. With this feature, customers will be able to connect their G Suite accounts with AppStream 2.0 and enable Google Drive access for an AppStream 2.0 stack. Users of the stack can then link their Google Drive using their G Suite login credentials and use their existing files stored in Drive with their AppStream 2.0 applications. File changes will be synced automatically to Google cloud. -* `service/ec2`: Updates service API and documentation - * You are now able to use instance storage (up to 3600 GB of NVMe based SSD) on M5 instances, the next generation of EC2's General Purpose instances in us-east-1, us-west-2, us-east-2, eu-west-1 and ca-central-1. M5 instances offer up to 96 vCPUs, 384 GiB of DDR4 instance memory, 25 Gbps in Network bandwidth and improved EBS and Networking bandwidth on smaller instance sizes and provide a balance of compute, memory and network resources for many applications. -* `service/eks`: Adds new service -* `service/mediaconvert`: Updates service API and documentation - * This release adds the support for Common Media Application Format (CMAF) fragmented outputs, RF64 WAV audio output format, and HEV1 or HEVC1 MP4 packaging types when using HEVC in DASH or CMAF outputs. -* `service/sagemaker`: Updates service API, documentation, and paginators - * Amazon SageMaker has added the ability to run hyperparameter tuning jobs. A hyperparameter tuning job will create and evaluate multiple training jobs while tuning algorithm hyperparameters, to optimize a customer specified objective metric. - -### SDK Features -* Add support for EventStream based APIs (S3 SelectObjectContent) ([#1941](https://github.com/aws/aws-sdk-go/pull/1941)) - * Adds support for EventStream asynchronous APIs such as S3 SelectObjectContents API. This API allows your application to receiving multiple events asynchronously from the API response. Your application recieves these events from a channel on the API response. - * See PR [#1941](https://github.com/aws/aws-sdk-go/pull/1941) for example. - * Fixes [#1895](https://github.com/aws/aws-sdk-go/issues/1895) - -Release v1.13.60 (2018-06-01) -=== - -### Service Client Updates -* `service/ds`: Updates service API and documentation - * Added ResetUserPassword API. Customers can now reset their users' passwords without providing the old passwords in Simple AD and Microsoft AD. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iot`: Updates service API and documentation - * We are releasing force CancelJob and CancelJobExecution functionalities to customers. -* `service/mediatailor`: Adds new service -* `service/redshift`: Updates service documentation - * Documentation updates for redshift -* `service/sns`: Updates service API, documentation, and paginators - * The SNS Subscribe API has been updated with two new optional parameters: Attributes and ReturnSubscriptionArn. Attributes is a map of subscription attributes which can be one or more of: FilterPolicy, DeliveryPolicy, and RawMessageDelivery. ReturnSubscriptionArn is a boolean parameter that overrides the default behavior of returning "pending confirmation" for subscriptions that require confirmation instead of returning the subscription ARN. - -### SDK Bugs -* `private/mode/api`: Fix error code constants being generated incorrectly.([#1958](https://github.com/aws/aws-sdk-go/issues/1958)) - * Fixes the SDK's code generation to not modify the error code text value when generating error code constants. This prevents generating error code values which are invalid and will never be sent by the service. This change does not change the error code constant variable name generated by the SDK, only the value of the error code. - * Fixes [#1856](https://github.com/aws/aws-sdk-go/issues/1856) -Release v1.13.59 (2018-05-31) -=== - -* `aws/endpoints`: Updated Regions and Endpoints metadata. -Release v1.13.58 (2018-05-30) -=== - -### Service Client Updates -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/neptune`: Adds new service - * Amazon Neptune is a fast, reliable graph database service that makes it easy to build and run applications that work with highly connected datasets. Neptune supports popular graph models Property Graph and W3C's Resource Description Frame (RDF), and their respective query languages Apache TinkerPop Gremlin 3.3.2 and SPARQL 1.1. - -Release v1.13.57 (2018-05-29) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/pi`: Adds new service - -Release v1.13.56 (2018-05-25) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * This API update enables customers to control whether users can transfer data between their local devices and their streaming applications through file uploads and downloads, clipboard operations, or printing to local devices -* `service/config`: Updates service API and documentation -* `service/glue`: Updates service API and documentation - * AWS Glue now sends a delay notification to Amazon CloudWatch Events when an ETL job runs longer than the specified delay notification threshold. -* `service/iot`: Updates service API - * We are exposing DELETION_IN_PROGRESS as a new job status in regards to the release of DeleteJob API. - -Release v1.13.55 (2018-05-24) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API - * AWS CodeBuild Adds Support for Windows Builds. -* `service/elasticloadbalancingv2`: Updates service documentation -* `service/rds`: Updates service API and documentation - * This release adds CloudWatch Logs integration capabilities to RDS Aurora MySQL clusters -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager - -Release v1.13.54 (2018-05-22) -=== - -### Service Client Updates -* `service/ecs`: Updates service API and documentation - * Amazon Elastic Container Service (ECS) adds service discovery for services that use host or bridged network mode. ECS can now also register instance IPs for active tasks using bridged and host networking with Route 53, making them available via DNS. -* `service/inspector`: Updates service API - * We are launching the ability to target all EC2 instances. With this launch, resourceGroupArn is now optional for CreateAssessmentTarget and UpdateAssessmentTarget. If resourceGroupArn is not specified, all EC2 instances in the account in the AWS region are included in the assessment target. - -Release v1.13.53 (2018-05-21) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API and documentation - * 1) Filtered Update for StackSet based on Accounts and Regions: This feature will allow flexibility for the customers to roll out updates on a StackSet based on specific Accounts and Regions. 2) Support for customized ExecutionRoleName: This feature will allow customers to attach ExecutionRoleName to the StackSet thus ensuring more security and controlling the behavior of any AWS resources in the target accounts. - -Release v1.13.52 (2018-05-18) -=== - -### Service Client Updates -* `service/email`: Updates service documentation - * Fixed a broken link in the documentation for S3Action. -* `service/iot`: Updates service API and documentation - * We are releasing DeleteJob and DeleteJobExecution APIs to allow customer to delete resources created using AWS IoT Jobs. - -Release v1.13.51 (2018-05-17) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service documentation - * Documentation updates for codedeploy -* `service/cognito-idp`: Updates service API and documentation -* `service/ec2`: Updates service API and documentation - * You are now able to use instance storage (up to 1800 GB of NVMe based SSD) on C5 instances, the next generation of EC2's compute optimized instances in us-east-1, us-west-2, us-east-2, eu-west-1 and ca-central-1. C5 instances offer up to 72 vCPUs, 144 GiB of DDR4 instance memory, 25 Gbps in Network bandwidth and improved EBS and Networking bandwidth on smaller instance sizes to deliver improved performance for compute-intensive workloads.You can now run bare metal workloads on EC2 with i3.metal instances. As a new instance size belonging to the I3 instance family, i3.metal instances have the same characteristics as other instances in the family, including NVMe SSD-backed instance storage optimized for low latency, very high random I/O performance, and high sequential read throughput. I3.metal instances are powered by 2.3 GHz Intel Xeon processors, offering 36 hyper-threaded cores (72 logical processors), 512 GiB of memory, and 15.2 TB of NVMe SSD-backed instance storage. These instances deliver high networking throughput and lower latency with up to 25 Gbps of aggregate network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking. - -Release v1.13.50 (2018-05-16) -=== - -### Service Client Updates -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager -* `service/servicecatalog`: Updates service API and documentation - * Users can now pass a new option to ListAcceptedPortfolioShares called portfolio-share-type with a value of AWS_SERVICECATALOG in order to access Getting Started Portfolios that contain selected products representing common customer use cases. - -Release v1.13.49 (2018-05-15) -=== - -### Service Client Updates -* `service/config`: Updates service API - -Release v1.13.48 (2018-05-14) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Adding support for more override fields for StartBuild API, add support for idempotency token field for StartBuild API in AWS CodeBuild. -* `service/iot1click-devices`: Adds new service -* `service/iot1click-projects`: Adds new service -* `service/organizations`: Updates service documentation - * Documentation updates for organizations - -Release v1.13.47 (2018-05-10) -=== - -### Service Client Updates -* `service/firehose`: Updates service API and documentation - * With this release, Amazon Kinesis Data Firehose can convert the format of your input data from JSON to Apache Parquet or Apache ORC before storing the data in Amazon S3. Parquet and ORC are columnar data formats that save space and enable faster queries compared to row-oriented formats like JSON. - -Release v1.13.46 (2018-05-10) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/gamelift`: Updates service API and documentation - * AutoScaling Target Tracking scaling simplification along with StartFleetActions and StopFleetActions APIs to suspend and resume automatic scaling at will. - -Release v1.13.45 (2018-05-10) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Updating the regex for the NumericValue fields. -* `service/ec2`: Updates service API and documentation - * Enable support for latest flag with Get Console Output -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Changes to support the Aurora MySQL Backtrack feature. - -Release v1.13.44 (2018-05-08) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Enable support for specifying CPU options during instance launch. -* `service/rds`: Updates service documentation - * Correction to the documentation about copying unencrypted snapshots. - -Release v1.13.43 (2018-05-07) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API -* `service/budgets`: Updates service API and documentation - * "With this release, customers can use AWS Budgets to monitor how much of their Amazon EC2, Amazon RDS, Amazon Redshift, and Amazon ElastiCache instance usage is covered by reservations, and receive alerts when their coverage falls below the threshold they define." -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/es`: Updates service API, documentation, and paginators - * This change brings support for Reserved Instances to AWS Elasticsearch. -* `service/s3`: Updates service API and documentation - * Added BytesReturned details for Progress and Stats Events for Amazon S3 Select . - -Release v1.13.42 (2018-05-04) -=== - -### Service Client Updates -* `service/guardduty`: Updates service API, documentation, and paginators - * Amazon GuardDuty is adding five new API operations for creating and managing filters. For each filter, you can specify a criteria and an action. The action you specify is applied to findings that match the specified criteria. - -Release v1.13.41 (2018-05-03) -=== - -### Service Client Updates -* `service/appsync`: Updates service API and documentation -* `service/config`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager - -Release v1.13.40 (2018-05-02) -=== - -### Service Client Updates -* `service/acm`: Updates service documentation - * Documentation updates for acm -* `service/codepipeline`: Updates service API and documentation - * Added support for webhooks with accompanying definitions as needed in the AWS CodePipeline API Guide. -* `service/ec2`: Updates service API and documentation - * Amazon EC2 Fleet is a new feature that simplifies the provisioning of Amazon EC2 capacity across different EC2 instance types, Availability Zones, and the On-Demand, Reserved Instance, and Spot Instance purchase models. With a single API call, you can now provision capacity to achieve desired scale, performance, and cost. -* `service/ssm`: Updates service API and documentation - * Added support for new parameter, DocumentVersion, for SendCommand API. Users can now specify version of SSM document to be executed on the target(s). - -Release v1.13.39 (2018-04-30) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API, documentation, and paginators -* `service/dynamodb`: Updates service API and documentation - * Adds two new APIs UpdateGlobalTableSettings and DescribeGlobalTableSettings. This update introduces new constraints in the CreateGlobalTable and UpdateGlobalTable APIs . Tables must have the same write capacity units. If Global Secondary Indexes exist then they must have the same write capacity units and key schema. -* `service/guardduty`: Updates service API and documentation - * You can disable the email notification when inviting GuardDuty members using the disableEmailNotification parameter in the InviteMembers operation. -* `service/route53domains`: Updates service API and documentation - * This release adds a SubmittedSince attribute to the ListOperations API, so you can list operations that were submitted after a specified date and time. -* `service/sagemaker`: Updates service API and documentation - * SageMaker has added support for VPC configuration for both Endpoints and Training Jobs. This allows you to connect from the instances running the Endpoint or Training Job to your VPC and any resources reachable in the VPC rather than being restricted to resources that were internet accessible. -* `service/workspaces`: Updates service API and documentation - * Added new IP Access Control APIs, an API to change the state of a Workspace, and the ADMIN_MAINTENANCE WorkSpace state. With the new IP Access Control APIs, you can now create/delete IP Access Control Groups, add/delete/update rules for IP Access Control Groups, Associate/Disassociate IP Access Control Groups to/from a WorkSpaces Directory, and Describe IP Based Access Control Groups. - -Release v1.13.38 (2018-04-26) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service documentation - * Documentation updates for Glacier to fix a broken link -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager - -Release v1.13.37 (2018-04-25) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * AWS CodeDeploy has a new exception that indicates when a GitHub token is not valid. -* `service/rekognition`: Updates service documentation - * Documentation updates for Amazon Rekognition. -* `service/xray`: Updates service API and documentation - * Added PutEncryptionConfig and GetEncryptionConfig APIs for managing data encryption settings. Use PutEncryptionConfig to configure X-Ray to use an AWS Key Management Service customer master key to encrypt trace data at rest. - -Release v1.13.36 (2018-04-24) -=== - -### Service Client Updates -* `service/elasticbeanstalk`: Updates service API and documentation - * Support tracking Elastic Beanstalk resources in AWS Config. -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager - -Release v1.13.35 (2018-04-23) -=== - -### Service Client Updates -* `service/autoscaling-plans`: Updates service API and documentation -* `service/iot`: Updates service API and documentation - * Add IotAnalyticsAction which sends message data to an AWS IoT Analytics channel -* `service/iotanalytics`: Adds new service - -### SDK Enhancements -* `aws/endpoints`: Add Get Region description to endpoints package ([#1909](https://github.com/aws/aws-sdk-go/pull/1909)) - * Adds exposing the description field of the endpoints Region struct. - * Fixes [#1194](https://github.com/aws/aws-sdk-go/issues/1194) - -### SDK Bugs -* Fix XML unmarshaler not correctly unmarshaling list of timestamp values ([#1894](https://github.com/aws/aws-sdk-go/pull/1894)) - * Fixes a bug in the XML unmarshaler that would incorrectly try to unmarshal "time.Time" parameters that did not have the struct tag type on them. This would occur for nested lists like CloudWatch's GetMetricDataResponse MetricDataResults timestamp parameters. - * Fixes [#1892](https://github.com/aws/aws-sdk-go/issues/1892) -Release v1.13.34 (2018-04-20) -=== - -### Service Client Updates -* `service/firehose`: Updates service API and documentation - * With this release, Amazon Kinesis Data Firehose allows you to tag your delivery streams. Tags are metadata that you can create and use to manage your delivery streams. For more information about tagging, see AWS Tagging Strategies. For technical documentation, look for the tagging operations in the Amazon Kinesis Firehose API reference. -* `service/medialive`: Updates service API and documentation - * With AWS Elemental MediaLive you can now output live channels as RTMP (Real-Time Messaging Protocol) and RTMPS as the encrypted version of the protocol (Secure, over SSL/TLS). RTMP is the preferred protocol for sending live streams to popular social platforms which means you can send live channel content to social and sharing platforms in a secure and reliable way while continuing to stream to your own website, app or network. - -Release v1.13.33 (2018-04-19) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/codepipeline`: Updates service API and documentation - * Added new SourceRevision structure to Execution Summary with accompanying definitions as needed in the AWS CodePipeline API Guide. -* `service/devicefarm`: Updates service API and documentation - * Adding support for VPCEndpoint feature. Allows customers to be able to access their private endpoints/services running in their VPC during test automation. -* `service/ec2`: Updates service API and documentation - * Added support for customers to see the time at which a Dedicated Host was allocated or released. -* `service/rds`: Updates service API and documentation - * The ModifyDBCluster operation now includes an EngineVersion parameter. You can use this to upgrade the engine for a clustered database. -* `service/secretsmanager`: Updates service documentation and examples - * Documentation updates -* `service/ssm`: Updates service API and documentation - * Added new APIs DeleteInventory and DescribeInventoryDeletions, for customers to delete their custom inventory data. - -Release v1.13.32 (2018-04-10) -=== - -### Service Client Updates -* `service/dms`: Updates service API and documentation - * Native Change Data Capture start point and task recovery support in Database Migration Service. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glue`: Updates service API and documentation - * "AWS Glue now supports timeout values for ETL jobs. With this release, all new ETL jobs have a default timeout value of 48 hours. AWS Glue also now supports the ability to start a schedule or job events trigger when it is created." -* `service/mediapackage`: Updates service API and documentation - * Adds a new OriginEndpoint package type CmafPackage in MediaPackage. Origin endpoints can now be configured to use the Common Media Application Format (CMAF) media streaming format. This version of CmafPackage only supports HTTP Live Streaming (HLS) manifests with fragmented MP4. -* `service/ssm`: Updates service API and documentation - * Added TooManyUpdates exception for AddTagsToResource and RemoveTagsFromResource API -* `service/workmail`: Updates service API, documentation, and paginators - * Amazon WorkMail adds the ability to grant users and groups with "Full Access", "Send As" and "Send on Behalf" permissions on a given mailbox. - -Release v1.13.31 (2018-04-09) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Cloud Directory customers can fetch attributes within a facet on an object with the new GetObjectAttributes API and can fetch attributes from multiple facets or objects with the BatchGetObjectAttributes operation. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.30 (2018-04-06) -=== - -### Service Client Updates -* `service/batch`: Updates service API and documentation - * Support for Timeout in SubmitJob and RegisterJobDefinition - -Release v1.13.29 (2018-04-05) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/ssm`: Updates service documentation - -Release v1.13.28 (2018-04-04) -=== - -### Service Client Updates -* `service/acm`: Updates service API and documentation - * AWS Certificate Manager has added support for AWS Certificate Manager Private Certificate Authority (CA). Customers can now request private certificates with the RequestCertificate API, and also export private certificates with the ExportCertificate API. -* `service/acm-pca`: Adds new service -* `service/config`: Updates service API and documentation -* `service/fms`: Adds new service -* `service/monitoring`: Updates service API and documentation - * The new GetMetricData API enables you to collect batch amounts of metric data and optionally perform math expressions on the data. With one GetMetricData call you can retrieve as many as 100 different metrics and a total of 100,800 data points. -* `service/s3`: Updates service API and documentation - * ONEZONE_IA storage class stores object data in only one Availability Zone at a lower price than STANDARD_IA. This SDK release provides API support for this new storage class. -* `service/sagemaker`: Updates service API and documentation - * SageMaker is now supporting many additional instance types in previously supported families for Notebooks, Training Jobs, and Endpoints. Training Jobs and Endpoints now support instances in the m5 family in addition to the previously supported instance families. For specific instance types supported please see the documentation for the SageMaker API. -* `service/secretsmanager`: Adds new service - * AWS Secrets Manager enables you to easily create and manage the secrets that you use in your customer-facing apps. Instead of embedding credentials into your source code, you can dynamically query Secrets Manager from your app whenever you need credentials. You can automatically and frequently rotate your secrets without having to deploy updates to your apps. All secret values are encrypted when they're at rest with AWS KMS, and while they're in transit with HTTPS and TLS. -* `service/transcribe`: Updates service API, documentation, and paginators - -Release v1.13.27 (2018-04-03) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * Added Private Device Management feature. Customers can now manage their private devices efficiently - view their status, set labels and apply profiles on them. Customers can also schedule automated tests and remote access sessions on individual instances in their private device fleet. -* `service/lambda`: Updates service API and documentation - * added nodejs8.10 as a valid runtime -* `service/translate`: Updates service API and documentation - -Release v1.13.26 (2018-04-02) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Amazon API Gateway now supports resource policies for APIs making it easier to set access controls for invoking APIs. -* `service/cloudfront`: Adds new service - * You can now use a new Amazon CloudFront capability called Field-Level Encryption to further enhance the security of sensitive data, such as credit card numbers or personally identifiable information (PII) like social security numbers. CloudFront's field-level encryption further encrypts sensitive data in an HTTPS form using field-specific encryption keys (which you supply) before a POST request is forwarded to your origin. This ensures that sensitive data can only be decrypted and viewed by certain components or services in your application stack. Field-level encryption is easy to setup. Simply configure the fields that have to be further encrypted by CloudFront using the public keys you specify and you can reduce attack surface for your sensitive data. -* `service/es`: Updates service API and documentation - * This adds Amazon Cognito authentication support to Kibana. - -Release v1.13.25 (2018-03-30) -=== - -### Service Client Updates -* `service/acm`: Updates service API and documentation - * Documentation updates for acm -* `service/connect`: Adds new service -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.24 (2018-03-29) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API, documentation, and paginators -* `service/cloudformation`: Updates service API and documentation - * Enabling resource level permission control for StackSets APIs. Adding support for customers to use customized AdministrationRole to create security boundaries between different users. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/greengrass`: Updates service API and documentation - * Greengrass APIs now support creating Machine Learning resource types and configuring binary data as the input payload for Greengrass Lambda functions. -* `service/ssm`: Updates service API - * This Patch Manager release supports creating patch baselines for CentOS. - -Release v1.13.23 (2018-03-28) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iam`: Updates service API and documentation - * Add support for Longer Role Sessions. Four APIs manage max session duration: GetRole, ListRoles, CreateRole, and the new API UpdateRole. The max session duration integer attribute is measured in seconds. -* `service/mturk-requester`: Updates service API and documentation -* `service/sts`: Updates service API and documentation - * Change utilizes the Max Session Duration attribute introduced for IAM Roles and allows STS customers to request session duration up to the Max Session Duration of 12 hours from AssumeRole based APIs. - -Release v1.13.22 (2018-03-27) -=== - -### Service Client Updates -* `service/acm`: Updates service API and documentation - * AWS Certificate Manager has added support for customers to disable Certificate Transparency logging on a per-certificate basis. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.21 (2018-03-26) -=== - -### Service Client Updates -* `service/dynamodb`: Updates service API and documentation - * Point-in-time recovery (PITR) provides continuous backups of your DynamoDB table data. With PITR, you do not have to worry about creating, maintaining, or scheduling backups. You enable PITR on your table and your backup is available for restore at any point in time from the moment you enable it, up to a maximum of the 35 preceding days. PITR provides continuous backups until you explicitly disable it. For more information, see the Amazon DynamoDB Developer Guide. - -Release v1.13.20 (2018-03-23) -=== - -### Service Client Updates -* `service/rds`: Updates service documentation - * Documentation updates for RDS - -Release v1.13.19 (2018-03-22) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Feedback URL allows admins to provide a feedback link or a survey link for collecting user feedback while streaming sessions. When a feedback link is provided, streaming users will see a "Send Feedback" choice in their streaming session toolbar. On selecting this choice, user will be redirected to the link provided in a new browser tab. If a feedback link is not provided, users will not see the "Send Feedback" option. -* `service/codebuild`: Updates service API and documentation - * Adding support for branch filtering when using webhooks with AWS CodeBuild. -* `service/ecs`: Updates service API and documentation - * Amazon Elastic Container Service (ECS) now includes integrated Service Discovery using Route 53 Auto Naming. Customers can now specify a Route 53 Auto Naming service as part of an ECS service. ECS will register task IPs with Route 53, making them available via DNS in your VPC. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -### SDK Bugs -* `aws/endpoints`: Use service metadata for fallback signing name ([#1854](https://github.com/aws/aws-sdk-go/pull/1854)) - * Updates the SDK's endpoint resolution to fallback deriving the service's signing name from the service's modeled metadata in addition the endpoints modeled data. - * Fixes [#1850](https://github.com/aws/aws-sdk-go/issues/1850) -Release v1.13.18 (2018-03-21) -=== - -### Service Client Updates -* `service/serverlessrepo`: Updates service documentation - -Release v1.13.17 (2018-03-20) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/config`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - * Amazon ECS users can now mount a temporary volume in memory in containers and specify the shared memory that a container can use through the use of docker's 'tmpfs' and 'shm-size' features respectively. These fields can be specified under linuxParameters in ContainerDefinition in the Task Definition Template. -* `service/elasticbeanstalk`: Updates service documentation - * Documentation updates for the new Elastic Beanstalk API DescribeAccountAttributes. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/events`: Updates service API and documentation - * Added SQS FIFO queue target support -* `service/glue`: Updates service API and documentation - * API Updates for DevEndpoint: PublicKey is now optional for CreateDevEndpoint. The new DevEndpoint field PrivateAddress will be populated for DevEndpoints associated with a VPC. -* `service/medialive`: Updates service API and documentation - * AWS Elemental MediaLive has added support for updating Inputs and Input Security Groups. You can update Input Security Groups at any time and it will update all channels using that Input Security Group. Inputs can be updated as long as they are not attached to a currently running channel. - -Release v1.13.16 (2018-03-16) -=== - -### Service Client Updates -* `service/elasticbeanstalk`: Updates service API and documentation - * AWS Elastic Beanstalk is launching a new public API named DescribeAccountAttributes which allows customers to access account level attributes. In this release, the API will support quotas for resources such as applications, application versions, and environments. - -Release v1.13.15 (2018-03-15) -=== - -### Service Client Updates -* `service/organizations`: Updates service API and documentation - * This release adds additional reason codes to improve clarity to exceptions that can occur. -* `service/pinpoint`: Updates service API and documentation - * With this release, you can delete endpoints from your Amazon Pinpoint projects. Customers can now specify one of their leased dedicated long or short codes to send text messages. -* `service/sagemaker`: Updates service API, documentation, and paginators - * This release provides support for ml.p3.xlarge instance types for notebook instances. Lifecycle configuration is now available to customize your notebook instances on start; the configuration can be reused between multiple notebooks. If a notebook instance is attached to a VPC you can now opt out of internet access that by default is provided by SageMaker. - -Release v1.13.14 (2018-03-14) -=== - -### Service Client Updates -* `service/lightsail`: Updates service API and documentation - * Updates to existing Lightsail documentation - -Release v1.13.13 (2018-03-13) -=== - -### Service Client Updates -* `service/servicediscovery`: Updates service API and documentation - * This release adds support for custom health checks, which let you check the health of resources that aren't accessible over the internet. For example, you can use a custom health check when the instance is in an Amazon VPC. - -Release v1.13.12 (2018-03-12) -=== - -### Service Client Updates -* `service/cloudhsmv2`: Updates service API - * CreateCluster can now take both 8 and 17 character Subnet IDs. DeleteHsm can now take both 8 and 17 character ENI IDs. -* `service/discovery`: Updates service API and documentation - * Documentation updates for discovery -* `service/iot`: Updates service API and documentation - * We added new fields to the response of the following APIs. (1) describe-certificate: added new generationId, customerVersion fields (2) describe-ca-certificate: added new generationId, customerVersion and lastModifiedDate fields (3) get-policy: added generationId, creationDate and lastModifiedDate fields -* `service/redshift`: Updates service API and documentation - * DescribeClusterSnapshotsMessage with ClusterExists flag returns snapshots of existing clusters. Else both existing and deleted cluster snapshots are returned - -Release v1.13.11 (2018-03-08) -=== - -### Service Client Updates -* `service/AWSMigrationHub`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - * Amazon Elastic Container Service (ECS) now supports container health checks. Customers can now specify a docker container health check command and parameters in their task definition. ECS will monitor, report and take scheduling action based on the health status. -* `service/pinpoint`: Updates service API and documentation - * With this release, you can export endpoints from your Amazon Pinpoint projects. You can export a) all of the endpoints assigned to a project or b) the subset of endpoints assigned to a segment. -* `service/rds`: Updates service documentation - * Documentation updates for RDS - -Release v1.13.10 (2018-03-07) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/medialive`: Updates service API and documentation - * Updates API to model required traits and minimum/maximum constraints. - -Release v1.13.9 (2018-03-06) -=== - -### Service Client Updates -* `service/ecs`: Updates service documentation - * Documentation updates for Amazon ECS -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.8 (2018-03-01) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Added support for modifying Placement Group association of instances via ModifyInstancePlacement API. -* `service/events`: Updates service API and documentation - * Added BatchParameters to the PutTargets API -* `service/servicecatalog`: Updates service API and documentation - * This release of ServiceCatalog adds the DeleteTagOption API. -* `service/ssm`: Updates service API and documentation - * This Inventory release supports the status message details reported by the last sync for the resource data sync API. -* `service/storagegateway`: Updates service API and documentation - * AWS Storage Gateway (File) support for two new file share attributes are added. 1. Users can specify the S3 Canned ACL to use for new objects created in the file share. 2. Users can create file shares for requester-pays buckets. - -Release v1.13.7 (2018-02-28) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.6 (2018-02-27) -=== - -### Service Client Updates -* `service/ecr`: Updates service documentation - * Documentation updates for Amazon ECR. - -Release v1.13.5 (2018-02-26) -=== - -### Service Client Updates -* `service/route53`: Updates service API - * Added support for creating LBR rules using ap-northeast-3 region. -* `service/sts`: Updates service API and documentation - * Increased SAMLAssertion parameter size from 50000 to 100000 for AWS Security Token Service AssumeRoleWithSAML API to allow customers to pass bigger SAML assertions - -Release v1.13.4 (2018-02-23) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * This API update is to enable customers to copy their Amazon AppStream 2.0 images within and between AWS Regions -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.3 (2018-02-22) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/elasticloadbalancingv2`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.2 (2018-02-21) -=== - -### Service Client Updates -* `service/codecommit`: Updates service API and documentation - * This release adds an API for adding a file directly to an AWS CodeCommit repository without requiring a Git client. -* `service/ec2`: Updates service API and documentation - * Adds support for tagging an EBS snapshot as part of the API call that creates the EBS snapshot -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/serverlessrepo`: Updates service API, documentation, and paginators - -Release v1.13.1 (2018-02-20) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * Amazon EC2 Auto Scaling support for service-linked roles -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/waf`: Updates service API and documentation - * The new PermissionPolicy APIs in AWS WAF Regional allow customers to attach resource-based policies to their entities. -* `service/waf-regional`: Updates service API and documentation - -Release v1.13.0 (2018-02-19) -=== - -### Service Client Updates -* `service/config`: Updates service API - * With this release, AWS Config updated the ConfigurationItemStatus enum values. The values prior to this update did not represent appropriate values returned by GetResourceConfigHistory. You must update your code to enumerate the new enum values so this is a breaking change. To map old properties to new properties, use the following descriptions: New discovered resource - Old property: Discovered, New property: ResourceDiscovered. Updated resource - Old property: Ok, New property: OK. Deleted resource - Old property: Deleted, New property: ResourceDeleted or ResourceDeletedNotRecorded. Not-recorded resource - Old property: N/A, New property: ResourceNotRecorded or ResourceDeletedNotRecorded. - -Release v1.12.79 (2018-02-16) -=== - -### Service Client Updates -* `service/rds`: Updates service API and documentation - * Updates RDS API to indicate whether a DBEngine supports read replicas. - -Release v1.12.78 (2018-02-15) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/gamelift`: Updates service API and documentation - * Updates to allow Fleets to run on On-Demand or Spot instances. -* `service/mediaconvert`: Updates service API and documentation - * Nielsen ID3 tags can now be inserted into transport stream (TS) and HLS outputs. For more information on Nielsen configuration you can go to https://docs.aws.amazon.com/mediaconvert/latest/apireference/jobs.html#jobs-nielsenconfiguration - -Release v1.12.77 (2018-02-14) -=== - -### Service Client Updates -* `service/appsync`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lex-models`: Updates service API and documentation - -Release v1.12.76 (2018-02-13) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service documentation - * Documentation updates for glacier -* `service/route53`: Updates service API - * Added support for creating Private Hosted Zones and metric-based healthchecks in the ap-northeast-3 region for whitelisted customers. - -Release v1.12.75 (2018-02-12) -=== - -### Service Client Updates -* `service/cognito-idp`: Updates service API and documentation -* `service/ec2`: Updates service API and documentation - * Network interfaces now supply the following additional status of "associated" to better distinguish the current status. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/guardduty`: Updates service API and documentation - * Added PortProbeAction information to the Action section of the port probe-type finding. -* `service/kms`: Updates service API - * This release of AWS Key Management Service includes support for InvalidArnException in the RetireGrant API. -* `service/rds`: Updates service documentation - * Aurora MySQL now supports MySQL 5.7. - -Release v1.12.74 (2018-02-09) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Users can now better understand the longer ID opt-in status of their account using the two new APIs DescribeAggregateIdFormat and DescribePrincipalIdFormat -* `service/lex-models`: Updates service API and documentation -* `service/runtime.lex`: Updates service API and documentation - -Release v1.12.73 (2018-02-08) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Adds support for allowing customers to provide a redirect URL for a stack. Users will be redirected to the link provided by the admin at the end of their streaming session. -* `service/budgets`: Updates service API and documentation - * Making budgetLimit and timePeriod optional, and updating budgets docs. -* `service/dms`: Updates service API, documentation, and paginators - * This release includes the addition of two new APIs: describe replication instance task logs and reboot instance. The first allows user to see how much storage each log for a task on a given instance is occupying. The second gives users the option to reboot the application software on the instance and force a fail over for MAZ instances to test robustness of their integration with our service. -* `service/ds`: Updates service API - * Updated the regex of some input parameters to support longer EC2 identifiers. -* `service/dynamodb`: Updates service API and documentation - * Amazon DynamoDB now supports server-side encryption using a default service key (alias/aws/dynamodb) from the AWS Key Management Service (KMS). AWS KMS is a service that combines secure, highly available hardware and software to provide a key management system scaled for the cloud. AWS KMS is used via the AWS Management Console or APIs to centrally create encryption keys, define the policies that control how keys can be used, and audit key usage to prove they are being used correctly. For more information, see the Amazon DynamoDB Developer Guide. -* `service/gamelift`: Updates service API and documentation - * Amazon GameLift FlexMatch added the StartMatchBackfill API. This API allows developers to add new players to an existing game session using the same matchmaking rules and player data that were used to initially create the session. -* `service/medialive`: Updates service API and documentation - * AWS Elemental MediaLive has added support for updating channel settings for idle channels. You can now update channel name, channel outputs and output destinations, encoder settings, user role ARN, and input specifications. Channel settings can be updated in the console or with API calls. Please note that running channels need to be stopped before they can be updated. We've also deprecated the 'Reserved' field. -* `service/mediastore`: Updates service API and documentation - * AWS Elemental MediaStore now supports per-container CORS configuration. - -Release v1.12.72 (2018-02-07) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glue`: Updates service API and documentation - * This new feature will now allow customers to add a customized json classifier. They can specify a json path to indicate the object, array or field of the json documents they'd like crawlers to inspect when they crawl json files. -* `service/servicecatalog`: Updates service API, documentation, and paginators - * This release of Service Catalog adds SearchProvisionedProducts API and ProvisionedProductPlan APIs. -* `service/servicediscovery`: Updates service API and documentation - * This release adds support for registering CNAME record types and creating Route 53 alias records that route traffic to Amazon Elastic Load Balancers using Amazon Route 53 Auto Naming APIs. -* `service/ssm`: Updates service API and documentation - * This Patch Manager release supports configuring Linux repos as part of patch baselines, controlling updates of non-OS security packages and also creating patch baselines for SUSE12 - -### SDK Enhancements -* `private/model/api`: Add validation to ensure there is no duplication of services in models/apis ([#1758](https://github.com/aws/aws-sdk-go/pull/1758)) - * Prevents the SDK from mistakenly generating code a single service multiple times with different model versions. -* `example/service/ec2/instancesbyRegion`: Fix typos in example ([#1762](https://github.com/aws/aws-sdk-go/pull/1762)) -* `private/model/api`: removing SDK API reference crosslinks from input/output shapes. (#1765) - -### SDK Bugs -* `aws/session`: Fix bug in session.New not supporting AWS_SDK_LOAD_CONFIG ([#1770](https://github.com/aws/aws-sdk-go/pull/1770)) - * Fixes a bug in the session.New function that was not correctly sourcing the shared configuration files' path. - * Fixes [#1771](https://github.com/aws/aws-sdk-go/pull/1771) -Release v1.12.71 (2018-02-05) -=== - -### Service Client Updates -* `service/acm`: Updates service documentation - * Documentation updates for acm -* `service/cloud9`: Updates service documentation and examples - * API usage examples for AWS Cloud9. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kinesis`: Updates service API and documentation - * Using ListShards a Kinesis Data Streams customer or client can get information about shards in a data stream (including meta-data for each shard) without obtaining data stream level information. -* `service/opsworks`: Updates service API, documentation, and waiters - * AWS OpsWorks Stacks supports EBS encryption and HDD volume types. Also, a new DescribeOperatingSystems API is available, which lists all operating systems supported by OpsWorks Stacks. - -Release v1.12.70 (2018-01-26) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * Add InteractionMode in CreateRemoteAccessSession for DirectDeviceAccess feature. -* `service/medialive`: Updates service API and documentation - * Add InputSpecification to CreateChannel (specification of input attributes is used for channel sizing and affects pricing); add NotFoundException to DeleteInputSecurityGroups. -* `service/mturk-requester`: Updates service documentation - -Release v1.12.69 (2018-01-26) -=== - -### SDK Bugs -* `models/api`: Fix colliding names [#1754](https://github.com/aws/aws-sdk-go/pull/1754) [#1756](https://github.com/aws/aws-sdk-go/pull/1756) - * SDK had duplicate folders that were causing errors in some builds. - * Fixes [#1753](https://github.com/aws/aws-sdk-go/issues/1753) -Release v1.12.68 (2018-01-25) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API and documentation -* `service/codebuild`: Updates service API and documentation - * Adding support for Shallow Clone and GitHub Enterprise in AWS CodeBuild. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/guardduty`: Adds new service - * Added the missing AccessKeyDetails object to the resource shape. -* `service/lambda`: Updates service API and documentation - * AWS Lambda now supports Revision ID on your function versions and aliases, to track and apply conditional updates when you are updating your function version or alias resources. - -### SDK Bugs -* `service/s3/s3manager`: Fix check for nil OrigErr in Error() [#1749](https://github.com/aws/aws-sdk-go/issues/1749) - * S3 Manager's `Error` type did not check for nil of `OrigErr` when calling `Error()` - * Fixes [#1748](https://github.com/aws/aws-sdk-go/issues/1748) -Release v1.12.67 (2018-01-22) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Add additional costTypes: IncludeDiscount, UseAmortized, to support finer control for different charges included in a cost budget. - -Release v1.12.66 (2018-01-19) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glue`: Updates service API and documentation - * New AWS Glue DataCatalog APIs to manage table versions and a new feature to skip archiving of the old table version when updating table. -* `service/transcribe`: Adds new service - -Release v1.12.65 (2018-01-18) -=== - -### Service Client Updates -* `service/sagemaker`: Updates service API and documentation - * CreateTrainingJob and CreateEndpointConfig now supports KMS Key for volume encryption. - -Release v1.12.64 (2018-01-17) -=== - -### Service Client Updates -* `service/autoscaling-plans`: Updates service documentation -* `service/ec2`: Updates service documentation - * Documentation updates for EC2 - -Release v1.12.63 (2018-01-17) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/autoscaling-plans`: Adds new service -* `service/rds`: Updates service API and documentation - * With this release you can now integrate RDS DB instances with CloudWatch Logs. We have added parameters to the operations for creating and modifying DB instances (for example CreateDBInstance) to allow you to take advantage of this capability through the CLI and API. Once you enable this feature, a stream of log events will publish to CloudWatch Logs for each log type you enable. - -Release v1.12.62 (2018-01-15) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lambda`: Updates service API and documentation - * Support for creating Lambda Functions using 'dotnetcore2.0' and 'go1.x'. - -Release v1.12.61 (2018-01-12) -=== - -### Service Client Updates -* `service/glue`: Updates service API and documentation - * Support is added to generate ETL scripts in Scala which can now be run by AWS Glue ETL jobs. In addition, the trigger API now supports firing when any conditions are met (in addition to all conditions). Also, jobs can be triggered based on a "failed" or "stopped" job run (in addition to a "succeeded" job run). - -Release v1.12.60 (2018-01-11) -=== - -### Service Client Updates -* `service/elasticloadbalancing`: Updates service API and documentation -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `service/rds`: Updates service API and documentation - * Read Replicas for Amazon RDS for MySQL, MariaDB, and PostgreSQL now support Multi-AZ deployments.Amazon RDS Read Replicas enable you to create one or more read-only copies of your database instance within the same AWS Region or in a different AWS Region. Updates made to the source database are asynchronously copied to the Read Replicas. In addition to providing scalability for read-heavy workloads, you can choose to promote a Read Replica to become standalone a DB instance when needed.Amazon RDS Multi-AZ Deployments provide enhanced availability for database instances within a single AWS Region. With Multi-AZ, your data is synchronously replicated to a standby in a different Availability Zone (AZ). In case of an infrastructure failure, Amazon RDS performs an automatic failover to the standby, minimizing disruption to your applications.You can now combine Read Replicas with Multi-AZ as part of a disaster recovery strategy for your production databases. A well-designed and tested plan is critical for maintaining business continuity after a disaster. Since Read Replicas can also be created in different regions than the source database, your Read Replica can be promoted to become the new production database in case of a regional disruption.You can also combine Read Replicas with Multi-AZ for your database engine upgrade process. You can create a Read Replica of your production database instance and upgrade it to a new database engine version. When the upgrade is complete, you can stop applications, promote the Read Replica to a standalone database instance and switch over your applications. Since the database instance is already a Multi-AZ deployment, no additional steps are needed.For more information, see the Amazon RDS User Guide. -* `service/ssm`: Updates service documentation - * Updates documentation for the HierarchyLevelLimitExceededException error. - -Release v1.12.59 (2018-01-09) -=== - -### Service Client Updates -* `service/kms`: Updates service documentation - * Documentation updates for AWS KMS - -Release v1.12.58 (2018-01-09) -=== - -### Service Client Updates -* `service/ds`: Updates service API and documentation - * On October 24 we introduced AWS Directory Service for Microsoft Active Directory (Standard Edition), also known as AWS Microsoft AD (Standard Edition), which is a managed Microsoft Active Directory (AD) that is optimized for small and midsize businesses (SMBs). With this SDK release, you can now create an AWS Microsoft AD directory using API. This enables you to run typical SMB workloads using a cost-effective, highly available, and managed Microsoft AD in the AWS Cloud. - -Release v1.12.57 (2018-01-08) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * The AWS CodeDeploy API was updated to support DeleteGitHubAccountToken, a new method that deletes a GitHub account connection. -* `service/discovery`: Updates service API and documentation - * Documentation updates for AWS Application Discovery Service. -* `service/route53`: Updates service API and documentation - * This release adds an exception to the CreateTrafficPolicyVersion API operation. - -Release v1.12.56 (2018-01-05) -=== - -### Service Client Updates -* `service/inspector`: Updates service API, documentation, and examples - * Added 2 new attributes to the DescribeAssessmentTemplate response, indicating the total number of assessment runs and last assessment run ARN (if present.) -* `service/snowball`: Updates service documentation - * Documentation updates for snowball -* `service/ssm`: Updates service documentation - * Documentation updates for ssm - -Release v1.12.55 (2018-01-02) -=== - -### Service Client Updates -* `service/rds`: Updates service documentation - * Documentation updates for rds - -Release v1.12.54 (2017-12-29) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/workspaces`: Updates service API and documentation - * Modify WorkSpaces have been updated with flexible storage and switching of hardware bundles feature. The following configurations have been added to ModifyWorkSpacesProperties: storage and compute. This update provides the capability to configure the storage of a WorkSpace. It also adds the capability of switching hardware bundle of a WorkSpace by specifying an eligible compute (Value, Standard, Performance, Power). - -Release v1.12.53 (2017-12-22) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * This release fixes an issue with tags not showing in DescribeAddresses responses. -* `service/ecs`: Updates service API and documentation - * Amazon ECS users can now set a health check initialization wait period of their ECS services, the services that are associated with an Elastic Load Balancer (ELB) will wait for a period of time before the ELB become healthy. You can now configure this in Create and Update Service. -* `service/inspector`: Updates service API and documentation - * PreviewAgents API now returns additional fields within the AgentPreview data type. The API now shows the agent health and availability status for all instances included in the assessment target. This allows users to check the health status of Inspector Agents before running an assessment. In addition, it shows the instance ID, hostname, and IP address of the targeted instances. -* `service/sagemaker`: Updates service API and documentation - * SageMaker Models no longer support SupplementalContainers. API's that have been affected are CreateModel and DescribeModel. - -Release v1.12.52 (2017-12-21) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Adding support allowing AWS CodeBuild customers to select specific curated image versions. -* `service/ec2`: Updates service API and documentation - * Elastic IP tagging enables you to add key and value metadata to your Elastic IPs so that you can search, filter, and organize them according to your organization's needs. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kinesisanalytics`: Updates service API and documentation - * Kinesis Analytics now supports AWS Lambda functions as output. - -Release v1.12.51 (2017-12-21) -=== - -### Service Client Updates -* `service/config`: Updates service API -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iot`: Updates service API and documentation - * This release adds support for code signed Over-the-air update functionality for Amazon FreeRTOS. Users can now create and schedule Over-the-air updates to their Amazon FreeRTOS devices using these new APIs. - -Release v1.12.50 (2017-12-19) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * API Gateway now adds support for calling API with compressed payloads using one of the supported content codings, tagging an API stage for cost allocation, and returning API keys from a custom authorizer for use with a usage plan. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/mediastore-data`: Updates service documentation -* `service/route53`: Updates service API and documentation - * Route 53 added support for a new China (Ningxia) region, cn-northwest-1. You can now specify cn-northwest-1 as the region for latency-based or geoproximity routing. Route 53 also added support for a new EU (Paris) region, eu-west-3. You can now associate VPCs in eu-west-3 with private hosted zones and create alias records that route traffic to resources in eu-west-3. - -Release v1.12.49 (2017-12-19) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/monitoring`: Updates service documentation - * Documentation updates for monitoring - -Release v1.12.48 (2017-12-15) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * This API update is to enable customers to add tags to their Amazon AppStream 2.0 resources - -Release v1.12.47 (2017-12-14) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Adds support for Cognito Authorizer scopes at the API method level. -* `service/email`: Updates service documentation - * Added information about the maximum number of transactions per second for the SendCustomVerificationEmail operation. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.46 (2017-12-12) -=== - -### Service Client Updates -* `service/workmail`: Adds new service - * Today, Amazon WorkMail released an administrative SDK and enabled AWS CloudTrail integration. With the administrative SDK, you can natively integrate WorkMail with your existing services. The SDK enables programmatic user, resource, and group management through API calls. This means your existing IT tools and workflows can now automate WorkMail management, and third party applications can streamline WorkMail migrations and account actions. - -Release v1.12.45 (2017-12-11) -=== - -### Service Client Updates -* `service/cognito-idp`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lex-models`: Updates service API and documentation -* `service/sagemaker`: Updates service API - * CreateModel API Update: The request parameter 'ExecutionRoleArn' has changed from optional to required. - -Release v1.12.44 (2017-12-08) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * This API update is to support the feature that allows customers to automatically consume the latest Amazon AppStream 2.0 agent as and when published by AWS. -* `service/ecs`: Updates service documentation - * Documentation updates for Windows containers. -* `service/monitoring`: Updates service API and documentation - * With this launch, you can now create a CloudWatch alarm that alerts you when M out of N datapoints of a metric are breaching your predefined threshold, such as three out of five times in any given five minutes interval or two out of six times in a thirty minutes interval. When M out of N datapoints are not breaching your threshold in an interval, the alarm will be in OK state. Please note that the M datapoints out of N datapoints in an interval can be of any order and does not need to be consecutive. Consequently, you can now get alerted even when the spikes in your metrics are intermittent over an interval. - -Release v1.12.43 (2017-12-07) -=== - -### Service Client Updates -* `service/email`: Updates service API, documentation, and paginators - * Customers can customize the emails that Amazon SES sends when verifying new identities. This feature is helpful for developers whose applications send email through Amazon SES on behalf of their customers. -* `service/es`: Updates service API and documentation - * Added support for encryption of data at rest on Amazon Elasticsearch Service using AWS KMS - -### SDK Bugs -* `models/apis` Fixes removes colliding sagemaker models folders ([#1686](https://github.com/aws/aws-sdk-go/pull/1686)) - * Fixes Release v1.12.42's SageMaker vs sagemaker model folders. -Release v1.12.42 (2017-12-06) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Amazon Cloud Directory makes it easier for you to apply schema changes across your directories with in-place schema upgrades. Your directories now remain available while backward-compatible schema changes are being applied, such as the addition of new fields. You also can view the history of your schema changes in Cloud Directory by using both major and minor version identifiers, which can help you track and audit schema versions across directories. -* `service/elasticbeanstalk`: Updates service documentation - * Documentation updates for AWS Elastic Beanstalk. -* `service/sagemaker`: Adds new service - * Initial waiters for common SageMaker workflows. - -Release v1.12.41 (2017-12-05) -=== - -### Service Client Updates -* `service/iot`: Updates service API and documentation - * Add error action API for RulesEngine. -* `service/servicecatalog`: Updates service API and documentation - * ServiceCatalog has two distinct personas for its use, an "admin" persona (who creates sets of products with different versions and prescribes who has access to them) and an "end-user" persona (who can launch cloud resources based on the configuration data their admins have given them access to). This API update will allow admin users to deactivate/activate product versions, end-user will only be able to access and launch active product versions. -* `service/servicediscovery`: Adds new service - * Amazon Route 53 Auto Naming lets you configure public or private namespaces that your microservice applications run in. When instances of the service become available, you can call the Auto Naming API to register the instance, and Amazon Route 53 automatically creates up to five DNS records and an optional health check. Clients that submit DNS queries for the service receive an answer that contains up to eight healthy records. - -Release v1.12.40 (2017-12-04) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Add additional costTypes to support finer control for different charges included in a cost budget. -* `service/ecs`: Updates service documentation - * Documentation updates for ecs - -Release v1.12.39 (2017-12-01) -=== - -### Service Client Updates -* `service/SageMaker`: Updates service waiters - -Release v1.12.38 (2017-11-30) -=== - -### Service Client Updates -* `service/AWSMoneypenny`: Adds new service -* `service/Cloud9`: Adds new service -* `service/Serverless Registry`: Adds new service -* `service/apigateway`: Updates service API, documentation, and paginators - * Added support Private Integration and VPC Link features in API Gateway. This allows to create an API with the API Gateway private integration, thus providing clients access to HTTP/HTTPS resources in an Amazon VPC from outside of the VPC through a VpcLink resource. -* `service/ec2`: Updates service API and documentation - * Adds the following updates: 1. Spread Placement ensures that instances are placed on distinct hardware in order to reduce correlated failures. 2. Inter-region VPC Peering allows customers to peer VPCs across different AWS regions without requiring additional gateways, VPN connections or physical hardware -* `service/lambda`: Updates service API and documentation - * AWS Lambda now supports the ability to set the concurrency limits for individual functions, and increasing memory to 3008 MB. - -Release v1.12.37 (2017-11-30) -=== - -### Service Client Updates -* `service/Ardi`: Adds new service -* `service/autoscaling`: Updates service API and documentation - * You can now use Auto Scaling with EC2 Launch Templates via the CreateAutoScalingGroup and UpdateAutoScalingGroup APIs. -* `service/ec2`: Updates service API and documentation - * Adds the following updates: 1. T2 Unlimited enables high CPU performance for any period of time whenever required 2. You are now able to create and launch EC2 m5 and h1 instances -* `service/lightsail`: Updates service API and documentation - * This release adds support for load balancer and TLS/SSL certificate management. This set of APIs allows customers to create, manage, and scale secure load balanced applications on Lightsail infrastructure. To provide support for customers who manage their DNS on Lightsail, we've added the ability create an Alias A type record which can point to a load balancer DNS name via the CreateDomainEntry API http://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_CreateDomainEntry.html. -* `service/ssm`: Updates service API and documentation - * This release updates AWS Systems Manager APIs to enable executing automations at controlled rate, target resources in a resource groups and execute entire automation at once or single step at a time. It is now also possible to use YAML, in addition to JSON, when creating Systems Manager documents. -* `service/waf`: Updates service API and documentation - * This release adds support for rule group and managed rule group. Rule group is a container of rules that customers can create, put rules in it and associate the rule group to a WebACL. All rules in a rule group will function identically as they would if each rule was individually associated to the WebACL. Managed rule group is a pre-configured rule group composed by our security partners and made available via the AWS Marketplace. Customers can subscribe to these managed rule groups, associate the managed rule group to their WebACL and start using them immediately to protect their resources. -* `service/waf-regional`: Updates service API and documentation - -Release v1.12.36 (2017-11-29) -=== - -### Service Client Updates -* `service/DeepInsight`: Adds new service -* `service/IronmanRuntime`: Adds new service -* `service/Orchestra - Laser`: Adds new service -* `service/SageMaker`: Adds new service -* `service/Shine`: Adds new service -* `service/archived.kinesisvideo`: Adds new service -* `service/data.kinesisvideo`: Adds new service -* `service/dynamodb`: Updates service API and documentation - * Amazon DynamoDB now supports the following features: Global Table and On-Demand Backup. Global Table is a fully-managed, multi-region, multi-master database. DynamoDB customers can now write anywhere and read anywhere with single-digit millisecond latency by performing database operations closest to where end users reside. Global Table also enables customers to disaster-proof their applications, keeping them running and data accessible even in the face of natural disasters or region disruptions. Customers can set up Global Table with just a few clicks in the AWS Management Console-no application rewrites required. On-Demand Backup capability is to protect data from loss due to application errors, and meet customers' archival needs for compliance and regulatory reasons. Customers can backup and restore their DynamoDB table data anytime, with a single-click in the AWS management console or a single API call. Backup and restore actions execute with zero impact on table performance or availability. For more information, see the Amazon DynamoDB Developer Guide. -* `service/ecs`: Updates service API and documentation - * Amazon Elastic Container Service (Amazon ECS) released a new launch type for running containers on a serverless infrastructure. The Fargate launch type allows you to run your containerized applications without the need to provision and manage the backend infrastructure. Just register your task definition and Fargate launches the container for you. -* `service/glacier`: Updates service API and documentation - * This release includes support for Glacier Select, a new feature that allows you to filter and analyze your Glacier archives and store the results in a user-specified S3 location. -* `service/greengrass`: Updates service API and documentation - * Greengrass OTA feature allows updating Greengrass Core and Greengrass OTA Agent. Local Resource Access feature allows Greengrass Lambdas to access local resources such as peripheral devices and volumes. -* `service/iot`: Updates service API and documentation - * This release adds support for a number of new IoT features, including AWS IoT Device Management (Jobs, Fleet Index and Thing Registration), Thing Groups, Policies on Thing Groups, Registry & Job Events, JSON Logs, Fine-Grained Logging Controls, Custom Authorization and AWS Service Authentication Using X.509 Certificates. -* `service/kinesisvideo`: Adds new service - * Announcing Amazon Kinesis Video Streams, a fully managed video ingestion and storage service. Kinesis Video Streams makes it easy to securely stream video from connected devices to AWS for machine learning, analytics, and processing. You can also stream other time-encoded data like RADAR and LIDAR signals using Kinesis Video Streams. -* `service/rekognition`: Updates service API, documentation, and paginators - * This release introduces Amazon Rekognition support for video analysis. -* `service/s3`: Updates service API and documentation - * This release includes support for Glacier Select, a new feature that allows you to filter and analyze your Glacier storage class objects and store the results in a user-specified S3 location. - -Release v1.12.35 (2017-11-29) -=== - -### Service Client Updates -* `service/AmazonMQ`: Adds new service -* `service/GuardDuty`: Adds new service -* `service/apigateway`: Updates service API and documentation - * Changes related to CanaryReleaseDeployment feature. Enables API developer to create a deployment as canary deployment and test API changes with percentage of customers before promoting changes to all customers. -* `service/batch`: Updates service API and documentation - * Add support for Array Jobs which allow users to easily submit many copies of a job with a single API call. This change also enhances the job dependency model to support N_TO_N and sequential dependency chains. The ListJobs and DescribeJobs APIs now have the ability to list or describe the status of entire Array Jobs or individual elements within the array. -* `service/cognito-idp`: Updates service API and documentation -* `service/deepdish`: Adds new service - * AWS AppSync is an enterprise-level, fully managed GraphQL service with real-time data synchronization and offline programming features. -* `service/ec2`: Updates service API and documentation - * Adds the following updates: 1. You are now able to host a service powered by AWS PrivateLink to provide private connectivity to other VPCs. You are now also able to create endpoints to other services powered by PrivateLink including AWS services, Marketplace Seller services or custom services created by yourself or other AWS VPC customers. 2. You are now able to save launch parameters in a single template that can be used with Auto Scaling, Spot Fleet, Spot, and On Demand instances. 3. You are now able to launch Spot instances via the RunInstances API, using a single additional parameter. RunInstances will response synchronously with an instance ID should capacity be available for your Spot request. 4. A simplified Spot pricing model which delivers low, predictable prices that adjust gradually, based on long-term trends in supply and demand. 5. Amazon EC2 Spot can now hibernate Amazon EBS-backed instances in the event of an interruption, so your workloads pick up from where they left off. Spot can fulfill your request by resuming instances from a hibernated state when capacity is available. -* `service/lambda`: Updates service API and documentation - * Lambda aliases can now shift traffic between two function versions, based on preassigned weights. - -Release v1.12.34 (2017-11-27) -=== - -### Service Client Updates -* `service/data.mediastore`: Adds new service -* `service/mediaconvert`: Adds new service - * AWS Elemental MediaConvert is a file-based video conversion service that transforms media into formats required for traditional broadcast and for internet streaming to multi-screen devices. -* `service/medialive`: Adds new service - * AWS Elemental MediaLive is a video service that lets you easily create live outputs for broadcast and streaming delivery. -* `service/mediapackage`: Adds new service - * AWS Elemental MediaPackage is a just-in-time video packaging and origination service that lets you format highly secure and reliable live outputs for a variety of devices. -* `service/mediastore`: Adds new service - * AWS Elemental MediaStore is an AWS storage service optimized for media. It gives you the performance, consistency, and low latency required to deliver live and on-demand video content. AWS Elemental MediaStore acts as the origin store in your video workflow. - -Release v1.12.33 (2017-11-22) -=== - -### Service Client Updates -* `service/acm`: Updates service API and documentation - * AWS Certificate Manager now supports the ability to import domainless certs and additional Key Types as well as an additional validation method for DNS. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.32 (2017-11-22) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Add support for Access logs and customizable integration timeouts -* `service/cloudformation`: Updates service API and documentation - * 1) Instance-level parameter overrides (CloudFormation-StackSet feature): This feature will allow the customers to override the template parameters on specific stackInstances. Customers will also have ability to update their existing instances with/without parameter-overrides using a new API "UpdateStackInstances" 2) Add support for SSM parameters in CloudFormation - This feature will allow the customers to use Systems Manager parameters in CloudFormation templates. They will be able to see values for these parameters in Describe APIs. -* `service/codebuild`: Updates service API and documentation - * Adding support for accessing Amazon VPC resources from AWS CodeBuild, dependency caching and build badges. -* `service/elasticmapreduce`: Updates service API and documentation - * Enable Kerberos on Amazon EMR. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rekognition`: Updates service API and documentation - * This release includes updates to Amazon Rekognition for the following APIs. The new DetectText API allows you to recognize and extract textual content from images. Face Model Versioning has been added to operations that deal with face detection. -* `service/shield`: Updates service API, documentation, and paginators - * The AWS Shield SDK has been updated in order to support Elastic IP address protections, the addition of AttackProperties objects in DescribeAttack responses, and a new GetSubscriptionState operation. -* `service/storagegateway`: Updates service API and documentation - * AWS Storage Gateway now enables you to get notification when all your files written to your NFS file share have been uploaded to Amazon S3. Storage Gateway also enables guessing of the MIME type for uploaded objects based on file extensions. -* `service/xray`: Updates service API, documentation, and paginators - * Added automatic pagination support for AWS X-Ray APIs in the SDKs that support this feature. - -Release v1.12.31 (2017-11-20) -=== - -### Service Client Updates -* `service/apigateway`: Updates service documentation - * Documentation updates for Apigateway -* `service/codecommit`: Updates service API, documentation, and paginators - * AWS CodeCommit now supports pull requests. You can use pull requests to collaboratively review code changes for minor changes or fixes, major feature additions, or new versions of your released software. -* `service/firehose`: Updates service API and documentation - * This release includes a new Kinesis Firehose feature that supports Splunk as Kinesis Firehose delivery destination. You can now use Kinesis Firehose to ingest real-time data to Splunk in a serverless, reliable, and salable manner. This release also includes a new feature that allows you to configure Lambda buffer size in Kinesis Firehose data transformation feature. You can now customize the data buffer size before invoking Lambda function in Kinesis Firehose for data transformation. This feature allows you to flexibly trade-off processing and delivery latency with cost and efficiency based on your specific use cases and requirements. -* `service/iis`: Adds new service - * The AWS Cost Explorer API gives customers programmatic access to AWS cost and usage information, allowing them to perform adhoc queries and build interactive cost management applications that leverage this dataset. -* `service/kinesis`: Updates service API and documentation - * Customers can now obtain the important characteristics of their stream with DescribeStreamSummary. The response will not include the shard list for the stream but will have the number of open shards, and all the other fields included in the DescribeStream response. -* `service/workdocs`: Updates service API and documentation - * DescribeGroups API and miscellaneous enhancements - -### SDK Bugs -* `aws/client`: Retry delays for throttled exception were not limited to 5 minutes [#1654](https://github.com/aws/aws-sdk-go/pull/1654) - * Fixes [#1653](https://github.com/aws/aws-sdk-go/issues/1653) -Release v1.12.30 (2017-11-17) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/dms`: Updates service API, documentation, and paginators - * Support for migration task assessment. Support for data validation after the migration. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Amazon RDS now supports importing MySQL databases by using backup files from Amazon S3. -* `service/s3`: Updates service API - * Added ORC to the supported S3 Inventory formats. - -### SDK Bugs -* `private/protocol/restjson`: Define JSONValue marshaling for body and querystring ([#1640](https://github.com/aws/aws-sdk-go/pull/1640)) - * Adds support for APIs which use JSONValue for body and querystring targets. - * Fixes [#1636](https://github.com/aws/aws-sdk-go/issues/1636) -Release v1.12.29 (2017-11-16) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/ec2`: Updates service API - * You are now able to create and launch EC2 x1e smaller instance sizes -* `service/glue`: Updates service API and documentation - * API update for AWS Glue. New crawler configuration attribute enables customers to specify crawler behavior. New XML classifier enables classification of XML data. -* `service/opsworkscm`: Updates service API, documentation, and waiters - * Documentation updates for OpsWorks-cm: a new feature, OpsWorks for Puppet Enterprise, that allows users to create and manage OpsWorks-hosted Puppet Enterprise servers. -* `service/organizations`: Updates service API, documentation, and paginators - * This release adds APIs that you can use to enable and disable integration with AWS services designed to work with AWS Organizations. This integration allows the AWS service to perform operations on your behalf on all of the accounts in your organization. Although you can use these APIs yourself, we recommend that you instead use the commands provided in the other AWS service to enable integration with AWS Organizations. -* `service/route53`: Updates service API and documentation - * You can use Route 53's GetAccountLimit/GetHostedZoneLimit/GetReusableDelegationSetLimit APIs to view your current limits (including custom set limits) on Route 53 resources such as hosted zones and health checks. These APIs also return the number of each resource you're currently using to enable comparison against your current limits. - -Release v1.12.28 (2017-11-15) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * 1. Extended GetDocumentationParts operation to support retrieving documentation parts resources without contents. 2. Added hosted zone ID in the custom domain response. -* `service/email`: Updates service API, documentation, and examples - * SES launches Configuration Set Reputation Metrics and Email Pausing Today, two features that build upon the capabilities of the reputation dashboard. The first is the ability to export reputation metrics for individual configuration sets. The second is the ability to temporarily pause email sending, either at the configuration set level, or across your entire Amazon SES account. -* `service/polly`: Updates service API - * Amazon Polly adds Korean language support with new female voice - "Seoyeon" and new Indian English female voice - "Aditi" -* `service/states`: Updates service API and documentation - * You can now use the UpdateStateMachine API to update your state machine definition and role ARN. Existing executions will continue to use the previous definition and role ARN. You can use the DescribeStateMachineForExecution API to determine which state machine definition and role ARN is associated with an execution - -Release v1.12.27 (2017-11-14) -=== - -### Service Client Updates -* `service/ecs`: Updates service API and documentation - * Added new mode for Task Networking in ECS, called awsvpc mode. Mode configuration parameters to be passed in via awsvpcConfiguration. Updated APIs now use/show this new mode - RegisterTaskDefinition, CreateService, UpdateService, RunTask, StartTask. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lightsail`: Updates service API and documentation - * Lightsail now supports attached block storage, which allows you to scale your applications and protect application data with additional SSD-backed storage disks. This feature allows Lightsail customers to attach secure storage disks to their Lightsail instances and manage their attached disks, including creating and deleting disks, attaching and detaching disks from instances, and backing up disks via snapshot. -* `service/route53`: Updates service API and documentation - * When a Route 53 health check or hosted zone is created by a linked AWS service, the object now includes information about the service that created it. Hosted zones or health checks that are created by a linked service can't be updated or deleted using Route 53. -* `service/ssm`: Updates service API and documentation - * EC2 Systems Manager GetInventory API adds support for aggregation. - -### SDK Enhancements -* `aws/request`: Remove default port from HTTP host header ([#1618](https://github.com/aws/aws-sdk-go/pull/1618)) - * Updates the SDK to automatically remove default ports based on the URL's scheme when setting the HTTP Host header's value. - * Fixes [#1537](https://github.com/aws/aws-sdk-go/issues/1537) - -Release v1.12.26 (2017-11-09) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Introduces the following features: 1. Create a default subnet in an Availability Zone if no default subnet exists. 2. Spot Fleet integrates with Elastic Load Balancing to enable you to attach one or more load balancers to a Spot Fleet request. When you attach the load balancer, it automatically registers the instance in the Spot Fleet to the load balancers which distributes incoming traffic across the instances. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.25 (2017-11-08) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/batch`: Updates service documentation - * Documentation updates for AWS Batch. -* `service/ec2`: Updates service API and documentation - * AWS PrivateLink for Amazon Services - Customers can now privately access Amazon services from their Amazon Virtual Private Cloud (VPC), without using public IPs, and without requiring the traffic to traverse across the Internet. -* `service/elasticache`: Updates service API and documentation - * This release adds online resharding for ElastiCache for Redis offering, providing the ability to add and remove shards from a running cluster. Developers can now dynamically scale-out or scale-in their Redis cluster workloads to adapt to changes in demand. ElastiCache will resize the cluster by adding or removing shards and redistribute hash slots uniformly across the new shard configuration, all while the cluster continues to stay online and serves requests. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.24 (2017-11-07) -=== - -### Service Client Updates -* `service/elasticloadbalancingv2`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * DescribeOrderableDBInstanceOptions now returns the minimum and maximum allowed values for storage size, total provisioned IOPS, and provisioned IOPS per GiB for a DB instance. -* `service/s3`: Updates service API, documentation, and examples - * This releases adds support for 4 features: 1. Default encryption for S3 Bucket, 2. Encryption status in inventory and Encryption support for inventory. 3. Cross region replication of KMS-encrypted objects, and 4. ownership overwrite for CRR. - -Release v1.12.23 (2017-11-07) -=== - -### Service Client Updates -* `service/api.pricing`: Adds new service -* `service/ec2`: Updates service API - * You are now able to create and launch EC2 C5 instances, the next generation of EC2's compute-optimized instances, in us-east-1, us-west-2 and eu-west-1. C5 instances offer up to 72 vCPUs, 144 GiB of DDR4 instance memory, 25 Gbps in Network bandwidth and improved EBS and Networking bandwidth on smaller instance sizes to deliver improved performance for compute-intensive workloads. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kms`: Updates service API, documentation, and examples - * Documentation updates for AWS KMS. -* `service/organizations`: Updates service documentation - * This release updates permission statements for several API operations, and corrects some other minor errors. -* `service/states`: Updates service API, documentation, and paginators - * Documentation update. - -Release v1.12.22 (2017-11-03) -=== - -### Service Client Updates -* `service/ecs`: Updates service API and documentation - * Amazon ECS users can now add devices to their containers and enable init process in containers through the use of docker's 'devices' and 'init' features. These fields can be specified under linuxParameters in ContainerDefinition in the Task Definition Template. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.21 (2017-11-02) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * This release supports creating and managing Regional and Edge-Optimized API endpoints. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -### SDK Bugs -* `aws/request`: Fix bug in request presign creating invalid URL ([#1624](https://github.com/aws/aws-sdk-go/pull/1624)) - * Fixes a bug the Request Presign and PresignRequest methods that would allow a invalid expire duration as input. A expire time of 0 would be interpreted by the SDK to generate a normal request signature, not a presigned URL. This caused the returned URL unusable. - * Fixes [#1617](https://github.com/aws/aws-sdk-go/issues/1617) -Release v1.12.20 (2017-11-01) -=== - -### Service Client Updates -* `service/acm`: Updates service documentation - * Documentation updates for ACM -* `service/cloudhsmv2`: Updates service documentation - * Minor documentation update for AWS CloudHSM (cloudhsmv2). -* `service/directconnect`: Updates service API and documentation - * AWS DirectConnect now provides support for Global Access for Virtual Private Cloud (VPC) via a new feature called Direct Connect Gateway. A Direct Connect Gateway will allow you to group multiple Direct Connect Private Virtual Interfaces (DX-VIF) and Private Virtual Gateways (VGW) from different AWS regions (but belonging to the same AWS Account) and pass traffic from any DX-VIF to any VPC in the grouping. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -### SDK Enhancements -* `aws/client`: Adding status code 429 to throttlable status codes in default retryer (#1621) - -Release v1.12.19 (2017-10-26) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.18 (2017-10-26) -=== - -### Service Client Updates -* `service/cloudfront`: Updates service API and documentation - * You can now specify additional options for MinimumProtocolVersion, which controls the SSL/TLS protocol that CloudFront uses to communicate with viewers. The minimum protocol version that you choose also determines the ciphers that CloudFront uses to encrypt the content that it returns to viewers. -* `service/ec2`: Updates service API - * You are now able to create and launch EC2 P3 instance, next generation GPU instances, optimized for machine learning and high performance computing applications. With up to eight NVIDIA Tesla V100 GPUs, P3 instances provide up to one petaflop of mixed-precision, 125 teraflops of single-precision, and 62 teraflops of double-precision floating point performance, as well as a 300 GB/s second-generation NVLink interconnect that enables high-speed, low-latency GPU-to-GPU communication. P3 instances also feature up to 64 vCPUs based on custom Intel Xeon E5 (Broadwell) processors, 488 GB of DRAM, and 25 Gbps of dedicated aggregate network bandwidth using the Elastic Network Adapter (ENA). -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.17 (2017-10-24) -=== - -### Service Client Updates -* `service/config`: Updates service API -* `service/elasticache`: Updates service API, documentation, and examples - * Amazon ElastiCache for Redis today announced support for data encryption both for data in-transit and data at-rest. The new encryption in-transit functionality enables ElastiCache for Redis customers to encrypt data for all communication between clients and Redis engine, and all intra-cluster Redis communication. The encryption at-rest functionality allows customers to encrypt their S3 based backups. Customers can begin using the new functionality by simply enabling this functionality via AWS console, and a small configuration change in their Redis clients. The ElastiCache for Redis service automatically manages life cycle of the certificates required for encryption, including the issuance, renewal and expiration of certificates. Additionally, as part of this launch, customers will gain the ability to start using the Redis AUTH command that provides an added level of authentication. -* `service/glue`: Adds new service - * AWS Glue: Adding a new API, BatchStopJobRun, to stop one or more job runs for a specified Job. -* `service/pinpoint`: Updates service API and documentation - * Added support for APNs VoIP messages. Added support for collapsible IDs, message priority, and TTL for APNs and FCM/GCM. - -Release v1.12.16 (2017-10-23) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/organizations`: Updates service API and documentation - * This release supports integrating other AWS services with AWS Organizations through the use of an IAM service-linked role called AWSServiceRoleForOrganizations. Certain operations automatically create that role if it does not already exist. - -Release v1.12.15 (2017-10-20) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Adding pagination support for DescribeSecurityGroups for EC2 Classic and VPC Security Groups - -Release v1.12.14 (2017-10-19) -=== - -### Service Client Updates -* `service/sqs`: Updates service API and documentation - * Added support for tracking cost allocation by adding, updating, removing, and listing the metadata tags of Amazon SQS queues. -* `service/ssm`: Updates service API and documentation - * EC2 Systems Manager versioning support for Parameter Store. Also support for referencing parameter versions in SSM Documents. - -Release v1.12.13 (2017-10-18) -=== - -### Service Client Updates -* `service/lightsail`: Updates service API and documentation - * This release adds support for Windows Server-based Lightsail instances. The GetInstanceAccessDetails API now returns the password of your Windows Server-based instance when using the default key pair. GetInstanceAccessDetails also returns a PasswordData object for Windows Server instances containing the ciphertext and keyPairName. The Blueprint data type now includes a list of platform values (LINUX_UNIX or WINDOWS). The Bundle data type now includes a list of SupportedPlatforms values (LINUX_UNIX or WINDOWS). - -Release v1.12.12 (2017-10-17) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/es`: Updates service API and documentation - * This release adds support for VPC access to Amazon Elasticsearch Service. - * This release adds support for VPC access to Amazon Elasticsearch Service. - -Release v1.12.11 (2017-10-16) -=== - -### Service Client Updates -* `service/cloudhsm`: Updates service API and documentation - * Documentation updates for AWS CloudHSM Classic. -* `service/ec2`: Updates service API and documentation - * You can now change the tenancy of your VPC from dedicated to default with a single API operation. For more details refer to the documentation for changing VPC tenancy. -* `service/es`: Updates service API and documentation - * AWS Elasticsearch adds support for enabling slow log publishing. Using slow log publishing options customers can configure and enable index/query slow log publishing of their domain to preferred AWS Cloudwatch log group. -* `service/rds`: Updates service API and waiters - * Adds waiters for DBSnapshotAvailable and DBSnapshotDeleted. -* `service/waf`: Updates service API and documentation - * This release adds support for regular expressions as match conditions in rules, and support for geographical location by country of request IP address as a match condition in rules. -* `service/waf-regional`: Updates service API and documentation - -Release v1.12.10 (2017-10-12) -=== - -### Service Client Updates -* `service/codecommit`: Updates service API and documentation - * This release includes the DeleteBranch API and a change to the contents of a Commit object. -* `service/dms`: Updates service API and documentation - * This change includes addition of new optional parameter to an existing API -* `service/elasticbeanstalk`: Updates service API and documentation - * Added the ability to add, delete or update Tags -* `service/polly`: Updates service API - * Amazon Polly exposes two new voices: "Matthew" (US English) and "Takumi" (Japanese) -* `service/rds`: Updates service API and documentation - * You can now call DescribeValidDBInstanceModifications to learn what modifications you can make to your DB instance. You can use this information when you call ModifyDBInstance. - -Release v1.12.9 (2017-10-11) -=== - -### Service Client Updates -* `service/ecr`: Updates service API, documentation, and paginators - * Adds support for new API set used to manage Amazon ECR repository lifecycle policies. Amazon ECR lifecycle policies enable you to specify the lifecycle management of images in a repository. The configuration is a set of one or more rules, where each rule defines an action for Amazon ECR to apply to an image. This allows the automation of cleaning up unused images, for example expiring images based on age or status. A lifecycle policy preview API is provided as well, which allows you to see the impact of a lifecycle policy on an image repository before you execute it -* `service/email`: Updates service API and documentation - * Added content related to email template management and templated email sending operations. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.8 (2017-10-10) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * This release includes updates to AWS Virtual Private Gateway. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `service/opsworkscm`: Updates service API and documentation - * Provide engine specific information for node associations. - -Release v1.12.7 (2017-10-06) -=== - -### Service Client Updates -* `service/sqs`: Updates service documentation - * Documentation updates regarding availability of FIFO queues and miscellaneous corrections. - -Release v1.12.6 (2017-10-05) -=== - -### Service Client Updates -* `service/redshift`: Updates service API and documentation - * DescribeEventSubscriptions API supports tag keys and tag values as request parameters. - -Release v1.12.5 (2017-10-04) -=== - -### Service Client Updates -* `service/kinesisanalytics`: Updates service API and documentation - * Kinesis Analytics now supports schema discovery on objects in S3. Additionally, Kinesis Analytics now supports input data preprocessing through Lambda. -* `service/route53domains`: Updates service API and documentation - * Added a new API that checks whether a domain name can be transferred to Amazon Route 53. - -### SDK Bugs -* `service/s3/s3crypto`: Correct PutObjectRequest documentation ([#1568](https://github.com/aws/aws-sdk-go/pull/1568)) - * s3Crypto's PutObjectRequest docstring example was using an incorrect value. Corrected the type used in the example. -Release v1.12.4 (2017-10-03) -=== - -### Service Client Updates -* `service/ec2`: Updates service API, documentation, and waiters - * This release includes service updates to AWS VPN. -* `service/ssm`: Updates service API and documentation - * EC2 Systems Manager support for tagging SSM Documents. Also support for tag-based permissions to restrict access to SSM Documents based on these tags. - -Release v1.12.3 (2017-10-02) -=== - -### Service Client Updates -* `service/cloudhsm`: Updates service documentation and paginators - * Documentation updates for CloudHSM - -Release v1.12.2 (2017-09-29) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Includes APIs for managing and accessing image builders, and deleting images. -* `service/codebuild`: Updates service API and documentation - * Adding support for Building GitHub Pull Requests in AWS CodeBuild -* `service/mturk-requester`: Updates service API and documentation -* `service/organizations`: Updates service API and documentation - * This release flags the HandshakeParty structure's Type and Id fields as 'required'. They effectively were required in the past, as you received an error if you did not include them. This is now reflected at the API definition level. -* `service/route53`: Updates service API and documentation - * This change allows customers to reset elements of health check. - -### SDK Bugs -* `private/protocol/query`: Fix query protocol handling of nested byte slices ([#1557](https://github.com/aws/aws-sdk-go/issues/1557)) - * Fixes the query protocol to correctly marshal nested []byte values of API operations. -* `service/s3`: Fix PutObject and UploadPart API to include ContentMD5 field ([#1559](https://github.com/aws/aws-sdk-go/pull/1559)) - * Fixes the SDK's S3 PutObject and UploadPart API code generation to correctly render the ContentMD5 field into the associated input types for these two API operations. - * Fixes [#1553](https://github.com/aws/aws-sdk-go/pull/1553) -Release v1.12.1 (2017-09-27) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/pinpoint`: Updates service API and documentation - * Added two new push notification channels: Amazon Device Messaging (ADM) and, for push notification support in China, Baidu Cloud Push. Added support for APNs auth via .p8 key file. Added operation for direct message deliveries to user IDs, enabling you to message an individual user on multiple endpoints. - -Release v1.12.0 (2017-09-26) -=== - -### SDK Bugs -* `API Marshaler`: Revert REST JSON and XML protocol marshaler improvements - * Bug [#1550](https://github.com/aws/aws-sdk-go/issues/1550) identified a missed condition in the Amazon Route 53 RESTXML protocol marshaling causing requests to that service to fail. Reverting the marshaler improvements until the bug can be fixed. - -Release v1.11.0 (2017-09-26) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API and documentation - * You can now prevent a stack from being accidentally deleted by enabling termination protection on the stack. If you attempt to delete a stack with termination protection enabled, the deletion fails and the stack, including its status, remains unchanged. You can enable termination protection on a stack when you create it. Termination protection on stacks is disabled by default. After creation, you can set termination protection on a stack whose status is CREATE_COMPLETE, UPDATE_COMPLETE, or UPDATE_ROLLBACK_COMPLETE. - -### SDK Features -* Add dep Go dependency management metadata files (#1544) - * Adds the Go `dep` dependency management metadata files to the SDK. - * Fixes [#1451](https://github.com/aws/aws-sdk-go/issues/1451) - * Fixes [#634](https://github.com/aws/aws-sdk-go/issues/634) -* `service/dynamodb/expression`: Add expression building utility for DynamoDB ([#1527](https://github.com/aws/aws-sdk-go/pull/1527)) - * Adds a new package, expression, to the SDK providing builder utilities to create DynamoDB expressions safely taking advantage of type safety. -* `API Marshaler`: Add generated marshalers for RESTXML protocol ([#1409](https://github.com/aws/aws-sdk-go/pull/1409)) - * Updates the RESTXML protocol marshaler to use generated code instead of reflection for REST XML based services. -* `API Marshaler`: Add generated marshalers for RESTJSON protocol ([#1547](https://github.com/aws/aws-sdk-go/pull/1547)) - * Updates the RESTJSON protocol marshaler to use generated code instead of reflection for REST JSON based services. - -### SDK Enhancements -* `private/protocol`: Update format of REST JSON and XMl benchmarks ([#1546](https://github.com/aws/aws-sdk-go/pull/1546)) - * Updates the format of the REST JSON and XML benchmarks to be readable. RESTJSON benchmarks were updated to more accurately bench building of the protocol. - -Release v1.10.51 (2017-09-22) -=== - -### Service Client Updates -* `service/config`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - * Amazon ECS users can now add and drop Linux capabilities to their containers through the use of docker's cap-add and cap-drop features. Customers can specify the capabilities they wish to add or drop for each container in their task definition. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service documentation - * Documentation updates for rds - -Release v1.10.50 (2017-09-21) -=== - -### Service Client Updates -* `service/budgets`: Updates service API - * Including "DuplicateRecordException" in UpdateNotification and UpdateSubscriber. -* `service/ec2`: Updates service API and documentation - * Add EC2 APIs to copy Amazon FPGA Images (AFIs) within the same region and across multiple regions, delete AFIs, and modify AFI attributes. AFI attributes include name, description and granting/denying other AWS accounts to load the AFI. -* `service/logs`: Updates service API and documentation - * Adds support for associating LogGroups with KMS Keys. - -### SDK Bugs -* Fix greengrass service model being duplicated with different casing. ([#1541](https://github.com/aws/aws-sdk-go/pull/1541)) - * Fixes [#1540](https://github.com/aws/aws-sdk-go/issues/1540) - * Fixes [#1539](https://github.com/aws/aws-sdk-go/issues/1539) -Release v1.10.49 (2017-09-20) -=== - -### Service Client Updates -* `service/Greengrass`: Adds new service -* `service/appstream`: Updates service API and documentation - * API updates for supporting On-Demand fleets. -* `service/codepipeline`: Updates service API and documentation - * This change includes a PipelineMetadata object that is part of the output from the GetPipeline API that includes the Pipeline ARN, created, and updated timestamp. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Introduces the --option-group-name parameter to the ModifyDBSnapshot CLI command. You can specify this parameter when you upgrade an Oracle DB snapshot. The same option group considerations apply when upgrading a DB snapshot as when upgrading a DB instance. For more information, see http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Oracle.html#USER_UpgradeDBInstance.Oracle.OGPG.OG -* `service/runtime.lex`: Updates service API and documentation - -Release v1.10.48 (2017-09-19) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * Fixed bug in EC2 clients preventing ElasticGpuSet from being set. - -### SDK Enhancements -* `aws/credentials`: Add EnvProviderName constant. ([#1531](https://github.com/aws/aws-sdk-go/issues/1531)) - * Adds the "EnvConfigCredentials" string literal as EnvProviderName constant. - * Fixes [#1444](https://github.com/aws/aws-sdk-go/issues/1444) - -Release v1.10.47 (2017-09-18) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Amazon EC2 now lets you opt for Spot instances to be stopped in the event of an interruption instead of being terminated. Your Spot request can be fulfilled again by restarting instances from a previously stopped state, subject to availability of capacity at or below your preferred price. When you submit a persistent Spot request, you can choose from "terminate" or "stop" as the instance interruption behavior. Choosing "stop" will shutdown your Spot instances so you can continue from this stopped state later on. This feature is only available for instances with Amazon EBS volume as their root device. -* `service/email`: Updates service API and documentation - * Amazon Simple Email Service (Amazon SES) now lets you customize the domains used for tracking open and click events. Previously, open and click tracking links referred to destinations hosted on domains operated by Amazon SES. With this feature, you can use your own branded domains for capturing open and click events. -* `service/iam`: Updates service API and documentation - * A new API, DeleteServiceLinkedRole, submits a service-linked role deletion request and returns a DeletionTaskId, which you can use to check the status of the deletion. - -Release v1.10.46 (2017-09-15) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Add a new enum "REQUEST" to '--type ' field in the current create-authorizer API, and make "identitySource" optional. - -Release v1.10.45 (2017-09-14) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Supporting Parameter Store in environment variables for AWS CodeBuild -* `service/organizations`: Updates service documentation - * Documentation updates for AWS Organizations -* `service/servicecatalog`: Updates service API, documentation, and paginators - * This release of Service Catalog adds API support to copy products. - -Release v1.10.44 (2017-09-13) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * Customers can create Life Cycle Hooks at the time of creating Auto Scaling Groups through the CreateAutoScalingGroup API -* `service/batch`: Updates service documentation and examples - * Documentation updates for batch -* `service/ec2`: Updates service API - * You are now able to create and launch EC2 x1e.32xlarge instance, a new EC2 instance in the X1 family, in us-east-1, us-west-2, eu-west-1, and ap-northeast-1. x1e.32xlarge offers 128 vCPUs, 3,904 GiB of DDR4 instance memory, high memory bandwidth, large L3 caches, and leading reliability capabilities to boost the performance and reliability of in-memory applications. -* `service/events`: Updates service API and documentation - * Exposes ConcurrentModificationException as one of the valid exceptions for PutPermission and RemovePermission operation. - -### SDK Enhancements -* `service/autoscaling`: Fix documentation for PutScalingPolicy.AutoScalingGroupName [#1522](https://github.com/aws/aws-sdk-go/pull/1522) -* `service/s3/s3manager`: Clarify S3 Upload manager Concurrency config [#1521](https://github.com/aws/aws-sdk-go/pull/1521) - * Fixes [#1458](https://github.com/aws/aws-sdk-go/issues/1458) -* `service/dynamodb/dynamodbattribute`: Add support for time alias. [#1520](https://github.com/aws/aws-sdk-go/pull/1520) - * Related to [#1505](https://github.com/aws/aws-sdk-go/pull/1505) - -Release v1.10.43 (2017-09-12) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * Fixed bug in EC2 clients preventing HostOfferingSet from being set -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.42 (2017-09-12) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * DeviceFarm has added support for two features - RemoteDebugging and Customer Artifacts. Customers can now do remote Debugging on their Private Devices and can now retrieve custom files generated by their tests on the device and the device host (execution environment) on both public and private devices. - -Release v1.10.41 (2017-09-08) -=== - -### Service Client Updates -* `service/logs`: Updates service API and documentation - * Adds support for the PutResourcePolicy, DescribeResourcePolicy and DeleteResourcePolicy APIs. - -Release v1.10.40 (2017-09-07) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service documentation -* `service/ec2`: Updates service API and documentation - * With Tagging support, you can add Key and Value metadata to search, filter and organize your NAT Gateways according to your organization's needs. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lex-models`: Updates service API and documentation -* `service/route53`: Updates service API and documentation - * You can configure Amazon Route 53 to log information about the DNS queries that Amazon Route 53 receives for your domains and subdomains. When you configure query logging, Amazon Route 53 starts to send logs to CloudWatch Logs. You can use various tools, including the AWS console, to access the query logs. - -Release v1.10.39 (2017-09-06) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Add an optional "thresholdType" to notifications to support percentage or absolute value thresholds. - -Release v1.10.38 (2017-09-05) -=== - -### Service Client Updates -* `service/codestar`: Updates service API and documentation - * Added support to tag CodeStar projects. Tags can be used to organize and find CodeStar projects on key-value pairs that you can choose. For example, you could add a tag with a key of "Release" and a value of "Beta" to projects your organization is working on for an upcoming beta release. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.37 (2017-09-01) -=== - -### Service Client Updates -* `service/MobileHub`: Adds new service -* `service/gamelift`: Updates service API and documentation - * GameLift VPC resources can be peered with any other AWS VPC. R4 memory-optimized instances now available to deploy. -* `service/ssm`: Updates service API and documentation - * Adding KMS encryption support to SSM Inventory Resource Data Sync. Exposes the ClientToken parameter on SSM StartAutomationExecution to provide idempotent execution requests. - -Release v1.10.36 (2017-08-31) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API, documentation, and examples - * The AWS CodeBuild HTTP API now provides the BatchDeleteBuilds operation, which enables you to delete existing builds. -* `service/ec2`: Updates service API and documentation - * Descriptions for Security Group Rules enables customers to be able to define a description for ingress and egress security group rules . The Descriptions for Security Group Rules feature supports one description field per Security Group rule for both ingress and egress rules . Descriptions for Security Group Rules provides a simple way to describe the purpose or function of a Security Group Rule allowing for easier customer identification of configuration elements . Prior to the release of Descriptions for Security Group Rules , customers had to maintain a separate system outside of AWS if they wanted to track Security Group Rule mapping and their purpose for being implemented. If a security group rule has already been created and you would like to update or change your description for that security group rule you can use the UpdateSecurityGroupRuleDescription API. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lex-models`: Updates service API and documentation - -### SDK Bugs -* `aws/signer/v4`: Revert [#1491](https://github.com/aws/aws-sdk-go/issues/1491) as change conflicts with an undocumented AWS v4 signature test case. - * Related to: [#1495](https://github.com/aws/aws-sdk-go/issues/1495). -Release v1.10.35 (2017-08-30) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/organizations`: Updates service API and documentation - * The exception ConstraintViolationException now contains a new reason subcode MASTERACCOUNT_MISSING_CONTACT_INFO to make it easier to understand why attempting to remove an account from an Organization can fail. We also improved several other of the text descriptions and examples. - -Release v1.10.34 (2017-08-29) -=== - -### Service Client Updates -* `service/config`: Updates service API and documentation -* `service/ec2`: Updates service API and documentation - * Provides capability to add secondary CIDR blocks to a VPC. - -### SDK Bugs -* `aws/signer/v4`: Fix Signing Unordered Multi Value Query Parameters ([#1491](https://github.com/aws/aws-sdk-go/pull/1491)) - * Removes sorting of query string values when calculating v4 signing as this is not part of the spec. The spec only requires the keys, not values, to be sorted which is achieved by Query.Encode(). -Release v1.10.33 (2017-08-25) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API and documentation - * Rollback triggers enable you to have AWS CloudFormation monitor the state of your application during stack creation and updating, and to roll back that operation if the application breaches the threshold of any of the alarms you've specified. -* `service/gamelift`: Updates service API - * Update spelling of MatchmakingTicket status values for internal consistency. -* `service/rds`: Updates service API and documentation - * Option group options now contain additional properties that identify requirements for certain options. Check these properties to determine if your DB instance must be in a VPC or have auto minor upgrade turned on before you can use an option. Check to see if you can downgrade the version of an option after you have installed it. - -### SDK Enhancements -* `example/service/ec2`: Add EC2 list instances example ([#1492](https://github.com/aws/aws-sdk-go/pull/1492)) - -Release v1.10.32 (2017-08-25) -=== - -### Service Client Updates -* `service/rekognition`: Updates service API, documentation, and examples - * Update the enum value of LandmarkType and GenderType to be consistent with service response - -Release v1.10.31 (2017-08-23) -=== - -### Service Client Updates -* `service/appstream`: Updates service documentation - * Documentation updates for appstream -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.30 (2017-08-22) -=== - -### Service Client Updates -* `service/ssm`: Updates service API and documentation - * Changes to associations in Systems Manager State Manager can now be recorded. Previously, when you edited associations, you could not go back and review older association settings. Now, associations are versioned, and can be named using human-readable strings, allowing you to see a trail of association changes. You can also perform rate-based scheduling, which allows you to schedule associations more granularly. - -Release v1.10.29 (2017-08-21) -=== - -### Service Client Updates -* `service/firehose`: Updates service API, documentation, and paginators - * This change will allow customers to attach a Firehose delivery stream to an existing Kinesis stream directly. You no longer need a forwarder to move data from a Kinesis stream to a Firehose delivery stream. You can now run your streaming applications on your Kinesis stream and easily attach a Firehose delivery stream to it for data delivery to S3, Redshift, or Elasticsearch concurrently. -* `service/route53`: Updates service API and documentation - * Amazon Route 53 now supports CAA resource record type. A CAA record controls which certificate authorities are allowed to issue certificates for the domain or subdomain. - -Release v1.10.28 (2017-08-18) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.27 (2017-08-16) -=== - -### Service Client Updates -* `service/gamelift`: Updates service API and documentation - * The Matchmaking Grouping Service is a new feature that groups player match requests for a given game together into game sessions based on developer configured rules. - -### SDK Enhancements -* `aws/arn`: aws/arn: Package for parsing and producing ARNs ([#1463](https://github.com/aws/aws-sdk-go/pull/1463)) - * Adds the `arn` package for AWS ARN parsing and building. Use this package to build AWS ARNs for services such as outlined in the [documentation](http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). - -### SDK Bugs -* `aws/signer/v4`: Correct V4 presign signature to include content sha25 in URL ([#1469](https://github.com/aws/aws-sdk-go/pull/1469)) - * Updates the V4 signer so that when a Presign is generated the `X-Amz-Content-Sha256` header is added to the query string instead of being required to be in the header. This allows you to generate presigned URLs for GET requests, e.g S3.GetObject that do not require additional headers to be set by the downstream users of the presigned URL. - * Related To: [#1467](https://github.com/aws/aws-sdk-go/issues/1467) - -Release v1.10.26 (2017-08-15) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * Fixed bug in EC2 clients preventing HostReservation from being set -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.25 (2017-08-14) -=== - -### Service Client Updates -* `service/AWS Glue`: Adds new service -* `service/batch`: Updates service API and documentation - * This release enhances the DescribeJobs API to include the CloudWatch logStreamName attribute in ContainerDetail and ContainerDetailAttempt -* `service/cloudhsmv2`: Adds new service - * CloudHSM provides hardware security modules for protecting sensitive data and cryptographic keys within an EC2 VPC, and enable the customer to maintain control over key access and use. This is a second-generation of the service that will improve security, lower cost and provide better customer usability. -* `service/elasticfilesystem`: Updates service API, documentation, and paginators - * Customers can create encrypted EFS file systems and specify a KMS master key to encrypt it with. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/mgh`: Adds new service - * AWS Migration Hub provides a single location to track migrations across multiple AWS and partner solutions. Using Migration Hub allows you to choose the AWS and partner migration tools that best fit your needs, while providing visibility into the status of your entire migration portfolio. Migration Hub also provides key metrics and progress for individual applications, regardless of which tools are being used to migrate them. For example, you might use AWS Database Migration Service, AWS Server Migration Service, and partner migration tools to migrate an application comprised of a database, virtualized web servers, and a bare metal server. Using Migration Hub will provide you with a single screen that shows the migration progress of all the resources in the application. This allows you to quickly get progress updates across all of your migrations, easily identify and troubleshoot any issues, and reduce the overall time and effort spent on your migration projects. Migration Hub is available to all AWS customers at no additional charge. You only pay for the cost of the migration tools you use, and any resources being consumed on AWS. -* `service/ssm`: Updates service API and documentation - * Systems Manager Maintenance Windows include the following changes or enhancements: New task options using Systems Manager Automation, AWS Lambda, and AWS Step Functions; enhanced ability to edit the targets of a Maintenance Window, including specifying a target name and description, and ability to edit the owner field; enhanced ability to edits tasks; enhanced support for Run Command parameters; and you can now use a --safe flag when attempting to deregister a target. If this flag is enabled when you attempt to deregister a target, the system returns an error if the target is referenced by any task. Also, Systems Manager now includes Configuration Compliance to scan your fleet of managed instances for patch compliance and configuration inconsistencies. You can collect and aggregate data from multiple AWS accounts and Regions, and then drill down into specific resources that aren't compliant. -* `service/storagegateway`: Updates service API and documentation - * Add optional field ForceDelete to DeleteFileShare api. - -Release v1.10.24 (2017-08-11) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * Adds support for specifying Application Load Balancers in deployment groups, for both in-place and blue/green deployments. -* `service/cognito-idp`: Updates service API and documentation -* `service/ec2`: Updates service API and documentation - * Provides customers an opportunity to recover an EIP that was released - -Release v1.10.23 (2017-08-10) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Enable BatchDetachPolicy -* `service/codebuild`: Updates service API - * Supporting Bitbucket as source type in AWS CodeBuild. - -Release v1.10.22 (2017-08-09) -=== - -### Service Client Updates -* `service/rds`: Updates service documentation - * Documentation updates for RDS. - -Release v1.10.21 (2017-08-09) -=== - -### Service Client Updates -* `service/elasticbeanstalk`: Updates service API and documentation - * Add support for paginating the result of DescribeEnvironments Include the ARN of described environments in DescribeEnvironments output - -### SDK Enhancements -* `aws`: Add pointer conversion utilities to transform int64 to time.Time [#1433](https://github.com/aws/aws-sdk-go/pull/1433) - * Adds `SecondsTimeValue` and `MillisecondsTimeValue` utilities. - -Release v1.10.20 (2017-08-01) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * AWS CodeDeploy now supports the use of multiple tag groups in a single deployment group (an intersection of tags) to identify the instances for a deployment. When you create or update a deployment group, use the new ec2TagSet and onPremisesTagSet structures to specify up to three groups of tags. Only instances that are identified by at least one tag in each of the tag groups are included in the deployment group. -* `service/config`: Updates service API and documentation -* `service/ec2`: Updates service waiters - * Ec2 SpotInstanceRequestFulfilled waiter update -* `service/elasticloadbalancingv2`: Updates service waiters -* `service/email`: Updates service API, documentation, paginators, and examples - * This update adds information about publishing email open and click events. This update also adds information about publishing email events to Amazon Simple Notification Service (Amazon SNS). -* `service/pinpoint`: Updates service API and documentation - * This release of the Pinpoint SDK enables App management - create, delete, update operations, Raw Content delivery for APNs and GCM campaign messages and From Address override. - -Release v1.10.19 (2017-08-01) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/inspector`: Updates service API, documentation, and paginators - * Inspector's StopAssessmentRun API has been updated with a new input option - stopAction. This request parameter can be set to either START_EVALUATION or SKIP_EVALUATION. START_EVALUATION (the default value, and the previous behavior) stops the AWS agent data collection and begins the results evaluation for findings generation based on the data collected so far. SKIP_EVALUATION cancels the assessment run immediately, after which no findings are generated. -* `service/ssm`: Updates service API and documentation - * Adds a SendAutomationSignal API to SSM Service. This API is used to send a signal to an automation execution to change the current behavior or status of the execution. - -Release v1.10.18 (2017-07-27) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * The CreateDefaultVPC API enables you to create a new default VPC . You no longer need to contact AWS support, if your default VPC has been deleted. -* `service/kinesisanalytics`: Updates service API and documentation - * Added additional exception types and clarified documentation. - -Release v1.10.17 (2017-07-27) -=== - -### Service Client Updates -* `service/dynamodb`: Updates service documentation and examples - * Corrected a typo. -* `service/ec2`: Updates service API and documentation - * Amazon EC2 Elastic GPUs allow you to easily attach low-cost graphics acceleration to current generation EC2 instances. With Amazon EC2 Elastic GPUs, you can configure the right amount of graphics acceleration to your particular workload without being constrained by fixed hardware configurations and limited GPU selection. -* `service/monitoring`: Updates service documentation - * This release adds high resolution features to CloudWatch, with support for Custom Metrics down to 1 second and Alarms down to 10 seconds. - -Release v1.10.16 (2017-07-26) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Cloud Directory adds support for additional batch operations. -* `service/cloudformation`: Updates service API and documentation - * AWS CloudFormation StackSets enables you to manage stacks across multiple accounts and regions. - -### SDK Enhancements -* `aws/signer/v4`: Optimize V4 signer's header duplicate space stripping. [#1417](https://github.com/aws/aws-sdk-go/pull/1417) - -Release v1.10.15 (2017-07-24) -=== - -### Service Client Updates -* `service/appstream`: Updates service API, documentation, and waiters - * Amazon AppStream 2.0 image builders and fleets can now access applications and network resources that rely on Microsoft Active Directory (AD) for authentication and permissions. This new feature allows you to join your streaming instances to your AD, so you can use your existing AD user management tools. -* `service/ec2`: Updates service API and documentation - * Spot Fleet tagging capability allows customers to automatically tag instances launched by Spot Fleet. You can use this feature to label or distinguish instances created by distinct Spot Fleets. Tagging your EC2 instances also enables you to see instance cost allocation by tag in your AWS bill. - -### SDK Bugs -* `aws/signer/v4`: Fix out of bounds panic in stripExcessSpaces [#1412](https://github.com/aws/aws-sdk-go/pull/1412) - * Fixes the out of bands panic in stripExcessSpaces caused by an incorrect calculation of the stripToIdx value. Simplified to code also. - * Fixes [#1411](https://github.com/aws/aws-sdk-go/issues/1411) -Release v1.10.14 (2017-07-20) -=== - -### Service Client Updates -* `service/elasticmapreduce`: Updates service API and documentation - * Amazon EMR now includes the ability to use a custom Amazon Linux AMI and adjustable root volume size when launching a cluster. - -Release v1.10.13 (2017-07-19) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Update budget Management API's to list/create/update RI_UTILIZATION type budget. Update budget Management API's to support DAILY timeUnit for RI_UTILIZATION type budget. - -### SDK Enhancements -* `service/s3`: Use interfaces assertions instead of ValuesAtPath for S3 field lookups. [#1401](https://github.com/aws/aws-sdk-go/pull/1401) - * Improves the performance across the board for all S3 API calls by removing the usage of `ValuesAtPath` being used for every S3 API call. - -### SDK Bugs -* `aws/request`: waiter test bug - * waiters_test.go file would sometimes fail due to travis hiccups. This occurs because a test would sometimes fail the cancel check and succeed the timeout. However, the timeout check should never occur in that test. This fix introduces a new field that dictates how waiters will sleep. -Release v1.10.12 (2017-07-17) -=== - -### Service Client Updates -* `service/cognito-idp`: Updates service API and documentation -* `service/lambda`: Updates service API and documentation - * Lambda@Edge lets you run code closer to your end users without provisioning or managing servers. With Lambda@Edge, your code runs in AWS edge locations, allowing you to respond to your end users at the lowest latency. Your code is triggered by Amazon CloudFront events, such as requests to and from origin servers and viewers, and it is ready to execute at every AWS edge location whenever a request for content is received. You just upload your Node.js code to AWS Lambda and Lambda takes care of everything required to run and scale your code with high availability. You only pay for the compute time you consume - there is no charge when your code is not running. - -Release v1.10.11 (2017-07-14) -=== - -### Service Client Updates -* `service/discovery`: Updates service API and documentation - * Adding feature to the Export API for Discovery Service to allow filters for the export task to allow export based on per agent id. -* `service/ec2`: Updates service API - * New EC2 GPU Graphics instance -* `service/marketplacecommerceanalytics`: Updates service documentation - * Update to Documentation Model For New Report Cadence / Reformat of Docs - -Release v1.10.10 (2017-07-13) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Adds support for management of gateway responses. -* `service/ec2`: Updates service API and documentation - * X-ENI (or Cross-Account ENI) is a new feature that allows the attachment or association of Elastic Network Interfaces (ENI) between VPCs in different AWS accounts located in the same availability zone. With this new capability, service providers and partners can deliver managed solutions in a variety of new architectural patterns where the provider and consumer of the service are in different AWS accounts. -* `service/lex-models`: Updates service documentation - -Release v1.10.9 (2017-07-12) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * Auto Scaling now supports a new type of scaling policy called target tracking scaling policies that you can use to set up dynamic scaling for your application. -* `service/swf`: Updates service API, documentation, paginators, and examples - * Added support for attaching control data to Lambda tasks. Control data lets you attach arbitrary strings to your decisions and history events. - -Release v1.10.8 (2017-07-06) -=== - -### Service Client Updates -* `service/ds`: Updates service API, documentation, and paginators - * You can now improve the resilience and performance of your Microsoft AD directory by deploying additional domain controllers. Added UpdateNumberofDomainControllers API that allows you to update the number of domain controllers you want for your directory, and DescribeDomainControllers API that allows you to describe the detailed information of each domain controller of your directory. Also added the 'DesiredNumberOfDomainControllers' field to the DescribeDirectories API output for Microsoft AD. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kinesis`: Updates service API and documentation - * You can now encrypt your data at rest within an Amazon Kinesis Stream using server-side encryption. Server-side encryption via AWS KMS makes it easy for customers to meet strict data management requirements by encrypting their data at rest within the Amazon Kinesis Streams, a fully managed real-time data processing service. -* `service/kms`: Updates service API and documentation - * This release of AWS Key Management Service introduces the ability to determine whether a key is AWS managed or customer managed. -* `service/ssm`: Updates service API and documentation - * Amazon EC2 Systems Manager now expands Patching support to Amazon Linux, Red Hat and Ubuntu in addition to the already supported Windows Server. - -Release v1.10.7 (2017-07-05) -=== - -### Service Client Updates -* `service/monitoring`: Updates service API and documentation - * We are excited to announce the availability of APIs and CloudFormation support for CloudWatch Dashboards. You can use the new dashboard APIs or CloudFormation templates to dynamically build and maintain dashboards to monitor your infrastructure and applications. There are four new dashboard APIs - PutDashboard, GetDashboard, DeleteDashboards, and ListDashboards APIs. PutDashboard is used to create a new dashboard or modify an existing one whereas GetDashboard is the API to get the details of a specific dashboard. ListDashboards and DeleteDashboards are used to get the names or delete multiple dashboards respectively. Getting started with dashboard APIs is similar to any other AWS APIs. The APIs can be accessed through AWS SDK or through CLI tools. -* `service/route53`: Updates service API and documentation - * Bug fix for InvalidChangeBatch exception. - -### SDK Enhancements -* `service/s3/s3manager`: adding cleanup function to batch objects [#1375](https://github.com/aws/aws-sdk-go/issues/1375) - * This enhancement will add an After field that will be called after each iteration of the batch operation. - -Release v1.10.6 (2017-06-30) -=== - -### Service Client Updates -* `service/marketplacecommerceanalytics`: Updates service documentation - * Documentation updates for AWS Marketplace Commerce Analytics. -* `service/s3`: Updates service API and documentation - * API Update for S3: Adding Object Tagging Header to MultipartUpload Initialization - -Release v1.10.5 (2017-06-29) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/events`: Updates service API and documentation - * CloudWatch Events now allows different AWS accounts to share events with each other through a new resource called event bus. Event buses accept events from AWS services, other AWS accounts and PutEvents API calls. Currently all AWS accounts have one default event bus. To send events to another account, customers simply write rules to match the events of interest and attach an event bus in the receiving account as the target to the rule. The PutTargets API has been updated to allow adding cross account event buses as targets. In addition, we have released two new APIs - PutPermission and RemovePermission - that enables customers to add/remove permissions to their default event bus. -* `service/gamelift`: Updates service API and documentation - * Allow developers to download GameLift fleet creation logs to assist with debugging. -* `service/ssm`: Updates service API and documentation - * Adding Resource Data Sync support to SSM Inventory. New APIs: * CreateResourceDataSync - creates a new resource data sync configuration, * ListResourceDataSync - lists existing resource data sync configurations, * DeleteResourceDataSync - deletes an existing resource data sync configuration. - -Release v1.10.4 (2017-06-27) -=== - -### Service Client Updates -* `service/servicecatalog`: Updates service API, documentation, and paginators - * Proper tagging of resources is critical to post-launch operations such as billing, cost allocation, and resource management. By using Service Catalog's TagOption Library, administrators can define a library of re-usable TagOptions that conform to company standards, and associate these with Service Catalog portfolios and products. Learn how to move your current tags to the new library, create new TagOptions, and view and associate your library items with portfolios and products. Understand how to ensure that the right tags are created on products launched through Service Catalog and how to provide users with defined selectable tags. - -### SDK Bugs -* `aws/signer/v4`: checking length on `stripExcessSpaces` [#1372](https://github.com/aws/aws-sdk-go/issues/1372) - * Fixes a bug where `stripExcessSpaces` did not check length against the slice. - * Fixes: [#1371](https://github.com/aws/aws-sdk-go/issues/1371) -Release v1.10.3 (2017-06-23) -=== - -### Service Client Updates -* `service/lambda`: Updates service API and documentation - * The Lambda Invoke API will now throw new exception InvalidRuntimeException (status code 502) for invokes with deprecated runtimes. - -Release v1.10.2 (2017-06-22) -=== - -### Service Client Updates -* `service/codepipeline`: Updates service API, documentation, and paginators - * A new API, ListPipelineExecutions, enables you to retrieve summary information about the most recent executions in a pipeline, including pipeline execution ID, status, start time, and last updated time. You can request information for a maximum of 100 executions. Pipeline execution data is available for the most recent 12 months of activity. -* `service/dms`: Updates service API and documentation - * Added tagging for DMS certificates. -* `service/elasticloadbalancing`: Updates service waiters -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lightsail`: Updates service API and documentation - * This release adds a new nextPageToken property to the result of the GetOperationsForResource API. Developers can now get the next set of items in a list by making subsequent calls to GetOperationsForResource API with the token from the previous call. This release also deprecates the nextPageCount property, which previously returned null (use the nextPageToken property instead). This release also deprecates the customImageName property on the CreateInstancesRequest class, which was previously ignored by the API. -* `service/route53`: Updates service API and documentation - * This release reintroduces the HealthCheckInUse exception. - -Release v1.10.1 (2017-06-21) -=== - -### Service Client Updates -* `service/dax`: Adds new service - * Amazon DynamoDB Accelerator (DAX) is a fully managed, highly available, in-memory cache for DynamoDB that delivers up to a 10x performance improvement - from milliseconds to microseconds - even at millions of requests per second. DAX does all the heavy lifting required to add in-memory acceleration to your DynamoDB tables, without requiring developers to manage cache invalidation, data population, or cluster management. -* `service/route53`: Updates service API and documentation - * Amazon Route 53 now supports multivalue answers in response to DNS queries, which lets you route traffic approximately randomly to multiple resources, such as web servers. Create one multivalue answer record for each resource and, optionally, associate an Amazon Route 53 health check with each record, and Amazon Route 53 responds to DNS queries with up to eight healthy records. -* `service/ssm`: Updates service API, documentation, and paginators - * Adding hierarchy support to the SSM Parameter Store API. Added support tor tagging. New APIs: GetParameter - retrieves one parameter, DeleteParameters - deletes multiple parameters (max number 10), GetParametersByPath - retrieves parameters located in the hierarchy. Updated APIs: PutParameter - added ability to enforce parameter value by applying regex (AllowedPattern), DescribeParameters - modified to support Tag filtering. -* `service/waf`: Updates service API and documentation - * You can now create, edit, update, and delete a new type of WAF rule with a rate tracking component. -* `service/waf-regional`: Updates service API and documentation - -Release v1.10.0 (2017-06-20) -=== - -### Service Client Updates -* `service/workdocs`: Updates service API and documentation - * This release provides a new API to retrieve the activities performed by WorkDocs users. - -### SDK Features -* `aws/credentials/plugincreds`: Add support for Go plugin for credentials [#1320](https://github.com/aws/aws-sdk-go/pull/1320) - * Adds support for using plugins to retrieve credentials for API requests. This change adds a new package plugincreds under aws/credentials. See the `example/aws/credentials/plugincreds` folder in the SDK for example usage. - -Release v1.9.00 (2017-06-19) -=== - -### Service Client Updates -* `service/organizations`: Updates service API and documentation - * Improvements to Exception Modeling - -### SDK Features -* `service/s3/s3manager`: Adds batch operations to s3manager [#1333](https://github.com/aws/aws-sdk-go/pull/1333) - * Allows for batch upload, download, and delete of objects. Also adds the interface pattern to allow for easy traversal of objects. E.G `DownloadWithIterator`, `UploadWithIterator`, and `BatchDelete`. `BatchDelete` also contains a utility iterator using the `ListObjects` API to easily delete a list of objects. - -Release v1.8.44 (2017-06-16) -=== - -### Service Client Updates -* `service/xray`: Updates service API, documentation, and paginators - * Add a response time histogram to the services in response of GetServiceGraph API. - -Release v1.8.43 (2017-06-15) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Adds API to describe Amazon FPGA Images (AFIs) available to customers, which includes public AFIs, private AFIs that you own, and AFIs owned by other AWS accounts for which you have load permissions. -* `service/ecs`: Updates service API and documentation - * Added support for cpu, memory, and memory reservation container overrides on the RunTask and StartTask APIs. -* `service/iot`: Updates service API and documentation - * Revert the last release: remove CertificatePem from DescribeCertificate API. -* `service/servicecatalog`: Updates service API, documentation, and paginators - * Added ProvisioningArtifactSummaries to DescribeProductAsAdmin's output to show the provisioning artifacts belong to the product. Allow filtering by SourceProductId in SearchProductsAsAdmin for AWS Marketplace products. Added a verbose option to DescribeProvisioningArtifact to display the CloudFormation template used to create the provisioning artifact.Added DescribeProvisionedProduct API. Changed the type of ProvisionedProduct's Status to be distinct from Record's Status. New ProvisionedProduct's Status are AVAILABLE, UNDER_CHANGE, TAINTED, ERROR. Changed Record's Status set of values to CREATED, IN_PROGRESS, IN_PROGRESS_IN_ERROR, SUCCEEDED, FAILED. - -### SDK Bugs -* `private/model/api`: Fix RESTXML support for XML Namespace [#1343](https://github.com/aws/aws-sdk-go/pull/1343) - * Fixes a bug with the SDK's generation of services using the REST XML protocol not annotating shape references with the XML Namespace attribute. - * Fixes [#1334](https://github.com/aws/aws-sdk-go/pull/1334) -Release v1.8.42 (2017-06-14) -=== - -### Service Client Updates -* `service/applicationautoscaling`: Updates service API and documentation -* `service/clouddirectory`: Updates service documentation - * Documentation update for Cloud Directory - -Release v1.8.41 (2017-06-13) -=== - -### Service Client Updates -* `service/configservice`: Updates service API - -Release v1.8.40 (2017-06-13) -=== - -### Service Client Updates -* `service/rds`: Updates service API and documentation - * API Update for RDS: this update enables copy-on-write, a new Aurora MySQL Compatible Edition feature that allows users to restore their database, and support copy of TDE enabled snapshot cross region. - -### SDK Bugs -* `aws/request`: Fix NewErrParamMinLen to use correct ParamMinLenErrCode [#1336](https://github.com/aws/aws-sdk-go/issues/1336) - * Fixes the `NewErrParamMinLen` function returning the wrong error code. `ParamMinLenErrCode` should be returned not `ParamMinValueErrCode`. - * Fixes [#1335](https://github.com/aws/aws-sdk-go/issues/1335) -Release v1.8.39 (2017-06-09) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/opsworks`: Updates service API and documentation - * Tagging Support for AWS OpsWorks Stacks - -Release v1.8.38 (2017-06-08) -=== - -### Service Client Updates -* `service/iot`: Updates service API and documentation - * In addition to using certificate ID, AWS IoT customers can now obtain the description of a certificate with the certificate PEM. -* `service/pinpoint`: Updates service API and documentation - * Starting today Amazon Pinpoint adds SMS Text and Email Messaging support in addition to Mobile Push Notifications, providing developers, product managers and marketers with multi-channel messaging capabilities to drive user engagement in their applications. Pinpoint also enables backend services and applications to message users directly and provides advanced user and app analytics to understand user behavior and messaging performance. -* `service/rekognition`: Updates service API and documentation - * API Update for AmazonRekognition: Adding RecognizeCelebrities API - -Release v1.8.37 (2017-06-07) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Add support to APIs for privileged containers. This change would allow performing privileged operations like starting the Docker daemon inside builds possible in custom docker images. -* `service/greengrass`: Adds new service - * AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud. - -Release v1.8.36 (2017-06-06) -=== - -### Service Client Updates -* `service/acm`: Updates service documentation - * Documentation update for AWS Certificate Manager. -* `service/cloudfront`: Updates service documentation - * Doc update to fix incorrect prefix in S3OriginConfig -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iot`: Updates service API - * Update client side validation for SalesForce action. - -Release v1.8.35 (2017-06-05) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * AppStream 2.0 Custom Security Groups allows you to easily control what network resources your streaming instances and images have access to. You can assign up to 5 security groups per Fleet to control the inbound and outbound network access to your streaming instances to specific IP ranges, network protocols, or ports. -* `service/iot`: Updates service API, documentation, paginators, and examples - * Added Salesforce action to IoT Rules Engine. - -Release v1.8.34 (2017-06-02) -=== - -### Service Client Updates -* `service/kinesisanalytics`: Updates service API, documentation, and paginators - * Kinesis Analytics publishes error messages CloudWatch logs in case of application misconfigurations -* `service/workdocs`: Updates service API and documentation - * This release includes new APIs to manage tags and custom metadata on resources and also new APIs to add and retrieve comments at the document level. - -Release v1.8.33 (2017-06-01) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * AWS CodeDeploy has improved how it manages connections to GitHub accounts and repositories. You can now create and store up to 25 connections to GitHub accounts in order to associate AWS CodeDeploy applications with GitHub repositories. Each connection can support multiple repositories. You can create connections to up to 25 different GitHub accounts, or create more than one connection to a single account. The ListGitHubAccountTokenNames command has been introduced to retrieve the names of stored connections to GitHub accounts that you have created. The name of the connection to GitHub used for an AWS CodeDeploy application is also included in the ApplicationInfo structure. Two new fields, lastAttemptedDeployment and lastSuccessfulDeployment, have been added to DeploymentGroupInfo to improve the handling of deployment group information in the AWS CodeDeploy console. Information about these latest deployments can also be retrieved using the GetDeploymentGroup and BatchGetDeployment group requests. Also includes a region update (us-gov-west-1). -* `service/cognitoidentityprovider`: Updates service API, documentation, and paginators -* `service/elbv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lexmodelbuildingservice`: Updates service documentation and examples - -### SDK Enhancements -* `aws/defaults`: Exports shared credentials and config default filenames used by the SDK. [#1308](https://github.com/aws/aws-sdk-go/pull/1308) - * Adds SharedCredentialsFilename and SharedConfigFilename functions to defaults package. - -### SDK Bugs -* `aws/credentials`: Fixes shared credential provider's default filename on Windows. [#1308](https://github.com/aws/aws-sdk-go/pull/1308) - * The shared credentials provider would attempt to use the wrong filename on Windows if the `HOME` environment variable was defined. -* `service/s3/s3manager`: service/s3/s3manager: Fix Downloader ignoring Range get parameter [#1311](https://github.com/aws/aws-sdk-go/pull/1311) - * Fixes the S3 Download Manager ignoring the GetObjectInput's Range parameter. If this parameter is provided it will force the downloader to fallback to a single GetObject request disabling concurrency and automatic part size gets. - * Fixes [#1296](https://github.com/aws/aws-sdk-go/issues/1296) -Release v1.8.32 (2017-05-31) -=== - -### Service Client Updates -* `service/rds`: Updates service API and documentation - * Amazon RDS customers can now easily and quickly stop and start their DB instances. - -Release v1.8.31 (2017-05-30) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API, documentation, and paginators - * Cloud Directory has launched support for Typed Links, enabling customers to create object-to-object relationships that are not hierarchical in nature. Typed Links enable customers to quickly query for data along these relationships. Customers can also enforce referential integrity using Typed Links, ensuring data in use is not inadvertently deleted. -* `service/s3`: Updates service paginators and examples - * New example snippets for Amazon S3. - -Release v1.8.30 (2017-05-25) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Support added for persistent user storage, backed by S3. -* `service/rekognition`: Updates service API and documentation - * Updated the CompareFaces API response to include orientation information, unmatched faces, landmarks, pose, and quality of the compared faces. - -Release v1.8.29 (2017-05-24) -=== - -### Service Client Updates -* `service/iam`: Updates service API - * The unique ID and access key lengths were extended from 32 to 128 -* `service/storagegateway`: Updates service API and documentation - * Two Storage Gateway data types, Tape and TapeArchive, each have a new response element, TapeUsedInBytes. This element helps you manage your virtual tapes. By using TapeUsedInBytes, you can see the amount of data written to each virtual tape. -* `service/sts`: Updates service API, documentation, and paginators - * The unique ID and access key lengths were extended from 32 to 128. - -Release v1.8.28 (2017-05-23) -=== - -### Service Client Updates -* `service/databasemigrationservice`: Updates service API, documentation, paginators, and examples - * This release adds support for using Amazon S3 and Amazon DynamoDB as targets for database migration, and using MongoDB as a source for database migration. For more information, see the AWS Database Migration Service documentation. - -Release v1.8.27 (2017-05-22) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/resourcegroupstaggingapi`: Updates service API, documentation, and paginators - * You can now specify the number of resources returned per page in GetResources operation, as an optional parameter, to easily manage the list of resources returned by your queries. - -### SDK Bugs -* `aws/request`: Add support for PUT temporary redirects (307) [#1283](https://github.com/aws/aws-sdk-go/issues/1283) - * Adds support for Go 1.8's GetBody function allowing the SDK's http request using PUT and POST methods to be redirected with temporary redirects with 307 status code. - * Fixes: [#1267](https://github.com/aws/aws-sdk-go/issues/1267) -* `aws/request`: Add handling for retrying temporary errors during unmarshal [#1289](https://github.com/aws/aws-sdk-go/issues/1289) - * Adds support for retrying temporary errors that occur during unmarshaling of a request's response body. - * Fixes: [#1275](https://github.com/aws/aws-sdk-go/issues/1275) -Release v1.8.26 (2017-05-18) -=== - -### Service Client Updates -* `service/athena`: Adds new service - * This release adds support for Amazon Athena. Amazon Athena is an interactive query service that makes it easy to analyze data in Amazon S3 using standard SQL. Athena is serverless, so there is no infrastructure to manage, and you pay only for the queries that you run. -* `service/lightsail`: Updates service API, documentation, and paginators - * This release adds new APIs that make it easier to set network port configurations on Lightsail instances. Developers can now make a single request to both open and close public ports on an instance using the PutInstancePublicPorts operation. - -### SDK Bugs -* `aws/request`: Fix logging from reporting wrong retry request errors #1281 - * Fixes the SDK's retry request logging to report the the actual error that occurred, not a stubbed Unknown error message. - * Fixes the SDK's response logger to not output the response log multiple times per retry. -Release v1.8.25 (2017-05-17) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service documentation, paginators, and examples - * Various Auto Scaling documentation updates -* `service/cloudwatchevents`: Updates service documentation - * Various CloudWatch Events documentation updates. -* `service/cloudwatchlogs`: Updates service documentation and paginators - * Various CloudWatch Logs documentation updates. -* `service/polly`: Updates service API - * Amazon Polly adds new German voice "Vicki" - -Release v1.8.24 (2017-05-16) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * This release introduces the previousRevision field in the responses to the GetDeployment and BatchGetDeployments actions. previousRevision provides information about the application revision that was deployed to the deployment group before the most recent successful deployment. Also, the fileExistsBehavior parameter has been added for CreateDeployment action requests. In the past, if the AWS CodeDeploy agent detected files in a target location that weren't part of the application revision from the most recent successful deployment, it would fail the current deployment by default. This new parameter provides options for how the agent handles these files: fail the deployment, retain the content, or overwrite the content. -* `service/gamelift`: Updates service API and documentation - * Allow developers to specify how metrics are grouped in CloudWatch for their GameLift fleets. Developers can also specify how many concurrent game sessions activate on a per-instance basis. -* `service/inspector`: Updates service API, documentation, paginators, and examples - * Adds ability to produce an assessment report that includes detailed and comprehensive results of a specified assessment run. -* `service/kms`: Updates service documentation - * Update documentation for KMS. - -Release v1.8.23 (2017-05-15) -=== - -### Service Client Updates -* `service/ssm`: Updates service API and documentation - * UpdateAssociation API now supports updating document name and targets of an association. GetAutomationExecution API can return FailureDetails as an optional field to the StepExecution Object, which contains failure type, failure stage as well as other failure related information for a failed step. - -### SDK Enhancements -* `aws/session`: SDK should be able to load multiple custom shared config files. [#1258](https://github.com/aws/aws-sdk-go/issues/1258) - * This change adds a `SharedConfigFiles` field to the `session.Options` type that allows you to specify the files, and their order, the SDK will use for loading shared configuration and credentials from when the `Session` is created. Use the `NewSessionWithOptions` Session constructor to specify these options. You'll also most likely want to enable support for the shared configuration file's additional attributes by setting `session.Option`'s `SharedConfigState` to `session.SharedConfigEnabled`. - -Release v1.8.22 (2017-05-11) -=== - -### Service Client Updates -* `service/elb`: Updates service API, documentation, and paginators -* `service/elbv2`: Updates service API and documentation -* `service/lexmodelbuildingservice`: Updates service API and documentation -* `service/organizations`: Updates service API, documentation, paginators, and examples - * AWS Organizations APIs that return an Account object now include the email address associated with the account’s root user. - -Release v1.8.21 (2017-05-09) -=== - -### Service Client Updates -* `service/codestar`: Updates service documentation - * Updated documentation for AWS CodeStar. -* `service/workspaces`: Updates service API, documentation, and paginators - * Doc-only Update for WorkSpaces - -Release v1.8.20 (2017-05-04) -=== - -### Service Client Updates -* `service/ecs`: Updates service API, documentation, and paginators - * Exposes container instance registration time in ECS:DescribeContainerInstances. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/marketplaceentitlementservice`: Adds new service -* `service/lambda`: Updates service API and documentation - * Support for UpdateFunctionCode DryRun option - -Release v1.8.19 (2017-04-28) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service waiters and paginators - * Adding back the removed waiters and paginators. - -Release v1.8.18 (2017-04-28) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API, documentation, waiters, paginators, and examples - * API update for CloudFormation: New optional parameter ClientRequestToken which can be used as an idempotency token to safely retry certain operations as well as tagging StackEvents. -* `service/rds`: Updates service API, documentation, and examples - * The DescribeDBClusterSnapshots API now returns a SourceDBClusterSnapshotArn field which identifies the source DB cluster snapshot of a copied snapshot. -* `service/rekognition`: Updates service API - * Fix for missing file type check -* `service/snowball`: Updates service API, documentation, and paginators - * The Snowball API has a new exception that can be thrown for list operation requests. -* `service/sqs`: Updates service API, documentation, and paginators - * Adding server-side encryption (SSE) support to SQS by integrating with AWS KMS; adding new queue attributes to SQS CreateQueue, SetQueueAttributes and GetQueueAttributes APIs to support SSE. - -Release v1.8.17 (2017-04-26) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * With Amazon Relational Database Service (Amazon RDS) running MySQL or Amazon Aurora, you can now authenticate to your DB instance using IAM database authentication. - -Release v1.8.16 (2017-04-21) -=== - -### Service Client Updates -* `service/appstream`: Updates service API, documentation, and paginators - * The new feature named "Default Internet Access" will enable Internet access from AppStream 2.0 instances - image builders and fleet instances. Admins will check a flag either through AWS management console for AppStream 2.0 or through API while creating an image builder or while creating/updating a fleet. -* `service/kinesis`: Updates service API, documentation, waiters, and paginators - * Adds a new waiter, StreamNotExists, to Kinesis. - -### SDK Enhancements -* `aws/endpoints`: Add utilities improving endpoints lookup (#1218) - * Adds several utilities to the endpoints packages to make looking up partitions, regions, and services easier. - * Fixes #994 - -### SDK Bugs -* `private/protocol/xml/xmlutil`: Fix unmarshaling dropping errors (#1219) - * The XML unmarshaler would drop any serialization or body read error that occurred on the floor effectively hiding any errors that would occur. - * Fixes #1205 -Release v1.8.15 (2017-04-20) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * API Update for AWS Device Farm: Support for Deals and Promotions -* `service/directconnect`: Updates service documentation - * Documentation updates for AWS Direct Connect. -* `service/elbv2`: Updates service waiters -* `service/kms`: Updates service documentation and examples - * Doc-only update for Key Management Service (KMS): Update docs for GrantConstraints and GenerateRandom -* `service/route53`: Updates service documentation - * Release notes: SDK documentation now includes examples for ChangeResourceRecordSets for all types of resource record set, such as weighted, alias, and failover. -* `service/route53domains`: Updates service API, documentation, and paginators - * Adding examples and other documentation updates. - -### SDK Enhancements -* `service/s3`: Add utilities to make getting a bucket's region easier (#1207) - * Adds two features which make it easier to get a bucket's region, `s3.NormalizeBucketLocation` and `s3manager.GetBucketRegion`. - -### SDK Bugs -* `service/s3`: Fix HeadObject's incorrect documented error codes (#1213) - * The HeadObject's model incorrectly states that the operation can return the NoSuchKey error code. - * Fixes #1208 - -Release v1.8.14 (2017-04-19) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Add support for "embed" property. -* `service/codestar`: Adds new service - * AWS CodeStar is a cloud-based service for creating, managing, and working with software development projects on AWS. An AWS CodeStar project creates and integrates AWS services for your project development toolchain. AWS CodeStar also manages the permissions required for project users. -* `service/ec2`: Updates service API and documentation - * Adds support for creating an Amazon FPGA Image (AFI) from a specified design checkpoint (DCP). -* `service/iam`: Updates service API and documentation - * This changes introduces a new IAM role type, Service Linked Role, which works like a normal role but must be managed via services' control. -* `service/lambda`: Updates service API and documentation - * Lambda integration with CloudDebugger service to enable customers to enable tracing for the Lambda functions and send trace information to the CloudDebugger service. -* `service/lexmodelbuildingservice`: Adds new service -* `service/polly`: Updates service API, documentation, and paginators - * API Update for Amazon Polly: Add support for speech marks -* `service/rekognition`: Updates service API and documentation - * Given an image, the API detects explicit or suggestive adult content in the image and returns a list of corresponding labels with confidence scores, as well as a taxonomy (parent-child relation) for each label. - -Release v1.8.13 (2017-04-18) -=== - -### Service Client Updates -* `service/lambda`: Updates service API and documentation - * You can use tags to group and filter your Lambda functions, making it easier to analyze them for billing allocation purposes. For more information, see Tagging Lambda Functions. You can now write or upgrade your Lambda functions using Python version 3.6. For more information, see Programming Model for Authoring Lambda Functions in Python. Note: Features will be rolled out in the US regions on 4/19. - -### SDK Enhancements -* `aws/request`: add support for appengine's custom standard library (#1190) - * Remove syscall error checking on appengine platforms. - -Release v1.8.12 (2017-04-11) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * API Gateway request validators -* `service/batch`: Updates service API and documentation - * API Update for AWS Batch: Customer provided AMI for MANAGED Compute Environment -* `service/gamelift`: Updates service API and documentation - * Allows developers to utilize an improved workflow when calling our Queues API and introduces a new feature that allows developers to specify a maximum allowable latency per Queue. -* `service/opsworks`: Updates service API, documentation, and paginators - * Cloudwatch Logs agent configuration can now be attached to OpsWorks Layers using CreateLayer and UpdateLayer. OpsWorks will then automatically install and manage the CloudWatch Logs agent on the instances part of the OpsWorks Layer. - -### SDK Bugs -* `aws/client`: Fix clients polluting handler list (#1197) - * Fixes the clients potentially polluting the passed in handler list with the client's customizations. This change ensures every client always works with a clean copy of the request handlers and it cannot pollute the handlers back upstream. - * Fixes #1184 -* `aws/request`: Fix waiter error match condition (#1195) - * Fixes the waiters's matching overwriting the request's err, effectively ignoring the error condition. This broke waiters with the FailureWaiterState matcher state. -Release v1.8.11 (2017-04-07) -=== - -### Service Client Updates -* `service/redshift`: Updates service API, documentation, and paginators - * This update adds the GetClusterCredentials API which is used to get temporary login credentials to the cluster. AccountWithRestoreAccess now has a new member AccountAlias, this is the identifier of the AWS support account authorized to restore the specified snapshot. This is added to support the feature where the customer can share their snapshot with the Amazon Redshift Support Account without having to manually specify the AWS Redshift Service account ID on the AWS Console/API. - -Release v1.8.10 (2017-04-06) -=== - -### Service Client Updates -* `service/elbv2`: Updates service documentation - -Release v1.8.9 (2017-04-05) -=== - -### Service Client Updates -* `service/elasticache`: Updates service API, documentation, paginators, and examples - * ElastiCache added support for testing the Elasticache Multi-AZ feature with Automatic Failover. - -Release v1.8.8 (2017-04-04) -=== - -### Service Client Updates -* `service/cloudwatch`: Updates service API, documentation, and paginators - * Amazon Web Services announced the immediate availability of two additional alarm configuration rules for Amazon CloudWatch Alarms. The first rule is for configuring missing data treatment. Customers have the options to treat missing data as alarm threshold breached, alarm threshold not breached, maintain alarm state and the current default treatment. The second rule is for alarms based on percentiles metrics that can trigger unnecassarily if the percentile is calculated from a small number of samples. The new rule can treat percentiles with low sample counts as same as missing data. If the first rule is enabled, the same treatment will be applied when an alarm encounters a percentile with low sample counts. - -Release v1.8.7 (2017-04-03) -=== - -### Service Client Updates -* `service/lexruntimeservice`: Updates service API and documentation - * Adds support to PostContent for speech input - -### SDK Enhancements -* `aws/request`: Improve handler copy, push back, push front performance (#1171) - * Minor optimization to the handler list's handling of copying and pushing request handlers to the handler list. -* Update codegen header to use Go std wording (#1172) - * Go recently accepted the proposal for standard generated file header wording in, https://golang.org/s/generatedcode. - -### SDK Bugs -* `service/dynamodb`: Fix DynamoDB using custom retryer (#1170) - * Fixes (#1139) the DynamoDB service client clobbering any custom retryer that was passed into the service client or Session's config. -Release v1.8.6 (2017-04-01) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * ListObjectAttributes now supports filtering by facet. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.8.5 (2017-03-30) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service waiters and paginators - * Adding paginators for ListExports and ListImports -* `service/cloudfront`: Adds new service - * Amazon CloudFront now supports user configurable HTTP Read and Keep-Alive Idle Timeouts for your Custom Origin Servers -* `service/configservice`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/resourcegroupstaggingapi`: Adds new service -* `service/storagegateway`: Updates service API and documentation - * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. Once a file share is created, any changes made externally to the S3 bucket will not be reflected by the gateway. Using the cache refresh feature in this update, the customer can trigger an on-demand scan of the keys in their S3 bucket and refresh the file namespace cached on the gateway. It takes as an input the fileShare ARN and refreshes the cache for only that file share. Additionally there is new functionality on file gateway that allows you configure what squash options they would like on their file share, this allows a customer to configure their gateway to not squash root permissions. This can be done by setting options in NfsOptions for CreateNfsFileShare and UpdateNfsFileShare APIs. - -Release v1.8.4 (2017-03-28) -=== - -### Service Client Updates -* `service/batch`: Updates service API, documentation, and paginators - * Customers can now provide a retryStrategy as part of the RegisterJobDefinition and SubmitJob API calls. The retryStrategy object has a number value for attempts. This is the number of non successful executions before a job is considered FAILED. In addition, the JobDetail object now has an attempts field and shows all execution attempts. -* `service/ec2`: Updates service API and documentation - * Customers can now tag their Amazon EC2 Instances and Amazon EBS Volumes at - the time of their creation. You can do this from the EC2 Instance launch - wizard or through the RunInstances or CreateVolume APIs. By tagging - resources at the time of creation, you can eliminate the need to run custom - tagging scripts after resource creation. In addition, you can now set - resource-level permissions on the CreateVolume, CreateTags, DeleteTags, and - the RunInstances APIs. This allows you to implement stronger security - policies by giving you more granular control over which users and groups - have access to these APIs. You can also enforce the use of tagging and - control what tag keys and values are set on your resources. When you combine - tag usage and resource-level IAM policies together, you can ensure your - instances and volumes are properly secured upon creation and achieve more - accurate cost allocation reporting. These new features are provided at no - additional cost. - -### SDK Enhancements -* `aws/request`: Add retry support for RequestTimeoutException (#1158) - * Adds support for retrying RequestTimeoutException error code that is returned by some services. - -### SDK Bugs -* `private/model/api`: Fix Waiter and Paginators panic on nil param inputs (#1157) - * Corrects the code generation for Paginators and waiters that caused a panic if nil input parameters were used with the operations. -Release v1.8.3 (2017-03-27) -=== - -## Service Client Updates -* `service/ssm`: Updates service API, documentation, and paginators - * Updated validation rules for SendCommand and RegisterTaskWithMaintenanceWindow APIs. -Release v1.8.2 (2017-03-24) -=== - -Service Client Updates ---- -* `service/applicationautoscaling`: Updates service API, documentation, and paginators - * Application AutoScaling is launching support for a new target resource (AppStream 2.0 Fleets) as a scalable target. -* `service/cloudtrail`: Updates service API and documentation - * Doc-only Update for CloudTrail: Add required parameters for GetEventSelectors and PutEventSelectors - -Release v1.8.1 (2017-03-23) -=== - -Service Client Updates ---- -* `service/applicationdiscoveryservice`: Updates service API, documentation, and paginators - * Adds export configuration options to the AWS Discovery Service API. -* `service/elbv2`: Updates waiters -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lambda`: Updates service API and paginators - * Adds support for new runtime Node.js v6.10 for AWS Lambda service - -Release v1.8.0 (2017-03-22) -=== - -Service Client Updates ---- -* `service/codebuild`: Updates service documentation -* `service/directconnect`: Updates service API - * Deprecated DescribeConnectionLoa, DescribeInterconnectLoa, AllocateConnectionOnInterconnect and DescribeConnectionsOnInterconnect operations in favor of DescribeLoa, DescribeLoa, AllocateHostedConnection and DescribeHostedConnections respectively. -* `service/marketplacecommerceanalytics`: Updates service API, documentation, and paginators - * This update adds a new data set, us_sales_and_use_tax_records, which enables AWS Marketplace sellers to programmatically access to their U.S. Sales and Use Tax report data. -* `service/pinpoint`: Updates service API and documentation - * Amazon Pinpoint User Segmentation - * Added ability to segment endpoints by user attributes in addition to endpoint attributes. Amazon Pinpoint Event Stream Preview - * Added functionality to publish raw app analytics and campaign events data as events streams to Kinesis and Kinesis Firehose - * The feature provides developers with increased flexibility of exporting raw events to S3, Redshift, Elasticsearch using a Kinesis Firehose stream or enable real time event processing use cases using a Kinesis stream -* `service/rekognition`: Updates service documentation. - -SDK Features ---- -* `aws/request`: Add support for context.Context to SDK API operation requests (#1132) - * Adds support for context.Context to the SDK by adding `WithContext` methods for each API operation, Paginators and Waiters. e.g `PutObjectWithContext`. This change also adds the ability to provide request functional options to the method calls instead of requiring you to use the `Request` API operation method (e.g `PutObjectRequest`). - * Adds a `Complete` Request handler list that will be called ever time a request is completed. This includes both success and failure. Complete will only be called once per API operation request. - * `private/waiter` package moved from the private group to `aws/request/waiter` and made publicly available. - * Adds Context support to all API operations, Waiters(WaitUntil) and Paginators(Pages) methods. - * Adds Context support for s3manager and s3crypto clients. - -SDK Enhancements ---- -* `aws/signer/v4`: Adds support for unsigned payload signer config (#1130) - * Adds configuration option to the v4.Signer to specify the request's body should not be signed. This will only correclty function on services that support unsigned payload. e.g. S3, Glacier. - -SDK Bug Fixes ---- -* `service/s3`: Fix S3 HostID to be available in S3 request error message (#1131) - * Adds a new type s3.RequestFailure which exposes the S3 HostID value from a S3 API operation response. This is helpful when you have an error with S3, and need to contact support. Both RequestID and HostID are needed. -* `private/model/api`: Do not return a link if uid is empty (#1133) - * Fixes SDK's doc generation to not generate API reference doc links if the SDK us unable to create a valid link. -* `aws/request`: Optimization to handler list copy to prevent multiple alloc calls. (#1134) -Release v1.7.9 (2017-03-13) -=== - -Service Client Updates ---- -* `service/devicefarm`: Updates service API, documentation, paginators, and examples - * Network shaping allows users to simulate network connections and conditions while testing their Android, iOS, and web apps with AWS Device Farm. -* `service/cloudwatchevents`: Updates service API, documentation, and examples - -SDK Enhancement -=== -* `aws/session`: Add support for side loaded CA bundles (#1117) - * Adds supports for side loading Certificate Authority bundle files to the SDK using AWS_CA_BUNDLE environment variable or CustomCABundle session option. -* `service/s3/s3crypto`: Add support for AES/CBC/PKCS5Padding (#1124) - -SDK Bug -=== -* `service/rds`: Fixing issue when not providing `SourceRegion` on cross -region operations (#1127) -* `service/rds`: Enables cross region for `CopyDBClusterSnapshot` and -`CreateDBCluster` (#1128) - -Release v1.7.8 (2017-03-10) -=== - -Service Client Updates ---- -* `service/codedeploy`: Updates service paginators - * Add paginators for Codedeploy -* `service/emr`: Updates service API, documentation, and paginators - * This release includes support for instance fleets in Amazon EMR. - -Release v1.7.7 (2017-03-09) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API, documentation, and paginators - * API Gateway has added support for ACM certificates on custom domain names. Both Amazon-issued certificates and uploaded third-part certificates are supported. -* `service/clouddirectory`: Updates service API, documentation, and paginators - * Introduces a new Cloud Directory API that enables you to retrieve all available parent paths for any type of object (a node, leaf node, policy node, and index node) in a hierarchy. - -Release v1.7.6 (2017-03-09) -=== - -Service Client Updates ---- -* `service/organizations`: Updates service documentation and examples - * Doc-only Update for Organizations: Add SDK Code Snippets -* `service/workdocs`: Adds new service - * The Administrative SDKs for Amazon WorkDocs provides full administrator level access to WorkDocs site resources, allowing developers to integrate their applications to manage WorkDocs users, content and permissions programmatically - -Release v1.7.5 (2017-03-08) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Add support to using encrypted clusters as cross-region replication masters. Update CopyDBClusterSnapshot API to support encrypted cross region copy of Aurora cluster snapshots. - -Release v1.7.4 (2017-03-06) -=== - -Service Client Updates ---- -* `service/budgets`: Updates service API and paginators - * When creating or editing a budget via the AWS Budgets API you can define notifications that are sent to subscribers when the actual or forecasted value for cost or usage exceeds the notificationThreshold associated with the budget notification object. Starting today, the maximum allowed value for the notificationThreshold was raised from 100 to 300. This change was made to give you more flexibility when setting budget notifications. -* `service/cloudtrail`: Updates service documentation and paginators - * Doc-only update for AWSCloudTrail: Updated links/descriptions -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/opsworkscm`: Updates service API, documentation, and paginators - * OpsWorks for Chef Automate has added a new field "AssociatePublicIpAddress" to the CreateServer request, "CloudFormationStackArn" to the Server model and "TERMINATED" server state. - - -Release v1.7.3 (2017-02-28) -=== - -Service Client Updates ---- -* `service/mturk`: Renaming service - * service/mechanicalturkrequesterservice was renamed to service/mturk. Be sure to change any references of the old client to the new. - -Release v1.7.2 (2017-02-28) -=== - -Service Client Updates ---- -* `service/dynamodb`: Updates service API and documentation - * Release notes: Time to Live (TTL) is a feature that allows you to define when items in a table expire and can be purged from the database, so that you don't have to track expired data and delete it manually. With TTL enabled on a DynamoDB table, you can set a timestamp for deletion on a per-item basis, allowing you to limit storage usage to only those records that are relevant. -* `service/iam`: Updates service API, documentation, and paginators - * This release adds support for AWS Organizations service control policies (SCPs) to SimulatePrincipalPolicy operation. If there are SCPs associated with the simulated user's account, their effect on the result is captured in the OrganizationDecisionDetail element in the EvaluationResult. -* `service/mechanicalturkrequesterservice`: Adds new service - * Amazon Mechanical Turk is a web service that provides an on-demand, scalable, human workforce to complete jobs that humans can do better than computers, for example, recognizing objects in photos. -* `service/organizations`: Adds new service - * AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources. -* `service/dynamodbstreams`: Updates service API, documentation, and paginators -* `service/waf`: Updates service API, documentation, and paginators - * Aws WAF - For GetSampledRequests action, changed max number of samples from 100 to 500. -* `service/wafregional`: Updates service API, documentation, and paginators - -Release v1.7.1 (2017-02-24) -=== - -Service Client Updates ---- -* `service/elasticsearchservice`: Updates service API, documentation, paginators, and examples - * Added three new API calls to existing Amazon Elasticsearch service to expose Amazon Elasticsearch imposed limits to customers. - -Release v1.7.0 (2017-02-23) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API - * New EC2 I3 instance type - -SDK Bug ---- -* `service/s3/s3manager`: Adding support for SSE (#1097) - * Fixes SSE fields not being applied to a part during multi part upload. - -SDK Feature ---- -* `aws/session`: Add support for AssumeRoles with MFA (#1088) - * Adds support for assuming IAM roles with MFA enabled. A TokenProvider func was added to stscreds.AssumeRoleProvider that will be called each time the role's credentials need to be refreshed. A basic token provider that sources the MFA token from stdin as stscreds.StdinTokenProvider. -* `aws/session`: Update SDK examples and docs to use session.Must (#1099) - * Updates the SDK's example and docs to use session.Must where possible to highlight its usage as apposed to session error checking that is most cases errors will be terminal to the application anyways. -Release v1.6.27 (2017-02-22) -=== - -Service Client Updates ---- -* `service/clouddirectory`: Updates service documentation - * ListObjectAttributes documentation updated based on forum feedback -* `service/elasticbeanstalk`: Updates service API, documentation, and paginators - * Elastic Beanstalk adds support for creating and managing custom platform. -* `service/gamelift`: Updates service API, documentation, and paginators - * Allow developers to configure global queues for creating GameSessions. Allow PlayerData on PlayerSessions to store player-specific data. -* `service/route53`: Updates service API, documentation, and examples - * Added support for operations CreateVPCAssociationAuthorization and DeleteVPCAssociationAuthorization to throw a ConcurrentModification error when a conflicting modification occurs in parallel to the authorizations in place for a given hosted zone. - -Release v1.6.26 (2017-02-21) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API and documentation - * Added the billingProduct parameter to the RegisterImage API. - -Release v1.6.25 (2017-02-17) -=== - -Service Client Updates ---- -* `service/directconnect`: Updates service API, documentation, and paginators - * This update will introduce the ability for Direct Connect customers to take advantage of Link Aggregation (LAG). This allows you to bundle many individual physical interfaces into a single logical interface, referred to as a LAG. This makes administration much simpler as the majority of configuration is done on the LAG while you are free to add or remove physical interfaces from the bundle as bandwidth demand increases or decreases. A concrete example of the simplification added by LAG is that customers need only a single BGP session as opposed to one session per physical connection. - -Release v1.6.24 (2017-02-16) -=== - -Service Client Updates ---- -* `service/cognitoidentity`: Updates service API, documentation, and paginators - * Allow createIdentityPool and updateIdentityPool API to set server side token check value on identity pool -* `service/configservice`: Updates service API and documentation - * AWS Config now supports a new test mode for the PutEvaluations API. Set the TestMode parameter to true in your custom rule to verify whether your AWS Lambda function will deliver evaluation results to AWS Config. No updates occur to your existing evaluations, and evaluation results are not sent to AWS Config. - -Release v1.6.23 (2017-02-15) -=== - -Service Client Updates ---- -* `service/kms`: Updates service API, documentation, paginators, and examples - * his release of AWS Key Management Service introduces the ability to tag keys. Tagging keys can help you organize your keys and track your KMS costs in the cost allocation report. This release also increases the maximum length of a key ID to accommodate ARNs that include a long key alias. - -Release v1.6.22 (2017-02-14) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API, documentation, and paginators - * Adds support for the new Modify Volumes apis. - -Release v1.6.21 (2017-02-11) -=== - -Service Client Updates ---- -* `service/storagegateway`: Updates service API, documentation, and paginators - * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. This is done by creating Nfs file shares using existing APIs CreateNfsFileShare. Using the feature in this update, the customer can restrict the clients that have read/write access to the gateway by specifying the list of clients as a list of IP addresses or CIDR blocks. This list can be specified using the API CreateNfsFileShare while creating new file shares, or UpdateNfsFileShare while update existing file shares. To find out the list of clients that have access, the existing API DescribeNfsFileShare will now output the list of clients that have access. - -Release v1.6.20 (2017-02-09) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API and documentation - * This feature allows customers to associate an IAM profile to running instances that do not have any. -* `service/rekognition`: Updates service API and documentation - * DetectFaces and IndexFaces operations now return an estimate of the age of the face as an age range. - -SDK Features ---- -* `aws/endpoints`: Add option to resolve unknown endpoints (#1074) -Release v1.6.19 (2017-02-08) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service examples - * Doc Update -* `service/lexruntimeservice`: Adds new service - * Preview release - -SDK Bug Fixes ---- -* `private/protocol/json`: Fixes json to throw an error if a float number is (+/-)Inf and NaN (#1068) -* `private/model/api`: Fix documentation error listing (#1067) - -SDK Features ---- -* `private/model`: Add service response error code generation (#1061) - -Release v1.6.18 (2017-01-27) -=== - -Service Client Updates ---- -* `service/clouddirectory`: Adds new service - * Amazon Cloud Directory is a highly scalable, high performance, multi-tenant directory service in the cloud. Its web-based directories make it easy for you to organize and manage application resources such as users, groups, locations, devices, policies, and the rich relationships between them. -* `service/codedeploy`: Updates service API, documentation, and paginators - * This release of AWS CodeDeploy introduces support for blue/green deployments. In a blue/green deployment, the current set of instances in a deployment group is replaced by new instances that have the latest application revision installed on them. After traffic is rerouted behind a load balancer to the replacement instances, the original instances can be terminated automatically or kept running for other uses. -* `service/ec2`: Updates service API and documentation - * Adds instance health check functionality to replace unhealthy EC2 Spot fleet instances with fresh ones. -* `service/rds`: Updates service API and documentation - * Snapshot Engine Version Upgrade - -Release v1.6.17 (2017-01-25) -=== - -Service Client Updates ---- -* `service/elbv2`: Updates service API, documentation, and paginators - * Application Load Balancers now support native Internet Protocol version 6 (IPv6) in an Amazon Virtual Private Cloud (VPC). With this ability, clients can now connect to the Application Load Balancer in a dual-stack mode via either IPv4 or IPv6. -* `service/rds`: Updates service API and documentation - * Cross Region Read Replica Copying (CreateDBInstanceReadReplica) - -Release v1.6.16 (2017-01-24) -=== - -Service Client Updates ---- -* `service/codebuild`: Updates service documentation and paginators - * Documentation updates -* `service/codecommit`: Updates service API, documentation, and paginators - * AWS CodeCommit now includes the option to view the differences between a commit and its parent commit from within the console. You can view the differences inline (Unified view) or side by side (Split view). To view information about the differences between a commit and something other than its parent, you can use the AWS CLI and the get-differences and get-blob commands, or you can use the GetDifferences and GetBlob APIs. -* `service/ecs`: Updates service API and documentation - * Amazon ECS now supports a state for container instances that can be used to drain a container instance in preparation for maintenance or cluster scale down. - -Release v1.6.15 (2017-01-20) -=== - -Service Client Updates ---- -* `service/acm`: Updates service API, documentation, and paginators - * Update for AWS Certificate Manager: Updated response elements for DescribeCertificate API in support of managed renewal -* `service/health`: Updates service documentation - -Release v1.6.14 (2017-01-19) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API, documentation, and paginators - * Amazon EC2 Spot instances now support dedicated tenancy, providing the ability to run Spot instances single-tenant manner on physically isolated hardware within a VPC to satisfy security, privacy, or other compliance requirements. Dedicated Spot instances can be requested using RequestSpotInstances and RequestSpotFleet. - -Release v1.6.13 (2017-01-18) -=== - -Service Client Updates ---- -* `service/rds`: Updates service API, documentation, and paginators - -Release v1.6.12 (2017-01-17) -=== - -Service Client Updates ---- -* `service/dynamodb`: Updates service API, documentation, and paginators - * Tagging Support for Amazon DynamoDB Tables and Indexes -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service API, paginators, and examples - * Doc-only Update for Glacier: Added code snippets -* `service/polly`: Updates service documentation and examples - * Doc-only update for Amazon Polly -- added snippets -* `service/rekognition`: Updates service documentation and paginators - * Added code samples to Rekognition reference topics. -* `service/route53`: Updates service API and paginators - * Add ca-central-1 and eu-west-2 enum values to CloudWatchRegion enum - -Release v1.6.11 (2017-01-16) -=== - -Service Client Updates ---- -* `service/configservice`: Updates service API, documentation, and paginators -* `service/costandusagereportservice`: Adds new service - * The AWS Cost and Usage Report Service API allows you to enable and disable the Cost & Usage report, as well as modify the report name, the data granularity, and the delivery preferences. -* `service/dynamodb`: Updates service API, documentation, and examples - * Snippets for the DynamoDB API. -* `service/elasticache`: Updates service API, documentation, and examples - * Adds new code examples. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.6.10 (2017-01-04) -=== - -Service Client Updates ---- -* `service/configservice`: Updates service API and documentation - * AWSConfig is planning to add support for OversizedConfigurationItemChangeNotification message type in putConfigRule. After this release customers can use/write rules based on OversizedConfigurationItemChangeNotification mesage type. -* `service/efs`: Updates service API, documentation, and examples - * Doc-only Update for EFS: Added code snippets -* `service/iam`: Updates service documentation and examples -* `service/lambda`: Updates service documentation and examples - * Doc only updates for Lambda: Added code snippets -* `service/marketplacecommerceanalytics`: Updates service API and documentation - * Added support for data set disbursed_amount_by_instance_hours, with historical data available starting 2012-09-04. New data is published to this data set every 30 days. -* `service/rds`: Updates service documentation - * Updated documentation for CopyDBSnapshot. -* `service/rekognition`: Updates service documentation and examples - * Doc-only Update for Rekognition: Added code snippets -* `service/snowball`: Updates service examples -* `service/dynamodbstreams`: Updates service API and examples - * Doc-only Update for DynamoDB Streams: Added code snippets - -SDK Feature ---- -* `private/model/api`: Increasing the readability of code generated files. (#1024) -Release v1.6.9 (2016-12-30) -=== - -Service Client Updates ---- -* `service/codedeploy`: Updates service API and documentation - * CodeDeploy will support Iam Session Arns in addition to Iam User Arns for on premise host authentication. -* `service/ecs`: Updates service API and documentation - * Amazon EC2 Container Service (ECS) now supports the ability to customize the placement of tasks on container instances. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.6.8 (2016-12-22) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation - * Amazon API Gateway is adding support for generating SDKs in more languages. This update introduces two new operations used to dynamically discover these SDK types and what configuration each type accepts. -* `service/directoryservice`: Updates service documentation - * Added code snippets for the DS SDKs -* `service/elasticbeanstalk`: Updates service API and documentation -* `service/iam`: Updates service API and documentation - * Adds service-specific credentials to IAM service to make it easier to onboard CodeCommit customers. These are username/password credentials that work with a single service. -* `service/kms`: Updates service API, documentation, and examples - * Update docs and add SDK examples - -Release v1.6.7 (2016-12-22) -=== - -Service Client Updates ---- -* `service/ecr`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Cross Region Encrypted Snapshot Copying (CopyDBSnapshot) - -Release v1.6.6 (2016-12-20) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/firehose`: Updates service API, documentation, and examples - * Processing feature enables users to process and modify records before Amazon Firehose delivers them to destinations. -* `service/route53`: Updates service API and documentation - * Enum updates for eu-west-2 and ca-central-1 -* `service/storagegateway`: Updates service API, documentation, and examples - * File gateway is a new mode in the AWS Storage Gateway that support a file interface into S3, alongside the current block-based volume and VTL storage. File gateway combines a service and virtual software appliance, enabling you to store and retrieve objects in Amazon S3 using industry standard file protocols such as NFS. The software appliance, or gateway, is deployed into your on-premises environment as a virtual machine (VM) running on VMware ESXi. The gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. - -Release v1.6.5 (2016-12-19) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service documentation - * Minor doc update for CloudFormation. -* `service/cloudtrail`: Updates service paginators -* `service/cognitoidentity`: Updates service API and documentation - * We are adding Groups to Cognito user pools. Developers can perform CRUD operations on groups, add and remove users from groups, list users in groups, etc. We are adding fine-grained role-based access control for Cognito identity pools. Developers can configure an identity pool to get the IAM role from an authenticated user's token, or they can configure rules that will map a user to a different role -* `service/applicationdiscoveryservice`: Updates service API and documentation - * Adds new APIs to group discovered servers into Applications with get summary and neighbors. Includes additional filters for ListConfigurations and DescribeAgents API. -* `service/inspector`: Updates service API, documentation, and examples - * Doc-only Update for Inspector: Adding SDK code snippets for Inspector -* `service/sqs`: Updates service documentation - -SDK Bug Fixes ---- -* `aws/request`: Add PriorRequestNotComplete to throttle retry codes (#1011) - * Fixes: Not retrying when PriorRequestNotComplete #1009 - -SDK Feature ---- -* `private/model/api`: Adds crosslinking to service documentation (#1010) - -Release v1.6.4 (2016-12-15) -=== - -Service Client Updates ---- -* `service/cognitoidentityprovider`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/ssm`: Updates service API and documentation - * This will provide customers with access to the Patch Baseline and Patch Compliance APIs. - -SDK Bug Fixes ---- -* `service/route53`: Fix URL path cleaning for Route53 API requests (#1006) - * Fixes: SerializationError when using Route53 ChangeResourceRecordSets #1005 -* `aws/request`: Add PriorRequestNotComplete to throttle retry codes (#1002) - * Fixes: Not retrying when PriorRequestNotComplete #1001 - -Release v1.6.3 (2016-12-14) -=== - -Service Client Updates ---- -* `service/batch`: Adds new service - * AWS Batch is a batch computing service that lets customers define queues and compute environments and then submit work as batch jobs. -* `service/databasemigrationservice`: Updates service API and documentation - * Adds support for SSL enabled Oracle endpoints and task modification. -* `service/elasticbeanstalk`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/cloudwatchlogs`: Updates service API and documentation - * Add support for associating LogGroups with AWSTagris tags -* `service/marketplacecommerceanalytics`: Updates service API and documentation - * Add new enum to DataSetType: sales_compensation_billed_revenue -* `service/rds`: Updates service documentation - * Doc-only Update for RDS: New versions available in CreateDBInstance -* `service/sts`: Updates service documentation - * Adding Code Snippet Examples for SDKs for STS - -SDK Bug Fixes ---- -* `aws/request`: Fix retrying timeout requests (#981) - * Fixes: Requests Retrying is broken if the error was caused due to a client timeout #947 -* `aws/request`: Fix for Go 1.8 request incorrectly sent with body (#991) - * Fixes: service/route53: ListHostedZones hangs and then fails with go1.8 #984 -* private/protocol/rest: Use RawPath instead of Opaque (#993) - * Fixes: HTTP2 request failing with REST protocol services, e.g AWS X-Ray -* private/model/api: Generate REST-JSON JSONVersion correctly (#998) - * Fixes: REST-JSON protocol service code missing JSONVersion metadata. - -Release v1.6.2 (2016-12-08) -=== - -Service Client Updates ---- -* `service/cloudfront`: Add lambda function associations to cache behaviors -* `service/codepipeline`: This is a doc-only update request to incorporate some recent minor revisions to the doc content. -* `service/rds`: Updates service API and documentation -* `service/wafregional`: With this new feature, customers can use AWS WAF directly on Application Load Balancers in a VPC within available regions to protect their websites and web services from malicious attacks such as SQL injection, Cross Site Scripting, bad bots, etc. - -Release v1.6.1 (2016-12-07) -=== - -Service Client Updates ---- -* `service/config`: Updates service API -* `service/s3`: Updates service API -* `service/sqs`: Updates service API and documentation - -Release v1.6.0 (2016-12-06) -=== - -Service Client Updates ---- -* `service/config`: Updates service API and documentation -* `service/ec2`: Updates service API -* `service/sts`: Updates service API, documentation, and examples - -SDK Bug Fixes ---- -* private/protocol/xml/xmlutil: Fix SDK XML unmarshaler #975 - * Fixes GetBucketACL Grantee required type always nil. #916 - -SDK Feature ---- -* aws/endpoints: Add endpoint metadata to SDK #961 - * Adds Region and Endpoint metadata to the SDK. This allows you to enumerate regions and endpoint metadata based on a defined model embedded in the SDK. - -Release v1.5.13 (2016-12-01) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation -* `service/appstream`: Adds new service -* `service/codebuild`: Adds new service -* `service/directconnect`: Updates service API and documentation -* `service/ec2`: Adds new service -* `service/elasticbeanstalk`: Updates service API and documentation -* `service/health`: Adds new service -* `service/lambda`: Updates service API and documentation -* `service/opsworkscm`: Adds new service -* `service/pinpoint`: Adds new service -* `service/shield`: Adds new service -* `service/ssm`: Updates service API and documentation -* `service/states`: Adds new service -* `service/xray`: Adds new service - -Release v1.5.12 (2016-11-30) -=== - -Service Client Updates ---- -* `service/lightsail`: Adds new service -* `service/polly`: Adds new service -* `service/rekognition`: Adds new service -* `service/snowball`: Updates service API and documentation - -Release v1.5.11 (2016-11-29) -=== - -Service Client Updates ---- -`service/s3`: Updates service API and documentation - -Release v1.5.10 (2016-11-22) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service API and documentation -* `service/glacier`: Updates service API, documentation, and examples -* `service/route53`: Updates service API and documentation -* `service/s3`: Updates service API and documentation - -SDK Bug Fixes ---- -* `private/protocol/xml/xmlutil`: Fixes xml marshaler to unmarshal properly -into tagged fields -[#916](https://github.com/aws/aws-sdk-go/issues/916) - -Release v1.5.9 (2016-11-22) -=== - -Service Client Updates ---- -* `service/cloudtrail`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - -Release v1.5.8 (2016-11-18) -=== - -Service Client Updates ---- -* `service/application-autoscaling`: Updates service API and documentation -* `service/elasticmapreduce`: Updates service API and documentation -* `service/elastictranscoder`: Updates service API, documentation, and examples -* `service/gamelift`: Updates service API and documentation -* `service/lambda`: Updates service API and documentation - -Release v1.5.7 (2016-11-18) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation -* `service/meteringmarketplace`: Updates service API and documentation -* `service/monitoring`: Updates service API and documentation -* `service/sqs`: Updates service API, documentation, and examples - -Release v1.5.6 (2016-11-16) -=== - -Service Client Updates ---- -`service/route53`: Updates service API and documentation -`service/servicecatalog`: Updates service API and documentation - -Release v1.5.5 (2016-11-15) -=== - -Service Client Updates ---- -* `service/ds`: Updates service API and documentation -* `service/elasticache`: Updates service API and documentation -* `service/kinesis`: Updates service API and documentation - -Release v1.5.4 (2016-11-15) -=== - -Service Client Updates ---- -* `service/cognito-idp`: Updates service API and documentation - -Release v1.5.3 (2016-11-11) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service documentation and examples -* `service/logs`: Updates service API and documentation - -Release v1.5.2 (2016-11-03) -=== - -Service Client Updates ---- -* `service/directconnect`: Updates service API and documentation - -Release v1.5.1 (2016-11-02) -=== - -Service Client Updates ---- -* `service/email`: Updates service API and documentation - -Release v1.5.0 (2016-11-01) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service API and documentation -* `service/ecr`: Updates service paginators - -SDK Feature Updates ---- -* `private/model/api`: Add generated setters for API parameters (#918) - * Adds setters to the SDK's API parameter types, and are a convenience method that reduce the need to use `aws.String` and like utility. - -Release v1.4.22 (2016-10-25) -=== - -Service Client Updates ---- -* `service/elasticloadbalancingv2`: Updates service documentation. -* `service/autoscaling`: Updates service documentation. - -Release v1.4.21 (2016-10-24) -=== - -Service Client Updates ---- -* `service/sms`: AWS Server Migration Service (SMS) is an agentless service which makes it easier and faster for you to migrate thousands of on-premises workloads to AWS. AWS SMS allows you to automate, schedule, and track incremental replications of live server volumes, making it easier for you to coordinate large-scale server migrations. -* `service/ecs`: Updates documentation. - -SDK Feature Updates ---- -* `private/models/api`: Improve code generation of documentation. - -Release v1.4.20 (2016-10-20) -=== - -Service Client Updates ---- -* `service/budgets`: Adds new service, AWS Budgets. -* `service/waf`: Updates service documentation. - -Release v1.4.19 (2016-10-18) -=== - -Service Client Updates ---- -* `service/cloudfront`: Updates service API and documentation. - * Ability to use Amazon CloudFront to deliver your content both via IPv6 and IPv4 using HTTP/HTTPS. -* `service/configservice`: Update service API and documentation. -* `service/iot`: Updates service API and documentation. -* `service/kinesisanalytics`: Updates service API and documentation. - * Whenever Amazon Kinesis Analytics is not able to detect schema for the given streaming source on DiscoverInputSchema API, we would return the raw records that was sampled to detect the schema. -* `service/rds`: Updates service API and documentation. - * Amazon Aurora integrates with other AWS services to allow you to extend your Aurora DB cluster to utilize other capabilities in the AWS cloud. Permission to access other AWS services is granted by creating an IAM role with the necessary permissions, and then associating the role with your DB cluster. - -SDK Feature Updates ---- -* `service/dynamodb/dynamodbattribute`: Add UnmarshalListOfMaps #897 - * Adds support for unmarshaling a list of maps. This is useful for unmarshaling the DynamoDB AttributeValue list of maps returned by APIs like Query and Scan. - -Release v1.4.18 (2016-10-17) -=== - -Service Model Updates ---- -* `service/route53`: Updates service API and documentation. - -Release v1.4.17 -=== - -Service Model Updates ---- -* `service/acm`: Update service API, and documentation. - * This change allows users to import third-party SSL/TLS certificates into ACM. -* `service/elasticbeanstalk`: Update service API, documentation, and pagination. - * Elastic Beanstalk DescribeApplicationVersions API is being updated to support pagination. -* `service/gamelift`: Update service API, and documentation. - * New APIs to protect game developer resource (builds, alias, fleets, instances, game sessions and player sessions) against abuse. - -SDK Features ---- -* `service/s3`: Add support for accelerate with dualstack [#887](https://github.com/aws/aws-sdk-go/issues/887) - -Release v1.4.16 (2016-10-13) -=== - -Service Model Updates ---- -* `service/ecr`: Update Amazon EC2 Container Registry service model - * DescribeImages is a new api used to expose image metadata which today includes image size and image creation timestamp. -* `service/elasticache`: Update Amazon ElastiCache service model - * Elasticache is launching a new major engine release of Redis, 3.2 (providing stability updates and new command sets over 2.8), as well as ElasticSupport for enabling Redis Cluster in 3.2, which provides support for multiple node groups to horizontally scale data, as well as superior engine failover capabilities - -SDK Bug Fixes ---- -* `aws/session`: Skip shared config on read errors [#883](https://github.com/aws/aws-sdk-go/issues/883) -* `aws/signer/v4`: Add support for URL.EscapedPath to signer [#885](https://github.com/aws/aws-sdk-go/issues/885) - -SDK Features ---- -* `private/model/api`: Add docs for errors to API operations [#881](https://github.com/aws/aws-sdk-go/issues/881) -* `private/model/api`: Improve field and waiter doc strings [#879](https://github.com/aws/aws-sdk-go/issues/879) -* `service/dynamodb/dynamodbattribute`: Allow multiple struct tag elements [#886](https://github.com/aws/aws-sdk-go/issues/886) -* Add build tags to internal SDK tools [#880](https://github.com/aws/aws-sdk-go/issues/880) - -Release v1.4.15 (2016-10-06) -=== - -Service Model Updates ---- -* `service/cognitoidentityprovider`: Update Amazon Cognito Identity Provider service model -* `service/devicefarm`: Update AWS Device Farm documentation -* `service/opsworks`: Update AWS OpsWorks service model -* `service/s3`: Update Amazon Simple Storage Service model -* `service/waf`: Update AWS WAF service model - -SDK Bug Fixes ---- -* `aws/request`: Fix HTTP Request Body race condition [#874](https://github.com/aws/aws-sdk-go/issues/874) - -SDK Feature Updates ---- -* `aws/ec2metadata`: Add support for EC2 User Data [#872](https://github.com/aws/aws-sdk-go/issues/872) -* `aws/signer/v4`: Remove logic determining if request needs to be resigned [#876](https://github.com/aws/aws-sdk-go/issues/876) - -Release v1.4.14 (2016-09-29) -=== -* `service/ec2`: api, documentation, and paginators updates. -* `service/s3`: api and documentation updates. - -Release v1.4.13 (2016-09-27) -=== -* `service/codepipeline`: documentation updates. -* `service/cloudformation`: api and documentation updates. -* `service/kms`: documentation updates. -* `service/elasticfilesystem`: documentation updates. -* `service/snowball`: documentation updates. diff --git a/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md b/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md deleted file mode 100644 index 8a1927a3..00000000 --- a/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md +++ /dev/null @@ -1,5 +0,0 @@ -### SDK Features - -### SDK Enhancements - -### SDK Bugs diff --git a/vendor/github.com/aws/aws-sdk-go/CODE_OF_CONDUCT.md b/vendor/github.com/aws/aws-sdk-go/CODE_OF_CONDUCT.md deleted file mode 100644 index 3b644668..00000000 --- a/vendor/github.com/aws/aws-sdk-go/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. diff --git a/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md b/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md deleted file mode 100644 index 9f4a0c14..00000000 --- a/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md +++ /dev/null @@ -1,127 +0,0 @@ -Contributing to the AWS SDK for Go - -We work hard to provide a high-quality and useful SDK, and we greatly value -feedback and contributions from our community. Whether it's a bug report, -new feature, correction, or additional documentation, we welcome your issues -and pull requests. Please read through this document before submitting any -issues or pull requests to ensure we have all the necessary information to -effectively respond to your bug report or contribution. - - -## Filing Bug Reports - -You can file bug reports against the SDK on the [GitHub issues][issues] page. - -If you are filing a report for a bug or regression in the SDK, it's extremely -helpful to provide as much information as possible when opening the original -issue. This helps us reproduce and investigate the possible bug without having -to wait for this extra information to be provided. Please read the following -guidelines prior to filing a bug report. - -1. Search through existing [issues][] to ensure that your specific issue has - not yet been reported. If it is a common issue, it is likely there is - already a bug report for your problem. - -2. Ensure that you have tested the latest version of the SDK. Although you - may have an issue against an older version of the SDK, we cannot provide - bug fixes for old versions. It's also possible that the bug may have been - fixed in the latest release. - -3. Provide as much information about your environment, SDK version, and - relevant dependencies as possible. For example, let us know what version - of Go you are using, which and version of the operating system, and the - the environment your code is running in. e.g Container. - -4. Provide a minimal test case that reproduces your issue or any error - information you related to your problem. We can provide feedback much - more quickly if we know what operations you are calling in the SDK. If - you cannot provide a full test case, provide as much code as you can - to help us diagnose the problem. Any relevant information should be provided - as well, like whether this is a persistent issue, or if it only occurs - some of the time. - - -## Submitting Pull Requests - -We are always happy to receive code and documentation contributions to the SDK. -Please be aware of the following notes prior to opening a pull request: - -1. The SDK is released under the [Apache license][license]. Any code you submit - will be released under that license. For substantial contributions, we may - ask you to sign a [Contributor License Agreement (CLA)][cla]. - -2. If you would like to implement support for a significant feature that is not - yet available in the SDK, please talk to us beforehand to avoid any - duplication of effort. - -3. Wherever possible, pull requests should contain tests as appropriate. - Bugfixes should contain tests that exercise the corrected behavior (i.e., the - test should fail without the bugfix and pass with it), and new features - should be accompanied by tests exercising the feature. - -4. Pull requests that contain failing tests will not be merged until the test - failures are addressed. Pull requests that cause a significant drop in the - SDK's test coverage percentage are unlikely to be merged until tests have - been added. - -5. The JSON files under the SDK's `models` folder are sourced from outside the SDK. - Such as `models/apis/ec2/2016-11-15/api.json`. We will not accept pull requests - directly on these models. If you discover an issue with the models please - create a [GitHub issue][issues] describing the issue. - -### Testing - -To run the tests locally, running the `make unit` command will `go get` the -SDK's testing dependencies, and run vet, link and unit tests for the SDK. - -``` -make unit -``` - -Standard go testing functionality is supported as well. To test SDK code that -is tagged with `codegen` you'll need to set the build tag in the go test -command. The `make unit` command will do this automatically. - -``` -go test -tags codegen ./private/... -``` - -See the `Makefile` for additional testing tags that can be used in testing. - -To test on multiple platform the SDK includes several DockerFiles under the -`awstesting/sandbox` folder, and associated make recipes to execute -unit testing within environments configured for specific Go versions. - -``` -make sandbox-test-go18 -``` - -To run all sandbox environments use the following make recipe - -``` -# Optionally update the Go tip that will be used during the batch testing -make update-aws-golang-tip - -# Run all SDK tests for supported Go versions in sandboxes -make sandbox-test -``` - -In addition the sandbox environment include make recipes for interactive modes -so you can run command within the Docker container and context of the SDK. - -``` -make sandbox-go18 -``` - -### Changelog - -You can see all release changes in the `CHANGELOG.md` file at the root of the -repository. The release notes added to this file will contain service client -updates, and major SDK changes. - -[issues]: https://github.com/aws/aws-sdk-go/issues -[pr]: https://github.com/aws/aws-sdk-go/pulls -[license]: http://aws.amazon.com/apache2.0/ -[cla]: http://en.wikipedia.org/wiki/Contributor_License_Agreement -[releasenotes]: https://github.com/aws/aws-sdk-go/releases - diff --git a/vendor/github.com/aws/aws-sdk-go/Gopkg.lock b/vendor/github.com/aws/aws-sdk-go/Gopkg.lock deleted file mode 100644 index 854c94fd..00000000 --- a/vendor/github.com/aws/aws-sdk-go/Gopkg.lock +++ /dev/null @@ -1,20 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - name = "github.com/go-ini/ini" - packages = ["."] - revision = "300e940a926eb277d3901b20bdfcc54928ad3642" - version = "v1.25.4" - -[[projects]] - name = "github.com/jmespath/go-jmespath" - packages = ["."] - revision = "0b12d6b5" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "51a86a867df617990082dec6b868e4efe2fdb2ed0e02a3daa93cd30f962b5085" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/aws/aws-sdk-go/Gopkg.toml b/vendor/github.com/aws/aws-sdk-go/Gopkg.toml deleted file mode 100644 index 664fc595..00000000 --- a/vendor/github.com/aws/aws-sdk-go/Gopkg.toml +++ /dev/null @@ -1,48 +0,0 @@ - -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" - -ignored = [ - # Testing/Example/Codegen dependencies - "github.com/stretchr/testify", - "github.com/stretchr/testify/assert", - "github.com/stretchr/testify/require", - "github.com/go-sql-driver/mysql", - "github.com/gucumber/gucumber", - "github.com/pkg/errors", - "golang.org/x/net", - "golang.org/x/net/html", - "golang.org/x/net/http2", - "golang.org/x/text", - "golang.org/x/text/html", - "golang.org/x/tools", - "golang.org/x/tools/go/loader", -] - - -[[constraint]] - name = "github.com/go-ini/ini" - version = "1.25.4" - -[[constraint]] - name = "github.com/jmespath/go-jmespath" - revision = "0b12d6b5" - #version = "0.2.2" diff --git a/vendor/github.com/aws/aws-sdk-go/Makefile b/vendor/github.com/aws/aws-sdk-go/Makefile deleted file mode 100644 index 89f4b7a8..00000000 --- a/vendor/github.com/aws/aws-sdk-go/Makefile +++ /dev/null @@ -1,211 +0,0 @@ -LINTIGNOREDOT='awstesting/integration.+should not use dot imports' -LINTIGNOREDOC='service/[^/]+/(api|service|waiters)\.go:.+(comment on exported|should have comment or be unexported)' -LINTIGNORECONST='service/[^/]+/(api|service|waiters)\.go:.+(type|struct field|const|func) ([^ ]+) should be ([^ ]+)' -LINTIGNORESTUTTER='service/[^/]+/(api|service)\.go:.+(and that stutters)' -LINTIGNOREINFLECT='service/[^/]+/(api|errors|service)\.go:.+(method|const) .+ should be ' -LINTIGNOREINFLECTS3UPLOAD='service/s3/s3manager/upload\.go:.+struct field SSEKMSKeyId should be ' -LINTIGNOREDEPS='vendor/.+\.go' -LINTIGNOREPKGCOMMENT='service/[^/]+/doc_custom.go:.+package comment should be of the form' -UNIT_TEST_TAGS="example codegen awsinclude" - -SDK_WITH_VENDOR_PKGS=$(shell go list -tags ${UNIT_TEST_TAGS} ./... | grep -v "/vendor/src") -SDK_ONLY_PKGS=$(shell go list ./... | grep -v "/vendor/") -SDK_UNIT_TEST_ONLY_PKGS=$(shell go list -tags ${UNIT_TEST_TAGS} ./... | grep -v "/vendor/") -SDK_GO_1_4=$(shell go version | grep "go1.4") -SDK_GO_1_5=$(shell go version | grep "go1.5") -SDK_GO_1_6=$(shell go version | grep "go1.6") -SDK_GO_VERSION=$(shell go version | awk '''{print $$3}''' | tr -d '''\n''') - -all: get-deps generate unit - -help: - @echo "Please use \`make ' where is one of" - @echo " api_info to print a list of services and versions" - @echo " docs to build SDK documentation" - @echo " build to go build the SDK" - @echo " unit to run unit tests" - @echo " integration to run integration tests" - @echo " performance to run performance tests" - @echo " verify to verify tests" - @echo " lint to lint the SDK" - @echo " vet to vet the SDK" - @echo " generate to go generate and make services" - @echo " gen-test to generate protocol tests" - @echo " gen-services to generate services" - @echo " get-deps to go get the SDK dependencies" - @echo " get-deps-tests to get the SDK's test dependencies" - @echo " get-deps-verify to get the SDK's verification dependencies" - -generate: cleanup-models gen-test gen-endpoints gen-services - -gen-test: gen-protocol-test - -gen-services: - go generate ./service - -gen-protocol-test: - go generate ./private/protocol/... - -gen-endpoints: - go generate ./models/endpoints/ - -cleanup-models: - @echo "Cleaning up stale model versions" - @./cleanup_models.sh - -build: - @echo "go build SDK and vendor packages" - @go build ${SDK_ONLY_PKGS} - -unit: get-deps-tests build verify - @echo "go test SDK and vendor packages" - @go test -tags ${UNIT_TEST_TAGS} $(SDK_UNIT_TEST_ONLY_PKGS) - -unit-with-race-cover: get-deps-tests build verify - @echo "go test SDK and vendor packages" - @go test -tags ${UNIT_TEST_TAGS} -race -cpu=1,2,4 $(SDK_UNIT_TEST_ONLY_PKGS) - -ci-test: ci-test-generate unit-with-race-cover ci-test-generate-validate - -ci-test-generate: get-deps - @echo "CI test generated code" - @if [ \( -z "${SDK_GO_1_6}" \) -a \( -z "${SDK_GO_1_5}" \) ]; then make generate; else echo "skipping generate"; fi - -ci-test-generate-validate: - @echo "CI test validate no generated code changes" - @gitstatus=`if [ \( -z "${SDK_GO_1_6}" \) -a \( -z "${SDK_GO_1_5}" \) ]; then git status --porcelain; else echo "skipping validation"; fi`; \ - echo "$$gitstatus"; \ - if [ "$$gitstatus" != "" ] && [ "$$gitstatus" != "skipping validation" ]; then git diff; exit 1; fi - -integration: get-deps-tests integ-custom smoke-tests performance - -integ-custom: - go test -tags "integration" ./awstesting/integration/customizations/... - -cleanup-integ: - go run -tags "integration" ./awstesting/cmd/bucket_cleanup/main.go "aws-sdk-go-integration" - -smoke-tests: get-deps-tests - gucumber -go-tags "integration" ./awstesting/integration/smoke - -performance: get-deps-tests - AWS_TESTING_LOG_RESULTS=${log-detailed} AWS_TESTING_REGION=$(region) AWS_TESTING_DB_TABLE=$(table) gucumber -go-tags "integration" ./awstesting/performance - -sandbox-tests: sandbox-test-go15 sandbox-test-go15-novendorexp sandbox-test-go16 sandbox-test-go17 sandbox-test-go18 sandbox-test-go19 sandbox-test-gotip - -sandbox-build-go15: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.5 -t "aws-sdk-go-1.5" . -sandbox-go15: sandbox-build-go15 - docker run -i -t aws-sdk-go-1.5 bash -sandbox-test-go15: sandbox-build-go15 - docker run -t aws-sdk-go-1.5 - -sandbox-build-go15-novendorexp: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.5-novendorexp -t "aws-sdk-go-1.5-novendorexp" . -sandbox-go15-novendorexp: sandbox-build-go15-novendorexp - docker run -i -t aws-sdk-go-1.5-novendorexp bash -sandbox-test-go15-novendorexp: sandbox-build-go15-novendorexp - docker run -t aws-sdk-go-1.5-novendorexp - -sandbox-build-go16: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.6 -t "aws-sdk-go-1.6" . -sandbox-go16: sandbox-build-go16 - docker run -i -t aws-sdk-go-1.6 bash -sandbox-test-go16: sandbox-build-go16 - docker run -t aws-sdk-go-1.6 - -sandbox-build-go17: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.7 -t "aws-sdk-go-1.7" . -sandbox-go17: sandbox-build-go17 - docker run -i -t aws-sdk-go-1.7 bash -sandbox-test-go17: sandbox-build-go17 - docker run -t aws-sdk-go-1.7 - -sandbox-build-go18: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.8 -t "aws-sdk-go-1.8" . -sandbox-go18: sandbox-build-go18 - docker run -i -t aws-sdk-go-1.8 bash -sandbox-test-go18: sandbox-build-go18 - docker run -t aws-sdk-go-1.8 - -sandbox-build-go19: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.8 -t "aws-sdk-go-1.9" . -sandbox-go19: sandbox-build-go19 - docker run -i -t aws-sdk-go-1.9 bash -sandbox-test-go19: sandbox-build-go19 - docker run -t aws-sdk-go-1.9 - -sandbox-build-go110: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.8 -t "aws-sdk-go-1.10" . -sandbox-go110: sandbox-build-go110 - docker run -i -t aws-sdk-go-1.10 bash -sandbox-test-go110: sandbox-build-go110 - docker run -t aws-sdk-go-1.10 - -sandbox-build-gotip: - @echo "Run make update-aws-golang-tip, if this test fails because missing aws-golang:tip container" - docker build -f ./awstesting/sandbox/Dockerfile.test.gotip -t "aws-sdk-go-tip" . -sandbox-gotip: sandbox-build-gotip - docker run -i -t aws-sdk-go-tip bash -sandbox-test-gotip: sandbox-build-gotip - docker run -t aws-sdk-go-tip - -update-aws-golang-tip: - docker build --no-cache=true -f ./awstesting/sandbox/Dockerfile.golang-tip -t "aws-golang:tip" . - -verify: get-deps-verify lint vet - -lint: - @echo "go lint SDK and vendor packages" - @lint=`if [ \( -z "${SDK_GO_1_4}" \) -a \( -z "${SDK_GO_1_5}" \) ]; then golint ./...; else echo "skipping golint"; fi`; \ - lint=`echo "$$lint" | grep -E -v -e ${LINTIGNOREDOT} -e ${LINTIGNOREDOC} -e ${LINTIGNORECONST} -e ${LINTIGNORESTUTTER} -e ${LINTIGNOREINFLECT} -e ${LINTIGNOREDEPS} -e ${LINTIGNOREINFLECTS3UPLOAD} -e ${LINTIGNOREPKGCOMMENT}`; \ - echo "$$lint"; \ - if [ "$$lint" != "" ] && [ "$$lint" != "skipping golint" ]; then exit 1; fi - -SDK_BASE_FOLDERS=$(shell ls -d */ | grep -v vendor | grep -v awsmigrate) -ifneq (,$(findstring go1.4, ${SDK_GO_VERSION})) - GO_VET_CMD=echo skipping go vet, ${SDK_GO_VERSION} -else ifneq (,$(findstring go1.6, ${SDK_GO_VERSION})) - GO_VET_CMD=go tool vet --all -shadow -example=false -else - GO_VET_CMD=go tool vet --all -shadow -endif - -vet: - ${GO_VET_CMD} ${SDK_BASE_FOLDERS} - -get-deps: get-deps-tests get-deps-verify - @echo "go get SDK dependencies" - @go get -v $(SDK_ONLY_PKGS) - -get-deps-tests: - @echo "go get SDK testing dependencies" - go get github.com/gucumber/gucumber/cmd/gucumber - go get github.com/stretchr/testify - go get github.com/smartystreets/goconvey - go get golang.org/x/net/html - go get golang.org/x/net/http2 - -get-deps-verify: - @echo "go get SDK verification utilities" - @if [ \( -z "${SDK_GO_1_4}" \) -a \( -z "${SDK_GO_1_5}" \) ]; then go get github.com/golang/lint/golint; else echo "skipped getting golint"; fi - -bench: - @echo "go bench SDK packages" - @go test -run NONE -bench . -benchmem -tags 'bench' $(SDK_ONLY_PKGS) - -bench-protocol: - @echo "go bench SDK protocol marshallers" - @go test -run NONE -bench . -benchmem -tags 'bench' ./private/protocol/... - -docs: - @echo "generate SDK docs" - @# This env variable, DOCS, is for internal use - @if [ -z ${AWS_DOC_GEN_TOOL} ]; then\ - rm -rf doc && bundle install && bundle exec yard;\ - else\ - $(AWS_DOC_GEN_TOOL) `pwd`;\ - fi - -api_info: - @go run private/model/cli/api-info/api-info.go diff --git a/vendor/github.com/aws/aws-sdk-go/README.md b/vendor/github.com/aws/aws-sdk-go/README.md deleted file mode 100644 index 3200765e..00000000 --- a/vendor/github.com/aws/aws-sdk-go/README.md +++ /dev/null @@ -1,451 +0,0 @@ -[![API Reference](http://img.shields.io/badge/api-reference-blue.svg)](http://docs.aws.amazon.com/sdk-for-go/api) [![Join the chat at https://gitter.im/aws/aws-sdk-go](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/aws/aws-sdk-go?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://img.shields.io/travis/aws/aws-sdk-go.svg)](https://travis-ci.org/aws/aws-sdk-go) [![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/aws/aws-sdk-go/blob/master/LICENSE.txt) - -# AWS SDK for Go - -aws-sdk-go is the official AWS SDK for the Go programming language. - -Checkout our [release notes](https://github.com/aws/aws-sdk-go/releases) for information about the latest bug fixes, updates, and features added to the SDK. - -We [announced](https://aws.amazon.com/blogs/developer/aws-sdk-for-go-2-0-developer-preview/) the Developer Preview for the [v2 AWS SDK for Go](https://github.com/aws/aws-sdk-go-v2). The v2 SDK is available at https://github.com/aws/aws-sdk-go-v2, and `go get github.com/aws/aws-sdk-go-v2` via `go get`. Check out the v2 SDK's [changes and updates](https://github.com/aws/aws-sdk-go-v2/blob/master/CHANGELOG.md), and let us know what you think. We want your feedback. - -## Installing - -If you are using Go 1.5 with the `GO15VENDOREXPERIMENT=1` vendoring flag, or 1.6 and higher you can use the following command to retrieve the SDK. The SDK's non-testing dependencies will be included and are vendored in the `vendor` folder. - - go get -u github.com/aws/aws-sdk-go - -Otherwise if your Go environment does not have vendoring support enabled, or you do not want to include the vendored SDK's dependencies you can use the following command to retrieve the SDK and its non-testing dependencies using `go get`. - - go get -u github.com/aws/aws-sdk-go/aws/... - go get -u github.com/aws/aws-sdk-go/service/... - -If you're looking to retrieve just the SDK without any dependencies use the following command. - - go get -d github.com/aws/aws-sdk-go/ - -These two processes will still include the `vendor` folder and it should be deleted if its not going to be used by your environment. - - rm -rf $GOPATH/src/github.com/aws/aws-sdk-go/vendor - -## Getting Help - -Please use these community resources for getting help. We use the GitHub issues for tracking bugs and feature requests. - -* Ask a question on [StackOverflow](http://stackoverflow.com/) and tag it with the [`aws-sdk-go`](http://stackoverflow.com/questions/tagged/aws-sdk-go) tag. -* Come join the AWS SDK for Go community chat on [gitter](https://gitter.im/aws/aws-sdk-go). -* Open a support ticket with [AWS Support](http://docs.aws.amazon.com/awssupport/latest/user/getting-started.html). -* If you think you may have found a bug, please open an [issue](https://github.com/aws/aws-sdk-go/issues/new). - -## Opening Issues - -If you encounter a bug with the AWS SDK for Go we would like to hear about it. Search the [existing issues](https://github.com/aws/aws-sdk-go/issues) and see if others are also experiencing the issue before opening a new issue. Please include the version of AWS SDK for Go, Go language, and OS you’re using. Please also include repro case when appropriate. - -The GitHub issues are intended for bug reports and feature requests. For help and questions with using AWS SDK for GO please make use of the resources listed in the [Getting Help](https://github.com/aws/aws-sdk-go#getting-help) section. Keeping the list of open issues lean will help us respond in a timely manner. - -## Reference Documentation - -[`Getting Started Guide`](https://aws.amazon.com/sdk-for-go/) - This document is a general introduction how to configure and make requests with the SDK. If this is your first time using the SDK, this documentation and the API documentation will help you get started. This document focuses on the syntax and behavior of the SDK. The [Service Developer Guide](https://aws.amazon.com/documentation/) will help you get started using specific AWS services. - -[`SDK API Reference Documentation`](https://docs.aws.amazon.com/sdk-for-go/api/) - Use this document to look up all API operation input and output parameters for AWS services supported by the SDK. The API reference also includes documentation of the SDK, and examples how to using the SDK, service client API operations, and API operation require parameters. - -[`Service Developer Guide`](https://aws.amazon.com/documentation/) - Use this documentation to learn how to interface with an AWS service. These are great guides both, if you're getting started with a service, or looking for more information on a service. You should not need this document for coding, though in some cases, services may supply helpful samples that you might want to look out for. - -[`SDK Examples`](https://github.com/aws/aws-sdk-go/tree/master/example) - Included in the SDK's repo are a several hand crafted examples using the SDK features and AWS services. - -## Overview of SDK's Packages - -The SDK is composed of two main components, SDK core, and service clients. -The SDK core packages are all available under the aws package at the root of -the SDK. Each client for a supported AWS service is available within its own -package under the service folder at the root of the SDK. - - * aws - SDK core, provides common shared types such as Config, Logger, - and utilities to make working with API parameters easier. - - * awserr - Provides the error interface that the SDK will use for all - errors that occur in the SDK's processing. This includes service API - response errors as well. The Error type is made up of a code and message. - Cast the SDK's returned error type to awserr.Error and call the Code - method to compare returned error to specific error codes. See the package's - documentation for additional values that can be extracted such as RequestID. - - * credentials - Provides the types and built in credentials providers - the SDK will use to retrieve AWS credentials to make API requests with. - Nested under this folder are also additional credentials providers such as - stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. - - * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. - Use this to lookup AWS service endpoint information such as which services - are in a region, and what regions a service is in. Constants are also provided - for all region identifiers, e.g UsWest2RegionID for "us-west-2". - - * session - Provides initial default configuration, and load - configuration from external sources such as environment and shared - credentials file. - - * request - Provides the API request sending, and retry logic for the SDK. - This package also includes utilities for defining your own request - retryer, and configuring how the SDK processes the request. - - * service - Clients for AWS services. All services supported by the SDK are - available under this folder. - -## How to Use the SDK's AWS Service Clients - -The SDK includes the Go types and utilities you can use to make requests to -AWS service APIs. Within the service folder at the root of the SDK you'll find -a package for each AWS service the SDK supports. All service clients follows -a common pattern of creation and usage. - -When creating a client for an AWS service you'll first need to have a Session -value constructed. The Session provides shared configuration that can be shared -between your service clients. When service clients are created you can pass -in additional configuration via the aws.Config type to override configuration -provided by in the Session to create service client instances with custom -configuration. - -Once the service's client is created you can use it to make API requests the -AWS service. These clients are safe to use concurrently. - -## Configuring the SDK - -In the AWS SDK for Go, you can configure settings for service clients, such -as the log level and maximum number of retries. Most settings are optional; -however, for each service client, you must specify a region and your credentials. -The SDK uses these values to send requests to the correct AWS region and sign -requests with the correct credentials. You can specify these values as part -of a session or as environment variables. - -See the SDK's [configuration guide][config_guide] for more information. - -See the [session][session_pkg] package documentation for more information on how to use Session -with the SDK. - -See the [Config][config_typ] type in the [aws][aws_pkg] package for more information on configuration -options. - -[config_guide]: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html -[session_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ -[config_typ]: https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -[aws_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/ - -### Configuring Credentials - -When using the SDK you'll generally need your AWS credentials to authenticate -with AWS services. The SDK supports multiple methods of supporting these -credentials. By default the SDK will source credentials automatically from -its default credential chain. See the session package for more information -on this chain, and how to configure it. The common items in the credential -chain are the following: - - * Environment Credentials - Set of environment variables that are useful - when sub processes are created for specific roles. - - * Shared Credentials file (~/.aws/credentials) - This file stores your - credentials based on a profile name and is useful for local development. - - * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials - to application running on an EC2 instance. This removes the need to manage - credential files in production. - -Credentials can be configured in code as well by setting the Config's Credentials -value to a custom provider or using one of the providers included with the -SDK to bypass the default credential chain and use a custom one. This is -helpful when you want to instruct the SDK to only use a specific set of -credentials or providers. - -This example creates a credential provider for assuming an IAM role, "myRoleARN" -and configures the S3 service client to use that role for API requests. - -```go - // Initial credentials loaded from SDK's default credential chain. Such as - // the environment, shared credentials (~/.aws/credentials), or EC2 Instance - // Role. These credentials will be used to to make the STS Assume Role API. - sess := session.Must(session.NewSession()) - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. - creds := stscreds.NewCredentials(sess, "myRoleArn") - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) -``` - -See the [credentials][credentials_pkg] package documentation for more information on credential -providers included with the SDK, and how to customize the SDK's usage of -credentials. - -The SDK has support for the shared configuration file (~/.aws/config). This -support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", -or enabling the feature in code when creating a Session via the -Option's SharedConfigState parameter. - -```go - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) -``` - -[credentials_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials - -### Configuring AWS Region - -In addition to the credentials you'll need to specify the region the SDK -will use to make AWS API requests to. In the SDK you can specify the region -either with an environment variable, or directly in code when a Session or -service client is created. The last value specified in code wins if the region -is specified multiple ways. - -To set the region via the environment variable set the "AWS_REGION" to the -region you want to the SDK to use. Using this method to set the region will -allow you to run your application in multiple regions without needing additional -code in the application to select the region. - - AWS_REGION=us-west-2 - -The endpoints package includes constants for all regions the SDK knows. The -values are all suffixed with RegionID. These values are helpful, because they -reduce the need to type the region string manually. - -To set the region on a Session use the aws package's Config struct parameter -Region to the AWS region you want the service clients created from the session to -use. This is helpful when you want to create multiple service clients, and -all of the clients make API requests to the same region. - -```go - sess := session.Must(session.NewSession(&aws.Config{ - Region: aws.String(endpoints.UsWest2RegionID), - })) -``` - -See the [endpoints][endpoints_pkg] package for the AWS Regions and Endpoints metadata. - -In addition to setting the region when creating a Session you can also set -the region on a per service client bases. This overrides the region of a -Session. This is helpful when you want to create service clients in specific -regions different from the Session's region. - -```go - svc := s3.New(sess, &aws.Config{ - Region: aws.String(endpoints.UsWest2RegionID), - }) -``` - -See the [Config][config_typ] type in the [aws][aws_pkg] package for more information and additional -options such as setting the Endpoint, and other service client configuration options. - -[endpoints_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ - -## Making API Requests - -Once the client is created you can make an API request to the service. -Each API method takes a input parameter, and returns the service response -and an error. The SDK provides methods for making the API call in multiple ways. - -In this list we'll use the S3 ListObjects API as an example for the different -ways of making API requests. - - * ListObjects - Base API operation that will make the API request to the service. - - * ListObjectsRequest - API methods suffixed with Request will construct the - API request, but not send it. This is also helpful when you want to get a - presigned URL for a request, and share the presigned URL instead of your - application making the request directly. - - * ListObjectsPages - Same as the base API operation, but uses a callback to - automatically handle pagination of the API's response. - - * ListObjectsWithContext - Same as base API operation, but adds support for - the Context pattern. This is helpful for controlling the canceling of in - flight requests. See the Go standard library context package for more - information. This method also takes request package's Option functional - options as the variadic argument for modifying how the request will be - made, or extracting information from the raw HTTP response. - - * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for - the Context pattern. Similar to ListObjectsWithContext this method also - takes the request package's Option function option types as the variadic - argument. - -In addition to the API operations the SDK also includes several higher level -methods that abstract checking for and waiting for an AWS resource to be in -a desired state. In this list we'll use WaitUntilBucketExists to demonstrate -the different forms of waiters. - - * WaitUntilBucketExists. - Method to make API request to query an AWS service for - a resource's state. Will return successfully when that state is accomplished. - - * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds - support for the Context pattern. In addition these methods take request - package's WaiterOptions to configure the waiter, and how underlying request - will be made by the SDK. - -The API method will document which error codes the service might return for -the operation. These errors will also be available as const strings prefixed -with "ErrCode" in the service client's package. If there are no errors listed -in the API's SDK documentation you'll need to consult the AWS service's API -documentation for the errors that could be returned. - -```go - ctx := context.Background() - - result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ - Bucket: aws.String("my-bucket"), - Key: aws.String("my-key"), - }) - if err != nil { - // Cast err to awserr.Error to handle specific error codes. - aerr, ok := err.(awserr.Error) - if ok && aerr.Code() == s3.ErrCodeNoSuchKey { - // Specific error code handling - } - return err - } - - // Make sure to close the body when done with it for S3 GetObject APIs or - // will leak connections. - defer result.Body.Close() - - fmt.Println("Object Size:", aws.Int64Value(result.ContentLength)) -``` - -### API Request Pagination and Resource Waiters - -Pagination helper methods are suffixed with "Pages", and provide the -functionality needed to round trip API page requests. Pagination methods -take a callback function that will be called for each page of the API's response. - -```go - objects := []string{} - err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ - Bucket: aws.String(myBucket), - }, func(p *s3.ListObjectsOutput, lastPage bool) bool { - for _, o := range p.Contents { - objects = append(objects, aws.StringValue(o.Key)) - } - return true // continue paging - }) - if err != nil { - panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) - } - - fmt.Println("Objects in bucket:", objects) -``` - -Waiter helper methods provide the functionality to wait for an AWS resource -state. These methods abstract the logic needed to check the state of an -AWS resource, and wait until that resource is in a desired state. The waiter -will block until the resource is in the state that is desired, an error occurs, -or the waiter times out. If a resource times out the error code returned will -be request.WaiterResourceNotReadyErrorCode. - -```go - err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ - Bucket: aws.String(myBucket), - }) - if err != nil { - aerr, ok := err.(awserr.Error) - if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { - fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") - } - panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) - } - fmt.Println("Bucket", myBucket, "exists") -``` - -## Complete SDK Example - -This example shows a complete working Go file which will upload a file to S3 -and use the Context pattern to implement timeout logic that will cancel the -request if it takes too long. This example highlights how to use sessions, -create a service client, make a request, handle the error, and process the -response. - -```go - package main - - import ( - "context" - "flag" - "fmt" - "os" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - ) - - // Uploads a file to S3 given a bucket and object key. Also takes a duration - // value to terminate the update if it doesn't complete within that time. - // - // The AWS Region needs to be provided in the AWS shared config or on the - // environment variable as `AWS_REGION`. Credentials also must be provided - // Will default to shared config file, but can load from environment if provided. - // - // Usage: - // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail - // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt - func main() { - var bucket, key string - var timeout time.Duration - - flag.StringVar(&bucket, "b", "", "Bucket name.") - flag.StringVar(&key, "k", "", "Object key name.") - flag.DurationVar(&timeout, "d", 0, "Upload timeout.") - flag.Parse() - - // All clients require a Session. The Session provides the client with - // shared configuration such as region, endpoint, and credentials. A - // Session should be shared where possible to take advantage of - // configuration and credential caching. See the session package for - // more information. - sess := session.Must(session.NewSession()) - - // Create a new instance of the service's client with a Session. - // Optional aws.Config values can also be provided as variadic arguments - // to the New function. This option allows you to provide service - // specific configuration. - svc := s3.New(sess) - - // Create a context with a timeout that will abort the upload if it takes - // more than the passed in timeout. - ctx := context.Background() - var cancelFn func() - if timeout > 0 { - ctx, cancelFn = context.WithTimeout(ctx, timeout) - } - // Ensure the context is canceled to prevent leaking. - // See context package for more information, https://golang.org/pkg/context/ - defer cancelFn() - - // Uploads the object to S3. The Context will interrupt the request if the - // timeout expires. - _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ - Bucket: aws.String(bucket), - Key: aws.String(key), - Body: os.Stdin, - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { - // If the SDK can determine the request or retry delay was canceled - // by a context the CanceledErrorCode error code will be returned. - fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) - } else { - fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) - } - os.Exit(1) - } - - fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) - } -``` - -## License - -This SDK is distributed under the -[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0), -see LICENSE.txt and NOTICE.txt for more information. diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go deleted file mode 100644 index 007b37be..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy_test.go +++ /dev/null @@ -1,353 +0,0 @@ -package awsutil_test - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "reflect" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -func ExampleCopy() { - type Foo struct { - A int - B []*string - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - f1 := &Foo{A: 1, B: []*string{&str1, &str2}} - - // Do the copy - var f2 Foo - awsutil.Copy(&f2, f1) - - // Print the result - fmt.Println(awsutil.Prettify(f2)) - - // Output: - // { - // A: 1, - // B: ["hello","bye bye"] - // } -} - -func TestCopy1(t *testing.T) { - type Bar struct { - a *int - B *int - c int - D int - } - type Foo struct { - A int - B []*string - C map[string]*int - D *time.Time - E *Bar - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - int1 := 1 - int2 := 2 - intPtr1 := 1 - intPtr2 := 2 - now := time.Now() - f1 := &Foo{ - A: 1, - B: []*string{&str1, &str2}, - C: map[string]*int{ - "A": &int1, - "B": &int2, - }, - D: &now, - E: &Bar{ - &intPtr1, - &intPtr2, - 2, - 3, - }, - } - - // Do the copy - var f2 Foo - awsutil.Copy(&f2, f1) - - // Values are equal - if v1, v2 := f2.A, f1.A; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.B, f1.B; !reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.C, f1.C; !reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.D, f1.D; !v1.Equal(*v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.E.B, f1.E.B; !reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.E.D, f1.E.D; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - - // But pointers are not! - str3 := "nothello" - int3 := 57 - f2.A = 100 - *f2.B[0] = str3 - *f2.C["B"] = int3 - *f2.D = time.Now() - f2.E.a = &int3 - *f2.E.B = int3 - f2.E.c = 5 - f2.E.D = 5 - if v1, v2 := f2.A, f1.A; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.B, f1.B; reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.C, f1.C; reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.D, f1.D; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.E.a, f1.E.a; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.E.B, f1.E.B; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.E.c, f1.E.c; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.E.D, f1.E.D; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } -} - -func TestCopyNestedWithUnexported(t *testing.T) { - type Bar struct { - a int - B int - } - type Foo struct { - A string - B Bar - } - - f1 := &Foo{A: "string", B: Bar{a: 1, B: 2}} - - var f2 Foo - awsutil.Copy(&f2, f1) - - // Values match - if v1, v2 := f2.A, f1.A; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.B, f1.B; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.B.a, f1.B.a; v1 == v2 { - t.Errorf("expected values to be not equivalent, but received %v", v1) - } - if v1, v2 := f2.B.B, f2.B.B; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } -} - -func TestCopyIgnoreNilMembers(t *testing.T) { - type Foo struct { - A *string - B []string - C map[string]string - } - - f := &Foo{} - if v1 := f.A; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f.B; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f.C; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - - var f2 Foo - awsutil.Copy(&f2, f) - if v1 := f2.A; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f2.B; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f2.C; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - - fcopy := awsutil.CopyOf(f) - f3 := fcopy.(*Foo) - if v1 := f3.A; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f3.B; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1 := f3.C; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } -} - -func TestCopyPrimitive(t *testing.T) { - str := "hello" - var s string - awsutil.Copy(&s, &str) - if v1, v2 := "hello", s; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } -} - -func TestCopyNil(t *testing.T) { - var s string - awsutil.Copy(&s, nil) - if v1, v2 := "", s; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } -} - -func TestCopyReader(t *testing.T) { - var buf io.Reader = bytes.NewReader([]byte("hello world")) - var r io.Reader - awsutil.Copy(&r, buf) - b, err := ioutil.ReadAll(r) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if v1, v2 := []byte("hello world"), b; !bytes.Equal(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - - // empty bytes because this is not a deep copy - b, err = ioutil.ReadAll(buf) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if v1, v2 := []byte(""), b; !bytes.Equal(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } -} - -func TestCopyDifferentStructs(t *testing.T) { - type SrcFoo struct { - A int - B []*string - C map[string]*int - SrcUnique string - SameNameDiffType int - unexportedPtr *int - ExportedPtr *int - } - type DstFoo struct { - A int - B []*string - C map[string]*int - DstUnique int - SameNameDiffType string - unexportedPtr *int - ExportedPtr *int - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - int1 := 1 - int2 := 2 - f1 := &SrcFoo{ - A: 1, - B: []*string{&str1, &str2}, - C: map[string]*int{ - "A": &int1, - "B": &int2, - }, - SrcUnique: "unique", - SameNameDiffType: 1, - unexportedPtr: &int1, - ExportedPtr: &int2, - } - - // Do the copy - var f2 DstFoo - awsutil.Copy(&f2, f1) - - // Values are equal - if v1, v2 := f2.A, f1.A; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.B, f1.B; !reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := f2.C, f1.C; !reflect.DeepEqual(v1, v2) { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := "unique", f1.SrcUnique; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := 1, f1.SameNameDiffType; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := 0, f2.DstUnique; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := "", f2.SameNameDiffType; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := int1, *f1.unexportedPtr; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1 := f2.unexportedPtr; v1 != nil { - t.Errorf("expected nil, but received %v", v1) - } - if v1, v2 := int2, *f1.ExportedPtr; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } - if v1, v2 := int2, *f2.ExportedPtr; v1 != v2 { - t.Errorf("expected values to be equivalent but received %v and %v", v1, v2) - } -} - -func ExampleCopyOf() { - type Foo struct { - A int - B []*string - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - f1 := &Foo{A: 1, B: []*string{&str1, &str2}} - - // Do the copy - v := awsutil.CopyOf(f1) - var f2 *Foo = v.(*Foo) - - // Print the result - fmt.Println(awsutil.Prettify(f2)) - - // Output: - // { - // A: 1, - // B: ["hello","bye bye"] - // } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal_test.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal_test.go deleted file mode 100644 index 18d3c5b8..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package awsutil_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -func TestDeepEqual(t *testing.T) { - cases := []struct { - a, b interface{} - equal bool - }{ - {"a", "a", true}, - {"a", "b", false}, - {"a", aws.String(""), false}, - {"a", nil, false}, - {"a", aws.String("a"), true}, - {(*bool)(nil), (*bool)(nil), true}, - {(*bool)(nil), (*string)(nil), false}, - {nil, nil, true}, - } - - for i, c := range cases { - if awsutil.DeepEqual(c.a, c.b) != c.equal { - t.Errorf("%d, a:%v b:%v, %t", i, c.a, c.b, c.equal) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go deleted file mode 100644 index 58a05d6c..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go +++ /dev/null @@ -1,182 +0,0 @@ -package awsutil_test - -import ( - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -type Struct struct { - A []Struct - z []Struct - B *Struct - D *Struct - C string - E map[string]string -} - -var data = Struct{ - A: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}}, - z: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}}, - B: &Struct{B: &Struct{C: "terminal"}, D: &Struct{C: "terminal2"}}, - C: "initial", -} -var data2 = Struct{A: []Struct{ - {A: []Struct{{C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}}}, - {A: []Struct{{C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}}}, -}} - -func TestValueAtPathSuccess(t *testing.T) { - var testCases = []struct { - expect []interface{} - data interface{} - path string - }{ - {[]interface{}{"initial"}, data, "C"}, - {[]interface{}{"value1"}, data, "A[0].C"}, - {[]interface{}{"value2"}, data, "A[1].C"}, - {[]interface{}{"value3"}, data, "A[2].C"}, - {[]interface{}{"value3"}, data, "a[2].c"}, - {[]interface{}{"value3"}, data, "A[-1].C"}, - {[]interface{}{"value1", "value2", "value3"}, data, "A[].C"}, - {[]interface{}{"terminal"}, data, "B . B . C"}, - {[]interface{}{"initial"}, data, "A.D.X || C"}, - {[]interface{}{"initial"}, data, "A[0].B || C"}, - {[]interface{}{ - Struct{A: []Struct{{C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}}}, - Struct{A: []Struct{{C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}}}, - }, data2, "A"}, - } - for i, c := range testCases { - v, err := awsutil.ValuesAtPath(c.data, c.path) - if err != nil { - t.Errorf("case %v, expected no error, %v", i, c.path) - } - if e, a := c.expect, v; !awsutil.DeepEqual(e, a) { - t.Errorf("case %v, %v", i, c.path) - } - } -} - -func TestValueAtPathFailure(t *testing.T) { - var testCases = []struct { - expect []interface{} - errContains string - data interface{} - path string - }{ - {nil, "", data, "C.x"}, - {nil, "SyntaxError: Invalid token: tDot", data, ".x"}, - {nil, "", data, "X.Y.Z"}, - {nil, "", data, "A[100].C"}, - {nil, "", data, "A[3].C"}, - {nil, "", data, "B.B.C.Z"}, - {nil, "", data, "z[-1].C"}, - {nil, "", nil, "A.B.C"}, - {[]interface{}{}, "", Struct{}, "A"}, - {nil, "", data, "A[0].B.C"}, - {nil, "", data, "D"}, - } - - for i, c := range testCases { - v, err := awsutil.ValuesAtPath(c.data, c.path) - if c.errContains != "" { - if !strings.Contains(err.Error(), c.errContains) { - t.Errorf("case %v, expected error, %v", i, c.path) - } - continue - } else { - if err != nil { - t.Errorf("case %v, expected no error, %v", i, c.path) - } - } - if e, a := c.expect, v; !awsutil.DeepEqual(e, a) { - t.Errorf("case %v, %v", i, c.path) - } - } -} - -func TestSetValueAtPathSuccess(t *testing.T) { - var s Struct - awsutil.SetValueAtPath(&s, "C", "test1") - awsutil.SetValueAtPath(&s, "B.B.C", "test2") - awsutil.SetValueAtPath(&s, "B.D.C", "test3") - if e, a := "test1", s.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - if e, a := "test2", s.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - if e, a := "test3", s.B.D.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - awsutil.SetValueAtPath(&s, "B.*.C", "test0") - if e, a := "test0", s.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - if e, a := "test0", s.B.D.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - var s2 Struct - awsutil.SetValueAtPath(&s2, "b.b.c", "test0") - if e, a := "test0", s2.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - awsutil.SetValueAtPath(&s2, "A", []Struct{{}}) - if e, a := []Struct{{}}, s2.A; !awsutil.DeepEqual(e, a) { - t.Errorf("expected %v, but received %v", e, a) - } - - str := "foo" - - s3 := Struct{} - awsutil.SetValueAtPath(&s3, "b.b.c", str) - if e, a := "foo", s3.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s3 = Struct{B: &Struct{B: &Struct{C: str}}} - awsutil.SetValueAtPath(&s3, "b.b.c", nil) - if e, a := "", s3.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s3 = Struct{} - awsutil.SetValueAtPath(&s3, "b.b.c", nil) - if e, a := "", s3.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s3 = Struct{} - awsutil.SetValueAtPath(&s3, "b.b.c", &str) - if e, a := "foo", s3.B.B.C; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - var s4 struct{ Name *string } - awsutil.SetValueAtPath(&s4, "Name", str) - if e, a := str, *s4.Name; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s4 = struct{ Name *string }{} - awsutil.SetValueAtPath(&s4, "Name", nil) - if e, a := (*string)(nil), s4.Name; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s4 = struct{ Name *string }{Name: &str} - awsutil.SetValueAtPath(&s4, "Name", nil) - if e, a := (*string)(nil), s4.Name; e != a { - t.Errorf("expected %v, but received %v", e, a) - } - - s4 = struct{ Name *string }{} - awsutil.SetValueAtPath(&s4, "Name", &str) - if e, a := str, *s4.Name; e != a { - t.Errorf("expected %v, but received %v", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go index 3271a18e..212fe25e 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go @@ -91,6 +91,6 @@ func (c *Client) AddDebugHandlers() { return } - c.Handlers.Send.PushFrontNamed(request.NamedHandler{Name: "awssdk.client.LogRequest", Fn: logRequest}) - c.Handlers.Send.PushBackNamed(request.NamedHandler{Name: "awssdk.client.LogResponse", Fn: logResponse}) + c.Handlers.Send.PushFrontNamed(LogHTTPRequestHandler) + c.Handlers.Send.PushBackNamed(LogHTTPResponseHandler) } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/client_test.go b/vendor/github.com/aws/aws-sdk-go/aws/client/client_test.go deleted file mode 100644 index 30d3b999..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/client_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package client - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" -) - -func pushBackTestHandler(name string, list *request.HandlerList) *bool { - called := false - (*list).PushBackNamed(request.NamedHandler{ - Name: name, - Fn: func(r *request.Request) { - called = true - }, - }) - - return &called -} - -func pushFrontTestHandler(name string, list *request.HandlerList) *bool { - called := false - (*list).PushFrontNamed(request.NamedHandler{ - Name: name, - Fn: func(r *request.Request) { - called = true - }, - }) - - return &called -} - -func TestNewClient_CopyHandlers(t *testing.T) { - handlers := request.Handlers{} - firstCalled := pushBackTestHandler("first", &handlers.Send) - secondCalled := pushBackTestHandler("second", &handlers.Send) - - var clientHandlerCalled *bool - c := New(aws.Config{}, metadata.ClientInfo{}, handlers, - func(c *Client) { - clientHandlerCalled = pushFrontTestHandler("client handler", &c.Handlers.Send) - }, - ) - - if e, a := 2, handlers.Send.Len(); e != a { - t.Errorf("expect %d original handlers, got %d", e, a) - } - if e, a := 3, c.Handlers.Send.Len(); e != a { - t.Errorf("expect %d client handlers, got %d", e, a) - } - - handlers.Send.Run(nil) - if !*firstCalled { - t.Errorf("expect first handler to of been called") - } - *firstCalled = false - if !*secondCalled { - t.Errorf("expect second handler to of been called") - } - *secondCalled = false - if *clientHandlerCalled { - t.Errorf("expect client handler to not of been called, but was") - } - - c.Handlers.Send.Run(nil) - if !*firstCalled { - t.Errorf("expect client's first handler to of been called") - } - if !*secondCalled { - t.Errorf("expect client's second handler to of been called") - } - if !*clientHandlerCalled { - t.Errorf("expect client's client handler to of been called") - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer_test.go b/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer_test.go deleted file mode 100644 index fddba4e4..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package client - -import ( - "net/http" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/request" -) - -func TestRetryThrottleStatusCodes(t *testing.T) { - cases := []struct { - expectThrottle bool - expectRetry bool - r request.Request - }{ - { - false, - false, - request.Request{ - HTTPResponse: &http.Response{StatusCode: 200}, - }, - }, - { - true, - true, - request.Request{ - HTTPResponse: &http.Response{StatusCode: 429}, - }, - }, - { - true, - true, - request.Request{ - HTTPResponse: &http.Response{StatusCode: 502}, - }, - }, - { - true, - true, - request.Request{ - HTTPResponse: &http.Response{StatusCode: 503}, - }, - }, - { - true, - true, - request.Request{ - HTTPResponse: &http.Response{StatusCode: 504}, - }, - }, - { - false, - true, - request.Request{ - HTTPResponse: &http.Response{StatusCode: 500}, - }, - }, - } - - d := DefaultRetryer{NumMaxRetries: 10} - for i, c := range cases { - throttle := d.shouldThrottle(&c.r) - retry := d.ShouldRetry(&c.r) - - if e, a := c.expectThrottle, throttle; e != a { - t.Errorf("%d: expected %v, but received %v", i, e, a) - } - - if e, a := c.expectRetry, retry; e != a { - t.Errorf("%d: expected %v, but received %v", i, e, a) - } - } -} - -func TestCanUseRetryAfter(t *testing.T) { - cases := []struct { - r request.Request - e bool - }{ - { - request.Request{ - HTTPResponse: &http.Response{StatusCode: 200}, - }, - false, - }, - { - request.Request{ - HTTPResponse: &http.Response{StatusCode: 500}, - }, - false, - }, - { - request.Request{ - HTTPResponse: &http.Response{StatusCode: 429}, - }, - true, - }, - { - request.Request{ - HTTPResponse: &http.Response{StatusCode: 503}, - }, - true, - }, - } - - for i, c := range cases { - a := canUseRetryAfterHeader(&c.r) - if c.e != a { - t.Errorf("%d: expected %v, but received %v", i, c.e, a) - } - } -} - -func TestGetRetryDelay(t *testing.T) { - cases := []struct { - r request.Request - e time.Duration - equal bool - ok bool - }{ - { - request.Request{ - HTTPResponse: &http.Response{StatusCode: 429, Header: http.Header{"Retry-After": []string{"3600"}}}, - }, - 3600 * time.Second, - true, - true, - }, - { - request.Request{ - HTTPResponse: &http.Response{StatusCode: 503, Header: http.Header{"Retry-After": []string{"120"}}}, - }, - 120 * time.Second, - true, - true, - }, - { - request.Request{ - HTTPResponse: &http.Response{StatusCode: 503, Header: http.Header{"Retry-After": []string{"120"}}}, - }, - 1 * time.Second, - false, - true, - }, - { - request.Request{ - HTTPResponse: &http.Response{StatusCode: 503, Header: http.Header{"Retry-After": []string{""}}}, - }, - 0 * time.Second, - true, - false, - }, - } - - for i, c := range cases { - a, ok := getRetryDelay(&c.r) - if c.ok != ok { - t.Errorf("%d: expected %v, but received %v", i, c.ok, ok) - } - - if (c.e != a) == c.equal { - t.Errorf("%d: expected %v, but received %v", i, c.e, a) - } - } -} - -func TestRetryDelay(t *testing.T) { - r := request.Request{} - for i := 0; i < 100; i++ { - rTemp := r - rTemp.HTTPResponse = &http.Response{StatusCode: 500, Header: http.Header{"Retry-After": []string{""}}} - rTemp.RetryCount = i - a, _ := getRetryDelay(&rTemp) - if a > 5*time.Minute { - t.Errorf("retry delay should never be greater than five minutes, received %d", a) - } - } - - for i := 0; i < 100; i++ { - rTemp := r - rTemp.RetryCount = i - rTemp.HTTPResponse = &http.Response{StatusCode: 503, Header: http.Header{"Retry-After": []string{""}}} - a, _ := getRetryDelay(&rTemp) - if a > 5*time.Minute { - t.Errorf("retry delay should never be greater than five minutes, received %d", a) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go b/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go index e223c54c..ce9fb896 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go @@ -44,12 +44,22 @@ func (reader *teeReaderCloser) Close() error { return reader.Source.Close() } +// LogHTTPRequestHandler is a SDK request handler to log the HTTP request sent +// to a service. Will include the HTTP request body if the LogLevel of the +// request matches LogDebugWithHTTPBody. +var LogHTTPRequestHandler = request.NamedHandler{ + Name: "awssdk.client.LogRequest", + Fn: logRequest, +} + func logRequest(r *request.Request) { logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) bodySeekable := aws.IsReaderSeekable(r.Body) - dumpedBody, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) + + b, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) if err != nil { - r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err)) + r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, + r.ClientInfo.ServiceName, r.Operation.Name, err)) return } @@ -63,7 +73,28 @@ func logRequest(r *request.Request) { r.ResetBody() } - r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.ClientInfo.ServiceName, r.Operation.Name, string(dumpedBody))) + r.Config.Logger.Log(fmt.Sprintf(logReqMsg, + r.ClientInfo.ServiceName, r.Operation.Name, string(b))) +} + +// LogHTTPRequestHeaderHandler is a SDK request handler to log the HTTP request sent +// to a service. Will only log the HTTP request's headers. The request payload +// will not be read. +var LogHTTPRequestHeaderHandler = request.NamedHandler{ + Name: "awssdk.client.LogRequestHeader", + Fn: logRequestHeader, +} + +func logRequestHeader(r *request.Request) { + b, err := httputil.DumpRequestOut(r.HTTPRequest, false) + if err != nil { + r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, + r.ClientInfo.ServiceName, r.Operation.Name, err)) + return + } + + r.Config.Logger.Log(fmt.Sprintf(logReqMsg, + r.ClientInfo.ServiceName, r.Operation.Name, string(b))) } const logRespMsg = `DEBUG: Response %s/%s Details: @@ -76,27 +107,44 @@ const logRespErrMsg = `DEBUG ERROR: Response %s/%s: %s -----------------------------------------------------` +// LogHTTPResponseHandler is a SDK request handler to log the HTTP response +// received from a service. Will include the HTTP response body if the LogLevel +// of the request matches LogDebugWithHTTPBody. +var LogHTTPResponseHandler = request.NamedHandler{ + Name: "awssdk.client.LogResponse", + Fn: logResponse, +} + func logResponse(r *request.Request) { lw := &logWriter{r.Config.Logger, bytes.NewBuffer(nil)} - r.HTTPResponse.Body = &teeReaderCloser{ - Reader: io.TeeReader(r.HTTPResponse.Body, lw), - Source: r.HTTPResponse.Body, + + logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) + if logBody { + r.HTTPResponse.Body = &teeReaderCloser{ + Reader: io.TeeReader(r.HTTPResponse.Body, lw), + Source: r.HTTPResponse.Body, + } } handlerFn := func(req *request.Request) { - body, err := httputil.DumpResponse(req.HTTPResponse, false) + b, err := httputil.DumpResponse(req.HTTPResponse, false) if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.ClientInfo.ServiceName, req.Operation.Name, err)) + lw.Logger.Log(fmt.Sprintf(logRespErrMsg, + req.ClientInfo.ServiceName, req.Operation.Name, err)) return } - b, err := ioutil.ReadAll(lw.buf) - if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.ClientInfo.ServiceName, req.Operation.Name, err)) - return - } - lw.Logger.Log(fmt.Sprintf(logRespMsg, req.ClientInfo.ServiceName, req.Operation.Name, string(body))) - if req.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) { + lw.Logger.Log(fmt.Sprintf(logRespMsg, + req.ClientInfo.ServiceName, req.Operation.Name, string(b))) + + if logBody { + b, err := ioutil.ReadAll(lw.buf) + if err != nil { + lw.Logger.Log(fmt.Sprintf(logRespErrMsg, + req.ClientInfo.ServiceName, req.Operation.Name, err)) + return + } + lw.Logger.Log(string(b)) } } @@ -110,3 +158,27 @@ func logResponse(r *request.Request) { Name: handlerName, Fn: handlerFn, }) } + +// LogHTTPResponseHeaderHandler is a SDK request handler to log the HTTP +// response received from a service. Will only log the HTTP response's headers. +// The response payload will not be read. +var LogHTTPResponseHeaderHandler = request.NamedHandler{ + Name: "awssdk.client.LogResponseHeader", + Fn: logResponseHeader, +} + +func logResponseHeader(r *request.Request) { + if r.Config.Logger == nil { + return + } + + b, err := httputil.DumpResponse(r.HTTPResponse, false) + if err != nil { + r.Config.Logger.Log(fmt.Sprintf(logRespErrMsg, + r.ClientInfo.ServiceName, r.Operation.Name, err)) + return + } + + r.Config.Logger.Log(fmt.Sprintf(logRespMsg, + r.ClientInfo.ServiceName, r.Operation.Name, string(b))) +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/logger_test.go b/vendor/github.com/aws/aws-sdk-go/aws/client/logger_test.go deleted file mode 100644 index f0e06b80..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/logger_test.go +++ /dev/null @@ -1,144 +0,0 @@ -package client - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "reflect" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" -) - -type mockCloser struct { - closed bool -} - -func (closer *mockCloser) Read(b []byte) (int, error) { - return 0, io.EOF -} - -func (closer *mockCloser) Close() error { - closer.closed = true - return nil -} - -func TestTeeReaderCloser(t *testing.T) { - expected := "FOO" - buf := bytes.NewBuffer([]byte(expected)) - lw := bytes.NewBuffer(nil) - c := &mockCloser{} - closer := teeReaderCloser{ - io.TeeReader(buf, lw), - c, - } - - b := make([]byte, len(expected)) - _, err := closer.Read(b) - closer.Close() - - if expected != lw.String() { - t.Errorf("Expected %q, but received %q", expected, lw.String()) - } - - if err != nil { - t.Errorf("Expected 'nil', but received %v", err) - } - - if !c.closed { - t.Error("Expected 'true', but received 'false'") - } -} - -func TestLogWriter(t *testing.T) { - expected := "FOO" - lw := &logWriter{nil, bytes.NewBuffer(nil)} - lw.Write([]byte(expected)) - - if expected != lw.buf.String() { - t.Errorf("Expected %q, but received %q", expected, lw.buf.String()) - } -} - -func TestLogRequest(t *testing.T) { - cases := []struct { - Body io.ReadSeeker - ExpectBody []byte - LogLevel aws.LogLevelType - }{ - { - Body: aws.ReadSeekCloser(bytes.NewBuffer([]byte("body content"))), - ExpectBody: []byte("body content"), - }, - { - Body: aws.ReadSeekCloser(bytes.NewBuffer([]byte("body content"))), - LogLevel: aws.LogDebugWithHTTPBody, - ExpectBody: []byte("body content"), - }, - { - Body: bytes.NewReader([]byte("body content")), - ExpectBody: []byte("body content"), - }, - { - Body: bytes.NewReader([]byte("body content")), - LogLevel: aws.LogDebugWithHTTPBody, - ExpectBody: []byte("body content"), - }, - } - - for i, c := range cases { - logW := bytes.NewBuffer(nil) - req := request.New( - aws.Config{ - Credentials: credentials.AnonymousCredentials, - Logger: &bufLogger{w: logW}, - LogLevel: aws.LogLevel(c.LogLevel), - }, - metadata.ClientInfo{ - Endpoint: "https://mock-service.mock-region.amazonaws.com", - }, - testHandlers(), - nil, - &request.Operation{ - Name: "APIName", - HTTPMethod: "POST", - HTTPPath: "/", - }, - struct{}{}, nil, - ) - req.SetReaderBody(c.Body) - req.Build() - - logRequest(req) - - b, err := ioutil.ReadAll(req.HTTPRequest.Body) - if err != nil { - t.Fatalf("%d, expect to read SDK request Body", i) - } - - if e, a := c.ExpectBody, b; !reflect.DeepEqual(e, a) { - t.Errorf("%d, expect %v body, got %v", i, e, a) - } - } -} - -type bufLogger struct { - w *bytes.Buffer -} - -func (l *bufLogger) Log(args ...interface{}) { - fmt.Fprintln(l.w, args...) -} - -func testHandlers() request.Handlers { - var handlers request.Handlers - - handlers.Build.PushBackNamed(corehandlers.SDKVersionUserAgentHandler) - - return handlers -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/config_test.go b/vendor/github.com/aws/aws-sdk-go/aws/config_test.go deleted file mode 100644 index fe97a31f..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/config_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package aws - -import ( - "net/http" - "reflect" - "testing" - - "github.com/aws/aws-sdk-go/aws/credentials" -) - -var testCredentials = credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - -var copyTestConfig = Config{ - Credentials: testCredentials, - Endpoint: String("CopyTestEndpoint"), - Region: String("COPY_TEST_AWS_REGION"), - DisableSSL: Bool(true), - HTTPClient: http.DefaultClient, - LogLevel: LogLevel(LogDebug), - Logger: NewDefaultLogger(), - MaxRetries: Int(3), - DisableParamValidation: Bool(true), - DisableComputeChecksums: Bool(true), - S3ForcePathStyle: Bool(true), -} - -func TestCopy(t *testing.T) { - want := copyTestConfig - got := copyTestConfig.Copy() - if !reflect.DeepEqual(*got, want) { - t.Errorf("Copy() = %+v", got) - t.Errorf(" want %+v", want) - } - - got.Region = String("other") - if got.Region == want.Region { - t.Errorf("Expect setting copy values not not reflect in source") - } -} - -func TestCopyReturnsNewInstance(t *testing.T) { - want := copyTestConfig - got := copyTestConfig.Copy() - if got == &want { - t.Errorf("Copy() = %p; want different instance as source %p", got, &want) - } -} - -var mergeTestZeroValueConfig = Config{} - -var mergeTestConfig = Config{ - Credentials: testCredentials, - Endpoint: String("MergeTestEndpoint"), - Region: String("MERGE_TEST_AWS_REGION"), - DisableSSL: Bool(true), - HTTPClient: http.DefaultClient, - LogLevel: LogLevel(LogDebug), - Logger: NewDefaultLogger(), - MaxRetries: Int(10), - DisableParamValidation: Bool(true), - DisableComputeChecksums: Bool(true), - S3ForcePathStyle: Bool(true), -} - -var mergeTests = []struct { - cfg *Config - in *Config - want *Config -}{ - {&Config{}, nil, &Config{}}, - {&Config{}, &mergeTestZeroValueConfig, &Config{}}, - {&Config{}, &mergeTestConfig, &mergeTestConfig}, -} - -func TestMerge(t *testing.T) { - for i, tt := range mergeTests { - got := tt.cfg.Copy() - got.MergeIn(tt.in) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Config %d %+v", i, tt.cfg) - t.Errorf(" Merge(%+v)", tt.in) - t.Errorf(" got %+v", got) - t.Errorf(" want %+v", tt.want) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_test.go b/vendor/github.com/aws/aws-sdk-go/aws/context_test.go deleted file mode 100644 index d80a1bb6..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package aws_test - -import ( - "fmt" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/awstesting" -) - -func TestSleepWithContext(t *testing.T) { - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - - err := aws.SleepWithContext(ctx, 1*time.Millisecond) - if err != nil { - t.Errorf("expect context to not be canceled, got %v", err) - } -} - -func TestSleepWithContext_Canceled(t *testing.T) { - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - - expectErr := fmt.Errorf("context canceled") - - ctx.Error = expectErr - close(ctx.DoneCh) - - err := aws.SleepWithContext(ctx, 1*time.Millisecond) - if err == nil { - t.Fatalf("expect error, did not get one") - } - - if e, a := expectErr, err; e != a { - t.Errorf("expect %v error, got %v", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/convert_types_test.go b/vendor/github.com/aws/aws-sdk-go/aws/convert_types_test.go deleted file mode 100644 index 1a9461e1..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/convert_types_test.go +++ /dev/null @@ -1,641 +0,0 @@ -package aws - -import ( - "reflect" - "testing" - "time" -) - -var testCasesStringSlice = [][]string{ - {"a", "b", "c", "d", "e"}, - {"a", "b", "", "", "e"}, -} - -func TestStringSlice(t *testing.T) { - for idx, in := range testCasesStringSlice { - if in == nil { - continue - } - out := StringSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := StringValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesStringValueSlice = [][]*string{ - {String("a"), String("b"), nil, String("c")}, -} - -func TestStringValueSlice(t *testing.T) { - for idx, in := range testCasesStringValueSlice { - if in == nil { - continue - } - out := StringValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if out[i] != "" { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := StringSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if *(out2[i]) != "" { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *in[i], *out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesStringMap = []map[string]string{ - {"a": "1", "b": "2", "c": "3"}, -} - -func TestStringMap(t *testing.T) { - for idx, in := range testCasesStringMap { - if in == nil { - continue - } - out := StringMap(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := StringValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesBoolSlice = [][]bool{ - {true, true, false, false}, -} - -func TestBoolSlice(t *testing.T) { - for idx, in := range testCasesBoolSlice { - if in == nil { - continue - } - out := BoolSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := BoolValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesBoolValueSlice = [][]*bool{} - -func TestBoolValueSlice(t *testing.T) { - for idx, in := range testCasesBoolValueSlice { - if in == nil { - continue - } - out := BoolValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if out[i] { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := BoolSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if *(out2[i]) { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := in[i], out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesBoolMap = []map[string]bool{ - {"a": true, "b": false, "c": true}, -} - -func TestBoolMap(t *testing.T) { - for idx, in := range testCasesBoolMap { - if in == nil { - continue - } - out := BoolMap(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := BoolValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesIntSlice = [][]int{ - {1, 2, 3, 4}, -} - -func TestIntSlice(t *testing.T) { - for idx, in := range testCasesIntSlice { - if in == nil { - continue - } - out := IntSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := IntValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesIntValueSlice = [][]*int{} - -func TestIntValueSlice(t *testing.T) { - for idx, in := range testCasesIntValueSlice { - if in == nil { - continue - } - out := IntValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if out[i] != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := IntSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if *(out2[i]) != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := in[i], out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesIntMap = []map[string]int{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestIntMap(t *testing.T) { - for idx, in := range testCasesIntMap { - if in == nil { - continue - } - out := IntMap(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := IntValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesInt64Slice = [][]int64{ - {1, 2, 3, 4}, -} - -func TestInt64Slice(t *testing.T) { - for idx, in := range testCasesInt64Slice { - if in == nil { - continue - } - out := Int64Slice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := Int64ValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesInt64ValueSlice = [][]*int64{} - -func TestInt64ValueSlice(t *testing.T) { - for idx, in := range testCasesInt64ValueSlice { - if in == nil { - continue - } - out := Int64ValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if out[i] != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := Int64Slice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if *(out2[i]) != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := in[i], out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesInt64Map = []map[string]int64{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestInt64Map(t *testing.T) { - for idx, in := range testCasesInt64Map { - if in == nil { - continue - } - out := Int64Map(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := Int64ValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesFloat64Slice = [][]float64{ - {1, 2, 3, 4}, -} - -func TestFloat64Slice(t *testing.T) { - for idx, in := range testCasesFloat64Slice { - if in == nil { - continue - } - out := Float64Slice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := Float64ValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesFloat64ValueSlice = [][]*float64{} - -func TestFloat64ValueSlice(t *testing.T) { - for idx, in := range testCasesFloat64ValueSlice { - if in == nil { - continue - } - out := Float64ValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if out[i] != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := Float64Slice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if *(out2[i]) != 0 { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := in[i], out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesFloat64Map = []map[string]float64{ - {"a": 3, "b": 2, "c": 1}, -} - -func TestFloat64Map(t *testing.T) { - for idx, in := range testCasesFloat64Map { - if in == nil { - continue - } - out := Float64Map(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := Float64ValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesTimeSlice = [][]time.Time{ - {time.Now(), time.Now().AddDate(100, 0, 0)}, -} - -func TestTimeSlice(t *testing.T) { - for idx, in := range testCasesTimeSlice { - if in == nil { - continue - } - out := TimeSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := TimeValueSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -var testCasesTimeValueSlice = [][]*time.Time{} - -func TestTimeValueSlice(t *testing.T) { - for idx, in := range testCasesTimeValueSlice { - if in == nil { - continue - } - out := TimeValueSlice(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if in[i] == nil { - if !out[i].IsZero() { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := *(in[i]), out[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - - out2 := TimeSlice(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out2 { - if in[i] == nil { - if !(*(out2[i])).IsZero() { - t.Errorf("Unexpected value at idx %d", idx) - } - } else { - if e, a := in[i], out2[i]; e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - } - } -} - -var testCasesTimeMap = []map[string]time.Time{ - {"a": time.Now().AddDate(-100, 0, 0), "b": time.Now()}, -} - -func TestTimeMap(t *testing.T) { - for idx, in := range testCasesTimeMap { - if in == nil { - continue - } - out := TimeMap(in) - if e, a := len(out), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - for i := range out { - if e, a := in[i], *(out[i]); e != a { - t.Errorf("Unexpected value at idx %d", idx) - } - } - - out2 := TimeValueMap(out) - if e, a := len(out2), len(in); e != a { - t.Errorf("Unexpected len at idx %d", idx) - } - if e, a := in, out2; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected value at idx %d", idx) - } - } -} - -type TimeValueTestCase struct { - in int64 - outSecs time.Time - outMillis time.Time -} - -var testCasesTimeValue = []TimeValueTestCase{ - { - in: int64(1501558289000), - outSecs: time.Unix(1501558289, 0), - outMillis: time.Unix(1501558289, 0), - }, - { - in: int64(1501558289001), - outSecs: time.Unix(1501558289, 0), - outMillis: time.Unix(1501558289, 1*1000000), - }, -} - -func TestSecondsTimeValue(t *testing.T) { - for idx, testCase := range testCasesTimeValue { - out := SecondsTimeValue(&testCase.in) - if e, a := testCase.outSecs, out; e != a { - t.Errorf("Unexpected value for time value at %d", idx) - } - } -} - -func TestMillisecondsTimeValue(t *testing.T) { - for idx, testCase := range testCasesTimeValue { - out := MillisecondsTimeValue(&testCase.in) - if e, a := testCase.outMillis, out; e != a { - t.Errorf("Unexpected value for time value at %d", idx) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_1_8_test.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_1_8_test.go deleted file mode 100644 index b47afc24..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_1_8_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// +build go1.8 - -package corehandlers_test - -import ( - "crypto/tls" - "net/http" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/service/s3" - "golang.org/x/net/http2" -) - -func TestSendHandler_HEADNoBody(t *testing.T) { - TLSBundleCertFile, TLSBundleKeyFile, TLSBundleCAFile, err := awstesting.CreateTLSBundleFiles() - if err != nil { - panic(err) - } - defer awstesting.CleanupTLSBundleFiles(TLSBundleCertFile, TLSBundleKeyFile, TLSBundleCAFile) - - endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - transport := http.DefaultTransport.(*http.Transport) - // test server's certificate is self-signed certificate - transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} - http2.ConfigureTransport(transport) - - sess, err := session.NewSessionWithOptions(session.Options{ - Config: aws.Config{ - HTTPClient: &http.Client{}, - Endpoint: aws.String(endpoint), - Region: aws.String("mock-region"), - Credentials: credentials.AnonymousCredentials, - S3ForcePathStyle: aws.Bool(true), - }, - }) - - svc := s3.New(sess) - - req, _ := svc.HeadObjectRequest(&s3.HeadObjectInput{ - Bucket: aws.String("bucketname"), - Key: aws.String("keyname"), - }) - - if e, a := request.NoBody, req.HTTPRequest.Body; e != a { - t.Fatalf("expect %T request body, got %T", e, a) - } - - err = req.Send() - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := http.StatusOK, req.HTTPResponse.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_test.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_test.go deleted file mode 100644 index 1d715c9f..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_test.go +++ /dev/null @@ -1,398 +0,0 @@ -package corehandlers_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "os" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/s3" -) - -func TestValidateEndpointHandler(t *testing.T) { - os.Clearenv() - - svc := awstesting.NewClient(aws.NewConfig().WithRegion("us-west-2")) - svc.Handlers.Clear() - svc.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) - - req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := req.Build() - - if err != nil { - t.Errorf("expect no error, got %v", err) - } -} - -func TestValidateEndpointHandlerErrorRegion(t *testing.T) { - os.Clearenv() - - svc := awstesting.NewClient() - svc.Handlers.Clear() - svc.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) - - req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := req.Build() - - if err == nil { - t.Errorf("expect error, got none") - } - if e, a := aws.ErrMissingRegion, err; e != a { - t.Errorf("expect %v to be %v", e, a) - } -} - -type mockCredsProvider struct { - expired bool - retrieveCalled bool -} - -func (m *mockCredsProvider) Retrieve() (credentials.Value, error) { - m.retrieveCalled = true - return credentials.Value{ProviderName: "mockCredsProvider"}, nil -} - -func (m *mockCredsProvider) IsExpired() bool { - return m.expired -} - -func TestAfterRetryRefreshCreds(t *testing.T) { - os.Clearenv() - credProvider := &mockCredsProvider{} - - svc := awstesting.NewClient(&aws.Config{ - Credentials: credentials.NewCredentials(credProvider), - MaxRetries: aws.Int(1), - }) - - svc.Handlers.Clear() - svc.Handlers.ValidateResponse.PushBack(func(r *request.Request) { - r.Error = awserr.New("UnknownError", "", nil) - r.HTTPResponse = &http.Response{StatusCode: 400, Body: ioutil.NopCloser(bytes.NewBuffer([]byte{}))} - }) - svc.Handlers.UnmarshalError.PushBack(func(r *request.Request) { - r.Error = awserr.New("ExpiredTokenException", "", nil) - }) - svc.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) - - if !svc.Config.Credentials.IsExpired() { - t.Errorf("Expect to start out expired") - } - if credProvider.retrieveCalled { - t.Errorf("expect not called") - } - - req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - req.Send() - - if !svc.Config.Credentials.IsExpired() { - t.Errorf("Expect to start out expired") - } - if credProvider.retrieveCalled { - t.Errorf("expect not called") - } - - _, err := svc.Config.Credentials.Get() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if !credProvider.retrieveCalled { - t.Errorf("expect not called") - } -} - -func TestAfterRetryWithContextCanceled(t *testing.T) { - c := awstesting.NewClient() - - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{}, 0)} - req.SetContext(ctx) - - req.Error = fmt.Errorf("some error") - req.Retryable = aws.Bool(true) - req.HTTPResponse = &http.Response{ - StatusCode: 500, - } - - close(ctx.DoneCh) - ctx.Error = fmt.Errorf("context canceled") - - corehandlers.AfterRetryHandler.Fn(req) - - if req.Error == nil { - t.Fatalf("expect error but didn't receive one") - } - - aerr := req.Error.(awserr.Error) - - if e, a := request.CanceledErrorCode, aerr.Code(); e != a { - t.Errorf("expect %q, error code got %q", e, a) - } -} - -func TestAfterRetryWithContext(t *testing.T) { - c := awstesting.NewClient() - - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{}, 0)} - req.SetContext(ctx) - - req.Error = fmt.Errorf("some error") - req.Retryable = aws.Bool(true) - req.HTTPResponse = &http.Response{ - StatusCode: 500, - } - - corehandlers.AfterRetryHandler.Fn(req) - - if req.Error != nil { - t.Fatalf("expect no error, got %v", req.Error) - } - if e, a := 1, req.RetryCount; e != a { - t.Errorf("expect retry count to be %d, got %d", e, a) - } -} - -func TestSendWithContextCanceled(t *testing.T) { - c := awstesting.NewClient(&aws.Config{ - SleepDelay: func(dur time.Duration) { - t.Errorf("SleepDelay should not be called") - }, - }) - - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{}, 0)} - req.SetContext(ctx) - - req.Error = fmt.Errorf("some error") - req.Retryable = aws.Bool(true) - req.HTTPResponse = &http.Response{ - StatusCode: 500, - } - - close(ctx.DoneCh) - ctx.Error = fmt.Errorf("context canceled") - - corehandlers.SendHandler.Fn(req) - - if req.Error == nil { - t.Fatalf("expect error but didn't receive one") - } - - aerr := req.Error.(awserr.Error) - - if e, a := request.CanceledErrorCode, aerr.Code(); e != a { - t.Errorf("expect %q, error code got %q", e, a) - } -} - -type testSendHandlerTransport struct{} - -func (t *testSendHandlerTransport) RoundTrip(r *http.Request) (*http.Response, error) { - return nil, fmt.Errorf("mock error") -} - -func TestSendHandlerError(t *testing.T) { - svc := awstesting.NewClient(&aws.Config{ - HTTPClient: &http.Client{ - Transport: &testSendHandlerTransport{}, - }, - }) - svc.Handlers.Clear() - svc.Handlers.Send.PushBackNamed(corehandlers.SendHandler) - r := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - - r.Send() - - if r.Error == nil { - t.Errorf("expect error, got none") - } - if r.HTTPResponse == nil { - t.Errorf("expect response, got none") - } -} - -func TestSendWithoutFollowRedirects(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/original": - w.Header().Set("Location", "/redirected") - w.WriteHeader(301) - case "/redirected": - t.Fatalf("expect not to redirect, but was") - } - })) - - svc := awstesting.NewClient(&aws.Config{ - DisableSSL: aws.Bool(true), - Endpoint: aws.String(server.URL), - }) - svc.Handlers.Clear() - svc.Handlers.Send.PushBackNamed(corehandlers.SendHandler) - - r := svc.NewRequest(&request.Operation{ - Name: "Operation", - HTTPPath: "/original", - }, nil, nil) - r.DisableFollowRedirects = true - - err := r.Send() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := 301, r.HTTPResponse.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} - -func TestValidateReqSigHandler(t *testing.T) { - cases := []struct { - Req *request.Request - Resign bool - }{ - { - Req: &request.Request{ - Config: aws.Config{Credentials: credentials.AnonymousCredentials}, - Time: time.Now().Add(-15 * time.Minute), - }, - Resign: false, - }, - { - Req: &request.Request{ - Time: time.Now().Add(-15 * time.Minute), - }, - Resign: true, - }, - { - Req: &request.Request{ - Time: time.Now().Add(-1 * time.Minute), - }, - Resign: false, - }, - } - - for i, c := range cases { - resigned := false - c.Req.Handlers.Sign.PushBack(func(r *request.Request) { - resigned = true - }) - - corehandlers.ValidateReqSigHandler.Fn(c.Req) - - if c.Req.Error != nil { - t.Errorf("expect no error, got %v", c.Req.Error) - } - if e, a := c.Resign, resigned; e != a { - t.Errorf("%d, expect %v to be %v", i, e, a) - } - } -} - -func setupContentLengthTestServer(t *testing.T, hasContentLength bool, contentLength int64) *httptest.Server { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, ok := r.Header["Content-Length"] - if e, a := hasContentLength, ok; e != a { - t.Errorf("expect %v to be %v", e, a) - } - if hasContentLength { - if e, a := contentLength, r.ContentLength; e != a { - t.Errorf("expect %v to be %v", e, a) - } - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("expect no error, got %v", err) - } - r.Body.Close() - - authHeader := r.Header.Get("Authorization") - if hasContentLength { - if e, a := "content-length", authHeader; !strings.Contains(a, e) { - t.Errorf("expect %v to be in %v", e, a) - } - } else { - if e, a := "content-length", authHeader; strings.Contains(a, e) { - t.Errorf("expect %v to not be in %v", e, a) - } - } - - if e, a := contentLength, int64(len(b)); e != a { - t.Errorf("expect %v to be %v", e, a) - } - })) - - return server -} - -func TestBuildContentLength_ZeroBody(t *testing.T) { - server := setupContentLengthTestServer(t, false, 0) - - svc := s3.New(unit.Session, &aws.Config{ - Endpoint: aws.String(server.URL), - S3ForcePathStyle: aws.Bool(true), - DisableSSL: aws.Bool(true), - }) - _, err := svc.GetObject(&s3.GetObjectInput{ - Bucket: aws.String("bucketname"), - Key: aws.String("keyname"), - }) - - if err != nil { - t.Errorf("expect no error, got %v", err) - } -} - -func TestBuildContentLength_NegativeBody(t *testing.T) { - server := setupContentLengthTestServer(t, false, 0) - - svc := s3.New(unit.Session, &aws.Config{ - Endpoint: aws.String(server.URL), - S3ForcePathStyle: aws.Bool(true), - DisableSSL: aws.Bool(true), - }) - req, _ := svc.GetObjectRequest(&s3.GetObjectInput{ - Bucket: aws.String("bucketname"), - Key: aws.String("keyname"), - }) - - req.HTTPRequest.Header.Set("Content-Length", "-1") - - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } -} - -func TestBuildContentLength_WithBody(t *testing.T) { - server := setupContentLengthTestServer(t, true, 1024) - - svc := s3.New(unit.Session, &aws.Config{ - Endpoint: aws.String(server.URL), - S3ForcePathStyle: aws.Bool(true), - DisableSSL: aws.Bool(true), - }) - _, err := svc.PutObject(&s3.PutObjectInput{ - Bucket: aws.String("bucketname"), - Key: aws.String("keyname"), - Body: bytes.NewReader(make([]byte, 1024)), - }) - - if err != nil { - t.Errorf("expect no error, got %v", err) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.go deleted file mode 100644 index e1d8a08f..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.go +++ /dev/null @@ -1,286 +0,0 @@ -package corehandlers_test - -import ( - "fmt" - "testing" - "reflect" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/kinesis" -) - -var testSvc = func() *client.Client { - s := &client.Client{ - Config: aws.Config{}, - ClientInfo: metadata.ClientInfo{ - ServiceName: "mock-service", - APIVersion: "2015-01-01", - }, - } - return s -}() - -type StructShape struct { - _ struct{} `type:"structure"` - - RequiredList []*ConditionalStructShape `required:"true"` - RequiredMap map[string]*ConditionalStructShape `required:"true"` - RequiredBool *bool `required:"true"` - OptionalStruct *ConditionalStructShape - - hiddenParameter *string -} - -func (s *StructShape) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StructShape"} - if s.RequiredList == nil { - invalidParams.Add(request.NewErrParamRequired("RequiredList")) - } - if s.RequiredMap == nil { - invalidParams.Add(request.NewErrParamRequired("RequiredMap")) - } - if s.RequiredBool == nil { - invalidParams.Add(request.NewErrParamRequired("RequiredBool")) - } - if s.RequiredList != nil { - for i, v := range s.RequiredList { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RequiredList", i), err.(request.ErrInvalidParams)) - } - } - } - if s.RequiredMap != nil { - for i, v := range s.RequiredMap { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RequiredMap", i), err.(request.ErrInvalidParams)) - } - } - } - if s.OptionalStruct != nil { - if err := s.OptionalStruct.Validate(); err != nil { - invalidParams.AddNested("OptionalStruct", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -type ConditionalStructShape struct { - _ struct{} `type:"structure"` - - Name *string `required:"true"` -} - -func (s *ConditionalStructShape) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ConditionalStructShape"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -func TestNoErrors(t *testing.T) { - input := &StructShape{ - RequiredList: []*ConditionalStructShape{}, - RequiredMap: map[string]*ConditionalStructShape{ - "key1": {Name: aws.String("Name")}, - "key2": {Name: aws.String("Name")}, - }, - RequiredBool: aws.Bool(true), - OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")}, - } - - req := testSvc.NewRequest(&request.Operation{}, input, nil) - corehandlers.ValidateParametersHandler.Fn(req) - if req.Error != nil { - t.Fatalf("expect no error, got %v", req.Error) - } -} - -func TestMissingRequiredParameters(t *testing.T) { - input := &StructShape{} - req := testSvc.NewRequest(&request.Operation{}, input, nil) - corehandlers.ValidateParametersHandler.Fn(req) - - if req.Error == nil { - t.Fatalf("expect error") - } - if e, a := "InvalidParameter", req.Error.(awserr.Error).Code(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "3 validation error(s) found.", req.Error.(awserr.Error).Message(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - - errs := req.Error.(awserr.BatchedErrors).OrigErrs() - if e, a := 3, len(errs); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.RequiredList.", errs[0].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.RequiredMap.", errs[1].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.RequiredBool.", errs[2].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - - if e, a := "InvalidParameter: 3 validation error(s) found.\n- missing required field, StructShape.RequiredList.\n- missing required field, StructShape.RequiredMap.\n- missing required field, StructShape.RequiredBool.\n", req.Error.Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestNestedMissingRequiredParameters(t *testing.T) { - input := &StructShape{ - RequiredList: []*ConditionalStructShape{{}}, - RequiredMap: map[string]*ConditionalStructShape{ - "key1": {Name: aws.String("Name")}, - "key2": {}, - }, - RequiredBool: aws.Bool(true), - OptionalStruct: &ConditionalStructShape{}, - } - - req := testSvc.NewRequest(&request.Operation{}, input, nil) - corehandlers.ValidateParametersHandler.Fn(req) - - if req.Error == nil { - t.Fatalf("expect error") - } - if e, a := "InvalidParameter", req.Error.(awserr.Error).Code(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "3 validation error(s) found.", req.Error.(awserr.Error).Message(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - - errs := req.Error.(awserr.BatchedErrors).OrigErrs() - if e, a := 3, len(errs); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.RequiredList[0].Name.", errs[0].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.RequiredMap[key2].Name.", errs[1].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "ParamRequiredError: missing required field, StructShape.OptionalStruct.Name.", errs[2].Error(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -type testInput struct { - StringField *string `min:"5"` - ListField []string `min:"3"` - MapField map[string]string `min:"4"` -} - -func (s testInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "testInput"} - if s.StringField != nil && len(*s.StringField) < 5 { - invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) - } - if s.ListField != nil && len(s.ListField) < 3 { - invalidParams.Add(request.NewErrParamMinLen("ListField", 3)) - } - if s.MapField != nil && len(s.MapField) < 4 { - invalidParams.Add(request.NewErrParamMinLen("MapField", 4)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -var testsFieldMin = []struct { - err awserr.Error - in testInput -}{ - { - err: func() awserr.Error { - invalidParams := request.ErrInvalidParams{Context: "testInput"} - invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) - return invalidParams - }(), - in: testInput{StringField: aws.String("abcd")}, - }, - { - err: func() awserr.Error { - invalidParams := request.ErrInvalidParams{Context: "testInput"} - invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) - invalidParams.Add(request.NewErrParamMinLen("ListField", 3)) - return invalidParams - }(), - in: testInput{StringField: aws.String("abcd"), ListField: []string{"a", "b"}}, - }, - { - err: func() awserr.Error { - invalidParams := request.ErrInvalidParams{Context: "testInput"} - invalidParams.Add(request.NewErrParamMinLen("StringField", 5)) - invalidParams.Add(request.NewErrParamMinLen("ListField", 3)) - invalidParams.Add(request.NewErrParamMinLen("MapField", 4)) - return invalidParams - }(), - in: testInput{StringField: aws.String("abcd"), ListField: []string{"a", "b"}, MapField: map[string]string{"a": "a", "b": "b"}}, - }, - { - err: nil, - in: testInput{StringField: aws.String("abcde"), - ListField: []string{"a", "b", "c"}, MapField: map[string]string{"a": "a", "b": "b", "c": "c", "d": "d"}}, - }, -} - -func TestValidateFieldMinParameter(t *testing.T) { - for i, c := range testsFieldMin { - req := testSvc.NewRequest(&request.Operation{}, &c.in, nil) - corehandlers.ValidateParametersHandler.Fn(req) - - if e, a := c.err, req.Error; !reflect.DeepEqual(e,a) { - t.Errorf("%d, expect %v, got %v", i, e, a) - } - } -} - -func BenchmarkValidateAny(b *testing.B) { - input := &kinesis.PutRecordsInput{ - StreamName: aws.String("stream"), - } - for i := 0; i < 100; i++ { - record := &kinesis.PutRecordsRequestEntry{ - Data: make([]byte, 10000), - PartitionKey: aws.String("partition"), - } - input.Records = append(input.Records, record) - } - - req, _ := kinesis.New(unit.Session).PutRecordsRequest(input) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - corehandlers.ValidateParametersHandler.Fn(req) - if err := req.Error; err != nil { - b.Fatalf("validation failed: %v", err) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent_test.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent_test.go deleted file mode 100644 index 4f618356..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package corehandlers - -import ( - "net/http" - "os" - "testing" - - "github.com/aws/aws-sdk-go/aws/request" -) - -func TestAddHostExecEnvUserAgentHander(t *testing.T) { - cases := []struct { - ExecEnv string - Expect string - }{ - {ExecEnv: "Lambda", Expect: "exec_env/Lambda"}, - {ExecEnv: "", Expect: ""}, - {ExecEnv: "someThingCool", Expect: "exec_env/someThingCool"}, - } - - for i, c := range cases { - os.Clearenv() - os.Setenv(execEnvVar, c.ExecEnv) - - req := &request.Request{ - HTTPRequest: &http.Request{ - Header: http.Header{}, - }, - } - AddHostExecEnvUserAgentHander.Fn(req) - - if err := req.Error; err != nil { - t.Fatalf("%d, expect no error, got %v", i, err) - } - - if e, a := c.Expect, req.HTTPRequest.Header.Get("User-Agent"); e != a { - t.Errorf("%d, expect %v user agent, got %v", i, e, a) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go deleted file mode 100644 index 3b393a2e..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package credentials - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/stretchr/testify/assert" -) - -type secondStubProvider struct { - creds Value - expired bool - err error -} - -func (s *secondStubProvider) Retrieve() (Value, error) { - s.expired = false - s.creds.ProviderName = "secondStubProvider" - return s.creds, s.err -} -func (s *secondStubProvider) IsExpired() bool { - return s.expired -} - -func TestChainProviderWithNames(t *testing.T) { - p := &ChainProvider{ - Providers: []Provider{ - &stubProvider{err: awserr.New("FirstError", "first provider error", nil)}, - &stubProvider{err: awserr.New("SecondError", "second provider error", nil)}, - &secondStubProvider{ - creds: Value{ - AccessKeyID: "AKIF", - SecretAccessKey: "NOSECRET", - SessionToken: "", - }, - }, - &stubProvider{ - creds: Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "", - }, - }, - }, - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - assert.Equal(t, "secondStubProvider", creds.ProviderName, "Expect provider name to match") - - // Also check credentials - assert.Equal(t, "AKIF", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "NOSECRET", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect session token to be empty") - -} - -func TestChainProviderGet(t *testing.T) { - p := &ChainProvider{ - Providers: []Provider{ - &stubProvider{err: awserr.New("FirstError", "first provider error", nil)}, - &stubProvider{err: awserr.New("SecondError", "second provider error", nil)}, - &stubProvider{ - creds: Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "", - }, - }, - }, - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - assert.Equal(t, "AKID", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "SECRET", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect session token to be empty") -} - -func TestChainProviderIsExpired(t *testing.T) { - stubProvider := &stubProvider{expired: true} - p := &ChainProvider{ - Providers: []Provider{ - stubProvider, - }, - } - - assert.True(t, p.IsExpired(), "Expect expired to be true before any Retrieve") - _, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - assert.False(t, p.IsExpired(), "Expect not expired after retrieve") - - stubProvider.expired = true - assert.True(t, p.IsExpired(), "Expect return of expired provider") - - _, err = p.Retrieve() - assert.False(t, p.IsExpired(), "Expect not expired after retrieve") -} - -func TestChainProviderWithNoProvider(t *testing.T) { - p := &ChainProvider{ - Providers: []Provider{}, - } - - assert.True(t, p.IsExpired(), "Expect expired with no providers") - _, err := p.Retrieve() - assert.Equal(t, - ErrNoValidProvidersFoundInChain, - err, - "Expect no providers error returned") -} - -func TestChainProviderWithNoValidProvider(t *testing.T) { - errs := []error{ - awserr.New("FirstError", "first provider error", nil), - awserr.New("SecondError", "second provider error", nil), - } - p := &ChainProvider{ - Providers: []Provider{ - &stubProvider{err: errs[0]}, - &stubProvider{err: errs[1]}, - }, - } - - assert.True(t, p.IsExpired(), "Expect expired with no providers") - _, err := p.Retrieve() - - assert.Equal(t, - ErrNoValidProvidersFoundInChain, - err, - "Expect no providers error returned") -} - -func TestChainProviderWithNoValidProviderWithVerboseEnabled(t *testing.T) { - errs := []error{ - awserr.New("FirstError", "first provider error", nil), - awserr.New("SecondError", "second provider error", nil), - } - p := &ChainProvider{ - VerboseErrors: true, - Providers: []Provider{ - &stubProvider{err: errs[0]}, - &stubProvider{err: errs[1]}, - }, - } - - assert.True(t, p.IsExpired(), "Expect expired with no providers") - _, err := p.Retrieve() - - assert.Equal(t, - awserr.NewBatchError("NoCredentialProviders", "no valid providers in chain", errs), - err, - "Expect no providers error returned") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials_bench_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials_bench_test.go deleted file mode 100644 index 01a5d633..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials_bench_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// +build go1.9 - -package credentials - -import ( - "fmt" - "strconv" - "sync" - "testing" - "time" -) - -func BenchmarkCredentials_Get(b *testing.B) { - stub := &stubProvider{} - - cases := []int{1, 10, 100, 500, 1000, 10000} - - for _, c := range cases { - b.Run(strconv.Itoa(c), func(b *testing.B) { - creds := NewCredentials(stub) - var wg sync.WaitGroup - wg.Add(c) - for i := 0; i < c; i++ { - go func() { - for j := 0; j < b.N; j++ { - v, err := creds.Get() - if err != nil { - b.Fatalf("expect no error %v, %v", v, err) - } - } - wg.Done() - }() - } - b.ResetTimer() - - wg.Wait() - }) - } -} - -func BenchmarkCredentials_Get_Expire(b *testing.B) { - p := &blockProvider{} - - expRates := []int{10000, 1000, 100} - cases := []int{1, 10, 100, 500, 1000, 10000} - - for _, expRate := range expRates { - for _, c := range cases { - b.Run(fmt.Sprintf("%d-%d", expRate, c), func(b *testing.B) { - creds := NewCredentials(p) - var wg sync.WaitGroup - wg.Add(c) - for i := 0; i < c; i++ { - go func(id int) { - for j := 0; j < b.N; j++ { - v, err := creds.Get() - if err != nil { - b.Fatalf("expect no error %v, %v", v, err) - } - // periodically expire creds to cause rwlock - if id == 0 && j%expRate == 0 { - creds.Expire() - } - } - wg.Done() - }(i) - } - b.ResetTimer() - - wg.Wait() - }) - } - } -} - -type blockProvider struct { - creds Value - expired bool - err error -} - -func (s *blockProvider) Retrieve() (Value, error) { - s.expired = false - s.creds.ProviderName = "blockProvider" - time.Sleep(time.Millisecond) - return s.creds, s.err -} -func (s *blockProvider) IsExpired() bool { - return s.expired -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go deleted file mode 100644 index 7b79ba98..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package credentials - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/stretchr/testify/assert" -) - -type stubProvider struct { - creds Value - expired bool - err error -} - -func (s *stubProvider) Retrieve() (Value, error) { - s.expired = false - s.creds.ProviderName = "stubProvider" - return s.creds, s.err -} -func (s *stubProvider) IsExpired() bool { - return s.expired -} - -func TestCredentialsGet(t *testing.T) { - c := NewCredentials(&stubProvider{ - creds: Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "", - }, - expired: true, - }) - - creds, err := c.Get() - assert.Nil(t, err, "Expected no error") - assert.Equal(t, "AKID", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "SECRET", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect session token to be empty") -} - -func TestCredentialsGetWithError(t *testing.T) { - c := NewCredentials(&stubProvider{err: awserr.New("provider error", "", nil), expired: true}) - - _, err := c.Get() - assert.Equal(t, "provider error", err.(awserr.Error).Code(), "Expected provider error") -} - -func TestCredentialsExpire(t *testing.T) { - stub := &stubProvider{} - c := NewCredentials(stub) - - stub.expired = false - assert.True(t, c.IsExpired(), "Expected to start out expired") - c.Expire() - assert.True(t, c.IsExpired(), "Expected to be expired") - - c.forceRefresh = false - assert.False(t, c.IsExpired(), "Expected not to be expired") - - stub.expired = true - assert.True(t, c.IsExpired(), "Expected to be expired") -} - -func TestCredentialsGetWithProviderName(t *testing.T) { - stub := &stubProvider{} - - c := NewCredentials(stub) - - creds, err := c.Get() - assert.Nil(t, err, "Expected no error") - assert.Equal(t, creds.ProviderName, "stubProvider", "Expected provider name to match") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go deleted file mode 100644 index cccd4bff..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package ec2rolecreds_test - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/awstesting/unit" -) - -const credsRespTmpl = `{ - "Code": "Success", - "Type": "AWS-HMAC", - "AccessKeyId" : "accessKey", - "SecretAccessKey" : "secret", - "Token" : "token", - "Expiration" : "%s", - "LastUpdated" : "2009-11-23T0:00:00Z" -}` - -const credsFailRespTmpl = `{ - "Code": "ErrorCode", - "Message": "ErrorMsg", - "LastUpdated": "2009-11-23T0:00:00Z" -}` - -func initTestServer(expireOn string, failAssume bool) *httptest.Server { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/latest/meta-data/iam/security-credentials" { - fmt.Fprintln(w, "RoleName") - } else if r.URL.Path == "/latest/meta-data/iam/security-credentials/RoleName" { - if failAssume { - fmt.Fprintf(w, credsFailRespTmpl) - } else { - fmt.Fprintf(w, credsRespTmpl, expireOn) - } - } else { - http.Error(w, "bad request", http.StatusBadRequest) - } - })) - - return server -} - -func TestEC2RoleProvider(t *testing.T) { - server := initTestServer("2014-12-16T01:51:37Z", false) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error, %v", err) - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") -} - -func TestEC2RoleProviderFailAssume(t *testing.T) { - server := initTestServer("2014-12-16T01:51:37Z", true) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), - } - - creds, err := p.Retrieve() - assert.Error(t, err, "Expect error") - - e := err.(awserr.Error) - assert.Equal(t, "ErrorCode", e.Code()) - assert.Equal(t, "ErrorMsg", e.Message()) - assert.Nil(t, e.OrigErr()) - - assert.Equal(t, "", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "", creds.SessionToken, "Expect session token to match") -} - -func TestEC2RoleProviderIsExpired(t *testing.T) { - server := initTestServer("2014-12-16T01:51:37Z", false) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), - } - p.CurrentTime = func() time.Time { - return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC) - } - - assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.") - - _, err := p.Retrieve() - assert.Nil(t, err, "Expect no error, %v", err) - - assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.") - - p.CurrentTime = func() time.Time { - return time.Date(3014, 12, 15, 21, 26, 0, 0, time.UTC) - } - - assert.True(t, p.IsExpired(), "Expect creds to be expired.") -} - -func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) { - server := initTestServer("2014-12-16T01:51:37Z", false) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), - ExpiryWindow: time.Hour * 1, - } - p.CurrentTime = func() time.Time { - return time.Date(2014, 12, 15, 0, 51, 37, 0, time.UTC) - } - - assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.") - - _, err := p.Retrieve() - assert.Nil(t, err, "Expect no error, %v", err) - - assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.") - - p.CurrentTime = func() time.Time { - return time.Date(2014, 12, 16, 0, 55, 37, 0, time.UTC) - } - - assert.True(t, p.IsExpired(), "Expect creds to be expired.") -} - -func BenchmarkEC3RoleProvider(b *testing.B) { - server := initTestServer("2014-12-16T01:51:37Z", false) - defer server.Close() - - p := &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), - } - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := p.Retrieve(); err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider_test.go deleted file mode 100644 index ad057a35..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package endpointcreds_test - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/stretchr/testify/assert" -) - -func TestRetrieveRefreshableCredentials(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/path/to/endpoint", r.URL.Path) - assert.Equal(t, "application/json", r.Header.Get("Accept")) - assert.Equal(t, "else", r.URL.Query().Get("something")) - - encoder := json.NewEncoder(w) - err := encoder.Encode(map[string]interface{}{ - "AccessKeyID": "AKID", - "SecretAccessKey": "SECRET", - "Token": "TOKEN", - "Expiration": time.Now().Add(1 * time.Hour), - }) - - if err != nil { - fmt.Println("failed to write out creds", err) - } - })) - - client := endpointcreds.NewProviderClient(*unit.Session.Config, - unit.Session.Handlers, - server.URL+"/path/to/endpoint?something=else", - ) - creds, err := client.Retrieve() - - assert.NoError(t, err) - - assert.Equal(t, "AKID", creds.AccessKeyID) - assert.Equal(t, "SECRET", creds.SecretAccessKey) - assert.Equal(t, "TOKEN", creds.SessionToken) - assert.False(t, client.IsExpired()) - - client.(*endpointcreds.Provider).CurrentTime = func() time.Time { - return time.Now().Add(2 * time.Hour) - } - - assert.True(t, client.IsExpired()) -} - -func TestRetrieveStaticCredentials(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - encoder := json.NewEncoder(w) - err := encoder.Encode(map[string]interface{}{ - "AccessKeyID": "AKID", - "SecretAccessKey": "SECRET", - }) - - if err != nil { - fmt.Println("failed to write out creds", err) - } - })) - - client := endpointcreds.NewProviderClient(*unit.Session.Config, unit.Session.Handlers, server.URL) - creds, err := client.Retrieve() - - assert.NoError(t, err) - - assert.Equal(t, "AKID", creds.AccessKeyID) - assert.Equal(t, "SECRET", creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.False(t, client.IsExpired()) -} - -func TestFailedRetrieveCredentials(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(400) - encoder := json.NewEncoder(w) - err := encoder.Encode(map[string]interface{}{ - "Code": "Error", - "Message": "Message", - }) - - if err != nil { - fmt.Println("failed to write error", err) - } - })) - - client := endpointcreds.NewProviderClient(*unit.Session.Config, unit.Session.Handlers, server.URL) - creds, err := client.Retrieve() - - assert.Error(t, err) - aerr := err.(awserr.Error) - - assert.Equal(t, "CredentialsEndpointError", aerr.Code()) - assert.Equal(t, "failed to load credentials", aerr.Message()) - - aerr = aerr.OrigErr().(awserr.Error) - assert.Equal(t, "Error", aerr.Code()) - assert.Equal(t, "Message", aerr.Message()) - - assert.Empty(t, creds.AccessKeyID) - assert.Empty(t, creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.True(t, client.IsExpired()) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider_test.go deleted file mode 100644 index 53f6ce25..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package credentials - -import ( - "github.com/stretchr/testify/assert" - "os" - "testing" -) - -func TestEnvProviderRetrieve(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_ACCESS_KEY_ID", "access") - os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") - os.Setenv("AWS_SESSION_TOKEN", "token") - - e := EnvProvider{} - creds, err := e.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "access", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") -} - -func TestEnvProviderIsExpired(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_ACCESS_KEY_ID", "access") - os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") - os.Setenv("AWS_SESSION_TOKEN", "token") - - e := EnvProvider{} - - assert.True(t, e.IsExpired(), "Expect creds to be expired before retrieve.") - - _, err := e.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.False(t, e.IsExpired(), "Expect creds to not be expired after retrieve.") -} - -func TestEnvProviderNoAccessKeyID(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") - - e := EnvProvider{} - creds, err := e.Retrieve() - assert.Equal(t, ErrAccessKeyIDNotFound, err, "ErrAccessKeyIDNotFound expected, but was %#v error: %#v", creds, err) -} - -func TestEnvProviderNoSecretAccessKey(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_ACCESS_KEY_ID", "access") - - e := EnvProvider{} - creds, err := e.Retrieve() - assert.Equal(t, ErrSecretAccessKeyNotFound, err, "ErrSecretAccessKeyNotFound expected, but was %#v error: %#v", creds, err) -} - -func TestEnvProviderAlternateNames(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_ACCESS_KEY", "access") - os.Setenv("AWS_SECRET_KEY", "secret") - - e := EnvProvider{} - creds, err := e.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "access", creds.AccessKeyID, "Expected access key ID") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expected secret access key") - assert.Empty(t, creds.SessionToken, "Expected no token") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini b/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini deleted file mode 100644 index 7fc91d9d..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini +++ /dev/null @@ -1,12 +0,0 @@ -[default] -aws_access_key_id = accessKey -aws_secret_access_key = secret -aws_session_token = token - -[no_token] -aws_access_key_id = accessKey -aws_secret_access_key = secret - -[with_colon] -aws_access_key_id: accessKey -aws_secret_access_key: secret diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go deleted file mode 100644 index 1eb45f26..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go +++ /dev/null @@ -1,136 +0,0 @@ -package credentials - -import ( - "os" - "path/filepath" - "testing" - - "github.com/aws/aws-sdk-go/internal/shareddefaults" - "github.com/stretchr/testify/assert" -) - -func TestSharedCredentialsProvider(t *testing.T) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""} - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") -} - -func TestSharedCredentialsProviderIsExpired(t *testing.T) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""} - - assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve") - - _, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve") -} - -func TestSharedCredentialsProviderWithAWS_SHARED_CREDENTIALS_FILE(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", "example.ini") - p := SharedCredentialsProvider{} - creds, err := p.Retrieve() - - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") -} - -func TestSharedCredentialsProviderWithAWS_SHARED_CREDENTIALS_FILEAbsPath(t *testing.T) { - os.Clearenv() - wd, err := os.Getwd() - assert.NoError(t, err) - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(wd, "example.ini")) - p := SharedCredentialsProvider{} - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") -} - -func TestSharedCredentialsProviderWithAWS_PROFILE(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_PROFILE", "no_token") - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""} - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect no token") -} - -func TestSharedCredentialsProviderWithoutTokenFromProfile(t *testing.T) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: "no_token"} - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect no token") -} - -func TestSharedCredentialsProviderColonInCredFile(t *testing.T) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: "with_colon"} - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect no token") -} - -func TestSharedCredentialsProvider_DefaultFilename(t *testing.T) { - os.Clearenv() - os.Setenv("USERPROFILE", "profile_dir") - os.Setenv("HOME", "home_dir") - - // default filename and profile - p := SharedCredentialsProvider{} - - filename, err := p.filename() - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if e, a := shareddefaults.SharedCredentialsFilename(), filename; e != a { - t.Errorf("expect %q filename, got %q", e, a) - } -} - -func BenchmarkSharedCredentialsProvider(b *testing.B) { - os.Clearenv() - - p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""} - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := p.Retrieve() - if err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider_test.go deleted file mode 100644 index ea012369..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package credentials - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestStaticProviderGet(t *testing.T) { - s := StaticProvider{ - Value: Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "", - }, - } - - creds, err := s.Retrieve() - assert.Nil(t, err, "Expect no error") - assert.Equal(t, "AKID", creds.AccessKeyID, "Expect access key ID to match") - assert.Equal(t, "SECRET", creds.SecretAccessKey, "Expect secret access key to match") - assert.Empty(t, creds.SessionToken, "Expect no session token") -} - -func TestStaticProviderIsExpired(t *testing.T) { - s := StaticProvider{ - Value: Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "", - }, - } - - assert.False(t, s.IsExpired(), "Expect static credentials to never expire") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go deleted file mode 100644 index 4c0212a0..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package stscreds - -import ( - "fmt" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/sts" - "github.com/stretchr/testify/assert" -) - -type stubSTS struct { - TestInput func(*sts.AssumeRoleInput) -} - -func (s *stubSTS) AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) { - if s.TestInput != nil { - s.TestInput(input) - } - expiry := time.Now().Add(60 * time.Minute) - return &sts.AssumeRoleOutput{ - Credentials: &sts.Credentials{ - // Just reflect the role arn to the provider. - AccessKeyId: input.RoleArn, - SecretAccessKey: aws.String("assumedSecretAccessKey"), - SessionToken: aws.String("assumedSessionToken"), - Expiration: &expiry, - }, - }, nil -} - -func TestAssumeRoleProvider(t *testing.T) { - stub := &stubSTS{} - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "roleARN", creds.AccessKeyID, "Expect access key ID to be reflected role ARN") - assert.Equal(t, "assumedSecretAccessKey", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "assumedSessionToken", creds.SessionToken, "Expect session token to match") -} - -func TestAssumeRoleProvider_WithTokenCode(t *testing.T) { - stub := &stubSTS{ - TestInput: func(in *sts.AssumeRoleInput) { - assert.Equal(t, "0123456789", *in.SerialNumber) - assert.Equal(t, "code", *in.TokenCode) - }, - } - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - SerialNumber: aws.String("0123456789"), - TokenCode: aws.String("code"), - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "roleARN", creds.AccessKeyID, "Expect access key ID to be reflected role ARN") - assert.Equal(t, "assumedSecretAccessKey", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "assumedSessionToken", creds.SessionToken, "Expect session token to match") -} - -func TestAssumeRoleProvider_WithTokenProvider(t *testing.T) { - stub := &stubSTS{ - TestInput: func(in *sts.AssumeRoleInput) { - assert.Equal(t, "0123456789", *in.SerialNumber) - assert.Equal(t, "code", *in.TokenCode) - }, - } - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - SerialNumber: aws.String("0123456789"), - TokenProvider: func() (string, error) { - return "code", nil - }, - } - - creds, err := p.Retrieve() - assert.Nil(t, err, "Expect no error") - - assert.Equal(t, "roleARN", creds.AccessKeyID, "Expect access key ID to be reflected role ARN") - assert.Equal(t, "assumedSecretAccessKey", creds.SecretAccessKey, "Expect secret access key to match") - assert.Equal(t, "assumedSessionToken", creds.SessionToken, "Expect session token to match") -} - -func TestAssumeRoleProvider_WithTokenProviderError(t *testing.T) { - stub := &stubSTS{ - TestInput: func(in *sts.AssumeRoleInput) { - assert.Fail(t, "API request should not of been called") - }, - } - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - SerialNumber: aws.String("0123456789"), - TokenProvider: func() (string, error) { - return "", fmt.Errorf("error occurred") - }, - } - - creds, err := p.Retrieve() - assert.Error(t, err) - - assert.Empty(t, creds.AccessKeyID) - assert.Empty(t, creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) -} - -func TestAssumeRoleProvider_MFAWithNoToken(t *testing.T) { - stub := &stubSTS{ - TestInput: func(in *sts.AssumeRoleInput) { - assert.Fail(t, "API request should not of been called") - }, - } - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - SerialNumber: aws.String("0123456789"), - } - - creds, err := p.Retrieve() - assert.Error(t, err) - - assert.Empty(t, creds.AccessKeyID) - assert.Empty(t, creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) -} - -func BenchmarkAssumeRoleProvider(b *testing.B) { - stub := &stubSTS{} - p := &AssumeRoleProvider{ - Client: stub, - RoleARN: "roleARN", - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := p.Retrieve(); err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/enable_test.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/enable_test.go deleted file mode 100644 index a7504d3f..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/csm/enable_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package csm - -import ( - "encoding/json" - "fmt" - "net" - "testing" -) - -func startUDPServer(done chan struct{}, fn func([]byte)) (string, error) { - addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0") - if err != nil { - return "", err - } - - conn, err := net.ListenUDP("udp", addr) - if err != nil { - return "", err - } - - buf := make([]byte, 1024) - go func() { - defer conn.Close() - - for { - select { - case <-done: - return - default: - } - - n, _, err := conn.ReadFromUDP(buf) - fn(buf[:n]) - - if err != nil { - panic(err) - } - } - }() - - return conn.LocalAddr().String(), nil -} - -func TestDifferentParams(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Errorf("expected panic with different parameters") - } - }() - Start("clientID2", ":0") -} - -var MetricsCh = make(chan map[string]interface{}, 1) -var Done = make(chan struct{}) - -func init() { - url, err := startUDPServer(Done, func(b []byte) { - m := map[string]interface{}{} - if err := json.Unmarshal(b, &m); err != nil { - panic(fmt.Sprintf("expected no error, but received %v", err)) - } - - MetricsCh <- m - }) - - if err != nil { - panic(err) - } - - _, err = Start("clientID", url) - if err != nil { - panic(err) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/example_test.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/example_test.go deleted file mode 100644 index 3da43dcc..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/csm/example_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package csm_test - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/csm" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" -) - -func ExampleStart() { - r, err := csm.Start("clientID", ":31000") - if err != nil { - panic(fmt.Errorf("failed starting CSM: %v", err)) - } - - sess, err := session.NewSession(&aws.Config{}) - if err != nil { - panic(fmt.Errorf("failed loading session: %v", err)) - } - - r.InjectHandlers(&sess.Handlers) - - client := s3.New(sess) - client.GetObject(&s3.GetObjectInput{ - Bucket: aws.String("bucket"), - Key: aws.String("key"), - }) - - // Pauses monitoring - r.Pause() - client.GetObject(&s3.GetObjectInput{ - Bucket: aws.String("bucket"), - Key: aws.String("key"), - }) - - // Resume monitoring - r.Continue() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/metricChan_test.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/metricChan_test.go deleted file mode 100644 index 81bdb25c..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/csm/metricChan_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package csm - -import ( - "testing" -) - -func TestMetricChanPush(t *testing.T) { - ch := newMetricChan(5) - defer close(ch.ch) - - pushed := ch.Push(metric{}) - if !pushed { - t.Errorf("expected metrics to be pushed") - } - - if e, a := 1, len(ch.ch); e != a { - t.Errorf("expected %d, but received %d", e, a) - } -} - -func TestMetricChanPauseContinue(t *testing.T) { - ch := newMetricChan(5) - defer close(ch.ch) - ch.Pause() - - if !ch.IsPaused() { - t.Errorf("expected to be paused, but did not pause properly") - } - - ch.Continue() - if ch.IsPaused() { - t.Errorf("expected to be not paused, but did not continue properly") - } - - pushed := ch.Push(metric{}) - if !pushed { - t.Errorf("expected metrics to be pushed") - } - - if e, a := 1, len(ch.ch); e != a { - t.Errorf("expected %d, but received %d", e, a) - } -} - -func TestMetricChanPushWhenPaused(t *testing.T) { - ch := newMetricChan(5) - defer close(ch.ch) - ch.Pause() - - pushed := ch.Push(metric{}) - if pushed { - t.Errorf("expected metrics to not be pushed") - } - - if e, a := 0, len(ch.ch); e != a { - t.Errorf("expected %d, but received %d", e, a) - } -} - -func TestMetricChanNonBlocking(t *testing.T) { - ch := newMetricChan(0) - defer close(ch.ch) - - pushed := ch.Push(metric{}) - if pushed { - t.Errorf("expected metrics to be not pushed") - } - - if e, a := 0, len(ch.ch); e != a { - t.Errorf("expected %d, but received %d", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter_test.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter_test.go deleted file mode 100644 index 7e93479f..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter_test.go +++ /dev/null @@ -1,233 +0,0 @@ -package csm_test - -import ( - "fmt" - "net" - "net/http" - "net/http/httptest" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/csm" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" -) - -func startUDPServer(done chan struct{}, fn func([]byte)) (string, error) { - addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0") - if err != nil { - return "", err - } - - conn, err := net.ListenUDP("udp", addr) - if err != nil { - return "", err - } - - buf := make([]byte, 1024) - i := 0 - go func() { - defer conn.Close() - for { - i++ - select { - case <-done: - return - default: - } - - n, _, err := conn.ReadFromUDP(buf) - fn(buf[:n]) - - if err != nil { - panic(err) - } - } - }() - - return conn.LocalAddr().String(), nil -} - -func TestReportingMetrics(t *testing.T) { - reporter := csm.Get() - if reporter == nil { - t.Errorf("expected non-nil reporter") - } - - sess := session.New() - sess.Handlers.Clear() - reporter.InjectHandlers(&sess.Handlers) - - md := metadata.ClientInfo{} - op := &request.Operation{} - r := request.New(*sess.Config, md, sess.Handlers, client.DefaultRetryer{NumMaxRetries: 0}, op, nil, nil) - sess.Handlers.Complete.Run(r) - m := <-csm.MetricsCh - - for k, v := range m { - switch k { - case "Timestamp": - if _, ok := v.(float64); !ok { - t.Errorf("expected a float value, but received %T", v) - } - case "Type": - if e, a := "ApiCall", v.(string); e != a { - t.Errorf("expected %q, but received %q", e, a) - } - } - } -} - -type mockService struct { - *client.Client -} - -type input struct{} -type output struct{} - -func (s *mockService) Request(i input) *request.Request { - op := &request.Operation{ - Name: "foo", - HTTPMethod: "POST", - HTTPPath: "/", - } - - o := output{} - req := s.NewRequest(op, &i, &o) - return req -} - -func BenchmarkWithCSM(b *testing.B) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(fmt.Sprintf("{}"))) - })) - - cfg := aws.Config{ - Endpoint: aws.String(server.URL), - } - - sess := session.New(&cfg) - r := csm.Get() - - r.InjectHandlers(&sess.Handlers) - - c := sess.ClientConfig("id", &cfg) - - svc := mockService{ - client.New( - *c.Config, - metadata.ClientInfo{ - ServiceName: "service", - ServiceID: "id", - SigningName: "signing", - SigningRegion: "region", - Endpoint: server.URL, - APIVersion: "0", - JSONVersion: "1.1", - TargetPrefix: "prefix", - }, - c.Handlers, - ), - } - - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) - - for i := 0; i < b.N; i++ { - req := svc.Request(input{}) - req.Send() - } -} - -func BenchmarkWithCSMNoUDPConnection(b *testing.B) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(fmt.Sprintf("{}"))) - })) - - cfg := aws.Config{ - Endpoint: aws.String(server.URL), - } - - sess := session.New(&cfg) - r := csm.Get() - r.Pause() - r.InjectHandlers(&sess.Handlers) - defer r.Pause() - - c := sess.ClientConfig("id", &cfg) - - svc := mockService{ - client.New( - *c.Config, - metadata.ClientInfo{ - ServiceName: "service", - ServiceID: "id", - SigningName: "signing", - SigningRegion: "region", - Endpoint: server.URL, - APIVersion: "0", - JSONVersion: "1.1", - TargetPrefix: "prefix", - }, - c.Handlers, - ), - } - - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) - - for i := 0; i < b.N; i++ { - req := svc.Request(input{}) - req.Send() - } -} - -func BenchmarkWithoutCSM(b *testing.B) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(fmt.Sprintf("{}"))) - })) - - cfg := aws.Config{ - Endpoint: aws.String(server.URL), - } - sess := session.New(&cfg) - c := sess.ClientConfig("id", &cfg) - - svc := mockService{ - client.New( - *c.Config, - metadata.ClientInfo{ - ServiceName: "service", - ServiceID: "id", - SigningName: "signing", - SigningRegion: "region", - Endpoint: server.URL, - APIVersion: "0", - JSONVersion: "1.1", - TargetPrefix: "prefix", - }, - c.Handlers, - ), - } - - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) - - for i := 0; i < b.N; i++ { - req := svc.Request(input{}) - req.Send() - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults_test.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults_test.go deleted file mode 100644 index cb064683..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package defaults - -import ( - "fmt" - "os" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds" - "github.com/aws/aws-sdk-go/aws/request" -) - -func TestHTTPCredProvider(t *testing.T) { - origFn := lookupHostFn - defer func() { lookupHostFn = origFn }() - - lookupHostFn = func(host string) ([]string, error) { - m := map[string]struct { - Addrs []string - Err error - }{ - "localhost": {Addrs: []string{"::1", "127.0.0.1"}}, - "actuallylocal": {Addrs: []string{"127.0.0.2"}}, - "notlocal": {Addrs: []string{"::1", "127.0.0.1", "192.168.1.10"}}, - "www.example.com": {Addrs: []string{"10.10.10.10"}}, - } - - h, ok := m[host] - if !ok { - t.Fatalf("unknown host in test, %v", host) - return nil, fmt.Errorf("unknown host") - } - - return h.Addrs, h.Err - } - - cases := []struct { - Host string - Fail bool - }{ - {"localhost", false}, - {"actuallylocal", false}, - {"127.0.0.1", false}, - {"127.1.1.1", false}, - {"[::1]", false}, - {"www.example.com", true}, - {"169.254.170.2", true}, - } - - defer os.Clearenv() - - for i, c := range cases { - u := fmt.Sprintf("http://%s/abc/123", c.Host) - os.Setenv(httpProviderEnvVar, u) - - provider := RemoteCredProvider(aws.Config{}, request.Handlers{}) - if provider == nil { - t.Fatalf("%d, expect provider not to be nil, but was", i) - } - - if c.Fail { - creds, err := provider.Retrieve() - if err == nil { - t.Fatalf("%d, expect error but got none", i) - } else { - aerr := err.(awserr.Error) - if e, a := "CredentialsEndpointError", aerr.Code(); e != a { - t.Errorf("%d, expect %s error code, got %s", i, e, a) - } - } - if e, a := endpointcreds.ProviderName, creds.ProviderName; e != a { - t.Errorf("%d, expect %s provider name got %s", i, e, a) - } - } else { - httpProvider := provider.(*endpointcreds.Provider) - if e, a := u, httpProvider.Client.Endpoint; e != a { - t.Errorf("%d, expect %q endpoint, got %q", i, e, a) - } - } - } -} - -func TestECSCredProvider(t *testing.T) { - defer os.Clearenv() - os.Setenv(ecsCredsProviderEnvVar, "/abc/123") - - provider := RemoteCredProvider(aws.Config{}, request.Handlers{}) - if provider == nil { - t.Fatalf("expect provider not to be nil, but was") - } - - httpProvider := provider.(*endpointcreds.Provider) - if httpProvider == nil { - t.Fatalf("expect provider not to be nil, but was") - } - if e, a := "http://169.254.170.2/abc/123", httpProvider.Client.Endpoint; e != a { - t.Errorf("expect %q endpoint, got %q", e, a) - } -} - -func TestDefaultEC2RoleProvider(t *testing.T) { - provider := RemoteCredProvider(aws.Config{}, request.Handlers{}) - if provider == nil { - t.Fatalf("expect provider not to be nil, but was") - } - - ec2Provider := provider.(*ec2rolecreds.EC2RoleProvider) - if ec2Provider == nil { - t.Fatalf("expect provider not to be nil, but was") - } - if e, a := "http://169.254.169.254/latest", ec2Provider.Client.Endpoint; e != a { - t.Errorf("expect %q endpoint, got %q", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go deleted file mode 100644 index 7dde1fb3..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go +++ /dev/null @@ -1,289 +0,0 @@ -package ec2metadata_test - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "path" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting/unit" -) - -const instanceIdentityDocument = `{ - "devpayProductCodes" : null, - "availabilityZone" : "us-east-1d", - "privateIp" : "10.158.112.84", - "version" : "2010-08-31", - "region" : "us-east-1", - "instanceId" : "i-1234567890abcdef0", - "billingProducts" : null, - "instanceType" : "t1.micro", - "accountId" : "123456789012", - "pendingTime" : "2015-11-19T16:32:11Z", - "imageId" : "ami-5fb8c835", - "kernelId" : "aki-919dcaf8", - "ramdiskId" : null, - "architecture" : "x86_64" -}` - -const validIamInfo = `{ - "Code" : "Success", - "LastUpdated" : "2016-03-17T12:27:32Z", - "InstanceProfileArn" : "arn:aws:iam::123456789012:instance-profile/my-instance-profile", - "InstanceProfileId" : "AIPAABCDEFGHIJKLMN123" -}` - -const unsuccessfulIamInfo = `{ - "Code" : "Failed", - "LastUpdated" : "2016-03-17T12:27:32Z", - "InstanceProfileArn" : "arn:aws:iam::123456789012:instance-profile/my-instance-profile", - "InstanceProfileId" : "AIPAABCDEFGHIJKLMN123" -}` - -func initTestServer(path string, resp string) *httptest.Server { - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.RequestURI != path { - http.Error(w, "not found", http.StatusNotFound) - return - } - - w.Write([]byte(resp)) - })) -} - -func TestEndpoint(t *testing.T) { - c := ec2metadata.New(unit.Session) - op := &request.Operation{ - Name: "GetMetadata", - HTTPMethod: "GET", - HTTPPath: path.Join("/", "meta-data", "testpath"), - } - - req := c.NewRequest(op, nil, nil) - if e, a := "http://169.254.169.254/latest", req.ClientInfo.Endpoint; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "http://169.254.169.254/latest/meta-data/testpath", req.HTTPRequest.URL.String(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestGetMetadata(t *testing.T) { - server := initTestServer( - "/latest/meta-data/some/path", - "success", // real response includes suffix - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - resp, err := c.GetMetadata("some/path") - - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "success", resp; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestGetUserData(t *testing.T) { - server := initTestServer( - "/latest/user-data", - "success", // real response includes suffix - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - resp, err := c.GetUserData() - - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "success", resp; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestGetUserData_Error(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - reader := strings.NewReader(` - - - - 404 - Not Found - - -

404 - Not Found

- -`) - w.Header().Set("Content-Type", "text/html") - w.Header().Set("Content-Length", fmt.Sprintf("%d", reader.Len())) - w.WriteHeader(http.StatusNotFound) - io.Copy(w, reader) - })) - - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - resp, err := c.GetUserData() - if err == nil { - t.Errorf("expect error") - } - if len(resp) != 0 { - t.Errorf("expect empty, got %v", resp) - } - - aerr := err.(awserr.Error) - if e, a := "NotFoundError", aerr.Code(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestGetRegion(t *testing.T) { - server := initTestServer( - "/latest/meta-data/placement/availability-zone", - "us-west-2a", // real response includes suffix - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - region, err := c.Region() - - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "us-west-2", region; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestMetadataAvailable(t *testing.T) { - server := initTestServer( - "/latest/meta-data/instance-id", - "instance-id", - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - if !c.Available() { - t.Errorf("expect available") - } -} - -func TestMetadataIAMInfo_success(t *testing.T) { - server := initTestServer( - "/latest/meta-data/iam/info", - validIamInfo, - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - iamInfo, err := c.IAMInfo() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "Success", iamInfo.Code; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "arn:aws:iam::123456789012:instance-profile/my-instance-profile", iamInfo.InstanceProfileArn; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "AIPAABCDEFGHIJKLMN123", iamInfo.InstanceProfileID; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestMetadataIAMInfo_failure(t *testing.T) { - server := initTestServer( - "/latest/meta-data/iam/info", - unsuccessfulIamInfo, - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - iamInfo, err := c.IAMInfo() - if err == nil { - t.Errorf("expect error") - } - if e, a := "", iamInfo.Code; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "", iamInfo.InstanceProfileArn; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "", iamInfo.InstanceProfileID; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestMetadataNotAvailable(t *testing.T) { - c := ec2metadata.New(unit.Session) - c.Handlers.Send.Clear() - c.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: int(0), - Status: http.StatusText(int(0)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - r.Error = awserr.New("RequestError", "send request failed", nil) - r.Retryable = aws.Bool(true) // network errors are retryable - }) - - if c.Available() { - t.Errorf("expect not available") - } -} - -func TestMetadataErrorResponse(t *testing.T) { - c := ec2metadata.New(unit.Session) - c.Handlers.Send.Clear() - c.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: http.StatusBadRequest, - Status: http.StatusText(http.StatusBadRequest), - Body: ioutil.NopCloser(strings.NewReader("error message text")), - } - r.Retryable = aws.Bool(false) // network errors are retryable - }) - - data, err := c.GetMetadata("uri/path") - if len(data) != 0 { - t.Errorf("expect empty, got %v", data) - } - if e, a := "error message text", err.Error(); !strings.Contains(a, e) { - t.Errorf("expect %v to be in %v", e, a) - } -} - -func TestEC2RoleProviderInstanceIdentity(t *testing.T) { - server := initTestServer( - "/latest/dynamic/instance-identity/document", - instanceIdentityDocument, - ) - defer server.Close() - c := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + "/latest")}) - - doc, err := c.GetInstanceIdentityDocument() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := doc.AccountID, "123456789012"; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := doc.AvailabilityZone, "us-east-1d"; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := doc.Region, "us-east-1"; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service_test.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service_test.go deleted file mode 100644 index 6902e0b1..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package ec2metadata_test - -import ( - "net/http" - "net/http/httptest" - "os" - "strings" - "sync" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" -) - -func TestClientOverrideDefaultHTTPClientTimeout(t *testing.T) { - svc := ec2metadata.New(unit.Session) - - if e, a := http.DefaultClient, svc.Config.HTTPClient; e == a { - t.Errorf("expect %v, not to equal %v", e, a) - } - - if e, a := 5*time.Second, svc.Config.HTTPClient.Timeout; e != a { - t.Errorf("expect %v to be %v", e, a) - } -} - -func TestClientNotOverrideDefaultHTTPClientTimeout(t *testing.T) { - http.DefaultClient.Transport = &http.Transport{} - defer func() { - http.DefaultClient.Transport = nil - }() - - svc := ec2metadata.New(unit.Session) - - if e, a := http.DefaultClient, svc.Config.HTTPClient; e != a { - t.Errorf("expect %v, got %v", e, a) - } - - tr := svc.Config.HTTPClient.Transport.(*http.Transport) - if tr == nil { - t.Fatalf("expect transport not to be nil") - } - if tr.Dial != nil { - t.Errorf("expect dial to be nil, was not") - } -} - -func TestClientDisableOverrideDefaultHTTPClientTimeout(t *testing.T) { - svc := ec2metadata.New(unit.Session, aws.NewConfig().WithEC2MetadataDisableTimeoutOverride(true)) - - if e, a := http.DefaultClient, svc.Config.HTTPClient; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestClientOverrideDefaultHTTPClientTimeoutRace(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("us-east-1a")) - })) - - cfg := aws.NewConfig().WithEndpoint(server.URL) - runEC2MetadataClients(t, cfg, 100) -} - -func TestClientOverrideDefaultHTTPClientTimeoutRaceWithTransport(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("us-east-1a")) - })) - - cfg := aws.NewConfig().WithEndpoint(server.URL).WithHTTPClient(&http.Client{ - Transport: http.DefaultTransport, - }) - - runEC2MetadataClients(t, cfg, 100) -} - -func TestClientDisableIMDS(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("AWS_EC2_METADATA_DISABLED", "true") - - svc := ec2metadata.New(unit.Session) - resp, err := svc.Region() - if err == nil { - t.Fatalf("expect error, got none") - } - if len(resp) != 0 { - t.Errorf("expect no response, got %v", resp) - } - - aerr := err.(awserr.Error) - if e, a := request.CanceledErrorCode, aerr.Code(); e != a { - t.Errorf("expect %v error code, got %v", e, a) - } - if e, a := "AWS_EC2_METADATA_DISABLED", aerr.Message(); !strings.Contains(a, e) { - t.Errorf("expect %v in error message, got %v", e, a) - } -} - -func runEC2MetadataClients(t *testing.T, cfg *aws.Config, atOnce int) { - var wg sync.WaitGroup - wg.Add(atOnce) - for i := 0; i < atOnce; i++ { - go func() { - svc := ec2metadata.New(unit.Session, cfg) - _, err := svc.Region() - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - wg.Done() - }() - } - wg.Wait() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode_test.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode_test.go deleted file mode 100644 index 31939072..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package endpoints - -import ( - "strings" - "testing" -) - -func TestDecodeEndpoints_V3(t *testing.T) { - const v3Doc = ` -{ - "version": 3, - "partitions": [ - { - "defaults": { - "hostname": "{service}.{region}.{dnsSuffix}", - "protocols": [ - "https" - ], - "signatureVersions": [ - "v4" - ] - }, - "dnsSuffix": "amazonaws.com", - "partition": "aws", - "partitionName": "AWS Standard", - "regionRegex": "^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$", - "regions": { - "ap-northeast-1": { - "description": "Asia Pacific (Tokyo)" - } - }, - "services": { - "acm": { - "endpoints": { - "ap-northeast-1": {} - } - }, - "s3": { - "endpoints": { - "ap-northeast-1": {} - } - } - } - } - ] -}` - - resolver, err := DecodeModel(strings.NewReader(v3Doc)) - if err != nil { - t.Fatalf("expected no error, got %v", err) - } - - endpoint, err := resolver.EndpointFor("acm", "ap-northeast-1") - if err != nil { - t.Fatalf("failed to resolve endpoint, %v", err) - } - - if a, e := endpoint.URL, "https://acm.ap-northeast-1.amazonaws.com"; a != e { - t.Errorf("expected %q URL got %q", e, a) - } - - p := resolver.(partitions)[0] - - s3Defaults := p.Services["s3"].Defaults - if a, e := s3Defaults.HasDualStack, boxedTrue; a != e { - t.Errorf("expect s3 service to have dualstack enabled") - } - if a, e := s3Defaults.DualStackHostname, "{service}.dualstack.{region}.{dnsSuffix}"; a != e { - t.Errorf("expect s3 dualstack host pattern to be %q, got %q", e, a) - } - - ec2metaEndpoint := p.Services["ec2metadata"].Endpoints["aws-global"] - if a, e := ec2metaEndpoint.Hostname, "169.254.169.254/latest"; a != e { - t.Errorf("expect ec2metadata host to be %q, got %q", e, a) - } -} - -func TestDecodeEndpoints_NoPartitions(t *testing.T) { - const doc = `{ "version": 3 }` - - resolver, err := DecodeModel(strings.NewReader(doc)) - if err == nil { - t.Fatalf("expected error") - } - - if resolver != nil { - t.Errorf("expect resolver to be nil") - } -} - -func TestDecodeEndpoints_UnsupportedVersion(t *testing.T) { - const doc = `{ "version": 2 }` - - resolver, err := DecodeModel(strings.NewReader(doc)) - if err == nil { - t.Fatalf("expected error decoding model") - } - - if resolver != nil { - t.Errorf("expect resolver to be nil") - } -} - -func TestDecodeModelOptionsSet(t *testing.T) { - var actual DecodeModelOptions - actual.Set(func(o *DecodeModelOptions) { - o.SkipCustomizations = true - }) - - expect := DecodeModelOptions{ - SkipCustomizations: true, - } - - if actual != expect { - t.Errorf("expect %v options got %v", expect, actual) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go index c3043279..75c351d0 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go @@ -571,6 +571,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -1193,8 +1194,10 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "us-east-1": endpoint{}, @@ -1208,6 +1211,7 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "eu-west-1": endpoint{}, "us-east-1": endpoint{}, "us-west-2": endpoint{}, }, @@ -1528,6 +1532,7 @@ var awsPartition = partition{ "ap-northeast-2": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "us-east-1": endpoint{}, "us-west-2": endpoint{}, @@ -2039,6 +2044,7 @@ var awsPartition = partition{ "eu-west-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -2981,6 +2987,12 @@ var awsusgovPartition = partition{ }, }, }, + "inspector": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, "kinesis": service{ Endpoints: endpoints{ diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints_test.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints_test.go deleted file mode 100644 index de0e5302..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints_test.go +++ /dev/null @@ -1,342 +0,0 @@ -package endpoints - -import "testing" - -func TestEnumDefaultPartitions(t *testing.T) { - resolver := DefaultResolver() - enum, ok := resolver.(EnumPartitions) - - if ok != true { - t.Fatalf("resolver must satisfy EnumPartition interface") - } - - ps := enum.Partitions() - - if a, e := len(ps), len(defaultPartitions); a != e { - t.Errorf("expected %d partitions, got %d", e, a) - } -} - -func TestEnumDefaultRegions(t *testing.T) { - expectPart := defaultPartitions[0] - partEnum := defaultPartitions[0].Partition() - - regEnum := partEnum.Regions() - - if a, e := len(regEnum), len(expectPart.Regions); a != e { - t.Errorf("expected %d regions, got %d", e, a) - } -} - -func TestEnumPartitionServices(t *testing.T) { - expectPart := testPartitions[0] - partEnum := testPartitions[0].Partition() - - if a, e := partEnum.ID(), "part-id"; a != e { - t.Errorf("expect %q partition ID, got %q", e, a) - } - - svcEnum := partEnum.Services() - - if a, e := len(svcEnum), len(expectPart.Services); a != e { - t.Errorf("expected %d regions, got %d", e, a) - } -} - -func TestEnumRegionServices(t *testing.T) { - p := testPartitions[0].Partition() - - rs := p.Regions() - - if a, e := len(rs), 2; a != e { - t.Errorf("expect %d regions got %d", e, a) - } - - if _, ok := rs["us-east-1"]; !ok { - t.Errorf("expect us-east-1 region to be found, was not") - } - if _, ok := rs["us-west-2"]; !ok { - t.Errorf("expect us-west-2 region to be found, was not") - } - - r := rs["us-east-1"] - - if a, e := r.ID(), "us-east-1"; a != e { - t.Errorf("expect %q region ID, got %q", e, a) - } - - if a, e := r.Description(), "region description"; a != e { - t.Errorf("expect %q region Description, got %q", e, a) - } - - ss := r.Services() - if a, e := len(ss), 1; a != e { - t.Errorf("expect %d services for us-east-1, got %d", e, a) - } - - if _, ok := ss["service1"]; !ok { - t.Errorf("expect service1 service to be found, was not") - } - - resolved, err := r.ResolveEndpoint("service1") - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if a, e := resolved.URL, "https://service1.us-east-1.amazonaws.com"; a != e { - t.Errorf("expect %q resolved URL, got %q", e, a) - } -} - -func TestEnumServiceRegions(t *testing.T) { - p := testPartitions[0].Partition() - - rs := p.Services()["service1"].Regions() - if e, a := 2, len(rs); e != a { - t.Errorf("expect %d regions, got %d", e, a) - } - - if _, ok := rs["us-east-1"]; !ok { - t.Errorf("expect region to be found") - } - if _, ok := rs["us-west-2"]; !ok { - t.Errorf("expect region to be found") - } -} - -func TestEnumServicesEndpoints(t *testing.T) { - p := testPartitions[0].Partition() - - ss := p.Services() - - if a, e := len(ss), 5; a != e { - t.Errorf("expect %d regions got %d", e, a) - } - - if _, ok := ss["service1"]; !ok { - t.Errorf("expect service1 region to be found, was not") - } - if _, ok := ss["service2"]; !ok { - t.Errorf("expect service2 region to be found, was not") - } - - s := ss["service1"] - if a, e := s.ID(), "service1"; a != e { - t.Errorf("expect %q service ID, got %q", e, a) - } - - resolved, err := s.ResolveEndpoint("us-west-2") - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if a, e := resolved.URL, "https://service1.us-west-2.amazonaws.com"; a != e { - t.Errorf("expect %q resolved URL, got %q", e, a) - } -} - -func TestEnumEndpoints(t *testing.T) { - p := testPartitions[0].Partition() - s := p.Services()["service1"] - - es := s.Endpoints() - if a, e := len(es), 2; a != e { - t.Errorf("expect %d endpoints for service2, got %d", e, a) - } - if _, ok := es["us-east-1"]; !ok { - t.Errorf("expect us-east-1 to be found, was not") - } - - e := es["us-east-1"] - if a, e := e.ID(), "us-east-1"; a != e { - t.Errorf("expect %q endpoint ID, got %q", e, a) - } - if a, e := e.ServiceID(), "service1"; a != e { - t.Errorf("expect %q service ID, got %q", e, a) - } - - resolved, err := e.ResolveEndpoint() - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if a, e := resolved.URL, "https://service1.us-east-1.amazonaws.com"; a != e { - t.Errorf("expect %q resolved URL, got %q", e, a) - } -} - -func TestResolveEndpointForPartition(t *testing.T) { - enum := testPartitions.Partitions()[0] - - expected, err := testPartitions.EndpointFor("service1", "us-east-1") - - actual, err := enum.EndpointFor("service1", "us-east-1") - if err != nil { - t.Fatalf("unexpected error, %v", err) - } - - if expected != actual { - t.Errorf("expect resolved endpoint to be %v, but got %v", expected, actual) - } -} - -func TestAddScheme(t *testing.T) { - cases := []struct { - In string - Expect string - DisableSSL bool - }{ - { - In: "https://example.com", - Expect: "https://example.com", - }, - { - In: "example.com", - Expect: "https://example.com", - }, - { - In: "http://example.com", - Expect: "http://example.com", - }, - { - In: "example.com", - Expect: "http://example.com", - DisableSSL: true, - }, - { - In: "https://example.com", - Expect: "https://example.com", - DisableSSL: true, - }, - } - - for i, c := range cases { - actual := AddScheme(c.In, c.DisableSSL) - if actual != c.Expect { - t.Errorf("%d, expect URL to be %q, got %q", i, c.Expect, actual) - } - } -} - -func TestResolverFunc(t *testing.T) { - var resolver Resolver - - resolver = ResolverFunc(func(s, r string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return ResolvedEndpoint{ - URL: "https://service.region.dnssuffix.com", - SigningRegion: "region", - SigningName: "service", - }, nil - }) - - resolved, err := resolver.EndpointFor("service", "region", func(o *Options) { - o.DisableSSL = true - }) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if a, e := resolved.URL, "https://service.region.dnssuffix.com"; a != e { - t.Errorf("expect %q endpoint URL, got %q", e, a) - } - - if a, e := resolved.SigningRegion, "region"; a != e { - t.Errorf("expect %q region, got %q", e, a) - } - if a, e := resolved.SigningName, "service"; a != e { - t.Errorf("expect %q signing name, got %q", e, a) - } -} - -func TestOptionsSet(t *testing.T) { - var actual Options - actual.Set(DisableSSLOption, UseDualStackOption, StrictMatchingOption) - - expect := Options{ - DisableSSL: true, - UseDualStack: true, - StrictMatching: true, - } - - if actual != expect { - t.Errorf("expect %v options got %v", expect, actual) - } -} - -func TestRegionsForService(t *testing.T) { - ps := DefaultPartitions() - - var expect map[string]Region - var serviceID string - for _, s := range ps[0].Services() { - expect = s.Regions() - serviceID = s.ID() - if len(expect) > 0 { - break - } - } - - actual, ok := RegionsForService(ps, ps[0].ID(), serviceID) - if !ok { - t.Fatalf("expect regions to be found, was not") - } - - if len(actual) == 0 { - t.Fatalf("expect service %s to have regions", serviceID) - } - if e, a := len(expect), len(actual); e != a { - t.Fatalf("expect %d regions, got %d", e, a) - } - - for id, r := range actual { - if e, a := id, r.ID(); e != a { - t.Errorf("expect %s region id, got %s", e, a) - } - if _, ok := expect[id]; !ok { - t.Errorf("expect %s region to be found", id) - } - if a, e := r.Description(), expect[id].desc; a != e { - t.Errorf("expect %q region Description, got %q", e, a) - } - } -} - -func TestRegionsForService_NotFound(t *testing.T) { - ps := testPartitions.Partitions() - - actual, ok := RegionsForService(ps, ps[0].ID(), "service-not-exists") - if ok { - t.Fatalf("expect no regions to be found, but were") - } - if len(actual) != 0 { - t.Errorf("expect no regions, got %v", actual) - } -} - -func TestPartitionForRegion(t *testing.T) { - ps := DefaultPartitions() - expect := ps[len(ps)%2] - - var regionID string - for id := range expect.Regions() { - regionID = id - break - } - - actual, ok := PartitionForRegion(ps, regionID) - if !ok { - t.Fatalf("expect partition to be found") - } - if e, a := expect.ID(), actual.ID(); e != a { - t.Errorf("expect %s partition, got %s", e, a) - } -} - -func TestPartitionForRegion_NotFound(t *testing.T) { - ps := DefaultPartitions() - - actual, ok := PartitionForRegion(ps, "regionNotExists") - if ok { - t.Errorf("expect no partition to be found, got %v", actual) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/example_test.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/example_test.go deleted file mode 100644 index 007fed2f..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/example_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package endpoints_test - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/sqs" -) - -func ExampleEnumPartitions() { - resolver := endpoints.DefaultResolver() - partitions := resolver.(endpoints.EnumPartitions).Partitions() - - for _, p := range partitions { - fmt.Println("Regions for", p.ID()) - for id := range p.Regions() { - fmt.Println("*", id) - } - - fmt.Println("Services for", p.ID()) - for id := range p.Services() { - fmt.Println("*", id) - } - } -} - -func ExampleResolverFunc() { - myCustomResolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { - if service == endpoints.S3ServiceID { - return endpoints.ResolvedEndpoint{ - URL: "s3.custom.endpoint.com", - SigningRegion: "custom-signing-region", - }, nil - } - - return endpoints.DefaultResolver().EndpointFor(service, region, optFns...) - } - - sess := session.Must(session.NewSession(&aws.Config{ - Region: aws.String("us-west-2"), - EndpointResolver: endpoints.ResolverFunc(myCustomResolver), - })) - - // Create the S3 service client with the shared session. This will - // automatically use the S3 custom endpoint configured in the custom - // endpoint resolver wrapping the default endpoint resolver. - s3Svc := s3.New(sess) - // Operation calls will be made to the custom endpoint. - s3Svc.GetObject(&s3.GetObjectInput{ - Bucket: aws.String("myBucket"), - Key: aws.String("myObjectKey"), - }) - - // Create the SQS service client with the shared session. This will - // fallback to the default endpoint resolver because the customization - // passes any non S3 service endpoint resolve to the default resolver. - sqsSvc := sqs.New(sess) - // Operation calls will be made to the default endpoint for SQS for the - // region configured. - sqsSvc.ReceiveMessage(&sqs.ReceiveMessageInput{ - QueueUrl: aws.String("my-queue-url"), - }) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_test.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_test.go deleted file mode 100644 index 0b8b0067..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_test.go +++ /dev/null @@ -1,541 +0,0 @@ -package endpoints - -import ( - "encoding/json" - "reflect" - "regexp" - "testing" -) - -func TestUnmarshalRegionRegex(t *testing.T) { - var input = []byte(` -{ - "regionRegex": "^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$" -}`) - - p := partition{} - err := json.Unmarshal(input, &p) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - expectRegexp, err := regexp.Compile(`^(us|eu|ap|sa|ca)\-\w+\-\d+$`) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if e, a := expectRegexp.String(), p.RegionRegex.Regexp.String(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestUnmarshalRegion(t *testing.T) { - var input = []byte(` -{ - "aws-global": { - "description": "AWS partition-global endpoint" - }, - "us-east-1": { - "description": "US East (N. Virginia)" - } -}`) - - rs := regions{} - err := json.Unmarshal(input, &rs) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if e, a := 2, len(rs); e != a { - t.Errorf("expect %v len, got %v", e, a) - } - r, ok := rs["aws-global"] - if !ok { - t.Errorf("expect found, was not") - } - if e, a := "AWS partition-global endpoint", r.Description; e != a { - t.Errorf("expect %v, got %v", e, a) - } - - r, ok = rs["us-east-1"] - if !ok { - t.Errorf("expect found, was not") - } - if e, a := "US East (N. Virginia)", r.Description; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestUnmarshalServices(t *testing.T) { - var input = []byte(` -{ - "acm": { - "endpoints": { - "us-east-1": {} - } - }, - "apigateway": { - "isRegionalized": true, - "endpoints": { - "us-east-1": {}, - "us-west-2": {} - } - }, - "notRegionalized": { - "isRegionalized": false, - "endpoints": { - "us-east-1": {}, - "us-west-2": {} - } - } -}`) - - ss := services{} - err := json.Unmarshal(input, &ss) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if e, a := 3, len(ss); e != a { - t.Errorf("expect %v len, got %v", e, a) - } - s, ok := ss["acm"] - if !ok { - t.Errorf("expect found, was not") - } - if e, a := 1, len(s.Endpoints); e != a { - t.Errorf("expect %v len, got %v", e, a) - } - if e, a := boxedBoolUnset, s.IsRegionalized; e != a { - t.Errorf("expect %v, got %v", e, a) - } - - s, ok = ss["apigateway"] - if !ok { - t.Errorf("expect found, was not") - } - if e, a := 2, len(s.Endpoints); e != a { - t.Errorf("expect %v len, got %v", e, a) - } - if e, a := boxedTrue, s.IsRegionalized; e != a { - t.Errorf("expect %v, got %v", e, a) - } - - s, ok = ss["notRegionalized"] - if !ok { - t.Errorf("expect found, was not") - } - if e, a := 2, len(s.Endpoints); e != a { - t.Errorf("expect %v len, got %v", e, a) - } - if e, a := boxedFalse, s.IsRegionalized; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestUnmarshalEndpoints(t *testing.T) { - var inputs = []byte(` -{ - "aws-global": { - "hostname": "cloudfront.amazonaws.com", - "protocols": [ - "http", - "https" - ], - "signatureVersions": [ "v4" ], - "credentialScope": { - "region": "us-east-1", - "service": "serviceName" - }, - "sslCommonName": "commonName" - }, - "us-east-1": {} -}`) - - es := endpoints{} - err := json.Unmarshal(inputs, &es) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if e, a := 2, len(es); e != a { - t.Errorf("expect %v len, got %v", e, a) - } - s, ok := es["aws-global"] - if !ok { - t.Errorf("expect found, was not") - } - if e, a := "cloudfront.amazonaws.com", s.Hostname; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := []string{"http", "https"}, s.Protocols; !reflect.DeepEqual(e, a) { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := []string{"v4"}, s.SignatureVersions; !reflect.DeepEqual(e, a) { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := (credentialScope{"us-east-1", "serviceName"}), s.CredentialScope; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "commonName", s.SSLCommonName; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestEndpointResolve(t *testing.T) { - defs := []endpoint{ - { - Hostname: "{service}.{region}.{dnsSuffix}", - SignatureVersions: []string{"v2"}, - SSLCommonName: "sslCommonName", - }, - { - Hostname: "other-hostname", - Protocols: []string{"http"}, - CredentialScope: credentialScope{ - Region: "signing_region", - Service: "signing_service", - }, - }, - } - - e := endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"v4"}, - SSLCommonName: "new sslCommonName", - } - - resolved := e.resolve("service", "region", "dnsSuffix", - defs, Options{}, - ) - - if e, a := "https://service.region.dnsSuffix", resolved.URL; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "signing_service", resolved.SigningName; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "signing_region", resolved.SigningRegion; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "v4", resolved.SigningMethod; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestEndpointMergeIn(t *testing.T) { - expected := endpoint{ - Hostname: "other hostname", - Protocols: []string{"http"}, - SignatureVersions: []string{"v4"}, - SSLCommonName: "ssl common name", - CredentialScope: credentialScope{ - Region: "region", - Service: "service", - }, - } - - actual := endpoint{} - actual.mergeIn(endpoint{ - Hostname: "other hostname", - Protocols: []string{"http"}, - SignatureVersions: []string{"v4"}, - SSLCommonName: "ssl common name", - CredentialScope: credentialScope{ - Region: "region", - Service: "service", - }, - }) - - if e, a := expected, actual; !reflect.DeepEqual(e, a) { - t.Errorf("expect %v, got %v", e, a) - } -} - -var testPartitions = partitions{ - partition{ - ID: "part-id", - Name: "partitionName", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "us-east-1": region{ - Description: "region description", - }, - "us-west-2": region{}, - }, - Services: services{ - "s3": service{}, - "service1": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "service1", - }, - }, - Endpoints: endpoints{ - "us-east-1": {}, - "us-west-2": { - HasDualStack: boxedTrue, - DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", - }, - }, - }, - "service2": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "service2", - }, - }, - }, - "httpService": service{ - Defaults: endpoint{ - Protocols: []string{"http"}, - }, - }, - "globalService": service{ - IsRegionalized: boxedFalse, - PartitionEndpoint: "aws-global", - Endpoints: endpoints{ - "aws-global": endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Hostname: "globalService.amazonaws.com", - }, - }, - }, - }, - }, -} - -func TestResolveEndpoint(t *testing.T) { - resolved, err := testPartitions.EndpointFor("service2", "us-west-2") - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := "https://service2.us-west-2.amazonaws.com", resolved.URL; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "us-west-2", resolved.SigningRegion; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "service2", resolved.SigningName; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if resolved.SigningNameDerived { - t.Errorf("expect the signing name not to be derived, but was") - } -} - -func TestResolveEndpoint_DisableSSL(t *testing.T) { - resolved, err := testPartitions.EndpointFor("service2", "us-west-2", DisableSSLOption) - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := "http://service2.us-west-2.amazonaws.com", resolved.URL; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "us-west-2", resolved.SigningRegion; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "service2", resolved.SigningName; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if resolved.SigningNameDerived { - t.Errorf("expect the signing name not to be derived, but was") - } -} - -func TestResolveEndpoint_UseDualStack(t *testing.T) { - resolved, err := testPartitions.EndpointFor("service1", "us-west-2", UseDualStackOption) - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := "https://service1.dualstack.us-west-2.amazonaws.com", resolved.URL; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "us-west-2", resolved.SigningRegion; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "service1", resolved.SigningName; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if resolved.SigningNameDerived { - t.Errorf("expect the signing name not to be derived, but was") - } -} - -func TestResolveEndpoint_HTTPProtocol(t *testing.T) { - resolved, err := testPartitions.EndpointFor("httpService", "us-west-2") - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := "http://httpService.us-west-2.amazonaws.com", resolved.URL; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "us-west-2", resolved.SigningRegion; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "httpService", resolved.SigningName; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if !resolved.SigningNameDerived { - t.Errorf("expect the signing name to be derived") - } -} - -func TestResolveEndpoint_UnknownService(t *testing.T) { - _, err := testPartitions.EndpointFor("unknownservice", "us-west-2") - - if err == nil { - t.Errorf("expect error, got none") - } - - _, ok := err.(UnknownServiceError) - if !ok { - t.Errorf("expect error to be UnknownServiceError") - } -} - -func TestResolveEndpoint_ResolveUnknownService(t *testing.T) { - resolved, err := testPartitions.EndpointFor("unknown-service", "us-region-1", - ResolveUnknownServiceOption) - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if e, a := "https://unknown-service.us-region-1.amazonaws.com", resolved.URL; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "us-region-1", resolved.SigningRegion; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "unknown-service", resolved.SigningName; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if !resolved.SigningNameDerived { - t.Errorf("expect the signing name to be derived") - } -} - -func TestResolveEndpoint_UnknownMatchedRegion(t *testing.T) { - resolved, err := testPartitions.EndpointFor("service2", "us-region-1") - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := "https://service2.us-region-1.amazonaws.com", resolved.URL; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "us-region-1", resolved.SigningRegion; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "service2", resolved.SigningName; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if resolved.SigningNameDerived { - t.Errorf("expect the signing name not to be derived, but was") - } -} - -func TestResolveEndpoint_UnknownRegion(t *testing.T) { - resolved, err := testPartitions.EndpointFor("service2", "unknownregion") - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := "https://service2.unknownregion.amazonaws.com", resolved.URL; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "unknownregion", resolved.SigningRegion; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "service2", resolved.SigningName; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if resolved.SigningNameDerived { - t.Errorf("expect the signing name not to be derived, but was") - } -} - -func TestResolveEndpoint_StrictPartitionUnknownEndpoint(t *testing.T) { - _, err := testPartitions[0].EndpointFor("service2", "unknownregion", StrictMatchingOption) - - if err == nil { - t.Errorf("expect error, got none") - } - - _, ok := err.(UnknownEndpointError) - if !ok { - t.Errorf("expect error to be UnknownEndpointError") - } -} - -func TestResolveEndpoint_StrictPartitionsUnknownEndpoint(t *testing.T) { - _, err := testPartitions.EndpointFor("service2", "us-region-1", StrictMatchingOption) - - if err == nil { - t.Errorf("expect error, got none") - } - - _, ok := err.(UnknownEndpointError) - if !ok { - t.Errorf("expect error to be UnknownEndpointError") - } -} - -func TestResolveEndpoint_NotRegionalized(t *testing.T) { - resolved, err := testPartitions.EndpointFor("globalService", "us-west-2") - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := "https://globalService.amazonaws.com", resolved.URL; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "us-east-1", resolved.SigningRegion; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "globalService", resolved.SigningName; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if !resolved.SigningNameDerived { - t.Errorf("expect the signing name to be derived") - } -} - -func TestResolveEndpoint_AwsGlobal(t *testing.T) { - resolved, err := testPartitions.EndpointFor("globalService", "aws-global") - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := "https://globalService.amazonaws.com", resolved.URL; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "us-east-1", resolved.SigningRegion; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "globalService", resolved.SigningName; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if !resolved.SigningNameDerived { - t.Errorf("expect the signing name to be derived") - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other_test.go deleted file mode 100644 index aba8eb4e..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other_test.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build appengine plan9 - -package request_test - -import ( - "errors" -) - -var stubConnectionResetError = errors.New("connection reset") diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_test.go deleted file mode 100644 index bb5f6bdd..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_test.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !appengine,!plan9 - -package request_test - -import ( - "net" - "os" - "syscall" -) - -var stubConnectionResetError = &net.OpError{Err: &os.SyscallError{Syscall: "read", Err: syscall.ECONNRESET}} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers_test.go deleted file mode 100644 index b2da558d..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers_test.go +++ /dev/null @@ -1,266 +0,0 @@ -package request_test - -import ( - "reflect" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/s3" -) - -func TestHandlerList(t *testing.T) { - s := "" - r := &request.Request{} - l := request.HandlerList{} - l.PushBack(func(r *request.Request) { - s += "a" - r.Data = s - }) - l.Run(r) - if e, a := "a", s; e != a { - t.Errorf("expect %q update got %q", e, a) - } - if e, a := "a", r.Data.(string); e != a { - t.Errorf("expect %q data update got %q", e, a) - } -} - -func TestMultipleHandlers(t *testing.T) { - r := &request.Request{} - l := request.HandlerList{} - l.PushBack(func(r *request.Request) { r.Data = nil }) - l.PushFront(func(r *request.Request) { r.Data = aws.Bool(true) }) - l.Run(r) - if r.Data != nil { - t.Error("Expected handler to execute") - } -} - -func TestNamedHandlers(t *testing.T) { - l := request.HandlerList{} - named := request.NamedHandler{Name: "Name", Fn: func(r *request.Request) {}} - named2 := request.NamedHandler{Name: "NotName", Fn: func(r *request.Request) {}} - l.PushBackNamed(named) - l.PushBackNamed(named) - l.PushBackNamed(named2) - l.PushBack(func(r *request.Request) {}) - if e, a := 4, l.Len(); e != a { - t.Errorf("expect %d list length, got %d", e, a) - } - l.Remove(named) - if e, a := 2, l.Len(); e != a { - t.Errorf("expect %d list length, got %d", e, a) - } -} - -func TestSwapHandlers(t *testing.T) { - firstHandlerCalled := 0 - swappedOutHandlerCalled := 0 - swappedInHandlerCalled := 0 - - l := request.HandlerList{} - named := request.NamedHandler{Name: "Name", Fn: func(r *request.Request) { - firstHandlerCalled++ - }} - named2 := request.NamedHandler{Name: "SwapOutName", Fn: func(r *request.Request) { - swappedOutHandlerCalled++ - }} - l.PushBackNamed(named) - l.PushBackNamed(named2) - l.PushBackNamed(named) - - l.SwapNamed(request.NamedHandler{Name: "SwapOutName", Fn: func(r *request.Request) { - swappedInHandlerCalled++ - }}) - - l.Run(&request.Request{}) - - if e, a := 2, firstHandlerCalled; e != a { - t.Errorf("expect first handler to be called %d, was called %d times", e, a) - } - if n := swappedOutHandlerCalled; n != 0 { - t.Errorf("expect swapped out handler to not be called, was called %d times", n) - } - if e, a := 1, swappedInHandlerCalled; e != a { - t.Errorf("expect swapped in handler to be called %d, was called %d times", e, a) - } -} - -func TestSetBackNamed_Exists(t *testing.T) { - firstHandlerCalled := 0 - swappedOutHandlerCalled := 0 - swappedInHandlerCalled := 0 - - l := request.HandlerList{} - named := request.NamedHandler{Name: "Name", Fn: func(r *request.Request) { - firstHandlerCalled++ - }} - named2 := request.NamedHandler{Name: "SwapOutName", Fn: func(r *request.Request) { - swappedOutHandlerCalled++ - }} - l.PushBackNamed(named) - l.PushBackNamed(named2) - - l.SetBackNamed(request.NamedHandler{Name: "SwapOutName", Fn: func(r *request.Request) { - swappedInHandlerCalled++ - }}) - - l.Run(&request.Request{}) - - if e, a := 1, firstHandlerCalled; e != a { - t.Errorf("expect first handler to be called %d, was called %d times", e, a) - } - if n := swappedOutHandlerCalled; n != 0 { - t.Errorf("expect swapped out handler to not be called, was called %d times", n) - } - if e, a := 1, swappedInHandlerCalled; e != a { - t.Errorf("expect swapped in handler to be called %d, was called %d times", e, a) - } -} - -func TestSetBackNamed_NotExists(t *testing.T) { - firstHandlerCalled := 0 - secondHandlerCalled := 0 - swappedInHandlerCalled := 0 - - l := request.HandlerList{} - named := request.NamedHandler{Name: "Name", Fn: func(r *request.Request) { - firstHandlerCalled++ - }} - named2 := request.NamedHandler{Name: "OtherName", Fn: func(r *request.Request) { - secondHandlerCalled++ - }} - l.PushBackNamed(named) - l.PushBackNamed(named2) - - l.SetBackNamed(request.NamedHandler{Name: "SwapOutName", Fn: func(r *request.Request) { - swappedInHandlerCalled++ - }}) - - l.Run(&request.Request{}) - - if e, a := 1, firstHandlerCalled; e != a { - t.Errorf("expect first handler to be called %d, was called %d times", e, a) - } - if e, a := 1, secondHandlerCalled; e != a { - t.Errorf("expect second handler to be called %d, was called %d times", e, a) - } - if e, a := 1, swappedInHandlerCalled; e != a { - t.Errorf("expect swapped in handler to be called %d, was called %d times", e, a) - } -} - -func TestLoggedHandlers(t *testing.T) { - expectedHandlers := []string{"name1", "name2"} - l := request.HandlerList{} - loggedHandlers := []string{} - l.AfterEachFn = request.HandlerListLogItem - cfg := aws.Config{Logger: aws.LoggerFunc(func(args ...interface{}) { - loggedHandlers = append(loggedHandlers, args[2].(string)) - })} - - named1 := request.NamedHandler{Name: "name1", Fn: func(r *request.Request) {}} - named2 := request.NamedHandler{Name: "name2", Fn: func(r *request.Request) {}} - l.PushBackNamed(named1) - l.PushBackNamed(named2) - l.Run(&request.Request{Config: cfg}) - - if !reflect.DeepEqual(expectedHandlers, loggedHandlers) { - t.Errorf("expect handlers executed %v to match logged handlers, %v", - expectedHandlers, loggedHandlers) - } -} - -func TestStopHandlers(t *testing.T) { - l := request.HandlerList{} - stopAt := 1 - l.AfterEachFn = func(item request.HandlerListRunItem) bool { - return item.Index != stopAt - } - - called := 0 - l.PushBackNamed(request.NamedHandler{Name: "name1", Fn: func(r *request.Request) { - called++ - }}) - l.PushBackNamed(request.NamedHandler{Name: "name2", Fn: func(r *request.Request) { - called++ - }}) - l.PushBackNamed(request.NamedHandler{Name: "name3", Fn: func(r *request.Request) { - t.Fatalf("third handler should not be called") - }}) - l.Run(&request.Request{}) - - if e, a := 2, called; e != a { - t.Errorf("expect %d handlers called, got %d", e, a) - } -} - -func BenchmarkNewRequest(b *testing.B) { - svc := s3.New(unit.Session) - - for i := 0; i < b.N; i++ { - r, _ := svc.GetObjectRequest(nil) - if r == nil { - b.Fatal("r should not be nil") - } - } -} - -func BenchmarkHandlersCopy(b *testing.B) { - handlers := request.Handlers{} - - handlers.Validate.PushBack(func(r *request.Request) {}) - handlers.Validate.PushBack(func(r *request.Request) {}) - handlers.Build.PushBack(func(r *request.Request) {}) - handlers.Build.PushBack(func(r *request.Request) {}) - handlers.Send.PushBack(func(r *request.Request) {}) - handlers.Send.PushBack(func(r *request.Request) {}) - handlers.Unmarshal.PushBack(func(r *request.Request) {}) - handlers.Unmarshal.PushBack(func(r *request.Request) {}) - - for i := 0; i < b.N; i++ { - h := handlers.Copy() - if e, a := handlers.Validate.Len(), h.Validate.Len(); e != a { - b.Fatalf("expected %d handlers got %d", e, a) - } - } -} - -func BenchmarkHandlersPushBack(b *testing.B) { - handlers := request.Handlers{} - - for i := 0; i < b.N; i++ { - h := handlers.Copy() - h.Validate.PushBack(func(r *request.Request) {}) - h.Validate.PushBack(func(r *request.Request) {}) - h.Validate.PushBack(func(r *request.Request) {}) - h.Validate.PushBack(func(r *request.Request) {}) - } -} - -func BenchmarkHandlersPushFront(b *testing.B) { - handlers := request.Handlers{} - - for i := 0; i < b.N; i++ { - h := handlers.Copy() - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - } -} - -func BenchmarkHandlersClear(b *testing.B) { - handlers := request.Handlers{} - - for i := 0; i < b.N; i++ { - h := handlers.Copy() - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - h.Validate.PushFront(func(r *request.Request) {}) - h.Clear() - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_copy_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_copy_test.go deleted file mode 100644 index 4a4f8550..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_copy_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package request - -import ( - "bytes" - "io/ioutil" - "net/http" - "net/url" - "sync" - "testing" -) - -func TestRequestCopyRace(t *testing.T) { - origReq := &http.Request{URL: &url.URL{}, Header: http.Header{}} - origReq.Header.Set("Header", "OrigValue") - - var wg sync.WaitGroup - for i := 0; i < 100; i++ { - wg.Add(1) - go func() { - req := copyHTTPRequest(origReq, ioutil.NopCloser(&bytes.Buffer{})) - req.Header.Set("Header", "Value") - go func() { - req2 := copyHTTPRequest(req, ioutil.NopCloser(&bytes.Buffer{})) - req2.Header.Add("Header", "Value2") - }() - _ = req.Header.Get("Header") - wg.Done() - }() - _ = origReq.Header.Get("Header") - } - origReq.Header.Get("Header") - - wg.Wait() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_retry_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_retry_test.go deleted file mode 100644 index 2ce9ef4c..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request_retry_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// +build go1.5 - -package request_test - -import ( - "errors" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting/mock" - "github.com/stretchr/testify/assert" -) - -func TestRequestCancelRetry(t *testing.T) { - c := make(chan struct{}) - - reqNum := 0 - s := mock.NewMockClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.Clear() - s.Handlers.UnmarshalMeta.Clear() - s.Handlers.UnmarshalError.Clear() - s.Handlers.Send.PushFront(func(r *request.Request) { - reqNum++ - r.Error = errors.New("net/http: request canceled") - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - r.HTTPRequest.Cancel = c - close(c) - - err := r.Send() - assert.True(t, strings.Contains(err.Error(), "canceled")) - assert.Equal(t, 1, reqNum) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader_test.go deleted file mode 100644 index e5ec043b..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader_test.go +++ /dev/null @@ -1,140 +0,0 @@ -package request - -import ( - "bytes" - "io" - "math/rand" - "sync" - "testing" - "time" - - "github.com/aws/aws-sdk-go/internal/sdkio" - "github.com/stretchr/testify/assert" -) - -func TestOffsetReaderRead(t *testing.T) { - buf := []byte("testData") - reader := &offsetReader{buf: bytes.NewReader(buf)} - - tempBuf := make([]byte, len(buf)) - - n, err := reader.Read(tempBuf) - - assert.Equal(t, n, len(buf)) - assert.Nil(t, err) - assert.Equal(t, buf, tempBuf) -} - -func TestOffsetReaderSeek(t *testing.T) { - buf := []byte("testData") - reader := newOffsetReader(bytes.NewReader(buf), 0) - - orig, err := reader.Seek(0, sdkio.SeekCurrent) - assert.NoError(t, err) - assert.Equal(t, int64(0), orig) - - n, err := reader.Seek(0, sdkio.SeekEnd) - assert.NoError(t, err) - assert.Equal(t, int64(len(buf)), n) - - n, err = reader.Seek(orig, sdkio.SeekStart) - assert.NoError(t, err) - assert.Equal(t, int64(0), n) -} - -func TestOffsetReaderClose(t *testing.T) { - buf := []byte("testData") - reader := &offsetReader{buf: bytes.NewReader(buf)} - - err := reader.Close() - assert.Nil(t, err) - - tempBuf := make([]byte, len(buf)) - n, err := reader.Read(tempBuf) - assert.Equal(t, n, 0) - assert.Equal(t, err, io.EOF) -} - -func TestOffsetReaderCloseAndCopy(t *testing.T) { - buf := []byte("testData") - tempBuf := make([]byte, len(buf)) - reader := &offsetReader{buf: bytes.NewReader(buf)} - - newReader := reader.CloseAndCopy(0) - - n, err := reader.Read(tempBuf) - assert.Equal(t, n, 0) - assert.Equal(t, err, io.EOF) - - n, err = newReader.Read(tempBuf) - assert.Equal(t, n, len(buf)) - assert.Nil(t, err) - assert.Equal(t, buf, tempBuf) -} - -func TestOffsetReaderCloseAndCopyOffset(t *testing.T) { - buf := []byte("testData") - tempBuf := make([]byte, len(buf)) - reader := &offsetReader{buf: bytes.NewReader(buf)} - - newReader := reader.CloseAndCopy(4) - n, err := newReader.Read(tempBuf) - assert.Equal(t, n, len(buf)-4) - assert.Nil(t, err) - - expected := []byte{'D', 'a', 't', 'a', 0, 0, 0, 0} - assert.Equal(t, expected, tempBuf) -} - -func TestOffsetReaderRace(t *testing.T) { - wg := sync.WaitGroup{} - - f := func(reader *offsetReader) { - defer wg.Done() - var err error - buf := make([]byte, 1) - _, err = reader.Read(buf) - for err != io.EOF { - _, err = reader.Read(buf) - } - - } - - closeFn := func(reader *offsetReader) { - defer wg.Done() - time.Sleep(time.Duration(rand.Intn(20)+1) * time.Millisecond) - reader.Close() - } - for i := 0; i < 50; i++ { - reader := &offsetReader{buf: bytes.NewReader(make([]byte, 1024*1024))} - wg.Add(1) - go f(reader) - wg.Add(1) - go closeFn(reader) - } - wg.Wait() -} - -func BenchmarkOffsetReader(b *testing.B) { - bufSize := 1024 * 1024 * 100 - buf := make([]byte, bufSize) - reader := &offsetReader{buf: bytes.NewReader(buf)} - - tempBuf := make([]byte, 1024) - - for i := 0; i < b.N; i++ { - reader.Read(tempBuf) - } -} - -func BenchmarkBytesReader(b *testing.B) { - bufSize := 1024 * 1024 * 100 - buf := make([]byte, bufSize) - reader := bytes.NewReader(buf) - - tempBuf := make([]byte, 1024) - - for i := 0; i < b.N; i++ { - reader.Read(tempBuf) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_5_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_5_test.go deleted file mode 100644 index 91b4e7b3..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_5_test.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !go1.6 - -package request_test - -import ( - "errors" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var errTimeout = awserr.New("foo", "bar", errors.New("net/http: request canceled Timeout")) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_6_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_6_test.go deleted file mode 100644 index d0314abe..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_6_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build go1.6 - -package request_test - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/request" -) - -// go version 1.4 and 1.5 do not return an error. Version 1.5 will url encode -// the uri while 1.4 will not -func TestRequestInvalidEndpoint(t *testing.T) { - endpoint := "http://localhost:90 " - - r := request.New( - aws.Config{}, - metadata.ClientInfo{Endpoint: endpoint}, - defaults.Handlers(), - client.DefaultRetryer{}, - &request.Operation{}, - nil, - nil, - ) - - assert.Error(t, r.Error) -} - -type timeoutErr struct { - error -} - -var errTimeout = awserr.New("foo", "bar", &timeoutErr{ - errors.New("net/http: request canceled"), -}) - -func (e *timeoutErr) Timeout() bool { - return true -} - -func (e *timeoutErr) Temporary() bool { - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7_test.go deleted file mode 100644 index ca6150cb..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7_test.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build !go1.8 - -package request - -import ( - "net/http" - "strings" - "testing" -) - -func TestResetBody_WithEmptyBody(t *testing.T) { - r := Request{ - HTTPRequest: &http.Request{}, - } - - reader := strings.NewReader("") - r.Body = reader - - r.ResetBody() - - if a, e := r.HTTPRequest.Body, (noBody{}); a != e { - t.Errorf("expected request body to be set to reader, got %#v", r.HTTPRequest.Body) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8_test.go deleted file mode 100644 index 8f3b0f04..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// +build go1.8 - -package request_test - -import ( - "bytes" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" -) - -func TestResetBody_WithEmptyBody(t *testing.T) { - r := request.Request{ - HTTPRequest: &http.Request{}, - } - - reader := strings.NewReader("") - r.Body = reader - - r.ResetBody() - - if a, e := r.HTTPRequest.Body, http.NoBody; a != e { - t.Errorf("expected request body to be set to reader, got %#v", - r.HTTPRequest.Body) - } -} - -func TestRequest_FollowPUTRedirects(t *testing.T) { - const bodySize = 1024 - - redirectHit := 0 - endpointHit := 0 - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/redirect-me": - u := *r.URL - u.Path = "/endpoint" - w.Header().Set("Location", u.String()) - w.WriteHeader(307) - redirectHit++ - case "/endpoint": - b := bytes.Buffer{} - io.Copy(&b, r.Body) - r.Body.Close() - if e, a := bodySize, b.Len(); e != a { - t.Fatalf("expect %d body size, got %d", e, a) - } - endpointHit++ - default: - t.Fatalf("unexpected endpoint used, %q", r.URL.String()) - } - })) - - svc := awstesting.NewClient(&aws.Config{ - Region: unit.Session.Config.Region, - DisableSSL: aws.Bool(true), - Endpoint: aws.String(server.URL), - }) - - req := svc.NewRequest(&request.Operation{ - Name: "Operation", - HTTPMethod: "PUT", - HTTPPath: "/redirect-me", - }, &struct{}{}, &struct{}{}) - req.SetReaderBody(bytes.NewReader(make([]byte, bodySize))) - - err := req.Send() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := 1, redirectHit; e != a { - t.Errorf("expect %d redirect hits, got %d", e, a) - } - if e, a := 1, endpointHit; e != a { - t.Errorf("expect %d endpoint hits, got %d", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_test.go deleted file mode 100644 index 2af28675..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package request_test - -import ( - "fmt" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" -) - -func TestRequest_SetContext(t *testing.T) { - svc := awstesting.NewClient() - svc.Handlers.Clear() - svc.Handlers.Send.PushBackNamed(corehandlers.SendHandler) - - r := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - r.SetContext(ctx) - - ctx.Error = fmt.Errorf("context canceled") - close(ctx.DoneCh) - - err := r.Send() - if err == nil { - t.Fatalf("expected error, got none") - } - - // Only check against canceled because go 1.6 will not use the context's - // Err(). - if e, a := "canceled", err.Error(); !strings.Contains(a, e) { - t.Errorf("expect %q to be in %q, but was not", e, a) - } -} - -func TestRequest_SetContextPanic(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Fatalf("expect SetContext to panic, did not") - } - }() - r := &request.Request{} - - r.SetContext(nil) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_internal_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_internal_test.go deleted file mode 100644 index 966f9345..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_internal_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package request - -import ( - "testing" -) - -func TestCopy(t *testing.T) { - handlers := Handlers{} - op := &Operation{} - op.HTTPMethod = "Foo" - req := &Request{} - req.Operation = op - req.Handlers = handlers - - r := req.copy() - - if r == req { - t.Fatal("expect request pointer copy to be different") - } - if r.Operation == req.Operation { - t.Errorf("expect request operation pointer to be different") - } - - if e, a := req.Operation.HTTPMethod, r.Operation.HTTPMethod; e != a { - t.Errorf("expect %q http method, got %q", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go deleted file mode 100644 index 03aed301..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go +++ /dev/null @@ -1,648 +0,0 @@ -package request_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/route53" - "github.com/aws/aws-sdk-go/service/s3" -) - -// Use DynamoDB methods for simplicity -func TestPaginationQueryPage(t *testing.T) { - db := dynamodb.New(unit.Session) - tokens, pages, numPages, gotToEnd := []map[string]*dynamodb.AttributeValue{}, []map[string]*dynamodb.AttributeValue{}, 0, false - - reqNum := 0 - resps := []*dynamodb.QueryOutput{ - { - LastEvaluatedKey: map[string]*dynamodb.AttributeValue{"key": {S: aws.String("key1")}}, - Count: aws.Int64(1), - Items: []map[string]*dynamodb.AttributeValue{ - { - "key": {S: aws.String("key1")}, - }, - }, - }, - { - LastEvaluatedKey: map[string]*dynamodb.AttributeValue{"key": {S: aws.String("key2")}}, - Count: aws.Int64(1), - Items: []map[string]*dynamodb.AttributeValue{ - { - "key": {S: aws.String("key2")}, - }, - }, - }, - { - LastEvaluatedKey: map[string]*dynamodb.AttributeValue{}, - Count: aws.Int64(1), - Items: []map[string]*dynamodb.AttributeValue{ - { - "key": {S: aws.String("key3")}, - }, - }, - }, - } - - db.Handlers.Send.Clear() // mock sending - db.Handlers.Unmarshal.Clear() - db.Handlers.UnmarshalMeta.Clear() - db.Handlers.ValidateResponse.Clear() - db.Handlers.Build.PushBack(func(r *request.Request) { - in := r.Params.(*dynamodb.QueryInput) - if in == nil { - tokens = append(tokens, nil) - } else if len(in.ExclusiveStartKey) != 0 { - tokens = append(tokens, in.ExclusiveStartKey) - } - }) - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.QueryInput{ - Limit: aws.Int64(2), - TableName: aws.String("tablename"), - } - err := db.QueryPages(params, func(p *dynamodb.QueryOutput, last bool) bool { - numPages++ - for _, item := range p.Items { - pages = append(pages, item) - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - return true - }) - assert.Nil(t, err) - - assert.Equal(t, - []map[string]*dynamodb.AttributeValue{ - {"key": {S: aws.String("key1")}}, - {"key": {S: aws.String("key2")}}, - }, tokens) - assert.Equal(t, - []map[string]*dynamodb.AttributeValue{ - {"key": {S: aws.String("key1")}}, - {"key": {S: aws.String("key2")}}, - {"key": {S: aws.String("key3")}}, - }, pages) - assert.Equal(t, 3, numPages) - assert.True(t, gotToEnd) - assert.Nil(t, params.ExclusiveStartKey) -} - -// Use DynamoDB methods for simplicity -func TestPagination(t *testing.T) { - db := dynamodb.New(unit.Session) - tokens, pages, numPages, gotToEnd := []string{}, []string{}, 0, false - - reqNum := 0 - resps := []*dynamodb.ListTablesOutput{ - {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, - {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, - {TableNames: []*string{aws.String("Table5")}}, - } - - db.Handlers.Send.Clear() // mock sending - db.Handlers.Unmarshal.Clear() - db.Handlers.UnmarshalMeta.Clear() - db.Handlers.ValidateResponse.Clear() - db.Handlers.Build.PushBack(func(r *request.Request) { - in := r.Params.(*dynamodb.ListTablesInput) - if in == nil { - tokens = append(tokens, "") - } else if in.ExclusiveStartTableName != nil { - tokens = append(tokens, *in.ExclusiveStartTableName) - } - }) - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool { - numPages++ - for _, t := range p.TableNames { - pages = append(pages, *t) - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - return true - }) - - assert.Equal(t, []string{"Table2", "Table4"}, tokens) - assert.Equal(t, []string{"Table1", "Table2", "Table3", "Table4", "Table5"}, pages) - assert.Equal(t, 3, numPages) - assert.True(t, gotToEnd) - assert.Nil(t, err) - assert.Nil(t, params.ExclusiveStartTableName) -} - -// Use DynamoDB methods for simplicity -func TestPaginationEachPage(t *testing.T) { - db := dynamodb.New(unit.Session) - tokens, pages, numPages, gotToEnd := []string{}, []string{}, 0, false - - reqNum := 0 - resps := []*dynamodb.ListTablesOutput{ - {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, - {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, - {TableNames: []*string{aws.String("Table5")}}, - } - - db.Handlers.Send.Clear() // mock sending - db.Handlers.Unmarshal.Clear() - db.Handlers.UnmarshalMeta.Clear() - db.Handlers.ValidateResponse.Clear() - db.Handlers.Build.PushBack(func(r *request.Request) { - in := r.Params.(*dynamodb.ListTablesInput) - if in == nil { - tokens = append(tokens, "") - } else if in.ExclusiveStartTableName != nil { - tokens = append(tokens, *in.ExclusiveStartTableName) - } - }) - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - req, _ := db.ListTablesRequest(params) - err := req.EachPage(func(p interface{}, last bool) bool { - numPages++ - for _, t := range p.(*dynamodb.ListTablesOutput).TableNames { - pages = append(pages, *t) - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - - return true - }) - - assert.Equal(t, []string{"Table2", "Table4"}, tokens) - assert.Equal(t, []string{"Table1", "Table2", "Table3", "Table4", "Table5"}, pages) - assert.Equal(t, 3, numPages) - assert.True(t, gotToEnd) - assert.Nil(t, err) -} - -// Use DynamoDB methods for simplicity -func TestPaginationEarlyExit(t *testing.T) { - db := dynamodb.New(unit.Session) - numPages, gotToEnd := 0, false - - reqNum := 0 - resps := []*dynamodb.ListTablesOutput{ - {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, - {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, - {TableNames: []*string{aws.String("Table5")}}, - } - - db.Handlers.Send.Clear() // mock sending - db.Handlers.Unmarshal.Clear() - db.Handlers.UnmarshalMeta.Clear() - db.Handlers.ValidateResponse.Clear() - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool { - numPages++ - if numPages == 2 { - return false - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - return true - }) - - assert.Equal(t, 2, numPages) - assert.False(t, gotToEnd) - assert.Nil(t, err) -} - -func TestSkipPagination(t *testing.T) { - client := s3.New(unit.Session) - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = &s3.HeadBucketOutput{} - }) - - req, _ := client.HeadBucketRequest(&s3.HeadBucketInput{Bucket: aws.String("bucket")}) - - numPages, gotToEnd := 0, false - req.EachPage(func(p interface{}, last bool) bool { - numPages++ - if last { - gotToEnd = true - } - return true - }) - assert.Equal(t, 1, numPages) - assert.True(t, gotToEnd) -} - -// Use S3 for simplicity -func TestPaginationTruncation(t *testing.T) { - client := s3.New(unit.Session) - - reqNum := 0 - resps := []*s3.ListObjectsOutput{ - {IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key1")}}}, - {IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key2")}}}, - {IsTruncated: aws.Bool(false), Contents: []*s3.Object{{Key: aws.String("Key3")}}}, - {IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key4")}}}, - } - - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &s3.ListObjectsInput{Bucket: aws.String("bucket")} - - results := []string{} - err := client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool { - results = append(results, *p.Contents[0].Key) - return true - }) - - assert.Equal(t, []string{"Key1", "Key2", "Key3"}, results) - assert.Nil(t, err) - - // Try again without truncation token at all - reqNum = 0 - resps[1].IsTruncated = nil - resps[2].IsTruncated = aws.Bool(true) - results = []string{} - err = client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool { - results = append(results, *p.Contents[0].Key) - return true - }) - - assert.Equal(t, []string{"Key1", "Key2"}, results) - assert.Nil(t, err) -} - -func TestPaginationNilToken(t *testing.T) { - client := route53.New(unit.Session) - - reqNum := 0 - resps := []*route53.ListResourceRecordSetsOutput{ - { - ResourceRecordSets: []*route53.ResourceRecordSet{ - {Name: aws.String("first.example.com.")}, - }, - IsTruncated: aws.Bool(true), - NextRecordName: aws.String("second.example.com."), - NextRecordType: aws.String("MX"), - NextRecordIdentifier: aws.String("second"), - MaxItems: aws.String("1"), - }, - { - ResourceRecordSets: []*route53.ResourceRecordSet{ - {Name: aws.String("second.example.com.")}, - }, - IsTruncated: aws.Bool(true), - NextRecordName: aws.String("third.example.com."), - NextRecordType: aws.String("MX"), - MaxItems: aws.String("1"), - }, - { - ResourceRecordSets: []*route53.ResourceRecordSet{ - {Name: aws.String("third.example.com.")}, - }, - IsTruncated: aws.Bool(false), - MaxItems: aws.String("1"), - }, - } - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - - idents := []string{} - client.Handlers.Build.PushBack(func(r *request.Request) { - p := r.Params.(*route53.ListResourceRecordSetsInput) - idents = append(idents, aws.StringValue(p.StartRecordIdentifier)) - - }) - client.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &route53.ListResourceRecordSetsInput{ - HostedZoneId: aws.String("id-zone"), - } - - results := []string{} - err := client.ListResourceRecordSetsPages(params, func(p *route53.ListResourceRecordSetsOutput, last bool) bool { - results = append(results, *p.ResourceRecordSets[0].Name) - return true - }) - - assert.NoError(t, err) - assert.Equal(t, []string{"", "second", ""}, idents) - assert.Equal(t, []string{"first.example.com.", "second.example.com.", "third.example.com."}, results) -} - -func TestPaginationNilInput(t *testing.T) { - // Code generation doesn't have a great way to verify the code is correct - // other than being run via unit tests in the SDK. This should be fixed - // So code generation can be validated independently. - - client := s3.New(unit.Session) - client.Handlers.Validate.Clear() - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = &s3.ListObjectsOutput{} - }) - - gotToEnd := false - numPages := 0 - err := client.ListObjectsPages(nil, func(p *s3.ListObjectsOutput, last bool) bool { - numPages++ - if last { - gotToEnd = true - } - return true - }) - - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 1, numPages; e != a { - t.Errorf("expect %d number pages but got %d", e, a) - } - if !gotToEnd { - t.Errorf("expect to of gotten to end, did not") - } -} - -func TestPaginationWithContextNilInput(t *testing.T) { - // Code generation doesn't have a great way to verify the code is correct - // other than being run via unit tests in the SDK. This should be fixed - // So code generation can be validated independently. - - client := s3.New(unit.Session) - client.Handlers.Validate.Clear() - client.Handlers.Send.Clear() // mock sending - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = &s3.ListObjectsOutput{} - }) - - gotToEnd := false - numPages := 0 - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - err := client.ListObjectsPagesWithContext(ctx, nil, func(p *s3.ListObjectsOutput, last bool) bool { - numPages++ - if last { - gotToEnd = true - } - return true - }) - - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 1, numPages; e != a { - t.Errorf("expect %d number pages but got %d", e, a) - } - if !gotToEnd { - t.Errorf("expect to of gotten to end, did not") - } -} - -func TestPagination_Standalone(t *testing.T) { - type testPageInput struct { - NextToken *string - } - type testPageOutput struct { - Value *string - NextToken *string - } - type testCase struct { - Value, PrevToken, NextToken *string - } - - type testCaseList struct { - StopOnSameToken bool - Cases []testCase - } - - cases := []testCaseList{ - { - Cases: []testCase{ - testCase{aws.String("FirstValue"), aws.String("InitalToken"), aws.String("FirstToken")}, - testCase{aws.String("SecondValue"), aws.String("FirstToken"), aws.String("SecondToken")}, - testCase{aws.String("ThirdValue"), aws.String("SecondToken"), nil}, - }, - StopOnSameToken: false, - }, - { - Cases: []testCase{ - testCase{aws.String("FirstValue"), aws.String("InitalToken"), aws.String("FirstToken")}, - testCase{aws.String("SecondValue"), aws.String("FirstToken"), aws.String("SecondToken")}, - testCase{aws.String("ThirdValue"), aws.String("SecondToken"), aws.String("")}, - }, - StopOnSameToken: false, - }, - { - Cases: []testCase{ - testCase{aws.String("FirstValue"), aws.String("InitalToken"), aws.String("FirstToken")}, - testCase{aws.String("SecondValue"), aws.String("FirstToken"), aws.String("SecondToken")}, - testCase{nil, aws.String("SecondToken"), aws.String("SecondToken")}, - }, - StopOnSameToken: true, - }, - { - Cases: []testCase{ - testCase{aws.String("FirstValue"), aws.String("InitalToken"), aws.String("FirstToken")}, - testCase{aws.String("SecondValue"), aws.String("FirstToken"), aws.String("SecondToken")}, - testCase{aws.String("SecondValue"), aws.String("SecondToken"), aws.String("SecondToken")}, - }, - StopOnSameToken: true, - }, - } - - for _, testcase := range cases { - c := testcase.Cases - input := testPageInput{ - NextToken: c[0].PrevToken, - } - - svc := awstesting.NewClient() - i := 0 - p := request.Pagination{ - EndPageOnSameToken: testcase.StopOnSameToken, - NewRequest: func() (*request.Request, error) { - r := svc.NewRequest( - &request.Operation{ - Name: "Operation", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - }, - }, - &input, &testPageOutput{}, - ) - // Setup handlers for testing - r.Handlers.Clear() - r.Handlers.Build.PushBack(func(req *request.Request) { - if e, a := len(c), i+1; a > e { - t.Fatalf("expect no more than %d requests, got %d", e, a) - } - in := req.Params.(*testPageInput) - if e, a := aws.StringValue(c[i].PrevToken), aws.StringValue(in.NextToken); e != a { - t.Errorf("%d, expect NextToken input %q, got %q", i, e, a) - } - }) - r.Handlers.Unmarshal.PushBack(func(req *request.Request) { - out := &testPageOutput{ - Value: c[i].Value, - } - if c[i].NextToken != nil { - next := *c[i].NextToken - out.NextToken = aws.String(next) - } - req.Data = out - }) - return r, nil - }, - } - - for p.Next() { - data := p.Page().(*testPageOutput) - - if e, a := aws.StringValue(c[i].Value), aws.StringValue(data.Value); e != a { - t.Errorf("%d, expect Value to be %q, got %q", i, e, a) - } - if e, a := aws.StringValue(c[i].NextToken), aws.StringValue(data.NextToken); e != a { - t.Errorf("%d, expect NextToken to be %q, got %q", i, e, a) - } - - i++ - } - if e, a := len(c), i; e != a { - t.Errorf("expected to process %d pages, did %d", e, a) - } - if err := p.Err(); err != nil { - t.Fatalf("%d, expected no error, got %v", i, err) - } - } -} - -// Benchmarks -var benchResps = []*dynamodb.ListTablesOutput{ - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - {TableNames: []*string{aws.String("TABLE")}}, -} - -var benchDb = func() *dynamodb.DynamoDB { - db := dynamodb.New(unit.Session) - db.Handlers.Send.Clear() // mock sending - db.Handlers.Unmarshal.Clear() - db.Handlers.UnmarshalMeta.Clear() - db.Handlers.ValidateResponse.Clear() - return db -} - -func BenchmarkCodegenIterator(b *testing.B) { - reqNum := 0 - db := benchDb() - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = benchResps[reqNum] - reqNum++ - }) - - input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - iter := func(fn func(*dynamodb.ListTablesOutput, bool) bool) error { - page, _ := db.ListTablesRequest(input) - for ; page != nil; page = page.NextPage() { - page.Send() - out := page.Data.(*dynamodb.ListTablesOutput) - if result := fn(out, !page.HasNextPage()); page.Error != nil || !result { - return page.Error - } - } - return nil - } - - for i := 0; i < b.N; i++ { - reqNum = 0 - iter(func(p *dynamodb.ListTablesOutput, last bool) bool { - return true - }) - } -} - -func BenchmarkEachPageIterator(b *testing.B) { - reqNum := 0 - db := benchDb() - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = benchResps[reqNum] - reqNum++ - }) - - input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - for i := 0; i < b.N; i++ { - reqNum = 0 - req, _ := db.ListTablesRequest(input) - req.EachPage(func(p interface{}, last bool) bool { - return true - }) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_resetbody_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_resetbody_test.go deleted file mode 100644 index d7845b75..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_resetbody_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package request - -import ( - "bytes" - "io" - "net/http" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" -) - -func TestResetBody_WithBodyContents(t *testing.T) { - r := Request{ - HTTPRequest: &http.Request{}, - } - - reader := strings.NewReader("abc") - r.Body = reader - - r.ResetBody() - - if v, ok := r.HTTPRequest.Body.(*offsetReader); !ok || v == nil { - t.Errorf("expected request body to be set to reader, got %#v", - r.HTTPRequest.Body) - } -} - -type mockReader struct{} - -func (mockReader) Read([]byte) (int, error) { - return 0, io.EOF -} - -func TestResetBody_ExcludeEmptyUnseekableBodyByMethod(t *testing.T) { - cases := []struct { - Method string - Body io.ReadSeeker - IsNoBody bool - }{ - { - Method: "GET", - IsNoBody: true, - Body: aws.ReadSeekCloser(mockReader{}), - }, - { - Method: "HEAD", - IsNoBody: true, - Body: aws.ReadSeekCloser(mockReader{}), - }, - { - Method: "DELETE", - IsNoBody: true, - Body: aws.ReadSeekCloser(mockReader{}), - }, - { - Method: "PUT", - IsNoBody: false, - Body: aws.ReadSeekCloser(mockReader{}), - }, - { - Method: "PATCH", - IsNoBody: false, - Body: aws.ReadSeekCloser(mockReader{}), - }, - { - Method: "POST", - IsNoBody: false, - Body: aws.ReadSeekCloser(mockReader{}), - }, - { - Method: "GET", - IsNoBody: false, - Body: aws.ReadSeekCloser(bytes.NewBuffer([]byte("abc"))), - }, - { - Method: "GET", - IsNoBody: true, - Body: aws.ReadSeekCloser(bytes.NewBuffer(nil)), - }, - { - Method: "POST", - IsNoBody: false, - Body: aws.ReadSeekCloser(bytes.NewBuffer([]byte("abc"))), - }, - { - Method: "POST", - IsNoBody: true, - Body: aws.ReadSeekCloser(bytes.NewBuffer(nil)), - }, - } - - for i, c := range cases { - r := Request{ - HTTPRequest: &http.Request{}, - Operation: &Operation{ - HTTPMethod: c.Method, - }, - } - r.SetReaderBody(c.Body) - - if a, e := r.HTTPRequest.Body == NoBody, c.IsNoBody; a != e { - t.Errorf("%d, expect body to be set to noBody(%t), but was %t", i, e, a) - } - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_test.go deleted file mode 100644 index 0e4cef06..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_test.go +++ /dev/null @@ -1,1121 +0,0 @@ -package request_test - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "runtime" - "strconv" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -type testData struct { - Data string -} - -func body(str string) io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader([]byte(str))) -} - -func unmarshal(req *request.Request) { - defer req.HTTPResponse.Body.Close() - if req.Data != nil { - json.NewDecoder(req.HTTPResponse.Body).Decode(req.Data) - } - return -} - -func unmarshalError(req *request.Request) { - bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body) - if err != nil { - req.Error = awserr.New("UnmarshaleError", req.HTTPResponse.Status, err) - return - } - if len(bodyBytes) == 0 { - req.Error = awserr.NewRequestFailure( - awserr.New("UnmarshaleError", req.HTTPResponse.Status, fmt.Errorf("empty body")), - req.HTTPResponse.StatusCode, - "", - ) - return - } - var jsonErr jsonErrorResponse - if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil { - req.Error = awserr.New("UnmarshaleError", "JSON unmarshal", err) - return - } - req.Error = awserr.NewRequestFailure( - awserr.New(jsonErr.Code, jsonErr.Message, nil), - req.HTTPResponse.StatusCode, - "", - ) -} - -type jsonErrorResponse struct { - Code string `json:"__type"` - Message string `json:"message"` -} - -// test that retries occur for 5xx status codes -func TestRequestRecoverRetry5xx(t *testing.T) { - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 502, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 2, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if e, a := "valid", out.Data; e != a { - t.Errorf("expect %q output got %q", e, a) - } -} - -// test that retries occur for 4xx status codes with a response type that can be retried - see `shouldRetry` -func TestRequestRecoverRetry4xxRetryable(t *testing.T) { - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 400, Body: body(`{"__type":"Throttling","message":"Rate exceeded."}`)}, - {StatusCode: 400, Body: body(`{"__type":"ProvisionedThroughputExceededException","message":"Rate exceeded."}`)}, - {StatusCode: 429, Body: body(`{"__type":"FooException","message":"Rate exceeded."}`)}, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 3, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if e, a := "valid", out.Data; e != a { - t.Errorf("expect %q output got %q", e, a) - } -} - -// test that retries don't occur for 4xx status codes with a response type that can't be retried -func TestRequest4xxUnretryable(t *testing.T) { - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{StatusCode: 401, Body: body(`{"__type":"SignatureDoesNotMatch","message":"Signature does not match."}`)} - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err == nil { - t.Fatalf("expect error, but did not get one") - } - aerr := err.(awserr.RequestFailure) - if e, a := 401, aerr.StatusCode(); e != a { - t.Errorf("expect %d status code, got %d", e, a) - } - if e, a := "SignatureDoesNotMatch", aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := "Signature does not match.", aerr.Message(); e != a { - t.Errorf("expect %q error message, got %q", e, a) - } - if e, a := 0, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } -} - -func TestRequestExhaustRetries(t *testing.T) { - delays := []time.Duration{} - sleepDelay := func(delay time.Duration) { - delays = append(delays, delay) - } - - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - } - - s := awstesting.NewClient(aws.NewConfig().WithSleepDelay(sleepDelay)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := r.Send() - if err == nil { - t.Fatalf("expect error, but did not get one") - } - aerr := err.(awserr.RequestFailure) - if e, a := 500, aerr.StatusCode(); e != a { - t.Errorf("expect %d status code, got %d", e, a) - } - if e, a := "UnknownError", aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := "An error occurred.", aerr.Message(); e != a { - t.Errorf("expect %q error message, got %q", e, a) - } - if e, a := 3, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - - expectDelays := []struct{ min, max time.Duration }{{30, 59}, {60, 118}, {120, 236}} - for i, v := range delays { - min := expectDelays[i].min * time.Millisecond - max := expectDelays[i].max * time.Millisecond - if !(min <= v && v <= max) { - t.Errorf("Expect delay to be within range, i:%d, v:%s, min:%s, max:%s", - i, v, min, max) - } - } -} - -// test that the request is retried after the credentials are expired. -func TestRequestRecoverExpiredCreds(t *testing.T) { - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 400, Body: body(`{"__type":"ExpiredTokenException","message":"expired token"}`)}, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - - s := awstesting.NewClient(&aws.Config{MaxRetries: aws.Int(10), Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "")}) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - - credExpiredBeforeRetry := false - credExpiredAfterRetry := false - - s.Handlers.AfterRetry.PushBack(func(r *request.Request) { - credExpiredAfterRetry = r.Config.Credentials.IsExpired() - }) - - s.Handlers.Sign.Clear() - s.Handlers.Sign.PushBack(func(r *request.Request) { - r.Config.Credentials.Get() - }) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if credExpiredBeforeRetry { - t.Errorf("Expect valid creds before retry check") - } - if !credExpiredAfterRetry { - t.Errorf("Expect expired creds after retry check") - } - if s.Config.Credentials.IsExpired() { - t.Errorf("Expect valid creds after cred expired recovery") - } - - if e, a := 1, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if e, a := "valid", out.Data; e != a { - t.Errorf("expect %q output got %q", e, a) - } -} - -func TestMakeAddtoUserAgentHandler(t *testing.T) { - fn := request.MakeAddToUserAgentHandler("name", "version", "extra1", "extra2") - r := &request.Request{HTTPRequest: &http.Request{Header: http.Header{}}} - r.HTTPRequest.Header.Set("User-Agent", "foo/bar") - fn(r) - - if e, a := "foo/bar name/version (extra1; extra2)", r.HTTPRequest.Header.Get("User-Agent"); e != a { - t.Errorf("expect %q user agent, got %q", e, a) - } -} - -func TestMakeAddtoUserAgentFreeFormHandler(t *testing.T) { - fn := request.MakeAddToUserAgentFreeFormHandler("name/version (extra1; extra2)") - r := &request.Request{HTTPRequest: &http.Request{Header: http.Header{}}} - r.HTTPRequest.Header.Set("User-Agent", "foo/bar") - fn(r) - - if e, a := "foo/bar name/version (extra1; extra2)", r.HTTPRequest.Header.Get("User-Agent"); e != a { - t.Errorf("expect %q user agent, got %q", e, a) - } -} - -func TestRequestUserAgent(t *testing.T) { - s := awstesting.NewClient(&aws.Config{Region: aws.String("us-east-1")}) - // s.Handlers.Validate.Clear() - - req := s.NewRequest(&request.Operation{Name: "Operation"}, nil, &testData{}) - req.HTTPRequest.Header.Set("User-Agent", "foo/bar") - if err := req.Build(); err != nil { - t.Fatalf("expect no error, got %v", err) - } - - expectUA := fmt.Sprintf("foo/bar %s/%s (%s; %s; %s)", - aws.SDKName, aws.SDKVersion, runtime.Version(), runtime.GOOS, runtime.GOARCH) - if e, a := expectUA, req.HTTPRequest.Header.Get("User-Agent"); e != a { - t.Errorf("expect %q user agent, got %q", e, a) - } -} - -func TestRequestThrottleRetries(t *testing.T) { - delays := []time.Duration{} - sleepDelay := func(delay time.Duration) { - delays = append(delays, delay) - } - - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 500, Body: body(`{"__type":"Throttling","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"Throttling","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"Throttling","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"Throttling","message":"An error occurred."}`)}, - } - - s := awstesting.NewClient(aws.NewConfig().WithSleepDelay(sleepDelay)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := r.Send() - if err == nil { - t.Fatalf("expect error, but did not get one") - } - aerr := err.(awserr.RequestFailure) - if e, a := 500, aerr.StatusCode(); e != a { - t.Errorf("expect %d status code, got %d", e, a) - } - if e, a := "Throttling", aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := "An error occurred.", aerr.Message(); e != a { - t.Errorf("expect %q error message, got %q", e, a) - } - if e, a := 3, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - - expectDelays := []struct{ min, max time.Duration }{{500, 999}, {1000, 1998}, {2000, 3996}} - for i, v := range delays { - min := expectDelays[i].min * time.Millisecond - max := expectDelays[i].max * time.Millisecond - if !(min <= v && v <= max) { - t.Errorf("Expect delay to be within range, i:%d, v:%s, min:%s, max:%s", - i, v, min, max) - } - } -} - -// test that retries occur for request timeouts when response.Body can be nil -func TestRequestRecoverTimeoutWithNilBody(t *testing.T) { - reqNum := 0 - reqs := []*http.Response{ - {StatusCode: 0, Body: nil}, // body can be nil when requests time out - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - errors := []error{ - errTimeout, nil, - } - - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.AfterRetry.Clear() // force retry on all errors - s.Handlers.AfterRetry.PushBack(func(r *request.Request) { - if r.Error != nil { - r.Error = nil - r.Retryable = aws.Bool(true) - r.RetryCount++ - } - }) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = reqs[reqNum] - r.Error = errors[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 1, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if e, a := "valid", out.Data; e != a { - t.Errorf("expect %q output got %q", e, a) - } -} - -func TestRequestRecoverTimeoutWithNilResponse(t *testing.T) { - reqNum := 0 - reqs := []*http.Response{ - nil, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - errors := []error{ - errTimeout, - nil, - } - - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.AfterRetry.Clear() // force retry on all errors - s.Handlers.AfterRetry.PushBack(func(r *request.Request) { - if r.Error != nil { - r.Error = nil - r.Retryable = aws.Bool(true) - r.RetryCount++ - } - }) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = reqs[reqNum] - r.Error = errors[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } - if e, a := 1, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if e, a := "valid", out.Data; e != a { - t.Errorf("expect %q output got %q", e, a) - } -} - -func TestRequest_NoBody(t *testing.T) { - cases := []string{ - "GET", "HEAD", "DELETE", - "PUT", "POST", "PATCH", - } - - for i, c := range cases { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if v := r.TransferEncoding; len(v) > 0 { - t.Errorf("%d, expect no body sent with Transfer-Encoding, %v", i, v) - } - - outMsg := []byte(`{"Value": "abc"}`) - - if b, err := ioutil.ReadAll(r.Body); err != nil { - t.Fatalf("%d, expect no error reading request body, got %v", i, err) - } else if n := len(b); n > 0 { - t.Errorf("%d, expect no request body, got %d bytes", i, n) - } - - w.Header().Set("Content-Length", strconv.Itoa(len(outMsg))) - if _, err := w.Write(outMsg); err != nil { - t.Fatalf("%d, expect no error writing server response, got %v", i, err) - } - })) - - s := awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - MaxRetries: aws.Int(0), - Endpoint: aws.String(server.URL), - DisableSSL: aws.Bool(true), - }) - s.Handlers.Build.PushBack(rest.Build) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - - in := struct { - Bucket *string `location:"uri" locationName:"bucket"` - Key *string `location:"uri" locationName:"key"` - }{ - Bucket: aws.String("mybucket"), Key: aws.String("myKey"), - } - - out := struct { - Value *string - }{} - - r := s.NewRequest(&request.Operation{ - Name: "OpName", HTTPMethod: c, HTTPPath: "/{bucket}/{key+}", - }, &in, &out) - - if err := r.Send(); err != nil { - t.Fatalf("%d, expect no error sending request, got %v", i, err) - } - } -} - -func TestIsSerializationErrorRetryable(t *testing.T) { - testCases := []struct { - err error - expected bool - }{ - { - err: awserr.New(request.ErrCodeSerialization, "foo error", nil), - expected: false, - }, - { - err: awserr.New("ErrFoo", "foo error", nil), - expected: false, - }, - { - err: nil, - expected: false, - }, - { - err: awserr.New(request.ErrCodeSerialization, "foo error", stubConnectionResetError), - expected: true, - }, - } - - for i, c := range testCases { - r := &request.Request{ - Error: c.err, - } - if r.IsErrorRetryable() != c.expected { - t.Errorf("Case %d: Expected %v, but received %v", i+1, c.expected, !c.expected) - } - } -} - -func TestWithLogLevel(t *testing.T) { - r := &request.Request{} - - opt := request.WithLogLevel(aws.LogDebugWithHTTPBody) - r.ApplyOptions(opt) - - if !r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) { - t.Errorf("expect log level to be set, but was not, %v", - r.Config.LogLevel.Value()) - } -} - -func TestWithGetResponseHeader(t *testing.T) { - r := &request.Request{} - - var val, val2 string - r.ApplyOptions( - request.WithGetResponseHeader("x-a-header", &val), - request.WithGetResponseHeader("x-second-header", &val2), - ) - - r.HTTPResponse = &http.Response{ - Header: func() http.Header { - h := http.Header{} - h.Set("x-a-header", "first") - h.Set("x-second-header", "second") - return h - }(), - } - r.Handlers.Complete.Run(r) - - if e, a := "first", val; e != a { - t.Errorf("expect %q header value got %q", e, a) - } - if e, a := "second", val2; e != a { - t.Errorf("expect %q header value got %q", e, a) - } -} - -func TestWithGetResponseHeaders(t *testing.T) { - r := &request.Request{} - - var headers http.Header - opt := request.WithGetResponseHeaders(&headers) - - r.ApplyOptions(opt) - - r.HTTPResponse = &http.Response{ - Header: func() http.Header { - h := http.Header{} - h.Set("x-a-header", "headerValue") - return h - }(), - } - r.Handlers.Complete.Run(r) - - if e, a := "headerValue", headers.Get("x-a-header"); e != a { - t.Errorf("expect %q header value got %q", e, a) - } -} - -type connResetCloser struct { -} - -func (rc *connResetCloser) Read(b []byte) (int, error) { - return 0, stubConnectionResetError -} - -func (rc *connResetCloser) Close() error { - return nil -} - -func TestSerializationErrConnectionReset(t *testing.T) { - count := 0 - handlers := request.Handlers{} - handlers.Send.PushBack(func(r *request.Request) { - count++ - r.HTTPResponse = &http.Response{} - r.HTTPResponse.Body = &connResetCloser{} - }) - - handlers.Sign.PushBackNamed(v4.SignRequestHandler) - handlers.Build.PushBackNamed(jsonrpc.BuildHandler) - handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) - handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) - handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) - handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) - - op := &request.Operation{ - Name: "op", - HTTPMethod: "POST", - HTTPPath: "/", - } - - meta := metadata.ClientInfo{ - ServiceName: "fooService", - SigningName: "foo", - SigningRegion: "foo", - Endpoint: "localhost", - APIVersion: "2001-01-01", - JSONVersion: "1.1", - TargetPrefix: "Foo", - } - cfg := unit.Session.Config.Copy() - cfg.MaxRetries = aws.Int(5) - - req := request.New( - *cfg, - meta, - handlers, - client.DefaultRetryer{NumMaxRetries: 5}, - op, - &struct { - }{}, - &struct { - }{}, - ) - - osErr := stubConnectionResetError - req.ApplyOptions(request.WithResponseReadTimeout(time.Second)) - err := req.Send() - if err == nil { - t.Error("Expected rror 'SerializationError', but received nil") - } - if aerr, ok := err.(awserr.Error); ok && aerr.Code() != "SerializationError" { - t.Errorf("Expected 'SerializationError', but received %q", aerr.Code()) - } else if !ok { - t.Errorf("Expected 'awserr.Error', but received %v", reflect.TypeOf(err)) - } else if aerr.OrigErr().Error() != osErr.Error() { - t.Errorf("Expected %q, but received %q", osErr.Error(), aerr.OrigErr().Error()) - } - - if count != 6 { - t.Errorf("Expected '6', but received %d", count) - } -} - -type testRetryer struct { - shouldRetry bool -} - -func (d *testRetryer) MaxRetries() int { - return 3 -} - -// RetryRules returns the delay duration before retrying this request again -func (d *testRetryer) RetryRules(r *request.Request) time.Duration { - return time.Duration(time.Millisecond) -} - -func (d *testRetryer) ShouldRetry(r *request.Request) bool { - d.shouldRetry = true - if r.Retryable != nil { - return *r.Retryable - } - - if r.HTTPResponse.StatusCode >= 500 { - return true - } - return r.IsErrorRetryable() -} - -func TestEnforceShouldRetryCheck(t *testing.T) { - tp := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - ResponseHeaderTimeout: 1 * time.Millisecond, - } - - client := &http.Client{Transport: tp} - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // This server should wait forever. Requests will timeout and the SDK should - // attempt to retry. - select {} - })) - - retryer := &testRetryer{} - s := awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - MaxRetries: aws.Int(0), - Endpoint: aws.String(server.URL), - DisableSSL: aws.Bool(true), - Retryer: retryer, - HTTPClient: client, - EnforceShouldRetryCheck: aws.Bool(true), - }) - - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err == nil { - t.Fatalf("expect error, but got nil") - } - if e, a := 3, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } - if !retryer.shouldRetry { - t.Errorf("expect 'true' for ShouldRetry, but got %v", retryer.shouldRetry) - } -} - -type errReader struct { - err error -} - -func (reader *errReader) Read(b []byte) (int, error) { - return 0, reader.err -} - -func (reader *errReader) Close() error { - return nil -} - -func TestIsNoBodyReader(t *testing.T) { - cases := []struct { - reader io.ReadCloser - expect bool - }{ - {ioutil.NopCloser(bytes.NewReader([]byte("abc"))), false}, - {ioutil.NopCloser(bytes.NewReader(nil)), false}, - {nil, false}, - {request.NoBody, true}, - } - - for i, c := range cases { - if e, a := c.expect, request.NoBody == c.reader; e != a { - t.Errorf("%d, expect %t match, but was %t", i, e, a) - } - } -} - -func TestRequest_TemporaryRetry(t *testing.T) { - done := make(chan struct{}) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Length", "1024") - w.WriteHeader(http.StatusOK) - - w.Write(make([]byte, 100)) - - f := w.(http.Flusher) - f.Flush() - - <-done - })) - - client := &http.Client{ - Timeout: 100 * time.Millisecond, - } - - svc := awstesting.NewClient(&aws.Config{ - Region: unit.Session.Config.Region, - MaxRetries: aws.Int(1), - HTTPClient: client, - DisableSSL: aws.Bool(true), - Endpoint: aws.String(server.URL), - }) - - req := svc.NewRequest(&request.Operation{ - Name: "name", HTTPMethod: "GET", HTTPPath: "/path", - }, &struct{}{}, &struct{}{}) - - req.Handlers.Unmarshal.PushBack(func(r *request.Request) { - defer req.HTTPResponse.Body.Close() - _, err := io.Copy(ioutil.Discard, req.HTTPResponse.Body) - r.Error = awserr.New(request.ErrCodeSerialization, "error", err) - }) - - err := req.Send() - if err == nil { - t.Errorf("expect error, got none") - } - close(done) - - aerr := err.(awserr.Error) - if e, a := request.ErrCodeSerialization, aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - - if e, a := 1, req.RetryCount; e != a { - t.Errorf("expect %d retries, got %d", e, a) - } - - type temporary interface { - Temporary() bool - } - - terr := aerr.OrigErr().(temporary) - if !terr.Temporary() { - t.Errorf("expect temporary error, was not") - } -} - -func TestRequest_Presign(t *testing.T) { - presign := func(r *request.Request, expire time.Duration) (string, http.Header, error) { - u, err := r.Presign(expire) - return u, nil, err - } - presignRequest := func(r *request.Request, expire time.Duration) (string, http.Header, error) { - return r.PresignRequest(expire) - } - mustParseURL := func(v string) *url.URL { - u, err := url.Parse(v) - if err != nil { - panic(err) - } - return u - } - - cases := []struct { - Expire time.Duration - PresignFn func(*request.Request, time.Duration) (string, http.Header, error) - SignerFn func(*request.Request) - URL string - Header http.Header - Err string - }{ - { - PresignFn: presign, - Err: request.ErrCodeInvalidPresignExpire, - }, - { - PresignFn: presignRequest, - Err: request.ErrCodeInvalidPresignExpire, - }, - { - Expire: -1, - PresignFn: presign, - Err: request.ErrCodeInvalidPresignExpire, - }, - { - // Presign clear NotHoist - Expire: 1 * time.Minute, - PresignFn: func(r *request.Request, dur time.Duration) (string, http.Header, error) { - r.NotHoist = true - return presign(r, dur) - }, - SignerFn: func(r *request.Request) { - r.HTTPRequest.URL = mustParseURL("https://endpoint/presignedURL") - if r.NotHoist { - r.Error = fmt.Errorf("expect NotHoist to be cleared") - } - }, - URL: "https://endpoint/presignedURL", - }, - { - // PresignRequest does not clear NotHoist - Expire: 1 * time.Minute, - PresignFn: func(r *request.Request, dur time.Duration) (string, http.Header, error) { - r.NotHoist = true - return presignRequest(r, dur) - }, - SignerFn: func(r *request.Request) { - r.HTTPRequest.URL = mustParseURL("https://endpoint/presignedURL") - if !r.NotHoist { - r.Error = fmt.Errorf("expect NotHoist not to be cleared") - } - }, - URL: "https://endpoint/presignedURL", - }, - { - // PresignRequest returns signed headers - Expire: 1 * time.Minute, - PresignFn: presignRequest, - SignerFn: func(r *request.Request) { - r.HTTPRequest.URL = mustParseURL("https://endpoint/presignedURL") - r.HTTPRequest.Header.Set("UnsigndHeader", "abc") - r.SignedHeaderVals = http.Header{ - "X-Amzn-Header": []string{"abc", "123"}, - "X-Amzn-Header2": []string{"efg", "456"}, - } - }, - URL: "https://endpoint/presignedURL", - Header: http.Header{ - "X-Amzn-Header": []string{"abc", "123"}, - "X-Amzn-Header2": []string{"efg", "456"}, - }, - }, - } - - svc := awstesting.NewClient() - svc.Handlers.Clear() - for i, c := range cases { - req := svc.NewRequest(&request.Operation{ - Name: "name", HTTPMethod: "GET", HTTPPath: "/path", - }, &struct{}{}, &struct{}{}) - req.Handlers.Sign.PushBack(c.SignerFn) - - u, h, err := c.PresignFn(req, c.Expire) - if len(c.Err) != 0 { - if e, a := c.Err, err.Error(); !strings.Contains(a, e) { - t.Errorf("%d, expect %v to be in %v", i, e, a) - } - continue - } else if err != nil { - t.Errorf("%d, expect no error, got %v", i, err) - continue - } - if e, a := c.URL, u; e != a { - t.Errorf("%d, expect %v URL, got %v", i, e, a) - } - if e, a := c.Header, h; !reflect.DeepEqual(e, a) { - t.Errorf("%d, expect %v header got %v", i, e, a) - } - } -} - -func TestNew_EndpointWithDefaultPort(t *testing.T) { - endpoint := "https://estest.us-east-1.es.amazonaws.com:443" - expectedRequestHost := "estest.us-east-1.es.amazonaws.com" - - r := request.New( - aws.Config{}, - metadata.ClientInfo{Endpoint: endpoint}, - defaults.Handlers(), - client.DefaultRetryer{}, - &request.Operation{}, - nil, - nil, - ) - - if h := r.HTTPRequest.Host; h != expectedRequestHost { - t.Errorf("expect %v host, got %q", expectedRequestHost, h) - } -} - -func TestSanitizeHostForHeader(t *testing.T) { - cases := []struct { - url string - expectedRequestHost string - }{ - {"https://estest.us-east-1.es.amazonaws.com:443", "estest.us-east-1.es.amazonaws.com"}, - {"https://estest.us-east-1.es.amazonaws.com", "estest.us-east-1.es.amazonaws.com"}, - {"https://localhost:9200", "localhost:9200"}, - {"http://localhost:80", "localhost"}, - {"http://localhost:8080", "localhost:8080"}, - } - - for _, c := range cases { - r, _ := http.NewRequest("GET", c.url, nil) - request.SanitizeHostForHeader(r) - - if h := r.Host; h != c.expectedRequestHost { - t.Errorf("expect %v host, got %q", c.expectedRequestHost, h) - } - } -} - -func TestRequestWillRetry_ByBody(t *testing.T) { - svc := awstesting.NewClient() - - cases := []struct { - WillRetry bool - HTTPMethod string - Body io.ReadSeeker - IsReqNoBody bool - }{ - { - WillRetry: true, - HTTPMethod: "GET", - Body: bytes.NewReader([]byte{}), - IsReqNoBody: true, - }, - { - WillRetry: true, - HTTPMethod: "GET", - Body: bytes.NewReader(nil), - IsReqNoBody: true, - }, - { - WillRetry: true, - HTTPMethod: "POST", - Body: bytes.NewReader([]byte("abc123")), - }, - { - WillRetry: true, - HTTPMethod: "POST", - Body: aws.ReadSeekCloser(bytes.NewReader([]byte("abc123"))), - }, - { - WillRetry: true, - HTTPMethod: "GET", - Body: aws.ReadSeekCloser(bytes.NewBuffer(nil)), - IsReqNoBody: true, - }, - { - WillRetry: true, - HTTPMethod: "POST", - Body: aws.ReadSeekCloser(bytes.NewBuffer(nil)), - IsReqNoBody: true, - }, - { - WillRetry: false, - HTTPMethod: "POST", - Body: aws.ReadSeekCloser(bytes.NewBuffer([]byte("abc123"))), - }, - } - - for i, c := range cases { - req := svc.NewRequest(&request.Operation{ - Name: "Operation", - HTTPMethod: c.HTTPMethod, - HTTPPath: "/", - }, nil, nil) - req.SetReaderBody(c.Body) - req.Build() - - req.Error = fmt.Errorf("some error") - req.Retryable = aws.Bool(true) - req.HTTPResponse = &http.Response{ - StatusCode: 500, - } - - if e, a := c.IsReqNoBody, request.NoBody == req.HTTPRequest.Body; e != a { - t.Errorf("%d, expect request to be no body, %t, got %t, %T", i, e, a, req.HTTPRequest.Body) - } - - if e, a := c.WillRetry, req.WillRetry(); e != a { - t.Errorf("%d, expect %t willRetry, got %t", i, e, a) - } - - if req.Error == nil { - t.Fatalf("%d, expect error, got none", i) - } - if e, a := "some error", req.Error.Error(); !strings.Contains(a, e) { - t.Errorf("%d, expect %q error in %q", i, e, a) - } - if e, a := 0, req.RetryCount; e != a { - t.Errorf("%d, expect retry count to be %d, got %d", i, e, a) - } - } -} - -func Test501NotRetrying(t *testing.T) { - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 501, Body: body(`{"__type":"NotImplemented","message":"An error occurred."}`)}, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - - s := awstesting.NewClient(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - if err == nil { - t.Fatal("expect error, but got none") - } - - aerr := err.(awserr.Error) - if e, a := "NotImplemented", aerr.Code(); e != a { - t.Errorf("expected error code %q, but received %q", e, a) - } - if e, a := 1, int(r.RetryCount); e != a { - t.Errorf("expect %d retry count, got %d", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer_test.go deleted file mode 100644 index a8787487..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package request - -import ( - "errors" - "fmt" - "testing" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -func TestRequestThrottling(t *testing.T) { - req := Request{} - - req.Error = awserr.New("Throttling", "", nil) - if e, a := true, req.IsErrorThrottle(); e != a { - t.Errorf("expect %t to be throttled, was %t", e, a) - } -} - -type mockTempError bool - -func (e mockTempError) Error() string { - return fmt.Sprintf("mock temporary error: %t", e.Temporary()) -} -func (e mockTempError) Temporary() bool { - return bool(e) -} - -func TestIsErrorRetryable(t *testing.T) { - cases := []struct { - Err error - IsTemp bool - }{ - { - Err: awserr.New(ErrCodeSerialization, "temporary error", mockTempError(true)), - IsTemp: true, - }, - { - Err: awserr.New(ErrCodeSerialization, "temporary error", mockTempError(false)), - IsTemp: false, - }, - { - Err: awserr.New(ErrCodeSerialization, "some error", errors.New("blah")), - IsTemp: false, - }, - { - Err: awserr.New("SomeError", "some error", nil), - IsTemp: false, - }, - { - Err: awserr.New("RequestError", "some error", nil), - IsTemp: true, - }, - } - - for i, c := range cases { - retryable := IsErrorRetryable(c.Err) - if e, a := c.IsTemp, retryable; e != a { - t.Errorf("%d, expect %t temporary error, got %t", i, e, a) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_benchmark_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_benchmark_test.go deleted file mode 100644 index 33e1b2d1..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_benchmark_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package request_test - -import ( - "bytes" - "io/ioutil" - "net/http" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" -) - -func BenchmarkTimeoutReadCloser(b *testing.B) { - resp := ` - { - "Bar": "qux" - } - ` - - handlers := request.Handlers{} - - handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: http.StatusOK, - Body: ioutil.NopCloser(bytes.NewBuffer([]byte(resp))), - } - }) - handlers.Sign.PushBackNamed(v4.SignRequestHandler) - handlers.Build.PushBackNamed(jsonrpc.BuildHandler) - handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) - handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) - handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) - - op := &request.Operation{ - Name: "op", - HTTPMethod: "POST", - HTTPPath: "/", - } - - meta := metadata.ClientInfo{ - ServiceName: "fooService", - SigningName: "foo", - SigningRegion: "foo", - Endpoint: "localhost", - APIVersion: "2001-01-01", - JSONVersion: "1.1", - TargetPrefix: "Foo", - } - - req := request.New( - *unit.Session.Config, - meta, - handlers, - client.DefaultRetryer{NumMaxRetries: 5}, - op, - &struct { - Foo *string - }{}, - &struct { - Bar *string - }{}, - ) - - req.ApplyOptions(request.WithResponseReadTimeout(15 * time.Second)) - for i := 0; i < b.N; i++ { - err := req.Send() - if err != nil { - b.Errorf("Expected no error, but received %v", err) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_test.go deleted file mode 100644 index c814158d..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package request - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -type testReader struct { - duration time.Duration - count int -} - -func (r *testReader) Read(b []byte) (int, error) { - if r.count > 0 { - r.count-- - return len(b), nil - } - time.Sleep(r.duration) - return 0, io.EOF -} - -func (r *testReader) Close() error { - return nil -} - -func TestTimeoutReadCloser(t *testing.T) { - reader := timeoutReadCloser{ - reader: &testReader{ - duration: time.Second, - count: 5, - }, - duration: time.Millisecond, - } - b := make([]byte, 100) - _, err := reader.Read(b) - if err != nil { - t.Log(err) - } -} - -func TestTimeoutReadCloserSameDuration(t *testing.T) { - reader := timeoutReadCloser{ - reader: &testReader{ - duration: time.Millisecond, - count: 5, - }, - duration: time.Millisecond, - } - b := make([]byte, 100) - _, err := reader.Read(b) - if err != nil { - t.Log(err) - } -} - -func TestWithResponseReadTimeout(t *testing.T) { - r := Request{ - HTTPResponse: &http.Response{ - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, - } - r.ApplyOptions(WithResponseReadTimeout(time.Second)) - err := r.Send() - if err != nil { - t.Error(err) - } - v, ok := r.HTTPResponse.Body.(*timeoutReadCloser) - if !ok { - t.Error("Expected the body to be a timeoutReadCloser") - } - if v.duration != time.Second { - t.Errorf("Expected %v, but receive %v\n", time.Second, v.duration) - } -} - -func TestAdaptToResponseTimeout(t *testing.T) { - testCases := []struct { - childErr error - r Request - expectedRootCode string - }{ - { - childErr: awserr.New(ErrCodeResponseTimeout, "timeout!", nil), - r: Request{ - Error: awserr.New("ErrTest", "FooBar", awserr.New(ErrCodeResponseTimeout, "timeout!", nil)), - }, - expectedRootCode: ErrCodeResponseTimeout, - }, - { - childErr: awserr.New(ErrCodeResponseTimeout+"1", "timeout!", nil), - r: Request{ - Error: awserr.New("ErrTest", "FooBar", awserr.New(ErrCodeResponseTimeout+"1", "timeout!", nil)), - }, - expectedRootCode: "ErrTest", - }, - { - r: Request{ - Error: awserr.New("ErrTest", "FooBar", nil), - }, - expectedRootCode: "ErrTest", - }, - } - - for i, c := range testCases { - adaptToResponseTimeoutError(&c.r) - if aerr, ok := c.r.Error.(awserr.Error); !ok { - t.Errorf("Case %d: Expected 'awserr', but received %v", i+1, c.r.Error) - } else if aerr.Code() != c.expectedRootCode { - t.Errorf("Case %d: Expected %q, but received %s", i+1, c.expectedRootCode, aerr.Code()) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter_test.go b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter_test.go deleted file mode 100644 index db0f92df..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter_test.go +++ /dev/null @@ -1,654 +0,0 @@ -package request_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "testing" - "time" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/s3" -) - -type mockClient struct { - *client.Client -} -type MockInput struct{} -type MockOutput struct { - States []*MockState -} -type MockState struct { - State *string -} - -func (c *mockClient) MockRequest(input *MockInput) (*request.Request, *MockOutput) { - op := &request.Operation{ - Name: "Mock", - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &MockInput{} - } - - output := &MockOutput{} - req := c.NewRequest(op, input, output) - req.Data = output - return req, output -} - -func BuildNewMockRequest(c *mockClient, in *MockInput) func([]request.Option) (*request.Request, error) { - return func(opts []request.Option) (*request.Request, error) { - req, _ := c.MockRequest(in) - req.ApplyOptions(opts...) - return req, nil - } -} - -func TestWaiterPathAll(t *testing.T) { - svc := &mockClient{Client: awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - })} - svc.Handlers.Send.Clear() // mock sending - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.ValidateResponse.Clear() - - reqNum := 0 - resps := []*MockOutput{ - { // Request 1 - States: []*MockState{ - {State: aws.String("pending")}, - {State: aws.String("pending")}, - }, - }, - { // Request 2 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("pending")}, - }, - }, - { // Request 3 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("running")}, - }, - }, - } - - numBuiltReq := 0 - svc.Handlers.Build.PushBack(func(r *request.Request) { - numBuiltReq++ - }) - svc.Handlers.Unmarshal.PushBack(func(r *request.Request) { - if reqNum >= len(resps) { - assert.Fail(t, "too many polling requests made") - return - } - r.Data = resps[reqNum] - reqNum++ - }) - - w := request.Waiter{ - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(0), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.PathAllWaiterMatch, - Argument: "States[].State", - Expected: "running", - }, - }, - NewRequest: BuildNewMockRequest(svc, &MockInput{}), - } - - err := w.WaitWithContext(aws.BackgroundContext()) - assert.NoError(t, err) - assert.Equal(t, 3, numBuiltReq) - assert.Equal(t, 3, reqNum) -} - -func TestWaiterPath(t *testing.T) { - svc := &mockClient{Client: awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - })} - svc.Handlers.Send.Clear() // mock sending - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.ValidateResponse.Clear() - - reqNum := 0 - resps := []*MockOutput{ - { // Request 1 - States: []*MockState{ - {State: aws.String("pending")}, - {State: aws.String("pending")}, - }, - }, - { // Request 2 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("pending")}, - }, - }, - { // Request 3 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("running")}, - }, - }, - } - - numBuiltReq := 0 - svc.Handlers.Build.PushBack(func(r *request.Request) { - numBuiltReq++ - }) - svc.Handlers.Unmarshal.PushBack(func(r *request.Request) { - if reqNum >= len(resps) { - assert.Fail(t, "too many polling requests made") - return - } - r.Data = resps[reqNum] - reqNum++ - }) - - w := request.Waiter{ - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(0), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.PathWaiterMatch, - Argument: "States[].State", - Expected: "running", - }, - }, - NewRequest: BuildNewMockRequest(svc, &MockInput{}), - } - - err := w.WaitWithContext(aws.BackgroundContext()) - assert.NoError(t, err) - assert.Equal(t, 3, numBuiltReq) - assert.Equal(t, 3, reqNum) -} - -func TestWaiterFailure(t *testing.T) { - svc := &mockClient{Client: awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - })} - svc.Handlers.Send.Clear() // mock sending - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.ValidateResponse.Clear() - - reqNum := 0 - resps := []*MockOutput{ - { // Request 1 - States: []*MockState{ - {State: aws.String("pending")}, - {State: aws.String("pending")}, - }, - }, - { // Request 2 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("pending")}, - }, - }, - { // Request 3 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("stopping")}, - }, - }, - } - - numBuiltReq := 0 - svc.Handlers.Build.PushBack(func(r *request.Request) { - numBuiltReq++ - }) - svc.Handlers.Unmarshal.PushBack(func(r *request.Request) { - if reqNum >= len(resps) { - assert.Fail(t, "too many polling requests made") - return - } - r.Data = resps[reqNum] - reqNum++ - }) - - w := request.Waiter{ - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(0), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.PathAllWaiterMatch, - Argument: "States[].State", - Expected: "running", - }, - { - State: request.FailureWaiterState, - Matcher: request.PathAnyWaiterMatch, - Argument: "States[].State", - Expected: "stopping", - }, - }, - NewRequest: BuildNewMockRequest(svc, &MockInput{}), - } - - err := w.WaitWithContext(aws.BackgroundContext()).(awserr.Error) - assert.Error(t, err) - assert.Equal(t, request.WaiterResourceNotReadyErrorCode, err.Code()) - assert.Equal(t, "failed waiting for successful resource state", err.Message()) - assert.Equal(t, 3, numBuiltReq) - assert.Equal(t, 3, reqNum) -} - -func TestWaiterError(t *testing.T) { - svc := &mockClient{Client: awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - })} - svc.Handlers.Send.Clear() // mock sending - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.UnmarshalError.Clear() - svc.Handlers.ValidateResponse.Clear() - - reqNum := 0 - resps := []*MockOutput{ - { // Request 1 - States: []*MockState{ - {State: aws.String("pending")}, - {State: aws.String("pending")}, - }, - }, - { // Request 1, error case retry - }, - { // Request 2, error case failure - }, - { // Request 3 - States: []*MockState{ - {State: aws.String("running")}, - {State: aws.String("running")}, - }, - }, - } - reqErrs := make([]error, len(resps)) - reqErrs[1] = awserr.New("MockException", "mock exception message", nil) - reqErrs[2] = awserr.New("FailureException", "mock failure exception message", nil) - - numBuiltReq := 0 - svc.Handlers.Build.PushBack(func(r *request.Request) { - numBuiltReq++ - }) - svc.Handlers.Send.PushBack(func(r *request.Request) { - code := 200 - if reqNum == 1 { - code = 400 - } - r.HTTPResponse = &http.Response{ - StatusCode: code, - Status: http.StatusText(code), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - }) - svc.Handlers.Unmarshal.PushBack(func(r *request.Request) { - if reqNum >= len(resps) { - assert.Fail(t, "too many polling requests made") - return - } - r.Data = resps[reqNum] - reqNum++ - }) - svc.Handlers.UnmarshalMeta.PushBack(func(r *request.Request) { - // If there was an error unmarshal error will be called instead of unmarshal - // need to increment count here also - if err := reqErrs[reqNum]; err != nil { - r.Error = err - reqNum++ - } - }) - - w := request.Waiter{ - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(0), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.PathAllWaiterMatch, - Argument: "States[].State", - Expected: "running", - }, - { - State: request.RetryWaiterState, - Matcher: request.ErrorWaiterMatch, - Argument: "", - Expected: "MockException", - }, - { - State: request.FailureWaiterState, - Matcher: request.ErrorWaiterMatch, - Argument: "", - Expected: "FailureException", - }, - }, - NewRequest: BuildNewMockRequest(svc, &MockInput{}), - } - - err := w.WaitWithContext(aws.BackgroundContext()) - if err == nil { - t.Fatalf("expected error, but did not get one") - } - aerr := err.(awserr.Error) - if e, a := request.WaiterResourceNotReadyErrorCode, aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := 3, numBuiltReq; e != a { - t.Errorf("expect %d built requests got %d", e, a) - } - if e, a := 3, reqNum; e != a { - t.Errorf("expect %d reqNum got %d", e, a) - } -} - -func TestWaiterStatus(t *testing.T) { - svc := &mockClient{Client: awstesting.NewClient(&aws.Config{ - Region: aws.String("mock-region"), - })} - svc.Handlers.Send.Clear() // mock sending - svc.Handlers.Unmarshal.Clear() - svc.Handlers.UnmarshalMeta.Clear() - svc.Handlers.ValidateResponse.Clear() - - reqNum := 0 - svc.Handlers.Build.PushBack(func(r *request.Request) { - reqNum++ - }) - svc.Handlers.Send.PushBack(func(r *request.Request) { - code := 200 - if reqNum == 3 { - code = 404 - r.Error = awserr.New("NotFound", "Not Found", nil) - } - r.HTTPResponse = &http.Response{ - StatusCode: code, - Status: http.StatusText(code), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - }) - - w := request.Waiter{ - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(0), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Argument: "", - Expected: 404, - }, - }, - NewRequest: BuildNewMockRequest(svc, &MockInput{}), - } - - err := w.WaitWithContext(aws.BackgroundContext()) - assert.NoError(t, err) - assert.Equal(t, 3, reqNum) -} - -func TestWaiter_ApplyOptions(t *testing.T) { - w := request.Waiter{} - - logger := aws.NewDefaultLogger() - - w.ApplyOptions( - request.WithWaiterLogger(logger), - request.WithWaiterRequestOptions(request.WithLogLevel(aws.LogDebug)), - request.WithWaiterMaxAttempts(2), - request.WithWaiterDelay(request.ConstantWaiterDelay(5*time.Second)), - ) - - if e, a := logger, w.Logger; e != a { - t.Errorf("expect logger to be set, and match, was not, %v, %v", e, a) - } - - if len(w.RequestOptions) != 1 { - t.Fatalf("expect request options to be set to only a single option, %v", w.RequestOptions) - } - r := request.Request{} - r.ApplyOptions(w.RequestOptions...) - if e, a := aws.LogDebug, r.Config.LogLevel.Value(); e != a { - t.Errorf("expect %v loglevel got %v", e, a) - } - - if e, a := 2, w.MaxAttempts; e != a { - t.Errorf("expect %d retryer max attempts, got %d", e, a) - } - if e, a := 5*time.Second, w.Delay(0); e != a { - t.Errorf("expect %d retryer delay, got %d", e, a) - } -} - -func TestWaiter_WithContextCanceled(t *testing.T) { - c := awstesting.NewClient() - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - reqCount := 0 - - w := request.Waiter{ - Name: "TestWaiter", - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(1 * time.Millisecond), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 200, - }, - }, - Logger: aws.NewDefaultLogger(), - NewRequest: func(opts []request.Option) (*request.Request, error) { - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - req.HTTPResponse = &http.Response{StatusCode: http.StatusNotFound} - req.Handlers.Clear() - req.Data = struct{}{} - req.Handlers.Send.PushBack(func(r *request.Request) { - if reqCount == 1 { - ctx.Error = fmt.Errorf("context canceled") - close(ctx.DoneCh) - } - reqCount++ - }) - - return req, nil - }, - } - - w.SleepWithContext = func(c aws.Context, delay time.Duration) error { - context := c.(*awstesting.FakeContext) - select { - case <-context.DoneCh: - return context.Err() - default: - return nil - } - } - - err := w.WaitWithContext(ctx) - - if err == nil { - t.Fatalf("expect waiter to be canceled.") - } - aerr := err.(awserr.Error) - if e, a := request.CanceledErrorCode, aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := 2, reqCount; e != a { - t.Errorf("expect %d requests, got %d", e, a) - } -} - -func TestWaiter_WithContext(t *testing.T) { - c := awstesting.NewClient() - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - reqCount := 0 - - statuses := []int{http.StatusNotFound, http.StatusOK} - - w := request.Waiter{ - Name: "TestWaiter", - MaxAttempts: 10, - Delay: request.ConstantWaiterDelay(1 * time.Millisecond), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 200, - }, - }, - Logger: aws.NewDefaultLogger(), - NewRequest: func(opts []request.Option) (*request.Request, error) { - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - req.HTTPResponse = &http.Response{StatusCode: statuses[reqCount]} - req.Handlers.Clear() - req.Data = struct{}{} - req.Handlers.Send.PushBack(func(r *request.Request) { - if reqCount == 1 { - ctx.Error = fmt.Errorf("context canceled") - close(ctx.DoneCh) - } - reqCount++ - }) - - return req, nil - }, - } - - err := w.WaitWithContext(ctx) - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := 2, reqCount; e != a { - t.Errorf("expect %d requests, got %d", e, a) - } -} - -func TestWaiter_AttemptsExpires(t *testing.T) { - c := awstesting.NewClient() - - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - reqCount := 0 - - w := request.Waiter{ - Name: "TestWaiter", - MaxAttempts: 2, - Delay: request.ConstantWaiterDelay(1 * time.Millisecond), - SleepWithContext: aws.SleepWithContext, - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 200, - }, - }, - Logger: aws.NewDefaultLogger(), - NewRequest: func(opts []request.Option) (*request.Request, error) { - req := c.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - req.HTTPResponse = &http.Response{StatusCode: http.StatusNotFound} - req.Handlers.Clear() - req.Data = struct{}{} - req.Handlers.Send.PushBack(func(r *request.Request) { - reqCount++ - }) - - return req, nil - }, - } - - err := w.WaitWithContext(ctx) - - if err == nil { - t.Fatalf("expect error did not get one") - } - aerr := err.(awserr.Error) - if e, a := request.WaiterResourceNotReadyErrorCode, aerr.Code(); e != a { - t.Errorf("expect %q error code, got %q", e, a) - } - if e, a := 2, reqCount; e != a { - t.Errorf("expect %d requests, got %d", e, a) - } -} - -func TestWaiterNilInput(t *testing.T) { - // Code generation doesn't have a great way to verify the code is correct - // other than being run via unit tests in the SDK. This should be fixed - // So code generation can be validated independently. - - client := s3.New(unit.Session) - client.Handlers.Validate.Clear() - client.Handlers.Send.Clear() // mock sending - client.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: http.StatusOK, - } - }) - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - client.Config.SleepDelay = func(dur time.Duration) {} - - // Ensure waiters do not panic on nil input. It doesn't make sense to - // call a waiter without an input, Validation will - err := client.WaitUntilBucketExists(nil) - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } -} - -func TestWaiterWithContextNilInput(t *testing.T) { - // Code generation doesn't have a great way to verify the code is correct - // other than being run via unit tests in the SDK. This should be fixed - // So code generation can be validated independently. - - client := s3.New(unit.Session) - client.Handlers.Validate.Clear() - client.Handlers.Send.Clear() // mock sending - client.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: http.StatusOK, - } - }) - client.Handlers.Unmarshal.Clear() - client.Handlers.UnmarshalMeta.Clear() - client.Handlers.ValidateResponse.Clear() - - // Ensure waiters do not panic on nil input - ctx := &awstesting.FakeContext{DoneCh: make(chan struct{})} - err := client.WaitUntilBucketExistsWithContext(ctx, nil, - request.WithWaiterDelay(request.ConstantWaiterDelay(0)), - request.WithWaiterMaxAttempts(1), - ) - if err != nil { - t.Fatalf("expect no error, but got %v", err) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_ca_bundle_test.go b/vendor/github.com/aws/aws-sdk-go/aws/session/custom_ca_bundle_test.go deleted file mode 100644 index a89c0af5..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_ca_bundle_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package session - -import ( - "bytes" - "fmt" - "net" - "net/http" - "os" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/awstesting" -) - -var TLSBundleCertFile string -var TLSBundleKeyFile string -var TLSBundleCAFile string - -func TestMain(m *testing.M) { - var err error - - TLSBundleCertFile, TLSBundleKeyFile, TLSBundleCAFile, err = awstesting.CreateTLSBundleFiles() - if err != nil { - panic(err) - } - - fmt.Println("TestMain", TLSBundleCertFile, TLSBundleKeyFile) - - code := m.Run() - - err = awstesting.CleanupTLSBundleFiles(TLSBundleCertFile, TLSBundleKeyFile, TLSBundleCAFile) - if err != nil { - panic(err) - } - - os.Exit(code) -} - -func TestNewSession_WithCustomCABundle_Env(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - os.Setenv("AWS_CA_BUNDLE", TLSBundleCAFile) - - s, err := NewSession(&aws.Config{ - HTTPClient: &http.Client{}, - Endpoint: aws.String(endpoint), - Region: aws.String("mock-region"), - Credentials: credentials.AnonymousCredentials, - }) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if s == nil { - t.Fatalf("expect session to be created, got none") - } - - req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) - resp, err := s.Config.HTTPClient.Do(req) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} - -func TestNewSession_WithCustomCABundle_EnvNotExists(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_CA_BUNDLE", "file-not-exists") - - s, err := NewSession() - if err == nil { - t.Fatalf("expect error, got none") - } - if e, a := "LoadCustomCABundleError", err.(awserr.Error).Code(); e != a { - t.Errorf("expect %s error code, got %s", e, a) - } - if s != nil { - t.Errorf("expect nil session, got %v", s) - } -} - -func TestNewSession_WithCustomCABundle_Option(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - s, err := NewSessionWithOptions(Options{ - Config: aws.Config{ - HTTPClient: &http.Client{}, - Endpoint: aws.String(endpoint), - Region: aws.String("mock-region"), - Credentials: credentials.AnonymousCredentials, - }, - CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), - }) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if s == nil { - t.Fatalf("expect session to be created, got none") - } - - req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) - resp, err := s.Config.HTTPClient.Do(req) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} - -func TestNewSession_WithCustomCABundle_OptionPriority(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - os.Setenv("AWS_CA_BUNDLE", "file-not-exists") - - s, err := NewSessionWithOptions(Options{ - Config: aws.Config{ - HTTPClient: &http.Client{}, - Endpoint: aws.String(endpoint), - Region: aws.String("mock-region"), - Credentials: credentials.AnonymousCredentials, - }, - CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), - }) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if s == nil { - t.Fatalf("expect session to be created, got none") - } - - req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) - resp, err := s.Config.HTTPClient.Do(req) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} - -type mockRoundTripper struct{} - -func (m *mockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { - return nil, nil -} - -func TestNewSession_WithCustomCABundle_UnsupportedTransport(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - s, err := NewSessionWithOptions(Options{ - Config: aws.Config{ - HTTPClient: &http.Client{ - Transport: &mockRoundTripper{}, - }, - }, - CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), - }) - if err == nil { - t.Fatalf("expect error, got none") - } - if e, a := "LoadCustomCABundleError", err.(awserr.Error).Code(); e != a { - t.Errorf("expect %s error code, got %s", e, a) - } - if s != nil { - t.Errorf("expect nil session, got %v", s) - } - aerrMsg := err.(awserr.Error).Message() - if e, a := "transport unsupported type", aerrMsg; !strings.Contains(a, e) { - t.Errorf("expect %s to be in %s", e, a) - } -} - -func TestNewSession_WithCustomCABundle_TransportSet(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - endpoint, err := awstesting.CreateTLSServer(TLSBundleCertFile, TLSBundleKeyFile, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - s, err := NewSessionWithOptions(Options{ - Config: aws.Config{ - Endpoint: aws.String(endpoint), - Region: aws.String("mock-region"), - Credentials: credentials.AnonymousCredentials, - HTTPClient: &http.Client{ - Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).Dial, - TLSHandshakeTimeout: 2 * time.Second, - }, - }, - }, - CustomCABundle: bytes.NewReader(awstesting.TLSBundleCA), - }) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if s == nil { - t.Fatalf("expect session to be created, got none") - } - - req, _ := http.NewRequest("GET", *s.Config.Endpoint, nil) - resp, err := s.Config.HTTPClient.Do(req) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %d status code, got %d", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config_test.go b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config_test.go deleted file mode 100644 index 3a0b6464..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config_test.go +++ /dev/null @@ -1,306 +0,0 @@ -package session - -import ( - "os" - "reflect" - "testing" - - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -func TestLoadEnvConfig_Creds(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - cases := []struct { - Env map[string]string - Val credentials.Value - }{ - { - Env: map[string]string{ - "AWS_ACCESS_KEY": "AKID", - }, - Val: credentials.Value{}, - }, - { - Env: map[string]string{ - "AWS_ACCESS_KEY_ID": "AKID", - }, - Val: credentials.Value{}, - }, - { - Env: map[string]string{ - "AWS_SECRET_KEY": "SECRET", - }, - Val: credentials.Value{}, - }, - { - Env: map[string]string{ - "AWS_SECRET_ACCESS_KEY": "SECRET", - }, - Val: credentials.Value{}, - }, - { - Env: map[string]string{ - "AWS_ACCESS_KEY_ID": "AKID", - "AWS_SECRET_ACCESS_KEY": "SECRET", - }, - Val: credentials.Value{ - AccessKeyID: "AKID", SecretAccessKey: "SECRET", - ProviderName: "EnvConfigCredentials", - }, - }, - { - Env: map[string]string{ - "AWS_ACCESS_KEY": "AKID", - "AWS_SECRET_KEY": "SECRET", - }, - Val: credentials.Value{ - AccessKeyID: "AKID", SecretAccessKey: "SECRET", - ProviderName: "EnvConfigCredentials", - }, - }, - { - Env: map[string]string{ - "AWS_ACCESS_KEY": "AKID", - "AWS_SECRET_KEY": "SECRET", - "AWS_SESSION_TOKEN": "TOKEN", - }, - Val: credentials.Value{ - AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "TOKEN", - ProviderName: "EnvConfigCredentials", - }, - }, - } - - for _, c := range cases { - os.Clearenv() - - for k, v := range c.Env { - os.Setenv(k, v) - } - - cfg := loadEnvConfig() - if !reflect.DeepEqual(c.Val, cfg.Creds) { - t.Errorf("expect credentials to match.\n%s", - awstesting.SprintExpectActual(c.Val, cfg.Creds)) - } - } -} - -func TestLoadEnvConfig(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - cases := []struct { - Env map[string]string - UseSharedConfigCall bool - Config envConfig - }{ - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_PROFILE": "profile", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - }, - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_DEFAULT_REGION": "default_region", - "AWS_PROFILE": "profile", - "AWS_DEFAULT_PROFILE": "default_profile", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - }, - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_DEFAULT_REGION": "default_region", - "AWS_PROFILE": "profile", - "AWS_DEFAULT_PROFILE": "default_profile", - "AWS_SDK_LOAD_CONFIG": "1", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - EnableSharedConfig: true, - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - }, - { - Env: map[string]string{ - "AWS_DEFAULT_REGION": "default_region", - "AWS_DEFAULT_PROFILE": "default_profile", - }, - Config: envConfig{ - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - }, - { - Env: map[string]string{ - "AWS_DEFAULT_REGION": "default_region", - "AWS_DEFAULT_PROFILE": "default_profile", - "AWS_SDK_LOAD_CONFIG": "1", - }, - Config: envConfig{ - Region: "default_region", Profile: "default_profile", - EnableSharedConfig: true, - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - }, - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_PROFILE": "profile", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - EnableSharedConfig: true, - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_DEFAULT_REGION": "default_region", - "AWS_PROFILE": "profile", - "AWS_DEFAULT_PROFILE": "default_profile", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - EnableSharedConfig: true, - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_REGION": "region", - "AWS_DEFAULT_REGION": "default_region", - "AWS_PROFILE": "profile", - "AWS_DEFAULT_PROFILE": "default_profile", - "AWS_SDK_LOAD_CONFIG": "1", - }, - Config: envConfig{ - Region: "region", Profile: "profile", - EnableSharedConfig: true, - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_DEFAULT_REGION": "default_region", - "AWS_DEFAULT_PROFILE": "default_profile", - }, - Config: envConfig{ - Region: "default_region", Profile: "default_profile", - EnableSharedConfig: true, - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_DEFAULT_REGION": "default_region", - "AWS_DEFAULT_PROFILE": "default_profile", - "AWS_SDK_LOAD_CONFIG": "1", - }, - Config: envConfig{ - Region: "default_region", Profile: "default_profile", - EnableSharedConfig: true, - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_CA_BUNDLE": "custom_ca_bundle", - }, - Config: envConfig{ - CustomCABundle: "custom_ca_bundle", - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - }, - { - Env: map[string]string{ - "AWS_CA_BUNDLE": "custom_ca_bundle", - }, - Config: envConfig{ - CustomCABundle: "custom_ca_bundle", - EnableSharedConfig: true, - SharedCredentialsFile: shareddefaults.SharedCredentialsFilename(), - SharedConfigFile: shareddefaults.SharedConfigFilename(), - }, - UseSharedConfigCall: true, - }, - { - Env: map[string]string{ - "AWS_SHARED_CREDENTIALS_FILE": "/path/to/credentials/file", - "AWS_CONFIG_FILE": "/path/to/config/file", - }, - Config: envConfig{ - SharedCredentialsFile: "/path/to/credentials/file", - SharedConfigFile: "/path/to/config/file", - }, - }, - } - - for _, c := range cases { - os.Clearenv() - - for k, v := range c.Env { - os.Setenv(k, v) - } - - var cfg envConfig - if c.UseSharedConfigCall { - cfg = loadSharedEnvConfig() - } else { - cfg = loadEnvConfig() - } - - if !reflect.DeepEqual(c.Config, cfg) { - t.Errorf("expect config to match.\n%s", - awstesting.SprintExpectActual(c.Config, cfg)) - } - } -} - -func TestSetEnvValue(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("empty_key", "") - os.Setenv("second_key", "2") - os.Setenv("third_key", "3") - - var dst string - setFromEnvVal(&dst, []string{ - "empty_key", "first_key", "second_key", "third_key", - }) - - if e, a := "2", dst; e != a { - t.Errorf("expect %s value from environment, got %s", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/session_test.go b/vendor/github.com/aws/aws-sdk-go/aws/session/session_test.go deleted file mode 100644 index 9612b315..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/session_test.go +++ /dev/null @@ -1,446 +0,0 @@ -package session - -import ( - "bytes" - "fmt" - "net/http" - "net/http/httptest" - "os" - "testing" - "time" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/service/s3" -) - -func TestNewDefaultSession(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - s := New(&aws.Config{Region: aws.String("region")}) - - assert.Equal(t, "region", *s.Config.Region) - assert.Equal(t, http.DefaultClient, s.Config.HTTPClient) - assert.NotNil(t, s.Config.Logger) - assert.Equal(t, aws.LogOff, *s.Config.LogLevel) -} - -func TestNew_WithCustomCreds(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - customCreds := credentials.NewStaticCredentials("AKID", "SECRET", "TOKEN") - s := New(&aws.Config{Credentials: customCreds}) - - assert.Equal(t, customCreds, s.Config.Credentials) -} - -type mockLogger struct { - *bytes.Buffer -} - -func (w mockLogger) Log(args ...interface{}) { - fmt.Fprintln(w, args...) -} - -func TestNew_WithSessionLoadError(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_CONFIG_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_invalid_source_profile") - - logger := bytes.Buffer{} - s := New(&aws.Config{Logger: &mockLogger{&logger}}) - - assert.NotNil(t, s) - - svc := s3.New(s) - _, err := svc.ListBuckets(&s3.ListBucketsInput{}) - - assert.Error(t, err) - assert.Contains(t, logger.String(), "ERROR: failed to create session with AWS_SDK_LOAD_CONFIG enabled") - assert.Contains(t, err.Error(), SharedConfigAssumeRoleError{ - RoleARN: "assume_role_invalid_source_profile_role_arn", - }.Error()) -} - -func TestSessionCopy(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_REGION", "orig_region") - - s := Session{ - Config: defaults.Config(), - Handlers: defaults.Handlers(), - } - - newSess := s.Copy(&aws.Config{Region: aws.String("new_region")}) - - assert.Equal(t, "orig_region", *s.Config.Region) - assert.Equal(t, "new_region", *newSess.Config.Region) -} - -func TestSessionClientConfig(t *testing.T) { - s, err := NewSession(&aws.Config{ - Credentials: credentials.AnonymousCredentials, - Region: aws.String("orig_region"), - EndpointResolver: endpoints.ResolverFunc( - func(service, region string, opts ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { - if e, a := "mock-service", service; e != a { - t.Errorf("expect %q service, got %q", e, a) - } - if e, a := "other-region", region; e != a { - t.Errorf("expect %q region, got %q", e, a) - } - return endpoints.ResolvedEndpoint{ - URL: "https://" + service + "." + region + ".amazonaws.com", - SigningRegion: region, - }, nil - }, - ), - }) - assert.NoError(t, err) - - cfg := s.ClientConfig("mock-service", &aws.Config{Region: aws.String("other-region")}) - - assert.Equal(t, "https://mock-service.other-region.amazonaws.com", cfg.Endpoint) - assert.Equal(t, "other-region", cfg.SigningRegion) - assert.Equal(t, "other-region", *cfg.Config.Region) -} - -func TestNewSession_NoCredentials(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - s, err := NewSession() - assert.NoError(t, err) - - assert.NotNil(t, s.Config.Credentials) - assert.NotEqual(t, credentials.AnonymousCredentials, s.Config.Credentials) -} - -func TestNewSessionWithOptions_OverrideProfile(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "other_profile") - - s, err := NewSessionWithOptions(Options{ - Profile: "full_profile", - }) - assert.NoError(t, err) - - assert.Equal(t, "full_profile_region", *s.Config.Region) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "full_profile_akid", creds.AccessKeyID) - assert.Equal(t, "full_profile_secret", creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.Contains(t, creds.ProviderName, "SharedConfigCredentials") -} - -func TestNewSessionWithOptions_OverrideSharedConfigEnable(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "0") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "full_profile") - - s, err := NewSessionWithOptions(Options{ - SharedConfigState: SharedConfigEnable, - }) - assert.NoError(t, err) - - assert.Equal(t, "full_profile_region", *s.Config.Region) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "full_profile_akid", creds.AccessKeyID) - assert.Equal(t, "full_profile_secret", creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.Contains(t, creds.ProviderName, "SharedConfigCredentials") -} - -func TestNewSessionWithOptions_OverrideSharedConfigDisable(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "full_profile") - - s, err := NewSessionWithOptions(Options{ - SharedConfigState: SharedConfigDisable, - }) - assert.NoError(t, err) - - assert.Empty(t, *s.Config.Region) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "full_profile_akid", creds.AccessKeyID) - assert.Equal(t, "full_profile_secret", creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.Contains(t, creds.ProviderName, "SharedConfigCredentials") -} - -func TestNewSessionWithOptions_OverrideSharedConfigFiles(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "config_file_load_order") - - s, err := NewSessionWithOptions(Options{ - SharedConfigFiles: []string{testConfigOtherFilename}, - }) - assert.NoError(t, err) - - assert.Equal(t, "shared_config_other_region", *s.Config.Region) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "shared_config_other_akid", creds.AccessKeyID) - assert.Equal(t, "shared_config_other_secret", creds.SecretAccessKey) - assert.Empty(t, creds.SessionToken) - assert.Contains(t, creds.ProviderName, "SharedConfigCredentials") -} - -func TestNewSessionWithOptions_Overrides(t *testing.T) { - cases := []struct { - InEnvs map[string]string - InProfile string - OutRegion string - OutCreds credentials.Value - }{ - { - InEnvs: map[string]string{ - "AWS_SDK_LOAD_CONFIG": "0", - "AWS_SHARED_CREDENTIALS_FILE": testConfigFilename, - "AWS_PROFILE": "other_profile", - }, - InProfile: "full_profile", - OutRegion: "full_profile_region", - OutCreds: credentials.Value{ - AccessKeyID: "full_profile_akid", - SecretAccessKey: "full_profile_secret", - ProviderName: "SharedConfigCredentials", - }, - }, - { - InEnvs: map[string]string{ - "AWS_SDK_LOAD_CONFIG": "0", - "AWS_SHARED_CREDENTIALS_FILE": testConfigFilename, - "AWS_REGION": "env_region", - "AWS_ACCESS_KEY": "env_akid", - "AWS_SECRET_ACCESS_KEY": "env_secret", - "AWS_PROFILE": "other_profile", - }, - InProfile: "full_profile", - OutRegion: "env_region", - OutCreds: credentials.Value{ - AccessKeyID: "env_akid", - SecretAccessKey: "env_secret", - ProviderName: "EnvConfigCredentials", - }, - }, - { - InEnvs: map[string]string{ - "AWS_SDK_LOAD_CONFIG": "0", - "AWS_SHARED_CREDENTIALS_FILE": testConfigFilename, - "AWS_CONFIG_FILE": testConfigOtherFilename, - "AWS_PROFILE": "shared_profile", - }, - InProfile: "config_file_load_order", - OutRegion: "shared_config_region", - OutCreds: credentials.Value{ - AccessKeyID: "shared_config_akid", - SecretAccessKey: "shared_config_secret", - ProviderName: "SharedConfigCredentials", - }, - }, - } - - for _, c := range cases { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - for k, v := range c.InEnvs { - os.Setenv(k, v) - } - - s, err := NewSessionWithOptions(Options{ - Profile: c.InProfile, - SharedConfigState: SharedConfigEnable, - }) - assert.NoError(t, err) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, c.OutRegion, *s.Config.Region) - assert.Equal(t, c.OutCreds.AccessKeyID, creds.AccessKeyID) - assert.Equal(t, c.OutCreds.SecretAccessKey, creds.SecretAccessKey) - assert.Equal(t, c.OutCreds.SessionToken, creds.SessionToken) - assert.Contains(t, creds.ProviderName, c.OutCreds.ProviderName) - } -} - -const assumeRoleRespMsg = ` - - - - arn:aws:sts::account_id:assumed-role/role/session_name - AKID:session_name - - - AKID - SECRET - SESSION_TOKEN - %s - - - - request-id - - -` - -func TestSesisonAssumeRole(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_REGION", "us-east-1") - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_w_creds") - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(fmt.Sprintf(assumeRoleRespMsg, time.Now().Add(15*time.Minute).Format("2006-01-02T15:04:05Z")))) - })) - - s, err := NewSession(&aws.Config{Endpoint: aws.String(server.URL), DisableSSL: aws.Bool(true)}) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "AKID", creds.AccessKeyID) - assert.Equal(t, "SECRET", creds.SecretAccessKey) - assert.Equal(t, "SESSION_TOKEN", creds.SessionToken) - assert.Contains(t, creds.ProviderName, "AssumeRoleProvider") -} - -func TestSessionAssumeRole_WithMFA(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_REGION", "us-east-1") - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_w_creds") - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.FormValue("SerialNumber"), "0123456789") - assert.Equal(t, r.FormValue("TokenCode"), "tokencode") - - w.Write([]byte(fmt.Sprintf(assumeRoleRespMsg, time.Now().Add(15*time.Minute).Format("2006-01-02T15:04:05Z")))) - })) - - customProviderCalled := false - sess, err := NewSessionWithOptions(Options{ - Profile: "assume_role_w_mfa", - Config: aws.Config{ - Region: aws.String("us-east-1"), - Endpoint: aws.String(server.URL), - DisableSSL: aws.Bool(true), - }, - SharedConfigState: SharedConfigEnable, - AssumeRoleTokenProvider: func() (string, error) { - customProviderCalled = true - - return "tokencode", nil - }, - }) - assert.NoError(t, err) - - creds, err := sess.Config.Credentials.Get() - assert.NoError(t, err) - assert.True(t, customProviderCalled) - - assert.Equal(t, "AKID", creds.AccessKeyID) - assert.Equal(t, "SECRET", creds.SecretAccessKey) - assert.Equal(t, "SESSION_TOKEN", creds.SessionToken) - assert.Contains(t, creds.ProviderName, "AssumeRoleProvider") -} - -func TestSessionAssumeRole_WithMFA_NoTokenProvider(t *testing.T) { - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_REGION", "us-east-1") - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_w_creds") - - _, err := NewSessionWithOptions(Options{ - Profile: "assume_role_w_mfa", - SharedConfigState: SharedConfigEnable, - }) - assert.Equal(t, err, AssumeRoleTokenProviderNotSetError{}) -} - -func TestSessionAssumeRole_DisableSharedConfig(t *testing.T) { - // Backwards compatibility with Shared config disabled - // assume role should not be built into the config. - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "0") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_w_creds") - - s, err := NewSession() - assert.NoError(t, err) - - creds, err := s.Config.Credentials.Get() - assert.NoError(t, err) - assert.Equal(t, "assume_role_w_creds_akid", creds.AccessKeyID) - assert.Equal(t, "assume_role_w_creds_secret", creds.SecretAccessKey) - assert.Contains(t, creds.ProviderName, "SharedConfigCredentials") -} - -func TestSessionAssumeRole_InvalidSourceProfile(t *testing.T) { - // Backwards compatibility with Shared config disabled - // assume role should not be built into the config. - oldEnv := initSessionTestEnv() - defer awstesting.PopEnv(oldEnv) - - os.Setenv("AWS_SDK_LOAD_CONFIG", "1") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", testConfigFilename) - os.Setenv("AWS_PROFILE", "assume_role_invalid_source_profile") - - s, err := NewSession() - assert.Error(t, err) - assert.Contains(t, err.Error(), "SharedConfigAssumeRoleError: failed to load assume role") - assert.Nil(t, s) -} - -func initSessionTestEnv() (oldEnv []string) { - oldEnv = awstesting.StashEnv() - os.Setenv("AWS_CONFIG_FILE", "file_not_exists") - os.Setenv("AWS_SHARED_CREDENTIALS_FILE", "file_not_exists") - - return oldEnv -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config_test.go b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config_test.go deleted file mode 100644 index 3a07b8d9..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config_test.go +++ /dev/null @@ -1,274 +0,0 @@ -package session - -import ( - "fmt" - "path/filepath" - "testing" - - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/go-ini/ini" - "github.com/stretchr/testify/assert" -) - -var ( - testConfigFilename = filepath.Join("testdata", "shared_config") - testConfigOtherFilename = filepath.Join("testdata", "shared_config_other") -) - -func TestLoadSharedConfig(t *testing.T) { - cases := []struct { - Filenames []string - Profile string - Expected sharedConfig - Err error - }{ - { - Filenames: []string{"file_not_exists"}, - Profile: "default", - }, - { - Filenames: []string{testConfigFilename}, - Expected: sharedConfig{ - Region: "default_region", - }, - }, - { - Filenames: []string{testConfigOtherFilename, testConfigFilename}, - Profile: "config_file_load_order", - Expected: sharedConfig{ - Region: "shared_config_region", - Creds: credentials.Value{ - AccessKeyID: "shared_config_akid", - SecretAccessKey: "shared_config_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - }, - }, - { - Filenames: []string{testConfigFilename, testConfigOtherFilename}, - Profile: "config_file_load_order", - Expected: sharedConfig{ - Region: "shared_config_other_region", - Creds: credentials.Value{ - AccessKeyID: "shared_config_other_akid", - SecretAccessKey: "shared_config_other_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigOtherFilename), - }, - }, - }, - { - Filenames: []string{testConfigOtherFilename, testConfigFilename}, - Profile: "assume_role", - Expected: sharedConfig{ - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_role_arn", - SourceProfile: "complete_creds", - }, - AssumeRoleSource: &sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "complete_creds_akid", - SecretAccessKey: "complete_creds_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - }, - }, - }, - { - Filenames: []string{testConfigOtherFilename, testConfigFilename}, - Profile: "assume_role_invalid_source_profile", - Expected: sharedConfig{ - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_invalid_source_profile_role_arn", - SourceProfile: "profile_not_exists", - }, - }, - Err: SharedConfigAssumeRoleError{RoleARN: "assume_role_invalid_source_profile_role_arn"}, - }, - { - Filenames: []string{testConfigOtherFilename, testConfigFilename}, - Profile: "assume_role_w_creds", - Expected: sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "assume_role_w_creds_akid", - SecretAccessKey: "assume_role_w_creds_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_w_creds_role_arn", - SourceProfile: "assume_role_w_creds", - ExternalID: "1234", - RoleSessionName: "assume_role_w_creds_session_name", - }, - AssumeRoleSource: &sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "assume_role_w_creds_akid", - SecretAccessKey: "assume_role_w_creds_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - }, - }, - }, - { - Filenames: []string{testConfigOtherFilename, testConfigFilename}, - Profile: "assume_role_wo_creds", - Expected: sharedConfig{ - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_wo_creds_role_arn", - SourceProfile: "assume_role_wo_creds", - }, - }, - Err: SharedConfigAssumeRoleError{RoleARN: "assume_role_wo_creds_role_arn"}, - }, - { - Filenames: []string{filepath.Join("testdata", "shared_config_invalid_ini")}, - Profile: "profile_name", - Err: SharedConfigLoadError{Filename: filepath.Join("testdata", "shared_config_invalid_ini")}, - }, - } - - for i, c := range cases { - cfg, err := loadSharedConfig(c.Profile, c.Filenames) - if c.Err != nil { - assert.Contains(t, err.Error(), c.Err.Error(), "expected error, %d", i) - continue - } - - assert.NoError(t, err, "unexpected error, %d", i) - assert.Equal(t, c.Expected, cfg, "not equal, %d", i) - } -} - -func TestLoadSharedConfigFromFile(t *testing.T) { - filename := testConfigFilename - f, err := ini.Load(filename) - if err != nil { - t.Fatalf("failed to load test config file, %s, %v", filename, err) - } - iniFile := sharedConfigFile{IniData: f, Filename: filename} - - cases := []struct { - Profile string - Expected sharedConfig - Err error - }{ - { - Profile: "default", - Expected: sharedConfig{Region: "default_region"}, - }, - { - Profile: "alt_profile_name", - Expected: sharedConfig{Region: "alt_profile_name_region"}, - }, - { - Profile: "short_profile_name_first", - Expected: sharedConfig{Region: "short_profile_name_first_short"}, - }, - { - Profile: "partial_creds", - Expected: sharedConfig{}, - }, - { - Profile: "complete_creds", - Expected: sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "complete_creds_akid", - SecretAccessKey: "complete_creds_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - }, - }, - { - Profile: "complete_creds_with_token", - Expected: sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "complete_creds_with_token_akid", - SecretAccessKey: "complete_creds_with_token_secret", - SessionToken: "complete_creds_with_token_token", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - }, - }, - { - Profile: "full_profile", - Expected: sharedConfig{ - Creds: credentials.Value{ - AccessKeyID: "full_profile_akid", - SecretAccessKey: "full_profile_secret", - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", testConfigFilename), - }, - Region: "full_profile_region", - }, - }, - { - Profile: "partial_assume_role", - Expected: sharedConfig{}, - }, - { - Profile: "assume_role", - Expected: sharedConfig{ - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_role_arn", - SourceProfile: "complete_creds", - }, - }, - }, - { - Profile: "assume_role_w_mfa", - Expected: sharedConfig{ - AssumeRole: assumeRoleConfig{ - RoleARN: "assume_role_role_arn", - SourceProfile: "complete_creds", - MFASerial: "0123456789", - }, - }, - }, - { - Profile: "does_not_exists", - Err: SharedConfigProfileNotExistsError{Profile: "does_not_exists"}, - }, - } - - for i, c := range cases { - cfg := sharedConfig{} - - err := cfg.setFromIniFile(c.Profile, iniFile) - if c.Err != nil { - assert.Contains(t, err.Error(), c.Err.Error(), "expected error, %d", i) - continue - } - - assert.NoError(t, err, "unexpected error, %d", i) - assert.Equal(t, c.Expected, cfg, "not equal, %d", i) - } -} - -func TestLoadSharedConfigIniFiles(t *testing.T) { - cases := []struct { - Filenames []string - Expected []sharedConfigFile - }{ - { - Filenames: []string{"not_exists", testConfigFilename}, - Expected: []sharedConfigFile{ - {Filename: testConfigFilename}, - }, - }, - { - Filenames: []string{testConfigFilename, testConfigOtherFilename}, - Expected: []sharedConfigFile{ - {Filename: testConfigFilename}, - {Filename: testConfigOtherFilename}, - }, - }, - } - - for i, c := range cases { - files, err := loadSharedConfigIniFiles(c.Filenames) - assert.NoError(t, err, "unexpected error, %d", i) - assert.Equal(t, len(c.Expected), len(files), "expected num files, %d", i) - - for i, expectedFile := range c.Expected { - assert.Equal(t, expectedFile.Filename, files[i].Filename) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_1_5_test.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_1_5_test.go deleted file mode 100644 index 2e591c27..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_1_5_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// +build go1.5 - -package v4_test - -import ( - "fmt" - "net/http" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting/unit" -) - -func TestStandaloneSign(t *testing.T) { - creds := unit.Session.Config.Credentials - signer := v4.NewSigner(creds) - - for _, c := range standaloneSignCases { - host := fmt.Sprintf("https://%s.%s.%s.amazonaws.com", - c.SubDomain, c.Region, c.Service) - - req, err := http.NewRequest("GET", host, nil) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - - // URL.EscapedPath() will be used by the signer to get the - // escaped form of the request's URI path. - req.URL.Path = c.OrigURI - req.URL.RawQuery = c.OrigQuery - - _, err = signer.Sign(req, nil, c.Service, c.Region, time.Unix(0, 0)) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - - actual := req.Header.Get("Authorization") - if e, a := c.ExpSig, actual; e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - if e, a := c.OrigURI, req.URL.Path; e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - if e, a := c.EscapedURI, req.URL.EscapedPath(); e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - } -} - -func TestStandaloneSign_RawPath(t *testing.T) { - creds := unit.Session.Config.Credentials - signer := v4.NewSigner(creds) - - for _, c := range standaloneSignCases { - host := fmt.Sprintf("https://%s.%s.%s.amazonaws.com", - c.SubDomain, c.Region, c.Service) - - req, err := http.NewRequest("GET", host, nil) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - - // URL.EscapedPath() will be used by the signer to get the - // escaped form of the request's URI path. - req.URL.Path = c.OrigURI - req.URL.RawPath = c.EscapedURI - req.URL.RawQuery = c.OrigQuery - - _, err = signer.Sign(req, nil, c.Service, c.Region, time.Unix(0, 0)) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - - actual := req.Header.Get("Authorization") - if e, a := c.ExpSig, actual; e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - if e, a := c.OrigURI, req.URL.Path; e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - if e, a := c.EscapedURI, req.URL.EscapedPath(); e != a { - t.Errorf("expected %v, but recieved %v", e, a) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_test.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_test.go deleted file mode 100644 index 81749452..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/functional_test.go +++ /dev/null @@ -1,254 +0,0 @@ -package v4_test - -import ( - "net/http" - "net/url" - "reflect" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/s3" -) - -var standaloneSignCases = []struct { - OrigURI string - OrigQuery string - Region, Service, SubDomain string - ExpSig string - EscapedURI string -}{ - { - OrigURI: `/logs-*/_search`, - OrigQuery: `pretty=true`, - Region: "us-west-2", Service: "es", SubDomain: "hostname-clusterkey", - EscapedURI: `/logs-%2A/_search`, - ExpSig: `AWS4-HMAC-SHA256 Credential=AKID/19700101/us-west-2/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=79d0760751907af16f64a537c1242416dacf51204a7dd5284492d15577973b91`, - }, -} - -func TestPresignHandler(t *testing.T) { - svc := s3.New(unit.Session) - req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ - Bucket: aws.String("bucket"), - Key: aws.String("key"), - ContentDisposition: aws.String("a+b c$d"), - ACL: aws.String("public-read"), - }) - req.Time = time.Unix(0, 0) - urlstr, err := req.Presign(5 * time.Minute) - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - expectedHost := "bucket.s3.mock-region.amazonaws.com" - expectedDate := "19700101T000000Z" - expectedHeaders := "content-disposition;host;x-amz-acl" - expectedSig := "2d76a414208c0eac2a23ef9c834db9635ecd5a0fbb447a00ad191f82d854f55b" - expectedCred := "AKID/19700101/mock-region/s3/aws4_request" - - u, _ := url.Parse(urlstr) - urlQ := u.Query() - if e, a := expectedHost, u.Host; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedSig, urlQ.Get("X-Amz-Signature"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedCred, urlQ.Get("X-Amz-Credential"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedHeaders, urlQ.Get("X-Amz-SignedHeaders"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedDate, urlQ.Get("X-Amz-Date"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "300", urlQ.Get("X-Amz-Expires"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if a := urlQ.Get("X-Amz-Content-Sha256"); len(a) != 0 { - t.Errorf("expect no content sha256 got %v", a) - } - - if e, a := "+", urlstr; strings.Contains(a, e) { // + encoded as %20 - t.Errorf("expect %v not to be in %v", e, a) - } -} - -func TestPresignRequest(t *testing.T) { - svc := s3.New(unit.Session) - req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ - Bucket: aws.String("bucket"), - Key: aws.String("key"), - ContentDisposition: aws.String("a+b c$d"), - ACL: aws.String("public-read"), - }) - req.Time = time.Unix(0, 0) - urlstr, headers, err := req.PresignRequest(5 * time.Minute) - - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - expectedHost := "bucket.s3.mock-region.amazonaws.com" - expectedDate := "19700101T000000Z" - expectedHeaders := "content-disposition;host;x-amz-acl" - expectedSig := "2d76a414208c0eac2a23ef9c834db9635ecd5a0fbb447a00ad191f82d854f55b" - expectedCred := "AKID/19700101/mock-region/s3/aws4_request" - expectedHeaderMap := http.Header{ - "x-amz-acl": []string{"public-read"}, - "content-disposition": []string{"a+b c$d"}, - } - - u, _ := url.Parse(urlstr) - urlQ := u.Query() - if e, a := expectedHost, u.Host; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedSig, urlQ.Get("X-Amz-Signature"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedCred, urlQ.Get("X-Amz-Credential"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedHeaders, urlQ.Get("X-Amz-SignedHeaders"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedDate, urlQ.Get("X-Amz-Date"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedHeaderMap, headers; !reflect.DeepEqual(e, a) { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "300", urlQ.Get("X-Amz-Expires"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if a := urlQ.Get("X-Amz-Content-Sha256"); len(a) != 0 { - t.Errorf("expect no content sha256 got %v", a) - } - - if e, a := "+", urlstr; strings.Contains(a, e) { // + encoded as %20 - t.Errorf("expect %v not to be in %v", e, a) - } -} - -func TestStandaloneSign_CustomURIEscape(t *testing.T) { - var expectSig = `AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=6601e883cc6d23871fd6c2a394c5677ea2b8c82b04a6446786d64cd74f520967` - - creds := unit.Session.Config.Credentials - signer := v4.NewSigner(creds, func(s *v4.Signer) { - s.DisableURIPathEscaping = true - }) - - host := "https://subdomain.us-east-1.es.amazonaws.com" - req, err := http.NewRequest("GET", host, nil) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - req.URL.Path = `/log-*/_search` - req.URL.Opaque = "//subdomain.us-east-1.es.amazonaws.com/log-%2A/_search" - - _, err = signer.Sign(req, nil, "es", "us-east-1", time.Unix(0, 0)) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - actual := req.Header.Get("Authorization") - if e, a := expectSig, actual; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestStandaloneSign_WithPort(t *testing.T) { - - cases := []struct { - description string - url string - expectedSig string - }{ - { - "default HTTPS port", - "https://estest.us-east-1.es.amazonaws.com:443/_search", - "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=e573fc9aa3a156b720976419319be98fb2824a3abc2ddd895ecb1d1611c6a82d", - }, - { - "default HTTP port", - "http://example.com:80/_search", - "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=54ebe60c4ae03a40948b849e13c333523235f38002e2807059c64a9a8c7cb951", - }, - { - "non-standard HTTP port", - "http://example.com:9200/_search", - "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=cd9d926a460f8d3b58b57beadbd87666dc667e014c0afaa4cea37b2867f51b4f", - }, - { - "non-standard HTTPS port", - "https://example.com:9200/_search", - "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/es/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=cd9d926a460f8d3b58b57beadbd87666dc667e014c0afaa4cea37b2867f51b4f", - }, - } - - for _, c := range cases { - signer := v4.NewSigner(unit.Session.Config.Credentials) - req, _ := http.NewRequest("GET", c.url, nil) - _, err := signer.Sign(req, nil, "es", "us-east-1", time.Unix(0, 0)) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - actual := req.Header.Get("Authorization") - if e, a := c.expectedSig, actual; e != a { - t.Errorf("%s, expect %v, got %v", c.description, e, a) - } - } -} - -func TestStandalonePresign_WithPort(t *testing.T) { - - cases := []struct { - description string - url string - expectedSig string - }{ - { - "default HTTPS port", - "https://estest.us-east-1.es.amazonaws.com:443/_search", - "0abcf61a351063441296febf4b485734d780634fba8cf1e7d9769315c35255d6", - }, - { - "default HTTP port", - "http://example.com:80/_search", - "fce9976dd6c849c21adfa6d3f3e9eefc651d0e4a2ccd740d43efddcccfdc8179", - }, - { - "non-standard HTTP port", - "http://example.com:9200/_search", - "f33c25a81c735e42bef35ed5e9f720c43940562e3e616ff0777bf6dde75249b0", - }, - { - "non-standard HTTPS port", - "https://example.com:9200/_search", - "f33c25a81c735e42bef35ed5e9f720c43940562e3e616ff0777bf6dde75249b0", - }, - } - - for _, c := range cases { - signer := v4.NewSigner(unit.Session.Config.Credentials) - req, _ := http.NewRequest("GET", c.url, nil) - _, err := signer.Presign(req, nil, "es", "us-east-1", 5*time.Minute, time.Unix(0, 0)) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - actual := req.URL.Query().Get("X-Amz-Signature") - if e, a := c.expectedSig, actual; e != a { - t.Errorf("%s, expect %v, got %v", c.description, e, a) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules_test.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules_test.go deleted file mode 100644 index f4be951a..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package v4 - -import ( - "testing" -) - -func TestRuleCheckWhitelist(t *testing.T) { - w := whitelist{ - mapRule{ - "Cache-Control": struct{}{}, - }, - } - - if !w.IsValid("Cache-Control") { - t.Error("expected true value") - } - if w.IsValid("Cache-") { - t.Error("expected false value") - } -} - -func TestRuleCheckBlacklist(t *testing.T) { - b := blacklist{ - mapRule{ - "Cache-Control": struct{}{}, - }, - } - - if b.IsValid("Cache-Control") { - t.Error("expected false value") - } - if !b.IsValid("Cache-") { - t.Error("expected true value") - } -} - -func TestRuleCheckPattern(t *testing.T) { - p := patterns{"X-Amz-Meta-"} - - if !p.IsValid("X-Amz-Meta-") { - t.Error("expected true value") - } - if !p.IsValid("X-Amz-Meta-Star") { - t.Error("expected true value") - } - if p.IsValid("Cache-") { - t.Error("expected false value") - } -} - -func TestRuleComplexWhitelist(t *testing.T) { - w := rules{ - whitelist{ - mapRule{ - "Cache-Control": struct{}{}, - }, - }, - patterns{"X-Amz-Meta-"}, - } - - r := rules{ - inclusiveRules{patterns{"X-Amz-"}, blacklist{w}}, - } - - if !r.IsValid("X-Amz-Blah") { - t.Error("expected true value") - } - if r.IsValid("X-Amz-Meta-") { - t.Error("expected false value") - } - if r.IsValid("X-Amz-Meta-Star") { - t.Error("expected false value") - } - if r.IsValid("Cache-Control") { - t.Error("expected false value") - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4_test.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4_test.go deleted file mode 100644 index 09c054d0..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4_test.go +++ /dev/null @@ -1,737 +0,0 @@ -package v4 - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "reflect" - "strconv" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" -) - -func TestStripExcessHeaders(t *testing.T) { - vals := []string{ - "", - "123", - "1 2 3", - "1 2 3 ", - " 1 2 3", - "1 2 3", - "1 23", - "1 2 3", - "1 2 ", - " 1 2 ", - "12 3", - "12 3 1", - "12 3 1", - "12 3 1abc123", - } - - expected := []string{ - "", - "123", - "1 2 3", - "1 2 3", - "1 2 3", - "1 2 3", - "1 23", - "1 2 3", - "1 2", - "1 2", - "12 3", - "12 3 1", - "12 3 1", - "12 3 1abc123", - } - - stripExcessSpaces(vals) - for i := 0; i < len(vals); i++ { - if e, a := expected[i], vals[i]; e != a { - t.Errorf("%d, expect %v, got %v", i, e, a) - } - } -} - -func buildRequest(serviceName, region, body string) (*http.Request, io.ReadSeeker) { - reader := strings.NewReader(body) - return buildRequestWithBodyReader(serviceName, region, reader) -} - -func buildRequestWithBodyReader(serviceName, region string, body io.Reader) (*http.Request, io.ReadSeeker) { - var bodyLen int - - type lenner interface { - Len() int - } - if lr, ok := body.(lenner); ok { - bodyLen = lr.Len() - } - - endpoint := "https://" + serviceName + "." + region + ".amazonaws.com" - req, _ := http.NewRequest("POST", endpoint, body) - req.URL.Opaque = "//example.org/bucket/key-._~,!@#$%^&*()" - req.Header.Set("X-Amz-Target", "prefix.Operation") - req.Header.Set("Content-Type", "application/x-amz-json-1.0") - - if bodyLen > 0 { - req.Header.Set("Content-Length", strconv.Itoa(bodyLen)) - } - - req.Header.Set("X-Amz-Meta-Other-Header", "some-value=!@#$%^&* (+)") - req.Header.Add("X-Amz-Meta-Other-Header_With_Underscore", "some-value=!@#$%^&* (+)") - req.Header.Add("X-amz-Meta-Other-Header_With_Underscore", "some-value=!@#$%^&* (+)") - - var seeker io.ReadSeeker - if sr, ok := body.(io.ReadSeeker); ok { - seeker = sr - } else { - seeker = aws.ReadSeekCloser(body) - } - - return req, seeker -} - -func buildSigner() Signer { - return Signer{ - Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), - } -} - -func removeWS(text string) string { - text = strings.Replace(text, " ", "", -1) - text = strings.Replace(text, "\n", "", -1) - text = strings.Replace(text, "\t", "", -1) - return text -} - -func assertEqual(t *testing.T, expected, given string) { - if removeWS(expected) != removeWS(given) { - t.Errorf("\nExpected: %s\nGiven: %s", expected, given) - } -} - -func TestPresignRequest(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "{}") - - signer := buildSigner() - signer.Presign(req, body, "dynamodb", "us-east-1", 300*time.Second, time.Unix(0, 0)) - - expectedDate := "19700101T000000Z" - expectedHeaders := "content-length;content-type;host;x-amz-meta-other-header;x-amz-meta-other-header_with_underscore" - expectedSig := "122f0b9e091e4ba84286097e2b3404a1f1f4c4aad479adda95b7dff0ccbe5581" - expectedCred := "AKID/19700101/us-east-1/dynamodb/aws4_request" - expectedTarget := "prefix.Operation" - - q := req.URL.Query() - if e, a := expectedSig, q.Get("X-Amz-Signature"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedCred, q.Get("X-Amz-Credential"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedHeaders, q.Get("X-Amz-SignedHeaders"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedDate, q.Get("X-Amz-Date"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if a := q.Get("X-Amz-Meta-Other-Header"); len(a) != 0 { - t.Errorf("expect %v to be empty", a) - } - if e, a := expectedTarget, q.Get("X-Amz-Target"); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestPresignBodyWithArrayRequest(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "{}") - req.URL.RawQuery = "Foo=z&Foo=o&Foo=m&Foo=a" - - signer := buildSigner() - signer.Presign(req, body, "dynamodb", "us-east-1", 300*time.Second, time.Unix(0, 0)) - - expectedDate := "19700101T000000Z" - expectedHeaders := "content-length;content-type;host;x-amz-meta-other-header;x-amz-meta-other-header_with_underscore" - expectedSig := "e3ac55addee8711b76c6d608d762cff285fe8b627a057f8b5ec9268cf82c08b1" - expectedCred := "AKID/19700101/us-east-1/dynamodb/aws4_request" - expectedTarget := "prefix.Operation" - - q := req.URL.Query() - if e, a := expectedSig, q.Get("X-Amz-Signature"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedCred, q.Get("X-Amz-Credential"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedHeaders, q.Get("X-Amz-SignedHeaders"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := expectedDate, q.Get("X-Amz-Date"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if a := q.Get("X-Amz-Meta-Other-Header"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - if e, a := expectedTarget, q.Get("X-Amz-Target"); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignRequest(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "{}") - signer := buildSigner() - signer.Sign(req, body, "dynamodb", "us-east-1", time.Unix(0, 0)) - - expectedDate := "19700101T000000Z" - expectedSig := "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/dynamodb/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date;x-amz-meta-other-header;x-amz-meta-other-header_with_underscore;x-amz-security-token;x-amz-target, Signature=a518299330494908a70222cec6899f6f32f297f8595f6df1776d998936652ad9" - - q := req.Header - if e, a := expectedSig, q.Get("Authorization"); e != a { - t.Errorf("expect\n%v\nactual\n%v\n", e, a) - } - if e, a := expectedDate, q.Get("X-Amz-Date"); e != a { - t.Errorf("expect\n%v\nactual\n%v\n", e, a) - } -} - -func TestSignBodyS3(t *testing.T) { - req, body := buildRequest("s3", "us-east-1", "hello") - signer := buildSigner() - signer.Sign(req, body, "s3", "us-east-1", time.Now()) - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignBodyGlacier(t *testing.T) { - req, body := buildRequest("glacier", "us-east-1", "hello") - signer := buildSigner() - signer.Sign(req, body, "glacier", "us-east-1", time.Now()) - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestPresign_SignedPayload(t *testing.T) { - req, body := buildRequest("glacier", "us-east-1", "hello") - signer := buildSigner() - signer.Presign(req, body, "glacier", "us-east-1", 5*time.Minute, time.Now()) - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestPresign_UnsignedPayload(t *testing.T) { - req, body := buildRequest("service-name", "us-east-1", "hello") - signer := buildSigner() - signer.UnsignedPayload = true - signer.Presign(req, body, "service-name", "us-east-1", 5*time.Minute, time.Now()) - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "UNSIGNED-PAYLOAD", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestPresign_UnsignedPayload_S3(t *testing.T) { - req, body := buildRequest("s3", "us-east-1", "hello") - signer := buildSigner() - signer.Presign(req, body, "s3", "us-east-1", 5*time.Minute, time.Now()) - if a := req.Header.Get("X-Amz-Content-Sha256"); len(a) != 0 { - t.Errorf("expect no content sha256 got %v", a) - } -} - -func TestSignUnseekableBody(t *testing.T) { - req, body := buildRequestWithBodyReader("mock-service", "mock-region", bytes.NewBuffer([]byte("hello"))) - signer := buildSigner() - _, err := signer.Sign(req, body, "mock-service", "mock-region", time.Now()) - if err == nil { - t.Fatalf("expect error signing request") - } - - if e, a := "unseekable request body", err.Error(); !strings.Contains(a, e) { - t.Errorf("expect %q to be in %q", e, a) - } -} - -func TestSignUnsignedPayloadUnseekableBody(t *testing.T) { - req, body := buildRequestWithBodyReader("mock-service", "mock-region", bytes.NewBuffer([]byte("hello"))) - - signer := buildSigner() - signer.UnsignedPayload = true - - _, err := signer.Sign(req, body, "mock-service", "mock-region", time.Now()) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "UNSIGNED-PAYLOAD", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignPreComputedHashUnseekableBody(t *testing.T) { - req, body := buildRequestWithBodyReader("mock-service", "mock-region", bytes.NewBuffer([]byte("hello"))) - - signer := buildSigner() - - req.Header.Set("X-Amz-Content-Sha256", "some-content-sha256") - _, err := signer.Sign(req, body, "mock-service", "mock-region", time.Now()) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "some-content-sha256", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignPrecomputedBodyChecksum(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "hello") - req.Header.Set("X-Amz-Content-Sha256", "PRECOMPUTED") - signer := buildSigner() - signer.Sign(req, body, "dynamodb", "us-east-1", time.Now()) - hash := req.Header.Get("X-Amz-Content-Sha256") - if e, a := "PRECOMPUTED", hash; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestAnonymousCredentials(t *testing.T) { - svc := awstesting.NewClient(&aws.Config{Credentials: credentials.AnonymousCredentials}) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - SignSDKRequest(r) - - urlQ := r.HTTPRequest.URL.Query() - if a := urlQ.Get("X-Amz-Signature"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - if a := urlQ.Get("X-Amz-Credential"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - if a := urlQ.Get("X-Amz-SignedHeaders"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - if a := urlQ.Get("X-Amz-Date"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - - hQ := r.HTTPRequest.Header - if a := hQ.Get("Authorization"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } - if a := hQ.Get("X-Amz-Date"); len(a) != 0 { - t.Errorf("expect %v to be empty, was not", a) - } -} - -func TestIgnoreResignRequestWithValidCreds(t *testing.T) { - svc := awstesting.NewClient(&aws.Config{ - Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), - Region: aws.String("us-west-2"), - }) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - - SignSDKRequest(r) - sig := r.HTTPRequest.Header.Get("Authorization") - - signSDKRequestWithCurrTime(r, func() time.Time { - // Simulate one second has passed so that signature's date changes - // when it is resigned. - return time.Now().Add(1 * time.Second) - }) - if e, a := sig, r.HTTPRequest.Header.Get("Authorization"); e == a { - t.Errorf("expect %v to be %v, but was not", e, a) - } -} - -func TestIgnorePreResignRequestWithValidCreds(t *testing.T) { - svc := awstesting.NewClient(&aws.Config{ - Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), - Region: aws.String("us-west-2"), - }) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - r.ExpireTime = time.Minute * 10 - - SignSDKRequest(r) - sig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature") - - signSDKRequestWithCurrTime(r, func() time.Time { - // Simulate one second has passed so that signature's date changes - // when it is resigned. - return time.Now().Add(1 * time.Second) - }) - if e, a := sig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature"); e == a { - t.Errorf("expect %v to be %v, but was not", e, a) - } -} - -func TestResignRequestExpiredCreds(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - svc := awstesting.NewClient(&aws.Config{Credentials: creds}) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - SignSDKRequest(r) - querySig := r.HTTPRequest.Header.Get("Authorization") - var origSignedHeaders string - for _, p := range strings.Split(querySig, ", ") { - if strings.HasPrefix(p, "SignedHeaders=") { - origSignedHeaders = p[len("SignedHeaders="):] - break - } - } - if a := origSignedHeaders; len(a) == 0 { - t.Errorf("expect not to be empty, but was") - } - if e, a := origSignedHeaders, "authorization"; strings.Contains(a, e) { - t.Errorf("expect %v to not be in %v, but was", e, a) - } - origSignedAt := r.LastSignedAt - - creds.Expire() - - signSDKRequestWithCurrTime(r, func() time.Time { - // Simulate one second has passed so that signature's date changes - // when it is resigned. - return time.Now().Add(1 * time.Second) - }) - updatedQuerySig := r.HTTPRequest.Header.Get("Authorization") - if e, a := querySig, updatedQuerySig; e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } - - var updatedSignedHeaders string - for _, p := range strings.Split(updatedQuerySig, ", ") { - if strings.HasPrefix(p, "SignedHeaders=") { - updatedSignedHeaders = p[len("SignedHeaders="):] - break - } - } - if a := updatedSignedHeaders; len(a) == 0 { - t.Errorf("expect not to be empty, but was") - } - if e, a := updatedQuerySig, "authorization"; strings.Contains(a, e) { - t.Errorf("expect %v to not be in %v, but was", e, a) - } - if e, a := origSignedAt, r.LastSignedAt; e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } -} - -func TestPreResignRequestExpiredCreds(t *testing.T) { - provider := &credentials.StaticProvider{Value: credentials.Value{ - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "SESSION", - }} - creds := credentials.NewCredentials(provider) - svc := awstesting.NewClient(&aws.Config{Credentials: creds}) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - r.ExpireTime = time.Minute * 10 - - SignSDKRequest(r) - querySig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature") - signedHeaders := r.HTTPRequest.URL.Query().Get("X-Amz-SignedHeaders") - if a := signedHeaders; len(a) == 0 { - t.Errorf("expect not to be empty, but was") - } - origSignedAt := r.LastSignedAt - - creds.Expire() - - signSDKRequestWithCurrTime(r, func() time.Time { - // Simulate the request occurred 15 minutes in the past - return time.Now().Add(-48 * time.Hour) - }) - if e, a := querySig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature"); e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } - resignedHeaders := r.HTTPRequest.URL.Query().Get("X-Amz-SignedHeaders") - if e, a := signedHeaders, resignedHeaders; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := signedHeaders, "x-amz-signedHeaders"; strings.Contains(a, e) { - t.Errorf("expect %v to not be in %v, but was", e, a) - } - if e, a := origSignedAt, r.LastSignedAt; e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } -} - -func TestResignRequestExpiredRequest(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - svc := awstesting.NewClient(&aws.Config{Credentials: creds}) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - - SignSDKRequest(r) - querySig := r.HTTPRequest.Header.Get("Authorization") - origSignedAt := r.LastSignedAt - - signSDKRequestWithCurrTime(r, func() time.Time { - // Simulate the request occurred 15 minutes in the past - return time.Now().Add(15 * time.Minute) - }) - if e, a := querySig, r.HTTPRequest.Header.Get("Authorization"); e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } - if e, a := origSignedAt, r.LastSignedAt; e == a { - t.Errorf("expect %v to be %v, was not", e, a) - } -} - -func TestSignWithRequestBody(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - signer := NewSigner(creds) - - expectBody := []byte("abc123") - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - b, err := ioutil.ReadAll(r.Body) - r.Body.Close() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := expectBody, b; !reflect.DeepEqual(e, a) { - t.Errorf("expect %v, got %v", e, a) - } - w.WriteHeader(http.StatusOK) - })) - - req, err := http.NewRequest("POST", server.URL, nil) - - _, err = signer.Sign(req, bytes.NewReader(expectBody), "service", "region", time.Now()) - if err != nil { - t.Errorf("expect not no error, got %v", err) - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Errorf("expect not no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignWithRequestBody_Overwrite(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - signer := NewSigner(creds) - - var expectBody []byte - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - b, err := ioutil.ReadAll(r.Body) - r.Body.Close() - if err != nil { - t.Errorf("expect not no error, got %v", err) - } - if e, a := len(expectBody), len(b); e != a { - t.Errorf("expect %v, got %v", e, a) - } - w.WriteHeader(http.StatusOK) - })) - - req, err := http.NewRequest("GET", server.URL, strings.NewReader("invalid body")) - - _, err = signer.Sign(req, nil, "service", "region", time.Now()) - req.ContentLength = 0 - - if err != nil { - t.Errorf("expect not no error, got %v", err) - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Errorf("expect not no error, got %v", err) - } - if e, a := http.StatusOK, resp.StatusCode; e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestBuildCanonicalRequest(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "{}") - req.URL.RawQuery = "Foo=z&Foo=o&Foo=m&Foo=a" - ctx := &signingCtx{ - ServiceName: "dynamodb", - Region: "us-east-1", - Request: req, - Body: body, - Query: req.URL.Query(), - Time: time.Now(), - ExpireTime: 5 * time.Second, - } - - ctx.buildCanonicalString() - expected := "https://example.org/bucket/key-._~,!@#$%^&*()?Foo=z&Foo=o&Foo=m&Foo=a" - if e, a := expected, ctx.Request.URL.String(); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestSignWithBody_ReplaceRequestBody(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - req, seekerBody := buildRequest("dynamodb", "us-east-1", "{}") - req.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) - - s := NewSigner(creds) - origBody := req.Body - - _, err := s.Sign(req, seekerBody, "dynamodb", "us-east-1", time.Now()) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if req.Body == origBody { - t.Errorf("expeect request body to not be origBody") - } - - if req.Body == nil { - t.Errorf("expect request body to be changed but was nil") - } -} - -func TestSignWithBody_NoReplaceRequestBody(t *testing.T) { - creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") - req, seekerBody := buildRequest("dynamodb", "us-east-1", "{}") - req.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) - - s := NewSigner(creds, func(signer *Signer) { - signer.DisableRequestBodyOverwrite = true - }) - - origBody := req.Body - - _, err := s.Sign(req, seekerBody, "dynamodb", "us-east-1", time.Now()) - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if req.Body != origBody { - t.Errorf("expect request body to not be chagned") - } -} - -func TestRequestHost(t *testing.T) { - req, body := buildRequest("dynamodb", "us-east-1", "{}") - req.URL.RawQuery = "Foo=z&Foo=o&Foo=m&Foo=a" - req.Host = "myhost" - ctx := &signingCtx{ - ServiceName: "dynamodb", - Region: "us-east-1", - Request: req, - Body: body, - Query: req.URL.Query(), - Time: time.Now(), - ExpireTime: 5 * time.Second, - } - - ctx.buildCanonicalHeaders(ignoredHeaders, ctx.Request.Header) - if !strings.Contains(ctx.canonicalHeaders, "host:"+req.Host) { - t.Errorf("canonical host header invalid") - } -} - -func BenchmarkPresignRequest(b *testing.B) { - signer := buildSigner() - req, body := buildRequest("dynamodb", "us-east-1", "{}") - for i := 0; i < b.N; i++ { - signer.Presign(req, body, "dynamodb", "us-east-1", 300*time.Second, time.Now()) - } -} - -func BenchmarkSignRequest(b *testing.B) { - signer := buildSigner() - req, body := buildRequest("dynamodb", "us-east-1", "{}") - for i := 0; i < b.N; i++ { - signer.Sign(req, body, "dynamodb", "us-east-1", time.Now()) - } -} - -var stripExcessSpaceCases = []string{ - `AWS4-HMAC-SHA256 Credential=AKIDFAKEIDFAKEID/20160628/us-west-2/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=1234567890abcdef1234567890abcdef1234567890abcdef`, - `123 321 123 321`, - ` 123 321 123 321 `, - ` 123 321 123 321 `, - "123", - "1 2 3", - " 1 2 3", - "1 2 3", - "1 23", - "1 2 3", - "1 2 ", - " 1 2 ", - "12 3", - "12 3 1", - "12 3 1", - "12 3 1abc123", -} - -func BenchmarkStripExcessSpaces(b *testing.B) { - for i := 0; i < b.N; i++ { - // Make sure to start with a copy of the cases - cases := append([]string{}, stripExcessSpaceCases...) - stripExcessSpaces(cases) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/types_test.go b/vendor/github.com/aws/aws-sdk-go/aws/types_test.go deleted file mode 100644 index e399ef57..00000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/types_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package aws - -import ( - "bytes" - "math/rand" - "testing" -) - -func TestWriteAtBuffer(t *testing.T) { - b := &WriteAtBuffer{} - - n, err := b.WriteAt([]byte{1}, 0) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if e, a := 1, n; e != a { - t.Errorf("expected %d, but recieved %d", e, a) - } - - n, err = b.WriteAt([]byte{1, 1, 1}, 5) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if e, a := 3, n; e != a { - t.Errorf("expected %d, but recieved %d", e, a) - } - - n, err = b.WriteAt([]byte{2}, 1) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if e, a := 1, n; e != a { - t.Errorf("expected %d, but recieved %d", e, a) - } - - n, err = b.WriteAt([]byte{3}, 2) - if err != nil { - t.Errorf("expected no error, but received %v", err) - } - if e, a := 1, n; e != a { - t.Errorf("expected %d, but received %d", e, a) - } - - if !bytes.Equal([]byte{1, 2, 3, 0, 0, 1, 1, 1}, b.Bytes()) { - t.Errorf("expected %v, but received %v", []byte{1, 2, 3, 0, 0, 1, 1, 1}, b.Bytes()) - } -} - -func BenchmarkWriteAtBuffer(b *testing.B) { - buf := &WriteAtBuffer{} - r := rand.New(rand.NewSource(1)) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - to := r.Intn(10) * 4096 - bs := make([]byte, to) - buf.WriteAt(bs, r.Int63n(10)*4096) - } -} - -func BenchmarkWriteAtBufferOrderedWrites(b *testing.B) { - // test the performance of a WriteAtBuffer when written in an - // ordered fashion. This is similar to the behavior of the - // s3.Downloader, since downloads the first chunk of the file, then - // the second, and so on. - // - // This test simulates a 150MB file being written in 30 ordered 5MB chunks. - chunk := int64(5e6) - max := chunk * 30 - // we'll write the same 5MB chunk every time - tmp := make([]byte, chunk) - for i := 0; i < b.N; i++ { - buf := &WriteAtBuffer{} - for i := int64(0); i < max; i += chunk { - buf.WriteAt(tmp, i) - } - } -} - -func BenchmarkWriteAtBufferParallel(b *testing.B) { - buf := &WriteAtBuffer{} - r := rand.New(rand.NewSource(1)) - - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - to := r.Intn(10) * 4096 - bs := make([]byte, to) - buf.WriteAt(bs, r.Int63n(10)*4096) - } - }) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go index 2d9595a2..38caca42 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/version.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/version.go @@ -5,4 +5,4 @@ package aws const SDKName = "aws-sdk-go" // SDKVersion is the version of this SDK -const SDKVersion = "1.14.7" +const SDKVersion = "1.14.13" diff --git a/vendor/github.com/aws/aws-sdk-go/buildspec.yml b/vendor/github.com/aws/aws-sdk-go/buildspec.yml deleted file mode 100644 index 2defb7f6..00000000 --- a/vendor/github.com/aws/aws-sdk-go/buildspec.yml +++ /dev/null @@ -1,21 +0,0 @@ -version: 0.2 - -phases: - build: - commands: - - echo Build started on `date` - - export GOPATH=/go - - export SDK_CB_ROOT=`pwd` - - export SDK_GO_ROOT=/go/src/github.com/aws/aws-sdk-go - - mkdir -p /go/src/github.com/aws - - ln -s $SDK_CB_ROOT $SDK_GO_ROOT - - cd $SDK_GO_ROOT - - make ci-test - - cd $SDK_CB_ROOT - - #echo Compiling the Go code... - post_build: - commands: - - echo Build completed on `date` -#artifacts: -# files: -# - hello diff --git a/vendor/github.com/aws/aws-sdk-go/cleanup_models.sh b/vendor/github.com/aws/aws-sdk-go/cleanup_models.sh deleted file mode 100755 index 184ec40a..00000000 --- a/vendor/github.com/aws/aws-sdk-go/cleanup_models.sh +++ /dev/null @@ -1,9 +0,0 @@ -#/usr/bin/env bash - -# Deletes all but the most current model version. -for v in $(ls ./models/apis | grep -v '.go' ); do - for vm in $(ls -r models/apis/$v/ | sed -n '1!p' ); do - echo "rm -r models/apis/$v/$vm" - rm -r models/apis/$v/$vm - done -done diff --git a/vendor/github.com/aws/aws-sdk-go/doc.go b/vendor/github.com/aws/aws-sdk-go/doc.go deleted file mode 100644 index 32b806a4..00000000 --- a/vendor/github.com/aws/aws-sdk-go/doc.go +++ /dev/null @@ -1,405 +0,0 @@ -// Package sdk is the official AWS SDK for the Go programming language. -// -// The AWS SDK for Go provides APIs and utilities that developers can use to -// build Go applications that use AWS services, such as Amazon Elastic Compute -// Cloud (Amazon EC2) and Amazon Simple Storage Service (Amazon S3). -// -// The SDK removes the complexity of coding directly against a web service -// interface. It hides a lot of the lower-level plumbing, such as authentication, -// request retries, and error handling. -// -// The SDK also includes helpful utilities on top of the AWS APIs that add additional -// capabilities and functionality. For example, the Amazon S3 Download and Upload -// Manager will automatically split up large objects into multiple parts and -// transfer them concurrently. -// -// See the s3manager package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/ -// -// Getting More Information -// -// Checkout the Getting Started Guide and API Reference Docs detailed the SDK's -// components and details on each AWS client the SDK supports. -// -// The Getting Started Guide provides examples and detailed description of how -// to get setup with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/welcome.html -// -// The API Reference Docs include a detailed breakdown of the SDK's components -// such as utilities and AWS clients. Use this as a reference of the Go types -// included with the SDK, such as AWS clients, API operations, and API parameters. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// Overview of SDK's Packages -// -// The SDK is composed of two main components, SDK core, and service clients. -// The SDK core packages are all available under the aws package at the root of -// the SDK. Each client for a supported AWS service is available within its own -// package under the service folder at the root of the SDK. -// -// * aws - SDK core, provides common shared types such as Config, Logger, -// and utilities to make working with API parameters easier. -// -// * awserr - Provides the error interface that the SDK will use for all -// errors that occur in the SDK's processing. This includes service API -// response errors as well. The Error type is made up of a code and message. -// Cast the SDK's returned error type to awserr.Error and call the Code -// method to compare returned error to specific error codes. See the package's -// documentation for additional values that can be extracted such as RequestId. -// -// * credentials - Provides the types and built in credentials providers -// the SDK will use to retrieve AWS credentials to make API requests with. -// Nested under this folder are also additional credentials providers such as -// stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. -// -// * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. -// Use this to lookup AWS service endpoint information such as which services -// are in a region, and what regions a service is in. Constants are also provided -// for all region identifiers, e.g UsWest2RegionID for "us-west-2". -// -// * session - Provides initial default configuration, and load -// configuration from external sources such as environment and shared -// credentials file. -// -// * request - Provides the API request sending, and retry logic for the SDK. -// This package also includes utilities for defining your own request -// retryer, and configuring how the SDK processes the request. -// -// * service - Clients for AWS services. All services supported by the SDK are -// available under this folder. -// -// How to Use the SDK's AWS Service Clients -// -// The SDK includes the Go types and utilities you can use to make requests to -// AWS service APIs. Within the service folder at the root of the SDK you'll find -// a package for each AWS service the SDK supports. All service clients follows -// a common pattern of creation and usage. -// -// When creating a client for an AWS service you'll first need to have a Session -// value constructed. The Session provides shared configuration that can be shared -// between your service clients. When service clients are created you can pass -// in additional configuration via the aws.Config type to override configuration -// provided by in the Session to create service client instances with custom -// configuration. -// -// Once the service's client is created you can use it to make API requests the -// AWS service. These clients are safe to use concurrently. -// -// Configuring the SDK -// -// In the AWS SDK for Go, you can configure settings for service clients, such -// as the log level and maximum number of retries. Most settings are optional; -// however, for each service client, you must specify a region and your credentials. -// The SDK uses these values to send requests to the correct AWS region and sign -// requests with the correct credentials. You can specify these values as part -// of a session or as environment variables. -// -// See the SDK's configuration guide for more information. -// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html -// -// See the session package documentation for more information on how to use Session -// with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ -// -// See the Config type in the aws package for more information on configuration -// options. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// Configuring Credentials -// -// When using the SDK you'll generally need your AWS credentials to authenticate -// with AWS services. The SDK supports multiple methods of supporting these -// credentials. By default the SDK will source credentials automatically from -// its default credential chain. See the session package for more information -// on this chain, and how to configure it. The common items in the credential -// chain are the following: -// -// * Environment Credentials - Set of environment variables that are useful -// when sub processes are created for specific roles. -// -// * Shared Credentials file (~/.aws/credentials) - This file stores your -// credentials based on a profile name and is useful for local development. -// -// * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials -// to application running on an EC2 instance. This removes the need to manage -// credential files in production. -// -// Credentials can be configured in code as well by setting the Config's Credentials -// value to a custom provider or using one of the providers included with the -// SDK to bypass the default credential chain and use a custom one. This is -// helpful when you want to instruct the SDK to only use a specific set of -// credentials or providers. -// -// This example creates a credential provider for assuming an IAM role, "myRoleARN" -// and configures the S3 service client to use that role for API requests. -// -// // Initial credentials loaded from SDK's default credential chain. Such as -// // the environment, shared credentials (~/.aws/credentials), or EC2 Instance -// // Role. These credentials will be used to to make the STS Assume Role API. -// sess := session.Must(session.NewSession()) -// -// // Create the credentials from AssumeRoleProvider to assume the role -// // referenced by the "myRoleARN" ARN. -// creds := stscreds.NewCredentials(sess, "myRoleArn") -// -// // Create service client value configured for credentials -// // from assumed role. -// svc := s3.New(sess, &aws.Config{Credentials: creds})/ -// -// See the credentials package documentation for more information on credential -// providers included with the SDK, and how to customize the SDK's usage of -// credentials. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials -// -// The SDK has support for the shared configuration file (~/.aws/config). This -// support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", -// or enabling the feature in code when creating a Session via the -// Option's SharedConfigState parameter. -// -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// SharedConfigState: session.SharedConfigEnable, -// })) -// -// Configuring AWS Region -// -// In addition to the credentials you'll need to specify the region the SDK -// will use to make AWS API requests to. In the SDK you can specify the region -// either with an environment variable, or directly in code when a Session or -// service client is created. The last value specified in code wins if the region -// is specified multiple ways. -// -// To set the region via the environment variable set the "AWS_REGION" to the -// region you want to the SDK to use. Using this method to set the region will -// allow you to run your application in multiple regions without needing additional -// code in the application to select the region. -// -// AWS_REGION=us-west-2 -// -// The endpoints package includes constants for all regions the SDK knows. The -// values are all suffixed with RegionID. These values are helpful, because they -// reduce the need to type the region string manually. -// -// To set the region on a Session use the aws package's Config struct parameter -// Region to the AWS region you want the service clients created from the session to -// use. This is helpful when you want to create multiple service clients, and -// all of the clients make API requests to the same region. -// -// sess := session.Must(session.NewSession(&aws.Config{ -// Region: aws.String(endpoints.UsWest2RegionID), -// })) -// -// See the endpoints package for the AWS Regions and Endpoints metadata. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ -// -// In addition to setting the region when creating a Session you can also set -// the region on a per service client bases. This overrides the region of a -// Session. This is helpful when you want to create service clients in specific -// regions different from the Session's region. -// -// svc := s3.New(sess, &aws.Config{ -// Region: aws.String(endpoints.UsWest2RegionID), -// }) -// -// See the Config type in the aws package for more information and additional -// options such as setting the Endpoint, and other service client configuration options. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// Making API Requests -// -// Once the client is created you can make an API request to the service. -// Each API method takes a input parameter, and returns the service response -// and an error. The SDK provides methods for making the API call in multiple ways. -// -// In this list we'll use the S3 ListObjects API as an example for the different -// ways of making API requests. -// -// * ListObjects - Base API operation that will make the API request to the service. -// -// * ListObjectsRequest - API methods suffixed with Request will construct the -// API request, but not send it. This is also helpful when you want to get a -// presigned URL for a request, and share the presigned URL instead of your -// application making the request directly. -// -// * ListObjectsPages - Same as the base API operation, but uses a callback to -// automatically handle pagination of the API's response. -// -// * ListObjectsWithContext - Same as base API operation, but adds support for -// the Context pattern. This is helpful for controlling the canceling of in -// flight requests. See the Go standard library context package for more -// information. This method also takes request package's Option functional -// options as the variadic argument for modifying how the request will be -// made, or extracting information from the raw HTTP response. -// -// * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for -// the Context pattern. Similar to ListObjectsWithContext this method also -// takes the request package's Option function option types as the variadic -// argument. -// -// In addition to the API operations the SDK also includes several higher level -// methods that abstract checking for and waiting for an AWS resource to be in -// a desired state. In this list we'll use WaitUntilBucketExists to demonstrate -// the different forms of waiters. -// -// * WaitUntilBucketExists. - Method to make API request to query an AWS service for -// a resource's state. Will return successfully when that state is accomplished. -// -// * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds -// support for the Context pattern. In addition these methods take request -// package's WaiterOptions to configure the waiter, and how underlying request -// will be made by the SDK. -// -// The API method will document which error codes the service might return for -// the operation. These errors will also be available as const strings prefixed -// with "ErrCode" in the service client's package. If there are no errors listed -// in the API's SDK documentation you'll need to consult the AWS service's API -// documentation for the errors that could be returned. -// -// ctx := context.Background() -// -// result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ -// Bucket: aws.String("my-bucket"), -// Key: aws.String("my-key"), -// }) -// if err != nil { -// // Cast err to awserr.Error to handle specific error codes. -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == s3.ErrCodeNoSuchKey { -// // Specific error code handling -// } -// return err -// } -// -// // Make sure to close the body when done with it for S3 GetObject APIs or -// // will leak connections. -// defer result.Body.Close() -// -// fmt.Println("Object Size:", aws.StringValue(result.ContentLength)) -// -// API Request Pagination and Resource Waiters -// -// Pagination helper methods are suffixed with "Pages", and provide the -// functionality needed to round trip API page requests. Pagination methods -// take a callback function that will be called for each page of the API's response. -// -// objects := []string{} -// err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ -// Bucket: aws.String(myBucket), -// }, func(p *s3.ListObjectsOutput, lastPage bool) bool { -// for _, o := range p.Contents { -// objects = append(objects, aws.StringValue(o.Key)) -// } -// return true // continue paging -// }) -// if err != nil { -// panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) -// } -// -// fmt.Println("Objects in bucket:", objects) -// -// Waiter helper methods provide the functionality to wait for an AWS resource -// state. These methods abstract the logic needed to to check the state of an -// AWS resource, and wait until that resource is in a desired state. The waiter -// will block until the resource is in the state that is desired, an error occurs, -// or the waiter times out. If a resource times out the error code returned will -// be request.WaiterResourceNotReadyErrorCode. -// -// err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ -// Bucket: aws.String(myBucket), -// }) -// if err != nil { -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { -// fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") -// } -// panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) -// } -// fmt.Println("Bucket", myBucket, "exists") -// -// Complete SDK Example -// -// This example shows a complete working Go file which will upload a file to S3 -// and use the Context pattern to implement timeout logic that will cancel the -// request if it takes too long. This example highlights how to use sessions, -// create a service client, make a request, handle the error, and process the -// response. -// -// package main -// -// import ( -// "context" -// "flag" -// "fmt" -// "os" -// "time" -// -// "github.com/aws/aws-sdk-go/aws" -// "github.com/aws/aws-sdk-go/aws/awserr" -// "github.com/aws/aws-sdk-go/aws/request" -// "github.com/aws/aws-sdk-go/aws/session" -// "github.com/aws/aws-sdk-go/service/s3" -// ) -// -// // Uploads a file to S3 given a bucket and object key. Also takes a duration -// // value to terminate the update if it doesn't complete within that time. -// // -// // The AWS Region needs to be provided in the AWS shared config or on the -// // environment variable as `AWS_REGION`. Credentials also must be provided -// // Will default to shared config file, but can load from environment if provided. -// // -// // Usage: -// // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail -// // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt -// func main() { -// var bucket, key string -// var timeout time.Duration -// -// flag.StringVar(&bucket, "b", "", "Bucket name.") -// flag.StringVar(&key, "k", "", "Object key name.") -// flag.DurationVar(&timeout, "d", 0, "Upload timeout.") -// flag.Parse() -// -// // All clients require a Session. The Session provides the client with -// // shared configuration such as region, endpoint, and credentials. A -// // Session should be shared where possible to take advantage of -// // configuration and credential caching. See the session package for -// // more information. -// sess := session.Must(session.NewSession()) -// -// // Create a new instance of the service's client with a Session. -// // Optional aws.Config values can also be provided as variadic arguments -// // to the New function. This option allows you to provide service -// // specific configuration. -// svc := s3.New(sess) -// -// // Create a context with a timeout that will abort the upload if it takes -// // more than the passed in timeout. -// ctx := context.Background() -// var cancelFn func() -// if timeout > 0 { -// ctx, cancelFn = context.WithTimeout(ctx, timeout) -// } -// // Ensure the context is canceled to prevent leaking. -// // See context package for more information, https://golang.org/pkg/context/ -// defer cancelFn() -// -// // Uploads the object to S3. The Context will interrupt the request if the -// // timeout expires. -// _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ -// Bucket: aws.String(bucket), -// Key: aws.String(key), -// Body: os.Stdin, -// }) -// if err != nil { -// if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { -// // If the SDK can determine the request or retry delay was canceled -// // by a context the CanceledErrorCode error code will be returned. -// fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) -// } else { -// fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) -// } -// os.Exit(1) -// } -// -// fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) -// } -package sdk diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_other_test.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_other_test.go deleted file mode 100644 index a2fd4558..00000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_other_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package shareddefaults_test - -import ( - "os" - "path/filepath" - "testing" - - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -func TestSharedCredsFilename(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("HOME", "home_dir") - os.Setenv("USERPROFILE", "profile_dir") - - expect := filepath.Join("home_dir", ".aws", "credentials") - - name := shareddefaults.SharedCredentialsFilename() - if e, a := expect, name; e != a { - t.Errorf("expect %q shared creds filename, got %q", e, a) - } -} - -func TestSharedConfigFilename(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("HOME", "home_dir") - os.Setenv("USERPROFILE", "profile_dir") - - expect := filepath.Join("home_dir", ".aws", "config") - - name := shareddefaults.SharedConfigFilename() - if e, a := expect, name; e != a { - t.Errorf("expect %q shared config filename, got %q", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_windows_test.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_windows_test.go deleted file mode 100644 index afe96b17..00000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_windows_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package shareddefaults_test - -import ( - "os" - "path/filepath" - "testing" - - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -func TestSharedCredsFilename(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("HOME", "home_dir") - os.Setenv("USERPROFILE", "profile_dir") - - expect := filepath.Join("profile_dir", ".aws", "credentials") - - name := shareddefaults.SharedCredentialsFilename() - if e, a := expect, name; e != a { - t.Errorf("expect %q shared creds filename, got %q", e, a) - } -} - -func TestSharedConfigFilename(t *testing.T) { - env := awstesting.StashEnv() - defer awstesting.PopEnv(env) - - os.Setenv("HOME", "home_dir") - os.Setenv("USERPROFILE", "profile_dir") - - expect := filepath.Join("profile_dir", ".aws", "config") - - name := shareddefaults.SharedConfigFilename() - if e, a := expect, name; e != a { - t.Errorf("expect %q shared config filename, got %q", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/README.md b/vendor/github.com/aws/aws-sdk-go/private/README.md deleted file mode 100644 index 5bdb4c50..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## AWS SDK for Go Private packages ## -`private` is a collection of packages used internally by the SDK, and is subject to have breaking changes. This package is not `internal` so that if you really need to use its functionality, and understand breaking changes will be made, you are able to. - -These packages will be refactored in the future so that the API generator and model parsers are exposed cleanly on their own. Making it easier for you to generate your own code based on the API models. diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_bench_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_bench_test.go deleted file mode 100644 index e135b936..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_bench_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// +build bench - -package ec2query_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/private/protocol/ec2query" - "github.com/aws/aws-sdk-go/service/ec2" -) - -func BenchmarkEC2QueryBuild_Complex_ec2AuthorizeSecurityGroupEgress(b *testing.B) { - params := &ec2.AuthorizeSecurityGroupEgressInput{ - GroupId: aws.String("String"), // Required - CidrIp: aws.String("String"), - DryRun: aws.Bool(true), - FromPort: aws.Int64(1), - IpPermissions: []*ec2.IpPermission{ - { // Required - FromPort: aws.Int64(1), - IpProtocol: aws.String("String"), - IpRanges: []*ec2.IpRange{ - { // Required - CidrIp: aws.String("String"), - }, - // More values... - }, - PrefixListIds: []*ec2.PrefixListId{ - { // Required - PrefixListId: aws.String("String"), - }, - // More values... - }, - ToPort: aws.Int64(1), - UserIdGroupPairs: []*ec2.UserIdGroupPair{ - { // Required - GroupId: aws.String("String"), - GroupName: aws.String("String"), - UserId: aws.String("String"), - }, - // More values... - }, - }, - // More values... - }, - IpProtocol: aws.String("String"), - SourceSecurityGroupName: aws.String("String"), - SourceSecurityGroupOwnerId: aws.String("String"), - ToPort: aws.Int64(1), - } - - benchEC2QueryBuild(b, "AuthorizeSecurityGroupEgress", params) -} - -func BenchmarkEC2QueryBuild_Simple_ec2AttachNetworkInterface(b *testing.B) { - params := &ec2.AttachNetworkInterfaceInput{ - DeviceIndex: aws.Int64(1), // Required - InstanceId: aws.String("String"), // Required - NetworkInterfaceId: aws.String("String"), // Required - DryRun: aws.Bool(true), - } - - benchEC2QueryBuild(b, "AttachNetworkInterface", params) -} - -func benchEC2QueryBuild(b *testing.B, opName string, params interface{}) { - svc := awstesting.NewClient() - svc.ServiceName = "ec2" - svc.APIVersion = "2015-04-15" - - for i := 0; i < b.N; i++ { - r := svc.NewRequest(&request.Operation{ - Name: opName, - HTTPMethod: "POST", - HTTPPath: "/", - }, params, nil) - ec2query.Build(r) - if r.Error != nil { - b.Fatal("Unexpected error", r.Error) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_test.go deleted file mode 100644 index 7b69c91a..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/build_test.go +++ /dev/null @@ -1,2102 +0,0 @@ -package ec2query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/ec2query" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/private/util" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF -var _ = aws.String -var _ = fmt.Println -var _ = reflect.Value{} - -func init() { - protocol.RandReader = &awstesting.ZeroReader{} -} - -// InputService1ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService1ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService1ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService1ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService1ProtocolTest client from just a session. -// svc := inputservice1protocoltest.New(mySession) -// -// // Create a InputService1ProtocolTest client with additional configuration -// svc := inputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService1ProtocolTest { - c := p.ClientConfig("inputservice1protocoltest", cfgs...) - return newInputService1ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService1ProtocolTest { - svc := &InputService1ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice1protocoltest", - ServiceID: "InputService1ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService1TestCaseOperation1 = "OperationName" - -// InputService1TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService1TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService1TestCaseOperation1 for more information on using the InputService1TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService1TestCaseOperation1Request method. -// req, resp := client.InputService1TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputService1TestCaseOperation1Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService1TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService1TestShapeInputService1TestCaseOperation1Input{} - } - - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService1TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService1TestCaseOperation1 for usage and error information. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputService1TestCaseOperation1Input) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService1TestCaseOperation1WithContext is the same as InputService1TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService1TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1WithContext(ctx aws.Context, input *InputService1TestShapeInputService1TestCaseOperation1Input, opts ...request.Option) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService1TestShapeInputService1TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - Bar *string `type:"string"` - - Foo *string `type:"string"` -} - -// SetBar sets the Bar field's value. -func (s *InputService1TestShapeInputService1TestCaseOperation1Input) SetBar(v string) *InputService1TestShapeInputService1TestCaseOperation1Input { - s.Bar = &v - return s -} - -// SetFoo sets the Foo field's value. -func (s *InputService1TestShapeInputService1TestCaseOperation1Input) SetFoo(v string) *InputService1TestShapeInputService1TestCaseOperation1Input { - s.Foo = &v - return s -} - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService2ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService2ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService2ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService2ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService2ProtocolTest client from just a session. -// svc := inputservice2protocoltest.New(mySession) -// -// // Create a InputService2ProtocolTest client with additional configuration -// svc := inputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService2ProtocolTest { - c := p.ClientConfig("inputservice2protocoltest", cfgs...) - return newInputService2ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService2ProtocolTest { - svc := &InputService2ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice2protocoltest", - ServiceID: "InputService2ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService2TestCaseOperation1 = "OperationName" - -// InputService2TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService2TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService2TestCaseOperation1 for more information on using the InputService2TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService2TestCaseOperation1Request method. -// req, resp := client.InputService2TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputService2TestCaseOperation1Input) (req *request.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService2TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService2TestShapeInputService2TestCaseOperation1Input{} - } - - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService2TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService2TestCaseOperation1 for usage and error information. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputService2TestCaseOperation1Input) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService2TestCaseOperation1WithContext is the same as InputService2TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService2TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1WithContext(ctx aws.Context, input *InputService2TestShapeInputService2TestCaseOperation1Input, opts ...request.Option) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService2TestShapeInputService2TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - Bar *string `locationName:"barLocationName" type:"string"` - - Foo *string `type:"string"` - - Yuck *string `locationName:"yuckLocationName" queryName:"yuckQueryName" type:"string"` -} - -// SetBar sets the Bar field's value. -func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetBar(v string) *InputService2TestShapeInputService2TestCaseOperation1Input { - s.Bar = &v - return s -} - -// SetFoo sets the Foo field's value. -func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetFoo(v string) *InputService2TestShapeInputService2TestCaseOperation1Input { - s.Foo = &v - return s -} - -// SetYuck sets the Yuck field's value. -func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetYuck(v string) *InputService2TestShapeInputService2TestCaseOperation1Input { - s.Yuck = &v - return s -} - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService3ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService3ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService3ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService3ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService3ProtocolTest client from just a session. -// svc := inputservice3protocoltest.New(mySession) -// -// // Create a InputService3ProtocolTest client with additional configuration -// svc := inputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService3ProtocolTest { - c := p.ClientConfig("inputservice3protocoltest", cfgs...) - return newInputService3ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService3ProtocolTest { - svc := &InputService3ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice3protocoltest", - ServiceID: "InputService3ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService3TestCaseOperation1 = "OperationName" - -// InputService3TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService3TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService3TestCaseOperation1 for more information on using the InputService3TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService3TestCaseOperation1Request method. -// req, resp := client.InputService3TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputService3TestCaseOperation1Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService3TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService3TestShapeInputService3TestCaseOperation1Input{} - } - - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService3TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService3TestCaseOperation1 for usage and error information. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputService3TestCaseOperation1Input) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService3TestCaseOperation1WithContext is the same as InputService3TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService3TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1WithContext(ctx aws.Context, input *InputService3TestShapeInputService3TestCaseOperation1Input, opts ...request.Option) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService3TestShapeInputService3TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - StructArg *InputService3TestShapeStructType `locationName:"Struct" type:"structure"` -} - -// SetStructArg sets the StructArg field's value. -func (s *InputService3TestShapeInputService3TestCaseOperation1Input) SetStructArg(v *InputService3TestShapeStructType) *InputService3TestShapeInputService3TestCaseOperation1Input { - s.StructArg = v - return s -} - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService3TestShapeStructType struct { - _ struct{} `type:"structure"` - - ScalarArg *string `locationName:"Scalar" type:"string"` -} - -// SetScalarArg sets the ScalarArg field's value. -func (s *InputService3TestShapeStructType) SetScalarArg(v string) *InputService3TestShapeStructType { - s.ScalarArg = &v - return s -} - -// InputService4ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService4ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService4ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService4ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService4ProtocolTest client from just a session. -// svc := inputservice4protocoltest.New(mySession) -// -// // Create a InputService4ProtocolTest client with additional configuration -// svc := inputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService4ProtocolTest { - c := p.ClientConfig("inputservice4protocoltest", cfgs...) - return newInputService4ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService4ProtocolTest { - svc := &InputService4ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice4protocoltest", - ServiceID: "InputService4ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService4TestCaseOperation1 = "OperationName" - -// InputService4TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService4TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService4TestCaseOperation1 for more information on using the InputService4TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService4TestCaseOperation1Request method. -// req, resp := client.InputService4TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputService4TestCaseOperation1Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService4TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService4TestShapeInputService4TestCaseOperation1Input{} - } - - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService4TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService4TestCaseOperation1 for usage and error information. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputService4TestCaseOperation1Input) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService4TestCaseOperation1WithContext is the same as InputService4TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService4TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1WithContext(ctx aws.Context, input *InputService4TestShapeInputService4TestCaseOperation1Input, opts ...request.Option) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService4TestShapeInputService4TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - ListBools []*bool `type:"list"` - - ListFloats []*float64 `type:"list"` - - ListIntegers []*int64 `type:"list"` - - ListStrings []*string `type:"list"` -} - -// SetListBools sets the ListBools field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListBools(v []*bool) *InputService4TestShapeInputService4TestCaseOperation1Input { - s.ListBools = v - return s -} - -// SetListFloats sets the ListFloats field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListFloats(v []*float64) *InputService4TestShapeInputService4TestCaseOperation1Input { - s.ListFloats = v - return s -} - -// SetListIntegers sets the ListIntegers field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListIntegers(v []*int64) *InputService4TestShapeInputService4TestCaseOperation1Input { - s.ListIntegers = v - return s -} - -// SetListStrings sets the ListStrings field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation1Input) SetListStrings(v []*string) *InputService4TestShapeInputService4TestCaseOperation1Input { - s.ListStrings = v - return s -} - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService5ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService5ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService5ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService5ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService5ProtocolTest client from just a session. -// svc := inputservice5protocoltest.New(mySession) -// -// // Create a InputService5ProtocolTest client with additional configuration -// svc := inputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService5ProtocolTest { - c := p.ClientConfig("inputservice5protocoltest", cfgs...) - return newInputService5ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService5ProtocolTest { - svc := &InputService5ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice5protocoltest", - ServiceID: "InputService5ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService5TestCaseOperation1 = "OperationName" - -// InputService5TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService5TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService5TestCaseOperation1 for more information on using the InputService5TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService5TestCaseOperation1Request method. -// req, resp := client.InputService5TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputService5TestCaseOperation1Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService5TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService5TestShapeInputService5TestCaseOperation1Input{} - } - - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService5TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService5TestCaseOperation1 for usage and error information. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputService5TestCaseOperation1Input) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService5TestCaseOperation1WithContext is the same as InputService5TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService5TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation1Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService5TestShapeInputService5TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `locationName:"ListMemberName" locationNameList:"item" type:"list"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService5TestShapeInputService5TestCaseOperation1Input) SetListArg(v []*string) *InputService5TestShapeInputService5TestCaseOperation1Input { - s.ListArg = v - return s -} - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService6ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService6ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService6ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService6ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService6ProtocolTest client from just a session. -// svc := inputservice6protocoltest.New(mySession) -// -// // Create a InputService6ProtocolTest client with additional configuration -// svc := inputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService6ProtocolTest { - c := p.ClientConfig("inputservice6protocoltest", cfgs...) - return newInputService6ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService6ProtocolTest { - svc := &InputService6ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice6protocoltest", - ServiceID: "InputService6ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService6TestCaseOperation1 = "OperationName" - -// InputService6TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService6TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService6TestCaseOperation1 for more information on using the InputService6TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService6TestCaseOperation1Request method. -// req, resp := client.InputService6TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputService6TestCaseOperation1Input) (req *request.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService6TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService6TestShapeInputService6TestCaseOperation1Input{} - } - - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService6TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService6TestCaseOperation1 for usage and error information. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputService6TestCaseOperation1Input) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService6TestCaseOperation1WithContext is the same as InputService6TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService6TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1WithContext(ctx aws.Context, input *InputService6TestShapeInputService6TestCaseOperation1Input, opts ...request.Option) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService6TestShapeInputService6TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `locationName:"ListMemberName" queryName:"ListQueryName" locationNameList:"item" type:"list"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService6TestShapeInputService6TestCaseOperation1Input) SetListArg(v []*string) *InputService6TestShapeInputService6TestCaseOperation1Input { - s.ListArg = v - return s -} - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService7ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService7ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService7ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService7ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService7ProtocolTest client from just a session. -// svc := inputservice7protocoltest.New(mySession) -// -// // Create a InputService7ProtocolTest client with additional configuration -// svc := inputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService7ProtocolTest { - c := p.ClientConfig("inputservice7protocoltest", cfgs...) - return newInputService7ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService7ProtocolTest { - svc := &InputService7ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice7protocoltest", - ServiceID: "InputService7ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService7TestCaseOperation1 = "OperationName" - -// InputService7TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService7TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService7TestCaseOperation1 for more information on using the InputService7TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService7TestCaseOperation1Request method. -// req, resp := client.InputService7TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputService7TestCaseOperation1Input) (req *request.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService7TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService7TestShapeInputService7TestCaseOperation1Input{} - } - - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService7TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService7TestCaseOperation1 for usage and error information. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputService7TestCaseOperation1Input) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService7TestCaseOperation1WithContext is the same as InputService7TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService7TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1WithContext(ctx aws.Context, input *InputService7TestShapeInputService7TestCaseOperation1Input, opts ...request.Option) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService7TestShapeInputService7TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - // BlobArg is automatically base64 encoded/decoded by the SDK. - BlobArg []byte `type:"blob"` -} - -// SetBlobArg sets the BlobArg field's value. -func (s *InputService7TestShapeInputService7TestCaseOperation1Input) SetBlobArg(v []byte) *InputService7TestShapeInputService7TestCaseOperation1Input { - s.BlobArg = v - return s -} - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService8ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService8ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService8ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService8ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService8ProtocolTest client from just a session. -// svc := inputservice8protocoltest.New(mySession) -// -// // Create a InputService8ProtocolTest client with additional configuration -// svc := inputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService8ProtocolTest { - c := p.ClientConfig("inputservice8protocoltest", cfgs...) - return newInputService8ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService8ProtocolTest { - svc := &InputService8ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice8protocoltest", - ServiceID: "InputService8ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService8TestCaseOperation1 = "OperationName" - -// InputService8TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService8TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService8TestCaseOperation1 for more information on using the InputService8TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService8TestCaseOperation1Request method. -// req, resp := client.InputService8TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputService8TestCaseOperation1Input) (req *request.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService8TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService8TestShapeInputService8TestCaseOperation1Input{} - } - - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService8TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService8TestCaseOperation1 for usage and error information. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputService8TestCaseOperation1Input) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService8TestCaseOperation1WithContext is the same as InputService8TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService8TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1WithContext(ctx aws.Context, input *InputService8TestShapeInputService8TestCaseOperation1Input, opts ...request.Option) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService8TestShapeInputService8TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"` -} - -// SetTimeArg sets the TimeArg field's value. -func (s *InputService8TestShapeInputService8TestCaseOperation1Input) SetTimeArg(v time.Time) *InputService8TestShapeInputService8TestCaseOperation1Input { - s.TimeArg = &v - return s -} - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService9ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService9ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService9ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService9ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService9ProtocolTest client from just a session. -// svc := inputservice9protocoltest.New(mySession) -// -// // Create a InputService9ProtocolTest client with additional configuration -// svc := inputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService9ProtocolTest { - c := p.ClientConfig("inputservice9protocoltest", cfgs...) - return newInputService9ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService9ProtocolTest { - svc := &InputService9ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice9protocoltest", - ServiceID: "InputService9ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService9TestCaseOperation1 = "OperationName" - -// InputService9TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService9TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService9TestCaseOperation1 for more information on using the InputService9TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService9TestCaseOperation1Request method. -// req, resp := client.InputService9TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputService9TestCaseOperation2Input) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService9TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService9TestShapeInputService9TestCaseOperation2Input{} - } - - output = &InputService9TestShapeInputService9TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService9TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService9TestCaseOperation1 for usage and error information. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *InputService9TestShapeInputService9TestCaseOperation2Input) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) { - req, out := c.InputService9TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService9TestCaseOperation1WithContext is the same as InputService9TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService9TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1WithContext(ctx aws.Context, input *InputService9TestShapeInputService9TestCaseOperation2Input, opts ...request.Option) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) { - req, out := c.InputService9TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService9TestCaseOperation2 = "OperationName" - -// InputService9TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService9TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService9TestCaseOperation2 for more information on using the InputService9TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService9TestCaseOperation2Request method. -// req, resp := client.InputService9TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService9ProtocolTest) InputService9TestCaseOperation2Request(input *InputService9TestShapeInputService9TestCaseOperation2Input) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService9TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService9TestShapeInputService9TestCaseOperation2Input{} - } - - output = &InputService9TestShapeInputService9TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService9TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService9TestCaseOperation2 for usage and error information. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation2(input *InputService9TestShapeInputService9TestCaseOperation2Input) (*InputService9TestShapeInputService9TestCaseOperation2Output, error) { - req, out := c.InputService9TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService9TestCaseOperation2WithContext is the same as InputService9TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService9TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation2WithContext(ctx aws.Context, input *InputService9TestShapeInputService9TestCaseOperation2Input, opts ...request.Option) (*InputService9TestShapeInputService9TestCaseOperation2Output, error) { - req, out := c.InputService9TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService9TestShapeInputService9TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation2Input struct { - _ struct{} `type:"structure"` - - Token *string `type:"string" idempotencyToken:"true"` -} - -// SetToken sets the Token field's value. -func (s *InputService9TestShapeInputService9TestCaseOperation2Input) SetToken(v string) *InputService9TestShapeInputService9TestCaseOperation2Input { - s.Token = &v - return s -} - -type InputService9TestShapeInputService9TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -// InputService10ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService10ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService10ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService10ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService10ProtocolTest client from just a session. -// svc := inputservice10protocoltest.New(mySession) -// -// // Create a InputService10ProtocolTest client with additional configuration -// svc := inputservice10protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService10ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService10ProtocolTest { - c := p.ClientConfig("inputservice10protocoltest", cfgs...) - return newInputService10ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService10ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService10ProtocolTest { - svc := &InputService10ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice10protocoltest", - ServiceID: "InputService10ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService10TestCaseOperation1 = "OperationName" - -// InputService10TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService10TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService10TestCaseOperation1 for more information on using the InputService10TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService10TestCaseOperation1Request method. -// req, resp := client.InputService10TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1Request(input *InputService10TestShapeInputService10TestCaseOperation2Input) (req *request.Request, output *InputService10TestShapeInputService10TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService10TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService10TestShapeInputService10TestCaseOperation2Input{} - } - - output = &InputService10TestShapeInputService10TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService10TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService10TestCaseOperation1 for usage and error information. -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1(input *InputService10TestShapeInputService10TestCaseOperation2Input) (*InputService10TestShapeInputService10TestCaseOperation1Output, error) { - req, out := c.InputService10TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService10TestCaseOperation1WithContext is the same as InputService10TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService10TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1WithContext(ctx aws.Context, input *InputService10TestShapeInputService10TestCaseOperation2Input, opts ...request.Option) (*InputService10TestShapeInputService10TestCaseOperation1Output, error) { - req, out := c.InputService10TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService10TestCaseOperation2 = "OperationName" - -// InputService10TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService10TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService10TestCaseOperation2 for more information on using the InputService10TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService10TestCaseOperation2Request method. -// req, resp := client.InputService10TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService10ProtocolTest) InputService10TestCaseOperation2Request(input *InputService10TestShapeInputService10TestCaseOperation2Input) (req *request.Request, output *InputService10TestShapeInputService10TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService10TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService10TestShapeInputService10TestCaseOperation2Input{} - } - - output = &InputService10TestShapeInputService10TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService10TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService10TestCaseOperation2 for usage and error information. -func (c *InputService10ProtocolTest) InputService10TestCaseOperation2(input *InputService10TestShapeInputService10TestCaseOperation2Input) (*InputService10TestShapeInputService10TestCaseOperation2Output, error) { - req, out := c.InputService10TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService10TestCaseOperation2WithContext is the same as InputService10TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService10TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService10ProtocolTest) InputService10TestCaseOperation2WithContext(ctx aws.Context, input *InputService10TestShapeInputService10TestCaseOperation2Input, opts ...request.Option) (*InputService10TestShapeInputService10TestCaseOperation2Output, error) { - req, out := c.InputService10TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService10TestShapeInputService10TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService10TestShapeInputService10TestCaseOperation2Input struct { - _ struct{} `type:"structure"` - - FooEnum *string `type:"string" enum:"InputService10TestShapeEnumType"` - - ListEnums []*string `type:"list"` -} - -// SetFooEnum sets the FooEnum field's value. -func (s *InputService10TestShapeInputService10TestCaseOperation2Input) SetFooEnum(v string) *InputService10TestShapeInputService10TestCaseOperation2Input { - s.FooEnum = &v - return s -} - -// SetListEnums sets the ListEnums field's value. -func (s *InputService10TestShapeInputService10TestCaseOperation2Input) SetListEnums(v []*string) *InputService10TestShapeInputService10TestCaseOperation2Input { - s.ListEnums = v - return s -} - -type InputService10TestShapeInputService10TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -const ( - // EnumTypeFoo is a InputService10TestShapeEnumType enum value - EnumTypeFoo = "foo" - - // EnumTypeBar is a InputService10TestShapeEnumType enum value - EnumTypeBar = "bar" -) - -// -// Tests begin here -// - -func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewInputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService1TestShapeInputService1TestCaseOperation1Input{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - } - req, _ := svc.InputService1TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Bar=val2&Foo=val1&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService2ProtocolTestStructureWithLocationNameAndQueryNameAppliedToMembersCase1(t *testing.T) { - svc := NewInputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService2TestShapeInputService2TestCaseOperation1Input{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - Yuck: aws.String("val3"), - } - req, _ := svc.InputService2TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&BarLocationName=val2&Foo=val1&Version=2014-01-01&yuckQueryName=val3`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestNestedStructureMembersCase1(t *testing.T) { - svc := NewInputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService3TestShapeInputService3TestCaseOperation1Input{ - StructArg: &InputService3TestShapeStructType{ - ScalarArg: aws.String("foo"), - }, - } - req, _ := svc.InputService3TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Struct.Scalar=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestListTypesCase1(t *testing.T) { - svc := NewInputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService4TestShapeInputService4TestCaseOperation1Input{ - ListBools: []*bool{ - aws.Bool(true), - aws.Bool(false), - aws.Bool(false), - }, - ListFloats: []*float64{ - aws.Float64(1.1), - aws.Float64(2.718), - aws.Float64(3.14), - }, - ListIntegers: []*int64{ - aws.Int64(0), - aws.Int64(1), - aws.Int64(2), - }, - ListStrings: []*string{ - aws.String("foo"), - aws.String("bar"), - aws.String("baz"), - }, - } - req, _ := svc.InputService4TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListBools.1=true&ListBools.2=false&ListBools.3=false&ListFloats.1=1.1&ListFloats.2=2.718&ListFloats.3=3.14&ListIntegers.1=0&ListIntegers.2=1&ListIntegers.3=2&ListStrings.1=foo&ListStrings.2=bar&ListStrings.3=baz&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestListWithLocationNameAppliedToMemberCase1(t *testing.T) { - svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService5TestShapeInputService5TestCaseOperation1Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - } - req, _ := svc.InputService5TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListMemberName.1=a&ListMemberName.2=b&ListMemberName.3=c&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService6ProtocolTestListWithLocationNameAndQueryNameCase1(t *testing.T) { - svc := NewInputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService6TestShapeInputService6TestCaseOperation1Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - } - req, _ := svc.InputService6TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListQueryName.1=a&ListQueryName.2=b&ListQueryName.3=c&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService7ProtocolTestBase64EncodedBlobsCase1(t *testing.T) { - svc := NewInputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService7TestShapeInputService7TestCaseOperation1Input{ - BlobArg: []byte("foo"), - } - req, _ := svc.InputService7TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&BlobArg=Zm9v&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService8ProtocolTestTimestampValuesCase1(t *testing.T) { - svc := NewInputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService8TestShapeInputService8TestCaseOperation1Input{ - TimeArg: aws.Time(time.Unix(1422172800, 0)), - } - req, _ := svc.InputService8TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&TimeArg=2015-01-25T08%3A00%3A00Z&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestIdempotencyTokenAutoFillCase1(t *testing.T) { - svc := NewInputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService9TestShapeInputService9TestCaseOperation2Input{ - Token: aws.String("abc123"), - } - req, _ := svc.InputService9TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Token=abc123&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestIdempotencyTokenAutoFillCase2(t *testing.T) { - svc := NewInputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService9TestShapeInputService9TestCaseOperation2Input{} - req, _ := svc.InputService9TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Token=00000000-0000-4000-8000-000000000000&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService10ProtocolTestEnumCase1(t *testing.T) { - svc := NewInputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService10TestShapeInputService10TestCaseOperation2Input{ - ListEnums: []*string{ - aws.String("foo"), - aws.String(""), - aws.String("bar"), - }, - } - req, _ := svc.InputService10TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListEnums.1=foo&ListEnums.2=&ListEnums.3=bar&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService10ProtocolTestEnumCase2(t *testing.T) { - svc := NewInputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService10TestShapeInputService10TestCaseOperation2Input{} - req, _ := svc.InputService10TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/unmarshal_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/unmarshal_test.go deleted file mode 100644 index f5555011..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/ec2query/unmarshal_test.go +++ /dev/null @@ -1,1879 +0,0 @@ -package ec2query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/ec2query" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/private/util" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF -var _ = aws.String -var _ = fmt.Println -var _ = reflect.Value{} - -func init() { - protocol.RandReader = &awstesting.ZeroReader{} -} - -// OutputService1ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService1ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService1ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService1ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService1ProtocolTest client from just a session. -// svc := outputservice1protocoltest.New(mySession) -// -// // Create a OutputService1ProtocolTest client with additional configuration -// svc := outputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService1ProtocolTest { - c := p.ClientConfig("outputservice1protocoltest", cfgs...) - return newOutputService1ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService1ProtocolTest { - svc := &OutputService1ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice1protocoltest", - ServiceID: "OutputService1ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService1TestCaseOperation1 = "OperationName" - -// OutputService1TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService1TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService1TestCaseOperation1 for more information on using the OutputService1TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService1TestCaseOperation1Request method. -// req, resp := client.OutputService1TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *request.Request, output *OutputService1TestShapeOutputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService1TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - output = &OutputService1TestShapeOutputService1TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService1TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService1TestCaseOperation1 for usage and error information. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService1TestCaseOperation1WithContext is the same as OutputService1TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService1TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1WithContext(ctx aws.Context, input *OutputService1TestShapeOutputService1TestCaseOperation1Input, opts ...request.Option) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Char *string `type:"character"` - - Double *float64 `type:"double"` - - FalseBool *bool `type:"boolean"` - - Float *float64 `type:"float"` - - Long *int64 `type:"long"` - - Num *int64 `locationName:"FooNum" type:"integer"` - - Str *string `type:"string"` - - TrueBool *bool `type:"boolean"` -} - -// SetChar sets the Char field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetChar(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Char = &v - return s -} - -// SetDouble sets the Double field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetDouble(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Double = &v - return s -} - -// SetFalseBool sets the FalseBool field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFalseBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.FalseBool = &v - return s -} - -// SetFloat sets the Float field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFloat(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Float = &v - return s -} - -// SetLong sets the Long field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetLong(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Long = &v - return s -} - -// SetNum sets the Num field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetNum(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Num = &v - return s -} - -// SetStr sets the Str field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetStr(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Str = &v - return s -} - -// SetTrueBool sets the TrueBool field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetTrueBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.TrueBool = &v - return s -} - -// OutputService2ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService2ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService2ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService2ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService2ProtocolTest client from just a session. -// svc := outputservice2protocoltest.New(mySession) -// -// // Create a OutputService2ProtocolTest client with additional configuration -// svc := outputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService2ProtocolTest { - c := p.ClientConfig("outputservice2protocoltest", cfgs...) - return newOutputService2ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService2ProtocolTest { - svc := &OutputService2ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice2protocoltest", - ServiceID: "OutputService2ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService2TestCaseOperation1 = "OperationName" - -// OutputService2TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService2TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService2TestCaseOperation1 for more information on using the OutputService2TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService2TestCaseOperation1Request method. -// req, resp := client.OutputService2TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *request.Request, output *OutputService2TestShapeOutputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService2TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - output = &OutputService2TestShapeOutputService2TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService2TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService2TestCaseOperation1 for usage and error information. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService2TestCaseOperation1WithContext is the same as OutputService2TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService2TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1WithContext(ctx aws.Context, input *OutputService2TestShapeOutputService2TestCaseOperation1Input, opts ...request.Option) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - // Blob is automatically base64 encoded/decoded by the SDK. - Blob []byte `type:"blob"` -} - -// SetBlob sets the Blob field's value. -func (s *OutputService2TestShapeOutputService2TestCaseOperation1Output) SetBlob(v []byte) *OutputService2TestShapeOutputService2TestCaseOperation1Output { - s.Blob = v - return s -} - -// OutputService3ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService3ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService3ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService3ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService3ProtocolTest client from just a session. -// svc := outputservice3protocoltest.New(mySession) -// -// // Create a OutputService3ProtocolTest client with additional configuration -// svc := outputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService3ProtocolTest { - c := p.ClientConfig("outputservice3protocoltest", cfgs...) - return newOutputService3ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService3ProtocolTest { - svc := &OutputService3ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice3protocoltest", - ServiceID: "OutputService3ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService3TestCaseOperation1 = "OperationName" - -// OutputService3TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService3TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService3TestCaseOperation1 for more information on using the OutputService3TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService3TestCaseOperation1Request method. -// req, resp := client.OutputService3TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *request.Request, output *OutputService3TestShapeOutputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService3TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - output = &OutputService3TestShapeOutputService3TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService3TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService3TestCaseOperation1 for usage and error information. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService3TestCaseOperation1WithContext is the same as OutputService3TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService3TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1WithContext(ctx aws.Context, input *OutputService3TestShapeOutputService3TestCaseOperation1Input, opts ...request.Option) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `type:"list"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService3TestShapeOutputService3TestCaseOperation1Output) SetListMember(v []*string) *OutputService3TestShapeOutputService3TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService4ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService4ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService4ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService4ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService4ProtocolTest client from just a session. -// svc := outputservice4protocoltest.New(mySession) -// -// // Create a OutputService4ProtocolTest client with additional configuration -// svc := outputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService4ProtocolTest { - c := p.ClientConfig("outputservice4protocoltest", cfgs...) - return newOutputService4ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService4ProtocolTest { - svc := &OutputService4ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice4protocoltest", - ServiceID: "OutputService4ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService4TestCaseOperation1 = "OperationName" - -// OutputService4TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService4TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService4TestCaseOperation1 for more information on using the OutputService4TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService4TestCaseOperation1Request method. -// req, resp := client.OutputService4TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *request.Request, output *OutputService4TestShapeOutputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService4TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - output = &OutputService4TestShapeOutputService4TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService4TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService4TestCaseOperation1 for usage and error information. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService4TestCaseOperation1WithContext is the same as OutputService4TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService4TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1WithContext(ctx aws.Context, input *OutputService4TestShapeOutputService4TestCaseOperation1Input, opts ...request.Option) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `locationNameList:"item" type:"list"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService4TestShapeOutputService4TestCaseOperation1Output) SetListMember(v []*string) *OutputService4TestShapeOutputService4TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService5ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService5ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService5ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService5ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService5ProtocolTest client from just a session. -// svc := outputservice5protocoltest.New(mySession) -// -// // Create a OutputService5ProtocolTest client with additional configuration -// svc := outputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService5ProtocolTest { - c := p.ClientConfig("outputservice5protocoltest", cfgs...) - return newOutputService5ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService5ProtocolTest { - svc := &OutputService5ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice5protocoltest", - ServiceID: "OutputService5ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService5TestCaseOperation1 = "OperationName" - -// OutputService5TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService5TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService5TestCaseOperation1 for more information on using the OutputService5TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService5TestCaseOperation1Request method. -// req, resp := client.OutputService5TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *request.Request, output *OutputService5TestShapeOutputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService5TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - output = &OutputService5TestShapeOutputService5TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService5TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService5TestCaseOperation1 for usage and error information. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService5TestCaseOperation1WithContext is the same as OutputService5TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService5TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1WithContext(ctx aws.Context, input *OutputService5TestShapeOutputService5TestCaseOperation1Input, opts ...request.Option) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `type:"list" flattened:"true"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService5TestShapeOutputService5TestCaseOperation1Output) SetListMember(v []*string) *OutputService5TestShapeOutputService5TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService6ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService6ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService6ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService6ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService6ProtocolTest client from just a session. -// svc := outputservice6protocoltest.New(mySession) -// -// // Create a OutputService6ProtocolTest client with additional configuration -// svc := outputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService6ProtocolTest { - c := p.ClientConfig("outputservice6protocoltest", cfgs...) - return newOutputService6ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService6ProtocolTest { - svc := &OutputService6ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice6protocoltest", - ServiceID: "OutputService6ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService6TestCaseOperation1 = "OperationName" - -// OutputService6TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService6TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService6TestCaseOperation1 for more information on using the OutputService6TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService6TestCaseOperation1Request method. -// req, resp := client.OutputService6TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *request.Request, output *OutputService6TestShapeOutputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService6TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - output = &OutputService6TestShapeOutputService6TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService6TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService6TestCaseOperation1 for usage and error information. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService6TestCaseOperation1WithContext is the same as OutputService6TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService6TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1WithContext(ctx aws.Context, input *OutputService6TestShapeOutputService6TestCaseOperation1Input, opts ...request.Option) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*OutputService6TestShapeStructureType `type:"map"` -} - -// SetMap sets the Map field's value. -func (s *OutputService6TestShapeOutputService6TestCaseOperation1Output) SetMap(v map[string]*OutputService6TestShapeStructureType) *OutputService6TestShapeOutputService6TestCaseOperation1Output { - s.Map = v - return s -} - -type OutputService6TestShapeStructureType struct { - _ struct{} `type:"structure"` - - Foo *string `locationName:"foo" type:"string"` -} - -// SetFoo sets the Foo field's value. -func (s *OutputService6TestShapeStructureType) SetFoo(v string) *OutputService6TestShapeStructureType { - s.Foo = &v - return s -} - -// OutputService7ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService7ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService7ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService7ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService7ProtocolTest client from just a session. -// svc := outputservice7protocoltest.New(mySession) -// -// // Create a OutputService7ProtocolTest client with additional configuration -// svc := outputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService7ProtocolTest { - c := p.ClientConfig("outputservice7protocoltest", cfgs...) - return newOutputService7ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService7ProtocolTest { - svc := &OutputService7ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice7protocoltest", - ServiceID: "OutputService7ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService7TestCaseOperation1 = "OperationName" - -// OutputService7TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService7TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService7TestCaseOperation1 for more information on using the OutputService7TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService7TestCaseOperation1Request method. -// req, resp := client.OutputService7TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *request.Request, output *OutputService7TestShapeOutputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService7TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - output = &OutputService7TestShapeOutputService7TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService7TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService7TestCaseOperation1 for usage and error information. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService7TestCaseOperation1WithContext is the same as OutputService7TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService7TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1WithContext(ctx aws.Context, input *OutputService7TestShapeOutputService7TestCaseOperation1Input, opts ...request.Option) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*string `type:"map" flattened:"true"` -} - -// SetMap sets the Map field's value. -func (s *OutputService7TestShapeOutputService7TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService7TestShapeOutputService7TestCaseOperation1Output { - s.Map = v - return s -} - -// OutputService8ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService8ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService8ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService8ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService8ProtocolTest client from just a session. -// svc := outputservice8protocoltest.New(mySession) -// -// // Create a OutputService8ProtocolTest client with additional configuration -// svc := outputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService8ProtocolTest { - c := p.ClientConfig("outputservice8protocoltest", cfgs...) - return newOutputService8ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService8ProtocolTest { - svc := &OutputService8ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice8protocoltest", - ServiceID: "OutputService8ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService8TestCaseOperation1 = "OperationName" - -// OutputService8TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService8TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService8TestCaseOperation1 for more information on using the OutputService8TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService8TestCaseOperation1Request method. -// req, resp := client.OutputService8TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *request.Request, output *OutputService8TestShapeOutputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService8TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - output = &OutputService8TestShapeOutputService8TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService8TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService8TestCaseOperation1 for usage and error information. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService8TestCaseOperation1WithContext is the same as OutputService8TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService8TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1WithContext(ctx aws.Context, input *OutputService8TestShapeOutputService8TestCaseOperation1Input, opts ...request.Option) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"` -} - -// SetMap sets the Map field's value. -func (s *OutputService8TestShapeOutputService8TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService8TestShapeOutputService8TestCaseOperation1Output { - s.Map = v - return s -} - -// OutputService9ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService9ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService9ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService9ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService9ProtocolTest client from just a session. -// svc := outputservice9protocoltest.New(mySession) -// -// // Create a OutputService9ProtocolTest client with additional configuration -// svc := outputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService9ProtocolTest { - c := p.ClientConfig("outputservice9protocoltest", cfgs...) - return newOutputService9ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService9ProtocolTest { - svc := &OutputService9ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice9protocoltest", - ServiceID: "OutputService9ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService9TestCaseOperation1 = "OperationName" - -// OutputService9TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService9TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService9TestCaseOperation1 for more information on using the OutputService9TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService9TestCaseOperation1Request method. -// req, resp := client.OutputService9TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *request.Request, output *OutputService9TestShapeOutputService9TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService9TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} - } - - output = &OutputService9TestShapeOutputService9TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService9TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService9TestCaseOperation1 for usage and error information. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService9TestCaseOperation1WithContext is the same as OutputService9TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService9TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1WithContext(ctx aws.Context, input *OutputService9TestShapeOutputService9TestCaseOperation1Input, opts ...request.Option) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService9TestShapeOutputService9TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService9TestShapeOutputService9TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Foo *string `type:"string"` -} - -// SetFoo sets the Foo field's value. -func (s *OutputService9TestShapeOutputService9TestCaseOperation1Output) SetFoo(v string) *OutputService9TestShapeOutputService9TestCaseOperation1Output { - s.Foo = &v - return s -} - -// OutputService10ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService10ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService10ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService10ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService10ProtocolTest client from just a session. -// svc := outputservice10protocoltest.New(mySession) -// -// // Create a OutputService10ProtocolTest client with additional configuration -// svc := outputservice10protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService10ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService10ProtocolTest { - c := p.ClientConfig("outputservice10protocoltest", cfgs...) - return newOutputService10ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService10ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService10ProtocolTest { - svc := &OutputService10ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice10protocoltest", - ServiceID: "OutputService10ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(ec2query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(ec2query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(ec2query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(ec2query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService10TestCaseOperation1 = "OperationName" - -// OutputService10TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService10TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService10TestCaseOperation1 for more information on using the OutputService10TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService10TestCaseOperation1Request method. -// req, resp := client.OutputService10TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *request.Request, output *OutputService10TestShapeOutputService10TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService10TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{} - } - - output = &OutputService10TestShapeOutputService10TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService10TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService10TestCaseOperation1 for usage and error information. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) { - req, out := c.OutputService10TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService10TestCaseOperation1WithContext is the same as OutputService10TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService10TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1WithContext(ctx aws.Context, input *OutputService10TestShapeOutputService10TestCaseOperation1Input, opts ...request.Option) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) { - req, out := c.OutputService10TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService10TestShapeOutputService10TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService10TestShapeOutputService10TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - FooEnum *string `type:"string" enum:"OutputService10TestShapeEC2EnumType"` - - ListEnums []*string `type:"list"` -} - -// SetFooEnum sets the FooEnum field's value. -func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetFooEnum(v string) *OutputService10TestShapeOutputService10TestCaseOperation1Output { - s.FooEnum = &v - return s -} - -// SetListEnums sets the ListEnums field's value. -func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetListEnums(v []*string) *OutputService10TestShapeOutputService10TestCaseOperation1Output { - s.ListEnums = v - return s -} - -const ( - // EC2EnumTypeFoo is a OutputService10TestShapeEC2EnumType enum value - EC2EnumTypeFoo = "foo" - - // EC2EnumTypeBar is a OutputService10TestShapeEC2EnumType enum value - EC2EnumTypeBar = "bar" -) - -// -// Tests begin here -// - -func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewOutputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("myname123falsetrue1.21.3200arequest-id")) - req, out := svc.OutputService1TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "a", *out.Char; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := 1.3, *out.Double; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := false, *out.FalseBool; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := 1.2, *out.Float; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := int64(200), *out.Long; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := int64(123), *out.Num; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "myname", *out.Str; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := true, *out.TrueBool; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService2ProtocolTestBlobCase1(t *testing.T) { - svc := NewOutputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("dmFsdWU=requestid")) - req, out := svc.OutputService2TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "value", string(out.Blob); e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService3ProtocolTestListsCase1(t *testing.T) { - svc := NewOutputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService3TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService4ProtocolTestListWithCustomMemberNameCase1(t *testing.T) { - svc := NewOutputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService4TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService5ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewOutputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService5TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService6ProtocolTestNormalMapCase1(t *testing.T) { - svc := NewOutputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService6TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService7ProtocolTestFlattenedMapCase1(t *testing.T) { - svc := NewOutputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService7TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService8ProtocolTestNamedMapCase1(t *testing.T) { - svc := NewOutputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService8TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService9ProtocolTestEmptyStringCase1(t *testing.T) { - svc := NewOutputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("requestid")) - req, out := svc.OutputService9TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "", *out.Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService10ProtocolTestEnumOutputCase1(t *testing.T) { - svc := NewOutputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("foofoobar")) - req, out := svc.OutputService10TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - ec2query.UnmarshalMeta(req) - ec2query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "foo", *out.FooEnum; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "foo", *out.ListEnums[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.ListEnums[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency_test.go deleted file mode 100644 index b6ea2356..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package protocol_test - -import ( - "reflect" - "testing" - - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/stretchr/testify/assert" -) - -func TestCanSetIdempotencyToken(t *testing.T) { - cases := []struct { - CanSet bool - Case interface{} - }{ - { - true, - struct { - Field *string `idempotencyToken:"true"` - }{}, - }, - { - true, - struct { - Field string `idempotencyToken:"true"` - }{}, - }, - { - false, - struct { - Field *string `idempotencyToken:"true"` - }{Field: new(string)}, - }, - { - false, - struct { - Field string `idempotencyToken:"true"` - }{Field: "value"}, - }, - { - false, - struct { - Field *int `idempotencyToken:"true"` - }{}, - }, - { - false, - struct { - Field *string - }{}, - }, - } - - for i, c := range cases { - v := reflect.Indirect(reflect.ValueOf(c.Case)) - ty := v.Type() - canSet := protocol.CanSetIdempotencyToken(v.Field(0), ty.Field(0)) - assert.Equal(t, c.CanSet, canSet, "Expect case %d can set to match", i) - } -} - -func TestSetIdempotencyToken(t *testing.T) { - cases := []struct { - Case interface{} - }{ - { - &struct { - Field *string `idempotencyToken:"true"` - }{}, - }, - { - &struct { - Field string `idempotencyToken:"true"` - }{}, - }, - { - &struct { - Field *string `idempotencyToken:"true"` - }{Field: new(string)}, - }, - { - &struct { - Field string `idempotencyToken:"true"` - }{Field: ""}, - }, - } - - for i, c := range cases { - v := reflect.Indirect(reflect.ValueOf(c.Case)) - - protocol.SetIdempotencyToken(v.Field(0)) - assert.NotEmpty(t, v.Field(0).Interface(), "Expect case %d to be set", i) - } -} - -func TestUUIDVersion4(t *testing.T) { - uuid := protocol.UUIDVersion4(make([]byte, 16)) - assert.Equal(t, `00000000-0000-4000-8000-000000000000`, uuid) - - b := make([]byte, 16) - for i := 0; i < len(b); i++ { - b[i] = 1 - } - uuid = protocol.UUIDVersion4(b) - assert.Equal(t, `01010101-0101-4101-8101-010101010101`, uuid) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue_test.go deleted file mode 100644 index 66a3c8cd..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package protocol - -import ( - "fmt" - "reflect" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" -) - -var testJSONValueCases = []struct { - Value aws.JSONValue - Mode EscapeMode - String string -}{ - { - Value: aws.JSONValue{ - "abc": 123., - }, - Mode: NoEscape, - String: `{"abc":123}`, - }, - { - Value: aws.JSONValue{ - "abc": 123., - }, - Mode: Base64Escape, - String: `eyJhYmMiOjEyM30=`, - }, - { - Value: aws.JSONValue{ - "abc": 123., - }, - Mode: QuotedEscape, - String: `"{\"abc\":123}"`, - }, -} - -func TestEncodeJSONValue(t *testing.T) { - for i, c := range testJSONValueCases { - str, err := EncodeJSONValue(c.Value, c.Mode) - if err != nil { - t.Fatalf("%d, expect no error, got %v", i, err) - } - if e, a := c.String, str; e != a { - t.Errorf("%d, expect %v encoded value, got %v", i, e, a) - } - } -} - -func TestDecodeJSONValue(t *testing.T) { - for i, c := range testJSONValueCases { - val, err := DecodeJSONValue(c.String, c.Mode) - if err != nil { - t.Fatalf("%d, expect no error, got %v", i, err) - } - if e, a := c.Value, val; !reflect.DeepEqual(e, a) { - t.Errorf("%d, expect %v encoded value, got %v", i, e, a) - } - } -} - -func TestEncodeJSONValue_PanicUnkownMode(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Errorf("expect panic, got none") - } else { - reason := fmt.Sprintf("%v", r) - if e, a := "unknown EscapeMode", reason; !strings.Contains(a, e) { - t.Errorf("expect %q to be in %v", e, a) - } - } - }() - - val := aws.JSONValue{} - - EncodeJSONValue(val, 123456) -} -func TestDecodeJSONValue_PanicUnkownMode(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Errorf("expect panic, got none") - } else { - reason := fmt.Sprintf("%v", r) - if e, a := "unknown EscapeMode", reason; !strings.Contains(a, e) { - t.Errorf("expect %q to be in %v", e, a) - } - } - }() - - DecodeJSONValue(`{"abc":123}`, 123456) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/protocol_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/protocol_test.go deleted file mode 100644 index eb2e155b..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/protocol_test.go +++ /dev/null @@ -1,203 +0,0 @@ -package protocol_test - -import ( - "net/http" - "net/url" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/ec2query" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" - "github.com/aws/aws-sdk-go/private/protocol/query" - "github.com/aws/aws-sdk-go/private/protocol/rest" - "github.com/aws/aws-sdk-go/private/protocol/restjson" - "github.com/aws/aws-sdk-go/private/protocol/restxml" -) - -func xmlData(set bool, b []byte, size, delta int) { - const openingTags = "" - const closingTags = "" - if !set { - copy(b, []byte(openingTags)) - } - if size == 0 { - copy(b[delta-len(closingTags):], []byte(closingTags)) - } -} - -func jsonData(set bool, b []byte, size, delta int) { - if !set { - copy(b, []byte("{\"A\": \"")) - } - if size == 0 { - copy(b[delta-len("\"}"):], []byte("\"}")) - } -} - -func buildNewRequest(data interface{}) *request.Request { - v := url.Values{} - v.Set("test", "TEST") - v.Add("test1", "TEST1") - - req := &request.Request{ - HTTPRequest: &http.Request{ - Header: make(http.Header), - Body: &awstesting.ReadCloser{Size: 2048}, - URL: &url.URL{ - RawQuery: v.Encode(), - }, - }, - Params: &struct { - LocationName string `locationName:"test"` - }{ - "Test", - }, - ClientInfo: metadata.ClientInfo{ - ServiceName: "test", - TargetPrefix: "test", - JSONVersion: "test", - APIVersion: "test", - Endpoint: "test", - SigningName: "test", - SigningRegion: "test", - }, - Operation: &request.Operation{ - Name: "test", - }, - } - req.HTTPResponse = &http.Response{ - Body: &awstesting.ReadCloser{Size: 2048}, - Header: http.Header{ - "X-Amzn-Requestid": []string{"1"}, - }, - StatusCode: http.StatusOK, - } - - if data == nil { - data = &struct { - _ struct{} `type:"structure"` - LocationName *string `locationName:"testName"` - Location *string `location:"statusCode"` - A *string `type:"string"` - }{} - } - - req.Data = data - - return req -} - -type expected struct { - dataType int - closed bool - size int - errExists bool -} - -const ( - jsonType = iota - xmlType -) - -func checkForLeak(data interface{}, build, fn func(*request.Request), t *testing.T, result expected) { - req := buildNewRequest(data) - reader := req.HTTPResponse.Body.(*awstesting.ReadCloser) - switch result.dataType { - case jsonType: - reader.FillData = jsonData - case xmlType: - reader.FillData = xmlData - } - build(req) - fn(req) - - if result.errExists { - assert.NotNil(t, req.Error) - } else { - assert.Nil(t, req.Error) - } - - assert.Equal(t, reader.Closed, result.closed) - assert.Equal(t, reader.Size, result.size) -} - -func TestJSONRpc(t *testing.T) { - checkForLeak(nil, jsonrpc.Build, jsonrpc.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(nil, jsonrpc.Build, jsonrpc.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - checkForLeak(nil, jsonrpc.Build, jsonrpc.UnmarshalError, t, expected{jsonType, true, 0, true}) -} - -func TestQuery(t *testing.T) { - checkForLeak(nil, query.Build, query.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(nil, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - checkForLeak(nil, query.Build, query.UnmarshalError, t, expected{jsonType, true, 0, true}) -} - -func TestRest(t *testing.T) { - // case 1: Payload io.ReadSeeker - checkForLeak(nil, rest.Build, rest.Unmarshal, t, expected{jsonType, false, 2048, false}) - checkForLeak(nil, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - - // case 2: Payload *string - // should close the body - dataStr := struct { - _ struct{} `type:"structure" payload:"Payload"` - LocationName *string `locationName:"testName"` - Location *string `location:"statusCode"` - A *string `type:"string"` - Payload *string `locationName:"payload" type:"blob" required:"true"` - }{} - checkForLeak(&dataStr, rest.Build, rest.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(&dataStr, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - - // case 3: Payload []byte - // should close the body - dataBytes := struct { - _ struct{} `type:"structure" payload:"Payload"` - LocationName *string `locationName:"testName"` - Location *string `location:"statusCode"` - A *string `type:"string"` - Payload []byte `locationName:"payload" type:"blob" required:"true"` - }{} - checkForLeak(&dataBytes, rest.Build, rest.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(&dataBytes, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - - // case 4: Payload unsupported type - // should close the body - dataUnsupported := struct { - _ struct{} `type:"structure" payload:"Payload"` - LocationName *string `locationName:"testName"` - Location *string `location:"statusCode"` - A *string `type:"string"` - Payload string `locationName:"payload" type:"blob" required:"true"` - }{} - checkForLeak(&dataUnsupported, rest.Build, rest.Unmarshal, t, expected{jsonType, true, 0, true}) - checkForLeak(&dataUnsupported, query.Build, query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) -} - -func TestRestJSON(t *testing.T) { - checkForLeak(nil, restjson.Build, restjson.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(nil, restjson.Build, restjson.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - checkForLeak(nil, restjson.Build, restjson.UnmarshalError, t, expected{jsonType, true, 0, true}) -} - -func TestRestXML(t *testing.T) { - checkForLeak(nil, restxml.Build, restxml.Unmarshal, t, expected{xmlType, true, 0, false}) - checkForLeak(nil, restxml.Build, restxml.UnmarshalMeta, t, expected{xmlType, false, 2048, false}) - checkForLeak(nil, restxml.Build, restxml.UnmarshalError, t, expected{xmlType, true, 0, true}) -} - -func TestXML(t *testing.T) { - checkForLeak(nil, ec2query.Build, ec2query.Unmarshal, t, expected{jsonType, true, 0, false}) - checkForLeak(nil, ec2query.Build, ec2query.UnmarshalMeta, t, expected{jsonType, false, 2048, false}) - checkForLeak(nil, ec2query.Build, ec2query.UnmarshalError, t, expected{jsonType, true, 0, true}) -} - -func TestProtocol(t *testing.T) { - checkForLeak(nil, restxml.Build, protocol.UnmarshalDiscardBody, t, expected{xmlType, true, 0, false}) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build_test.go deleted file mode 100644 index da3a7758..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build_test.go +++ /dev/null @@ -1,4071 +0,0 @@ -package query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/query" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/private/util" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF -var _ = aws.String -var _ = fmt.Println -var _ = reflect.Value{} - -func init() { - protocol.RandReader = &awstesting.ZeroReader{} -} - -// InputService1ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService1ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService1ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService1ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService1ProtocolTest client from just a session. -// svc := inputservice1protocoltest.New(mySession) -// -// // Create a InputService1ProtocolTest client with additional configuration -// svc := inputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService1ProtocolTest { - c := p.ClientConfig("inputservice1protocoltest", cfgs...) - return newInputService1ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService1ProtocolTest { - svc := &InputService1ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice1protocoltest", - ServiceID: "InputService1ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService1TestCaseOperation1 = "OperationName" - -// InputService1TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService1TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService1TestCaseOperation1 for more information on using the InputService1TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService1TestCaseOperation1Request method. -// req, resp := client.InputService1TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputService1TestCaseOperation3Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService1TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService1TestShapeInputService1TestCaseOperation3Input{} - } - - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService1TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService1TestCaseOperation1 for usage and error information. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputService1TestCaseOperation3Input) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService1TestCaseOperation1WithContext is the same as InputService1TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService1TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1WithContext(ctx aws.Context, input *InputService1TestShapeInputService1TestCaseOperation3Input, opts ...request.Option) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService1TestCaseOperation2 = "OperationName" - -// InputService1TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService1TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService1TestCaseOperation2 for more information on using the InputService1TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService1TestCaseOperation2Request method. -// req, resp := client.InputService1TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService1ProtocolTest) InputService1TestCaseOperation2Request(input *InputService1TestShapeInputService1TestCaseOperation3Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService1TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService1TestShapeInputService1TestCaseOperation3Input{} - } - - output = &InputService1TestShapeInputService1TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService1TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService1TestCaseOperation2 for usage and error information. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation2(input *InputService1TestShapeInputService1TestCaseOperation3Input) (*InputService1TestShapeInputService1TestCaseOperation2Output, error) { - req, out := c.InputService1TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService1TestCaseOperation2WithContext is the same as InputService1TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService1TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation2WithContext(ctx aws.Context, input *InputService1TestShapeInputService1TestCaseOperation3Input, opts ...request.Option) (*InputService1TestShapeInputService1TestCaseOperation2Output, error) { - req, out := c.InputService1TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService1TestCaseOperation3 = "OperationName" - -// InputService1TestCaseOperation3Request generates a "aws/request.Request" representing the -// client's request for the InputService1TestCaseOperation3 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService1TestCaseOperation3 for more information on using the InputService1TestCaseOperation3 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService1TestCaseOperation3Request method. -// req, resp := client.InputService1TestCaseOperation3Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService1ProtocolTest) InputService1TestCaseOperation3Request(input *InputService1TestShapeInputService1TestCaseOperation3Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation3Output) { - op := &request.Operation{ - Name: opInputService1TestCaseOperation3, - HTTPPath: "/", - } - - if input == nil { - input = &InputService1TestShapeInputService1TestCaseOperation3Input{} - } - - output = &InputService1TestShapeInputService1TestCaseOperation3Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService1TestCaseOperation3 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService1TestCaseOperation3 for usage and error information. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation3(input *InputService1TestShapeInputService1TestCaseOperation3Input) (*InputService1TestShapeInputService1TestCaseOperation3Output, error) { - req, out := c.InputService1TestCaseOperation3Request(input) - return out, req.Send() -} - -// InputService1TestCaseOperation3WithContext is the same as InputService1TestCaseOperation3 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService1TestCaseOperation3 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation3WithContext(ctx aws.Context, input *InputService1TestShapeInputService1TestCaseOperation3Input, opts ...request.Option) (*InputService1TestShapeInputService1TestCaseOperation3Output, error) { - req, out := c.InputService1TestCaseOperation3Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService1TestShapeInputService1TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -type InputService1TestShapeInputService1TestCaseOperation3Input struct { - _ struct{} `type:"structure"` - - Bar *string `type:"string"` - - Baz *bool `type:"boolean"` - - Foo *string `type:"string"` -} - -// SetBar sets the Bar field's value. -func (s *InputService1TestShapeInputService1TestCaseOperation3Input) SetBar(v string) *InputService1TestShapeInputService1TestCaseOperation3Input { - s.Bar = &v - return s -} - -// SetBaz sets the Baz field's value. -func (s *InputService1TestShapeInputService1TestCaseOperation3Input) SetBaz(v bool) *InputService1TestShapeInputService1TestCaseOperation3Input { - s.Baz = &v - return s -} - -// SetFoo sets the Foo field's value. -func (s *InputService1TestShapeInputService1TestCaseOperation3Input) SetFoo(v string) *InputService1TestShapeInputService1TestCaseOperation3Input { - s.Foo = &v - return s -} - -type InputService1TestShapeInputService1TestCaseOperation3Output struct { - _ struct{} `type:"structure"` -} - -// InputService2ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService2ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService2ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService2ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService2ProtocolTest client from just a session. -// svc := inputservice2protocoltest.New(mySession) -// -// // Create a InputService2ProtocolTest client with additional configuration -// svc := inputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService2ProtocolTest { - c := p.ClientConfig("inputservice2protocoltest", cfgs...) - return newInputService2ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService2ProtocolTest { - svc := &InputService2ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice2protocoltest", - ServiceID: "InputService2ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService2TestCaseOperation1 = "OperationName" - -// InputService2TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService2TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService2TestCaseOperation1 for more information on using the InputService2TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService2TestCaseOperation1Request method. -// req, resp := client.InputService2TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputService2TestCaseOperation1Input) (req *request.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService2TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService2TestShapeInputService2TestCaseOperation1Input{} - } - - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService2TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService2TestCaseOperation1 for usage and error information. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputService2TestCaseOperation1Input) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService2TestCaseOperation1WithContext is the same as InputService2TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService2TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1WithContext(ctx aws.Context, input *InputService2TestShapeInputService2TestCaseOperation1Input, opts ...request.Option) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService2TestShapeInputService2TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - StructArg *InputService2TestShapeStructType `type:"structure"` -} - -// SetStructArg sets the StructArg field's value. -func (s *InputService2TestShapeInputService2TestCaseOperation1Input) SetStructArg(v *InputService2TestShapeStructType) *InputService2TestShapeInputService2TestCaseOperation1Input { - s.StructArg = v - return s -} - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService2TestShapeStructType struct { - _ struct{} `type:"structure"` - - ScalarArg *string `type:"string"` -} - -// SetScalarArg sets the ScalarArg field's value. -func (s *InputService2TestShapeStructType) SetScalarArg(v string) *InputService2TestShapeStructType { - s.ScalarArg = &v - return s -} - -// InputService3ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService3ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService3ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService3ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService3ProtocolTest client from just a session. -// svc := inputservice3protocoltest.New(mySession) -// -// // Create a InputService3ProtocolTest client with additional configuration -// svc := inputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService3ProtocolTest { - c := p.ClientConfig("inputservice3protocoltest", cfgs...) - return newInputService3ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService3ProtocolTest { - svc := &InputService3ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice3protocoltest", - ServiceID: "InputService3ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService3TestCaseOperation1 = "OperationName" - -// InputService3TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService3TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService3TestCaseOperation1 for more information on using the InputService3TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService3TestCaseOperation1Request method. -// req, resp := client.InputService3TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputService3TestCaseOperation2Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService3TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService3TestShapeInputService3TestCaseOperation2Input{} - } - - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService3TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService3TestCaseOperation1 for usage and error information. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputService3TestCaseOperation2Input) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService3TestCaseOperation1WithContext is the same as InputService3TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService3TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1WithContext(ctx aws.Context, input *InputService3TestShapeInputService3TestCaseOperation2Input, opts ...request.Option) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService3TestCaseOperation2 = "OperationName" - -// InputService3TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService3TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService3TestCaseOperation2 for more information on using the InputService3TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService3TestCaseOperation2Request method. -// req, resp := client.InputService3TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService3ProtocolTest) InputService3TestCaseOperation2Request(input *InputService3TestShapeInputService3TestCaseOperation2Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService3TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService3TestShapeInputService3TestCaseOperation2Input{} - } - - output = &InputService3TestShapeInputService3TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService3TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService3TestCaseOperation2 for usage and error information. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation2(input *InputService3TestShapeInputService3TestCaseOperation2Input) (*InputService3TestShapeInputService3TestCaseOperation2Output, error) { - req, out := c.InputService3TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService3TestCaseOperation2WithContext is the same as InputService3TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService3TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation2WithContext(ctx aws.Context, input *InputService3TestShapeInputService3TestCaseOperation2Input, opts ...request.Option) (*InputService3TestShapeInputService3TestCaseOperation2Output, error) { - req, out := c.InputService3TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService3TestShapeInputService3TestCaseOperation2Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `type:"list"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService3TestShapeInputService3TestCaseOperation2Input) SetListArg(v []*string) *InputService3TestShapeInputService3TestCaseOperation2Input { - s.ListArg = v - return s -} - -type InputService3TestShapeInputService3TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -// InputService4ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService4ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService4ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService4ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService4ProtocolTest client from just a session. -// svc := inputservice4protocoltest.New(mySession) -// -// // Create a InputService4ProtocolTest client with additional configuration -// svc := inputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService4ProtocolTest { - c := p.ClientConfig("inputservice4protocoltest", cfgs...) - return newInputService4ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService4ProtocolTest { - svc := &InputService4ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice4protocoltest", - ServiceID: "InputService4ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService4TestCaseOperation1 = "OperationName" - -// InputService4TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService4TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService4TestCaseOperation1 for more information on using the InputService4TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService4TestCaseOperation1Request method. -// req, resp := client.InputService4TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputService4TestCaseOperation2Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService4TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService4TestShapeInputService4TestCaseOperation2Input{} - } - - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService4TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService4TestCaseOperation1 for usage and error information. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputService4TestCaseOperation2Input) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService4TestCaseOperation1WithContext is the same as InputService4TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService4TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1WithContext(ctx aws.Context, input *InputService4TestShapeInputService4TestCaseOperation2Input, opts ...request.Option) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService4TestCaseOperation2 = "OperationName" - -// InputService4TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService4TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService4TestCaseOperation2 for more information on using the InputService4TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService4TestCaseOperation2Request method. -// req, resp := client.InputService4TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService4ProtocolTest) InputService4TestCaseOperation2Request(input *InputService4TestShapeInputService4TestCaseOperation2Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService4TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService4TestShapeInputService4TestCaseOperation2Input{} - } - - output = &InputService4TestShapeInputService4TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService4TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService4TestCaseOperation2 for usage and error information. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation2(input *InputService4TestShapeInputService4TestCaseOperation2Input) (*InputService4TestShapeInputService4TestCaseOperation2Output, error) { - req, out := c.InputService4TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService4TestCaseOperation2WithContext is the same as InputService4TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService4TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation2WithContext(ctx aws.Context, input *InputService4TestShapeInputService4TestCaseOperation2Input, opts ...request.Option) (*InputService4TestShapeInputService4TestCaseOperation2Output, error) { - req, out := c.InputService4TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService4TestShapeInputService4TestCaseOperation2Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `type:"list" flattened:"true"` - - NamedListArg []*string `locationNameList:"Foo" type:"list" flattened:"true"` - - ScalarArg *string `type:"string"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation2Input) SetListArg(v []*string) *InputService4TestShapeInputService4TestCaseOperation2Input { - s.ListArg = v - return s -} - -// SetNamedListArg sets the NamedListArg field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation2Input) SetNamedListArg(v []*string) *InputService4TestShapeInputService4TestCaseOperation2Input { - s.NamedListArg = v - return s -} - -// SetScalarArg sets the ScalarArg field's value. -func (s *InputService4TestShapeInputService4TestCaseOperation2Input) SetScalarArg(v string) *InputService4TestShapeInputService4TestCaseOperation2Input { - s.ScalarArg = &v - return s -} - -type InputService4TestShapeInputService4TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -// InputService5ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService5ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService5ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService5ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService5ProtocolTest client from just a session. -// svc := inputservice5protocoltest.New(mySession) -// -// // Create a InputService5ProtocolTest client with additional configuration -// svc := inputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService5ProtocolTest { - c := p.ClientConfig("inputservice5protocoltest", cfgs...) - return newInputService5ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService5ProtocolTest { - svc := &InputService5ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice5protocoltest", - ServiceID: "InputService5ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService5TestCaseOperation1 = "OperationName" - -// InputService5TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService5TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService5TestCaseOperation1 for more information on using the InputService5TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService5TestCaseOperation1Request method. -// req, resp := client.InputService5TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputService5TestCaseOperation1Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService5TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService5TestShapeInputService5TestCaseOperation1Input{} - } - - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService5TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService5TestCaseOperation1 for usage and error information. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputService5TestCaseOperation1Input) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService5TestCaseOperation1WithContext is the same as InputService5TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService5TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1WithContext(ctx aws.Context, input *InputService5TestShapeInputService5TestCaseOperation1Input, opts ...request.Option) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService5TestShapeInputService5TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - MapArg map[string]*string `type:"map" flattened:"true"` -} - -// SetMapArg sets the MapArg field's value. -func (s *InputService5TestShapeInputService5TestCaseOperation1Input) SetMapArg(v map[string]*string) *InputService5TestShapeInputService5TestCaseOperation1Input { - s.MapArg = v - return s -} - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService6ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService6ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService6ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService6ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService6ProtocolTest client from just a session. -// svc := inputservice6protocoltest.New(mySession) -// -// // Create a InputService6ProtocolTest client with additional configuration -// svc := inputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService6ProtocolTest { - c := p.ClientConfig("inputservice6protocoltest", cfgs...) - return newInputService6ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService6ProtocolTest { - svc := &InputService6ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice6protocoltest", - ServiceID: "InputService6ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService6TestCaseOperation1 = "OperationName" - -// InputService6TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService6TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService6TestCaseOperation1 for more information on using the InputService6TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService6TestCaseOperation1Request method. -// req, resp := client.InputService6TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputService6TestCaseOperation1Input) (req *request.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService6TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService6TestShapeInputService6TestCaseOperation1Input{} - } - - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService6TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService6TestCaseOperation1 for usage and error information. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputService6TestCaseOperation1Input) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService6TestCaseOperation1WithContext is the same as InputService6TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService6TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1WithContext(ctx aws.Context, input *InputService6TestShapeInputService6TestCaseOperation1Input, opts ...request.Option) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService6TestShapeInputService6TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `locationNameList:"item" type:"list"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService6TestShapeInputService6TestCaseOperation1Input) SetListArg(v []*string) *InputService6TestShapeInputService6TestCaseOperation1Input { - s.ListArg = v - return s -} - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService7ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService7ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService7ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService7ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService7ProtocolTest client from just a session. -// svc := inputservice7protocoltest.New(mySession) -// -// // Create a InputService7ProtocolTest client with additional configuration -// svc := inputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService7ProtocolTest { - c := p.ClientConfig("inputservice7protocoltest", cfgs...) - return newInputService7ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService7ProtocolTest { - svc := &InputService7ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice7protocoltest", - ServiceID: "InputService7ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService7TestCaseOperation1 = "OperationName" - -// InputService7TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService7TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService7TestCaseOperation1 for more information on using the InputService7TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService7TestCaseOperation1Request method. -// req, resp := client.InputService7TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputService7TestCaseOperation1Input) (req *request.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService7TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService7TestShapeInputService7TestCaseOperation1Input{} - } - - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService7TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService7TestCaseOperation1 for usage and error information. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputService7TestCaseOperation1Input) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService7TestCaseOperation1WithContext is the same as InputService7TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService7TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1WithContext(ctx aws.Context, input *InputService7TestShapeInputService7TestCaseOperation1Input, opts ...request.Option) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService7TestShapeInputService7TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - ListArg []*string `locationNameList:"ListArgLocation" type:"list" flattened:"true"` - - ScalarArg *string `type:"string"` -} - -// SetListArg sets the ListArg field's value. -func (s *InputService7TestShapeInputService7TestCaseOperation1Input) SetListArg(v []*string) *InputService7TestShapeInputService7TestCaseOperation1Input { - s.ListArg = v - return s -} - -// SetScalarArg sets the ScalarArg field's value. -func (s *InputService7TestShapeInputService7TestCaseOperation1Input) SetScalarArg(v string) *InputService7TestShapeInputService7TestCaseOperation1Input { - s.ScalarArg = &v - return s -} - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService8ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService8ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService8ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService8ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService8ProtocolTest client from just a session. -// svc := inputservice8protocoltest.New(mySession) -// -// // Create a InputService8ProtocolTest client with additional configuration -// svc := inputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService8ProtocolTest { - c := p.ClientConfig("inputservice8protocoltest", cfgs...) - return newInputService8ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService8ProtocolTest { - svc := &InputService8ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice8protocoltest", - ServiceID: "InputService8ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService8TestCaseOperation1 = "OperationName" - -// InputService8TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService8TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService8TestCaseOperation1 for more information on using the InputService8TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService8TestCaseOperation1Request method. -// req, resp := client.InputService8TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputService8TestCaseOperation1Input) (req *request.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService8TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService8TestShapeInputService8TestCaseOperation1Input{} - } - - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService8TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService8TestCaseOperation1 for usage and error information. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputService8TestCaseOperation1Input) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService8TestCaseOperation1WithContext is the same as InputService8TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService8TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1WithContext(ctx aws.Context, input *InputService8TestShapeInputService8TestCaseOperation1Input, opts ...request.Option) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService8TestShapeInputService8TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - MapArg map[string]*string `type:"map"` -} - -// SetMapArg sets the MapArg field's value. -func (s *InputService8TestShapeInputService8TestCaseOperation1Input) SetMapArg(v map[string]*string) *InputService8TestShapeInputService8TestCaseOperation1Input { - s.MapArg = v - return s -} - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService9ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService9ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService9ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService9ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService9ProtocolTest client from just a session. -// svc := inputservice9protocoltest.New(mySession) -// -// // Create a InputService9ProtocolTest client with additional configuration -// svc := inputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService9ProtocolTest { - c := p.ClientConfig("inputservice9protocoltest", cfgs...) - return newInputService9ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService9ProtocolTest { - svc := &InputService9ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice9protocoltest", - ServiceID: "InputService9ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService9TestCaseOperation1 = "OperationName" - -// InputService9TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService9TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService9TestCaseOperation1 for more information on using the InputService9TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService9TestCaseOperation1Request method. -// req, resp := client.InputService9TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputService9TestCaseOperation1Input) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService9TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService9TestShapeInputService9TestCaseOperation1Input{} - } - - output = &InputService9TestShapeInputService9TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService9TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService9TestCaseOperation1 for usage and error information. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *InputService9TestShapeInputService9TestCaseOperation1Input) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) { - req, out := c.InputService9TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService9TestCaseOperation1WithContext is the same as InputService9TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService9TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1WithContext(ctx aws.Context, input *InputService9TestShapeInputService9TestCaseOperation1Input, opts ...request.Option) (*InputService9TestShapeInputService9TestCaseOperation1Output, error) { - req, out := c.InputService9TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService9TestShapeInputService9TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - MapArg map[string]*string `locationNameKey:"TheKey" locationNameValue:"TheValue" type:"map"` -} - -// SetMapArg sets the MapArg field's value. -func (s *InputService9TestShapeInputService9TestCaseOperation1Input) SetMapArg(v map[string]*string) *InputService9TestShapeInputService9TestCaseOperation1Input { - s.MapArg = v - return s -} - -type InputService9TestShapeInputService9TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService10ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService10ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService10ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService10ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService10ProtocolTest client from just a session. -// svc := inputservice10protocoltest.New(mySession) -// -// // Create a InputService10ProtocolTest client with additional configuration -// svc := inputservice10protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService10ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService10ProtocolTest { - c := p.ClientConfig("inputservice10protocoltest", cfgs...) - return newInputService10ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService10ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService10ProtocolTest { - svc := &InputService10ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice10protocoltest", - ServiceID: "InputService10ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService10TestCaseOperation1 = "OperationName" - -// InputService10TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService10TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService10TestCaseOperation1 for more information on using the InputService10TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService10TestCaseOperation1Request method. -// req, resp := client.InputService10TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1Request(input *InputService10TestShapeInputService10TestCaseOperation1Input) (req *request.Request, output *InputService10TestShapeInputService10TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService10TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService10TestShapeInputService10TestCaseOperation1Input{} - } - - output = &InputService10TestShapeInputService10TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService10TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService10TestCaseOperation1 for usage and error information. -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1(input *InputService10TestShapeInputService10TestCaseOperation1Input) (*InputService10TestShapeInputService10TestCaseOperation1Output, error) { - req, out := c.InputService10TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService10TestCaseOperation1WithContext is the same as InputService10TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService10TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1WithContext(ctx aws.Context, input *InputService10TestShapeInputService10TestCaseOperation1Input, opts ...request.Option) (*InputService10TestShapeInputService10TestCaseOperation1Output, error) { - req, out := c.InputService10TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService10TestShapeInputService10TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - // BlobArg is automatically base64 encoded/decoded by the SDK. - BlobArg []byte `type:"blob"` -} - -// SetBlobArg sets the BlobArg field's value. -func (s *InputService10TestShapeInputService10TestCaseOperation1Input) SetBlobArg(v []byte) *InputService10TestShapeInputService10TestCaseOperation1Input { - s.BlobArg = v - return s -} - -type InputService10TestShapeInputService10TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService11ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService11ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService11ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService11ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService11ProtocolTest client from just a session. -// svc := inputservice11protocoltest.New(mySession) -// -// // Create a InputService11ProtocolTest client with additional configuration -// svc := inputservice11protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService11ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService11ProtocolTest { - c := p.ClientConfig("inputservice11protocoltest", cfgs...) - return newInputService11ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService11ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService11ProtocolTest { - svc := &InputService11ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice11protocoltest", - ServiceID: "InputService11ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService11ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService11TestCaseOperation1 = "OperationName" - -// InputService11TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService11TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService11TestCaseOperation1 for more information on using the InputService11TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService11TestCaseOperation1Request method. -// req, resp := client.InputService11TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService11ProtocolTest) InputService11TestCaseOperation1Request(input *InputService11TestShapeInputService11TestCaseOperation1Input) (req *request.Request, output *InputService11TestShapeInputService11TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService11TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService11TestShapeInputService11TestCaseOperation1Input{} - } - - output = &InputService11TestShapeInputService11TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService11TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService11TestCaseOperation1 for usage and error information. -func (c *InputService11ProtocolTest) InputService11TestCaseOperation1(input *InputService11TestShapeInputService11TestCaseOperation1Input) (*InputService11TestShapeInputService11TestCaseOperation1Output, error) { - req, out := c.InputService11TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService11TestCaseOperation1WithContext is the same as InputService11TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService11TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService11ProtocolTest) InputService11TestCaseOperation1WithContext(ctx aws.Context, input *InputService11TestShapeInputService11TestCaseOperation1Input, opts ...request.Option) (*InputService11TestShapeInputService11TestCaseOperation1Output, error) { - req, out := c.InputService11TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService11TestShapeInputService11TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - BlobArgs [][]byte `type:"list" flattened:"true"` -} - -// SetBlobArgs sets the BlobArgs field's value. -func (s *InputService11TestShapeInputService11TestCaseOperation1Input) SetBlobArgs(v [][]byte) *InputService11TestShapeInputService11TestCaseOperation1Input { - s.BlobArgs = v - return s -} - -type InputService11TestShapeInputService11TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService12ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService12ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService12ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService12ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService12ProtocolTest client from just a session. -// svc := inputservice12protocoltest.New(mySession) -// -// // Create a InputService12ProtocolTest client with additional configuration -// svc := inputservice12protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService12ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService12ProtocolTest { - c := p.ClientConfig("inputservice12protocoltest", cfgs...) - return newInputService12ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService12ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService12ProtocolTest { - svc := &InputService12ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice12protocoltest", - ServiceID: "InputService12ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService12ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService12ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService12TestCaseOperation1 = "OperationName" - -// InputService12TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService12TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService12TestCaseOperation1 for more information on using the InputService12TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService12TestCaseOperation1Request method. -// req, resp := client.InputService12TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService12ProtocolTest) InputService12TestCaseOperation1Request(input *InputService12TestShapeInputService12TestCaseOperation1Input) (req *request.Request, output *InputService12TestShapeInputService12TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService12TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService12TestShapeInputService12TestCaseOperation1Input{} - } - - output = &InputService12TestShapeInputService12TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService12TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService12TestCaseOperation1 for usage and error information. -func (c *InputService12ProtocolTest) InputService12TestCaseOperation1(input *InputService12TestShapeInputService12TestCaseOperation1Input) (*InputService12TestShapeInputService12TestCaseOperation1Output, error) { - req, out := c.InputService12TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService12TestCaseOperation1WithContext is the same as InputService12TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService12TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService12ProtocolTest) InputService12TestCaseOperation1WithContext(ctx aws.Context, input *InputService12TestShapeInputService12TestCaseOperation1Input, opts ...request.Option) (*InputService12TestShapeInputService12TestCaseOperation1Output, error) { - req, out := c.InputService12TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService12TestShapeInputService12TestCaseOperation1Input struct { - _ struct{} `type:"structure"` - - TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"` -} - -// SetTimeArg sets the TimeArg field's value. -func (s *InputService12TestShapeInputService12TestCaseOperation1Input) SetTimeArg(v time.Time) *InputService12TestShapeInputService12TestCaseOperation1Input { - s.TimeArg = &v - return s -} - -type InputService12TestShapeInputService12TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -// InputService13ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService13ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService13ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService13ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService13ProtocolTest client from just a session. -// svc := inputservice13protocoltest.New(mySession) -// -// // Create a InputService13ProtocolTest client with additional configuration -// svc := inputservice13protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService13ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService13ProtocolTest { - c := p.ClientConfig("inputservice13protocoltest", cfgs...) - return newInputService13ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService13ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService13ProtocolTest { - svc := &InputService13ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice13protocoltest", - ServiceID: "InputService13ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService13ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService13ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService13TestCaseOperation1 = "OperationName" - -// InputService13TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation1 for more information on using the InputService13TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation1Request method. -// req, resp := client.InputService13TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation1Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation1 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation1(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation1Output, error) { - req, out := c.InputService13TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation1WithContext is the same as InputService13TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation1WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation1Output, error) { - req, out := c.InputService13TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService13TestCaseOperation2 = "OperationName" - -// InputService13TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation2 for more information on using the InputService13TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation2Request method. -// req, resp := client.InputService13TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation2Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation2, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation2 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation2(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation2Output, error) { - req, out := c.InputService13TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation2WithContext is the same as InputService13TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation2WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation2Output, error) { - req, out := c.InputService13TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService13TestCaseOperation3 = "OperationName" - -// InputService13TestCaseOperation3Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation3 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation3 for more information on using the InputService13TestCaseOperation3 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation3Request method. -// req, resp := client.InputService13TestCaseOperation3Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation3Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation3Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation3, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation3Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation3 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation3 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation3(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation3Output, error) { - req, out := c.InputService13TestCaseOperation3Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation3WithContext is the same as InputService13TestCaseOperation3 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation3 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation3WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation3Output, error) { - req, out := c.InputService13TestCaseOperation3Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService13TestCaseOperation4 = "OperationName" - -// InputService13TestCaseOperation4Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation4 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation4 for more information on using the InputService13TestCaseOperation4 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation4Request method. -// req, resp := client.InputService13TestCaseOperation4Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation4Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation4Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation4, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation4Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation4 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation4 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation4(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation4Output, error) { - req, out := c.InputService13TestCaseOperation4Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation4WithContext is the same as InputService13TestCaseOperation4 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation4 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation4WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation4Output, error) { - req, out := c.InputService13TestCaseOperation4Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService13TestCaseOperation5 = "OperationName" - -// InputService13TestCaseOperation5Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation5 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation5 for more information on using the InputService13TestCaseOperation5 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation5Request method. -// req, resp := client.InputService13TestCaseOperation5Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation5Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation5Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation5, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation5Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation5 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation5 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation5(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation5Output, error) { - req, out := c.InputService13TestCaseOperation5Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation5WithContext is the same as InputService13TestCaseOperation5 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation5 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation5WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation5Output, error) { - req, out := c.InputService13TestCaseOperation5Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService13TestCaseOperation6 = "OperationName" - -// InputService13TestCaseOperation6Request generates a "aws/request.Request" representing the -// client's request for the InputService13TestCaseOperation6 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService13TestCaseOperation6 for more information on using the InputService13TestCaseOperation6 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService13TestCaseOperation6Request method. -// req, resp := client.InputService13TestCaseOperation6Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService13ProtocolTest) InputService13TestCaseOperation6Request(input *InputService13TestShapeInputService13TestCaseOperation6Input) (req *request.Request, output *InputService13TestShapeInputService13TestCaseOperation6Output) { - op := &request.Operation{ - Name: opInputService13TestCaseOperation6, - HTTPPath: "/", - } - - if input == nil { - input = &InputService13TestShapeInputService13TestCaseOperation6Input{} - } - - output = &InputService13TestShapeInputService13TestCaseOperation6Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService13TestCaseOperation6 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService13TestCaseOperation6 for usage and error information. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation6(input *InputService13TestShapeInputService13TestCaseOperation6Input) (*InputService13TestShapeInputService13TestCaseOperation6Output, error) { - req, out := c.InputService13TestCaseOperation6Request(input) - return out, req.Send() -} - -// InputService13TestCaseOperation6WithContext is the same as InputService13TestCaseOperation6 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService13TestCaseOperation6 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation6WithContext(ctx aws.Context, input *InputService13TestShapeInputService13TestCaseOperation6Input, opts ...request.Option) (*InputService13TestShapeInputService13TestCaseOperation6Output, error) { - req, out := c.InputService13TestCaseOperation6Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService13TestShapeInputService13TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation3Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation4Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation5Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation6Input struct { - _ struct{} `type:"structure"` - - RecursiveStruct *InputService13TestShapeRecursiveStructType `type:"structure"` -} - -// SetRecursiveStruct sets the RecursiveStruct field's value. -func (s *InputService13TestShapeInputService13TestCaseOperation6Input) SetRecursiveStruct(v *InputService13TestShapeRecursiveStructType) *InputService13TestShapeInputService13TestCaseOperation6Input { - s.RecursiveStruct = v - return s -} - -type InputService13TestShapeInputService13TestCaseOperation6Output struct { - _ struct{} `type:"structure"` -} - -type InputService13TestShapeRecursiveStructType struct { - _ struct{} `type:"structure"` - - NoRecurse *string `type:"string"` - - RecursiveList []*InputService13TestShapeRecursiveStructType `type:"list"` - - RecursiveMap map[string]*InputService13TestShapeRecursiveStructType `type:"map"` - - RecursiveStruct *InputService13TestShapeRecursiveStructType `type:"structure"` -} - -// SetNoRecurse sets the NoRecurse field's value. -func (s *InputService13TestShapeRecursiveStructType) SetNoRecurse(v string) *InputService13TestShapeRecursiveStructType { - s.NoRecurse = &v - return s -} - -// SetRecursiveList sets the RecursiveList field's value. -func (s *InputService13TestShapeRecursiveStructType) SetRecursiveList(v []*InputService13TestShapeRecursiveStructType) *InputService13TestShapeRecursiveStructType { - s.RecursiveList = v - return s -} - -// SetRecursiveMap sets the RecursiveMap field's value. -func (s *InputService13TestShapeRecursiveStructType) SetRecursiveMap(v map[string]*InputService13TestShapeRecursiveStructType) *InputService13TestShapeRecursiveStructType { - s.RecursiveMap = v - return s -} - -// SetRecursiveStruct sets the RecursiveStruct field's value. -func (s *InputService13TestShapeRecursiveStructType) SetRecursiveStruct(v *InputService13TestShapeRecursiveStructType) *InputService13TestShapeRecursiveStructType { - s.RecursiveStruct = v - return s -} - -// InputService14ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService14ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService14ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService14ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService14ProtocolTest client from just a session. -// svc := inputservice14protocoltest.New(mySession) -// -// // Create a InputService14ProtocolTest client with additional configuration -// svc := inputservice14protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService14ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService14ProtocolTest { - c := p.ClientConfig("inputservice14protocoltest", cfgs...) - return newInputService14ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService14ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService14ProtocolTest { - svc := &InputService14ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice14protocoltest", - ServiceID: "InputService14ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService14ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService14ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService14TestCaseOperation1 = "OperationName" - -// InputService14TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService14TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService14TestCaseOperation1 for more information on using the InputService14TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService14TestCaseOperation1Request method. -// req, resp := client.InputService14TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService14ProtocolTest) InputService14TestCaseOperation1Request(input *InputService14TestShapeInputService14TestCaseOperation2Input) (req *request.Request, output *InputService14TestShapeInputService14TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService14TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService14TestShapeInputService14TestCaseOperation2Input{} - } - - output = &InputService14TestShapeInputService14TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService14TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService14TestCaseOperation1 for usage and error information. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation1(input *InputService14TestShapeInputService14TestCaseOperation2Input) (*InputService14TestShapeInputService14TestCaseOperation1Output, error) { - req, out := c.InputService14TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService14TestCaseOperation1WithContext is the same as InputService14TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService14TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation1WithContext(ctx aws.Context, input *InputService14TestShapeInputService14TestCaseOperation2Input, opts ...request.Option) (*InputService14TestShapeInputService14TestCaseOperation1Output, error) { - req, out := c.InputService14TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService14TestCaseOperation2 = "OperationName" - -// InputService14TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService14TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService14TestCaseOperation2 for more information on using the InputService14TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService14TestCaseOperation2Request method. -// req, resp := client.InputService14TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService14ProtocolTest) InputService14TestCaseOperation2Request(input *InputService14TestShapeInputService14TestCaseOperation2Input) (req *request.Request, output *InputService14TestShapeInputService14TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService14TestCaseOperation2, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService14TestShapeInputService14TestCaseOperation2Input{} - } - - output = &InputService14TestShapeInputService14TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService14TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService14TestCaseOperation2 for usage and error information. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation2(input *InputService14TestShapeInputService14TestCaseOperation2Input) (*InputService14TestShapeInputService14TestCaseOperation2Output, error) { - req, out := c.InputService14TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService14TestCaseOperation2WithContext is the same as InputService14TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService14TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation2WithContext(ctx aws.Context, input *InputService14TestShapeInputService14TestCaseOperation2Input, opts ...request.Option) (*InputService14TestShapeInputService14TestCaseOperation2Output, error) { - req, out := c.InputService14TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService14TestShapeInputService14TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService14TestShapeInputService14TestCaseOperation2Input struct { - _ struct{} `type:"structure"` - - Token *string `type:"string" idempotencyToken:"true"` -} - -// SetToken sets the Token field's value. -func (s *InputService14TestShapeInputService14TestCaseOperation2Input) SetToken(v string) *InputService14TestShapeInputService14TestCaseOperation2Input { - s.Token = &v - return s -} - -type InputService14TestShapeInputService14TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -// InputService15ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// InputService15ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type InputService15ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the InputService15ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a InputService15ProtocolTest client from just a session. -// svc := inputservice15protocoltest.New(mySession) -// -// // Create a InputService15ProtocolTest client with additional configuration -// svc := inputservice15protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewInputService15ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *InputService15ProtocolTest { - c := p.ClientConfig("inputservice15protocoltest", cfgs...) - return newInputService15ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newInputService15ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *InputService15ProtocolTest { - svc := &InputService15ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "inputservice15protocoltest", - ServiceID: "InputService15ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2014-01-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a InputService15ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService15ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService15TestCaseOperation1 = "OperationName" - -// InputService15TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the InputService15TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService15TestCaseOperation1 for more information on using the InputService15TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService15TestCaseOperation1Request method. -// req, resp := client.InputService15TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService15ProtocolTest) InputService15TestCaseOperation1Request(input *InputService15TestShapeInputService15TestCaseOperation3Input) (req *request.Request, output *InputService15TestShapeInputService15TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService15TestCaseOperation1, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService15TestShapeInputService15TestCaseOperation3Input{} - } - - output = &InputService15TestShapeInputService15TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService15TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService15TestCaseOperation1 for usage and error information. -func (c *InputService15ProtocolTest) InputService15TestCaseOperation1(input *InputService15TestShapeInputService15TestCaseOperation3Input) (*InputService15TestShapeInputService15TestCaseOperation1Output, error) { - req, out := c.InputService15TestCaseOperation1Request(input) - return out, req.Send() -} - -// InputService15TestCaseOperation1WithContext is the same as InputService15TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService15TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService15ProtocolTest) InputService15TestCaseOperation1WithContext(ctx aws.Context, input *InputService15TestShapeInputService15TestCaseOperation3Input, opts ...request.Option) (*InputService15TestShapeInputService15TestCaseOperation1Output, error) { - req, out := c.InputService15TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService15TestCaseOperation2 = "OperationName" - -// InputService15TestCaseOperation2Request generates a "aws/request.Request" representing the -// client's request for the InputService15TestCaseOperation2 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService15TestCaseOperation2 for more information on using the InputService15TestCaseOperation2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService15TestCaseOperation2Request method. -// req, resp := client.InputService15TestCaseOperation2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService15ProtocolTest) InputService15TestCaseOperation2Request(input *InputService15TestShapeInputService15TestCaseOperation3Input) (req *request.Request, output *InputService15TestShapeInputService15TestCaseOperation2Output) { - op := &request.Operation{ - Name: opInputService15TestCaseOperation2, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService15TestShapeInputService15TestCaseOperation3Input{} - } - - output = &InputService15TestShapeInputService15TestCaseOperation2Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService15TestCaseOperation2 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService15TestCaseOperation2 for usage and error information. -func (c *InputService15ProtocolTest) InputService15TestCaseOperation2(input *InputService15TestShapeInputService15TestCaseOperation3Input) (*InputService15TestShapeInputService15TestCaseOperation2Output, error) { - req, out := c.InputService15TestCaseOperation2Request(input) - return out, req.Send() -} - -// InputService15TestCaseOperation2WithContext is the same as InputService15TestCaseOperation2 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService15TestCaseOperation2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService15ProtocolTest) InputService15TestCaseOperation2WithContext(ctx aws.Context, input *InputService15TestShapeInputService15TestCaseOperation3Input, opts ...request.Option) (*InputService15TestShapeInputService15TestCaseOperation2Output, error) { - req, out := c.InputService15TestCaseOperation2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opInputService15TestCaseOperation3 = "OperationName" - -// InputService15TestCaseOperation3Request generates a "aws/request.Request" representing the -// client's request for the InputService15TestCaseOperation3 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See InputService15TestCaseOperation3 for more information on using the InputService15TestCaseOperation3 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the InputService15TestCaseOperation3Request method. -// req, resp := client.InputService15TestCaseOperation3Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *InputService15ProtocolTest) InputService15TestCaseOperation3Request(input *InputService15TestShapeInputService15TestCaseOperation3Input) (req *request.Request, output *InputService15TestShapeInputService15TestCaseOperation3Output) { - op := &request.Operation{ - Name: opInputService15TestCaseOperation3, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &InputService15TestShapeInputService15TestCaseOperation3Input{} - } - - output = &InputService15TestShapeInputService15TestCaseOperation3Output{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// InputService15TestCaseOperation3 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation InputService15TestCaseOperation3 for usage and error information. -func (c *InputService15ProtocolTest) InputService15TestCaseOperation3(input *InputService15TestShapeInputService15TestCaseOperation3Input) (*InputService15TestShapeInputService15TestCaseOperation3Output, error) { - req, out := c.InputService15TestCaseOperation3Request(input) - return out, req.Send() -} - -// InputService15TestCaseOperation3WithContext is the same as InputService15TestCaseOperation3 with the addition of -// the ability to pass a context and additional request options. -// -// See InputService15TestCaseOperation3 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *InputService15ProtocolTest) InputService15TestCaseOperation3WithContext(ctx aws.Context, input *InputService15TestShapeInputService15TestCaseOperation3Input, opts ...request.Option) (*InputService15TestShapeInputService15TestCaseOperation3Output, error) { - req, out := c.InputService15TestCaseOperation3Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type InputService15TestShapeInputService15TestCaseOperation1Output struct { - _ struct{} `type:"structure"` -} - -type InputService15TestShapeInputService15TestCaseOperation2Output struct { - _ struct{} `type:"structure"` -} - -type InputService15TestShapeInputService15TestCaseOperation3Input struct { - _ struct{} `type:"structure"` - - FooEnum *string `type:"string" enum:"InputService15TestShapeEnumType"` - - ListEnums []*string `type:"list"` -} - -// SetFooEnum sets the FooEnum field's value. -func (s *InputService15TestShapeInputService15TestCaseOperation3Input) SetFooEnum(v string) *InputService15TestShapeInputService15TestCaseOperation3Input { - s.FooEnum = &v - return s -} - -// SetListEnums sets the ListEnums field's value. -func (s *InputService15TestShapeInputService15TestCaseOperation3Input) SetListEnums(v []*string) *InputService15TestShapeInputService15TestCaseOperation3Input { - s.ListEnums = v - return s -} - -type InputService15TestShapeInputService15TestCaseOperation3Output struct { - _ struct{} `type:"structure"` -} - -const ( - // EnumTypeFoo is a InputService15TestShapeEnumType enum value - EnumTypeFoo = "foo" - - // EnumTypeBar is a InputService15TestShapeEnumType enum value - EnumTypeBar = "bar" -) - -// -// Tests begin here -// - -func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewInputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService1TestShapeInputService1TestCaseOperation3Input{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - } - req, _ := svc.InputService1TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Bar=val2&Foo=val1&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService1ProtocolTestScalarMembersCase2(t *testing.T) { - svc := NewInputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService1TestShapeInputService1TestCaseOperation3Input{ - Baz: aws.Bool(true), - } - req, _ := svc.InputService1TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Baz=true&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService1ProtocolTestScalarMembersCase3(t *testing.T) { - svc := NewInputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService1TestShapeInputService1TestCaseOperation3Input{ - Baz: aws.Bool(false), - } - req, _ := svc.InputService1TestCaseOperation3Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Baz=false&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService2ProtocolTestNestedStructureMembersCase1(t *testing.T) { - svc := NewInputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService2TestShapeInputService2TestCaseOperation1Input{ - StructArg: &InputService2TestShapeStructType{ - ScalarArg: aws.String("foo"), - }, - } - req, _ := svc.InputService2TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&StructArg.ScalarArg=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestListTypesCase1(t *testing.T) { - svc := NewInputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService3TestShapeInputService3TestCaseOperation2Input{ - ListArg: []*string{ - aws.String("foo"), - aws.String("bar"), - aws.String("baz"), - }, - } - req, _ := svc.InputService3TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArg.member.1=foo&ListArg.member.2=bar&ListArg.member.3=baz&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestListTypesCase2(t *testing.T) { - svc := NewInputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService3TestShapeInputService3TestCaseOperation2Input{ - ListArg: []*string{}, - } - req, _ := svc.InputService3TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArg=&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewInputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService4TestShapeInputService4TestCaseOperation2Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - ScalarArg: aws.String("foo"), - } - req, _ := svc.InputService4TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArg.1=a&ListArg.2=b&ListArg.3=c&ScalarArg=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestFlattenedListCase2(t *testing.T) { - svc := NewInputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService4TestShapeInputService4TestCaseOperation2Input{ - NamedListArg: []*string{ - aws.String("a"), - }, - } - req, _ := svc.InputService4TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Foo.1=a&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestSerializeFlattenedMapTypeCase1(t *testing.T) { - svc := NewInputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService5TestShapeInputService5TestCaseOperation1Input{ - MapArg: map[string]*string{ - "key1": aws.String("val1"), - "key2": aws.String("val2"), - }, - } - req, _ := svc.InputService5TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&MapArg.1.key=key1&MapArg.1.value=val1&MapArg.2.key=key2&MapArg.2.value=val2&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService6ProtocolTestNonFlattenedListWithLocationNameCase1(t *testing.T) { - svc := NewInputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService6TestShapeInputService6TestCaseOperation1Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - } - req, _ := svc.InputService6TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArg.item.1=a&ListArg.item.2=b&ListArg.item.3=c&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService7ProtocolTestFlattenedListWithLocationNameCase1(t *testing.T) { - svc := NewInputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService7TestShapeInputService7TestCaseOperation1Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - ScalarArg: aws.String("foo"), - } - req, _ := svc.InputService7TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&ListArgLocation.1=a&ListArgLocation.2=b&ListArgLocation.3=c&ScalarArg=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService8ProtocolTestSerializeMapTypeCase1(t *testing.T) { - svc := NewInputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService8TestShapeInputService8TestCaseOperation1Input{ - MapArg: map[string]*string{ - "key1": aws.String("val1"), - "key2": aws.String("val2"), - }, - } - req, _ := svc.InputService8TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&MapArg.entry.1.key=key1&MapArg.entry.1.value=val1&MapArg.entry.2.key=key2&MapArg.entry.2.value=val2&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestSerializeMapTypeWithLocationNameCase1(t *testing.T) { - svc := NewInputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService9TestShapeInputService9TestCaseOperation1Input{ - MapArg: map[string]*string{ - "key1": aws.String("val1"), - "key2": aws.String("val2"), - }, - } - req, _ := svc.InputService9TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&MapArg.entry.1.TheKey=key1&MapArg.entry.1.TheValue=val1&MapArg.entry.2.TheKey=key2&MapArg.entry.2.TheValue=val2&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService10ProtocolTestBase64EncodedBlobsCase1(t *testing.T) { - svc := NewInputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService10TestShapeInputService10TestCaseOperation1Input{ - BlobArg: []byte("foo"), - } - req, _ := svc.InputService10TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&BlobArg=Zm9v&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService11ProtocolTestBase64EncodedBlobsNestedCase1(t *testing.T) { - svc := NewInputService11ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService11TestShapeInputService11TestCaseOperation1Input{ - BlobArgs: [][]byte{ - []byte("foo"), - }, - } - req, _ := svc.InputService11TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&BlobArgs.1=Zm9v&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService12ProtocolTestTimestampValuesCase1(t *testing.T) { - svc := NewInputService12ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService12TestShapeInputService12TestCaseOperation1Input{ - TimeArg: aws.Time(time.Unix(1422172800, 0)), - } - req, _ := svc.InputService12TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&TimeArg=2015-01-25T08%3A00%3A00Z&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase1(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - } - req, _ := svc.InputService13TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.NoRecurse=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase2(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - } - req, _ := svc.InputService13TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.RecursiveStruct.NoRecurse=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase3(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - }, - }, - } - req, _ := svc.InputService13TestCaseOperation3Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.RecursiveStruct.RecursiveStruct.RecursiveStruct.NoRecurse=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase4(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveList: []*InputService13TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - NoRecurse: aws.String("bar"), - }, - }, - }, - } - req, _ := svc.InputService13TestCaseOperation4Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.RecursiveList.member.1.NoRecurse=foo&RecursiveStruct.RecursiveList.member.2.NoRecurse=bar&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase5(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveList: []*InputService13TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - NoRecurse: aws.String("bar"), - }, - }, - }, - }, - } - req, _ := svc.InputService13TestCaseOperation5Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.RecursiveList.member.1.NoRecurse=foo&RecursiveStruct.RecursiveList.member.2.RecursiveStruct.NoRecurse=bar&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestRecursiveShapesCase6(t *testing.T) { - svc := NewInputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService13TestShapeInputService13TestCaseOperation6Input{ - RecursiveStruct: &InputService13TestShapeRecursiveStructType{ - RecursiveMap: map[string]*InputService13TestShapeRecursiveStructType{ - "bar": { - NoRecurse: aws.String("bar"), - }, - "foo": { - NoRecurse: aws.String("foo"), - }, - }, - }, - } - req, _ := svc.InputService13TestCaseOperation6Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&RecursiveStruct.RecursiveMap.entry.1.key=foo&RecursiveStruct.RecursiveMap.entry.1.value.NoRecurse=foo&RecursiveStruct.RecursiveMap.entry.2.key=bar&RecursiveStruct.RecursiveMap.entry.2.value.NoRecurse=bar&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService14ProtocolTestIdempotencyTokenAutoFillCase1(t *testing.T) { - svc := NewInputService14ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService14TestShapeInputService14TestCaseOperation2Input{ - Token: aws.String("abc123"), - } - req, _ := svc.InputService14TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Token=abc123&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService14ProtocolTestIdempotencyTokenAutoFillCase2(t *testing.T) { - svc := NewInputService14ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService14TestShapeInputService14TestCaseOperation2Input{} - req, _ := svc.InputService14TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Token=00000000-0000-4000-8000-000000000000&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService15ProtocolTestEnumCase1(t *testing.T) { - svc := NewInputService15ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService15TestShapeInputService15TestCaseOperation3Input{ - FooEnum: aws.String("foo"), - ListEnums: []*string{ - aws.String("foo"), - aws.String(""), - aws.String("bar"), - }, - } - req, _ := svc.InputService15TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&FooEnum=foo&ListEnums.member.1=foo&ListEnums.member.2=&ListEnums.member.3=bar&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService15ProtocolTestEnumCase2(t *testing.T) { - svc := NewInputService15ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService15TestShapeInputService15TestCaseOperation3Input{ - FooEnum: aws.String("foo"), - } - req, _ := svc.InputService15TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&FooEnum=foo&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService15ProtocolTestEnumCase3(t *testing.T) { - svc := NewInputService15ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - input := &InputService15TestShapeInputService15TestCaseOperation3Input{} - req, _ := svc.InputService15TestCaseOperation3Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - if req.Error != nil { - t.Errorf("expect no error, got %v", req.Error) - } - - // assert body - if r.Body == nil { - t.Errorf("expect body not to be nil") - } - body, _ := ioutil.ReadAll(r.Body) - awstesting.AssertQuery(t, `Action=OperationName&Version=2014-01-01`, util.Trim(string(body))) - - // assert URL - awstesting.AssertURL(t, "https://test/", r.URL.String()) - - // assert headers - -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_test.go deleted file mode 100644 index afbe3df2..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_test.go +++ /dev/null @@ -1,3007 +0,0 @@ -package query_test - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/query" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" - "github.com/aws/aws-sdk-go/private/util" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF -var _ = aws.String -var _ = fmt.Println -var _ = reflect.Value{} - -func init() { - protocol.RandReader = &awstesting.ZeroReader{} -} - -// OutputService1ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService1ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService1ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService1ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService1ProtocolTest client from just a session. -// svc := outputservice1protocoltest.New(mySession) -// -// // Create a OutputService1ProtocolTest client with additional configuration -// svc := outputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService1ProtocolTest { - c := p.ClientConfig("outputservice1protocoltest", cfgs...) - return newOutputService1ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService1ProtocolTest { - svc := &OutputService1ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice1protocoltest", - ServiceID: "OutputService1ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService1TestCaseOperation1 = "OperationName" - -// OutputService1TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService1TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService1TestCaseOperation1 for more information on using the OutputService1TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService1TestCaseOperation1Request method. -// req, resp := client.OutputService1TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *request.Request, output *OutputService1TestShapeOutputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService1TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - output = &OutputService1TestShapeOutputService1TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService1TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService1TestCaseOperation1 for usage and error information. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService1TestCaseOperation1WithContext is the same as OutputService1TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService1TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1WithContext(ctx aws.Context, input *OutputService1TestShapeOutputService1TestCaseOperation1Input, opts ...request.Option) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService1TestShapeOutputService1TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Char *string `type:"character"` - - Double *float64 `type:"double"` - - FalseBool *bool `type:"boolean"` - - Float *float64 `type:"float"` - - Long *int64 `type:"long"` - - Num *int64 `locationName:"FooNum" type:"integer"` - - Str *string `type:"string"` - - Timestamp *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - TrueBool *bool `type:"boolean"` -} - -// SetChar sets the Char field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetChar(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Char = &v - return s -} - -// SetDouble sets the Double field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetDouble(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Double = &v - return s -} - -// SetFalseBool sets the FalseBool field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFalseBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.FalseBool = &v - return s -} - -// SetFloat sets the Float field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetFloat(v float64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Float = &v - return s -} - -// SetLong sets the Long field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetLong(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Long = &v - return s -} - -// SetNum sets the Num field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetNum(v int64) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Num = &v - return s -} - -// SetStr sets the Str field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetStr(v string) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Str = &v - return s -} - -// SetTimestamp sets the Timestamp field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetTimestamp(v time.Time) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.Timestamp = &v - return s -} - -// SetTrueBool sets the TrueBool field's value. -func (s *OutputService1TestShapeOutputService1TestCaseOperation1Output) SetTrueBool(v bool) *OutputService1TestShapeOutputService1TestCaseOperation1Output { - s.TrueBool = &v - return s -} - -// OutputService2ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService2ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService2ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService2ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService2ProtocolTest client from just a session. -// svc := outputservice2protocoltest.New(mySession) -// -// // Create a OutputService2ProtocolTest client with additional configuration -// svc := outputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService2ProtocolTest { - c := p.ClientConfig("outputservice2protocoltest", cfgs...) - return newOutputService2ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService2ProtocolTest { - svc := &OutputService2ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice2protocoltest", - ServiceID: "OutputService2ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService2TestCaseOperation1 = "OperationName" - -// OutputService2TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService2TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService2TestCaseOperation1 for more information on using the OutputService2TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService2TestCaseOperation1Request method. -// req, resp := client.OutputService2TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *request.Request, output *OutputService2TestShapeOutputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService2TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - output = &OutputService2TestShapeOutputService2TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService2TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService2TestCaseOperation1 for usage and error information. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService2TestCaseOperation1WithContext is the same as OutputService2TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService2TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1WithContext(ctx aws.Context, input *OutputService2TestShapeOutputService2TestCaseOperation1Input, opts ...request.Option) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService2TestShapeOutputService2TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Num *int64 `type:"integer"` - - Str *string `type:"string"` -} - -// SetNum sets the Num field's value. -func (s *OutputService2TestShapeOutputService2TestCaseOperation1Output) SetNum(v int64) *OutputService2TestShapeOutputService2TestCaseOperation1Output { - s.Num = &v - return s -} - -// SetStr sets the Str field's value. -func (s *OutputService2TestShapeOutputService2TestCaseOperation1Output) SetStr(v string) *OutputService2TestShapeOutputService2TestCaseOperation1Output { - s.Str = &v - return s -} - -// OutputService3ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService3ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService3ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService3ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService3ProtocolTest client from just a session. -// svc := outputservice3protocoltest.New(mySession) -// -// // Create a OutputService3ProtocolTest client with additional configuration -// svc := outputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService3ProtocolTest { - c := p.ClientConfig("outputservice3protocoltest", cfgs...) - return newOutputService3ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService3ProtocolTest { - svc := &OutputService3ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice3protocoltest", - ServiceID: "OutputService3ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService3TestCaseOperation1 = "OperationName" - -// OutputService3TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService3TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService3TestCaseOperation1 for more information on using the OutputService3TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService3TestCaseOperation1Request method. -// req, resp := client.OutputService3TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *request.Request, output *OutputService3TestShapeOutputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService3TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - output = &OutputService3TestShapeOutputService3TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService3TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService3TestCaseOperation1 for usage and error information. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService3TestCaseOperation1WithContext is the same as OutputService3TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService3TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1WithContext(ctx aws.Context, input *OutputService3TestShapeOutputService3TestCaseOperation1Input, opts ...request.Option) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService3TestShapeOutputService3TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - // Blob is automatically base64 encoded/decoded by the SDK. - Blob []byte `type:"blob"` -} - -// SetBlob sets the Blob field's value. -func (s *OutputService3TestShapeOutputService3TestCaseOperation1Output) SetBlob(v []byte) *OutputService3TestShapeOutputService3TestCaseOperation1Output { - s.Blob = v - return s -} - -// OutputService4ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService4ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService4ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService4ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService4ProtocolTest client from just a session. -// svc := outputservice4protocoltest.New(mySession) -// -// // Create a OutputService4ProtocolTest client with additional configuration -// svc := outputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService4ProtocolTest { - c := p.ClientConfig("outputservice4protocoltest", cfgs...) - return newOutputService4ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService4ProtocolTest { - svc := &OutputService4ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice4protocoltest", - ServiceID: "OutputService4ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService4TestCaseOperation1 = "OperationName" - -// OutputService4TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService4TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService4TestCaseOperation1 for more information on using the OutputService4TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService4TestCaseOperation1Request method. -// req, resp := client.OutputService4TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *request.Request, output *OutputService4TestShapeOutputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService4TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - output = &OutputService4TestShapeOutputService4TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService4TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService4TestCaseOperation1 for usage and error information. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService4TestCaseOperation1WithContext is the same as OutputService4TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService4TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1WithContext(ctx aws.Context, input *OutputService4TestShapeOutputService4TestCaseOperation1Input, opts ...request.Option) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService4TestShapeOutputService4TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `type:"list"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService4TestShapeOutputService4TestCaseOperation1Output) SetListMember(v []*string) *OutputService4TestShapeOutputService4TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService5ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService5ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService5ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService5ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService5ProtocolTest client from just a session. -// svc := outputservice5protocoltest.New(mySession) -// -// // Create a OutputService5ProtocolTest client with additional configuration -// svc := outputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService5ProtocolTest { - c := p.ClientConfig("outputservice5protocoltest", cfgs...) - return newOutputService5ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService5ProtocolTest { - svc := &OutputService5ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice5protocoltest", - ServiceID: "OutputService5ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService5TestCaseOperation1 = "OperationName" - -// OutputService5TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService5TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService5TestCaseOperation1 for more information on using the OutputService5TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService5TestCaseOperation1Request method. -// req, resp := client.OutputService5TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *request.Request, output *OutputService5TestShapeOutputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService5TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - output = &OutputService5TestShapeOutputService5TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService5TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService5TestCaseOperation1 for usage and error information. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService5TestCaseOperation1WithContext is the same as OutputService5TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService5TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1WithContext(ctx aws.Context, input *OutputService5TestShapeOutputService5TestCaseOperation1Input, opts ...request.Option) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService5TestShapeOutputService5TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `locationNameList:"item" type:"list"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService5TestShapeOutputService5TestCaseOperation1Output) SetListMember(v []*string) *OutputService5TestShapeOutputService5TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService6ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService6ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService6ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService6ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService6ProtocolTest client from just a session. -// svc := outputservice6protocoltest.New(mySession) -// -// // Create a OutputService6ProtocolTest client with additional configuration -// svc := outputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService6ProtocolTest { - c := p.ClientConfig("outputservice6protocoltest", cfgs...) - return newOutputService6ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService6ProtocolTest { - svc := &OutputService6ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice6protocoltest", - ServiceID: "OutputService6ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService6TestCaseOperation1 = "OperationName" - -// OutputService6TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService6TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService6TestCaseOperation1 for more information on using the OutputService6TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService6TestCaseOperation1Request method. -// req, resp := client.OutputService6TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *request.Request, output *OutputService6TestShapeOutputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService6TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - output = &OutputService6TestShapeOutputService6TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService6TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService6TestCaseOperation1 for usage and error information. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService6TestCaseOperation1WithContext is the same as OutputService6TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService6TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1WithContext(ctx aws.Context, input *OutputService6TestShapeOutputService6TestCaseOperation1Input, opts ...request.Option) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService6TestShapeOutputService6TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `type:"list" flattened:"true"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService6TestShapeOutputService6TestCaseOperation1Output) SetListMember(v []*string) *OutputService6TestShapeOutputService6TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService7ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService7ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService7ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService7ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService7ProtocolTest client from just a session. -// svc := outputservice7protocoltest.New(mySession) -// -// // Create a OutputService7ProtocolTest client with additional configuration -// svc := outputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService7ProtocolTest { - c := p.ClientConfig("outputservice7protocoltest", cfgs...) - return newOutputService7ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService7ProtocolTest { - svc := &OutputService7ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice7protocoltest", - ServiceID: "OutputService7ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService7TestCaseOperation1 = "OperationName" - -// OutputService7TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService7TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService7TestCaseOperation1 for more information on using the OutputService7TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService7TestCaseOperation1Request method. -// req, resp := client.OutputService7TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *request.Request, output *OutputService7TestShapeOutputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService7TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - output = &OutputService7TestShapeOutputService7TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService7TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService7TestCaseOperation1 for usage and error information. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService7TestCaseOperation1WithContext is the same as OutputService7TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService7TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1WithContext(ctx aws.Context, input *OutputService7TestShapeOutputService7TestCaseOperation1Input, opts ...request.Option) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService7TestShapeOutputService7TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - ListMember []*string `type:"list" flattened:"true"` -} - -// SetListMember sets the ListMember field's value. -func (s *OutputService7TestShapeOutputService7TestCaseOperation1Output) SetListMember(v []*string) *OutputService7TestShapeOutputService7TestCaseOperation1Output { - s.ListMember = v - return s -} - -// OutputService8ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService8ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService8ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService8ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService8ProtocolTest client from just a session. -// svc := outputservice8protocoltest.New(mySession) -// -// // Create a OutputService8ProtocolTest client with additional configuration -// svc := outputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService8ProtocolTest { - c := p.ClientConfig("outputservice8protocoltest", cfgs...) - return newOutputService8ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService8ProtocolTest { - svc := &OutputService8ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice8protocoltest", - ServiceID: "OutputService8ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService8TestCaseOperation1 = "OperationName" - -// OutputService8TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService8TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService8TestCaseOperation1 for more information on using the OutputService8TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService8TestCaseOperation1Request method. -// req, resp := client.OutputService8TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *request.Request, output *OutputService8TestShapeOutputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService8TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - output = &OutputService8TestShapeOutputService8TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService8TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService8TestCaseOperation1 for usage and error information. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService8TestCaseOperation1WithContext is the same as OutputService8TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService8TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1WithContext(ctx aws.Context, input *OutputService8TestShapeOutputService8TestCaseOperation1Input, opts ...request.Option) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService8TestShapeOutputService8TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - List []*OutputService8TestShapeStructureShape `type:"list"` -} - -// SetList sets the List field's value. -func (s *OutputService8TestShapeOutputService8TestCaseOperation1Output) SetList(v []*OutputService8TestShapeStructureShape) *OutputService8TestShapeOutputService8TestCaseOperation1Output { - s.List = v - return s -} - -type OutputService8TestShapeStructureShape struct { - _ struct{} `type:"structure"` - - Bar *string `type:"string"` - - Baz *string `type:"string"` - - Foo *string `type:"string"` -} - -// SetBar sets the Bar field's value. -func (s *OutputService8TestShapeStructureShape) SetBar(v string) *OutputService8TestShapeStructureShape { - s.Bar = &v - return s -} - -// SetBaz sets the Baz field's value. -func (s *OutputService8TestShapeStructureShape) SetBaz(v string) *OutputService8TestShapeStructureShape { - s.Baz = &v - return s -} - -// SetFoo sets the Foo field's value. -func (s *OutputService8TestShapeStructureShape) SetFoo(v string) *OutputService8TestShapeStructureShape { - s.Foo = &v - return s -} - -// OutputService9ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService9ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService9ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService9ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService9ProtocolTest client from just a session. -// svc := outputservice9protocoltest.New(mySession) -// -// // Create a OutputService9ProtocolTest client with additional configuration -// svc := outputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService9ProtocolTest { - c := p.ClientConfig("outputservice9protocoltest", cfgs...) - return newOutputService9ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService9ProtocolTest { - svc := &OutputService9ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice9protocoltest", - ServiceID: "OutputService9ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService9TestCaseOperation1 = "OperationName" - -// OutputService9TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService9TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService9TestCaseOperation1 for more information on using the OutputService9TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService9TestCaseOperation1Request method. -// req, resp := client.OutputService9TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *request.Request, output *OutputService9TestShapeOutputService9TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService9TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} - } - - output = &OutputService9TestShapeOutputService9TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService9TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService9TestCaseOperation1 for usage and error information. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService9TestCaseOperation1WithContext is the same as OutputService9TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService9TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1WithContext(ctx aws.Context, input *OutputService9TestShapeOutputService9TestCaseOperation1Input, opts ...request.Option) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService9TestShapeOutputService9TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService9TestShapeOutputService9TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - List []*OutputService9TestShapeStructureShape `type:"list" flattened:"true"` -} - -// SetList sets the List field's value. -func (s *OutputService9TestShapeOutputService9TestCaseOperation1Output) SetList(v []*OutputService9TestShapeStructureShape) *OutputService9TestShapeOutputService9TestCaseOperation1Output { - s.List = v - return s -} - -type OutputService9TestShapeStructureShape struct { - _ struct{} `type:"structure"` - - Bar *string `type:"string"` - - Baz *string `type:"string"` - - Foo *string `type:"string"` -} - -// SetBar sets the Bar field's value. -func (s *OutputService9TestShapeStructureShape) SetBar(v string) *OutputService9TestShapeStructureShape { - s.Bar = &v - return s -} - -// SetBaz sets the Baz field's value. -func (s *OutputService9TestShapeStructureShape) SetBaz(v string) *OutputService9TestShapeStructureShape { - s.Baz = &v - return s -} - -// SetFoo sets the Foo field's value. -func (s *OutputService9TestShapeStructureShape) SetFoo(v string) *OutputService9TestShapeStructureShape { - s.Foo = &v - return s -} - -// OutputService10ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService10ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService10ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService10ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService10ProtocolTest client from just a session. -// svc := outputservice10protocoltest.New(mySession) -// -// // Create a OutputService10ProtocolTest client with additional configuration -// svc := outputservice10protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService10ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService10ProtocolTest { - c := p.ClientConfig("outputservice10protocoltest", cfgs...) - return newOutputService10ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService10ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService10ProtocolTest { - svc := &OutputService10ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice10protocoltest", - ServiceID: "OutputService10ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService10TestCaseOperation1 = "OperationName" - -// OutputService10TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService10TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService10TestCaseOperation1 for more information on using the OutputService10TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService10TestCaseOperation1Request method. -// req, resp := client.OutputService10TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *request.Request, output *OutputService10TestShapeOutputService10TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService10TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{} - } - - output = &OutputService10TestShapeOutputService10TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService10TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService10TestCaseOperation1 for usage and error information. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) { - req, out := c.OutputService10TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService10TestCaseOperation1WithContext is the same as OutputService10TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService10TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1WithContext(ctx aws.Context, input *OutputService10TestShapeOutputService10TestCaseOperation1Input, opts ...request.Option) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) { - req, out := c.OutputService10TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService10TestShapeOutputService10TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService10TestShapeOutputService10TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - List []*string `locationNameList:"NamedList" type:"list" flattened:"true"` -} - -// SetList sets the List field's value. -func (s *OutputService10TestShapeOutputService10TestCaseOperation1Output) SetList(v []*string) *OutputService10TestShapeOutputService10TestCaseOperation1Output { - s.List = v - return s -} - -// OutputService11ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService11ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService11ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService11ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService11ProtocolTest client from just a session. -// svc := outputservice11protocoltest.New(mySession) -// -// // Create a OutputService11ProtocolTest client with additional configuration -// svc := outputservice11protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService11ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService11ProtocolTest { - c := p.ClientConfig("outputservice11protocoltest", cfgs...) - return newOutputService11ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService11ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService11ProtocolTest { - svc := &OutputService11ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice11protocoltest", - ServiceID: "OutputService11ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService11ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService11TestCaseOperation1 = "OperationName" - -// OutputService11TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService11TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService11TestCaseOperation1 for more information on using the OutputService11TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService11TestCaseOperation1Request method. -// req, resp := client.OutputService11TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *request.Request, output *OutputService11TestShapeOutputService11TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService11TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{} - } - - output = &OutputService11TestShapeOutputService11TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService11TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService11TestCaseOperation1 for usage and error information. -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (*OutputService11TestShapeOutputService11TestCaseOperation1Output, error) { - req, out := c.OutputService11TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService11TestCaseOperation1WithContext is the same as OutputService11TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService11TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1WithContext(ctx aws.Context, input *OutputService11TestShapeOutputService11TestCaseOperation1Input, opts ...request.Option) (*OutputService11TestShapeOutputService11TestCaseOperation1Output, error) { - req, out := c.OutputService11TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService11TestShapeOutputService11TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService11TestShapeOutputService11TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*OutputService11TestShapeStructType `type:"map"` -} - -// SetMap sets the Map field's value. -func (s *OutputService11TestShapeOutputService11TestCaseOperation1Output) SetMap(v map[string]*OutputService11TestShapeStructType) *OutputService11TestShapeOutputService11TestCaseOperation1Output { - s.Map = v - return s -} - -type OutputService11TestShapeStructType struct { - _ struct{} `type:"structure"` - - Foo *string `locationName:"foo" type:"string"` -} - -// SetFoo sets the Foo field's value. -func (s *OutputService11TestShapeStructType) SetFoo(v string) *OutputService11TestShapeStructType { - s.Foo = &v - return s -} - -// OutputService12ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService12ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService12ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService12ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService12ProtocolTest client from just a session. -// svc := outputservice12protocoltest.New(mySession) -// -// // Create a OutputService12ProtocolTest client with additional configuration -// svc := outputservice12protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService12ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService12ProtocolTest { - c := p.ClientConfig("outputservice12protocoltest", cfgs...) - return newOutputService12ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService12ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService12ProtocolTest { - svc := &OutputService12ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice12protocoltest", - ServiceID: "OutputService12ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService12ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService12ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService12TestCaseOperation1 = "OperationName" - -// OutputService12TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService12TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService12TestCaseOperation1 for more information on using the OutputService12TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService12TestCaseOperation1Request method. -// req, resp := client.OutputService12TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1Request(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (req *request.Request, output *OutputService12TestShapeOutputService12TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService12TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService12TestShapeOutputService12TestCaseOperation1Input{} - } - - output = &OutputService12TestShapeOutputService12TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService12TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService12TestCaseOperation1 for usage and error information. -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (*OutputService12TestShapeOutputService12TestCaseOperation1Output, error) { - req, out := c.OutputService12TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService12TestCaseOperation1WithContext is the same as OutputService12TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService12TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1WithContext(ctx aws.Context, input *OutputService12TestShapeOutputService12TestCaseOperation1Input, opts ...request.Option) (*OutputService12TestShapeOutputService12TestCaseOperation1Output, error) { - req, out := c.OutputService12TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService12TestShapeOutputService12TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService12TestShapeOutputService12TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*string `type:"map" flattened:"true"` -} - -// SetMap sets the Map field's value. -func (s *OutputService12TestShapeOutputService12TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService12TestShapeOutputService12TestCaseOperation1Output { - s.Map = v - return s -} - -// OutputService13ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService13ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService13ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService13ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService13ProtocolTest client from just a session. -// svc := outputservice13protocoltest.New(mySession) -// -// // Create a OutputService13ProtocolTest client with additional configuration -// svc := outputservice13protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService13ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService13ProtocolTest { - c := p.ClientConfig("outputservice13protocoltest", cfgs...) - return newOutputService13ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService13ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService13ProtocolTest { - svc := &OutputService13ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice13protocoltest", - ServiceID: "OutputService13ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService13ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService13ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService13TestCaseOperation1 = "OperationName" - -// OutputService13TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService13TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService13TestCaseOperation1 for more information on using the OutputService13TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService13TestCaseOperation1Request method. -// req, resp := client.OutputService13TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1Request(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (req *request.Request, output *OutputService13TestShapeOutputService13TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService13TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService13TestShapeOutputService13TestCaseOperation1Input{} - } - - output = &OutputService13TestShapeOutputService13TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService13TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService13TestCaseOperation1 for usage and error information. -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (*OutputService13TestShapeOutputService13TestCaseOperation1Output, error) { - req, out := c.OutputService13TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService13TestCaseOperation1WithContext is the same as OutputService13TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService13TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1WithContext(ctx aws.Context, input *OutputService13TestShapeOutputService13TestCaseOperation1Input, opts ...request.Option) (*OutputService13TestShapeOutputService13TestCaseOperation1Output, error) { - req, out := c.OutputService13TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService13TestShapeOutputService13TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService13TestShapeOutputService13TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` -} - -// SetMap sets the Map field's value. -func (s *OutputService13TestShapeOutputService13TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService13TestShapeOutputService13TestCaseOperation1Output { - s.Map = v - return s -} - -// OutputService14ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService14ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService14ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService14ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService14ProtocolTest client from just a session. -// svc := outputservice14protocoltest.New(mySession) -// -// // Create a OutputService14ProtocolTest client with additional configuration -// svc := outputservice14protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService14ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService14ProtocolTest { - c := p.ClientConfig("outputservice14protocoltest", cfgs...) - return newOutputService14ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService14ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService14ProtocolTest { - svc := &OutputService14ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice14protocoltest", - ServiceID: "OutputService14ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService14ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService14ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService14TestCaseOperation1 = "OperationName" - -// OutputService14TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService14TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService14TestCaseOperation1 for more information on using the OutputService14TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService14TestCaseOperation1Request method. -// req, resp := client.OutputService14TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1Request(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (req *request.Request, output *OutputService14TestShapeOutputService14TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService14TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService14TestShapeOutputService14TestCaseOperation1Input{} - } - - output = &OutputService14TestShapeOutputService14TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService14TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService14TestCaseOperation1 for usage and error information. -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (*OutputService14TestShapeOutputService14TestCaseOperation1Output, error) { - req, out := c.OutputService14TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService14TestCaseOperation1WithContext is the same as OutputService14TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService14TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1WithContext(ctx aws.Context, input *OutputService14TestShapeOutputService14TestCaseOperation1Input, opts ...request.Option) (*OutputService14TestShapeOutputService14TestCaseOperation1Output, error) { - req, out := c.OutputService14TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService14TestShapeOutputService14TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService14TestShapeOutputService14TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"` -} - -// SetMap sets the Map field's value. -func (s *OutputService14TestShapeOutputService14TestCaseOperation1Output) SetMap(v map[string]*string) *OutputService14TestShapeOutputService14TestCaseOperation1Output { - s.Map = v - return s -} - -// OutputService15ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService15ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService15ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService15ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService15ProtocolTest client from just a session. -// svc := outputservice15protocoltest.New(mySession) -// -// // Create a OutputService15ProtocolTest client with additional configuration -// svc := outputservice15protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService15ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService15ProtocolTest { - c := p.ClientConfig("outputservice15protocoltest", cfgs...) - return newOutputService15ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService15ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService15ProtocolTest { - svc := &OutputService15ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice15protocoltest", - ServiceID: "OutputService15ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService15ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService15ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService15TestCaseOperation1 = "OperationName" - -// OutputService15TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService15TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService15TestCaseOperation1 for more information on using the OutputService15TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService15TestCaseOperation1Request method. -// req, resp := client.OutputService15TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService15ProtocolTest) OutputService15TestCaseOperation1Request(input *OutputService15TestShapeOutputService15TestCaseOperation1Input) (req *request.Request, output *OutputService15TestShapeOutputService15TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService15TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService15TestShapeOutputService15TestCaseOperation1Input{} - } - - output = &OutputService15TestShapeOutputService15TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService15TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService15TestCaseOperation1 for usage and error information. -func (c *OutputService15ProtocolTest) OutputService15TestCaseOperation1(input *OutputService15TestShapeOutputService15TestCaseOperation1Input) (*OutputService15TestShapeOutputService15TestCaseOperation1Output, error) { - req, out := c.OutputService15TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService15TestCaseOperation1WithContext is the same as OutputService15TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService15TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService15ProtocolTest) OutputService15TestCaseOperation1WithContext(ctx aws.Context, input *OutputService15TestShapeOutputService15TestCaseOperation1Input, opts ...request.Option) (*OutputService15TestShapeOutputService15TestCaseOperation1Output, error) { - req, out := c.OutputService15TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService15TestShapeOutputService15TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService15TestShapeOutputService15TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - Foo *string `type:"string"` -} - -// SetFoo sets the Foo field's value. -func (s *OutputService15TestShapeOutputService15TestCaseOperation1Output) SetFoo(v string) *OutputService15TestShapeOutputService15TestCaseOperation1Output { - s.Foo = &v - return s -} - -// OutputService16ProtocolTest provides the API operation methods for making requests to -// . See this package's package overview docs -// for details on the service. -// -// OutputService16ProtocolTest methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type OutputService16ProtocolTest struct { - *client.Client -} - -// New creates a new instance of the OutputService16ProtocolTest client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a OutputService16ProtocolTest client from just a session. -// svc := outputservice16protocoltest.New(mySession) -// -// // Create a OutputService16ProtocolTest client with additional configuration -// svc := outputservice16protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func NewOutputService16ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService16ProtocolTest { - c := p.ClientConfig("outputservice16protocoltest", cfgs...) - return newOutputService16ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newOutputService16ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *OutputService16ProtocolTest { - svc := &OutputService16ProtocolTest{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "outputservice16protocoltest", - ServiceID: "OutputService16ProtocolTest", - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - return svc -} - -// newRequest creates a new request for a OutputService16ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService16ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService16TestCaseOperation1 = "OperationName" - -// OutputService16TestCaseOperation1Request generates a "aws/request.Request" representing the -// client's request for the OutputService16TestCaseOperation1 operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OutputService16TestCaseOperation1 for more information on using the OutputService16TestCaseOperation1 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OutputService16TestCaseOperation1Request method. -// req, resp := client.OutputService16TestCaseOperation1Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -func (c *OutputService16ProtocolTest) OutputService16TestCaseOperation1Request(input *OutputService16TestShapeOutputService16TestCaseOperation1Input) (req *request.Request, output *OutputService16TestShapeOutputService16TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService16TestCaseOperation1, - HTTPPath: "/", - } - - if input == nil { - input = &OutputService16TestShapeOutputService16TestCaseOperation1Input{} - } - - output = &OutputService16TestShapeOutputService16TestCaseOperation1Output{} - req = c.newRequest(op, input, output) - return -} - -// OutputService16TestCaseOperation1 API operation for . -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for 's -// API operation OutputService16TestCaseOperation1 for usage and error information. -func (c *OutputService16ProtocolTest) OutputService16TestCaseOperation1(input *OutputService16TestShapeOutputService16TestCaseOperation1Input) (*OutputService16TestShapeOutputService16TestCaseOperation1Output, error) { - req, out := c.OutputService16TestCaseOperation1Request(input) - return out, req.Send() -} - -// OutputService16TestCaseOperation1WithContext is the same as OutputService16TestCaseOperation1 with the addition of -// the ability to pass a context and additional request options. -// -// See OutputService16TestCaseOperation1 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *OutputService16ProtocolTest) OutputService16TestCaseOperation1WithContext(ctx aws.Context, input *OutputService16TestShapeOutputService16TestCaseOperation1Input, opts ...request.Option) (*OutputService16TestShapeOutputService16TestCaseOperation1Output, error) { - req, out := c.OutputService16TestCaseOperation1Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type OutputService16TestShapeOutputService16TestCaseOperation1Input struct { - _ struct{} `type:"structure"` -} - -type OutputService16TestShapeOutputService16TestCaseOperation1Output struct { - _ struct{} `type:"structure"` - - FooEnum *string `type:"string" enum:"OutputService16TestShapeEC2EnumType"` - - ListEnums []*string `type:"list"` -} - -// SetFooEnum sets the FooEnum field's value. -func (s *OutputService16TestShapeOutputService16TestCaseOperation1Output) SetFooEnum(v string) *OutputService16TestShapeOutputService16TestCaseOperation1Output { - s.FooEnum = &v - return s -} - -// SetListEnums sets the ListEnums field's value. -func (s *OutputService16TestShapeOutputService16TestCaseOperation1Output) SetListEnums(v []*string) *OutputService16TestShapeOutputService16TestCaseOperation1Output { - s.ListEnums = v - return s -} - -const ( - // EC2EnumTypeFoo is a OutputService16TestShapeEC2EnumType enum value - EC2EnumTypeFoo = "foo" - - // EC2EnumTypeBar is a OutputService16TestShapeEC2EnumType enum value - EC2EnumTypeBar = "bar" -) - -// -// Tests begin here -// - -func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewOutputService1ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("myname123falsetrue1.21.3200a2015-01-25T08:00:00Zrequest-id")) - req, out := svc.OutputService1TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "a", *out.Char; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := 1.3, *out.Double; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := false, *out.FalseBool; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := 1.2, *out.Float; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := int64(200), *out.Long; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := int64(123), *out.Num; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "myname", *out.Str; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.UTC().String(); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := true, *out.TrueBool; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService2ProtocolTestNotAllMembersInResponseCase1(t *testing.T) { - svc := NewOutputService2ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("mynamerequest-id")) - req, out := svc.OutputService2TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "myname", *out.Str; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService3ProtocolTestBlobCase1(t *testing.T) { - svc := NewOutputService3ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("dmFsdWU=requestid")) - req, out := svc.OutputService3TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "value", string(out.Blob); e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService4ProtocolTestListsCase1(t *testing.T) { - svc := NewOutputService4ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService4TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService5ProtocolTestListWithCustomMemberNameCase1(t *testing.T) { - svc := NewOutputService5ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService5TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService6ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewOutputService6ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService6TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "123", *out.ListMember[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService7ProtocolTestFlattenedSingleElementListCase1(t *testing.T) { - svc := NewOutputService7ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abcrequestid")) - req, out := svc.OutputService7TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "abc", *out.ListMember[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService8ProtocolTestListOfStructuresCase1(t *testing.T) { - svc := NewOutputService8ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("firstfoofirstbarfirstbazsecondfoosecondbarsecondbazrequestid")) - req, out := svc.OutputService8TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "firstbar", *out.List[0].Bar; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "firstbaz", *out.List[0].Baz; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "firstfoo", *out.List[0].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondbar", *out.List[1].Bar; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondbaz", *out.List[1].Baz; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondfoo", *out.List[1].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService9ProtocolTestFlattenedListOfStructuresCase1(t *testing.T) { - svc := NewOutputService9ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("firstfoofirstbarfirstbazsecondfoosecondbarsecondbazrequestid")) - req, out := svc.OutputService9TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "firstbar", *out.List[0].Bar; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "firstbaz", *out.List[0].Baz; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "firstfoo", *out.List[0].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondbar", *out.List[1].Bar; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondbaz", *out.List[1].Baz; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "secondfoo", *out.List[1].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService10ProtocolTestFlattenedListWithLocationNameCase1(t *testing.T) { - svc := NewOutputService10ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("abrequestid")) - req, out := svc.OutputService10TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "a", *out.List[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "b", *out.List[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService11ProtocolTestNormalMapCase1(t *testing.T) { - svc := NewOutputService11ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService11TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"].Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService12ProtocolTestFlattenedMapCase1(t *testing.T) { - svc := NewOutputService12ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService12TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService13ProtocolTestFlattenedMapInShapeDefinitionCase1(t *testing.T) { - svc := NewOutputService13ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarrequestid")) - req, out := svc.OutputService13TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bar", *out.Map["qux"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService14ProtocolTestNamedMapCase1(t *testing.T) { - svc := NewOutputService14ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService14TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "bam", *out.Map["baz"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.Map["qux"]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService15ProtocolTestEmptyStringCase1(t *testing.T) { - svc := NewOutputService15ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("requestid")) - req, out := svc.OutputService15TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "", *out.Foo; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} - -func TestOutputService16ProtocolTestEnumOutputCase1(t *testing.T) { - svc := NewOutputService16ProtocolTest(unit.Session, &aws.Config{Endpoint: aws.String("https://test")}) - - buf := bytes.NewReader([]byte("foofoobar")) - req, out := svc.OutputService16TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - if req.Error != nil { - t.Errorf("expect not error, got %v", req.Error) - } - - // assert response - if out == nil { - t.Errorf("expect not to be nil") - } - if e, a := "foo", *out.FooEnum; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "foo", *out.ListEnums[0]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "bar", *out.ListEnums[1]; e != a { - t.Errorf("expect %v, got %v", e, a) - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build_test.go deleted file mode 100644 index 9f18081a..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package rest - -import ( - "net/http" - "net/url" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -func TestCleanPath(t *testing.T) { - uri := &url.URL{ - Path: "//foo//bar", - Scheme: "https", - Host: "host", - } - cleanPath(uri) - - expected := "https://host/foo/bar" - if a, e := uri.String(), expected; a != e { - t.Errorf("expect %q URI, got %q", e, a) - } -} - -func TestMarshalPath(t *testing.T) { - in := struct { - Bucket *string `location:"uri" locationName:"bucket"` - Key *string `location:"uri" locationName:"key"` - }{ - Bucket: aws.String("mybucket"), - Key: aws.String("my/cool+thing space/object世界"), - } - - expectURL := `/mybucket/my/cool+thing space/object世界` - expectEscapedURL := `/mybucket/my/cool%2Bthing%20space/object%E4%B8%96%E7%95%8C` - - req := &request.Request{ - HTTPRequest: &http.Request{ - URL: &url.URL{Scheme: "https", Host: "exmaple.com", Path: "/{bucket}/{key+}"}, - }, - Params: &in, - } - - Build(req) - - if req.Error != nil { - t.Fatalf("unexpected error, %v", req.Error) - } - - if a, e := req.HTTPRequest.URL.Path, expectURL; a != e { - t.Errorf("expect %q URI, got %q", e, a) - } - - if a, e := req.HTTPRequest.URL.RawPath, expectEscapedURL; a != e { - t.Errorf("expect %q escaped URI, got %q", e, a) - } - - if a, e := req.HTTPRequest.URL.EscapedPath(), expectEscapedURL; a != e { - t.Errorf("expect %q escaped URI, got %q", e, a) - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/rest_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/rest_test.go deleted file mode 100644 index 46457b27..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/rest_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package rest_test - -import ( - "bytes" - "io/ioutil" - "net/http" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -func TestUnsetHeaders(t *testing.T) { - cfg := &aws.Config{Region: aws.String("us-west-2")} - c := unit.Session.ClientConfig("testService", cfg) - svc := client.New( - *cfg, - metadata.ClientInfo{ - ServiceName: "testService", - SigningName: c.SigningName, - SigningRegion: c.SigningRegion, - Endpoint: c.Endpoint, - APIVersion: "", - }, - c.Handlers, - ) - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(rest.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(rest.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(rest.UnmarshalMetaHandler) - op := &request.Operation{ - Name: "test-operation", - HTTPPath: "/", - } - - input := &struct { - Foo aws.JSONValue `location:"header" locationName:"x-amz-foo" type:"jsonvalue"` - Bar aws.JSONValue `location:"header" locationName:"x-amz-bar" type:"jsonvalue"` - }{} - - output := &struct { - Foo aws.JSONValue `location:"header" locationName:"x-amz-foo" type:"jsonvalue"` - Bar aws.JSONValue `location:"header" locationName:"x-amz-bar" type:"jsonvalue"` - }{} - - req := svc.NewRequest(op, input, output) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewBuffer(nil)), Header: http.Header{}} - req.HTTPResponse.Header.Set("X-Amz-Foo", "e30=") - - // unmarshal response - rest.UnmarshalMeta(req) - rest.Unmarshal(req) - if req.Error != nil { - t.Fatal(req.Error) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_test.go deleted file mode 100644 index 2733e993..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package protocol_test - -import ( - "net/http" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/stretchr/testify/assert" -) - -type mockCloser struct { - *strings.Reader - Closed bool -} - -func (m *mockCloser) Close() error { - m.Closed = true - return nil -} - -func TestUnmarshalDrainBody(t *testing.T) { - b := &mockCloser{Reader: strings.NewReader("example body")} - r := &request.Request{HTTPResponse: &http.Response{ - Body: b, - }} - - protocol.UnmarshalDiscardBody(r) - assert.NoError(t, r.Error) - assert.Equal(t, 0, b.Len()) - assert.True(t, b.Closed) -} - -func TestUnmarshalDrainBodyNoBody(t *testing.T) { - r := &request.Request{HTTPResponse: &http.Response{}} - - protocol.UnmarshalDiscardBody(r) - assert.NoError(t, r.Error) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal_test.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal_test.go deleted file mode 100644 index 1185d232..00000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package xmlutil - -import ( - "encoding/xml" - "fmt" - "io" - "reflect" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -type mockBody struct { - DoneErr error - Body io.Reader -} - -func (m *mockBody) Read(p []byte) (int, error) { - n, err := m.Body.Read(p) - if (n == 0 || err == io.EOF) && m.DoneErr != nil { - return n, m.DoneErr - } - - return n, err -} - -type mockOutput struct { - _ struct{} `type:"structure"` - String *string `type:"string"` - Integer *int64 `type:"integer"` - Nested *mockNestedStruct `type:"structure"` - List []*mockListElem `locationName:"List" locationNameList:"Elem" type:"list"` - Closed *mockClosedTags `type:"structure"` -} -type mockNestedStruct struct { - _ struct{} `type:"structure"` - NestedString *string `type:"string"` - NestedInt *int64 `type:"integer"` -} -type mockClosedTags struct { - _ struct{} `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` - Attr *string `locationName:"xsi:attrval" type:"string" xmlAttribute:"true"` -} -type mockListElem struct { - _ struct{} `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` - String *string `type:"string"` - NestedElem *mockNestedListElem `type:"structure"` -} -type mockNestedListElem struct { - _ struct{} `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` - - String *string `type:"string"` - Type *string `locationName:"xsi:type" type:"string" xmlAttribute:"true"` -} - -func TestUnmarshal(t *testing.T) { - const xmlBodyStr = ` - - string value - 123 - - - nested string value - 321 - - - - - nested elem string value - - elem string value - - -` - - expect := mockOutput{ - String: aws.String("string value"), - Integer: aws.Int64(123), - Closed: &mockClosedTags{ - Attr: aws.String("attr value"), - }, - Nested: &mockNestedStruct{ - NestedString: aws.String("nested string value"), - NestedInt: aws.Int64(321), - }, - List: []*mockListElem{ - { - String: aws.String("elem string value"), - NestedElem: &mockNestedListElem{ - String: aws.String("nested elem string value"), - Type: aws.String("type"), - }, - }, - }, - } - - actual := mockOutput{} - decoder := xml.NewDecoder(strings.NewReader(xmlBodyStr)) - err := UnmarshalXML(&actual, decoder, "") - if err != nil { - t.Fatalf("expect no error, got %v", err) - } - - if !reflect.DeepEqual(expect, actual) { - t.Errorf("expect unmarshal to match\nExpect: %s\nActual: %s", - awsutil.Prettify(expect), awsutil.Prettify(actual)) - } -} - -func TestUnmarshal_UnexpectedEOF(t *testing.T) { - const partialXMLBody = ` - first value - Second val` - - out := struct { - First *string `locationName:"First" type:"string"` - Second *string `locationName:"Second" type:"string"` - }{} - - expect := out - expect.First = aws.String("first") - expect.Second = aws.String("second") - - expectErr := fmt.Errorf("expected read error") - - body := &mockBody{ - DoneErr: expectErr, - Body: strings.NewReader(partialXMLBody), - } - - decoder := xml.NewDecoder(body) - err := UnmarshalXML(&out, decoder, "") - - if err == nil { - t.Fatalf("expect error, got none") - } - if e, a := expectErr, err; e != a { - t.Errorf("expect %v error in %v, but was not", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/examples_test.go b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/examples_test.go deleted file mode 100644 index bb34769e..00000000 --- a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/examples_test.go +++ /dev/null @@ -1,1963 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package autoscaling_test - -import ( - "fmt" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/autoscaling" -) - -var _ time.Duration -var _ strings.Reader -var _ aws.Config - -func parseTime(layout, value string) *time.Time { - t, err := time.Parse(layout, value) - if err != nil { - panic(err) - } - return &t -} - -// To attach an instance to an Auto Scaling group -// -// This example attaches the specified instance to the specified Auto Scaling group. -func ExampleAutoScaling_AttachInstances_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.AttachInstancesInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - InstanceIds: []*string{ - aws.String("i-93633f9b"), - }, - } - - result, err := svc.AttachInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To attach a target group to an Auto Scaling group -// -// This example attaches the specified target group to the specified Auto Scaling group. -func ExampleAutoScaling_AttachLoadBalancerTargetGroups_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.AttachLoadBalancerTargetGroupsInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - TargetGroupARNs: []*string{ - aws.String("arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067"), - }, - } - - result, err := svc.AttachLoadBalancerTargetGroups(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To attach a load balancer to an Auto Scaling group -// -// This example attaches the specified load balancer to the specified Auto Scaling group. -func ExampleAutoScaling_AttachLoadBalancers_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.AttachLoadBalancersInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - LoadBalancerNames: []*string{ - aws.String("my-load-balancer"), - }, - } - - result, err := svc.AttachLoadBalancers(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To complete the lifecycle action -// -// This example notifies Auto Scaling that the specified lifecycle action is complete -// so that it can finish launching or terminating the instance. -func ExampleAutoScaling_CompleteLifecycleAction_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.CompleteLifecycleActionInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - LifecycleActionResult: aws.String("CONTINUE"), - LifecycleActionToken: aws.String("bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635"), - LifecycleHookName: aws.String("my-lifecycle-hook"), - } - - result, err := svc.CompleteLifecycleAction(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create an Auto Scaling group -// -// This example creates an Auto Scaling group. -func ExampleAutoScaling_CreateAutoScalingGroup_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.CreateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - LaunchConfigurationName: aws.String("my-launch-config"), - MaxSize: aws.Int64(3), - MinSize: aws.Int64(1), - VPCZoneIdentifier: aws.String("subnet-4176792c"), - } - - result, err := svc.CreateAutoScalingGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeAlreadyExistsFault: - fmt.Println(autoscaling.ErrCodeAlreadyExistsFault, aerr.Error()) - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create an Auto Scaling group with an attached load balancer -// -// This example creates an Auto Scaling group and attaches the specified Classic Load -// Balancer. -func ExampleAutoScaling_CreateAutoScalingGroup_shared01() { - svc := autoscaling.New(session.New()) - input := &autoscaling.CreateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - AvailabilityZones: []*string{ - aws.String("us-west-2c"), - }, - HealthCheckGracePeriod: aws.Int64(120), - HealthCheckType: aws.String("ELB"), - LaunchConfigurationName: aws.String("my-launch-config"), - LoadBalancerNames: []*string{ - aws.String("my-load-balancer"), - }, - MaxSize: aws.Int64(3), - MinSize: aws.Int64(1), - } - - result, err := svc.CreateAutoScalingGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeAlreadyExistsFault: - fmt.Println(autoscaling.ErrCodeAlreadyExistsFault, aerr.Error()) - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create an Auto Scaling group with an attached target group -// -// This example creates an Auto Scaling group and attaches the specified target group. -func ExampleAutoScaling_CreateAutoScalingGroup_shared02() { - svc := autoscaling.New(session.New()) - input := &autoscaling.CreateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - HealthCheckGracePeriod: aws.Int64(120), - HealthCheckType: aws.String("ELB"), - LaunchConfigurationName: aws.String("my-launch-config"), - MaxSize: aws.Int64(3), - MinSize: aws.Int64(1), - TargetGroupARNs: []*string{ - aws.String("arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067"), - }, - VPCZoneIdentifier: aws.String("subnet-4176792c, subnet-65ea5f08"), - } - - result, err := svc.CreateAutoScalingGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeAlreadyExistsFault: - fmt.Println(autoscaling.ErrCodeAlreadyExistsFault, aerr.Error()) - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a launch configuration -// -// This example creates a launch configuration. -func ExampleAutoScaling_CreateLaunchConfiguration_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.CreateLaunchConfigurationInput{ - IamInstanceProfile: aws.String("my-iam-role"), - ImageId: aws.String("ami-12345678"), - InstanceType: aws.String("m3.medium"), - LaunchConfigurationName: aws.String("my-launch-config"), - SecurityGroups: []*string{ - aws.String("sg-eb2af88e"), - }, - } - - result, err := svc.CreateLaunchConfiguration(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeAlreadyExistsFault: - fmt.Println(autoscaling.ErrCodeAlreadyExistsFault, aerr.Error()) - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create or update tags for an Auto Scaling group -// -// This example adds two tags to the specified Auto Scaling group. -func ExampleAutoScaling_CreateOrUpdateTags_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.CreateOrUpdateTagsInput{ - Tags: []*autoscaling.Tag{ - { - Key: aws.String("Role"), - PropagateAtLaunch: aws.Bool(true), - ResourceId: aws.String("my-auto-scaling-group"), - ResourceType: aws.String("auto-scaling-group"), - Value: aws.String("WebServer"), - }, - { - Key: aws.String("Dept"), - PropagateAtLaunch: aws.Bool(true), - ResourceId: aws.String("my-auto-scaling-group"), - ResourceType: aws.String("auto-scaling-group"), - Value: aws.String("Research"), - }, - }, - } - - result, err := svc.CreateOrUpdateTags(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeAlreadyExistsFault: - fmt.Println(autoscaling.ErrCodeAlreadyExistsFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeResourceInUseFault: - fmt.Println(autoscaling.ErrCodeResourceInUseFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete an Auto Scaling group -// -// This example deletes the specified Auto Scaling group. -func ExampleAutoScaling_DeleteAutoScalingGroup_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DeleteAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - } - - result, err := svc.DeleteAutoScalingGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeScalingActivityInProgressFault: - fmt.Println(autoscaling.ErrCodeScalingActivityInProgressFault, aerr.Error()) - case autoscaling.ErrCodeResourceInUseFault: - fmt.Println(autoscaling.ErrCodeResourceInUseFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete an Auto Scaling group and all its instances -// -// This example deletes the specified Auto Scaling group and all its instances. -func ExampleAutoScaling_DeleteAutoScalingGroup_shared01() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DeleteAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - ForceDelete: aws.Bool(true), - } - - result, err := svc.DeleteAutoScalingGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeScalingActivityInProgressFault: - fmt.Println(autoscaling.ErrCodeScalingActivityInProgressFault, aerr.Error()) - case autoscaling.ErrCodeResourceInUseFault: - fmt.Println(autoscaling.ErrCodeResourceInUseFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a launch configuration -// -// This example deletes the specified launch configuration. -func ExampleAutoScaling_DeleteLaunchConfiguration_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DeleteLaunchConfigurationInput{ - LaunchConfigurationName: aws.String("my-launch-config"), - } - - result, err := svc.DeleteLaunchConfiguration(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceInUseFault: - fmt.Println(autoscaling.ErrCodeResourceInUseFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a lifecycle hook -// -// This example deletes the specified lifecycle hook. -func ExampleAutoScaling_DeleteLifecycleHook_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DeleteLifecycleHookInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - LifecycleHookName: aws.String("my-lifecycle-hook"), - } - - result, err := svc.DeleteLifecycleHook(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete an Auto Scaling notification -// -// This example deletes the specified notification from the specified Auto Scaling group. -func ExampleAutoScaling_DeleteNotificationConfiguration_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DeleteNotificationConfigurationInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - TopicARN: aws.String("arn:aws:sns:us-west-2:123456789012:my-sns-topic"), - } - - result, err := svc.DeleteNotificationConfiguration(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete an Auto Scaling policy -// -// This example deletes the specified Auto Scaling policy. -func ExampleAutoScaling_DeletePolicy_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DeletePolicyInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - PolicyName: aws.String("ScaleIn"), - } - - result, err := svc.DeletePolicy(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a scheduled action from an Auto Scaling group -// -// This example deletes the specified scheduled action from the specified Auto Scaling -// group. -func ExampleAutoScaling_DeleteScheduledAction_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DeleteScheduledActionInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - ScheduledActionName: aws.String("my-scheduled-action"), - } - - result, err := svc.DeleteScheduledAction(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a tag from an Auto Scaling group -// -// This example deletes the specified tag from the specified Auto Scaling group. -func ExampleAutoScaling_DeleteTags_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DeleteTagsInput{ - Tags: []*autoscaling.Tag{ - { - Key: aws.String("Dept"), - ResourceId: aws.String("my-auto-scaling-group"), - ResourceType: aws.String("auto-scaling-group"), - Value: aws.String("Research"), - }, - }, - } - - result, err := svc.DeleteTags(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeResourceInUseFault: - fmt.Println(autoscaling.ErrCodeResourceInUseFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Auto Scaling account limits -// -// This example describes the Auto Scaling limits for your AWS account. -func ExampleAutoScaling_DescribeAccountLimits_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeAccountLimitsInput{} - - result, err := svc.DescribeAccountLimits(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the Auto Scaling adjustment types -// -// This example describes the available adjustment types. -func ExampleAutoScaling_DescribeAdjustmentTypes_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeAdjustmentTypesInput{} - - result, err := svc.DescribeAdjustmentTypes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe an Auto Scaling group -// -// This example describes the specified Auto Scaling group. -func ExampleAutoScaling_DescribeAutoScalingGroups_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeAutoScalingGroupsInput{ - AutoScalingGroupNames: []*string{ - aws.String("my-auto-scaling-group"), - }, - } - - result, err := svc.DescribeAutoScalingGroups(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeInvalidNextToken: - fmt.Println(autoscaling.ErrCodeInvalidNextToken, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe one or more Auto Scaling instances -// -// This example describes the specified Auto Scaling instance. -func ExampleAutoScaling_DescribeAutoScalingInstances_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeAutoScalingInstancesInput{ - InstanceIds: []*string{ - aws.String("i-4ba0837f"), - }, - } - - result, err := svc.DescribeAutoScalingInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeInvalidNextToken: - fmt.Println(autoscaling.ErrCodeInvalidNextToken, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the Auto Scaling notification types -// -// This example describes the available notification types. -func ExampleAutoScaling_DescribeAutoScalingNotificationTypes_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeAutoScalingNotificationTypesInput{} - - result, err := svc.DescribeAutoScalingNotificationTypes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe Auto Scaling launch configurations -// -// This example describes the specified launch configuration. -func ExampleAutoScaling_DescribeLaunchConfigurations_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeLaunchConfigurationsInput{ - LaunchConfigurationNames: []*string{ - aws.String("my-launch-config"), - }, - } - - result, err := svc.DescribeLaunchConfigurations(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeInvalidNextToken: - fmt.Println(autoscaling.ErrCodeInvalidNextToken, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the available types of lifecycle hooks -// -// This example describes the available lifecycle hook types. -func ExampleAutoScaling_DescribeLifecycleHookTypes_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeLifecycleHookTypesInput{} - - result, err := svc.DescribeLifecycleHookTypes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your lifecycle hooks -// -// This example describes the lifecycle hooks for the specified Auto Scaling group. -func ExampleAutoScaling_DescribeLifecycleHooks_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeLifecycleHooksInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - } - - result, err := svc.DescribeLifecycleHooks(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the target groups for an Auto Scaling group -// -// This example describes the target groups attached to the specified Auto Scaling group. -func ExampleAutoScaling_DescribeLoadBalancerTargetGroups_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeLoadBalancerTargetGroupsInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - } - - result, err := svc.DescribeLoadBalancerTargetGroups(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the load balancers for an Auto Scaling group -// -// This example describes the load balancers attached to the specified Auto Scaling -// group. -func ExampleAutoScaling_DescribeLoadBalancers_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeLoadBalancersInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - } - - result, err := svc.DescribeLoadBalancers(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the Auto Scaling metric collection types -// -// This example describes the available metric collection types. -func ExampleAutoScaling_DescribeMetricCollectionTypes_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeMetricCollectionTypesInput{} - - result, err := svc.DescribeMetricCollectionTypes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe Auto Scaling notification configurations -// -// This example describes the notification configurations for the specified Auto Scaling -// group. -func ExampleAutoScaling_DescribeNotificationConfigurations_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeNotificationConfigurationsInput{ - AutoScalingGroupNames: []*string{ - aws.String("my-auto-scaling-group"), - }, - } - - result, err := svc.DescribeNotificationConfigurations(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeInvalidNextToken: - fmt.Println(autoscaling.ErrCodeInvalidNextToken, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe Auto Scaling policies -// -// This example describes the policies for the specified Auto Scaling group. -func ExampleAutoScaling_DescribePolicies_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribePoliciesInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - } - - result, err := svc.DescribePolicies(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeInvalidNextToken: - fmt.Println(autoscaling.ErrCodeInvalidNextToken, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the scaling activities for an Auto Scaling group -// -// This example describes the scaling activities for the specified Auto Scaling group. -func ExampleAutoScaling_DescribeScalingActivities_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeScalingActivitiesInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - } - - result, err := svc.DescribeScalingActivities(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeInvalidNextToken: - fmt.Println(autoscaling.ErrCodeInvalidNextToken, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the Auto Scaling process types -// -// This example describes the Auto Scaling process types. -func ExampleAutoScaling_DescribeScalingProcessTypes_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeScalingProcessTypesInput{} - - result, err := svc.DescribeScalingProcessTypes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe scheduled actions -// -// This example describes the scheduled actions for the specified Auto Scaling group. -func ExampleAutoScaling_DescribeScheduledActions_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeScheduledActionsInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - } - - result, err := svc.DescribeScheduledActions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeInvalidNextToken: - fmt.Println(autoscaling.ErrCodeInvalidNextToken, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe tags -// -// This example describes the tags for the specified Auto Scaling group. -func ExampleAutoScaling_DescribeTags_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeTagsInput{ - Filters: []*autoscaling.Filter{ - { - Name: aws.String("auto-scaling-group"), - Values: []*string{ - aws.String("my-auto-scaling-group"), - }, - }, - }, - } - - result, err := svc.DescribeTags(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeInvalidNextToken: - fmt.Println(autoscaling.ErrCodeInvalidNextToken, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe termination policy types -// -// This example describes the available termination policy types. -func ExampleAutoScaling_DescribeTerminationPolicyTypes_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DescribeTerminationPolicyTypesInput{} - - result, err := svc.DescribeTerminationPolicyTypes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To detach an instance from an Auto Scaling group -// -// This example detaches the specified instance from the specified Auto Scaling group. -func ExampleAutoScaling_DetachInstances_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DetachInstancesInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - InstanceIds: []*string{ - aws.String("i-93633f9b"), - }, - ShouldDecrementDesiredCapacity: aws.Bool(true), - } - - result, err := svc.DetachInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To detach a target group from an Auto Scaling group -// -// This example detaches the specified target group from the specified Auto Scaling -// group -func ExampleAutoScaling_DetachLoadBalancerTargetGroups_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DetachLoadBalancerTargetGroupsInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - TargetGroupARNs: []*string{ - aws.String("arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067"), - }, - } - - result, err := svc.DetachLoadBalancerTargetGroups(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To detach a load balancer from an Auto Scaling group -// -// This example detaches the specified load balancer from the specified Auto Scaling -// group. -func ExampleAutoScaling_DetachLoadBalancers_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DetachLoadBalancersInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - LoadBalancerNames: []*string{ - aws.String("my-load-balancer"), - }, - } - - result, err := svc.DetachLoadBalancers(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To disable metrics collection for an Auto Scaling group -// -// This example disables collecting data for the GroupDesiredCapacity metric for the -// specified Auto Scaling group. -func ExampleAutoScaling_DisableMetricsCollection_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.DisableMetricsCollectionInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - Metrics: []*string{ - aws.String("GroupDesiredCapacity"), - }, - } - - result, err := svc.DisableMetricsCollection(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To enable metrics collection for an Auto Scaling group -// -// This example enables data collection for the specified Auto Scaling group. -func ExampleAutoScaling_EnableMetricsCollection_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.EnableMetricsCollectionInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - Granularity: aws.String("1Minute"), - } - - result, err := svc.EnableMetricsCollection(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To move instances into standby mode -// -// This example puts the specified instance into standby mode. -func ExampleAutoScaling_EnterStandby_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.EnterStandbyInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - InstanceIds: []*string{ - aws.String("i-93633f9b"), - }, - ShouldDecrementDesiredCapacity: aws.Bool(true), - } - - result, err := svc.EnterStandby(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To execute an Auto Scaling policy -// -// This example executes the specified Auto Scaling policy for the specified Auto Scaling -// group. -func ExampleAutoScaling_ExecutePolicy_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.ExecutePolicyInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - HonorCooldown: aws.Bool(true), - PolicyName: aws.String("ScaleIn"), - } - - result, err := svc.ExecutePolicy(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeScalingActivityInProgressFault: - fmt.Println(autoscaling.ErrCodeScalingActivityInProgressFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To move instances out of standby mode -// -// This example moves the specified instance out of standby mode. -func ExampleAutoScaling_ExitStandby_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.ExitStandbyInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - InstanceIds: []*string{ - aws.String("i-93633f9b"), - }, - } - - result, err := svc.ExitStandby(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a lifecycle hook -// -// This example creates a lifecycle hook. -func ExampleAutoScaling_PutLifecycleHook_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.PutLifecycleHookInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - LifecycleHookName: aws.String("my-lifecycle-hook"), - LifecycleTransition: aws.String("autoscaling:EC2_INSTANCE_LAUNCHING"), - NotificationTargetARN: aws.String("arn:aws:sns:us-west-2:123456789012:my-sns-topic --role-arn"), - RoleARN: aws.String("arn:aws:iam::123456789012:role/my-auto-scaling-role"), - } - - result, err := svc.PutLifecycleHook(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To add an Auto Scaling notification -// -// This example adds the specified notification to the specified Auto Scaling group. -func ExampleAutoScaling_PutNotificationConfiguration_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.PutNotificationConfigurationInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - NotificationTypes: []*string{ - aws.String("autoscaling:TEST_NOTIFICATION"), - }, - TopicARN: aws.String("arn:aws:sns:us-west-2:123456789012:my-sns-topic"), - } - - result, err := svc.PutNotificationConfiguration(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To add a scaling policy to an Auto Scaling group -// -// This example adds the specified policy to the specified Auto Scaling group. -func ExampleAutoScaling_PutScalingPolicy_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.PutScalingPolicyInput{ - AdjustmentType: aws.String("ChangeInCapacity"), - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - PolicyName: aws.String("ScaleIn"), - ScalingAdjustment: aws.Int64(-1), - } - - result, err := svc.PutScalingPolicy(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To add a scheduled action to an Auto Scaling group -// -// This example adds the specified scheduled action to the specified Auto Scaling group. -func ExampleAutoScaling_PutScheduledUpdateGroupAction_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.PutScheduledUpdateGroupActionInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - DesiredCapacity: aws.Int64(4), - EndTime: parseTime("2006-01-02T15:04:05Z", "2014-05-12T08:00:00Z"), - MaxSize: aws.Int64(6), - MinSize: aws.Int64(2), - ScheduledActionName: aws.String("my-scheduled-action"), - StartTime: parseTime("2006-01-02T15:04:05Z", "2014-05-12T08:00:00Z"), - } - - result, err := svc.PutScheduledUpdateGroupAction(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeAlreadyExistsFault: - fmt.Println(autoscaling.ErrCodeAlreadyExistsFault, aerr.Error()) - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To record a lifecycle action heartbeat -// -// This example records a lifecycle action heartbeat to keep the instance in a pending -// state. -func ExampleAutoScaling_RecordLifecycleActionHeartbeat_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.RecordLifecycleActionHeartbeatInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - LifecycleActionToken: aws.String("bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635"), - LifecycleHookName: aws.String("my-lifecycle-hook"), - } - - result, err := svc.RecordLifecycleActionHeartbeat(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To resume Auto Scaling processes -// -// This example resumes the specified suspended scaling process for the specified Auto -// Scaling group. -func ExampleAutoScaling_ResumeProcesses_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.ScalingProcessQuery{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - ScalingProcesses: []*string{ - aws.String("AlarmNotification"), - }, - } - - result, err := svc.ResumeProcesses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceInUseFault: - fmt.Println(autoscaling.ErrCodeResourceInUseFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To set the desired capacity for an Auto Scaling group -// -// This example sets the desired capacity for the specified Auto Scaling group. -func ExampleAutoScaling_SetDesiredCapacity_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.SetDesiredCapacityInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - DesiredCapacity: aws.Int64(2), - HonorCooldown: aws.Bool(true), - } - - result, err := svc.SetDesiredCapacity(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeScalingActivityInProgressFault: - fmt.Println(autoscaling.ErrCodeScalingActivityInProgressFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To set the health status of an instance -// -// This example sets the health status of the specified instance to Unhealthy. -func ExampleAutoScaling_SetInstanceHealth_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.SetInstanceHealthInput{ - HealthStatus: aws.String("Unhealthy"), - InstanceId: aws.String("i-93633f9b"), - } - - result, err := svc.SetInstanceHealth(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To enable instance protection for an instance -// -// This example enables instance protection for the specified instance. -func ExampleAutoScaling_SetInstanceProtection_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.SetInstanceProtectionInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - InstanceIds: []*string{ - aws.String("i-93633f9b"), - }, - ProtectedFromScaleIn: aws.Bool(true), - } - - result, err := svc.SetInstanceProtection(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To disable instance protection for an instance -// -// This example disables instance protection for the specified instance. -func ExampleAutoScaling_SetInstanceProtection_shared01() { - svc := autoscaling.New(session.New()) - input := &autoscaling.SetInstanceProtectionInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - InstanceIds: []*string{ - aws.String("i-93633f9b"), - }, - ProtectedFromScaleIn: aws.Bool(false), - } - - result, err := svc.SetInstanceProtection(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeLimitExceededFault: - fmt.Println(autoscaling.ErrCodeLimitExceededFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To suspend Auto Scaling processes -// -// This example suspends the specified scaling process for the specified Auto Scaling -// group. -func ExampleAutoScaling_SuspendProcesses_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.ScalingProcessQuery{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - ScalingProcesses: []*string{ - aws.String("AlarmNotification"), - }, - } - - result, err := svc.SuspendProcesses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeResourceInUseFault: - fmt.Println(autoscaling.ErrCodeResourceInUseFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To terminate an instance in an Auto Scaling group -// -// This example terminates the specified instance from the specified Auto Scaling group -// without updating the size of the group. Auto Scaling launches a replacement instance -// after the specified instance terminates. -func ExampleAutoScaling_TerminateInstanceInAutoScalingGroup_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.TerminateInstanceInAutoScalingGroupInput{ - InstanceId: aws.String("i-93633f9b"), - ShouldDecrementDesiredCapacity: aws.Bool(false), - } - - result, err := svc.TerminateInstanceInAutoScalingGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeScalingActivityInProgressFault: - fmt.Println(autoscaling.ErrCodeScalingActivityInProgressFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To update the launch configuration -// -// This example updates the launch configuration of the specified Auto Scaling group. -func ExampleAutoScaling_UpdateAutoScalingGroup_shared00() { - svc := autoscaling.New(session.New()) - input := &autoscaling.UpdateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - LaunchConfigurationName: aws.String("new-launch-config"), - } - - result, err := svc.UpdateAutoScalingGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeScalingActivityInProgressFault: - fmt.Println(autoscaling.ErrCodeScalingActivityInProgressFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To update the minimum and maximum size -// -// This example updates the minimum size and maximum size of the specified Auto Scaling -// group. -func ExampleAutoScaling_UpdateAutoScalingGroup_shared01() { - svc := autoscaling.New(session.New()) - input := &autoscaling.UpdateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - MaxSize: aws.Int64(3), - MinSize: aws.Int64(1), - } - - result, err := svc.UpdateAutoScalingGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeScalingActivityInProgressFault: - fmt.Println(autoscaling.ErrCodeScalingActivityInProgressFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To enable instance protection -// -// This example enables instance protection for the specified Auto Scaling group. -func ExampleAutoScaling_UpdateAutoScalingGroup_shared02() { - svc := autoscaling.New(session.New()) - input := &autoscaling.UpdateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("my-auto-scaling-group"), - NewInstancesProtectedFromScaleIn: aws.Bool(true), - } - - result, err := svc.UpdateAutoScalingGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case autoscaling.ErrCodeScalingActivityInProgressFault: - fmt.Println(autoscaling.ErrCodeScalingActivityInProgressFault, aerr.Error()) - case autoscaling.ErrCodeResourceContentionFault: - fmt.Println(autoscaling.ErrCodeResourceContentionFault, aerr.Error()) - case autoscaling.ErrCodeServiceLinkedRoleFailure: - fmt.Println(autoscaling.ErrCodeServiceLinkedRoleFailure, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/service.go b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/service.go index a844a83f..e1da9fd7 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/autoscaling/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/autoscaling/service.go @@ -29,9 +29,9 @@ var initRequest func(*request.Request) // Service information constants const ( - ServiceName = "autoscaling" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. - ServiceID = "Auto Scaling" // ServiceID is a unique identifer of a specific service + ServiceName = "autoscaling" // Name of service. + EndpointsID = ServiceName // ID to lookup a service endpoint with. + ServiceID = "Auto Scaling" // ServiceID is a unique identifer of a specific service. ) // New creates a new instance of the AutoScaling client with a session. diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go deleted file mode 100644 index 08ff2cf0..00000000 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package ec2_test - -import ( - "io/ioutil" - "net/url" - "regexp" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/ec2" -) - -func TestCopySnapshotPresignedURL(t *testing.T) { - svc := ec2.New(unit.Session, &aws.Config{Region: aws.String("us-west-2")}) - - func() { - defer func() { - if r := recover(); r != nil { - t.Fatalf("expect CopySnapshotRequest with nill") - } - }() - // Doesn't panic on nil input - req, _ := svc.CopySnapshotRequest(nil) - req.Sign() - }() - - req, _ := svc.CopySnapshotRequest(&ec2.CopySnapshotInput{ - SourceRegion: aws.String("us-west-1"), - SourceSnapshotId: aws.String("snap-id"), - }) - req.Sign() - - b, _ := ioutil.ReadAll(req.HTTPRequest.Body) - q, _ := url.ParseQuery(string(b)) - u, _ := url.QueryUnescape(q.Get("PresignedUrl")) - if e, a := "us-west-2", q.Get("DestinationRegion"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - if e, a := "us-west-1", q.Get("SourceRegion"); e != a { - t.Errorf("expect %v, got %v", e, a) - } - - r := regexp.MustCompile(`^https://ec2\.us-west-1\.amazonaws\.com/.+&DestinationRegion=us-west-2`) - if !r.MatchString(u) { - t.Errorf("expect %v to match, got %v", r.String(), u) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/examples_test.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/examples_test.go deleted file mode 100644 index fdc8670c..00000000 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/examples_test.go +++ /dev/null @@ -1,4213 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package ec2_test - -import ( - "fmt" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" -) - -var _ time.Duration -var _ strings.Reader -var _ aws.Config - -func parseTime(layout, value string) *time.Time { - t, err := time.Parse(layout, value) - if err != nil { - panic(err) - } - return &t -} - -// To allocate an Elastic IP address for EC2-VPC -// -// This example allocates an Elastic IP address to use with an instance in a VPC. -func ExampleEC2_AllocateAddress_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AllocateAddressInput{ - Domain: aws.String("vpc"), - } - - result, err := svc.AllocateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To allocate an Elastic IP address for EC2-Classic -// -// This example allocates an Elastic IP address to use with an instance in EC2-Classic. -func ExampleEC2_AllocateAddress_shared01() { - svc := ec2.New(session.New()) - input := &ec2.AllocateAddressInput{} - - result, err := svc.AllocateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To assign a specific secondary private IP address to an interface -// -// This example assigns the specified secondary private IP address to the specified -// network interface. -func ExampleEC2_AssignPrivateIpAddresses_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AssignPrivateIpAddressesInput{ - NetworkInterfaceId: aws.String("eni-e5aa89a3"), - PrivateIpAddresses: []*string{ - aws.String("10.0.0.82"), - }, - } - - result, err := svc.AssignPrivateIpAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To assign secondary private IP addresses that Amazon EC2 selects to an interface -// -// This example assigns two secondary private IP addresses to the specified network -// interface. Amazon EC2 automatically assigns these IP addresses from the available -// IP addresses in the CIDR block range of the subnet the network interface is associated -// with. -func ExampleEC2_AssignPrivateIpAddresses_shared01() { - svc := ec2.New(session.New()) - input := &ec2.AssignPrivateIpAddressesInput{ - NetworkInterfaceId: aws.String("eni-e5aa89a3"), - SecondaryPrivateIpAddressCount: aws.Int64(2), - } - - result, err := svc.AssignPrivateIpAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate an Elastic IP address in EC2-VPC -// -// This example associates the specified Elastic IP address with the specified instance -// in a VPC. -func ExampleEC2_AssociateAddress_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AssociateAddressInput{ - AllocationId: aws.String("eipalloc-64d5890a"), - InstanceId: aws.String("i-0b263919b6498b123"), - } - - result, err := svc.AssociateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate an Elastic IP address with a network interface -// -// This example associates the specified Elastic IP address with the specified network -// interface. -func ExampleEC2_AssociateAddress_shared01() { - svc := ec2.New(session.New()) - input := &ec2.AssociateAddressInput{ - AllocationId: aws.String("eipalloc-64d5890a"), - NetworkInterfaceId: aws.String("eni-1a2b3c4d"), - } - - result, err := svc.AssociateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate an Elastic IP address in EC2-Classic -// -// This example associates an Elastic IP address with an instance in EC2-Classic. -func ExampleEC2_AssociateAddress_shared02() { - svc := ec2.New(session.New()) - input := &ec2.AssociateAddressInput{ - InstanceId: aws.String("i-07ffe74c7330ebf53"), - PublicIp: aws.String("198.51.100.0"), - } - - result, err := svc.AssociateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate a DHCP options set with a VPC -// -// This example associates the specified DHCP options set with the specified VPC. -func ExampleEC2_AssociateDhcpOptions_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AssociateDhcpOptionsInput{ - DhcpOptionsId: aws.String("dopt-d9070ebb"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.AssociateDhcpOptions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate the default DHCP options set with a VPC -// -// This example associates the default DHCP options set with the specified VPC. -func ExampleEC2_AssociateDhcpOptions_shared01() { - svc := ec2.New(session.New()) - input := &ec2.AssociateDhcpOptionsInput{ - DhcpOptionsId: aws.String("default"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.AssociateDhcpOptions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To associate a route table with a subnet -// -// This example associates the specified route table with the specified subnet. -func ExampleEC2_AssociateRouteTable_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AssociateRouteTableInput{ - RouteTableId: aws.String("rtb-22574640"), - SubnetId: aws.String("subnet-9d4a7b6"), - } - - result, err := svc.AssociateRouteTable(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To attach an Internet gateway to a VPC -// -// This example attaches the specified Internet gateway to the specified VPC. -func ExampleEC2_AttachInternetGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AttachInternetGatewayInput{ - InternetGatewayId: aws.String("igw-c0a643a9"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.AttachInternetGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To attach a network interface to an instance -// -// This example attaches the specified network interface to the specified instance. -func ExampleEC2_AttachNetworkInterface_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AttachNetworkInterfaceInput{ - DeviceIndex: aws.Int64(1), - InstanceId: aws.String("i-1234567890abcdef0"), - NetworkInterfaceId: aws.String("eni-e5aa89a3"), - } - - result, err := svc.AttachNetworkInterface(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To attach a volume to an instance -// -// This example attaches a volume (``vol-1234567890abcdef0``) to an instance (``i-01474ef662b89480``) -// as ``/dev/sdf``. -func ExampleEC2_AttachVolume_shared00() { - svc := ec2.New(session.New()) - input := &ec2.AttachVolumeInput{ - Device: aws.String("/dev/sdf"), - InstanceId: aws.String("i-01474ef662b89480"), - VolumeId: aws.String("vol-1234567890abcdef0"), - } - - result, err := svc.AttachVolume(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To cancel a Spot fleet request -// -// This example cancels the specified Spot fleet request and terminates its associated -// Spot Instances. -func ExampleEC2_CancelSpotFleetRequests_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CancelSpotFleetRequestsInput{ - SpotFleetRequestIds: []*string{ - aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - }, - TerminateInstances: aws.Bool(true), - } - - result, err := svc.CancelSpotFleetRequests(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To cancel a Spot fleet request without terminating its Spot Instances -// -// This example cancels the specified Spot fleet request without terminating its associated -// Spot Instances. -func ExampleEC2_CancelSpotFleetRequests_shared01() { - svc := ec2.New(session.New()) - input := &ec2.CancelSpotFleetRequestsInput{ - SpotFleetRequestIds: []*string{ - aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - }, - TerminateInstances: aws.Bool(false), - } - - result, err := svc.CancelSpotFleetRequests(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To cancel Spot Instance requests -// -// This example cancels a Spot Instance request. -func ExampleEC2_CancelSpotInstanceRequests_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CancelSpotInstanceRequestsInput{ - SpotInstanceRequestIds: []*string{ - aws.String("sir-08b93456"), - }, - } - - result, err := svc.CancelSpotInstanceRequests(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To confirm the product instance -// -// This example determines whether the specified product code is associated with the -// specified instance. -func ExampleEC2_ConfirmProductInstance_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ConfirmProductInstanceInput{ - InstanceId: aws.String("i-1234567890abcdef0"), - ProductCode: aws.String("774F4FF8"), - } - - result, err := svc.ConfirmProductInstance(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To copy a snapshot -// -// This example copies a snapshot with the snapshot ID of ``snap-066877671789bd71b`` -// from the ``us-west-2`` region to the ``us-east-1`` region and adds a short description -// to identify the snapshot. -func ExampleEC2_CopySnapshot_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CopySnapshotInput{ - Description: aws.String("This is my copied snapshot."), - DestinationRegion: aws.String("us-east-1"), - SourceRegion: aws.String("us-west-2"), - SourceSnapshotId: aws.String("snap-066877671789bd71b"), - } - - result, err := svc.CopySnapshot(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a customer gateway -// -// This example creates a customer gateway with the specified IP address for its outside -// interface. -func ExampleEC2_CreateCustomerGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateCustomerGatewayInput{ - BgpAsn: aws.Int64(65534), - PublicIp: aws.String("12.1.2.3"), - Type: aws.String("ipsec.1"), - } - - result, err := svc.CreateCustomerGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a DHCP options set -// -// This example creates a DHCP options set. -func ExampleEC2_CreateDhcpOptions_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateDhcpOptionsInput{ - DhcpConfigurations: []*ec2.NewDhcpConfiguration{ - { - Key: aws.String("domain-name-servers"), - Values: []*string{ - aws.String("10.2.5.1"), - aws.String("10.2.5.2"), - }, - }, - }, - } - - result, err := svc.CreateDhcpOptions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create an Internet gateway -// -// This example creates an Internet gateway. -func ExampleEC2_CreateInternetGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateInternetGatewayInput{} - - result, err := svc.CreateInternetGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a key pair -// -// This example creates a key pair named my-key-pair. -func ExampleEC2_CreateKeyPair_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateKeyPairInput{ - KeyName: aws.String("my-key-pair"), - } - - result, err := svc.CreateKeyPair(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a NAT gateway -// -// This example creates a NAT gateway in subnet subnet-1a2b3c4d and associates an Elastic -// IP address with the allocation ID eipalloc-37fc1a52 with the NAT gateway. -func ExampleEC2_CreateNatGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateNatGatewayInput{ - AllocationId: aws.String("eipalloc-37fc1a52"), - SubnetId: aws.String("subnet-1a2b3c4d"), - } - - result, err := svc.CreateNatGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a network ACL -// -// This example creates a network ACL for the specified VPC. -func ExampleEC2_CreateNetworkAcl_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateNetworkAclInput{ - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.CreateNetworkAcl(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a network ACL entry -// -// This example creates an entry for the specified network ACL. The rule allows ingress -// traffic from anywhere (0.0.0.0/0) on UDP port 53 (DNS) into any associated subnet. -func ExampleEC2_CreateNetworkAclEntry_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateNetworkAclEntryInput{ - CidrBlock: aws.String("0.0.0.0/0"), - Egress: aws.Bool(false), - NetworkAclId: aws.String("acl-5fb85d36"), - PortRange: &ec2.PortRange{ - From: aws.Int64(53), - To: aws.Int64(53), - }, - Protocol: aws.String("udp"), - RuleAction: aws.String("allow"), - RuleNumber: aws.Int64(100), - } - - result, err := svc.CreateNetworkAclEntry(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a network interface -// -// This example creates a network interface for the specified subnet. -func ExampleEC2_CreateNetworkInterface_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateNetworkInterfaceInput{ - Description: aws.String("my network interface"), - Groups: []*string{ - aws.String("sg-903004f8"), - }, - PrivateIpAddress: aws.String("10.0.2.17"), - SubnetId: aws.String("subnet-9d4a7b6c"), - } - - result, err := svc.CreateNetworkInterface(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a placement group -// -// This example creates a placement group with the specified name. -func ExampleEC2_CreatePlacementGroup_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreatePlacementGroupInput{ - GroupName: aws.String("my-cluster"), - Strategy: aws.String("cluster"), - } - - result, err := svc.CreatePlacementGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a route -// -// This example creates a route for the specified route table. The route matches all -// traffic (0.0.0.0/0) and routes it to the specified Internet gateway. -func ExampleEC2_CreateRoute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateRouteInput{ - DestinationCidrBlock: aws.String("0.0.0.0/0"), - GatewayId: aws.String("igw-c0a643a9"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.CreateRoute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a route table -// -// This example creates a route table for the specified VPC. -func ExampleEC2_CreateRouteTable_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateRouteTableInput{ - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.CreateRouteTable(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a snapshot -// -// This example creates a snapshot of the volume with a volume ID of ``vol-1234567890abcdef0`` -// and a short description to identify the snapshot. -func ExampleEC2_CreateSnapshot_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateSnapshotInput{ - Description: aws.String("This is my root volume snapshot."), - VolumeId: aws.String("vol-1234567890abcdef0"), - } - - result, err := svc.CreateSnapshot(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a Spot Instance datafeed -// -// This example creates a Spot Instance data feed for your AWS account. -func ExampleEC2_CreateSpotDatafeedSubscription_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateSpotDatafeedSubscriptionInput{ - Bucket: aws.String("my-s3-bucket"), - Prefix: aws.String("spotdata"), - } - - result, err := svc.CreateSpotDatafeedSubscription(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a subnet -// -// This example creates a subnet in the specified VPC with the specified CIDR block. -// We recommend that you let us select an Availability Zone for you. -func ExampleEC2_CreateSubnet_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateSubnetInput{ - CidrBlock: aws.String("10.0.1.0/24"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.CreateSubnet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To add a tag to a resource -// -// This example adds the tag Stack=production to the specified image, or overwrites -// an existing tag for the AMI where the tag key is Stack. -func ExampleEC2_CreateTags_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateTagsInput{ - Resources: []*string{ - aws.String("ami-78a54011"), - }, - Tags: []*ec2.Tag{ - { - Key: aws.String("Stack"), - Value: aws.String("production"), - }, - }, - } - - result, err := svc.CreateTags(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a new volume -// -// This example creates an 80 GiB General Purpose (SSD) volume in the Availability Zone -// ``us-east-1a``. -func ExampleEC2_CreateVolume_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateVolumeInput{ - AvailabilityZone: aws.String("us-east-1a"), - Size: aws.Int64(80), - VolumeType: aws.String("gp2"), - } - - result, err := svc.CreateVolume(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a new Provisioned IOPS (SSD) volume from a snapshot -// -// This example creates a new Provisioned IOPS (SSD) volume with 1000 provisioned IOPS -// from a snapshot in the Availability Zone ``us-east-1a``. -func ExampleEC2_CreateVolume_shared01() { - svc := ec2.New(session.New()) - input := &ec2.CreateVolumeInput{ - AvailabilityZone: aws.String("us-east-1a"), - Iops: aws.Int64(1000), - SnapshotId: aws.String("snap-066877671789bd71b"), - VolumeType: aws.String("io1"), - } - - result, err := svc.CreateVolume(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a VPC -// -// This example creates a VPC with the specified CIDR block. -func ExampleEC2_CreateVpc_shared00() { - svc := ec2.New(session.New()) - input := &ec2.CreateVpcInput{ - CidrBlock: aws.String("10.0.0.0/16"), - } - - result, err := svc.CreateVpc(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a customer gateway -// -// This example deletes the specified customer gateway. -func ExampleEC2_DeleteCustomerGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteCustomerGatewayInput{ - CustomerGatewayId: aws.String("cgw-0e11f167"), - } - - result, err := svc.DeleteCustomerGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a DHCP options set -// -// This example deletes the specified DHCP options set. -func ExampleEC2_DeleteDhcpOptions_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteDhcpOptionsInput{ - DhcpOptionsId: aws.String("dopt-d9070ebb"), - } - - result, err := svc.DeleteDhcpOptions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete an Internet gateway -// -// This example deletes the specified Internet gateway. -func ExampleEC2_DeleteInternetGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteInternetGatewayInput{ - InternetGatewayId: aws.String("igw-c0a643a9"), - } - - result, err := svc.DeleteInternetGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a key pair -// -// This example deletes the specified key pair. -func ExampleEC2_DeleteKeyPair_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteKeyPairInput{ - KeyName: aws.String("my-key-pair"), - } - - result, err := svc.DeleteKeyPair(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a NAT gateway -// -// This example deletes the specified NAT gateway. -func ExampleEC2_DeleteNatGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteNatGatewayInput{ - NatGatewayId: aws.String("nat-04ae55e711cec5680"), - } - - result, err := svc.DeleteNatGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a network ACL -// -// This example deletes the specified network ACL. -func ExampleEC2_DeleteNetworkAcl_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteNetworkAclInput{ - NetworkAclId: aws.String("acl-5fb85d36"), - } - - result, err := svc.DeleteNetworkAcl(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a network ACL entry -// -// This example deletes ingress rule number 100 from the specified network ACL. -func ExampleEC2_DeleteNetworkAclEntry_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteNetworkAclEntryInput{ - Egress: aws.Bool(true), - NetworkAclId: aws.String("acl-5fb85d36"), - RuleNumber: aws.Int64(100), - } - - result, err := svc.DeleteNetworkAclEntry(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a network interface -// -// This example deletes the specified network interface. -func ExampleEC2_DeleteNetworkInterface_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteNetworkInterfaceInput{ - NetworkInterfaceId: aws.String("eni-e5aa89a3"), - } - - result, err := svc.DeleteNetworkInterface(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a placement group -// -// This example deletes the specified placement group. -// -func ExampleEC2_DeletePlacementGroup_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeletePlacementGroupInput{ - GroupName: aws.String("my-cluster"), - } - - result, err := svc.DeletePlacementGroup(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a route -// -// This example deletes the specified route from the specified route table. -func ExampleEC2_DeleteRoute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteRouteInput{ - DestinationCidrBlock: aws.String("0.0.0.0/0"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.DeleteRoute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a route table -// -// This example deletes the specified route table. -func ExampleEC2_DeleteRouteTable_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteRouteTableInput{ - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.DeleteRouteTable(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a snapshot -// -// This example deletes a snapshot with the snapshot ID of ``snap-1234567890abcdef0``. -// If the command succeeds, no output is returned. -func ExampleEC2_DeleteSnapshot_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteSnapshotInput{ - SnapshotId: aws.String("snap-1234567890abcdef0"), - } - - result, err := svc.DeleteSnapshot(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To cancel a Spot Instance data feed subscription -// -// This example deletes a Spot data feed subscription for the account. -func ExampleEC2_DeleteSpotDatafeedSubscription_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteSpotDatafeedSubscriptionInput{} - - result, err := svc.DeleteSpotDatafeedSubscription(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a subnet -// -// This example deletes the specified subnet. -func ExampleEC2_DeleteSubnet_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteSubnetInput{ - SubnetId: aws.String("subnet-9d4a7b6c"), - } - - result, err := svc.DeleteSubnet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a tag from a resource -// -// This example deletes the tag Stack=test from the specified image. -func ExampleEC2_DeleteTags_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteTagsInput{ - Resources: []*string{ - aws.String("ami-78a54011"), - }, - Tags: []*ec2.Tag{ - { - Key: aws.String("Stack"), - Value: aws.String("test"), - }, - }, - } - - result, err := svc.DeleteTags(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a volume -// -// This example deletes an available volume with the volume ID of ``vol-049df61146c4d7901``. -// If the command succeeds, no output is returned. -func ExampleEC2_DeleteVolume_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteVolumeInput{ - VolumeId: aws.String("vol-049df61146c4d7901"), - } - - result, err := svc.DeleteVolume(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To delete a VPC -// -// This example deletes the specified VPC. -func ExampleEC2_DeleteVpc_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DeleteVpcInput{ - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.DeleteVpc(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a single attribute for your AWS account -// -// This example describes the supported-platforms attribute for your AWS account. -func ExampleEC2_DescribeAccountAttributes_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAccountAttributesInput{ - AttributeNames: []*string{ - aws.String("supported-platforms"), - }, - } - - result, err := svc.DescribeAccountAttributes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe all attributes for your AWS account -// -// This example describes the attributes for your AWS account. -func ExampleEC2_DescribeAccountAttributes_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAccountAttributesInput{} - - result, err := svc.DescribeAccountAttributes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Elastic IP addresses -// -// This example describes your Elastic IP addresses. -func ExampleEC2_DescribeAddresses_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAddressesInput{} - - result, err := svc.DescribeAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Elastic IP addresses for EC2-VPC -// -// This example describes your Elastic IP addresses for use with instances in a VPC. -func ExampleEC2_DescribeAddresses_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAddressesInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("domain"), - Values: []*string{ - aws.String("vpc"), - }, - }, - }, - } - - result, err := svc.DescribeAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Elastic IP addresses for EC2-Classic -// -// This example describes your Elastic IP addresses for use with instances in EC2-Classic. -func ExampleEC2_DescribeAddresses_shared02() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAddressesInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("domain"), - Values: []*string{ - aws.String("standard"), - }, - }, - }, - } - - result, err := svc.DescribeAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Availability Zones -// -// This example describes the Availability Zones that are available to you. The response -// includes Availability Zones only for the current region. -func ExampleEC2_DescribeAvailabilityZones_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeAvailabilityZonesInput{} - - result, err := svc.DescribeAvailabilityZones(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a customer gateway -// -// This example describes the specified customer gateway. -func ExampleEC2_DescribeCustomerGateways_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeCustomerGatewaysInput{ - CustomerGatewayIds: []*string{ - aws.String("cgw-0e11f167"), - }, - } - - result, err := svc.DescribeCustomerGateways(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a DHCP options set -// -// This example describes the specified DHCP options set. -func ExampleEC2_DescribeDhcpOptions_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeDhcpOptionsInput{ - DhcpOptionsIds: []*string{ - aws.String("dopt-d9070ebb"), - }, - } - - result, err := svc.DescribeDhcpOptions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the instance type -// -// This example describes the instance type of the specified instance. -// -func ExampleEC2_DescribeInstanceAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeInstanceAttributeInput{ - Attribute: aws.String("instanceType"), - InstanceId: aws.String("i-1234567890abcdef0"), - } - - result, err := svc.DescribeInstanceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the disableApiTermination attribute -// -// This example describes the ``disableApiTermination`` attribute of the specified instance. -// -func ExampleEC2_DescribeInstanceAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeInstanceAttributeInput{ - Attribute: aws.String("disableApiTermination"), - InstanceId: aws.String("i-1234567890abcdef0"), - } - - result, err := svc.DescribeInstanceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the block device mapping for an instance -// -// This example describes the ``blockDeviceMapping`` attribute of the specified instance. -// -func ExampleEC2_DescribeInstanceAttribute_shared02() { - svc := ec2.New(session.New()) - input := &ec2.DescribeInstanceAttributeInput{ - Attribute: aws.String("blockDeviceMapping"), - InstanceId: aws.String("i-1234567890abcdef0"), - } - - result, err := svc.DescribeInstanceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the Internet gateway for a VPC -// -// This example describes the Internet gateway for the specified VPC. -func ExampleEC2_DescribeInternetGateways_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeInternetGatewaysInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("attachment.vpc-id"), - Values: []*string{ - aws.String("vpc-a01106c2"), - }, - }, - }, - } - - result, err := svc.DescribeInternetGateways(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To display a key pair -// -// This example displays the fingerprint for the specified key. -func ExampleEC2_DescribeKeyPairs_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeKeyPairsInput{ - KeyNames: []*string{ - aws.String("my-key-pair"), - }, - } - - result, err := svc.DescribeKeyPairs(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your moving addresses -// -// This example describes all of your moving Elastic IP addresses. -func ExampleEC2_DescribeMovingAddresses_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeMovingAddressesInput{} - - result, err := svc.DescribeMovingAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a NAT gateway -// -// This example describes the NAT gateway for the specified VPC. -func ExampleEC2_DescribeNatGateways_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNatGatewaysInput{ - Filter: []*ec2.Filter{ - { - Name: aws.String("vpc-id"), - Values: []*string{ - aws.String("vpc-1a2b3c4d"), - }, - }, - }, - } - - result, err := svc.DescribeNatGateways(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a network ACL -// -// This example describes the specified network ACL. -func ExampleEC2_DescribeNetworkAcls_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkAclsInput{ - NetworkAclIds: []*string{ - aws.String("acl-5fb85d36"), - }, - } - - result, err := svc.DescribeNetworkAcls(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the attachment attribute of a network interface -// -// This example describes the attachment attribute of the specified network interface. -func ExampleEC2_DescribeNetworkInterfaceAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkInterfaceAttributeInput{ - Attribute: aws.String("attachment"), - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.DescribeNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the description attribute of a network interface -// -// This example describes the description attribute of the specified network interface. -func ExampleEC2_DescribeNetworkInterfaceAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkInterfaceAttributeInput{ - Attribute: aws.String("description"), - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.DescribeNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the groupSet attribute of a network interface -// -// This example describes the groupSet attribute of the specified network interface. -func ExampleEC2_DescribeNetworkInterfaceAttribute_shared02() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkInterfaceAttributeInput{ - Attribute: aws.String("groupSet"), - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.DescribeNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the sourceDestCheck attribute of a network interface -// -// This example describes the sourceDestCheck attribute of the specified network interface. -func ExampleEC2_DescribeNetworkInterfaceAttribute_shared03() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkInterfaceAttributeInput{ - Attribute: aws.String("sourceDestCheck"), - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.DescribeNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a network interface -// - -func ExampleEC2_DescribeNetworkInterfaces_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeNetworkInterfacesInput{ - NetworkInterfaceIds: []*string{ - aws.String("eni-e5aa89a3"), - }, - } - - result, err := svc.DescribeNetworkInterfaces(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your regions -// -// This example describes all the regions that are available to you. -func ExampleEC2_DescribeRegions_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeRegionsInput{} - - result, err := svc.DescribeRegions(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a route table -// -// This example describes the specified route table. -func ExampleEC2_DescribeRouteTables_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeRouteTablesInput{ - RouteTableIds: []*string{ - aws.String("rtb-1f382e7d"), - }, - } - - result, err := svc.DescribeRouteTables(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe an available schedule -// -// This example describes a schedule that occurs every week on Sunday, starting on the -// specified date. Note that the output contains a single schedule as an example. -func ExampleEC2_DescribeScheduledInstanceAvailability_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeScheduledInstanceAvailabilityInput{ - FirstSlotStartTimeRange: &ec2.SlotDateTimeRangeRequest{ - EarliestTime: parseTime("2006-01-02T15:04:05Z", "2016-01-31T00:00:00Z"), - LatestTime: parseTime("2006-01-02T15:04:05Z", "2016-01-31T04:00:00Z"), - }, - Recurrence: &ec2.ScheduledInstanceRecurrenceRequest{ - Frequency: aws.String("Weekly"), - Interval: aws.Int64(1), - OccurrenceDays: []*int64{ - aws.Int64(1), - }, - }, - } - - result, err := svc.DescribeScheduledInstanceAvailability(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe your Scheduled Instances -// -// This example describes the specified Scheduled Instance. -func ExampleEC2_DescribeScheduledInstances_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeScheduledInstancesInput{ - ScheduledInstanceIds: []*string{ - aws.String("sci-1234-1234-1234-1234-123456789012"), - }, - } - - result, err := svc.DescribeScheduledInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe snapshot attributes -// -// This example describes the ``createVolumePermission`` attribute on a snapshot with -// the snapshot ID of ``snap-066877671789bd71b``. -func ExampleEC2_DescribeSnapshotAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSnapshotAttributeInput{ - Attribute: aws.String("createVolumePermission"), - SnapshotId: aws.String("snap-066877671789bd71b"), - } - - result, err := svc.DescribeSnapshotAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a snapshot -// -// This example describes a snapshot with the snapshot ID of ``snap-1234567890abcdef0``. -func ExampleEC2_DescribeSnapshots_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSnapshotsInput{ - SnapshotIds: []*string{ - aws.String("snap-1234567890abcdef0"), - }, - } - - result, err := svc.DescribeSnapshots(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe snapshots using filters -// -// This example describes all snapshots owned by the ID 012345678910 that are in the -// ``pending`` status. -func ExampleEC2_DescribeSnapshots_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSnapshotsInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("status"), - Values: []*string{ - aws.String("pending"), - }, - }, - }, - OwnerIds: []*string{ - aws.String("012345678910"), - }, - } - - result, err := svc.DescribeSnapshots(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the datafeed for your AWS account -// -// This example describes the Spot Instance datafeed subscription for your AWS account. -func ExampleEC2_DescribeSpotDatafeedSubscription_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotDatafeedSubscriptionInput{} - - result, err := svc.DescribeSpotDatafeedSubscription(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the Spot Instances associated with a Spot fleet -// -// This example lists the Spot Instances associated with the specified Spot fleet. -func ExampleEC2_DescribeSpotFleetInstances_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotFleetInstancesInput{ - SpotFleetRequestId: aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - } - - result, err := svc.DescribeSpotFleetInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe Spot fleet history -// -// This example returns the history for the specified Spot fleet starting at the specified -// time. -func ExampleEC2_DescribeSpotFleetRequestHistory_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotFleetRequestHistoryInput{ - SpotFleetRequestId: aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - StartTime: parseTime("2006-01-02T15:04:05Z", "2015-05-26T00:00:00Z"), - } - - result, err := svc.DescribeSpotFleetRequestHistory(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a Spot fleet request -// -// This example describes the specified Spot fleet request. -func ExampleEC2_DescribeSpotFleetRequests_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotFleetRequestsInput{ - SpotFleetRequestIds: []*string{ - aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - }, - } - - result, err := svc.DescribeSpotFleetRequests(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a Spot Instance request -// -// This example describes the specified Spot Instance request. -func ExampleEC2_DescribeSpotInstanceRequests_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotInstanceRequestsInput{ - SpotInstanceRequestIds: []*string{ - aws.String("sir-08b93456"), - }, - } - - result, err := svc.DescribeSpotInstanceRequests(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe Spot price history for Linux/UNIX (Amazon VPC) -// -// This example returns the Spot Price history for m1.xlarge, Linux/UNIX (Amazon VPC) -// instances for a particular day in January. -func ExampleEC2_DescribeSpotPriceHistory_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSpotPriceHistoryInput{ - EndTime: parseTime("2006-01-02T15:04:05Z", "2014-01-06T08:09:10"), - InstanceTypes: []*string{ - aws.String("m1.xlarge"), - }, - ProductDescriptions: []*string{ - aws.String("Linux/UNIX (Amazon VPC)"), - }, - StartTime: parseTime("2006-01-02T15:04:05Z", "2014-01-06T07:08:09"), - } - - result, err := svc.DescribeSpotPriceHistory(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the subnets for a VPC -// -// This example describes the subnets for the specified VPC. -func ExampleEC2_DescribeSubnets_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeSubnetsInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("vpc-id"), - Values: []*string{ - aws.String("vpc-a01106c2"), - }, - }, - }, - } - - result, err := svc.DescribeSubnets(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the tags for a single resource -// -// This example describes the tags for the specified instance. -func ExampleEC2_DescribeTags_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeTagsInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("resource-id"), - Values: []*string{ - aws.String("i-1234567890abcdef8"), - }, - }, - }, - } - - result, err := svc.DescribeTags(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a volume attribute -// -// This example describes the ``autoEnableIo`` attribute of the volume with the ID ``vol-049df61146c4d7901``. -func ExampleEC2_DescribeVolumeAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVolumeAttributeInput{ - Attribute: aws.String("autoEnableIO"), - VolumeId: aws.String("vol-049df61146c4d7901"), - } - - result, err := svc.DescribeVolumeAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the status of a single volume -// -// This example describes the status for the volume ``vol-1234567890abcdef0``. -func ExampleEC2_DescribeVolumeStatus_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVolumeStatusInput{ - VolumeIds: []*string{ - aws.String("vol-1234567890abcdef0"), - }, - } - - result, err := svc.DescribeVolumeStatus(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the status of impaired volumes -// -// This example describes the status for all volumes that are impaired. In this example -// output, there are no impaired volumes. -func ExampleEC2_DescribeVolumeStatus_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVolumeStatusInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("volume-status.status"), - Values: []*string{ - aws.String("impaired"), - }, - }, - }, - } - - result, err := svc.DescribeVolumeStatus(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe all volumes -// -// This example describes all of your volumes in the default region. -func ExampleEC2_DescribeVolumes_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVolumesInput{} - - result, err := svc.DescribeVolumes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe volumes that are attached to a specific instance -// -// This example describes all volumes that are both attached to the instance with the -// ID i-1234567890abcdef0 and set to delete when the instance terminates. -func ExampleEC2_DescribeVolumes_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVolumesInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("attachment.instance-id"), - Values: []*string{ - aws.String("i-1234567890abcdef0"), - }, - }, - { - Name: aws.String("attachment.delete-on-termination"), - Values: []*string{ - aws.String("true"), - }, - }, - }, - } - - result, err := svc.DescribeVolumes(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the enableDnsSupport attribute -// -// This example describes the enableDnsSupport attribute. This attribute indicates whether -// DNS resolution is enabled for the VPC. If this attribute is true, the Amazon DNS -// server resolves DNS hostnames for your instances to their corresponding IP addresses; -// otherwise, it does not. -func ExampleEC2_DescribeVpcAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVpcAttributeInput{ - Attribute: aws.String("enableDnsSupport"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.DescribeVpcAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe the enableDnsHostnames attribute -// -// This example describes the enableDnsHostnames attribute. This attribute indicates -// whether the instances launched in the VPC get DNS hostnames. If this attribute is -// true, instances in the VPC get DNS hostnames; otherwise, they do not. -func ExampleEC2_DescribeVpcAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVpcAttributeInput{ - Attribute: aws.String("enableDnsHostnames"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.DescribeVpcAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To describe a VPC -// -// This example describes the specified VPC. -func ExampleEC2_DescribeVpcs_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DescribeVpcsInput{ - VpcIds: []*string{ - aws.String("vpc-a01106c2"), - }, - } - - result, err := svc.DescribeVpcs(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To detach an Internet gateway from a VPC -// -// This example detaches the specified Internet gateway from the specified VPC. -func ExampleEC2_DetachInternetGateway_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DetachInternetGatewayInput{ - InternetGatewayId: aws.String("igw-c0a643a9"), - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.DetachInternetGateway(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To detach a network interface from an instance -// -// This example detaches the specified network interface from its attached instance. -func ExampleEC2_DetachNetworkInterface_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DetachNetworkInterfaceInput{ - AttachmentId: aws.String("eni-attach-66c4350a"), - } - - result, err := svc.DetachNetworkInterface(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To detach a volume from an instance -// -// This example detaches the volume (``vol-049df61146c4d7901``) from the instance it -// is attached to. -func ExampleEC2_DetachVolume_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DetachVolumeInput{ - VolumeId: aws.String("vol-1234567890abcdef0"), - } - - result, err := svc.DetachVolume(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To disable route propagation -// -// This example disables the specified virtual private gateway from propagating static -// routes to the specified route table. -func ExampleEC2_DisableVgwRoutePropagation_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DisableVgwRoutePropagationInput{ - GatewayId: aws.String("vgw-9a4cacf3"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.DisableVgwRoutePropagation(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To disassociate an Elastic IP address in EC2-VPC -// -// This example disassociates an Elastic IP address from an instance in a VPC. -func ExampleEC2_DisassociateAddress_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DisassociateAddressInput{ - AssociationId: aws.String("eipassoc-2bebb745"), - } - - result, err := svc.DisassociateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To disassociate an Elastic IP addresses in EC2-Classic -// -// This example disassociates an Elastic IP address from an instance in EC2-Classic. -func ExampleEC2_DisassociateAddress_shared01() { - svc := ec2.New(session.New()) - input := &ec2.DisassociateAddressInput{ - PublicIp: aws.String("198.51.100.0"), - } - - result, err := svc.DisassociateAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To disassociate a route table -// -// This example disassociates the specified route table from its associated subnet. -func ExampleEC2_DisassociateRouteTable_shared00() { - svc := ec2.New(session.New()) - input := &ec2.DisassociateRouteTableInput{ - AssociationId: aws.String("rtbassoc-781d0d1a"), - } - - result, err := svc.DisassociateRouteTable(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To enable route propagation -// -// This example enables the specified virtual private gateway to propagate static routes -// to the specified route table. -func ExampleEC2_EnableVgwRoutePropagation_shared00() { - svc := ec2.New(session.New()) - input := &ec2.EnableVgwRoutePropagationInput{ - GatewayId: aws.String("vgw-9a4cacf3"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.EnableVgwRoutePropagation(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To enable I/O for a volume -// -// This example enables I/O on volume ``vol-1234567890abcdef0``. -func ExampleEC2_EnableVolumeIO_shared00() { - svc := ec2.New(session.New()) - input := &ec2.EnableVolumeIOInput{ - VolumeId: aws.String("vol-1234567890abcdef0"), - } - - result, err := svc.EnableVolumeIO(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the attachment attribute of a network interface -// -// This example modifies the attachment attribute of the specified network interface. -func ExampleEC2_ModifyNetworkInterfaceAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifyNetworkInterfaceAttributeInput{ - Attachment: &ec2.NetworkInterfaceAttachmentChanges{ - AttachmentId: aws.String("eni-attach-43348162"), - DeleteOnTermination: aws.Bool(false), - }, - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.ModifyNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the description attribute of a network interface -// -// This example modifies the description attribute of the specified network interface. -func ExampleEC2_ModifyNetworkInterfaceAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.ModifyNetworkInterfaceAttributeInput{ - Description: &ec2.AttributeValue{ - Value: aws.String("My description"), - }, - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.ModifyNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the groupSet attribute of a network interface -// -// This example command modifies the groupSet attribute of the specified network interface. -func ExampleEC2_ModifyNetworkInterfaceAttribute_shared02() { - svc := ec2.New(session.New()) - input := &ec2.ModifyNetworkInterfaceAttributeInput{ - Groups: []*string{ - aws.String("sg-903004f8"), - aws.String("sg-1a2b3c4d"), - }, - NetworkInterfaceId: aws.String("eni-686ea200"), - } - - result, err := svc.ModifyNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the sourceDestCheck attribute of a network interface -// -// This example command modifies the sourceDestCheck attribute of the specified network -// interface. -func ExampleEC2_ModifyNetworkInterfaceAttribute_shared03() { - svc := ec2.New(session.New()) - input := &ec2.ModifyNetworkInterfaceAttributeInput{ - NetworkInterfaceId: aws.String("eni-686ea200"), - SourceDestCheck: &ec2.AttributeBooleanValue{ - Value: aws.Bool(false), - }, - } - - result, err := svc.ModifyNetworkInterfaceAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify a snapshot attribute -// -// This example modifies snapshot ``snap-1234567890abcdef0`` to remove the create volume -// permission for a user with the account ID ``123456789012``. If the command succeeds, -// no output is returned. -func ExampleEC2_ModifySnapshotAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifySnapshotAttributeInput{ - Attribute: aws.String("createVolumePermission"), - OperationType: aws.String("remove"), - SnapshotId: aws.String("snap-1234567890abcdef0"), - UserIds: []*string{ - aws.String("123456789012"), - }, - } - - result, err := svc.ModifySnapshotAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To make a snapshot public -// -// This example makes the snapshot ``snap-1234567890abcdef0`` public. -func ExampleEC2_ModifySnapshotAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.ModifySnapshotAttributeInput{ - Attribute: aws.String("createVolumePermission"), - GroupNames: []*string{ - aws.String("all"), - }, - OperationType: aws.String("add"), - SnapshotId: aws.String("snap-1234567890abcdef0"), - } - - result, err := svc.ModifySnapshotAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To increase the target capacity of a Spot fleet request -// -// This example increases the target capacity of the specified Spot fleet request. -func ExampleEC2_ModifySpotFleetRequest_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifySpotFleetRequestInput{ - SpotFleetRequestId: aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - TargetCapacity: aws.Int64(20), - } - - result, err := svc.ModifySpotFleetRequest(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To decrease the target capacity of a Spot fleet request -// -// This example decreases the target capacity of the specified Spot fleet request without -// terminating any Spot Instances as a result. -func ExampleEC2_ModifySpotFleetRequest_shared01() { - svc := ec2.New(session.New()) - input := &ec2.ModifySpotFleetRequestInput{ - ExcessCapacityTerminationPolicy: aws.String("NoTermination "), - SpotFleetRequestId: aws.String("sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"), - TargetCapacity: aws.Int64(10), - } - - result, err := svc.ModifySpotFleetRequest(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To change a subnet's public IP addressing behavior -// -// This example modifies the specified subnet so that all instances launched into this -// subnet are assigned a public IP address. -func ExampleEC2_ModifySubnetAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifySubnetAttributeInput{ - MapPublicIpOnLaunch: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - SubnetId: aws.String("subnet-1a2b3c4d"), - } - - result, err := svc.ModifySubnetAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify a volume attribute -// -// This example sets the ``autoEnableIo`` attribute of the volume with the ID ``vol-1234567890abcdef0`` -// to ``true``. If the command succeeds, no output is returned. -func ExampleEC2_ModifyVolumeAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifyVolumeAttributeInput{ - AutoEnableIO: &ec2.AttributeBooleanValue{ - Value: aws.Bool(true), - }, - DryRun: aws.Bool(true), - VolumeId: aws.String("vol-1234567890abcdef0"), - } - - result, err := svc.ModifyVolumeAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the enableDnsSupport attribute -// -// This example modifies the enableDnsSupport attribute. This attribute indicates whether -// DNS resolution is enabled for the VPC. If this attribute is true, the Amazon DNS -// server resolves DNS hostnames for instances in the VPC to their corresponding IP -// addresses; otherwise, it does not. -func ExampleEC2_ModifyVpcAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ModifyVpcAttributeInput{ - EnableDnsSupport: &ec2.AttributeBooleanValue{ - Value: aws.Bool(false), - }, - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.ModifyVpcAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To modify the enableDnsHostnames attribute -// -// This example modifies the enableDnsHostnames attribute. This attribute indicates -// whether instances launched in the VPC get DNS hostnames. If this attribute is true, -// instances in the VPC get DNS hostnames; otherwise, they do not. -func ExampleEC2_ModifyVpcAttribute_shared01() { - svc := ec2.New(session.New()) - input := &ec2.ModifyVpcAttributeInput{ - EnableDnsHostnames: &ec2.AttributeBooleanValue{ - Value: aws.Bool(false), - }, - VpcId: aws.String("vpc-a01106c2"), - } - - result, err := svc.ModifyVpcAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To move an address to EC2-VPC -// -// This example moves the specified Elastic IP address to the EC2-VPC platform. -func ExampleEC2_MoveAddressToVpc_shared00() { - svc := ec2.New(session.New()) - input := &ec2.MoveAddressToVpcInput{ - PublicIp: aws.String("54.123.4.56"), - } - - result, err := svc.MoveAddressToVpc(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To purchase a Scheduled Instance -// -// This example purchases a Scheduled Instance. -func ExampleEC2_PurchaseScheduledInstances_shared00() { - svc := ec2.New(session.New()) - input := &ec2.PurchaseScheduledInstancesInput{ - PurchaseRequests: []*ec2.PurchaseRequest{ - { - InstanceCount: aws.Int64(1), - PurchaseToken: aws.String("eyJ2IjoiMSIsInMiOjEsImMiOi..."), - }, - }, - } - - result, err := svc.PurchaseScheduledInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To release an Elastic IP address for EC2-VPC -// -// This example releases an Elastic IP address for use with instances in a VPC. -func ExampleEC2_ReleaseAddress_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ReleaseAddressInput{ - AllocationId: aws.String("eipalloc-64d5890a"), - } - - result, err := svc.ReleaseAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To release an Elastic IP addresses for EC2-Classic -// -// This example releases an Elastic IP address for use with instances in EC2-Classic. -func ExampleEC2_ReleaseAddress_shared01() { - svc := ec2.New(session.New()) - input := &ec2.ReleaseAddressInput{ - PublicIp: aws.String("198.51.100.0"), - } - - result, err := svc.ReleaseAddress(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To replace the network ACL associated with a subnet -// -// This example associates the specified network ACL with the subnet for the specified -// network ACL association. -func ExampleEC2_ReplaceNetworkAclAssociation_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ReplaceNetworkAclAssociationInput{ - AssociationId: aws.String("aclassoc-e5b95c8c"), - NetworkAclId: aws.String("acl-5fb85d36"), - } - - result, err := svc.ReplaceNetworkAclAssociation(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To replace a network ACL entry -// -// This example replaces an entry for the specified network ACL. The new rule 100 allows -// ingress traffic from 203.0.113.12/24 on UDP port 53 (DNS) into any associated subnet. -func ExampleEC2_ReplaceNetworkAclEntry_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ReplaceNetworkAclEntryInput{ - CidrBlock: aws.String("203.0.113.12/24"), - Egress: aws.Bool(false), - NetworkAclId: aws.String("acl-5fb85d36"), - PortRange: &ec2.PortRange{ - From: aws.Int64(53), - To: aws.Int64(53), - }, - Protocol: aws.String("udp"), - RuleAction: aws.String("allow"), - RuleNumber: aws.Int64(100), - } - - result, err := svc.ReplaceNetworkAclEntry(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To replace a route -// -// This example replaces the specified route in the specified table table. The new route -// matches the specified CIDR and sends the traffic to the specified virtual private -// gateway. -func ExampleEC2_ReplaceRoute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ReplaceRouteInput{ - DestinationCidrBlock: aws.String("10.0.0.0/16"), - GatewayId: aws.String("vgw-9a4cacf3"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.ReplaceRoute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To replace the route table associated with a subnet -// -// This example associates the specified route table with the subnet for the specified -// route table association. -func ExampleEC2_ReplaceRouteTableAssociation_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ReplaceRouteTableAssociationInput{ - AssociationId: aws.String("rtbassoc-781d0d1a"), - RouteTableId: aws.String("rtb-22574640"), - } - - result, err := svc.ReplaceRouteTableAssociation(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To request a Spot fleet in the subnet with the lowest price -// -// This example creates a Spot fleet request with two launch specifications that differ -// only by subnet. The Spot fleet launches the instances in the specified subnet with -// the lowest price. If the instances are launched in a default VPC, they receive a -// public IP address by default. If the instances are launched in a nondefault VPC, -// they do not receive a public IP address by default. Note that you can't specify different -// subnets from the same Availability Zone in a Spot fleet request. -func ExampleEC2_RequestSpotFleet_shared00() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotFleetInput{ - SpotFleetRequestConfig: &ec2.SpotFleetRequestConfigData{ - IamFleetRole: aws.String("arn:aws:iam::123456789012:role/my-spot-fleet-role"), - LaunchSpecifications: []*ec2.SpotFleetLaunchSpecification{ - { - IamInstanceProfile: &ec2.IamInstanceProfileSpecification{ - Arn: aws.String("arn:aws:iam::123456789012:instance-profile/my-iam-role"), - }, - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.medium"), - KeyName: aws.String("my-key-pair"), - SecurityGroups: []*ec2.GroupIdentifier{ - { - GroupId: aws.String("sg-1a2b3c4d"), - }, - }, - SubnetId: aws.String("subnet-1a2b3c4d, subnet-3c4d5e6f"), - }, - }, - SpotPrice: aws.String("0.04"), - TargetCapacity: aws.Int64(2), - }, - } - - result, err := svc.RequestSpotFleet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To request a Spot fleet in the Availability Zone with the lowest price -// -// This example creates a Spot fleet request with two launch specifications that differ -// only by Availability Zone. The Spot fleet launches the instances in the specified -// Availability Zone with the lowest price. If your account supports EC2-VPC only, Amazon -// EC2 launches the Spot instances in the default subnet of the Availability Zone. If -// your account supports EC2-Classic, Amazon EC2 launches the instances in EC2-Classic -// in the Availability Zone. -func ExampleEC2_RequestSpotFleet_shared01() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotFleetInput{ - SpotFleetRequestConfig: &ec2.SpotFleetRequestConfigData{ - IamFleetRole: aws.String("arn:aws:iam::123456789012:role/my-spot-fleet-role"), - LaunchSpecifications: []*ec2.SpotFleetLaunchSpecification{ - { - IamInstanceProfile: &ec2.IamInstanceProfileSpecification{ - Arn: aws.String("arn:aws:iam::123456789012:instance-profile/my-iam-role"), - }, - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.medium"), - KeyName: aws.String("my-key-pair"), - Placement: &ec2.SpotPlacement{ - AvailabilityZone: aws.String("us-west-2a, us-west-2b"), - }, - SecurityGroups: []*ec2.GroupIdentifier{ - { - GroupId: aws.String("sg-1a2b3c4d"), - }, - }, - }, - }, - SpotPrice: aws.String("0.04"), - TargetCapacity: aws.Int64(2), - }, - } - - result, err := svc.RequestSpotFleet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To launch Spot instances in a subnet and assign them public IP addresses -// -// This example assigns public addresses to instances launched in a nondefault VPC. -// Note that when you specify a network interface, you must include the subnet ID and -// security group ID using the network interface. -func ExampleEC2_RequestSpotFleet_shared02() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotFleetInput{ - SpotFleetRequestConfig: &ec2.SpotFleetRequestConfigData{ - IamFleetRole: aws.String("arn:aws:iam::123456789012:role/my-spot-fleet-role"), - LaunchSpecifications: []*ec2.SpotFleetLaunchSpecification{ - { - IamInstanceProfile: &ec2.IamInstanceProfileSpecification{ - Arn: aws.String("arn:aws:iam::880185128111:instance-profile/my-iam-role"), - }, - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.medium"), - KeyName: aws.String("my-key-pair"), - NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{ - { - AssociatePublicIpAddress: aws.Bool(true), - DeviceIndex: aws.Int64(0), - Groups: []*string{ - aws.String("sg-1a2b3c4d"), - }, - SubnetId: aws.String("subnet-1a2b3c4d"), - }, - }, - }, - }, - SpotPrice: aws.String("0.04"), - TargetCapacity: aws.Int64(2), - }, - } - - result, err := svc.RequestSpotFleet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To request a Spot fleet using the diversified allocation strategy -// -// This example creates a Spot fleet request that launches 30 instances using the diversified -// allocation strategy. The launch specifications differ by instance type. The Spot -// fleet distributes the instances across the launch specifications such that there -// are 10 instances of each type. -func ExampleEC2_RequestSpotFleet_shared03() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotFleetInput{ - SpotFleetRequestConfig: &ec2.SpotFleetRequestConfigData{ - AllocationStrategy: aws.String("diversified"), - IamFleetRole: aws.String("arn:aws:iam::123456789012:role/my-spot-fleet-role"), - LaunchSpecifications: []*ec2.SpotFleetLaunchSpecification{ - { - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("c4.2xlarge"), - SubnetId: aws.String("subnet-1a2b3c4d"), - }, - { - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.2xlarge"), - SubnetId: aws.String("subnet-1a2b3c4d"), - }, - { - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("r3.2xlarge"), - SubnetId: aws.String("subnet-1a2b3c4d"), - }, - }, - SpotPrice: aws.String("0.70"), - TargetCapacity: aws.Int64(30), - }, - } - - result, err := svc.RequestSpotFleet(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a one-time Spot Instance request -// -// This example creates a one-time Spot Instance request for five instances in the specified -// Availability Zone. If your account supports EC2-VPC only, Amazon EC2 launches the -// instances in the default subnet of the specified Availability Zone. If your account -// supports EC2-Classic, Amazon EC2 launches the instances in EC2-Classic in the specified -// Availability Zone. -func ExampleEC2_RequestSpotInstances_shared00() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotInstancesInput{ - InstanceCount: aws.Int64(5), - LaunchSpecification: &ec2.RequestSpotLaunchSpecification{ - IamInstanceProfile: &ec2.IamInstanceProfileSpecification{ - Arn: aws.String("arn:aws:iam::123456789012:instance-profile/my-iam-role"), - }, - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.medium"), - KeyName: aws.String("my-key-pair"), - Placement: &ec2.SpotPlacement{ - AvailabilityZone: aws.String("us-west-2a"), - }, - SecurityGroupIds: []*string{ - aws.String("sg-1a2b3c4d"), - }, - }, - SpotPrice: aws.String("0.03"), - Type: aws.String("one-time"), - } - - result, err := svc.RequestSpotInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To create a one-time Spot Instance request -// -// This example command creates a one-time Spot Instance request for five instances -// in the specified subnet. Amazon EC2 launches the instances in the specified subnet. -// If the VPC is a nondefault VPC, the instances do not receive a public IP address -// by default. -func ExampleEC2_RequestSpotInstances_shared01() { - svc := ec2.New(session.New()) - input := &ec2.RequestSpotInstancesInput{ - InstanceCount: aws.Int64(5), - LaunchSpecification: &ec2.RequestSpotLaunchSpecification{ - IamInstanceProfile: &ec2.IamInstanceProfileSpecification{ - Arn: aws.String("arn:aws:iam::123456789012:instance-profile/my-iam-role"), - }, - ImageId: aws.String("ami-1a2b3c4d"), - InstanceType: aws.String("m3.medium"), - SecurityGroupIds: []*string{ - aws.String("sg-1a2b3c4d"), - }, - SubnetId: aws.String("subnet-1a2b3c4d"), - }, - SpotPrice: aws.String("0.050"), - Type: aws.String("one-time"), - } - - result, err := svc.RequestSpotInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To reset a snapshot attribute -// -// This example resets the create volume permissions for snapshot ``snap-1234567890abcdef0``. -// If the command succeeds, no output is returned. -func ExampleEC2_ResetSnapshotAttribute_shared00() { - svc := ec2.New(session.New()) - input := &ec2.ResetSnapshotAttributeInput{ - Attribute: aws.String("createVolumePermission"), - SnapshotId: aws.String("snap-1234567890abcdef0"), - } - - result, err := svc.ResetSnapshotAttribute(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To restore an address to EC2-Classic -// -// This example restores the specified Elastic IP address to the EC2-Classic platform. -func ExampleEC2_RestoreAddressToClassic_shared00() { - svc := ec2.New(session.New()) - input := &ec2.RestoreAddressToClassicInput{ - PublicIp: aws.String("198.51.100.0"), - } - - result, err := svc.RestoreAddressToClassic(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To launch a Scheduled Instance in a VPC -// -// This example launches the specified Scheduled Instance in a VPC. -func ExampleEC2_RunScheduledInstances_shared00() { - svc := ec2.New(session.New()) - input := &ec2.RunScheduledInstancesInput{ - InstanceCount: aws.Int64(1), - LaunchSpecification: &ec2.ScheduledInstancesLaunchSpecification{ - IamInstanceProfile: &ec2.ScheduledInstancesIamInstanceProfile{ - Name: aws.String("my-iam-role"), - }, - ImageId: aws.String("ami-12345678"), - InstanceType: aws.String("c4.large"), - KeyName: aws.String("my-key-pair"), - NetworkInterfaces: []*ec2.ScheduledInstancesNetworkInterface{ - { - AssociatePublicIpAddress: aws.Bool(true), - DeviceIndex: aws.Int64(0), - Groups: []*string{ - aws.String("sg-12345678"), - }, - SubnetId: aws.String("subnet-12345678"), - }, - }, - }, - ScheduledInstanceId: aws.String("sci-1234-1234-1234-1234-123456789012"), - } - - result, err := svc.RunScheduledInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To launch a Scheduled Instance in EC2-Classic -// -// This example launches the specified Scheduled Instance in EC2-Classic. -func ExampleEC2_RunScheduledInstances_shared01() { - svc := ec2.New(session.New()) - input := &ec2.RunScheduledInstancesInput{ - InstanceCount: aws.Int64(1), - LaunchSpecification: &ec2.ScheduledInstancesLaunchSpecification{ - IamInstanceProfile: &ec2.ScheduledInstancesIamInstanceProfile{ - Name: aws.String("my-iam-role"), - }, - ImageId: aws.String("ami-12345678"), - InstanceType: aws.String("c4.large"), - KeyName: aws.String("my-key-pair"), - Placement: &ec2.ScheduledInstancesPlacement{ - AvailabilityZone: aws.String("us-west-2b"), - }, - SecurityGroupIds: []*string{ - aws.String("sg-12345678"), - }, - }, - ScheduledInstanceId: aws.String("sci-1234-1234-1234-1234-123456789012"), - } - - result, err := svc.RunScheduledInstances(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To unassign a secondary private IP address from a network interface -// -// This example unassigns the specified private IP address from the specified network -// interface. -func ExampleEC2_UnassignPrivateIpAddresses_shared00() { - svc := ec2.New(session.New()) - input := &ec2.UnassignPrivateIpAddressesInput{ - NetworkInterfaceId: aws.String("eni-e5aa89a3"), - PrivateIpAddresses: []*string{ - aws.String("10.0.0.82"), - }, - } - - result, err := svc.UnassignPrivateIpAddresses(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/retryer_test.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/retryer_test.go deleted file mode 100644 index 5c955a0d..00000000 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/retryer_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package ec2 - -import ( - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/awstesting/unit" -) - -func TestCustomRetryer(t *testing.T) { - svc := New(unit.Session, &aws.Config{Region: aws.String("us-west-2")}) - if _, ok := svc.Client.Retryer.(retryer); !ok { - t.Error("expected custom retryer, but received otherwise") - } - - req, _ := svc.ModifyNetworkInterfaceAttributeRequest(&ModifyNetworkInterfaceAttributeInput{ - NetworkInterfaceId: aws.String("foo"), - }) - - duration := svc.Client.Retryer.RetryRules(req) - if duration < time.Second*1 || duration > time.Second*2 { - t.Errorf("expected duration to be between 1 and 2, but received %v", duration) - } - - req.RetryCount = 15 - duration = svc.Client.Retryer.RetryRules(req) - if duration < time.Second*5 || duration > time.Second*10 { - t.Errorf("expected duration to be between 1 and 2, but received %v", duration) - } - - svc = New(unit.Session, &aws.Config{Region: aws.String("us-west-2"), Retryer: client.DefaultRetryer{}}) - if _, ok := svc.Client.Retryer.(client.DefaultRetryer); !ok { - t.Error("expected default retryer, but received otherwise") - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/service.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/service.go index 199c64c8..6acbc43f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/service.go @@ -29,9 +29,9 @@ var initRequest func(*request.Request) // Service information constants const ( - ServiceName = "ec2" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. - ServiceID = "EC2" // ServiceID is a unique identifer of a specific service + ServiceName = "ec2" // Name of service. + EndpointsID = ServiceName // ID to lookup a service endpoint with. + ServiceID = "EC2" // ServiceID is a unique identifer of a specific service. ) // New creates a new instance of the EC2 client with a session. diff --git a/vendor/github.com/aws/aws-sdk-go/service/generate.go b/vendor/github.com/aws/aws-sdk-go/service/generate.go deleted file mode 100644 index 3ffc9fcc..00000000 --- a/vendor/github.com/aws/aws-sdk-go/service/generate.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package service contains automatically generated AWS clients. -package service - -//go:generate go run -tags codegen ../private/model/cli/gen-api/main.go -path=../service ../models/apis/*/*/api-2.json -//go:generate gofmt -s -w ../service diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations_test.go b/vendor/github.com/aws/aws-sdk-go/service/sts/customizations_test.go deleted file mode 100644 index 18972b1f..00000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package sts_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/awstesting/unit" - "github.com/aws/aws-sdk-go/service/sts" -) - -var svc = sts.New(unit.Session, &aws.Config{ - Region: aws.String("mock-region"), -}) - -func TestUnsignedRequest_AssumeRoleWithSAML(t *testing.T) { - req, _ := svc.AssumeRoleWithSAMLRequest(&sts.AssumeRoleWithSAMLInput{ - PrincipalArn: aws.String("ARN01234567890123456789"), - RoleArn: aws.String("ARN01234567890123456789"), - SAMLAssertion: aws.String("ASSERT"), - }) - - err := req.Sign() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "", req.HTTPRequest.Header.Get("Authorization"); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} - -func TestUnsignedRequest_AssumeRoleWithWebIdentity(t *testing.T) { - req, _ := svc.AssumeRoleWithWebIdentityRequest(&sts.AssumeRoleWithWebIdentityInput{ - RoleArn: aws.String("ARN01234567890123456789"), - RoleSessionName: aws.String("SESSION"), - WebIdentityToken: aws.String("TOKEN"), - }) - - err := req.Sign() - if err != nil { - t.Errorf("expect no error, got %v", err) - } - if e, a := "", req.HTTPRequest.Header.Get("Authorization"); e != a { - t.Errorf("expect %v, got %v", e, a) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/examples_test.go b/vendor/github.com/aws/aws-sdk-go/service/sts/examples_test.go deleted file mode 100644 index d61a9932..00000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/examples_test.go +++ /dev/null @@ -1,282 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts_test - -import ( - "fmt" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sts" -) - -var _ time.Duration -var _ strings.Reader -var _ aws.Config - -func parseTime(layout, value string) *time.Time { - t, err := time.Parse(layout, value) - if err != nil { - panic(err) - } - return &t -} - -// To assume a role -// - -func ExampleSTS_AssumeRole_shared00() { - svc := sts.New(session.New()) - input := &sts.AssumeRoleInput{ - DurationSeconds: aws.Int64(3600), - ExternalId: aws.String("123ABC"), - Policy: aws.String("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}"), - RoleArn: aws.String("arn:aws:iam::123456789012:role/demo"), - RoleSessionName: aws.String("Bob"), - } - - result, err := svc.AssumeRole(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case sts.ErrCodeMalformedPolicyDocumentException: - fmt.Println(sts.ErrCodeMalformedPolicyDocumentException, aerr.Error()) - case sts.ErrCodePackedPolicyTooLargeException: - fmt.Println(sts.ErrCodePackedPolicyTooLargeException, aerr.Error()) - case sts.ErrCodeRegionDisabledException: - fmt.Println(sts.ErrCodeRegionDisabledException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To assume a role as an OpenID Connect-federated user -// - -func ExampleSTS_AssumeRoleWithWebIdentity_shared00() { - svc := sts.New(session.New()) - input := &sts.AssumeRoleWithWebIdentityInput{ - DurationSeconds: aws.Int64(3600), - ProviderId: aws.String("www.amazon.com"), - RoleArn: aws.String("arn:aws:iam::123456789012:role/FederatedWebIdentityRole"), - RoleSessionName: aws.String("app1"), - WebIdentityToken: aws.String("Atza%7CIQEBLjAsAhRFiXuWpUXuRvQ9PZL3GMFcYevydwIUFAHZwXZXXXXXXXXJnrulxKDHwy87oGKPznh0D6bEQZTSCzyoCtL_8S07pLpr0zMbn6w1lfVZKNTBdDansFBmtGnIsIapjI6xKR02Yc_2bQ8LZbUXSGm6Ry6_BG7PrtLZtj_dfCTj92xNGed-CrKqjG7nPBjNIL016GGvuS5gSvPRUxWES3VYfm1wl7WTI7jn-Pcb6M-buCgHhFOzTQxod27L9CqnOLio7N3gZAGpsp6n1-AJBOCJckcyXe2c6uD0srOJeZlKUm2eTDVMf8IehDVI0r1QOnTV6KzzAI3OY87Vd_cVMQ"), - } - - result, err := svc.AssumeRoleWithWebIdentity(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case sts.ErrCodeMalformedPolicyDocumentException: - fmt.Println(sts.ErrCodeMalformedPolicyDocumentException, aerr.Error()) - case sts.ErrCodePackedPolicyTooLargeException: - fmt.Println(sts.ErrCodePackedPolicyTooLargeException, aerr.Error()) - case sts.ErrCodeIDPRejectedClaimException: - fmt.Println(sts.ErrCodeIDPRejectedClaimException, aerr.Error()) - case sts.ErrCodeIDPCommunicationErrorException: - fmt.Println(sts.ErrCodeIDPCommunicationErrorException, aerr.Error()) - case sts.ErrCodeInvalidIdentityTokenException: - fmt.Println(sts.ErrCodeInvalidIdentityTokenException, aerr.Error()) - case sts.ErrCodeExpiredTokenException: - fmt.Println(sts.ErrCodeExpiredTokenException, aerr.Error()) - case sts.ErrCodeRegionDisabledException: - fmt.Println(sts.ErrCodeRegionDisabledException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To decode information about an authorization status of a request -// - -func ExampleSTS_DecodeAuthorizationMessage_shared00() { - svc := sts.New(session.New()) - input := &sts.DecodeAuthorizationMessageInput{ - EncodedMessage: aws.String(""), - } - - result, err := svc.DecodeAuthorizationMessage(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case sts.ErrCodeInvalidAuthorizationMessageException: - fmt.Println(sts.ErrCodeInvalidAuthorizationMessageException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To get details about a calling IAM user -// -// This example shows a request and response made with the credentials for a user named -// Alice in the AWS account 123456789012. -func ExampleSTS_GetCallerIdentity_shared00() { - svc := sts.New(session.New()) - input := &sts.GetCallerIdentityInput{} - - result, err := svc.GetCallerIdentity(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To get details about a calling user federated with AssumeRole -// -// This example shows a request and response made with temporary credentials created -// by AssumeRole. The name of the assumed role is my-role-name, and the RoleSessionName -// is set to my-role-session-name. -func ExampleSTS_GetCallerIdentity_shared01() { - svc := sts.New(session.New()) - input := &sts.GetCallerIdentityInput{} - - result, err := svc.GetCallerIdentity(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To get details about a calling user federated with GetFederationToken -// -// This example shows a request and response made with temporary credentials created -// by using GetFederationToken. The Name parameter is set to my-federated-user-name. -func ExampleSTS_GetCallerIdentity_shared02() { - svc := sts.New(session.New()) - input := &sts.GetCallerIdentityInput{} - - result, err := svc.GetCallerIdentity(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To get temporary credentials for a role by using GetFederationToken -// - -func ExampleSTS_GetFederationToken_shared00() { - svc := sts.New(session.New()) - input := &sts.GetFederationTokenInput{ - DurationSeconds: aws.Int64(3600), - Name: aws.String("Bob"), - Policy: aws.String("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}"), - } - - result, err := svc.GetFederationToken(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case sts.ErrCodeMalformedPolicyDocumentException: - fmt.Println(sts.ErrCodeMalformedPolicyDocumentException, aerr.Error()) - case sts.ErrCodePackedPolicyTooLargeException: - fmt.Println(sts.ErrCodePackedPolicyTooLargeException, aerr.Error()) - case sts.ErrCodeRegionDisabledException: - fmt.Println(sts.ErrCodeRegionDisabledException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} - -// To get temporary credentials for an IAM user or an AWS account -// - -func ExampleSTS_GetSessionToken_shared00() { - svc := sts.New(session.New()) - input := &sts.GetSessionTokenInput{ - DurationSeconds: aws.Int64(3600), - SerialNumber: aws.String("YourMFASerialNumber"), - TokenCode: aws.String("123456"), - } - - result, err := svc.GetSessionToken(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case sts.ErrCodeRegionDisabledException: - fmt.Println(sts.ErrCodeRegionDisabledException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - fmt.Println(result) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go index 15ab7b46..185c914d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go @@ -29,9 +29,9 @@ var initRequest func(*request.Request) // Service information constants const ( - ServiceName = "sts" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. - ServiceID = "STS" // ServiceID is a unique identifer of a specific service + ServiceName = "sts" // Name of service. + EndpointsID = ServiceName // ID to lookup a service endpoint with. + ServiceID = "STS" // ServiceID is a unique identifer of a specific service. ) // New creates a new instance of the STS client with a session. diff --git a/vendor/github.com/aws/aws-xray-sdk-go/CONTRIBUTORS.md b/vendor/github.com/aws/aws-xray-sdk-go/CONTRIBUTORS.md new file mode 100644 index 00000000..39f91bf0 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/CONTRIBUTORS.md @@ -0,0 +1,8 @@ +# Contributors +The following people have contributed to the AWS X-Ray SDK for Go's design and/or implementation (alphabetical): +* Anssi Alaranta +* Bilal Khan +* James Bowman +* Lulu Zhao +* Raymond Lin +* Rohit Banga diff --git a/vendor/github.com/aws/aws-xray-sdk-go/LICENSE b/vendor/github.com/aws/aws-xray-sdk-go/LICENSE new file mode 100644 index 00000000..8dada3ed --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/aws/aws-xray-sdk-go/NOTICE.txt b/vendor/github.com/aws/aws-xray-sdk-go/NOTICE.txt new file mode 100644 index 00000000..3e0ee43d --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/NOTICE.txt @@ -0,0 +1,2 @@ +AWS X-Ray SDK for Go +Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/vendor/github.com/aws/aws-xray-sdk-go/header/header.go b/vendor/github.com/aws/aws-xray-sdk-go/header/header.go new file mode 100644 index 00000000..7d5f12b5 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/header/header.go @@ -0,0 +1,134 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package header + +import ( + "bytes" + "strings" +) + +const ( + // RootPrefix is the prefix for + // Root attribute in X-Amzn-Trace-Id. + RootPrefix = "Root=" + + // ParentPrefix is the prefix for + // Parent attribute in X-Amzn-Trace-Id. + ParentPrefix = "Parent=" + + // SampledPrefix is the prefix for + // Sampled attribute in X-Amzn-Trace-Id. + SampledPrefix = "Sampled=" + + // SelfPrefix is the prefix for + // Self attribute in X-Amzn-Trace-Id. + SelfPrefix = "Self=" +) + +// SamplingDecision is a string representation of +// whether or not the current segment has been sampled. +type SamplingDecision string + +const ( + // Sampled indicates the current segment has been + // sampled and will be sent to the X-Ray daemon. + Sampled SamplingDecision = "Sampled=1" + + // NotSampled indicates the current segment has + // not been sampled. + NotSampled SamplingDecision = "Sampled=0" + + // Requested indicates sampling decision will be + // made by the downstream service and propagated + // back upstream in the response. + Requested SamplingDecision = "Sampled=?" + + // Unknown indicates no sampling decision will be made. + Unknown SamplingDecision = "" +) + +func samplingDecision(s string) SamplingDecision { + if s == string(Sampled) { + return Sampled + } else if s == string(NotSampled) { + return NotSampled + } else if s == string(Requested) { + return Requested + } + return Unknown +} + +// Header is the value of X-Amzn-Trace-Id. +type Header struct { + TraceID string + ParentID string + SamplingDecision SamplingDecision + + AdditionalData map[string]string +} + +// FromString gets individual value for each item in Header struct. +func FromString(s string) *Header { + ret := &Header{ + SamplingDecision: Unknown, + AdditionalData: make(map[string]string), + } + parts := strings.Split(s, ";") + for i := range parts { + p := strings.TrimSpace(parts[i]) + value, valid := valueFromKeyValuePair(p) + if valid { + if strings.HasPrefix(p, RootPrefix) { + ret.TraceID = value + } else if strings.HasPrefix(p, ParentPrefix) { + ret.ParentID = value + } else if strings.HasPrefix(p, SampledPrefix) { + ret.SamplingDecision = samplingDecision(p) + } else if !strings.HasPrefix(p, SelfPrefix) { + key, valid := keyFromKeyValuePair(p) + if valid { + ret.AdditionalData[key] = value + } + } + } + } + return ret +} + +// String returns a string representation for header. +func (h Header) String() string { + var p [][]byte + if h.TraceID != "" { + p = append(p, []byte(RootPrefix+h.TraceID)) + } + if h.ParentID != "" { + p = append(p, []byte(ParentPrefix+h.ParentID)) + } + p = append(p, []byte(h.SamplingDecision)) + for key := range h.AdditionalData { + p = append(p, []byte(key+"="+h.AdditionalData[key])) + } + return string(bytes.Join(p, []byte(";"))) +} + +func keyFromKeyValuePair(s string) (string, bool) { + e := strings.Index(s, "=") + if -1 != e { + return s[:e], true + } + return "", false +} + +func valueFromKeyValuePair(s string) (string, bool) { + e := strings.Index(s, "=") + if -1 != e { + return s[e+1:], true + } + return "", false +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/internal/plugins/plugin.go b/vendor/github.com/aws/aws-xray-sdk-go/internal/plugins/plugin.go new file mode 100644 index 00000000..636635d0 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/internal/plugins/plugin.go @@ -0,0 +1,56 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package plugins + +const ( + EBServiceName = "elastic_beanstalk" + EC2ServiceName = "ec2" + ECSServiceName = "ecs" +) + +// InstancePluginMetadata points to the PluginMetadata struct. +var InstancePluginMetadata = &PluginMetadata{} + +// PluginMetadata struct contains items to record information +// about the AWS infrastructure hosting the traced application. +type PluginMetadata struct { + + // EC2Metadata records the ec2 instance ID and availability zone. + EC2Metadata *EC2Metadata + + // BeanstalkMetadata records the Elastic Beanstalk + // environment name, version label, and deployment ID. + BeanstalkMetadata *BeanstalkMetadata + + // ECSMetadata records the ECS container ID. + ECSMetadata *ECSMetadata + + // Origin records original service of the segment. + Origin string +} + +// EC2Metadata provides the shape for unmarshalling EC2 metadata. +type EC2Metadata struct { + InstanceID string `json:"instance_id"` + AvailabilityZone string `json:"availability_zone"` +} + +// ECSMetadata provides the shape for unmarshalling +// ECS metadata. +type ECSMetadata struct { + ContainerName string `json:"container"` +} + +// BeanstalkMetadata provides the shape for unmarshalling +// Elastic Beanstalk environment metadata. +type BeanstalkMetadata struct { + Environment string `json:"environment_name"` + VersionLabel string `json:"version_label"` + DeploymentID int `json:"deployment_id"` +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/pattern/search_pattern.go b/vendor/github.com/aws/aws-xray-sdk-go/pattern/search_pattern.go new file mode 100644 index 00000000..aab1aa9d --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/pattern/search_pattern.go @@ -0,0 +1,97 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +// Package pattern provides a basic pattern matching utility. +// Patterns may contain fixed text, and/or special characters (`*`, `?`). +// `*` represents 0 or more wildcard characters. `?` represents a single wildcard character. +package pattern + +import "strings" + +// WildcardMatchCaseInsensitive returns true if text matches pattern (case-insensitive); returns false otherwise. +func WildcardMatchCaseInsensitive(pattern string, text string) bool { + return WildcardMatch(pattern, text, true) +} + +// WildcardMatch returns true if text matches pattern at the given case-sensitivity; returns false otherwise. +func WildcardMatch(pattern string, text string, caseInsensitive bool) bool { + patternLen := len(pattern) + textLen := len(text) + if 0 == patternLen { + return 0 == textLen + } + + if isWildcardGlob(pattern) { + return true + } + + if caseInsensitive { + pattern = strings.ToLower(pattern) + text = strings.ToLower(text) + } + + indexOfGlob := strings.Index(pattern, "*") + if -1 == indexOfGlob || patternLen-1 == indexOfGlob { + return simpleWildcardMatch(pattern, text) + } + + res := make([]bool, textLen+1) + res[0] = true + for j := 0; j < patternLen; j++ { + p := pattern[j] + if '*' != p { + for i := textLen - 1; i >= 0; i-- { + t := text[i] + res[i+1] = res[i] && ('?' == p || t == p) + } + } else { + i := 0 + for i <= textLen && !res[i] { + i++ + } + for i <= textLen { + res[i] = true + i++ + } + } + res[0] = res[0] && '*' == p + } + return res[textLen] + +} + +func simpleWildcardMatch(pattern string, text string) bool { + j := 0 + patternLen := len(pattern) + textLen := len(text) + for i := 0; i < patternLen; i++ { + p := pattern[i] + if '*' == p { + return true + } else if '?' == p { + if textLen == j { + return false + } + j++ + } else { + if j >= textLen { + return false + } + t := text[j] + if p != t { + return false + } + j++ + } + } + return j == textLen +} + +func isWildcardGlob(pattern string) bool { + return pattern == "*" +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/resources/bindata.go b/vendor/github.com/aws/aws-xray-sdk-go/resources/bindata.go new file mode 100644 index 00000000..3b98966a --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/resources/bindata.go @@ -0,0 +1,283 @@ +// Code generated by go-bindata. +// sources: +// resources/AWSWhitelist.json +// resources/DefaultSamplingRules.json +// resources/ExampleSamplingRules.json +// DO NOT EDIT! + +package resources + +import ( + "bytes" + "compress/gzip" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strings" + "time" +) + +func bindataRead(data []byte, name string) ([]byte, error) { + gz, err := gzip.NewReader(bytes.NewBuffer(data)) + if err != nil { + return nil, fmt.Errorf("Read %q: %v", name, err) + } + + var buf bytes.Buffer + _, err = io.Copy(&buf, gz) + clErr := gz.Close() + + if err != nil { + return nil, fmt.Errorf("Read %q: %v", name, err) + } + if clErr != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +type asset struct { + bytes []byte + info os.FileInfo +} + +type bindataFileInfo struct { + name string + size int64 + mode os.FileMode + modTime time.Time +} + +func (fi bindataFileInfo) Name() string { + return fi.name +} +func (fi bindataFileInfo) Size() int64 { + return fi.size +} +func (fi bindataFileInfo) Mode() os.FileMode { + return fi.mode +} +func (fi bindataFileInfo) ModTime() time.Time { + return fi.modTime +} +func (fi bindataFileInfo) IsDir() bool { + return false +} +func (fi bindataFileInfo) Sys() interface{} { + return nil +} + +var _resourcesAwswhitelistJson = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xec\x59\xcd\x72\xe2\x38\x10\xbe\xf3\x14\x2e\x9f\x73\xdb\x5b\x6e\x0c\x49\x28\x6a\xc9\x84\x04\x66\x73\xd8\xda\xa2\x64\xa9\x71\x34\xb1\x25\x47\x3f\x0c\xd4\x56\xde\x7d\x4b\x92\x21\x60\x8c\x2d\xec\xc0\x90\x64\x0f\x53\x13\xac\xb6\xfa\xeb\xaf\x7f\xd4\x2d\xff\xdb\x09\x82\x50\x82\x98\x53\x0c\x32\xbc\x0c\xcc\xef\x20\x08\xc9\x92\xa1\x94\x93\x68\xfd\x24\x08\x42\x9e\x81\x40\x8a\x72\x26\x37\x9e\x06\x41\xf8\x0d\x29\xfc\xd4\x07\x35\x50\x90\x6e\xad\x04\x41\x28\xe0\x45\x83\x54\x53\x02\x12\x0b\x9a\x29\x2e\x64\x41\x24\x08\xc2\x07\x27\x64\xde\xdf\x5d\x0d\x82\x30\x45\x59\x78\x19\x28\xa1\xe1\xa2\xb8\x14\x83\x9a\x3e\xc3\x52\xee\x5b\x17\xc0\x50\x0a\x53\xc5\xc3\xcb\x20\x54\x28\x4a\x60\x6a\x1e\xc8\x70\x4b\xf0\x75\xe3\xd7\xeb\xc5\x36\x7e\x99\x71\x26\x61\x9a\x21\x81\x52\x50\x60\xf1\xff\xbd\x8d\xbf\xc7\x99\xd4\x29\x90\x1e\xca\x10\xa6\x6a\xb9\xb9\xf9\x3f\x9d\x92\x8d\x1d\x65\x8f\x82\x2a\xf8\x9f\xb4\x15\x69\xdb\x30\x42\x63\x58\x8f\x27\x09\x60\x13\x72\xb7\xa0\x04\xc5\xb2\x9e\xd9\x9e\x00\xa4\x60\x62\x40\xef\xa3\xb5\x0a\x55\x3f\xe1\x11\x4a\xc6\x80\x39\x23\x48\x2c\x07\x8c\xc0\x02\x64\x11\xdb\x90\xe3\x7a\xa1\x91\xe0\x73\x2a\x29\x67\x40\x26\x4f\x82\xeb\xf8\x29\xd3\xaa\x28\x64\x81\x7e\x47\x29\xd4\x5b\x76\x05\x09\x54\xc7\x4b\x95\x61\xe5\x8a\xce\xc6\x6d\xce\xb8\xc6\x6e\x3b\x88\x46\x93\x54\xd1\x49\x74\xd5\x14\xc5\x3a\x9e\xa9\x54\xc0\xd4\x03\x20\x52\x12\x5b\x3f\x1d\xc3\xd7\x8b\x4c\x80\x34\x61\xe6\x17\x5a\xa7\xa8\x6e\x43\x2a\x95\xd5\x5e\x2c\x4c\x5e\x96\x5f\x2f\x70\xa2\x25\x9d\xc3\x58\x21\xa1\xde\xac\x28\xe6\x20\x4d\xa9\xf2\x30\xad\xb2\x88\xae\x77\x2f\x2d\xa1\x09\x95\xaa\xaa\x86\x62\xae\xd9\x5e\x81\x92\x22\xea\xe4\xf7\x17\xd1\x52\x32\x47\xba\x71\x0c\x9d\x79\xce\xdf\x6b\x10\xcb\x26\x76\x75\x95\x12\x34\xd2\x0a\xe4\x84\xf7\x61\xa7\xa6\x56\xa7\x8e\xad\xd6\xfb\x03\xaa\x41\xa2\x8d\x31\x62\x76\xd7\x1b\x2e\x7e\x21\xb1\xa3\x71\x0c\x86\x99\xf3\x49\x4f\x83\xf7\x33\xd0\x0e\x71\x0a\x6c\xe7\xd5\x3a\xb6\x8b\x0b\x5c\x99\xa3\xdc\x6e\x25\x8f\x9c\x27\x3d\x9b\xff\x25\xd1\xc3\x80\xf4\x8a\xb5\xa1\xdc\x77\x3f\x32\x82\x3e\x6d\x13\xe0\x8c\x6b\x7c\x30\xaf\xe3\xf3\x0a\x66\x94\x51\x37\xa9\x5c\xd4\xf7\x77\x4e\xed\x71\xfa\xb7\xce\xe6\xff\xb9\xad\xa1\x7c\x91\x3e\x73\x55\x97\x90\x11\x88\x94\xba\xe8\x6f\x40\xc8\x10\x45\x90\x14\x11\xdf\x6b\xd0\xf0\x43\x24\x1e\xad\xf4\x13\x62\x31\xdc\x82\x94\x28\x86\xbf\xa8\xa4\x11\x4d\x8c\xb3\x1b\x20\x59\x2b\x2d\x80\x79\xdb\x75\x42\x53\xe0\xda\x23\x03\xf6\xa0\xb2\x13\x55\x2b\x68\xed\x52\xe2\x06\xd1\x04\x88\xef\x7c\x62\x95\xb6\xab\xc1\xa5\x7e\x3d\x64\x92\xc8\x29\x7c\x37\xce\xea\x55\x7d\x14\x1f\x39\xd0\x8d\x7d\xe4\xcf\x4e\x1f\x94\x15\xde\xf0\xea\xef\x63\x67\x03\x84\x37\x70\xa3\xb5\x29\xe2\xb2\xd3\xd8\x2e\xdc\xfd\x62\x20\xba\x8f\xe3\x2e\xb6\x0d\xf3\x80\xb4\x34\xcc\xdf\x1f\x66\x70\xb9\x02\x44\x86\xa0\x14\x88\x31\xd7\x02\xbb\x30\xf8\x9d\x7e\x59\x6d\xe3\xe1\x16\x83\xbf\x25\x5e\xe3\x95\x91\x80\x19\x5d\xb4\x9d\xad\xde\x70\x1f\x75\xb4\x7a\x31\x6a\x9a\x8e\x56\x22\x3e\x45\x9a\x3f\x00\x06\x3a\x6f\x53\x70\xd7\xb9\xe9\x66\xd5\x42\xd6\xdc\xa2\xc5\x77\x9d\x46\x20\xee\x66\xb9\x8e\x5d\x11\xf7\xbc\x7a\x1f\xff\x53\xba\x20\xf0\x88\xa8\x32\x4b\xae\xaf\xf2\x69\xa3\x2b\x23\x67\x6d\xc4\x51\x03\x27\x75\x5a\x9a\x85\xce\x03\xa4\x7c\x0e\xed\xda\x33\xff\x00\x1a\x03\x23\x2d\xa2\xe7\x0a\x12\xb4\x5c\xf9\xc6\xa7\x1d\xbc\x28\xd3\xe0\xe3\xb2\xbd\x07\x99\x15\x7a\xaf\x2b\xe9\x95\xe7\xd0\x4a\xdb\x11\xae\xa7\x73\x83\x06\x1e\xed\xc2\x86\x77\x8e\xda\xe1\x78\xb8\xe1\x9a\x29\x41\xcf\x25\x71\x1a\x64\x7e\xde\xa1\x1d\x15\xfe\xcc\xea\x28\x45\x5f\x1c\xcd\x35\xc6\x20\xe5\x4c\x17\x9b\x9c\x77\x46\x24\xd7\x7a\x9a\x15\xa3\xf1\xc9\xda\x48\x8f\x10\x3c\x4d\x09\xf0\x4f\xfd\x4e\xf1\xaf\xed\x59\x3c\x41\x69\x44\x90\xcf\x38\x3e\x60\x73\xfe\xdc\xa8\xfe\xde\x68\x66\x2f\x42\xca\x3a\x5e\xb3\x2b\xb6\xea\x26\xcb\x6c\xf7\x72\x8c\xc7\x65\x8f\xef\x35\x4a\xe8\x8c\x82\x68\x3b\x10\xe5\xc0\xae\x85\xe0\x62\xe7\x62\x4a\x21\xa5\x65\x8f\x13\x8f\x89\xd2\x71\xd3\x95\x4b\x86\x5b\x13\xd4\xce\x24\x87\xfa\xa0\xdb\x98\x3f\x7c\xbc\xef\xe6\xf6\x6f\x1a\x3f\x83\x6a\xf4\xbd\xb6\xf4\x55\xbb\x32\x47\x89\xed\x40\xeb\xa3\x3e\xb2\x7b\xd8\x90\x3f\xb4\x46\xb8\x99\xf6\xe3\xe2\xef\x83\xba\x8b\x7e\x02\xde\x0b\xbe\x2a\x28\xfe\x84\x65\xcb\xaa\x76\x16\xde\xfb\x1a\x04\x1c\x9e\xf3\xf9\x25\x13\x12\xcf\x85\x8a\x58\xcb\xe5\xde\x83\xf2\xac\xb9\xa8\x04\xe7\xcc\x3b\x72\x0f\x45\x9c\x92\x29\xb7\x2c\x36\xeb\x5a\x86\x54\x2a\xc7\x64\x89\x17\x7c\x2c\x2d\x7f\xf9\x9d\x2d\xcd\xfd\xd4\xd8\xc2\x4f\x1b\x67\x3d\xce\x94\xfd\x66\x76\x54\xfa\xdb\x04\xd8\x48\x7f\xe5\x23\x63\xa4\xf3\xec\x1a\xf2\x38\xa6\x2c\x3e\xf3\x08\xac\xb6\x61\xc4\x13\x8a\x1b\x7d\x79\xca\xdf\xfc\x1c\xae\x9c\xa0\x8f\xe5\xca\xed\x7e\xbb\x63\xfe\xbd\x76\xfe\x0b\x00\x00\xff\xff\x43\xa8\x98\xe0\x72\x2a\x00\x00") + +func resourcesAwswhitelistJsonBytes() ([]byte, error) { + return bindataRead( + _resourcesAwswhitelistJson, + "resources/AWSWhitelist.json", + ) +} + +func resourcesAwswhitelistJson() (*asset, error) { + bytes, err := resourcesAwswhitelistJsonBytes() + if err != nil { + return nil, err + } + + info := bindataFileInfo{name: "resources/AWSWhitelist.json", size: 10866, mode: os.FileMode(420), modTime: time.Unix(1504302313, 0)} + a := &asset{bytes: bytes, info: info} + return a, nil +} + +var _resourcesDefaultsamplingrulesJson = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xaa\xe6\x52\x50\x50\x2a\x4b\x2d\x2a\xce\xcc\xcf\x53\xb2\x52\x30\xd4\x01\xf1\x53\x52\xd3\x12\x4b\x73\x4a\x94\xac\x14\x40\xd2\x0a\x0a\x4a\x69\x99\x15\xa9\x29\xf1\x25\x89\x45\xe9\xa9\x25\x30\x55\x0a\x0a\x4a\x45\x89\x25\xa9\x4a\x56\x0a\x06\x7a\x06\xa6\x5c\x0a\x0a\xb5\x60\xbd\x45\xa5\x39\xa9\xc5\x4a\x56\x0a\xd1\x5c\x0a\x0a\xb1\x5c\xb5\x5c\x80\x00\x00\x00\xff\xff\xc9\x98\x17\x60\x61\x00\x00\x00") + +func resourcesDefaultsamplingrulesJsonBytes() ([]byte, error) { + return bindataRead( + _resourcesDefaultsamplingrulesJson, + "resources/DefaultSamplingRules.json", + ) +} + +func resourcesDefaultsamplingrulesJson() (*asset, error) { + bytes, err := resourcesDefaultsamplingrulesJsonBytes() + if err != nil { + return nil, err + } + + info := bindataFileInfo{name: "resources/DefaultSamplingRules.json", size: 97, mode: os.FileMode(420), modTime: time.Unix(1504288305, 0)} + a := &asset{bytes: bytes, info: info} + return a, nil +} + +var _resourcesExamplesamplingrulesJson = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x64\x90\xcd\x8e\xd4\x30\x10\x84\xef\x79\x8a\x92\x2f\x0b\xab\x6c\x98\x3d\x70\xc9\x8d\x03\x2f\x80\xb8\x21\x14\xf5\xc4\x9d\x49\x0b\xc7\xce\xda\xed\xd9\x45\x68\xde\x1d\xd9\xd9\x61\x7e\x38\xba\xab\xda\x5d\x5f\xfd\x69\x00\x73\xe4\x98\x24\x78\xd3\xe3\xb9\x2d\x6f\xcb\x13\x65\xa7\xa6\x47\x91\xeb\x20\x8d\x51\x56\xdd\x4c\xe6\x0b\xde\x1d\x88\xd9\x71\x0b\x4a\x10\x3f\xba\x6c\xd9\x62\xcf\x2e\xbc\xb6\x90\x84\xc8\x2f\x59\x22\x5b\x88\x07\xf9\xdf\x48\xb4\xac\x4e\xfc\xa1\x2e\x25\x4c\xe2\xb8\xc3\x87\xc4\xf1\x28\x23\x0f\x9e\x16\x6e\x31\xab\xae\xc3\xc2\x3a\x07\xdb\x82\xbc\x45\x8e\x6e\x58\x49\x67\x50\x64\x4c\xf2\xc6\x16\x1a\xf0\xf0\xf8\x80\x29\x44\xe8\x5c\xee\x64\xc7\xdd\x47\xd3\x6e\x51\xab\x67\x50\x8a\x07\xd6\x33\x10\x60\x22\x29\x9b\x1e\xbb\x6e\xf7\xb9\x01\x4e\x15\xb3\xe6\x30\x3d\x7e\x54\xcb\x86\xfa\x3f\xec\xd7\xb7\x92\x9b\x51\x52\x3c\xed\x29\xb1\xad\x17\x37\xd0\x0e\xdf\x2a\x4c\x49\xc7\x47\x72\x99\x74\x03\x16\xfb\x14\xa2\xe5\xd8\x42\x67\xbe\xa9\x0b\xaf\xe2\x1c\xf6\x8c\x5c\xbe\x92\x09\x3e\x78\xc6\x42\x3a\xce\xd5\x2b\x7e\x0c\x4b\xad\x89\x5f\x32\x27\xed\xf0\xbd\x50\x4a\x02\x6d\xfb\x1b\x38\x63\x9c\x79\xfc\x15\xb2\x62\xa5\x03\x77\xef\xfc\x80\x11\x5b\x62\x3f\x5f\x06\xd7\x15\x17\xe9\xf1\x22\x5d\xf5\x7d\xa7\x9c\x8b\x2f\xe3\x4f\xe7\x53\x17\xf9\xbe\xe6\xdd\x3f\xe5\xb6\x69\xe0\xd4\x00\x3f\x9b\xd3\xdf\x00\x00\x00\xff\xff\xc1\xd0\x29\x3f\x69\x02\x00\x00") + +func resourcesExamplesamplingrulesJsonBytes() ([]byte, error) { + return bindataRead( + _resourcesExamplesamplingrulesJson, + "resources/ExampleSamplingRules.json", + ) +} + +func resourcesExamplesamplingrulesJson() (*asset, error) { + bytes, err := resourcesExamplesamplingrulesJsonBytes() + if err != nil { + return nil, err + } + + info := bindataFileInfo{name: "resources/ExampleSamplingRules.json", size: 617, mode: os.FileMode(420), modTime: time.Unix(1504288305, 0)} + a := &asset{bytes: bytes, info: info} + return a, nil +} + +// Asset loads and returns the asset for the given name. +// It returns an error if the asset could not be found or +// could not be loaded. +func Asset(name string) ([]byte, error) { + cannonicalName := strings.Replace(name, "\\", "/", -1) + if f, ok := _bindata[cannonicalName]; ok { + a, err := f() + if err != nil { + return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) + } + return a.bytes, nil + } + return nil, fmt.Errorf("Asset %s not found", name) +} + +// MustAsset is like Asset but panics when Asset would return an error. +// It simplifies safe initialization of global variables. +func MustAsset(name string) []byte { + a, err := Asset(name) + if err != nil { + panic("asset: Asset(" + name + "): " + err.Error()) + } + + return a +} + +// AssetInfo loads and returns the asset info for the given name. +// It returns an error if the asset could not be found or +// could not be loaded. +func AssetInfo(name string) (os.FileInfo, error) { + cannonicalName := strings.Replace(name, "\\", "/", -1) + if f, ok := _bindata[cannonicalName]; ok { + a, err := f() + if err != nil { + return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) + } + return a.info, nil + } + return nil, fmt.Errorf("AssetInfo %s not found", name) +} + +// AssetNames returns the names of the assets. +func AssetNames() []string { + names := make([]string, 0, len(_bindata)) + for name := range _bindata { + names = append(names, name) + } + return names +} + +// _bindata is a table, holding each asset generator, mapped to its name. +var _bindata = map[string]func() (*asset, error){ + "resources/AWSWhitelist.json": resourcesAwswhitelistJson, + "resources/DefaultSamplingRules.json": resourcesDefaultsamplingrulesJson, + "resources/ExampleSamplingRules.json": resourcesExamplesamplingrulesJson, +} + +// AssetDir returns the file names below a certain +// directory embedded in the file by go-bindata. +// For example if you run go-bindata on data/... and data contains the +// following hierarchy: +// data/ +// foo.txt +// img/ +// a.png +// b.png +// then AssetDir("data") would return []string{"foo.txt", "img"} +// AssetDir("data/img") would return []string{"a.png", "b.png"} +// AssetDir("foo.txt") and AssetDir("notexist") would return an error +// AssetDir("") will return []string{"data"}. +func AssetDir(name string) ([]string, error) { + node := _bintree + if len(name) != 0 { + cannonicalName := strings.Replace(name, "\\", "/", -1) + pathList := strings.Split(cannonicalName, "/") + for _, p := range pathList { + node = node.Children[p] + if node == nil { + return nil, fmt.Errorf("Asset %s not found", name) + } + } + } + if node.Func != nil { + return nil, fmt.Errorf("Asset %s not found", name) + } + rv := make([]string, 0, len(node.Children)) + for childName := range node.Children { + rv = append(rv, childName) + } + return rv, nil +} + +type bintree struct { + Func func() (*asset, error) + Children map[string]*bintree +} + +var _bintree = &bintree{nil, map[string]*bintree{ + "resources": {nil, map[string]*bintree{ + "AWSWhitelist.json": {resourcesAwswhitelistJson, map[string]*bintree{}}, + "DefaultSamplingRules.json": {resourcesDefaultsamplingrulesJson, map[string]*bintree{}}, + "ExampleSamplingRules.json": {resourcesExamplesamplingrulesJson, map[string]*bintree{}}, + }}, +}} + +// RestoreAsset restores an asset under the given directory +func RestoreAsset(dir, name string) error { + data, err := Asset(name) + if err != nil { + return err + } + info, err := AssetInfo(name) + if err != nil { + return err + } + err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755)) + if err != nil { + return err + } + err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode()) + if err != nil { + return err + } + err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime()) + if err != nil { + return err + } + return nil +} + +// RestoreAssets restores an asset under the given directory recursively +func RestoreAssets(dir, name string) error { + children, err := AssetDir(name) + // File + if err != nil { + return RestoreAsset(dir, name) + } + // Dir + for _, child := range children { + err = RestoreAssets(dir, filepath.Join(name, child)) + if err != nil { + return err + } + } + return nil +} + +func _filePath(dir, name string) string { + cannonicalName := strings.Replace(name, "\\", "/", -1) + return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...) +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/strategy/ctxmissing/context_missing.go b/vendor/github.com/aws/aws-xray-sdk-go/strategy/ctxmissing/context_missing.go new file mode 100644 index 00000000..487d5396 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/strategy/ctxmissing/context_missing.go @@ -0,0 +1,18 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +// Package ctxmissing provides control over +// the behavior of the X-Ray SDK when subsegments +// are created without a provided parent segment. +package ctxmissing + +// Strategy provides an interface for +// implementing context missing strategies. +type Strategy interface { + ContextMissing(v interface{}) +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/strategy/ctxmissing/default_context_missing.go b/vendor/github.com/aws/aws-xray-sdk-go/strategy/ctxmissing/default_context_missing.go new file mode 100644 index 00000000..6983497c --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/strategy/ctxmissing/default_context_missing.go @@ -0,0 +1,54 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package ctxmissing + +import ( + log "github.com/cihub/seelog" +) + +// RuntimeErrorStrategy provides the AWS_XRAY_CONTEXT_MISSING +// environment variable value for enabling the runtime error +// context missing strategy (panic). +var RuntimeErrorStrategy = "RUNTIME_ERROR" + +// LogErrorStrategy provides the AWS_XRAY_CONTEXT_MISSING +// environment variable value for enabling the log error +// context missing strategy. +var LogErrorStrategy = "LOG_ERROR" + +// DefaultRuntimeErrorStrategy implements the +// runtime error context missing strategy. +type DefaultRuntimeErrorStrategy struct{} + +// DefaultLogErrorStrategy implements the +// log error context missing strategy. +type DefaultLogErrorStrategy struct{} + +// NewDefaultRuntimeErrorStrategy initializes +// an instance of DefaultRuntimeErrorStrategy. +func NewDefaultRuntimeErrorStrategy() *DefaultRuntimeErrorStrategy { + return &DefaultRuntimeErrorStrategy{} +} + +// NewDefaultLogErrorStrategy initializes +// an instance of DefaultLogErrorStrategy. +func NewDefaultLogErrorStrategy() *DefaultLogErrorStrategy { + return &DefaultLogErrorStrategy{} +} + +// ContextMissing panics when the segment context is missing. +func (dr *DefaultRuntimeErrorStrategy) ContextMissing(v interface{}) { + panic(v) +} + +// ContextMissing logs an error message when the +// segment context is missing. +func (dl *DefaultLogErrorStrategy) ContextMissing(v interface{}) { + log.Errorf("Suppressing AWS X-Ray context missing panic: %v", v) +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/strategy/exception/default_exception_formatting_strategy.go b/vendor/github.com/aws/aws-xray-sdk-go/strategy/exception/default_exception_formatting_strategy.go new file mode 100644 index 00000000..20dbf1ae --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/strategy/exception/default_exception_formatting_strategy.go @@ -0,0 +1,212 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package exception + +import ( + "bytes" + "crypto/rand" + "fmt" + "runtime" + "strings" + + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/pkg/errors" +) + +// StackTracer is an interface for implementing StackTrace method. +type StackTracer interface { + StackTrace() []uintptr +} + +// Exception provides the shape for unmarshalling an exception. +type Exception struct { + ID string `json:"id,omitempty"` + Type string `json:"type,omitempty"` + Message string `json:"message,omitempty"` + Stack []Stack `json:"stack,omitempty"` + Remote bool `json:"remote,omitempty"` +} + +// Stack provides the shape for unmarshalling an stack. +type Stack struct { + Path string `json:"path,omitempty"` + Line int `json:"line,omitempty"` + Label string `json:"label,omitempty"` +} + +// MultiError is a type for a slice of error. +type MultiError []error + +// Error returns a string format of concatenating multiple errors. +func (e MultiError) Error() string { + var buf bytes.Buffer + fmt.Fprintf(&buf, "%d errors occurred:\n", len(e)) + for _, err := range e { + buf.WriteString("* ") + buf.WriteString(err.Error()) + buf.WriteByte('\n') + } + return buf.String() +} + +var defaultErrorFrameCount = 32 + +// DefaultFormattingStrategy is the default implementation of +// the ExceptionFormattingStrategy and has a configurable frame count. +type DefaultFormattingStrategy struct { + FrameCount int +} + +// NewDefaultFormattingStrategy initializes DefaultFormattingStrategy +// with default value of frame count. +func NewDefaultFormattingStrategy() (*DefaultFormattingStrategy, error) { + return &DefaultFormattingStrategy{FrameCount: defaultErrorFrameCount}, nil +} + +// NewDefaultFormattingStrategyWithDefinedErrorFrameCount initializes +// DefaultFormattingStrategy with customer defined frame count. +func NewDefaultFormattingStrategyWithDefinedErrorFrameCount(frameCount int) (*DefaultFormattingStrategy, error) { + if frameCount > 32 || frameCount < 0 { + return nil, errors.New("frameCount must be a non-negative integer and less than 32") + } + return &DefaultFormattingStrategy{FrameCount: frameCount}, nil +} + +// Error returns the value of XRayError by given error message. +func (dEFS *DefaultFormattingStrategy) Error(message string) *XRayError { + s := make([]uintptr, dEFS.FrameCount) + n := runtime.Callers(2, s) + s = s[:n] + + return &XRayError{ + Type: "error", + Message: message, + Stack: s, + } +} + +// Errorf formats according to a format specifier and returns value of XRayError. +func (dEFS *DefaultFormattingStrategy) Errorf(formatString string, args ...interface{}) *XRayError { + e := dEFS.Error(fmt.Sprintf(formatString, args...)) + e.Stack = e.Stack[1:] + return e +} + +// Panic records error type as panic in segment and returns value of XRayError. +func (dEFS *DefaultFormattingStrategy) Panic(message string) *XRayError { + e := dEFS.Error(message) + e.Type = "panic" + e.Stack = e.Stack[4:] + return e +} + +// Panicf formats according to a format specifier and returns value of XRayError. +func (dEFS *DefaultFormattingStrategy) Panicf(formatString string, args ...interface{}) *XRayError { + e := dEFS.Panic(fmt.Sprintf(formatString, args...)) + e.Stack = e.Stack[1:] + return e +} + +// ExceptionFromError takes an error and returns value of Exception +func (dEFS *DefaultFormattingStrategy) ExceptionFromError(err error) Exception { + var isRemote bool + if reqErr, ok := err.(awserr.RequestFailure); ok { + // A service error occurs + if reqErr.RequestID() != "" { + isRemote = true + } + } + e := Exception{ + ID: newExceptionID(), + Type: "error", + Message: err.Error(), + Remote: isRemote, + } + + if err, ok := err.(*XRayError); ok { + e.Type = err.Type + } + + var s []uintptr + + // This is our publicly supported interface for passing along stack traces + if err, ok := err.(StackTracer); ok { + s = err.StackTrace() + } + + // We also accept github.com/pkg/errors style stack traces for ease of use + if err, ok := err.(interface { + StackTrace() errors.StackTrace + }); ok { + for _, frame := range err.StackTrace() { + s = append(s, uintptr(frame)) + } + } + + if s == nil { + s = make([]uintptr, dEFS.FrameCount) + n := runtime.Callers(5, s) + s = s[:n] + } + + e.Stack = convertStack(s) + return e +} + +func newExceptionID() string { + var r [8]byte + _, err := rand.Read(r[:]) + if err != nil { + panic(err) + } + return fmt.Sprintf("%02x", r) +} + +func convertStack(s []uintptr) []Stack { + var r []Stack + frames := runtime.CallersFrames(s) + + d := true + for frame, more := frames.Next(); d; frame, more = frames.Next() { + f := &Stack{} + f.Path, f.Line, f.Label = parseFrame(frame) + r = append(r, *f) + d = more + } + return r +} + +func parseFrame(frame runtime.Frame) (string, int, string) { + path, line, label := frame.File, frame.Line, frame.Function + + // Strip GOPATH from path by counting the number of seperators in label & path + // For example: + // GOPATH = /home/user + // path = /home/user/src/pkg/sub/file.go + // label = pkg/sub.Type.Method + // We want to set path to: + // pkg/sub/file.go + i := len(path) + for n, g := 0, strings.Count(label, "/")+2; n < g; n++ { + i = strings.LastIndex(path[:i], "/") + if i == -1 { + // Something went wrong and path has less seperators than we expected + // Abort and leave i as -1 to counteract the +1 below + break + } + } + path = path[i+1:] // Trim the initial / + + // Strip the path from the function name as it's already in the path + label = label[strings.LastIndex(label, "/")+1:] + // Likewise strip the package name + label = label[strings.Index(label, ".")+1:] + + return path, line, label +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/strategy/exception/exception_formatting_strategy.go b/vendor/github.com/aws/aws-xray-sdk-go/strategy/exception/exception_formatting_strategy.go new file mode 100644 index 00000000..d240e23b --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/strategy/exception/exception_formatting_strategy.go @@ -0,0 +1,18 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package exception + +// FormattingStrategy provides an interface for implementing methods that format errors and exceptions. +type FormattingStrategy interface { + Error(message string) *XRayError + Errorf(formatString string, args ...interface{}) *XRayError + Panic(message string) *XRayError + Panicf(formatString string, args ...interface{}) *XRayError + ExceptionFromError(err error) Exception +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/strategy/exception/xray_error.go b/vendor/github.com/aws/aws-xray-sdk-go/strategy/exception/xray_error.go new file mode 100644 index 00000000..a16e2a1d --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/strategy/exception/xray_error.go @@ -0,0 +1,27 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package exception + +// XRayError records error type, message, +// and a slice of stack frame pointers. +type XRayError struct { + Type string + Message string + Stack []uintptr +} + +// Error returns the value of error message. +func (e *XRayError) Error() string { + return e.Message +} + +// StackTrace returns a slice of integer pointers. +func (e *XRayError) StackTrace() []uintptr { + return e.Stack +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/localized.go b/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/localized.go new file mode 100644 index 00000000..301fcd45 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/localized.go @@ -0,0 +1,74 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package sampling + +import ( + "github.com/aws/aws-xray-sdk-go/resources" + log "github.com/cihub/seelog" +) + +// LocalizedStrategy makes trace sampling decisions based on +// a set of rules provided in a local JSON file. Trace sampling +// decisions are made by the root node in the trace. If a +// sampling decision is made by the root service, it will be passed +// to downstream services through the trace header. +type LocalizedStrategy struct { + manifest *RuleManifest +} + +// NewLocalizedStrategy initializes an instance of LocalizedStrategy +// with the default trace sampling rules. The default rules sample +// the first request per second, and 5% of requests thereafter. +func NewLocalizedStrategy() (*LocalizedStrategy, error) { + bytes, err := resources.Asset("resources/DefaultSamplingRules.json") + if err != nil { + return nil, err + } + manifest, err := ManifestFromJSONBytes(bytes) + if err != nil { + return nil, err + } + return &LocalizedStrategy{manifest: manifest}, nil +} + +// NewLocalizedStrategyFromFilePath initializes an instance of +// LocalizedStrategy using a custom ruleset found at the filepath fp. +func NewLocalizedStrategyFromFilePath(fp string) (*LocalizedStrategy, error) { + manifest, err := ManifestFromFilePath(fp) + if err != nil { + return nil, err + } + return &LocalizedStrategy{manifest: manifest}, nil +} + +// NewLocalizedStrategyFromJSONBytes initializes an instance of +// LocalizedStrategy using a custom ruleset provided in the json bytes b. +func NewLocalizedStrategyFromJSONBytes(b []byte) (*LocalizedStrategy, error) { + manifest, err := ManifestFromJSONBytes(b) + if err != nil { + return nil, err + } + return &LocalizedStrategy{manifest: manifest}, nil +} + +// ShouldTrace consults the LocalizedStrategy's rule set to determine +// if the given request should be traced or not. +func (lss *LocalizedStrategy) ShouldTrace(serviceName string, path string, method string) bool { + log.Tracef("Determining ShouldTrace decision for:\n\tserviceName: %s\n\tpath: %s\n\tmethod: %s", serviceName, path, method) + if nil != lss.manifest.Rules { + for _, r := range lss.manifest.Rules { + if r.AppliesTo(serviceName, path, method) { + log.Tracef("Applicable rule:\n\tfixed_target: %d\n\trate: %f\n\tservice_name: %s\n\turl_path: %s\n\thttp_method: %s", r.FixedTarget, r.Rate, r.ServiceName, r.URLPath, r.HTTPMethod) + return r.Sample() + } + } + } + log.Tracef("Default rule applies:\n\tfixed_target: %d\n\trate: %f", lss.manifest.Default.FixedTarget, lss.manifest.Default.Rate) + return lss.manifest.Default.Sample() +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/reservoir.go b/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/reservoir.go new file mode 100644 index 00000000..8d2fc755 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/reservoir.go @@ -0,0 +1,81 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package sampling + +import ( + "fmt" + "sync" + "sync/atomic" + "time" +) + +var maxRate uint64 = 1e8 + +// Reservoir allows a specified amount of `Take()`s per second. +// Support for atomic operations on uint64 is required. +// More information: https://golang.org/pkg/sync/atomic/#pkg-note-BUG +type Reservoir struct { + maskedCounter uint64 + perSecond uint64 + mutex sync.Mutex // don't use embedded struct to ensure 64 bit alignment for maskedCounter. +} + +// NewReservoir creates a new reservoir with a specified perSecond +// sampling capacity. The maximum supported sampling capacity per +// second is currently 100,000,000. An error is returned if the +// desired capacity is greater than this maximum value. +func NewReservoir(perSecond uint64) (*Reservoir, error) { + if perSecond >= maxRate { + return nil, fmt.Errorf("desired sampling capacity of %d is greater than maximum supported rate %d", perSecond, maxRate) + } + return &Reservoir{ + maskedCounter: 0, + perSecond: perSecond, + }, nil +} + +// Take returns true when the reservoir has remaining sampling +// capacity for the current epoch. Take returns false when the +// reservoir has no remaining sampling capacity for the current +// epoch. The sampling capacity decrements by one each time +// Take returns true. +func (r *Reservoir) Take() bool { + now := uint64(time.Now().Unix()) + counterNewVal := atomic.AddUint64(&r.maskedCounter, 1) + previousTimestamp := extractTime(counterNewVal) + + if previousTimestamp != now { + r.mutex.Lock() + beforeUpdate := atomic.LoadUint64(&r.maskedCounter) + timestampBeforeUpdate := extractTime(beforeUpdate) + + if timestampBeforeUpdate != now { + valueToSet := timestampToCounter(now) + atomic.StoreUint64(&r.maskedCounter, valueToSet) + } + + counterNewVal = atomic.AddUint64(&r.maskedCounter, 1) + r.mutex.Unlock() + } + + newCounterValue := extractCounter(counterNewVal) + return newCounterValue <= r.perSecond +} + +func extractTime(maskedCounter uint64) uint64 { + return maskedCounter / maxRate +} + +func extractCounter(maskedCounter uint64) uint64 { + return maskedCounter % maxRate +} + +func timestampToCounter(timestamp uint64) uint64 { + return timestamp * maxRate +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/sampling_rule.go b/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/sampling_rule.go new file mode 100644 index 00000000..ab3fb88d --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/sampling_rule.go @@ -0,0 +1,39 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package sampling + +import ( + "math/rand" + + "github.com/aws/aws-xray-sdk-go/pattern" +) + +// Rule represents a single entry in a sampling ruleset. +type Rule struct { + ServiceName string `json:"service_name"` + HTTPMethod string `json:"http_method"` + URLPath string `json:"url_path"` + FixedTarget uint64 `json:"fixed_target"` + Rate float64 `json:"rate"` + reservoir *Reservoir +} + +// AppliesTo returns true when the rule applies to the given parameters +func (sr *Rule) AppliesTo(serviceName string, path string, method string) bool { + return pattern.WildcardMatchCaseInsensitive(sr.ServiceName, serviceName) && pattern.WildcardMatchCaseInsensitive(sr.URLPath, path) && pattern.WildcardMatchCaseInsensitive(sr.HTTPMethod, method) +} + +// Sample returns true when the rule's reservoir is not full or +// when a randomly generated float is less than the rule's rate +func (sr *Rule) Sample() bool { + if sr.reservoir.Take() { + return true + } + return rand.Float64() < sr.Rate +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/sampling_rule_manifest.go b/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/sampling_rule_manifest.go new file mode 100644 index 00000000..e604d30d --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/sampling_rule_manifest.go @@ -0,0 +1,93 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package sampling + +import ( + "encoding/json" + "errors" + "fmt" + "io/ioutil" +) + +// RuleManifest represents a full sampling ruleset, with a list of +// custom rules and default values for incoming requests that do +// not match any of the provided rules. +type RuleManifest struct { + Version int `json:"version"` + Default *Rule `json:"default"` + Rules []*Rule `json:"rules"` +} + +// ManifestFromFilePath creates a sampling ruleset from a given filepath fp. +func ManifestFromFilePath(fp string) (*RuleManifest, error) { + b, err := ioutil.ReadFile(fp) + if err == nil { + s, e := ManifestFromJSONBytes(b) + if e != nil { + return nil, e + } + err = processManifest(s) + if err != nil { + return nil, err + } + return s, nil + } + return nil, err +} + +// ManifestFromJSONBytes creates a sampling ruleset from given JSON bytes b. +func ManifestFromJSONBytes(b []byte) (*RuleManifest, error) { + s := &RuleManifest{} + err := json.Unmarshal(b, s) + if err != nil { + return nil, err + } + err = processManifest(s) + if err != nil { + return nil, err + } + return s, nil +} + +// processManifest returns the provided manifest if valid, +// or an error if the provided manifest is invalid. +func processManifest(srm *RuleManifest) error { + if nil == srm { + return errors.New("sampling rule manifest must not be nil") + } + if 1 != srm.Version { + return fmt.Errorf("sampling rule manifest version %d not supported", srm.Version) + } + if nil == srm.Default { + return errors.New("sampling rule manifest must include a default rule") + } + if "" != srm.Default.URLPath || "" != srm.Default.ServiceName || "" != srm.Default.HTTPMethod { + return errors.New("the default rule must not specify values for url_path, service_name, or http_method") + } + if srm.Default.FixedTarget < 0 || srm.Default.Rate < 0 { + return errors.New("the default rule must specify non-negative values for fixed_target and rate") + } + + res, err := NewReservoir(srm.Default.FixedTarget) + if err != nil { + return err + } + srm.Default.reservoir = res + + if srm.Rules != nil { + for _, r := range srm.Rules { + res, err := NewReservoir(r.FixedTarget) + if err != nil { + return err + } + r.reservoir = res + } + } + return nil +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/sampling_strategy.go b/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/sampling_strategy.go new file mode 100644 index 00000000..583dfa39 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/strategy/sampling/sampling_strategy.go @@ -0,0 +1,14 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package sampling + +// Strategy provides an interface for implementing trace sampling strategies. +type Strategy interface { + ShouldTrace(serviceName string, path string, method string) bool +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/aws.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/aws.go new file mode 100644 index 00000000..a5f99852 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/aws.go @@ -0,0 +1,417 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io/ioutil" + "net/http/httptrace" + "reflect" + "strings" + "unicode" + + "github.com/aws/aws-sdk-go/aws/client" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-xray-sdk-go/resources" + log "github.com/cihub/seelog" +) + +const RequestIDKey string = "request_id" +const ExtendedRequestIDKey string = "id_2" +const S3ExtendedRequestIDHeaderKey string = "x-amz-id-2" + +type jsonMap struct { + object interface{} +} + +const ( + requestKeyword = iota + responseKeyword +) + +func beginSubsegment(r *request.Request, name string) { + ctx, _ := BeginSubsegment(r.HTTPRequest.Context(), name) + r.HTTPRequest = r.HTTPRequest.WithContext(ctx) +} + +func endSubsegment(r *request.Request) { + seg := GetSegment(r.HTTPRequest.Context()) + if seg == nil { + return + } + seg.Close(r.Error) + r.HTTPRequest = r.HTTPRequest.WithContext(context.WithValue(r.HTTPRequest.Context(), ContextKey, seg.parent)) +} + +var xRayBeforeValidateHandler = request.NamedHandler{ + Name: "XRayBeforeValidateHandler", + Fn: func(r *request.Request) { + ctx, opseg := BeginSubsegment(r.HTTPRequest.Context(), r.ClientInfo.ServiceName) + if opseg == nil { + return + } + opseg.Namespace = "aws" + marshalctx, _ := BeginSubsegment(ctx, "marshal") + + r.HTTPRequest = r.HTTPRequest.WithContext(marshalctx) + r.HTTPRequest.Header.Set("x-amzn-trace-id", opseg.DownstreamHeader().String()) + }, +} + +var xRayAfterBuildHandler = request.NamedHandler{ + Name: "XRayAfterBuildHandler", + Fn: func(r *request.Request) { + endSubsegment(r) + }, +} + +var xRayBeforeSignHandler = request.NamedHandler{ + Name: "XRayBeforeSignHandler", + Fn: func(r *request.Request) { + ctx, seg := BeginSubsegment(r.HTTPRequest.Context(), "attempt") + if seg == nil { + return + } + ct, _ := NewClientTrace(ctx) + r.HTTPRequest = r.HTTPRequest.WithContext(httptrace.WithClientTrace(ctx, ct.httpTrace)) + }, +} + +var xRayAfterSignHandler = request.NamedHandler{ + Name: "XRayAfterSignHandler", + Fn: func(r *request.Request) { + endSubsegment(r) + }, +} + +var xRayBeforeSendHandler = request.NamedHandler{ + Name: "XRayBeforeSendHandler", + Fn: func(r *request.Request) { + }, +} + +var xRayAfterSendHandler = request.NamedHandler{ + Name: "XRayAfterSendHandler", + Fn: func(r *request.Request) { + endSubsegment(r) + }, +} + +var xRayBeforeUnmarshalHandler = request.NamedHandler{ + Name: "XRayBeforeUnmarshalHandler", + Fn: func(r *request.Request) { + endSubsegment(r) // end attempt subsegment + beginSubsegment(r, "unmarshal") + }, +} + +var xRayAfterUnmarshalHandler = request.NamedHandler{ + Name: "XRayAfterUnmarshalHandler", + Fn: func(r *request.Request) { + endSubsegment(r) + }, +} + +var xRayBeforeRetryHandler = request.NamedHandler{ + Name: "XRayBeforeRetryHandler", + Fn: func(r *request.Request) { + endSubsegment(r) // end attempt subsegment + ctx, _ := BeginSubsegment(r.HTTPRequest.Context(), "wait") + + r.HTTPRequest = r.HTTPRequest.WithContext(ctx) + }, +} + +var xRayAfterRetryHandler = request.NamedHandler{ + Name: "XRayAfterRetryHandler", + Fn: func(r *request.Request) { + endSubsegment(r) + }, +} + +func pushHandlers(c *client.Client) { + c.Handlers.Validate.PushFrontNamed(xRayBeforeValidateHandler) + c.Handlers.Build.PushBackNamed(xRayAfterBuildHandler) + c.Handlers.Sign.PushFrontNamed(xRayBeforeSignHandler) + c.Handlers.Unmarshal.PushFrontNamed(xRayBeforeUnmarshalHandler) + c.Handlers.Unmarshal.PushBackNamed(xRayAfterUnmarshalHandler) + c.Handlers.Retry.PushFrontNamed(xRayBeforeRetryHandler) + c.Handlers.AfterRetry.PushBackNamed(xRayAfterRetryHandler) +} + +// AWS adds X-Ray tracing to an AWS client. +func AWS(c *client.Client) { + if c == nil { + panic("Please initialize the provided AWS client before passing to the AWS() method.") + } + pushHandlers(c) + c.Handlers.Complete.PushFrontNamed(xrayCompleteHandler("")) +} + +// AWSWithWhitelist allows a custom parameter whitelist JSON file to be defined. +func AWSWithWhitelist(c *client.Client, filename string) { + if c == nil { + panic("Please initialize the provided AWS client before passing to the AWSWithWhitelist() method.") + } + pushHandlers(c) + c.Handlers.Complete.PushFrontNamed(xrayCompleteHandler(filename)) +} + +func xrayCompleteHandler(filename string) request.NamedHandler { + whitelistJSON := parseWhitelistJSON(filename) + whitelist := &jsonMap{} + err := json.Unmarshal(whitelistJSON, &whitelist.object) + if err != nil { + panic(err) + } + + return request.NamedHandler{ + Name: "XRayCompleteHandler", + Fn: func(r *request.Request) { + curseg := GetSegment(r.HTTPRequest.Context()) + + for curseg != nil && curseg.Namespace != "aws" { + curseg.Close(nil) + curseg = curseg.parent + } + if curseg == nil { + return + } + + opseg := curseg + + opseg.Lock() + for k, v := range extractRequestParameters(r, whitelist) { + opseg.GetAWS()[strings.ToLower(addUnderScoreBetweenWords(k))] = v + } + for k, v := range extractResponseParameters(r, whitelist) { + opseg.GetAWS()[strings.ToLower(addUnderScoreBetweenWords(k))] = v + } + + opseg.GetAWS()["region"] = r.ClientInfo.SigningRegion + opseg.GetAWS()["operation"] = r.Operation.Name + opseg.GetAWS()["retries"] = r.RetryCount + opseg.GetAWS()[RequestIDKey] = r.RequestID + + if r.HTTPResponse != nil { + opseg.GetHTTP().GetResponse().Status = r.HTTPResponse.StatusCode + opseg.GetHTTP().GetResponse().ContentLength = int(r.HTTPResponse.ContentLength) + + if extendedRequestID := r.HTTPResponse.Header.Get(S3ExtendedRequestIDHeaderKey); extendedRequestID != "" { + opseg.GetAWS()[ExtendedRequestIDKey] = extendedRequestID + } + } + + if request.IsErrorThrottle(r.Error) { + opseg.Throttle = true + } + + opseg.Unlock() + opseg.Close(r.Error) + }, + } +} + +func parseWhitelistJSON(filename string) []byte { + if filename != "" { + readBytes, err := ioutil.ReadFile(filename) + if err != nil { + log.Errorf("Error occurred while reading customized AWS whitelist JSON file. %v \nReverting to default AWS whitelist JSON file.", err) + } else { + return readBytes + } + } + + defaultBytes, err := resources.Asset("resources/AWSWhitelist.json") + if err != nil { + panic(err) + } + return defaultBytes +} + +func keyValue(r interface{}, tag string) interface{} { + v := reflect.ValueOf(r) + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + if v.Kind() != reflect.Struct { + log.Errorf("keyValue only accepts structs; got %T", v) + } + typ := v.Type() + for i := 1; i < v.NumField(); i++ { + if typ.Field(i).Name == tag { + return v.Field(i).Interface() + } + } + return nil +} + +func addUnderScoreBetweenWords(name string) string { + var buffer bytes.Buffer + for i, char := range name { + if unicode.IsUpper(char) && i != 0 { + buffer.WriteRune('_') + } + buffer.WriteRune(char) + } + return buffer.String() +} + +func (j *jsonMap) data() interface{} { + if j == nil { + return nil + } + return j.object +} + +func (j *jsonMap) search(keys ...string) *jsonMap { + var object interface{} + object = j.data() + + for target := 0; target < len(keys); target++ { + if mmap, ok := object.(map[string]interface{}); ok { + object, ok = mmap[keys[target]] + if !ok { + return nil + } + } else { + return nil + } + } + return &jsonMap{object} +} + +func (j *jsonMap) children() ([]interface{}, error) { + if slice, ok := j.data().([]interface{}); ok { + return slice, nil + } + return nil, errors.New("cannot get corresponding items for given aws whitelisting json file") +} + +func (j *jsonMap) childrenMap() (map[string]interface{}, error) { + if mmap, ok := j.data().(map[string]interface{}); ok { + return mmap, nil + } + return nil, errors.New("cannot get corresponding items for given aws whitelisting json file") +} + +func extractRequestParameters(r *request.Request, whitelist *jsonMap) map[string]interface{} { + valueMap := make(map[string]interface{}) + + extractParameters("request_parameters", requestKeyword, r, whitelist, valueMap) + extractDescriptors("request_descriptors", requestKeyword, r, whitelist, valueMap) + + return valueMap +} + +func extractResponseParameters(r *request.Request, whitelist *jsonMap) map[string]interface{} { + valueMap := make(map[string]interface{}) + + extractParameters("response_parameters", responseKeyword, r, whitelist, valueMap) + extractDescriptors("response_descriptors", responseKeyword, r, whitelist, valueMap) + + return valueMap +} + +func extractParameters(whitelistKey string, rType int, r *request.Request, whitelist *jsonMap, valueMap map[string]interface{}) { + params := whitelist.search("services", r.ClientInfo.ServiceName, "operations", r.Operation.Name, whitelistKey) + if params != nil { + children, err := params.children() + if err != nil { + log.Errorf("failed to get values for aws attribute: %v", err) + return + } + for _, child := range children { + if child != nil { + var value interface{} + if rType == requestKeyword { + value = keyValue(r.Params, child.(string)) + } else if rType == responseKeyword { + value = keyValue(r.Data, child.(string)) + } + if (value != reflect.Value{}) { + valueMap[child.(string)] = value + } + } + } + } +} + +func extractDescriptors(whitelistKey string, rType int, r *request.Request, whitelist *jsonMap, valueMap map[string]interface{}) { + responseDtr := whitelist.search("services", r.ClientInfo.ServiceName, "operations", r.Operation.Name, whitelistKey) + if responseDtr != nil { + items, err := responseDtr.childrenMap() + if err != nil { + log.Errorf("failed to get values for aws attribute: %v", err) + return + } + for k := range items { + descriptorMap, _ := whitelist.search("services", r.ClientInfo.ServiceName, "operations", r.Operation.Name, whitelistKey, k).childrenMap() + if rType == requestKeyword { + insertDescriptorValuesIntoMap(k, r.Params, descriptorMap, valueMap) + } else if rType == responseKeyword { + insertDescriptorValuesIntoMap(k, r.Data, descriptorMap, valueMap) + } + } + } +} + +func descriptorType(descriptorMap map[string]interface{}) string { + var typeValue string + if (descriptorMap["map"] != nil) && (descriptorMap["get_keys"] != nil) { + typeValue = "map" + } else if (descriptorMap["list"] != nil) && (descriptorMap["get_count"] != nil) { + typeValue = "list" + } else if descriptorMap["value"] != nil { + typeValue = "value" + } else { + log.Error("Missing keys in request / response descriptors in AWS whitelist JSON file.") + } + return typeValue +} + +func insertDescriptorValuesIntoMap(key string, data interface{}, descriptorMap map[string]interface{}, valueMap map[string]interface{}) { + descriptorType := descriptorType(descriptorMap) + if descriptorType == "map" { + var keySlice []interface{} + m := keyValue(data, key) + val := reflect.ValueOf(m) + if val.Kind() == reflect.Map { + for _, key := range val.MapKeys() { + keySlice = append(keySlice, key.Interface()) + } + } + if descriptorMap["rename_to"] != nil { + valueMap[descriptorMap["rename_to"].(string)] = keySlice + } else { + valueMap[strings.ToLower(key)] = keySlice + } + } else if descriptorType == "list" { + var count int + l := keyValue(data, key) + val := reflect.ValueOf(l) + count = val.Len() + + if descriptorMap["rename_to"] != nil { + valueMap[descriptorMap["rename_to"].(string)] = count + } else { + valueMap[strings.ToLower(key)] = count + } + } else if descriptorType == "value" { + val := keyValue(data, key) + if descriptorMap["rename_to"] != nil { + valueMap[descriptorMap["rename_to"].(string)] = val + } else { + valueMap[strings.ToLower(key)] = val + } + } +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/capture.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/capture.go new file mode 100644 index 00000000..7362f663 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/capture.go @@ -0,0 +1,61 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "context" + "fmt" +) + +// Capture traces the provided synchronous function by +// beginning and closing a subsegment around its execution. +func Capture(ctx context.Context, name string, fn func(context.Context) error) (err error) { + c, seg := BeginSubsegment(ctx, name) + + defer func() { + if seg != nil { + seg.Close(err) + } else { + cfg := GetRecorder(ctx) + failedMessage := fmt.Sprintf("failed to end subsegment: subsegment '%v' cannot be found.", name) + if cfg != nil && cfg.ContextMissingStrategy != nil { + cfg.ContextMissingStrategy.ContextMissing(failedMessage) + } else { + globalCfg.ContextMissingStrategy().ContextMissing(failedMessage) + } + } + }() + + defer func() { + if p := recover(); p != nil { + err = seg.ParentSegment.GetConfiguration().ExceptionFormattingStrategy.Panicf("%v", p) + panic(p) + } + }() + + if c == nil && seg == nil { + err = fn(ctx) + } else { + err = fn(c) + } + + return err +} + +// CaptureAsync traces an arbitrary code segment within a goroutine. +// Use CaptureAsync instead of manually calling Capture within a goroutine +// to ensure the segment is flushed properly. +func CaptureAsync(ctx context.Context, name string, fn func(context.Context) error) { + started := make(chan struct{}) + go Capture(ctx, name, func(ctx context.Context) error { + close(started) + return fn(ctx) + }) + <-started +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/client.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/client.go new file mode 100644 index 00000000..c3957ba1 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/client.go @@ -0,0 +1,119 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "context" + "net/http" + "net/http/httptrace" + "strconv" + + log "github.com/cihub/seelog" +) + +const emptyHostRename = "empty_host_error" + +// Client creates a shallow copy of the provided http client, +// defaulting to http.DefaultClient, with roundtripper wrapped +// with xray.RoundTripper. +func Client(c *http.Client) *http.Client { + if c == nil { + c = http.DefaultClient + } + transport := c.Transport + if transport == nil { + transport = http.DefaultTransport + } + return &http.Client{ + Transport: RoundTripper(transport), + CheckRedirect: c.CheckRedirect, + Jar: c.Jar, + Timeout: c.Timeout, + } +} + +// RoundTripper wraps the provided http roundtripper with xray.Capture, +// sets HTTP-specific xray fields, and adds the trace header to the outbound request. +func RoundTripper(rt http.RoundTripper) http.RoundTripper { + return &roundtripper{rt} +} + +type roundtripper struct { + Base http.RoundTripper +} + +// RoundTrip wraps a single HTTP transaction and add corresponding information into a subsegment. +func (rt *roundtripper) RoundTrip(r *http.Request) (*http.Response, error) { + var isEmptyHost bool + var resp *http.Response + host := r.Host + if host == "" { + if h := r.URL.Host; h != "" { + host = h + } else { + host = emptyHostRename + isEmptyHost = true + } + } + + err := Capture(r.Context(), host, func(ctx context.Context) error { + var err error + seg := GetSegment(ctx) + if seg == nil { + resp, err = rt.Base.RoundTrip(r) + log.Warnf("failed to record HTTP transaction: segment cannot be found.") + return err + } + + ct, e := NewClientTrace(ctx) + if e != nil { + return e + } + r = r.WithContext(httptrace.WithClientTrace(ctx, ct.httpTrace)) + + seg.Lock() + + if isEmptyHost { + seg.Namespace = "" + } else { + seg.Namespace = "remote" + } + + seg.GetHTTP().GetRequest().Method = r.Method + seg.GetHTTP().GetRequest().URL = r.URL.String() + + r.Header.Set("x-amzn-trace-id", seg.DownstreamHeader().String()) + seg.Unlock() + + resp, err = rt.Base.RoundTrip(r) + + if resp != nil { + seg.Lock() + seg.GetHTTP().GetResponse().Status = resp.StatusCode + seg.GetHTTP().GetResponse().ContentLength, _ = strconv.Atoi(resp.Header.Get("Content-Length")) + + if resp.StatusCode >= 400 && resp.StatusCode < 500 { + seg.Error = true + } + if resp.StatusCode == 429 { + seg.Throttle = true + } + if resp.StatusCode >= 500 && resp.StatusCode < 600 { + seg.Fault = true + } + seg.Unlock() + } + if err != nil { + ct.subsegments.GotConn(nil, err) + } + + return err + }) + return resp, err +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/config.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/config.go new file mode 100644 index 00000000..507f0c80 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/config.go @@ -0,0 +1,303 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "context" + "fmt" + "net" + "os" + "sync" + + "github.com/aws/aws-xray-sdk-go/strategy/ctxmissing" + "github.com/aws/aws-xray-sdk-go/strategy/exception" + "github.com/aws/aws-xray-sdk-go/strategy/sampling" + log "github.com/cihub/seelog" +) + +// SDKVersion records the current X-Ray Go SDK version. +const SDKVersion = "1.0.0-rc.1" + +// SDKType records which X-Ray SDK customer uses. +const SDKType = "X-Ray for Go" + +// SDK provides the shape for unmarshalling an SDK struct. +type SDK struct { + Version string `json:"sdk_version,omitempty"` + Type string `json:"sdk,omitempty"` +} + +var globalCfg = newGlobalConfig() + +func newGlobalConfig() *globalConfig { + ret := &globalConfig{} + + // Set the logging configuration to the defaults + ret.logLevel, ret.logFormat = loadLogConfig("", "") + + // Try to get the X-Ray daemon address from an environment variable + if envDaemonAddr := os.Getenv("AWS_XRAY_DAEMON_ADDRESS"); envDaemonAddr != "" { + + // Try to resolve it, panic if it is malformed + daemonAddress, err := net.ResolveUDPAddr("udp", envDaemonAddr) + if err != nil { + panic(err) + } + ret.daemonAddr = daemonAddress + } else { + // Use a default if the environment variable is empty + ret.daemonAddr = &net.UDPAddr{ + IP: net.IPv4(127, 0, 0, 1), + Port: 2000, + } + } + + ss, err := sampling.NewLocalizedStrategy() + if err != nil { + panic(err) + } + ret.samplingStrategy = ss + + efs, err := exception.NewDefaultFormattingStrategy() + if err != nil { + panic(err) + } + ret.exceptionFormattingStrategy = efs + + sts, err := NewDefaultStreamingStrategy() + if err != nil { + panic(err) + } + ret.streamingStrategy = sts + + cm := ctxmissing.NewDefaultRuntimeErrorStrategy() + + ret.contextMissingStrategy = cm + + return ret +} + +type globalConfig struct { + sync.RWMutex + + daemonAddr *net.UDPAddr + serviceVersion string + samplingStrategy sampling.Strategy + streamingStrategy StreamingStrategy + exceptionFormattingStrategy exception.FormattingStrategy + contextMissingStrategy ctxmissing.Strategy + logLevel log.LogLevel + logFormat string +} + +// Config is a set of X-Ray configurations. +type Config struct { + DaemonAddr string + ServiceVersion string + SamplingStrategy sampling.Strategy + StreamingStrategy StreamingStrategy + ExceptionFormattingStrategy exception.FormattingStrategy + ContextMissingStrategy ctxmissing.Strategy + LogLevel string + LogFormat string +} + +// ContextWithConfig returns context with given configuration settings. +func ContextWithConfig(ctx context.Context, c Config) (context.Context, error) { + var errors exception.MultiError + + var daemonAddress string + if addr := os.Getenv("AWS_XRAY_DAEMON_ADDRESS"); addr != "" { + daemonAddress = addr + } else if c.DaemonAddr != "" { + daemonAddress = c.DaemonAddr + } + + if daemonAddress != "" { + raddr, err := net.ResolveUDPAddr("udp", daemonAddress) + if err == nil { + go refreshEmitterWithAddress(raddr) + } else { + errors = append(errors, err) + } + } + + cms := os.Getenv("AWS_XRAY_CONTEXT_MISSING") + if cms != "" { + if cms == ctxmissing.RuntimeErrorStrategy { + cm := ctxmissing.NewDefaultRuntimeErrorStrategy() + c.ContextMissingStrategy = cm + } else if cms == ctxmissing.LogErrorStrategy { + cm := ctxmissing.NewDefaultLogErrorStrategy() + c.ContextMissingStrategy = cm + } + } + + loadLogConfig(c.LogLevel, c.LogFormat) + + var err error + switch len(errors) { + case 0: + err = nil + case 1: + err = errors[0] + default: + err = errors + } + + return context.WithValue(ctx, RecorderContextKey{}, &c), err +} + +// Configure overrides default configuration options with customer-defined values. +func Configure(c Config) error { + globalCfg.Lock() + defer globalCfg.Unlock() + + var errors exception.MultiError + + var daemonAddress string + if addr := os.Getenv("AWS_XRAY_DAEMON_ADDRESS"); addr != "" { + daemonAddress = addr + } else if c.DaemonAddr != "" { + daemonAddress = c.DaemonAddr + } + + if daemonAddress != "" { + addr, err := net.ResolveUDPAddr("udp", daemonAddress) + if err == nil { + globalCfg.daemonAddr = addr + go refreshEmitter() + } else { + errors = append(errors, err) + } + } + + if c.SamplingStrategy != nil { + globalCfg.samplingStrategy = c.SamplingStrategy + } + + if c.ExceptionFormattingStrategy != nil { + globalCfg.exceptionFormattingStrategy = c.ExceptionFormattingStrategy + } + + if c.StreamingStrategy != nil { + globalCfg.streamingStrategy = c.StreamingStrategy + } + + cms := os.Getenv("AWS_XRAY_CONTEXT_MISSING") + if cms != "" { + if cms == ctxmissing.RuntimeErrorStrategy { + cm := ctxmissing.NewDefaultRuntimeErrorStrategy() + globalCfg.contextMissingStrategy = cm + } else if cms == ctxmissing.LogErrorStrategy { + cm := ctxmissing.NewDefaultLogErrorStrategy() + globalCfg.contextMissingStrategy = cm + } + } else if c.ContextMissingStrategy != nil { + globalCfg.contextMissingStrategy = c.ContextMissingStrategy + } + + if c.ServiceVersion != "" { + globalCfg.serviceVersion = c.ServiceVersion + } + + globalCfg.logLevel, globalCfg.logFormat = loadLogConfig(c.LogLevel, c.LogFormat) + + switch len(errors) { + case 0: + return nil + case 1: + return errors[0] + default: + return errors + } +} + +func loadLogConfig(logLevel string, logFormat string) (log.LogLevel, string) { + var level log.LogLevel + var format string + + switch logLevel { + case "trace": + level = log.TraceLvl + case "debug": + level = log.DebugLvl + case "info": + level = log.InfoLvl + case "warn": + level = log.WarnLvl + case "error": + level = log.ErrorLvl + default: + level = log.InfoLvl + logLevel = "info" + } + + if logFormat != "" { + format = logFormat + } else { + format = "%Date(2006-01-02T15:04:05Z07:00) [%Level] %Msg%n" + } + + writer, _ := log.NewConsoleWriter() + logger, err := log.LoggerFromWriterWithMinLevelAndFormat(writer, level, format) + if err != nil { + panic(fmt.Errorf("failed to create logs as StdOut: %v", err)) + } + log.ReplaceLogger(logger) + return level, format +} + +func (c *globalConfig) DaemonAddr() *net.UDPAddr { + c.RLock() + defer c.RUnlock() + return c.daemonAddr +} + +func (c *globalConfig) SamplingStrategy() sampling.Strategy { + c.RLock() + defer c.RUnlock() + return c.samplingStrategy +} + +func (c *globalConfig) StreamingStrategy() StreamingStrategy { + c.RLock() + defer c.RUnlock() + return c.streamingStrategy +} + +func (c *globalConfig) ExceptionFormattingStrategy() exception.FormattingStrategy { + c.RLock() + defer c.RUnlock() + return c.exceptionFormattingStrategy +} + +func (c *globalConfig) ContextMissingStrategy() ctxmissing.Strategy { + c.RLock() + defer c.RUnlock() + return c.contextMissingStrategy +} + +func (c *globalConfig) ServiceVersion() string { + c.RLock() + defer c.RUnlock() + return c.serviceVersion +} + +func (c *globalConfig) LogLevel() log.LogLevel { + c.RLock() + defer c.RUnlock() + return c.logLevel +} + +func (c *globalConfig) LogFormat() string { + c.RLock() + defer c.RUnlock() + return c.logFormat +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/context.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/context.go new file mode 100644 index 00000000..58a4eb57 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/context.go @@ -0,0 +1,107 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "context" + "errors" +) + +// ContextKeytype defines integer to be type of ContextKey. +type ContextKeytype int + +// ContextKey returns a pointer to a newly allocated zero value of ContextKeytype. +var ContextKey = new(ContextKeytype) + +// ErrRetrieveSegment happens when a segment cannot be retrieved +var ErrRetrieveSegment = errors.New("unable to retrieve segment") + +// RecorderContextKey records the key for Config value. +type RecorderContextKey struct{} + +// GetRecorder returns a pointer to the config struct provided +// in ctx, or nil if no config is set. +func GetRecorder(ctx context.Context) *Config { + if r, ok := ctx.Value(RecorderContextKey{}).(*Config); ok { + return r + } + return nil +} + +// GetSegment returns a pointer to the segment or subsegment provided +// in ctx, or nil if no segment or subsegment is found. +func GetSegment(ctx context.Context) *Segment { + if seg, ok := ctx.Value(ContextKey).(*Segment); ok { + return seg + } + return nil +} + +// TraceID returns the canonical ID of the cross-service trace from the +// given segment in ctx. The value can be used in X-Ray's UI to uniquely +// identify the code paths executed. If no segment is provided in ctx, +// an empty string is returned. +func TraceID(ctx context.Context) string { + if seg, ok := ctx.Value(ContextKey).(*Segment); ok { + return seg.TraceID + } + return "" +} + +// RequestWasTraced returns true if the context contains an X-Ray segment +// that was created from an HTTP request that contained a trace header. +// This is useful to ensure that a service is only called from X-Ray traced +// services. +func RequestWasTraced(ctx context.Context) bool { + for seg := GetSegment(ctx); seg != nil; seg = seg.parent { + if seg.RequestWasTraced { + return true + } + } + return false +} + +// DetachContext returns a new context with the existing segment. +// This is useful for creating background tasks which won't be cancelled +// when a request completes. +func DetachContext(ctx context.Context) context.Context { + return context.WithValue(context.Background(), ContextKey, GetSegment(ctx)) +} + +// AddAnnotation adds an annotation to the provided segment or subsegment in ctx. +func AddAnnotation(ctx context.Context, key string, value interface{}) error { + if seg := GetSegment(ctx); seg != nil { + return seg.AddAnnotation(key, value) + } + return ErrRetrieveSegment +} + +// AddMetadata adds a metadata to the provided segment or subsegment in ctx. +func AddMetadata(ctx context.Context, key string, value interface{}) error { + if seg := GetSegment(ctx); seg != nil { + return seg.AddMetadata(key, value) + } + return ErrRetrieveSegment +} + +// AddMetadataToNamespace adds a namespace to the provided segment's or subsegment's metadata in ctx. +func AddMetadataToNamespace(ctx context.Context, namespace string, key string, value interface{}) error { + if seg := GetSegment(ctx); seg != nil { + return seg.AddMetadataToNamespace(namespace, key, value) + } + return ErrRetrieveSegment +} + +// AddError adds an error to the provided segment or subsegment in ctx. +func AddError(ctx context.Context, err error) error { + if seg := GetSegment(ctx); seg != nil { + return seg.AddError(err) + } + return ErrRetrieveSegment +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/default_streaming_strategy.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/default_streaming_strategy.go new file mode 100644 index 00000000..d763d313 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/default_streaming_strategy.go @@ -0,0 +1,81 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "encoding/json" + "errors" + + log "github.com/cihub/seelog" +) + +var defaultMaxSubsegmentCount = 20 + +// DefaultStreamingStrategy provides a default value of 20 +// for the maximum number of subsegments that can be emitted +// in a single UDP packet. +type DefaultStreamingStrategy struct { + MaxSubsegmentCount int +} + +// NewDefaultStreamingStrategy initializes and returns a +// pointer to an instance of DefaultStreamingStrategy. +func NewDefaultStreamingStrategy() (*DefaultStreamingStrategy, error) { + return &DefaultStreamingStrategy{MaxSubsegmentCount: defaultMaxSubsegmentCount}, nil +} + +// NewDefaultStreamingStrategyWithMaxSubsegmentCount initializes +// and returns a pointer to an instance of DefaultStreamingStrategy +// with a custom maximum number of subsegments per UDP packet. +func NewDefaultStreamingStrategyWithMaxSubsegmentCount(maxSubsegmentCount int) (*DefaultStreamingStrategy, error) { + if maxSubsegmentCount <= 0 { + return nil, errors.New("maxSubsegmentCount must be a non-negative integer") + } + return &DefaultStreamingStrategy{MaxSubsegmentCount: maxSubsegmentCount}, nil +} + +// RequiresStreaming returns true when the number of subsegment +// children for a given segment is larger than MaxSubsegmentCount. +func (dSS *DefaultStreamingStrategy) RequiresStreaming(seg *Segment) bool { + if seg.ParentSegment.Sampled { + return seg.ParentSegment.totalSubSegments > dSS.MaxSubsegmentCount + } + return false +} + +// StreamCompletedSubsegments separates subsegments from the provided +// segment tree and sends them to daemon as streamed subsegment UDP packets. +func (dSS *DefaultStreamingStrategy) StreamCompletedSubsegments(seg *Segment) [][]byte { + log.Trace("Beginning to stream subsegments.") + var outSegments [][]byte + for i := 0; i < len(seg.rawSubsegments); i++ { + child := seg.rawSubsegments[i] + seg.rawSubsegments[i] = seg.rawSubsegments[len(seg.rawSubsegments)-1] + seg.rawSubsegments[len(seg.rawSubsegments)-1] = nil + seg.rawSubsegments = seg.rawSubsegments[:len(seg.rawSubsegments)-1] + + seg.Subsegments[i] = seg.Subsegments[len(seg.Subsegments)-1] + seg.Subsegments[len(seg.Subsegments)-1] = nil + seg.Subsegments = seg.Subsegments[:len(seg.Subsegments)-1] + + seg.ParentSegment.totalSubSegments-- + + // Add extra information into child subsegment + child.Lock() + child.beforeEmitSubsegment(seg) + cb, _ := json.Marshal(child) + outSegments = append(outSegments, cb) + log.Tracef("Streaming subsegment named '%s' from segment tree.", child.Name) + child.Unlock() + + break + } + log.Trace("Finished streaming subsegments.") + return outSegments +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/emitter.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/emitter.go new file mode 100644 index 00000000..5f08bbaa --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/emitter.go @@ -0,0 +1,105 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "bytes" + "encoding/json" + "net" + "sync" + + log "github.com/cihub/seelog" +) + +// Header is added before sending segments to daemon. +var Header = []byte(`{"format": "json", "version": 1}` + "\n") + +type emitter struct { + sync.Mutex + conn *net.UDPConn +} + +var e = &emitter{} + +func init() { + initLambda() + refreshEmitter() +} + +func refreshEmitter() { + e.Lock() + e.conn, _ = net.DialUDP("udp", nil, globalCfg.DaemonAddr()) + e.Unlock() +} + +func refreshEmitterWithAddress(raddr *net.UDPAddr) { + e.Lock() + e.conn, _ = net.DialUDP("udp", nil, raddr) + e.Unlock() +} + +// Emit segment or subsegment if root segment is sampled. +func Emit(seg *Segment) { + if seg == nil || !seg.ParentSegment.Sampled { + return + } + + // TODO: going to change our logging framework in next cr. + var logLevel string + if seg.Configuration != nil && seg.Configuration.LogLevel == "trace" { + logLevel = "trace" + } else if globalCfg.logLevel <= log.TraceLvl { + logLevel = "trace" + } + + for _, p := range packSegments(seg, nil) { + if logLevel == "trace" { + b := &bytes.Buffer{} + json.Indent(b, p, "", " ") + log.Trace(b.String()) + } + e.Lock() + _, err := e.conn.Write(append(Header, p...)) + if err != nil { + log.Error(err) + } + e.Unlock() + } +} + +func packSegments(seg *Segment, outSegments [][]byte) [][]byte { + trimSubsegment := func(s *Segment) []byte { + ss := globalCfg.StreamingStrategy() + if seg.ParentSegment.Configuration != nil && seg.ParentSegment.Configuration.StreamingStrategy != nil { + ss = seg.ParentSegment.Configuration.StreamingStrategy + } + for ss.RequiresStreaming(s) { + if len(s.rawSubsegments) == 0 { + break + } + cb := ss.StreamCompletedSubsegments(s) + outSegments = append(outSegments, cb...) + } + b, _ := json.Marshal(s) + return b + } + + for _, s := range seg.rawSubsegments { + outSegments = packSegments(s, outSegments) + if b := trimSubsegment(s); b != nil { + seg.Subsegments = append(seg.Subsegments, b) + } + } + if seg.parent == nil { + if b := trimSubsegment(seg); b != nil { + outSegments = append(outSegments, b) + } + } + return outSegments +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/handler.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/handler.go new file mode 100644 index 00000000..6bd92c2d --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/handler.go @@ -0,0 +1,202 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "bytes" + "context" + "net" + "net/http" + "os" + "strconv" + "strings" + + "github.com/aws/aws-xray-sdk-go/header" + "github.com/aws/aws-xray-sdk-go/pattern" + log "github.com/cihub/seelog" +) + +// SegmentNamer is the interface for naming service node. +type SegmentNamer interface { + Name(host string) string +} + +// FixedSegmentNamer records the fixed name of service node. +type FixedSegmentNamer struct { + FixedName string +} + +// NewFixedSegmentNamer initializes a FixedSegmentNamer which +// will provide a fixed segment name for every generated segment. +// If the AWS_XRAY_TRACING_NAME environment variable is set, +// its value will override the provided name argument. +func NewFixedSegmentNamer(name string) *FixedSegmentNamer { + if fName := os.Getenv("AWS_XRAY_TRACING_NAME"); fName != "" { + name = fName + } + return &FixedSegmentNamer{ + FixedName: name, + } +} + +// Name returns the segment name for the given host header value. +// In this case, FixedName is always returned. +func (fSN *FixedSegmentNamer) Name(host string) string { + return fSN.FixedName +} + +// DynamicSegmentNamer chooses names for segments generated +// for incoming requests by parsing the HOST header of the +// incoming request. If the host header matches a given +// recognized pattern (using the included pattern package), +// it is used as the segment name. Otherwise, the fallback +// name is used. +type DynamicSegmentNamer struct { + FallbackName string + RecognizedHosts string +} + +// NewDynamicSegmentNamer creates a new dynamic segment namer. +func NewDynamicSegmentNamer(fallback string, recognized string) *DynamicSegmentNamer { + if dName := os.Getenv("AWS_XRAY_TRACING_NAME"); dName != "" { + fallback = dName + } + return &DynamicSegmentNamer{ + FallbackName: fallback, + RecognizedHosts: recognized, + } +} + +// Name returns the segment name for the given host header value. +func (dSN *DynamicSegmentNamer) Name(host string) string { + if pattern.WildcardMatchCaseInsensitive(dSN.RecognizedHosts, host) { + return host + } + return dSN.FallbackName +} + +// HandlerWithContext wraps the provided http handler and context to parse +// the incoming headers, add response headers if needed, and sets HTTP +// specific trace fields. HandlerWithContext names the generated segments +// using the provided SegmentNamer. +func HandlerWithContext(ctx context.Context, sn SegmentNamer, h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + name := sn.Name(r.Host) + + traceHeader := header.FromString(r.Header.Get("x-amzn-trace-id")) + + r = r.WithContext(ctx) + c, seg := NewSegmentFromHeader(r.Context(), name, traceHeader) + r = r.WithContext(c) + + httpTrace(seg, h, w, r, traceHeader) + }) +} + +// Handler wraps the provided http handler with xray.Capture +// using the request's context, parsing the incoming headers, +// adding response headers if needed, and sets HTTP specific trace fields. +// Handler names the generated segments using the provided SegmentNamer. +func Handler(sn SegmentNamer, h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + name := sn.Name(r.Host) + + traceHeader := header.FromString(r.Header.Get("x-amzn-trace-id")) + ctx, seg := NewSegmentFromHeader(r.Context(), name, traceHeader) + + r = r.WithContext(ctx) + + httpTrace(seg, h, w, r, traceHeader) + }) +} + +func httpTrace(seg *Segment, h http.Handler, w http.ResponseWriter, r *http.Request, traceHeader *header.Header) { + seg.Lock() + + scheme := "https://" + if r.TLS == nil { + scheme = "http://" + } + seg.GetHTTP().GetRequest().Method = r.Method + seg.GetHTTP().GetRequest().URL = scheme + r.Host + r.URL.Path + seg.GetHTTP().GetRequest().ClientIP, seg.GetHTTP().GetRequest().XForwardedFor = clientIP(r) + seg.GetHTTP().GetRequest().UserAgent = r.UserAgent() + + // Don't use the segment's header here as we only want to + // send back the root and possibly sampled values. + var respHeader bytes.Buffer + respHeader.WriteString("Root=") + respHeader.WriteString(seg.TraceID) + + if traceHeader.SamplingDecision != header.Sampled && traceHeader.SamplingDecision != header.NotSampled { + seg.Sampled = seg.ParentSegment.GetConfiguration().SamplingStrategy.ShouldTrace(r.Host, r.URL.Path, r.Method) + log.Tracef("SamplingStrategy decided: %t", seg.Sampled) + } + if traceHeader.SamplingDecision == header.Requested { + respHeader.WriteString(";Sampled=") + respHeader.WriteString(strconv.Itoa(btoi(seg.Sampled))) + } + + w.Header().Set("x-amzn-trace-id", respHeader.String()) + seg.Unlock() + + resp := &responseCapturer{w, 200, 0} + h.ServeHTTP(resp, r) + + seg.Lock() + seg.GetHTTP().GetResponse().Status = resp.status + seg.GetHTTP().GetResponse().ContentLength, _ = strconv.Atoi(resp.Header().Get("Content-Length")) + + if resp.status >= 400 && resp.status < 500 { + seg.Error = true + } + if resp.status == 429 { + seg.Throttle = true + } + if resp.status >= 500 && resp.status < 600 { + seg.Fault = true + } + seg.Unlock() + seg.Close(nil) +} + +func clientIP(r *http.Request) (string, bool) { + forwardedFor := r.Header.Get("X-Forwarded-For") + if forwardedFor != "" { + return strings.TrimSpace(strings.Split(forwardedFor, ",")[0]), true + } + ip, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr, false + } + return ip, false +} + +type responseCapturer struct { + http.ResponseWriter + status int + length int +} + +func (w *responseCapturer) WriteHeader(status int) { + w.status = status + w.ResponseWriter.WriteHeader(status) +} + +func (w *responseCapturer) Write(data []byte) (int, error) { + w.length += len(data) + return w.ResponseWriter.Write(data) +} + +func btoi(b bool) int { + if b { + return 1 + } + return 0 +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/httptrace.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/httptrace.go new file mode 100644 index 00000000..ade0affd --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/httptrace.go @@ -0,0 +1,216 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +// +build go1.8 + +package xray + +import ( + "context" + "crypto/tls" + "errors" + "net/http/httptrace" +) + +// HTTPSubsegments is a set of context in different HTTP operation. +type HTTPSubsegments struct { + opCtx context.Context + connCtx context.Context + dnsCtx context.Context + connectCtx context.Context + tlsCtx context.Context + reqCtx context.Context + responseCtx context.Context +} + +// NewHTTPSubsegments creates a new HTTPSubsegments to use in +// httptrace.ClientTrace functions +func NewHTTPSubsegments(opCtx context.Context) *HTTPSubsegments { + return &HTTPSubsegments{opCtx: opCtx} +} + +// GetConn begins a connect subsegment if the HTTP operation +// subsegment is still in progress. +func (xt *HTTPSubsegments) GetConn(hostPort string) { + if GetSegment(xt.opCtx).InProgress { + xt.connCtx, _ = BeginSubsegment(xt.opCtx, "connect") + } +} + +// DNSStart begins a dns subsegment if the HTTP operation +// subsegment is still in progress. +func (xt *HTTPSubsegments) DNSStart(info httptrace.DNSStartInfo) { + if GetSegment(xt.opCtx).InProgress { + xt.dnsCtx, _ = BeginSubsegment(xt.connCtx, "dns") + } +} + +// DNSDone closes the dns subsegment if the HTTP operation +// subsegment is still in progress, passing the error value +// (if any). Information about the address values looked up, +// and whether or not the call was coalesced is added as +// metadata to the dns subsegment. +func (xt *HTTPSubsegments) DNSDone(info httptrace.DNSDoneInfo) { + if xt.dnsCtx != nil && GetSegment(xt.opCtx).InProgress { + metadata := make(map[string]interface{}) + metadata["addresses"] = info.Addrs + metadata["coalesced"] = info.Coalesced + + AddMetadataToNamespace(xt.dnsCtx, "http", "dns", metadata) + GetSegment(xt.dnsCtx).Close(info.Err) + } +} + +// ConnectStart begins a dial subsegment if the HTTP operation +// subsegment is still in progress. +func (xt *HTTPSubsegments) ConnectStart(network, addr string) { + if GetSegment(xt.opCtx).InProgress { + xt.connectCtx, _ = BeginSubsegment(xt.connCtx, "dial") + } +} + +// ConnectDone closes the dial subsegment if the HTTP operation +// subsegment is still in progress, passing the error value +// (if any). Information about the network over which the dial +// was made is added as metadata to the subsegment. +func (xt *HTTPSubsegments) ConnectDone(network, addr string, err error) { + if xt.connectCtx != nil && GetSegment(xt.opCtx).InProgress { + metadata := make(map[string]interface{}) + metadata["network"] = network + + AddMetadataToNamespace(xt.connectCtx, "http", "connect", metadata) + GetSegment(xt.connectCtx).Close(err) + } +} + +// TLSHandshakeStart begins a tls subsegment if the HTTP operation +// subsegment is still in progress. +func (xt *HTTPSubsegments) TLSHandshakeStart() { + if GetSegment(xt.opCtx).InProgress { + xt.tlsCtx, _ = BeginSubsegment(xt.connCtx, "tls") + } +} + +// TLSHandshakeDone closes the tls subsegment if the HTTP +// operation subsegment is still in progress, passing the +// error value(if any). Information about the tls connection +// is added as metadata to the subsegment. +func (xt *HTTPSubsegments) TLSHandshakeDone(connState tls.ConnectionState, err error) { + if xt.tlsCtx != nil && GetSegment(xt.opCtx).InProgress { + metadata := make(map[string]interface{}) + metadata["did_resume"] = connState.DidResume + metadata["negotiated_protocol"] = connState.NegotiatedProtocol + metadata["negotiated_protocol_is_mutual"] = connState.NegotiatedProtocolIsMutual + metadata["cipher_suite"] = connState.CipherSuite + + AddMetadataToNamespace(xt.tlsCtx, "http", "tls", metadata) + GetSegment(xt.tlsCtx).Close(err) + } +} + +// GotConn closes the connect subsegment if the HTTP operation +// subsegment is still in progress, passing the error value +// (if any). Information about the connection is added as +// metadata to the subsegment. If the connection is marked as reused, +// the connect subsegment is deleted. +func (xt *HTTPSubsegments) GotConn(info *httptrace.GotConnInfo, err error) { + if xt.connCtx != nil && GetSegment(xt.opCtx).InProgress { // GetConn may not have been called (client_test.TestBadRoundTrip) + if info != nil { + if info.Reused { + GetSegment(xt.opCtx).RemoveSubsegment(GetSegment(xt.connCtx)) + } else { + metadata := make(map[string]interface{}) + metadata["reused"] = info.Reused + metadata["was_idle"] = info.WasIdle + if info.WasIdle { + metadata["idle_time"] = info.IdleTime + } + + AddMetadataToNamespace(xt.connCtx, "http", "connection", metadata) + GetSegment(xt.connCtx).Close(err) + } + } + + if err == nil { + xt.reqCtx, _ = BeginSubsegment(xt.opCtx, "request") + } + + } +} + +// WroteRequest closes the request subsegment if the HTTP operation +// subsegment is still in progress, passing the error value +// (if any). The response subsegment is then begun. +func (xt *HTTPSubsegments) WroteRequest(info httptrace.WroteRequestInfo) { + if xt.reqCtx != nil && GetSegment(xt.opCtx).InProgress { + GetSegment(xt.reqCtx).Close(info.Err) + xt.responseCtx, _ = BeginSubsegment(xt.opCtx, "response") + } +} + +// GotFirstResponseByte closes the response subsegment if the HTTP +// operation subsegment is still in progress. +func (xt *HTTPSubsegments) GotFirstResponseByte() { + if xt.responseCtx != nil && GetSegment(xt.opCtx).InProgress { + GetSegment(xt.responseCtx).Close(nil) + } +} + +// ClientTrace is a set of pointers of HTTPSubsegments and ClientTrace. +type ClientTrace struct { + subsegments *HTTPSubsegments + httpTrace *httptrace.ClientTrace +} + +// NewClientTrace returns an instance of xray.ClientTrace, a wrapper +// around httptrace.ClientTrace. The ClientTrace implementation will +// generate subsegments for connection time, DNS lookup time, TLS +// handshake time, and provides additional information about the HTTP round trip +func NewClientTrace(opCtx context.Context) (ct *ClientTrace, err error) { + if opCtx == nil { + return nil, errors.New("opCtx must be non-nil") + } + + segs := NewHTTPSubsegments(opCtx) + + return &ClientTrace{ + subsegments: segs, + httpTrace: &httptrace.ClientTrace{ + GetConn: func(hostPort string) { + segs.GetConn(hostPort) + }, + DNSStart: func(info httptrace.DNSStartInfo) { + segs.DNSStart(info) + }, + DNSDone: func(info httptrace.DNSDoneInfo) { + segs.DNSDone(info) + }, + ConnectStart: func(network, addr string) { + segs.ConnectStart(network, addr) + }, + ConnectDone: func(network, addr string, err error) { + segs.ConnectDone(network, addr, err) + }, + TLSHandshakeStart: func() { + segs.TLSHandshakeStart() + }, + TLSHandshakeDone: func(connState tls.ConnectionState, err error) { + segs.TLSHandshakeDone(connState, err) + }, + GotConn: func(info httptrace.GotConnInfo) { + segs.GotConn(&info, nil) + }, + WroteRequest: func(info httptrace.WroteRequestInfo) { + segs.WroteRequest(info) + }, + GotFirstResponseByte: func() { + segs.GotFirstResponseByte() + }, + }, + }, nil +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/httptrace_go17.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/httptrace_go17.go new file mode 100644 index 00000000..d6c4bd5e --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/httptrace_go17.go @@ -0,0 +1,184 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +// +build !go1.8 + +package xray + +import ( + "context" + "errors" + "net/http/httptrace" +) + +// HTTPSubsegments is a set of context in different HTTP operation. +type HTTPSubsegments struct { + opCtx context.Context + connCtx context.Context + dnsCtx context.Context + connectCtx context.Context + tlsCtx context.Context + reqCtx context.Context + responseCtx context.Context +} + +// NewHTTPSubsegments creates a new HTTPSubsegments to use in +// httptrace.ClientTrace functions +func NewHTTPSubsegments(opCtx context.Context) *HTTPSubsegments { + return &HTTPSubsegments{opCtx: opCtx} +} + +// GetConn begins a connect subsegment if the HTTP operation +// subsegment is still in progress. +func (xt *HTTPSubsegments) GetConn(hostPort string) { + if GetSegment(xt.opCtx).InProgress { + xt.connCtx, _ = BeginSubsegment(xt.opCtx, "connect") + } +} + +// DNSStart begins a dns subsegment if the HTTP operation +// subsegment is still in progress. +func (xt *HTTPSubsegments) DNSStart(info httptrace.DNSStartInfo) { + if GetSegment(xt.opCtx).InProgress { + xt.dnsCtx, _ = BeginSubsegment(xt.connCtx, "dns") + } +} + +// DNSDone closes the dns subsegment if the HTTP operation +// subsegment is still in progress, passing the error value +// (if any). Information about the address values looked up, +// and whether or not the call was coalesced is added as +// metadata to the dns subsegment. +func (xt *HTTPSubsegments) DNSDone(info httptrace.DNSDoneInfo) { + if xt.dnsCtx != nil && GetSegment(xt.opCtx).InProgress { + metadata := make(map[string]interface{}) + metadata["addresses"] = info.Addrs + metadata["coalesced"] = info.Coalesced + + AddMetadataToNamespace(xt.dnsCtx, "http", "dns", metadata) + GetSegment(xt.dnsCtx).Close(info.Err) + } +} + +// ConnectStart begins a dial subsegment if the HTTP operation +// subsegment is still in progress. +func (xt *HTTPSubsegments) ConnectStart(network, addr string) { + if GetSegment(xt.opCtx).InProgress { + xt.connectCtx, _ = BeginSubsegment(xt.connCtx, "dial") + } +} + +// ConnectDone closes the dial subsegment if the HTTP operation +// subsegment is still in progress, passing the error value +// (if any). Information about the network over which the dial +// was made is added as metadata to the subsegment. +func (xt *HTTPSubsegments) ConnectDone(network, addr string, err error) { + if xt.connectCtx != nil && GetSegment(xt.opCtx).InProgress { + metadata := make(map[string]interface{}) + metadata["network"] = network + + AddMetadataToNamespace(xt.connectCtx, "http", "connect", metadata) + GetSegment(xt.connectCtx).Close(err) + } +} + +// GotConn closes the connect subsegment if the HTTP operation +// subsegment is still in progress, passing the error value +// (if any). Information about the connection is added as +// metadata to the subsegment. If the connection is marked as reused, +// the connect subsegment is deleted. +func (xt *HTTPSubsegments) GotConn(info *httptrace.GotConnInfo, err error) { + if xt.connCtx != nil && GetSegment(xt.opCtx).InProgress { // GetConn may not have been called (client_test.TestBadRoundTrip) + if info != nil { + if info.Reused { + GetSegment(xt.opCtx).RemoveSubsegment(GetSegment(xt.connCtx)) + } else { + metadata := make(map[string]interface{}) + metadata["reused"] = info.Reused + metadata["was_idle"] = info.WasIdle + if info.WasIdle { + metadata["idle_time"] = info.IdleTime + } + + AddMetadataToNamespace(xt.connCtx, "http", "connection", metadata) + GetSegment(xt.connCtx).Close(err) + } + } + + if err == nil { + xt.reqCtx, _ = BeginSubsegment(xt.opCtx, "request") + } + + } +} + +// WroteRequest closes the request subsegment if the HTTP operation +// subsegment is still in progress, passing the error value +// (if any). The response subsegment is then begun. +func (xt *HTTPSubsegments) WroteRequest(info httptrace.WroteRequestInfo) { + if xt.reqCtx != nil && GetSegment(xt.opCtx).InProgress { + GetSegment(xt.reqCtx).Close(info.Err) + xt.responseCtx, _ = BeginSubsegment(xt.opCtx, "response") + } +} + +// GotFirstResponseByte closes the response subsegment if the HTTP +// operation subsegment is still in progress. +func (xt *HTTPSubsegments) GotFirstResponseByte() { + if xt.responseCtx != nil && GetSegment(xt.opCtx).InProgress { + GetSegment(xt.responseCtx).Close(nil) + } +} + +// ClientTrace is a set of pointers of HTTPSubsegments and ClientTrace. +type ClientTrace struct { + subsegments *HTTPSubsegments + httpTrace *httptrace.ClientTrace +} + +// NewClientTrace returns an instance of xray.ClientTrace, a wrapper +// around httptrace.ClientTrace. The ClientTrace implementation will +// generate subsegments for connection time, DNS lookup time, TLS +// handshake time, and provides additional information about the HTTP round trip +func NewClientTrace(opCtx context.Context) (ct *ClientTrace, err error) { + if opCtx == nil { + return nil, errors.New("opCtx must be non-nil") + } + + segs := NewHTTPSubsegments(opCtx) + + return &ClientTrace{ + subsegments: segs, + httpTrace: &httptrace.ClientTrace{ + GetConn: func(hostPort string) { + segs.GetConn(hostPort) + }, + DNSStart: func(info httptrace.DNSStartInfo) { + segs.DNSStart(info) + }, + DNSDone: func(info httptrace.DNSDoneInfo) { + segs.DNSDone(info) + }, + ConnectStart: func(network, addr string) { + segs.ConnectStart(network, addr) + }, + ConnectDone: func(network, addr string, err error) { + segs.ConnectDone(network, addr, err) + }, + GotConn: func(info httptrace.GotConnInfo) { + segs.GotConn(&info, nil) + }, + WroteRequest: func(info httptrace.WroteRequestInfo) { + segs.WroteRequest(info) + }, + GotFirstResponseByte: func() { + segs.GotFirstResponseByte() + }, + }, + }, nil +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/lambda.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/lambda.go new file mode 100644 index 00000000..fe2e3529 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/lambda.go @@ -0,0 +1,92 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "context" + "os" + "path/filepath" + "time" + + "github.com/aws/aws-xray-sdk-go/header" + log "github.com/cihub/seelog" +) + +// LambdaTraceHeaderKey is key to get trace header from context. +const LambdaTraceHeaderKey string = "x-amzn-trace-id" + +// LambdaTaskRootKey is the key to get Lambda Task Root from environment variable. +const LambdaTaskRootKey string = "LAMBDA_TASK_ROOT" + +// SDKInitializedFileFolder records the location of SDK initialized file. +const SDKInitializedFileFolder string = "/tmp/.aws-xray" + +// SDKInitializedFileName records the SDK initialized file name. +const SDKInitializedFileName string = "initialized" + +func getTraceHeaderFromContext(ctx context.Context) *header.Header { + var traceHeader string + + if traceHeaderValue := ctx.Value(LambdaTraceHeaderKey); traceHeaderValue != nil { + traceHeader = traceHeaderValue.(string) + return header.FromString(traceHeader) + } + return nil +} + +func newFacadeSegment(ctx context.Context) (context.Context, *Segment) { + traceHeader := getTraceHeaderFromContext(ctx) + return BeginFacadeSegment(ctx, "facade", traceHeader) +} + +func getLambdaTaskRoot() string { + return os.Getenv(LambdaTaskRootKey) +} + +func initLambda() { + if getLambdaTaskRoot() != "" { + now := time.Now() + filePath, err := createFile(SDKInitializedFileFolder, SDKInitializedFileName) + if err != nil { + log.Tracef("unable to create file at %s. failed to signal SDK initialization with error: %v", filePath, err) + } else { + e := os.Chtimes(filePath, now, now) + if e != nil { + log.Tracef("unable to write to %s. failed to signal SDK initialization with error: %v", filePath, e) + } + } + } +} + +func createFile(dir string, name string) (string, error) { + fileDir := filepath.FromSlash(dir) + filePath := fileDir + string(os.PathSeparator) + name + + // detect if file exists + var _, err = os.Stat(filePath) + + // create file if not exists + if os.IsNotExist(err) { + e := os.MkdirAll(dir, os.ModePerm) + if e != nil { + return filePath, e + } else { + var file, err = os.Create(filePath) + if err != nil { + return filePath, err + } + file.Close() + return filePath, nil + } + } else if err != nil { + return filePath, err + } + + return filePath, nil +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/segment.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/segment.go new file mode 100644 index 00000000..baef7ce8 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/segment.go @@ -0,0 +1,427 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "context" + "crypto/rand" + "fmt" + "os" + "runtime" + "time" + + "github.com/aws/aws-xray-sdk-go/header" + "github.com/aws/aws-xray-sdk-go/internal/plugins" + log "github.com/cihub/seelog" +) + +// NewTraceID generates a string format of random trace ID. +func NewTraceID() string { + var r [12]byte + _, err := rand.Read(r[:]) + if err != nil { + panic(err) + } + return fmt.Sprintf("1-%08x-%02x", time.Now().Unix(), r) +} + +// NewSegmentID generates a string format of segment ID. +func NewSegmentID() string { + var r [8]byte + _, err := rand.Read(r[:]) + if err != nil { + panic(err) + } + return fmt.Sprintf("%02x", r) +} + +// BeginFacadeSegment creates a Segment for a given name and context. +func BeginFacadeSegment(ctx context.Context, name string, h *header.Header) (context.Context, *Segment) { + seg := basicSegment(name, h) + + cfg := GetRecorder(ctx) + seg.assignConfiguration(cfg) + + return context.WithValue(ctx, ContextKey, seg), seg +} + +// BeginSegment creates a Segment for a given name and context. +func BeginSegment(ctx context.Context, name string) (context.Context, *Segment) { + seg := basicSegment(name, nil) + + cfg := GetRecorder(ctx) + seg.assignConfiguration(cfg) + + seg.Lock() + defer seg.Unlock() + + seg.addPlugin(plugins.InstancePluginMetadata) + seg.addSDKAndServiceInformation() + if seg.ParentSegment.GetConfiguration().ServiceVersion != "" { + seg.GetService().Version = seg.ParentSegment.GetConfiguration().ServiceVersion + } + + go func() { + select { + case <-ctx.Done(): + seg.handleContextDone() + } + }() + + return context.WithValue(ctx, ContextKey, seg), seg +} + +func basicSegment(name string, h *header.Header) *Segment { + if len(name) > 200 { + name = name[:200] + } + seg := &Segment{parent: nil} + log.Tracef("Beginning segment named %s", name) + seg.ParentSegment = seg + + seg.Lock() + defer seg.Unlock() + + seg.Name = name + seg.StartTime = float64(time.Now().UnixNano()) / float64(time.Second) + seg.InProgress = true + + if h == nil { + seg.TraceID = NewTraceID() + seg.ID = NewSegmentID() + seg.Sampled = true + } else { + seg.Facade = true + seg.ID = h.ParentID + seg.TraceID = h.TraceID + seg.Sampled = h.SamplingDecision == header.Sampled + } + + return seg +} + +// assignConfiguration assigns value to seg.Configuration +func (seg *Segment) assignConfiguration(cfg *Config) { + seg.Lock() + if cfg == nil { + seg.GetConfiguration().ContextMissingStrategy = globalCfg.contextMissingStrategy + seg.GetConfiguration().ExceptionFormattingStrategy = globalCfg.exceptionFormattingStrategy + seg.GetConfiguration().SamplingStrategy = globalCfg.samplingStrategy + seg.GetConfiguration().StreamingStrategy = globalCfg.streamingStrategy + seg.GetConfiguration().ServiceVersion = globalCfg.serviceVersion + } else { + if cfg.ContextMissingStrategy != nil { + seg.GetConfiguration().ContextMissingStrategy = cfg.ContextMissingStrategy + } else { + seg.GetConfiguration().ContextMissingStrategy = globalCfg.contextMissingStrategy + } + + if cfg.ExceptionFormattingStrategy != nil { + seg.GetConfiguration().ExceptionFormattingStrategy = cfg.ExceptionFormattingStrategy + } else { + seg.GetConfiguration().ExceptionFormattingStrategy = globalCfg.exceptionFormattingStrategy + } + + if cfg.SamplingStrategy != nil { + seg.GetConfiguration().SamplingStrategy = cfg.SamplingStrategy + } else { + seg.GetConfiguration().SamplingStrategy = globalCfg.samplingStrategy + } + + if cfg.StreamingStrategy != nil { + seg.GetConfiguration().StreamingStrategy = cfg.StreamingStrategy + } else { + seg.GetConfiguration().StreamingStrategy = globalCfg.streamingStrategy + } + + if cfg.ServiceVersion != "" { + seg.GetConfiguration().ServiceVersion = cfg.ServiceVersion + } else { + seg.GetConfiguration().ServiceVersion = globalCfg.serviceVersion + } + } + seg.Unlock() +} + +// BeginSubsegment creates a subsegment for a given name and context. +func BeginSubsegment(ctx context.Context, name string) (context.Context, *Segment) { + if len(name) > 200 { + name = name[:200] + } + + parent := &Segment{} + // first time to create facade segment + if getTraceHeaderFromContext(ctx) != nil && GetSegment(ctx) == nil { + _, parent = newFacadeSegment(ctx) + } else { + parent = GetSegment(ctx) + if parent == nil { + cfg := GetRecorder(ctx) + failedMessage := fmt.Sprintf("failed to begin subsegment named '%v': segment cannot be found.", name) + if cfg != nil && cfg.ContextMissingStrategy != nil { + cfg.ContextMissingStrategy.ContextMissing(failedMessage) + } else { + globalCfg.ContextMissingStrategy().ContextMissing(failedMessage) + } + return ctx, nil + } + } + + seg := &Segment{parent: parent} + log.Tracef("Beginning subsegment named %s", name) + + seg.Lock() + defer seg.Unlock() + + parent.Lock() + seg.ParentSegment = parent.ParentSegment + seg.ParentSegment.totalSubSegments++ + parent.rawSubsegments = append(parent.rawSubsegments, seg) + parent.openSegments++ + parent.Unlock() + + seg.ID = NewSegmentID() + seg.Name = name + seg.StartTime = float64(time.Now().UnixNano()) / float64(time.Second) + seg.InProgress = true + + return context.WithValue(ctx, ContextKey, seg), seg +} + +// NewSegmentFromHeader creates a segment for downstream call and add information to the segment that gets from HTTP header. +func NewSegmentFromHeader(ctx context.Context, name string, h *header.Header) (context.Context, *Segment) { + con, seg := BeginSegment(ctx, name) + + if h.TraceID != "" { + seg.TraceID = h.TraceID + } + if h.ParentID != "" { + seg.ParentID = h.ParentID + } + + seg.Sampled = h.SamplingDecision == header.Sampled + switch h.SamplingDecision { + case header.Sampled: + log.Trace("Incoming header decided: Sampled=true") + case header.NotSampled: + log.Trace("Incoming header decided: Sampled=false") + } + + seg.IncomingHeader = h + seg.RequestWasTraced = true + + return con, seg +} + +// Close a segment. +func (seg *Segment) Close(err error) { + seg.Lock() + defer seg.Unlock() + if seg.parent != nil { + log.Tracef("Closing subsegment named %s", seg.Name) + } else { + log.Tracef("Closing segment named %s", seg.Name) + } + seg.EndTime = float64(time.Now().UnixNano()) / float64(time.Second) + seg.InProgress = false + + if err != nil { + seg.addError(err) + } + + seg.flush() +} + +// CloseAndStream closes a subsegment and sends it. +func (subseg *Segment) CloseAndStream(err error) { + subseg.Lock() + + if subseg.parent != nil { + log.Tracef("Ending subsegment named: %s", subseg.Name) + subseg.EndTime = float64(time.Now().UnixNano()) / float64(time.Second) + subseg.InProgress = false + subseg.Emitted = true + if subseg.parent.RemoveSubsegment(subseg) { + log.Tracef("Removing subsegment named: %s", subseg.Name) + } + } + + if err != nil { + subseg.addError(err) + } + + subseg.beforeEmitSubsegment(subseg.parent) + subseg.Unlock() + + Emit(subseg) +} + +// RemoveSubsegment removes a subsegment child from a segment or subsegment. +func (seg *Segment) RemoveSubsegment(remove *Segment) bool { + seg.Lock() + defer seg.Unlock() + + for i, v := range seg.rawSubsegments { + if v == remove { + seg.rawSubsegments[i] = seg.rawSubsegments[len(seg.rawSubsegments)-1] + seg.rawSubsegments[len(seg.rawSubsegments)-1] = nil + seg.rawSubsegments = seg.rawSubsegments[:len(seg.rawSubsegments)-1] + + seg.totalSubSegments-- + seg.openSegments-- + return true + } + } + return false +} + +func (seg *Segment) handleContextDone() { + seg.Lock() + defer seg.Unlock() + + seg.ContextDone = true + if !seg.InProgress && !seg.Emitted { + seg.flush() + } +} + +func (seg *Segment) flush() { + if (seg.openSegments == 0 && seg.EndTime > 0) || seg.ContextDone { + if seg.parent == nil { + seg.Emitted = true + Emit(seg) + } else if seg.parent != nil && seg.parent.Facade { + seg.Emitted = true + seg.beforeEmitSubsegment(seg.parent) + log.Tracef("emit lambda subsegment named: %v", seg.Name) + Emit(seg) + } else { + seg.parent.safeFlush() + } + } +} + +func (seg *Segment) safeFlush() { + seg.Lock() + defer seg.Unlock() + seg.openSegments-- + seg.flush() +} + +func (seg *Segment) root() *Segment { + if seg.parent == nil { + return seg + } + return seg.parent.root() +} + +func (seg *Segment) addPlugin(metadata *plugins.PluginMetadata) { + // Only called within a seg locked code block + if metadata == nil { + return + } + + if metadata.EC2Metadata != nil { + seg.GetAWS()[plugins.EC2ServiceName] = metadata.EC2Metadata + } + + if metadata.ECSMetadata != nil { + seg.GetAWS()[plugins.ECSServiceName] = metadata.ECSMetadata + } + + if metadata.BeanstalkMetadata != nil { + seg.GetAWS()[plugins.EBServiceName] = metadata.BeanstalkMetadata + } + + if metadata.Origin != "" { + seg.Origin = metadata.Origin + } +} + +func (seg *Segment) addSDKAndServiceInformation() { + seg.GetAWS()["xray"] = SDK{Version: SDKVersion, Type: SDKType} + + seg.GetService().Compiler = runtime.Compiler + seg.GetService().CompilerVersion = runtime.Version() +} + +func (sub *Segment) beforeEmitSubsegment(seg *Segment) { + // Only called within a subsegment locked code block + sub.TraceID = seg.root().TraceID + sub.ParentID = seg.ID + sub.Type = "subsegment" + sub.RequestWasTraced = seg.RequestWasTraced + sub.parent = nil +} + +// AddAnnotation allows adding an annotation to the segment. +func (seg *Segment) AddAnnotation(key string, value interface{}) error { + switch value.(type) { + case bool, int, uint, float32, float64, string: + default: + return fmt.Errorf("failed to add annotation key: %q value: %q to subsegment %q. value must be of type string, number or boolean", key, value, seg.Name) + } + + seg.Lock() + defer seg.Unlock() + + if seg.Annotations == nil { + seg.Annotations = map[string]interface{}{} + } + seg.Annotations[key] = value + return nil +} + +// AddMetadata allows adding metadata to the segment. +func (seg *Segment) AddMetadata(key string, value interface{}) error { + seg.Lock() + defer seg.Unlock() + + if seg.Metadata == nil { + seg.Metadata = map[string]map[string]interface{}{} + } + if seg.Metadata["default"] == nil { + seg.Metadata["default"] = map[string]interface{}{} + } + seg.Metadata["default"][key] = value + return nil +} + +// AddMetadataToNamespace allows adding a namespace into metadata for the segment. +func (seg *Segment) AddMetadataToNamespace(namespace string, key string, value interface{}) error { + seg.Lock() + defer seg.Unlock() + + if seg.Metadata == nil { + seg.Metadata = map[string]map[string]interface{}{} + } + if seg.Metadata[namespace] == nil { + seg.Metadata[namespace] = map[string]interface{}{} + } + seg.Metadata[namespace][key] = value + return nil +} + +// AddError allows adding an error to the segment. +func (seg *Segment) AddError(err error) error { + seg.Lock() + defer seg.Unlock() + + seg.addError(err) + + return nil +} + +func (seg *Segment) addError(err error) error { + seg.Fault = true + seg.GetCause().WorkingDirectory, _ = os.Getwd() + seg.GetCause().Exceptions = append(seg.GetCause().Exceptions, seg.ParentSegment.GetConfiguration().ExceptionFormattingStrategy.ExceptionFromError(err)) + + return nil +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/segment_model.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/segment_model.go new file mode 100644 index 00000000..aa3d3f2a --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/segment_model.go @@ -0,0 +1,207 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "encoding/json" + "sync" + + "github.com/aws/aws-xray-sdk-go/header" + "github.com/aws/aws-xray-sdk-go/strategy/exception" +) + +// Segment provides the resource's name, details about the request, and details about the work done. +type Segment struct { + sync.Mutex + parent *Segment + openSegments int + totalSubSegments int + Sampled bool `json:"-"` + RequestWasTraced bool `json:"-"` // Used by xray.RequestWasTraced + ContextDone bool `json:"-"` + Emitted bool `json:"-"` + IncomingHeader *header.Header `json:"-"` + ParentSegment *Segment `json:"-"` // The root of the Segment tree, the parent Segment (not Subsegment). + + // Required + TraceID string `json:"trace_id,omitempty"` + ID string `json:"id"` + Name string `json:"name"` + StartTime float64 `json:"start_time"` + EndTime float64 `json:"end_time,omitempty"` + + // Optional + InProgress bool `json:"in_progress,omitempty"` + ParentID string `json:"parent_id,omitempty"` + Fault bool `json:"fault,omitempty"` + Error bool `json:"error,omitempty"` + Throttle bool `json:"throttle,omitempty"` + Cause *CauseData `json:"cause,omitempty"` + ResourceARN string `json:"resource_arn,omitempty"` + Origin string `json:"origin,omitempty"` + + Type string `json:"type,omitempty"` + Namespace string `json:"namespace,omitempty"` + User string `json:"user,omitempty"` + PrecursorIDs []string `json:"precursor_ids,omitempty"` + + HTTP *HTTPData `json:"http,omitempty"` + AWS map[string]interface{} `json:"aws,omitempty"` + + Service *ServiceData `json:"service,omitempty"` + + // SQL + SQL *SQLData `json:"sql,omitempty"` + + // Metadata + Annotations map[string]interface{} `json:"annotations,omitempty"` + Metadata map[string]map[string]interface{} `json:"metadata,omitempty"` + + // Children + Subsegments []json.RawMessage `json:"subsegments,omitempty"` + rawSubsegments []*Segment + + // Configuration + Configuration *Config `json:"-"` + + // Lambda + Facade bool `json:"-"` +} + +// CauseData provides the shape for unmarshalling data that records exception. +type CauseData struct { + WorkingDirectory string `json:"working_directory,omitempty"` + Paths []string `json:"paths,omitempty"` + Exceptions []exception.Exception `json:"exceptions,omitempty"` +} + +// HTTPData provides the shape for unmarshalling request and response data. +type HTTPData struct { + Request *RequestData `json:"request,omitempty"` + Response *ResponseData `json:"response,omitempty"` +} + +// RequestData provides the shape for unmarshalling request data. +type RequestData struct { + Method string `json:"method,omitempty"` + URL string `json:"url,omitempty"` // http(s)://host/path + ClientIP string `json:"client_ip,omitempty"` + UserAgent string `json:"user_agent,omitempty"` + XForwardedFor bool `json:"x_forwarded_for,omitempty"` + Traced bool `json:"traced,omitempty"` +} + +// ResponseData provides the shape for unmarshalling response data. +type ResponseData struct { + Status int `json:"status,omitempty"` + ContentLength int `json:"content_length,omitempty"` +} + +// ServiceData provides the shape for unmarshalling service version. +type ServiceData struct { + Version string `json:"version,omitempty"` + CompilerVersion string `json:"compiler_version,omitempty"` + Compiler string `json:"compiler,omitempty"` +} + +// SQLData provides the shape for unmarshalling sql data. +type SQLData struct { + ConnectionString string `json:"connection_string,omitempty"` + URL string `json:"url,omitempty"` // host:port/database + DatabaseType string `json:"database_type,omitempty"` + DatabaseVersion string `json:"database_version,omitempty"` + DriverVersion string `json:"driver_version,omitempty"` + User string `json:"user,omitempty"` + Preparation string `json:"preparation,omitempty"` // "statement" / "call" + SanitizedQuery string `json:"sanitized_query,omitempty"` +} + +// DownstreamHeader returns a header for passing to downstream calls. +func (s *Segment) DownstreamHeader() *header.Header { + r := s.ParentSegment.IncomingHeader + if r == nil { + r = &header.Header{ + TraceID: s.ParentSegment.TraceID, + } + } + if r.TraceID == "" { + r.TraceID = s.ParentSegment.TraceID + } + if s.ParentSegment.Sampled { + r.SamplingDecision = header.Sampled + } else { + r.SamplingDecision = header.NotSampled + } + r.ParentID = s.ID + return r +} + +// GetCause returns value of Cause. +func (s *Segment) GetCause() *CauseData { + if s.Cause == nil { + s.Cause = &CauseData{} + } + return s.Cause +} + +// GetHTTP returns value of HTTP. +func (s *Segment) GetHTTP() *HTTPData { + if s.HTTP == nil { + s.HTTP = &HTTPData{} + } + return s.HTTP +} + +// GetAWS returns value of AWS. +func (s *Segment) GetAWS() map[string]interface{} { + if s.AWS == nil { + s.AWS = make(map[string]interface{}) + } + return s.AWS +} + +// GetService returns value of Service. +func (s *Segment) GetService() *ServiceData { + if s.Service == nil { + s.Service = &ServiceData{} + } + return s.Service +} + +// GetSQL returns value of SQL. +func (s *Segment) GetSQL() *SQLData { + if s.SQL == nil { + s.SQL = &SQLData{} + } + return s.SQL +} + +// GetRequest returns value of RequestData. +func (d *HTTPData) GetRequest() *RequestData { + if d.Request == nil { + d.Request = &RequestData{} + } + return d.Request +} + +// GetResponse returns value of ResponseData. +func (d *HTTPData) GetResponse() *ResponseData { + if d.Response == nil { + d.Response = &ResponseData{} + } + return d.Response +} + +// GetConfiguration returns a value of Config. +func (s *Segment) GetConfiguration() *Config { + if s.Configuration == nil { + s.Configuration = &Config{} + } + return s.Configuration +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/sql.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/sql.go new file mode 100644 index 00000000..d463672f --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/sql.go @@ -0,0 +1,274 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +import ( + "bytes" + "context" + "database/sql" + "database/sql/driver" + "fmt" + "net/url" + "reflect" + "strings" + "time" +) + +// SQL opens a normalized and traced wrapper around an *sql.DB connection. +// It uses `sql.Open` internally and shares the same function signature. +// To ensure passwords are filtered, it is HIGHLY RECOMMENDED that your DSN +// follows the format: `://:@:/` +func SQL(driver, dsn string) (*DB, error) { + rawDB, err := sql.Open(driver, dsn) + if err != nil { + return nil, err + } + + db := &DB{db: rawDB} + + // Detect if DSN is a URL or not, set appropriate attribute + urlDsn := dsn + if !strings.Contains(dsn, "//") { + urlDsn = "//" + urlDsn + } + // Here we're trying to detect things like `host:port/database` as a URL, which is pretty hard + // So we just assume that if it's got a scheme, a user, or a query that it's probably a URL + if u, err := url.Parse(urlDsn); err == nil && (u.Scheme != "" || u.User != nil || u.RawQuery != "" || strings.Contains(u.Path, "@")) { + // Check that this isn't in the form of user/pass@host:port/db, as that will shove the host into the path + if strings.Contains(u.Path, "@") { + u, _ = url.Parse(fmt.Sprintf("%s//%s%%2F%s", u.Scheme, u.Host, u.Path[1:])) + } + + // Strip password from user:password pair in address + if u.User != nil { + uname := u.User.Username() + + // Some drivers use "user/pass@host:port" instead of "user:pass@host:port" + // So we must manually attempt to chop off a potential password. + // But we can skip this if we already found the password. + if _, ok := u.User.Password(); !ok { + uname = strings.Split(uname, "/")[0] + } + + u.User = url.User(uname) + } + + // Strip password from query parameters + q := u.Query() + q.Del("password") + u.RawQuery = q.Encode() + + db.url = u.String() + if !strings.Contains(dsn, "//") { + db.url = db.url[2:] + } + } else { + // We don't *think* it's a URL, so now we have to try our best to strip passwords from + // some unknown DSL. We attempt to detect whether it's space-delimited or semicolon-delimited + // then remove any keys with the name "password" or "pwd". This won't catch everything, but + // from surveying the current (Jan 2017) landscape of drivers it should catch most. + db.connectionString = stripPasswords(dsn) + } + + // Detect database type and use that to populate attributes + var detectors []func(*DB) error + switch driver { + case "postgres": + detectors = append(detectors, postgresDetector) + case "mysql": + detectors = append(detectors, mysqlDetector) + default: + detectors = append(detectors, postgresDetector, mysqlDetector, mssqlDetector, oracleDetector) + } + for _, detector := range detectors { + if detector(db) == nil { + break + } + db.databaseType = "Unknown" + db.databaseVersion = "Unknown" + db.user = "Unknown" + db.dbname = "Unknown" + } + + // There's no standard to get SQL driver version information + // So we invent an interface by which drivers can provide us this data + type versionedDriver interface { + Version() string + } + + d := db.db.Driver() + if vd, ok := d.(versionedDriver); ok { + db.driverVersion = vd.Version() + } else { + t := reflect.TypeOf(d) + for t.Kind() == reflect.Ptr { + t = t.Elem() + } + db.driverVersion = t.PkgPath() + } + + return db, nil +} + +// DB copies the interface of sql.DB but adds X-Ray tracing. +// It must be created with xray.SQL. +type DB struct { + db *sql.DB + + connectionString string + url string + databaseType string + databaseVersion string + driverVersion string + user string + dbname string +} + +// Close closes a database and returns error if any. +func (db *DB) Close() error { return db.db.Close() } + +// Driver returns database's underlying driver. +func (db *DB) Driver() driver.Driver { return db.db.Driver() } + +// Stats returns database statistics. +func (db *DB) Stats() sql.DBStats { return db.db.Stats() } + +// SetConnMaxLifetime sets the maximum amount of time a connection may be reused. +func (db *DB) SetConnMaxLifetime(d time.Duration) { db.db.SetConnMaxLifetime(d) } + +// SetMaxIdleConns sets the maximum number of connections in the idle connection pool. +func (db *DB) SetMaxIdleConns(n int) { db.db.SetMaxIdleConns(n) } + +// SetMaxOpenConns sets the maximum number of open connections to the database. +func (db *DB) SetMaxOpenConns(n int) { db.db.SetMaxOpenConns(n) } + +func (db *DB) populate(ctx context.Context, query string) { + seg := GetSegment(ctx) + + seg.Lock() + seg.Namespace = "remote" + seg.GetSQL().ConnectionString = db.connectionString + seg.GetSQL().URL = db.url + seg.GetSQL().DatabaseType = db.databaseType + seg.GetSQL().DatabaseVersion = db.databaseVersion + seg.GetSQL().DriverVersion = db.driverVersion + seg.GetSQL().User = db.user + seg.GetSQL().SanitizedQuery = query + seg.Unlock() +} + +// Tx copies the interface of sql.Tx but adds X-Ray tracing. +// It must be created with xray.DB.Begin. +type Tx struct { + db *DB + tx *sql.Tx +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { return tx.tx.Commit() } + +// Rollback aborts the transaction. +func (tx *Tx) Rollback() error { return tx.tx.Rollback() } + +// Stmt copies the interface of sql.Stmt but adds X-Ray tracing. +// It must be created with xray.DB.Prepare or xray.Tx.Stmt. +type Stmt struct { + db *DB + stmt *sql.Stmt + query string +} + +// Close closes the statement. +func (stmt *Stmt) Close() error { return stmt.stmt.Close() } + +func (stmt *Stmt) populate(ctx context.Context, query string) { + stmt.db.populate(ctx, query) + + seg := GetSegment(ctx) + seg.Lock() + seg.GetSQL().Preparation = "statement" + seg.Unlock() +} + +func postgresDetector(db *DB) error { + db.databaseType = "Postgres" + row := db.db.QueryRow("SELECT version(), current_user, current_database()") + return row.Scan(&db.databaseVersion, &db.user, &db.dbname) +} + +func mysqlDetector(db *DB) error { + db.databaseType = "MySQL" + row := db.db.QueryRow("SELECT version(), current_user(), database()") + return row.Scan(&db.databaseVersion, &db.user, &db.dbname) +} + +func mssqlDetector(db *DB) error { + db.databaseType = "MS SQL" + row := db.db.QueryRow("SELECT @@version, current_user, db_name()") + return row.Scan(&db.databaseVersion, &db.user, &db.dbname) +} + +func oracleDetector(db *DB) error { + db.databaseType = "Oracle" + row := db.db.QueryRow("SELECT version FROM v$instance UNION SELECT user, ora_database_name FROM dual") + return row.Scan(&db.databaseVersion, &db.user, &db.dbname) +} + +func stripPasswords(dsn string) string { + var ( + tok bytes.Buffer + res bytes.Buffer + isPassword bool + inBraces bool + delimiter byte = ' ' + ) + flush := func() { + if inBraces { + return + } + if !isPassword { + res.Write(tok.Bytes()) + } + tok.Reset() + isPassword = false + } + if strings.Count(dsn, ";") > strings.Count(dsn, " ") { + delimiter = ';' + } + + buf := strings.NewReader(dsn) + for c, err := buf.ReadByte(); err == nil; c, err = buf.ReadByte() { + tok.WriteByte(c) + switch c { + case ':', delimiter: + flush() + case '=': + tokStr := strings.ToLower(tok.String()) + isPassword = `password=` == tokStr || `pwd=` == tokStr + if b, err := buf.ReadByte(); err == nil && b == '{' { + inBraces = true + } + buf.UnreadByte() + case '}': + b, err := buf.ReadByte() + if err != nil { + break + } + if b == '}' { + tok.WriteByte(b) + } else { + inBraces = false + buf.UnreadByte() + } + } + } + inBraces = false + flush() + return res.String() +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/sql_go17.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/sql_go17.go new file mode 100644 index 00000000..2690e001 --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/sql_go17.go @@ -0,0 +1,183 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +// +build !go1.8 + +package xray + +import ( + "context" + "database/sql" +) + +// Begin starts a transaction. +func (db *DB) Begin(ctx context.Context, opts interface{}) (*Tx, error) { + tx, err := db.db.Begin() + return &Tx{db, tx}, err +} + +// Prepare creates a prepared statement for later queries or executions. +func (db *DB) Prepare(ctx context.Context, query string) (*Stmt, error) { + stmt, err := db.db.Prepare(query) + return &Stmt{db, stmt, query}, err +} + +// Ping traces verifying a connection to the database is still alive, +// establishing a connection if necessary and adds corresponding information into subsegment. +func (db *DB) Ping(ctx context.Context) error { + return Capture(ctx, db.dbname, func(ctx context.Context) error { + db.populate(ctx, "PING") + return db.db.Ping() + }) +} + +// Exec captures executing a query without returning any rows and +// adds corresponding information into subsegment. +func (db *DB) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + var res sql.Result + + err := Capture(ctx, db.dbname, func(ctx context.Context) error { + db.populate(ctx, query) + + var err error + res, err = db.db.Exec(query, args...) + return err + }) + + return res, err +} + +// Query captures executing a query that returns rows and adds corresponding information into subsegment. +func (db *DB) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { + var res *sql.Rows + + err := Capture(ctx, db.dbname, func(ctx context.Context) error { + db.populate(ctx, query) + + var err error + res, err = db.db.Query(query, args...) + return err + }) + + return res, err +} + +// QueryRow captures executing a query that is expected to return at most one row +// and adds corresponding information into subsegment. +func (db *DB) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row { + var res *sql.Row + + Capture(ctx, db.dbname, func(ctx context.Context) error { + db.populate(ctx, query) + + res = db.db.QueryRow(query, args...) + return nil + }) + + return res +} + +// Exec captures executing a query that doesn't return rows and adds +// corresponding information into subsegment. +func (tx *Tx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + var res sql.Result + + err := Capture(ctx, tx.db.dbname, func(ctx context.Context) error { + tx.db.populate(ctx, query) + + var err error + res, err = tx.tx.Exec(query, args...) + return err + }) + + return res, err +} + +// Query captures executing a query that returns rows and adds corresponding information into subsegment. +func (tx *Tx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { + var res *sql.Rows + + err := Capture(ctx, tx.db.dbname, func(ctx context.Context) error { + tx.db.populate(ctx, query) + + var err error + res, err = tx.tx.Query(query, args...) + return err + }) + + return res, err +} + +// QueryRow captures executing a query that is expected to return at most one row and adds +// corresponding information into subsegment. +func (tx *Tx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row { + var res *sql.Row + + Capture(ctx, tx.db.dbname, func(ctx context.Context) error { + tx.db.populate(ctx, query) + + res = tx.tx.QueryRow(query, args...) + return nil + }) + + return res +} + +// Stmt returns a transaction-specific prepared statement from an existing statement. +func (tx *Tx) Stmt(ctx context.Context, stmt *Stmt) *Stmt { + return &Stmt{stmt.db, tx.tx.Stmt(stmt.stmt), stmt.query} +} + +// Exec captures executing a prepared statement with the given arguments and +// returning a Result summarizing the effect of the statement and adds corresponding +// information into subsegment. +func (stmt *Stmt) Exec(ctx context.Context, args ...interface{}) (sql.Result, error) { + var res sql.Result + + err := Capture(ctx, stmt.db.dbname, func(ctx context.Context) error { + stmt.populate(ctx, stmt.query) + + var err error + res, err = stmt.stmt.Exec(args...) + return err + }) + + return res, err +} + +// Query captures executing a prepared query statement with the given arguments +// and returning the query results as a *Rows and adds corresponding information +// into subsegment. +func (stmt *Stmt) Query(ctx context.Context, args ...interface{}) (*sql.Rows, error) { + var res *sql.Rows + + err := Capture(ctx, stmt.db.dbname, func(ctx context.Context) error { + stmt.populate(ctx, stmt.query) + + var err error + res, err = stmt.stmt.Query(args...) + return err + }) + + return res, err +} + +// QueryRow captures executing a prepared query statement with the given arguments and +// adds corresponding information into subsegment. +func (stmt *Stmt) QueryRow(ctx context.Context, args ...interface{}) *sql.Row { + var res *sql.Row + + Capture(ctx, stmt.db.dbname, func(ctx context.Context) error { + stmt.populate(ctx, stmt.query) + + res = stmt.stmt.QueryRow(args...) + return nil + }) + + return res +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/sql_go18.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/sql_go18.go new file mode 100644 index 00000000..2ee0e30c --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/sql_go18.go @@ -0,0 +1,183 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +// +build go1.8 + +package xray + +import ( + "context" + "database/sql" +) + +// Begin starts a transaction. +func (db *DB) Begin(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + tx, err := db.db.BeginTx(ctx, opts) + return &Tx{db, tx}, err +} + +// Prepare creates a prepared statement for later queries or executions. +func (db *DB) Prepare(ctx context.Context, query string) (*Stmt, error) { + stmt, err := db.db.PrepareContext(ctx, query) + return &Stmt{db, stmt, query}, err +} + +// Ping traces verifying a connection to the database is still alive, +// establishing a connection if necessary and adds corresponding information into subsegment. +func (db *DB) Ping(ctx context.Context) error { + return Capture(ctx, db.dbname, func(ctx context.Context) error { + db.populate(ctx, "PING") + return db.db.PingContext(ctx) + }) +} + +// Exec captures executing a query without returning any rows and +// adds corresponding information into subsegment. +func (db *DB) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + var res sql.Result + + err := Capture(ctx, db.dbname, func(ctx context.Context) error { + db.populate(ctx, query) + + var err error + res, err = db.db.ExecContext(ctx, query, args...) + return err + }) + + return res, err +} + +// Query captures executing a query that returns rows and adds corresponding information into subsegment. +func (db *DB) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { + var res *sql.Rows + + err := Capture(ctx, db.dbname, func(ctx context.Context) error { + db.populate(ctx, query) + + var err error + res, err = db.db.QueryContext(ctx, query, args...) + return err + }) + + return res, err +} + +// QueryRow captures executing a query that is expected to return at most one row +// and adds corresponding information into subsegment. +func (db *DB) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row { + var res *sql.Row + + Capture(ctx, db.dbname, func(ctx context.Context) error { + db.populate(ctx, query) + + res = db.db.QueryRowContext(ctx, query, args...) + return nil + }) + + return res +} + +// Exec captures executing a query that doesn't return rows and adds +// corresponding information into subsegment. +func (tx *Tx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + var res sql.Result + + err := Capture(ctx, tx.db.dbname, func(ctx context.Context) error { + tx.db.populate(ctx, query) + + var err error + res, err = tx.tx.ExecContext(ctx, query, args...) + return err + }) + + return res, err +} + +// Query captures executing a query that returns rows and adds corresponding information into subsegment. +func (tx *Tx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { + var res *sql.Rows + + err := Capture(ctx, tx.db.dbname, func(ctx context.Context) error { + tx.db.populate(ctx, query) + + var err error + res, err = tx.tx.QueryContext(ctx, query, args...) + return err + }) + + return res, err +} + +// QueryRow captures executing a query that is expected to return at most one row and adds +// corresponding information into subsegment. +func (tx *Tx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row { + var res *sql.Row + + Capture(ctx, tx.db.dbname, func(ctx context.Context) error { + tx.db.populate(ctx, query) + + res = tx.tx.QueryRowContext(ctx, query, args...) + return nil + }) + + return res +} + +// Stmt returns a transaction-specific prepared statement from an existing statement. +func (tx *Tx) Stmt(ctx context.Context, stmt *Stmt) *Stmt { + return &Stmt{stmt.db, tx.tx.StmtContext(ctx, stmt.stmt), stmt.query} +} + +// Exec captures executing a prepared statement with the given arguments and +// returning a Result summarizing the effect of the statement and adds corresponding +// information into subsegment. +func (stmt *Stmt) Exec(ctx context.Context, args ...interface{}) (sql.Result, error) { + var res sql.Result + + err := Capture(ctx, stmt.db.dbname, func(ctx context.Context) error { + stmt.populate(ctx, stmt.query) + + var err error + res, err = stmt.stmt.ExecContext(ctx, args...) + return err + }) + + return res, err +} + +// Query captures executing a prepared query statement with the given arguments +// and returning the query results as a *Rows and adds corresponding information +// into subsegment. +func (stmt *Stmt) Query(ctx context.Context, args ...interface{}) (*sql.Rows, error) { + var res *sql.Rows + + err := Capture(ctx, stmt.db.dbname, func(ctx context.Context) error { + stmt.populate(ctx, stmt.query) + + var err error + res, err = stmt.stmt.QueryContext(ctx, args...) + return err + }) + + return res, err +} + +// QueryRow captures executing a prepared query statement with the given arguments and +// adds corresponding information into subsegment. +func (stmt *Stmt) QueryRow(ctx context.Context, args ...interface{}) *sql.Row { + var res *sql.Row + + Capture(ctx, stmt.db.dbname, func(ctx context.Context) error { + stmt.populate(ctx, stmt.query) + + res = stmt.stmt.QueryRowContext(ctx, args...) + return nil + }) + + return res +} diff --git a/vendor/github.com/aws/aws-xray-sdk-go/xray/streaming_strategy.go b/vendor/github.com/aws/aws-xray-sdk-go/xray/streaming_strategy.go new file mode 100644 index 00000000..9f88174a --- /dev/null +++ b/vendor/github.com/aws/aws-xray-sdk-go/xray/streaming_strategy.go @@ -0,0 +1,15 @@ +// Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at +// +// http://aws.amazon.com/apache2.0/ +// +// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +package xray + +// StreamingStrategy provides an interface for implementing streaming strategies. +type StreamingStrategy interface { + RequiresStreaming(seg *Segment) bool + StreamCompletedSubsegments(seg *Segment) [][]byte +} diff --git a/vendor/github.com/cihub/seelog/LICENSE.txt b/vendor/github.com/cihub/seelog/LICENSE.txt new file mode 100644 index 00000000..8c706814 --- /dev/null +++ b/vendor/github.com/cihub/seelog/LICENSE.txt @@ -0,0 +1,24 @@ +Copyright (c) 2012, Cloud Instruments Co., Ltd. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Cloud Instruments Co., Ltd. nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/cihub/seelog/behavior_adaptivelogger.go b/vendor/github.com/cihub/seelog/behavior_adaptivelogger.go new file mode 100644 index 00000000..0c640cae --- /dev/null +++ b/vendor/github.com/cihub/seelog/behavior_adaptivelogger.go @@ -0,0 +1,129 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" + "fmt" + "math" + "time" +) + +var ( + adaptiveLoggerMaxInterval = time.Minute + adaptiveLoggerMaxCriticalMsgCount = uint32(1000) +) + +// asyncAdaptiveLogger represents asynchronous adaptive logger which acts like +// an async timer logger, but its interval depends on the current message count +// in the queue. +// +// Interval = I, minInterval = m, maxInterval = M, criticalMsgCount = C, msgCount = c: +// I = m + (C - Min(c, C)) / C * (M - m) +type asyncAdaptiveLogger struct { + asyncLogger + minInterval time.Duration + criticalMsgCount uint32 + maxInterval time.Duration +} + +// NewAsyncLoopLogger creates a new asynchronous adaptive logger +func NewAsyncAdaptiveLogger( + config *logConfig, + minInterval time.Duration, + maxInterval time.Duration, + criticalMsgCount uint32) (*asyncAdaptiveLogger, error) { + + if minInterval <= 0 { + return nil, errors.New("async adaptive logger min interval should be > 0") + } + + if maxInterval > adaptiveLoggerMaxInterval { + return nil, fmt.Errorf("async adaptive logger max interval should be <= %s", + adaptiveLoggerMaxInterval) + } + + if criticalMsgCount <= 0 { + return nil, errors.New("async adaptive logger critical msg count should be > 0") + } + + if criticalMsgCount > adaptiveLoggerMaxCriticalMsgCount { + return nil, fmt.Errorf("async adaptive logger critical msg count should be <= %s", + adaptiveLoggerMaxInterval) + } + + asnAdaptiveLogger := new(asyncAdaptiveLogger) + + asnAdaptiveLogger.asyncLogger = *newAsyncLogger(config) + asnAdaptiveLogger.minInterval = minInterval + asnAdaptiveLogger.maxInterval = maxInterval + asnAdaptiveLogger.criticalMsgCount = criticalMsgCount + + go asnAdaptiveLogger.processQueue() + + return asnAdaptiveLogger, nil +} + +func (asnAdaptiveLogger *asyncAdaptiveLogger) processItem() (closed bool, itemCount int) { + asnAdaptiveLogger.queueHasElements.L.Lock() + defer asnAdaptiveLogger.queueHasElements.L.Unlock() + + for asnAdaptiveLogger.msgQueue.Len() == 0 && !asnAdaptiveLogger.Closed() { + asnAdaptiveLogger.queueHasElements.Wait() + } + + if asnAdaptiveLogger.Closed() { + return true, asnAdaptiveLogger.msgQueue.Len() + } + + asnAdaptiveLogger.processQueueElement() + return false, asnAdaptiveLogger.msgQueue.Len() - 1 +} + +// I = m + (C - Min(c, C)) / C * (M - m) => +// I = m + cDiff * mDiff, +// cDiff = (C - Min(c, C)) / C) +// mDiff = (M - m) +func (asnAdaptiveLogger *asyncAdaptiveLogger) calcAdaptiveInterval(msgCount int) time.Duration { + critCountF := float64(asnAdaptiveLogger.criticalMsgCount) + cDiff := (critCountF - math.Min(float64(msgCount), critCountF)) / critCountF + mDiff := float64(asnAdaptiveLogger.maxInterval - asnAdaptiveLogger.minInterval) + + return asnAdaptiveLogger.minInterval + time.Duration(cDiff*mDiff) +} + +func (asnAdaptiveLogger *asyncAdaptiveLogger) processQueue() { + for !asnAdaptiveLogger.Closed() { + closed, itemCount := asnAdaptiveLogger.processItem() + + if closed { + break + } + + interval := asnAdaptiveLogger.calcAdaptiveInterval(itemCount) + + <-time.After(interval) + } +} diff --git a/vendor/github.com/cihub/seelog/behavior_asynclogger.go b/vendor/github.com/cihub/seelog/behavior_asynclogger.go new file mode 100644 index 00000000..75231067 --- /dev/null +++ b/vendor/github.com/cihub/seelog/behavior_asynclogger.go @@ -0,0 +1,142 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "container/list" + "fmt" + "sync" +) + +// MaxQueueSize is the critical number of messages in the queue that result in an immediate flush. +const ( + MaxQueueSize = 10000 +) + +type msgQueueItem struct { + level LogLevel + context LogContextInterface + message fmt.Stringer +} + +// asyncLogger represents common data for all asynchronous loggers +type asyncLogger struct { + commonLogger + msgQueue *list.List + queueHasElements *sync.Cond +} + +// newAsyncLogger creates a new asynchronous logger +func newAsyncLogger(config *logConfig) *asyncLogger { + asnLogger := new(asyncLogger) + + asnLogger.msgQueue = list.New() + asnLogger.queueHasElements = sync.NewCond(new(sync.Mutex)) + + asnLogger.commonLogger = *newCommonLogger(config, asnLogger) + + return asnLogger +} + +func (asnLogger *asyncLogger) innerLog( + level LogLevel, + context LogContextInterface, + message fmt.Stringer) { + + asnLogger.addMsgToQueue(level, context, message) +} + +func (asnLogger *asyncLogger) Close() { + asnLogger.m.Lock() + defer asnLogger.m.Unlock() + + if !asnLogger.Closed() { + asnLogger.flushQueue(true) + asnLogger.config.RootDispatcher.Flush() + + if err := asnLogger.config.RootDispatcher.Close(); err != nil { + reportInternalError(err) + } + + asnLogger.closedM.Lock() + asnLogger.closed = true + asnLogger.closedM.Unlock() + asnLogger.queueHasElements.Broadcast() + } +} + +func (asnLogger *asyncLogger) Flush() { + asnLogger.m.Lock() + defer asnLogger.m.Unlock() + + if !asnLogger.Closed() { + asnLogger.flushQueue(true) + asnLogger.config.RootDispatcher.Flush() + } +} + +func (asnLogger *asyncLogger) flushQueue(lockNeeded bool) { + if lockNeeded { + asnLogger.queueHasElements.L.Lock() + defer asnLogger.queueHasElements.L.Unlock() + } + + for asnLogger.msgQueue.Len() > 0 { + asnLogger.processQueueElement() + } +} + +func (asnLogger *asyncLogger) processQueueElement() { + if asnLogger.msgQueue.Len() > 0 { + backElement := asnLogger.msgQueue.Front() + msg, _ := backElement.Value.(msgQueueItem) + asnLogger.processLogMsg(msg.level, msg.message, msg.context) + asnLogger.msgQueue.Remove(backElement) + } +} + +func (asnLogger *asyncLogger) addMsgToQueue( + level LogLevel, + context LogContextInterface, + message fmt.Stringer) { + + if !asnLogger.Closed() { + asnLogger.queueHasElements.L.Lock() + defer asnLogger.queueHasElements.L.Unlock() + + if asnLogger.msgQueue.Len() >= MaxQueueSize { + fmt.Printf("Seelog queue overflow: more than %v messages in the queue. Flushing.\n", MaxQueueSize) + asnLogger.flushQueue(false) + } + + queueItem := msgQueueItem{level, context, message} + + asnLogger.msgQueue.PushBack(queueItem) + asnLogger.queueHasElements.Broadcast() + } else { + err := fmt.Errorf("queue closed! Cannot process element: %d %#v", level, message) + reportInternalError(err) + } +} diff --git a/vendor/github.com/cihub/seelog/behavior_asynclooplogger.go b/vendor/github.com/cihub/seelog/behavior_asynclooplogger.go new file mode 100644 index 00000000..972467b3 --- /dev/null +++ b/vendor/github.com/cihub/seelog/behavior_asynclooplogger.go @@ -0,0 +1,69 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +// asyncLoopLogger represents asynchronous logger which processes the log queue in +// a 'for' loop +type asyncLoopLogger struct { + asyncLogger +} + +// NewAsyncLoopLogger creates a new asynchronous loop logger +func NewAsyncLoopLogger(config *logConfig) *asyncLoopLogger { + + asnLoopLogger := new(asyncLoopLogger) + + asnLoopLogger.asyncLogger = *newAsyncLogger(config) + + go asnLoopLogger.processQueue() + + return asnLoopLogger +} + +func (asnLoopLogger *asyncLoopLogger) processItem() (closed bool) { + asnLoopLogger.queueHasElements.L.Lock() + defer asnLoopLogger.queueHasElements.L.Unlock() + + for asnLoopLogger.msgQueue.Len() == 0 && !asnLoopLogger.Closed() { + asnLoopLogger.queueHasElements.Wait() + } + + if asnLoopLogger.Closed() { + return true + } + + asnLoopLogger.processQueueElement() + return false +} + +func (asnLoopLogger *asyncLoopLogger) processQueue() { + for !asnLoopLogger.Closed() { + closed := asnLoopLogger.processItem() + + if closed { + break + } + } +} diff --git a/vendor/github.com/cihub/seelog/behavior_asynctimerlogger.go b/vendor/github.com/cihub/seelog/behavior_asynctimerlogger.go new file mode 100644 index 00000000..8118f205 --- /dev/null +++ b/vendor/github.com/cihub/seelog/behavior_asynctimerlogger.go @@ -0,0 +1,82 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" + "time" +) + +// asyncTimerLogger represents asynchronous logger which processes the log queue each +// 'duration' nanoseconds +type asyncTimerLogger struct { + asyncLogger + interval time.Duration +} + +// NewAsyncLoopLogger creates a new asynchronous loop logger +func NewAsyncTimerLogger(config *logConfig, interval time.Duration) (*asyncTimerLogger, error) { + + if interval <= 0 { + return nil, errors.New("async logger interval should be > 0") + } + + asnTimerLogger := new(asyncTimerLogger) + + asnTimerLogger.asyncLogger = *newAsyncLogger(config) + asnTimerLogger.interval = interval + + go asnTimerLogger.processQueue() + + return asnTimerLogger, nil +} + +func (asnTimerLogger *asyncTimerLogger) processItem() (closed bool) { + asnTimerLogger.queueHasElements.L.Lock() + defer asnTimerLogger.queueHasElements.L.Unlock() + + for asnTimerLogger.msgQueue.Len() == 0 && !asnTimerLogger.Closed() { + asnTimerLogger.queueHasElements.Wait() + } + + if asnTimerLogger.Closed() { + return true + } + + asnTimerLogger.processQueueElement() + return false +} + +func (asnTimerLogger *asyncTimerLogger) processQueue() { + for !asnTimerLogger.Closed() { + closed := asnTimerLogger.processItem() + + if closed { + break + } + + <-time.After(asnTimerLogger.interval) + } +} diff --git a/vendor/github.com/cihub/seelog/behavior_synclogger.go b/vendor/github.com/cihub/seelog/behavior_synclogger.go new file mode 100644 index 00000000..5a022ebc --- /dev/null +++ b/vendor/github.com/cihub/seelog/behavior_synclogger.go @@ -0,0 +1,75 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "fmt" +) + +// syncLogger performs logging in the same goroutine where 'Trace/Debug/...' +// func was called +type syncLogger struct { + commonLogger +} + +// NewSyncLogger creates a new synchronous logger +func NewSyncLogger(config *logConfig) *syncLogger { + syncLogger := new(syncLogger) + + syncLogger.commonLogger = *newCommonLogger(config, syncLogger) + + return syncLogger +} + +func (syncLogger *syncLogger) innerLog( + level LogLevel, + context LogContextInterface, + message fmt.Stringer) { + + syncLogger.processLogMsg(level, message, context) +} + +func (syncLogger *syncLogger) Close() { + syncLogger.m.Lock() + defer syncLogger.m.Unlock() + + if !syncLogger.Closed() { + if err := syncLogger.config.RootDispatcher.Close(); err != nil { + reportInternalError(err) + } + syncLogger.closedM.Lock() + syncLogger.closed = true + syncLogger.closedM.Unlock() + } +} + +func (syncLogger *syncLogger) Flush() { + syncLogger.m.Lock() + defer syncLogger.m.Unlock() + + if !syncLogger.Closed() { + syncLogger.config.RootDispatcher.Flush() + } +} diff --git a/vendor/github.com/cihub/seelog/cfg_config.go b/vendor/github.com/cihub/seelog/cfg_config.go new file mode 100644 index 00000000..c7d84812 --- /dev/null +++ b/vendor/github.com/cihub/seelog/cfg_config.go @@ -0,0 +1,188 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "bytes" + "encoding/xml" + "io" + "os" +) + +// LoggerFromConfigAsFile creates logger with config from file. File should contain valid seelog xml. +func LoggerFromConfigAsFile(fileName string) (LoggerInterface, error) { + file, err := os.Open(fileName) + if err != nil { + return nil, err + } + defer file.Close() + + conf, err := configFromReader(file) + if err != nil { + return nil, err + } + + return createLoggerFromFullConfig(conf) +} + +// LoggerFromConfigAsBytes creates a logger with config from bytes stream. Bytes should contain valid seelog xml. +func LoggerFromConfigAsBytes(data []byte) (LoggerInterface, error) { + conf, err := configFromReader(bytes.NewBuffer(data)) + if err != nil { + return nil, err + } + + return createLoggerFromFullConfig(conf) +} + +// LoggerFromConfigAsString creates a logger with config from a string. String should contain valid seelog xml. +func LoggerFromConfigAsString(data string) (LoggerInterface, error) { + return LoggerFromConfigAsBytes([]byte(data)) +} + +// LoggerFromParamConfigAsFile does the same as LoggerFromConfigAsFile, but includes special parser options. +// See 'CfgParseParams' comments. +func LoggerFromParamConfigAsFile(fileName string, parserParams *CfgParseParams) (LoggerInterface, error) { + file, err := os.Open(fileName) + if err != nil { + return nil, err + } + defer file.Close() + + conf, err := configFromReaderWithConfig(file, parserParams) + if err != nil { + return nil, err + } + + return createLoggerFromFullConfig(conf) +} + +// LoggerFromParamConfigAsBytes does the same as LoggerFromConfigAsBytes, but includes special parser options. +// See 'CfgParseParams' comments. +func LoggerFromParamConfigAsBytes(data []byte, parserParams *CfgParseParams) (LoggerInterface, error) { + conf, err := configFromReaderWithConfig(bytes.NewBuffer(data), parserParams) + if err != nil { + return nil, err + } + + return createLoggerFromFullConfig(conf) +} + +// LoggerFromParamConfigAsString does the same as LoggerFromConfigAsString, but includes special parser options. +// See 'CfgParseParams' comments. +func LoggerFromParamConfigAsString(data string, parserParams *CfgParseParams) (LoggerInterface, error) { + return LoggerFromParamConfigAsBytes([]byte(data), parserParams) +} + +// LoggerFromWriterWithMinLevel is shortcut for LoggerFromWriterWithMinLevelAndFormat(output, minLevel, DefaultMsgFormat) +func LoggerFromWriterWithMinLevel(output io.Writer, minLevel LogLevel) (LoggerInterface, error) { + return LoggerFromWriterWithMinLevelAndFormat(output, minLevel, DefaultMsgFormat) +} + +// LoggerFromWriterWithMinLevelAndFormat creates a proxy logger that uses io.Writer as the +// receiver with minimal level = minLevel and with specified format. +// +// All messages with level more or equal to minLevel will be written to output and +// formatted using the default seelog format. +// +// Can be called for usage with non-Seelog systems +func LoggerFromWriterWithMinLevelAndFormat(output io.Writer, minLevel LogLevel, format string) (LoggerInterface, error) { + constraints, err := NewMinMaxConstraints(minLevel, CriticalLvl) + if err != nil { + return nil, err + } + formatter, err := NewFormatter(format) + if err != nil { + return nil, err + } + dispatcher, err := NewSplitDispatcher(formatter, []interface{}{output}) + if err != nil { + return nil, err + } + + conf, err := newFullLoggerConfig(constraints, make([]*LogLevelException, 0), dispatcher, syncloggerTypeFromString, nil, nil) + if err != nil { + return nil, err + } + + return createLoggerFromFullConfig(conf) +} + +// LoggerFromXMLDecoder creates logger with config from a XML decoder starting from a specific node. +// It should contain valid seelog xml, except for root node name. +func LoggerFromXMLDecoder(xmlParser *xml.Decoder, rootNode xml.Token) (LoggerInterface, error) { + conf, err := configFromXMLDecoder(xmlParser, rootNode) + if err != nil { + return nil, err + } + + return createLoggerFromFullConfig(conf) +} + +// LoggerFromCustomReceiver creates a proxy logger that uses a CustomReceiver as the +// receiver. +// +// All messages will be sent to the specified custom receiver without additional +// formatting ('%Msg' format is used). +// +// Check CustomReceiver, RegisterReceiver for additional info. +// +// NOTE 1: CustomReceiver.AfterParse is only called when a receiver is instantiated +// by the config parser while parsing config. So, if you are not planning to use the +// same CustomReceiver for both proxying (via LoggerFromCustomReceiver call) and +// loading from config, just leave AfterParse implementation empty. +// +// NOTE 2: Unlike RegisterReceiver, LoggerFromCustomReceiver takes an already initialized +// instance that implements CustomReceiver. So, fill it with data and perform any initialization +// logic before calling this func and it won't be lost. +// +// So: +// * RegisterReceiver takes value just to get the reflect.Type from it and then +// instantiate it as many times as config is reloaded. +// +// * LoggerFromCustomReceiver takes value and uses it without modification and +// reinstantiation, directy passing it to the dispatcher tree. +func LoggerFromCustomReceiver(receiver CustomReceiver) (LoggerInterface, error) { + constraints, err := NewMinMaxConstraints(TraceLvl, CriticalLvl) + if err != nil { + return nil, err + } + + output, err := NewCustomReceiverDispatcherByValue(msgonlyformatter, receiver, "user-proxy", CustomReceiverInitArgs{}) + if err != nil { + return nil, err + } + dispatcher, err := NewSplitDispatcher(msgonlyformatter, []interface{}{output}) + if err != nil { + return nil, err + } + + conf, err := newFullLoggerConfig(constraints, make([]*LogLevelException, 0), dispatcher, syncloggerTypeFromString, nil, nil) + if err != nil { + return nil, err + } + + return createLoggerFromFullConfig(conf) +} diff --git a/vendor/github.com/cihub/seelog/cfg_errors.go b/vendor/github.com/cihub/seelog/cfg_errors.go new file mode 100644 index 00000000..c1fb4d10 --- /dev/null +++ b/vendor/github.com/cihub/seelog/cfg_errors.go @@ -0,0 +1,61 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" +) + +var ( + errNodeMustHaveChildren = errors.New("node must have children") + errNodeCannotHaveChildren = errors.New("node cannot have children") +) + +type unexpectedChildElementError struct { + baseError +} + +func newUnexpectedChildElementError(msg string) *unexpectedChildElementError { + custmsg := "Unexpected child element: " + msg + return &unexpectedChildElementError{baseError{message: custmsg}} +} + +type missingArgumentError struct { + baseError +} + +func newMissingArgumentError(nodeName, attrName string) *missingArgumentError { + custmsg := "Output '" + nodeName + "' has no '" + attrName + "' attribute" + return &missingArgumentError{baseError{message: custmsg}} +} + +type unexpectedAttributeError struct { + baseError +} + +func newUnexpectedAttributeError(nodeName, attr string) *unexpectedAttributeError { + custmsg := nodeName + " has unexpected attribute: " + attr + return &unexpectedAttributeError{baseError{message: custmsg}} +} diff --git a/vendor/github.com/cihub/seelog/cfg_logconfig.go b/vendor/github.com/cihub/seelog/cfg_logconfig.go new file mode 100644 index 00000000..6ba6f9a9 --- /dev/null +++ b/vendor/github.com/cihub/seelog/cfg_logconfig.go @@ -0,0 +1,141 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" +) + +type loggerTypeFromString uint8 + +const ( + syncloggerTypeFromString = iota + asyncLooploggerTypeFromString + asyncTimerloggerTypeFromString + adaptiveLoggerTypeFromString + defaultloggerTypeFromString = asyncLooploggerTypeFromString +) + +const ( + syncloggerTypeFromStringStr = "sync" + asyncloggerTypeFromStringStr = "asyncloop" + asyncTimerloggerTypeFromStringStr = "asynctimer" + adaptiveLoggerTypeFromStringStr = "adaptive" +) + +// asyncTimerLoggerData represents specific data for async timer logger +type asyncTimerLoggerData struct { + AsyncInterval uint32 +} + +// adaptiveLoggerData represents specific data for adaptive timer logger +type adaptiveLoggerData struct { + MinInterval uint32 + MaxInterval uint32 + CriticalMsgCount uint32 +} + +var loggerTypeToStringRepresentations = map[loggerTypeFromString]string{ + syncloggerTypeFromString: syncloggerTypeFromStringStr, + asyncLooploggerTypeFromString: asyncloggerTypeFromStringStr, + asyncTimerloggerTypeFromString: asyncTimerloggerTypeFromStringStr, + adaptiveLoggerTypeFromString: adaptiveLoggerTypeFromStringStr, +} + +// getLoggerTypeFromString parses a string and returns a corresponding logger type, if successful. +func getLoggerTypeFromString(logTypeString string) (level loggerTypeFromString, found bool) { + for logType, logTypeStr := range loggerTypeToStringRepresentations { + if logTypeStr == logTypeString { + return logType, true + } + } + + return 0, false +} + +// logConfig stores logging configuration. Contains messages dispatcher, allowed log level rules +// (general constraints and exceptions) +type logConfig struct { + Constraints logLevelConstraints // General log level rules (>min and ' element. It takes the 'name' attribute + // of the element and tries to find a match in two places: + // 1) CfgParseParams.CustomReceiverProducers map + // 2) Global type map, filled by RegisterReceiver + // + // If a match is found in the CustomReceiverProducers map, parser calls the corresponding producer func + // passing the init args to it. The func takes exactly the same args as CustomReceiver.AfterParse. + // The producer func must return a correct receiver or an error. If case of error, seelog will behave + // in the same way as with any other config error. + // + // You may use this param to set custom producers in case you need to pass some context when instantiating + // a custom receiver or if you frequently change custom receivers with different parameters or in any other + // situation where package-level registering (RegisterReceiver) is not an option for you. + CustomReceiverProducers map[string]CustomReceiverProducer +} + +func (cfg *CfgParseParams) String() string { + return fmt.Sprintf("CfgParams: {custom_recs=%d}", len(cfg.CustomReceiverProducers)) +} + +type elementMapEntry struct { + constructor func(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *CfgParseParams) (interface{}, error) +} + +var elementMap map[string]elementMapEntry +var predefinedFormats map[string]*formatter + +func init() { + elementMap = map[string]elementMapEntry{ + fileWriterID: {createfileWriter}, + splitterDispatcherID: {createSplitter}, + customReceiverID: {createCustomReceiver}, + filterDispatcherID: {createFilter}, + consoleWriterID: {createConsoleWriter}, + rollingfileWriterID: {createRollingFileWriter}, + bufferedWriterID: {createbufferedWriter}, + smtpWriterID: {createSMTPWriter}, + connWriterID: {createconnWriter}, + } + + err := fillPredefinedFormats() + if err != nil { + panic(fmt.Sprintf("Seelog couldn't start: predefined formats creation failed. Error: %s", err.Error())) + } +} + +func fillPredefinedFormats() error { + predefinedFormatsWithoutPrefix := map[string]string{ + "xml-debug": `%Lev%Msg%RelFile%Func%Line`, + "xml-debug-short": `%Ns%l%Msg

%RelFile

%Func`, + "xml": `%Lev%Msg`, + "xml-short": `%Ns%l%Msg`, + + "json-debug": `{"time":%Ns,"lev":"%Lev","msg":"%Msg","path":"%RelFile","func":"%Func","line":"%Line"}`, + "json-debug-short": `{"t":%Ns,"l":"%Lev","m":"%Msg","p":"%RelFile","f":"%Func"}`, + "json": `{"time":%Ns,"lev":"%Lev","msg":"%Msg"}`, + "json-short": `{"t":%Ns,"l":"%Lev","m":"%Msg"}`, + + "debug": `[%LEVEL] %RelFile:%Func.%Line %Date %Time %Msg%n`, + "debug-short": `[%LEVEL] %Date %Time %Msg%n`, + "fast": `%Ns %l %Msg%n`, + } + + predefinedFormats = make(map[string]*formatter) + + for formatKey, format := range predefinedFormatsWithoutPrefix { + formatter, err := NewFormatter(format) + if err != nil { + return err + } + + predefinedFormats[predefinedPrefix+formatKey] = formatter + } + + return nil +} + +// configFromXMLDecoder parses data from a given XML decoder. +// Returns parsed config which can be used to create logger in case no errors occured. +// Returns error if format is incorrect or anything happened. +func configFromXMLDecoder(xmlParser *xml.Decoder, rootNode xml.Token) (*configForParsing, error) { + return configFromXMLDecoderWithConfig(xmlParser, rootNode, nil) +} + +// configFromXMLDecoderWithConfig parses data from a given XML decoder. +// Returns parsed config which can be used to create logger in case no errors occured. +// Returns error if format is incorrect or anything happened. +func configFromXMLDecoderWithConfig(xmlParser *xml.Decoder, rootNode xml.Token, cfg *CfgParseParams) (*configForParsing, error) { + _, ok := rootNode.(xml.StartElement) + if !ok { + return nil, errors.New("rootNode must be XML startElement") + } + + config, err := unmarshalNode(xmlParser, rootNode) + if err != nil { + return nil, err + } + if config == nil { + return nil, errors.New("xml has no content") + } + + return configFromXMLNodeWithConfig(config, cfg) +} + +// configFromReader parses data from a given reader. +// Returns parsed config which can be used to create logger in case no errors occured. +// Returns error if format is incorrect or anything happened. +func configFromReader(reader io.Reader) (*configForParsing, error) { + return configFromReaderWithConfig(reader, nil) +} + +// configFromReaderWithConfig parses data from a given reader. +// Returns parsed config which can be used to create logger in case no errors occured. +// Returns error if format is incorrect or anything happened. +func configFromReaderWithConfig(reader io.Reader, cfg *CfgParseParams) (*configForParsing, error) { + config, err := unmarshalConfig(reader) + if err != nil { + return nil, err + } + + if config.name != seelogConfigID { + return nil, errors.New("root xml tag must be '" + seelogConfigID + "'") + } + + return configFromXMLNodeWithConfig(config, cfg) +} + +func configFromXMLNodeWithConfig(config *xmlNode, cfg *CfgParseParams) (*configForParsing, error) { + err := checkUnexpectedAttribute( + config, + minLevelID, + maxLevelID, + levelsID, + loggerTypeFromStringAttr, + asyncLoggerIntervalAttr, + adaptLoggerMinIntervalAttr, + adaptLoggerMaxIntervalAttr, + adaptLoggerCriticalMsgCountAttr, + ) + if err != nil { + return nil, err + } + + err = checkExpectedElements(config, optionalElement(outputsID), optionalElement(formatsID), optionalElement(exceptionsID)) + if err != nil { + return nil, err + } + + constraints, err := getConstraints(config) + if err != nil { + return nil, err + } + + exceptions, err := getExceptions(config) + if err != nil { + return nil, err + } + err = checkDistinctExceptions(exceptions) + if err != nil { + return nil, err + } + + formats, err := getFormats(config) + if err != nil { + return nil, err + } + + dispatcher, err := getOutputsTree(config, formats, cfg) + if err != nil { + // If we open several files, but then fail to parse the config, we should close + // those files before reporting that config is invalid. + if dispatcher != nil { + dispatcher.Close() + } + + return nil, err + } + + loggerType, logData, err := getloggerTypeFromStringData(config) + if err != nil { + return nil, err + } + + return newFullLoggerConfig(constraints, exceptions, dispatcher, loggerType, logData, cfg) +} + +func getConstraints(node *xmlNode) (logLevelConstraints, error) { + minLevelStr, isMinLevel := node.attributes[minLevelID] + maxLevelStr, isMaxLevel := node.attributes[maxLevelID] + levelsStr, isLevels := node.attributes[levelsID] + + if isLevels && (isMinLevel && isMaxLevel) { + return nil, errors.New("for level declaration use '" + levelsID + "'' OR '" + minLevelID + + "', '" + maxLevelID + "'") + } + + offString := LogLevel(Off).String() + + if (isLevels && strings.TrimSpace(levelsStr) == offString) || + (isMinLevel && !isMaxLevel && minLevelStr == offString) { + + return NewOffConstraints() + } + + if isLevels { + levels, err := parseLevels(levelsStr) + if err != nil { + return nil, err + } + return NewListConstraints(levels) + } + + var minLevel = LogLevel(TraceLvl) + if isMinLevel { + found := true + minLevel, found = LogLevelFromString(minLevelStr) + if !found { + return nil, errors.New("declared " + minLevelID + " not found: " + minLevelStr) + } + } + + var maxLevel = LogLevel(CriticalLvl) + if isMaxLevel { + found := true + maxLevel, found = LogLevelFromString(maxLevelStr) + if !found { + return nil, errors.New("declared " + maxLevelID + " not found: " + maxLevelStr) + } + } + + return NewMinMaxConstraints(minLevel, maxLevel) +} + +func parseLevels(str string) ([]LogLevel, error) { + levelsStrArr := strings.Split(strings.Replace(str, " ", "", -1), ",") + var levels []LogLevel + for _, levelStr := range levelsStrArr { + level, found := LogLevelFromString(levelStr) + if !found { + return nil, errors.New("declared level not found: " + levelStr) + } + + levels = append(levels, level) + } + + return levels, nil +} + +func getExceptions(config *xmlNode) ([]*LogLevelException, error) { + var exceptions []*LogLevelException + + var exceptionsNode *xmlNode + for _, child := range config.children { + if child.name == exceptionsID { + exceptionsNode = child + break + } + } + + if exceptionsNode == nil { + return exceptions, nil + } + + err := checkUnexpectedAttribute(exceptionsNode) + if err != nil { + return nil, err + } + + err = checkExpectedElements(exceptionsNode, multipleMandatoryElements("exception")) + if err != nil { + return nil, err + } + + for _, exceptionNode := range exceptionsNode.children { + if exceptionNode.name != exceptionID { + return nil, errors.New("incorrect nested element in exceptions section: " + exceptionNode.name) + } + + err := checkUnexpectedAttribute(exceptionNode, minLevelID, maxLevelID, levelsID, funcPatternID, filePatternID) + if err != nil { + return nil, err + } + + constraints, err := getConstraints(exceptionNode) + if err != nil { + return nil, errors.New("incorrect " + exceptionsID + " node: " + err.Error()) + } + + funcPattern, isFuncPattern := exceptionNode.attributes[funcPatternID] + filePattern, isFilePattern := exceptionNode.attributes[filePatternID] + if !isFuncPattern { + funcPattern = "*" + } + if !isFilePattern { + filePattern = "*" + } + + exception, err := NewLogLevelException(funcPattern, filePattern, constraints) + if err != nil { + return nil, errors.New("incorrect exception node: " + err.Error()) + } + + exceptions = append(exceptions, exception) + } + + return exceptions, nil +} + +func checkDistinctExceptions(exceptions []*LogLevelException) error { + for i, exception := range exceptions { + for j, exception1 := range exceptions { + if i == j { + continue + } + + if exception.FuncPattern() == exception1.FuncPattern() && + exception.FilePattern() == exception1.FilePattern() { + + return fmt.Errorf("there are two or more duplicate exceptions. Func: %v, file %v", + exception.FuncPattern(), exception.FilePattern()) + } + } + } + + return nil +} + +func getFormats(config *xmlNode) (map[string]*formatter, error) { + formats := make(map[string]*formatter, 0) + + var formatsNode *xmlNode + for _, child := range config.children { + if child.name == formatsID { + formatsNode = child + break + } + } + + if formatsNode == nil { + return formats, nil + } + + err := checkUnexpectedAttribute(formatsNode) + if err != nil { + return nil, err + } + + err = checkExpectedElements(formatsNode, multipleMandatoryElements("format")) + if err != nil { + return nil, err + } + + for _, formatNode := range formatsNode.children { + if formatNode.name != formatID { + return nil, errors.New("incorrect nested element in " + formatsID + " section: " + formatNode.name) + } + + err := checkUnexpectedAttribute(formatNode, formatKeyAttrID, formatID) + if err != nil { + return nil, err + } + + id, isID := formatNode.attributes[formatKeyAttrID] + formatStr, isFormat := formatNode.attributes[formatAttrID] + if !isID { + return nil, errors.New("format has no '" + formatKeyAttrID + "' attribute") + } + if !isFormat { + return nil, errors.New("format[" + id + "] has no '" + formatAttrID + "' attribute") + } + + formatter, err := NewFormatter(formatStr) + if err != nil { + return nil, err + } + + formats[id] = formatter + } + + return formats, nil +} + +func getloggerTypeFromStringData(config *xmlNode) (logType loggerTypeFromString, logData interface{}, err error) { + logTypeStr, loggerTypeExists := config.attributes[loggerTypeFromStringAttr] + + if !loggerTypeExists { + return defaultloggerTypeFromString, nil, nil + } + + logType, found := getLoggerTypeFromString(logTypeStr) + + if !found { + return 0, nil, fmt.Errorf("unknown logger type: %s", logTypeStr) + } + + if logType == asyncTimerloggerTypeFromString { + intervalStr, intervalExists := config.attributes[asyncLoggerIntervalAttr] + if !intervalExists { + return 0, nil, newMissingArgumentError(config.name, asyncLoggerIntervalAttr) + } + + interval, err := strconv.ParseUint(intervalStr, 10, 32) + if err != nil { + return 0, nil, err + } + + logData = asyncTimerLoggerData{uint32(interval)} + } else if logType == adaptiveLoggerTypeFromString { + + // Min interval + minIntStr, minIntExists := config.attributes[adaptLoggerMinIntervalAttr] + if !minIntExists { + return 0, nil, newMissingArgumentError(config.name, adaptLoggerMinIntervalAttr) + } + minInterval, err := strconv.ParseUint(minIntStr, 10, 32) + if err != nil { + return 0, nil, err + } + + // Max interval + maxIntStr, maxIntExists := config.attributes[adaptLoggerMaxIntervalAttr] + if !maxIntExists { + return 0, nil, newMissingArgumentError(config.name, adaptLoggerMaxIntervalAttr) + } + maxInterval, err := strconv.ParseUint(maxIntStr, 10, 32) + if err != nil { + return 0, nil, err + } + + // Critical msg count + criticalMsgCountStr, criticalMsgCountExists := config.attributes[adaptLoggerCriticalMsgCountAttr] + if !criticalMsgCountExists { + return 0, nil, newMissingArgumentError(config.name, adaptLoggerCriticalMsgCountAttr) + } + criticalMsgCount, err := strconv.ParseUint(criticalMsgCountStr, 10, 32) + if err != nil { + return 0, nil, err + } + + logData = adaptiveLoggerData{uint32(minInterval), uint32(maxInterval), uint32(criticalMsgCount)} + } + + return logType, logData, nil +} + +func getOutputsTree(config *xmlNode, formats map[string]*formatter, cfg *CfgParseParams) (dispatcherInterface, error) { + var outputsNode *xmlNode + for _, child := range config.children { + if child.name == outputsID { + outputsNode = child + break + } + } + + if outputsNode != nil { + err := checkUnexpectedAttribute(outputsNode, outputFormatID) + if err != nil { + return nil, err + } + + formatter, err := getCurrentFormat(outputsNode, DefaultFormatter, formats) + if err != nil { + return nil, err + } + + output, err := createSplitter(outputsNode, formatter, formats, cfg) + if err != nil { + return nil, err + } + + dispatcher, ok := output.(dispatcherInterface) + if ok { + return dispatcher, nil + } + } + + console, err := NewConsoleWriter() + if err != nil { + return nil, err + } + return NewSplitDispatcher(DefaultFormatter, []interface{}{console}) +} + +func getCurrentFormat(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter) (*formatter, error) { + formatID, isFormatID := node.attributes[outputFormatID] + if !isFormatID { + return formatFromParent, nil + } + + format, ok := formats[formatID] + if ok { + return format, nil + } + + // Test for predefined format match + pdFormat, pdOk := predefinedFormats[formatID] + + if !pdOk { + return nil, errors.New("formatid = '" + formatID + "' doesn't exist") + } + + return pdFormat, nil +} + +func createInnerReceivers(node *xmlNode, format *formatter, formats map[string]*formatter, cfg *CfgParseParams) ([]interface{}, error) { + var outputs []interface{} + for _, childNode := range node.children { + entry, ok := elementMap[childNode.name] + if !ok { + return nil, errors.New("unnknown tag '" + childNode.name + "' in outputs section") + } + + output, err := entry.constructor(childNode, format, formats, cfg) + if err != nil { + return nil, err + } + + outputs = append(outputs, output) + } + + return outputs, nil +} + +func createSplitter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *CfgParseParams) (interface{}, error) { + err := checkUnexpectedAttribute(node, outputFormatID) + if err != nil { + return nil, err + } + + if !node.hasChildren() { + return nil, errNodeMustHaveChildren + } + + currentFormat, err := getCurrentFormat(node, formatFromParent, formats) + if err != nil { + return nil, err + } + + receivers, err := createInnerReceivers(node, currentFormat, formats, cfg) + if err != nil { + return nil, err + } + + return NewSplitDispatcher(currentFormat, receivers) +} + +func createCustomReceiver(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *CfgParseParams) (interface{}, error) { + dataCustomPrefixes := make(map[string]string) + // Expecting only 'formatid', 'name' and 'data-' attrs + for attr, attrval := range node.attributes { + isExpected := false + if attr == outputFormatID || + attr == customNameAttrID { + isExpected = true + } + if strings.HasPrefix(attr, customNameDataAttrPrefix) { + dataCustomPrefixes[attr[len(customNameDataAttrPrefix):]] = attrval + isExpected = true + } + if !isExpected { + return nil, newUnexpectedAttributeError(node.name, attr) + } + } + + if node.hasChildren() { + return nil, errNodeCannotHaveChildren + } + customName, hasCustomName := node.attributes[customNameAttrID] + if !hasCustomName { + return nil, newMissingArgumentError(node.name, customNameAttrID) + } + currentFormat, err := getCurrentFormat(node, formatFromParent, formats) + if err != nil { + return nil, err + } + args := CustomReceiverInitArgs{ + XmlCustomAttrs: dataCustomPrefixes, + } + + if cfg != nil && cfg.CustomReceiverProducers != nil { + if prod, ok := cfg.CustomReceiverProducers[customName]; ok { + rec, err := prod(args) + if err != nil { + return nil, err + } + creceiver, err := NewCustomReceiverDispatcherByValue(currentFormat, rec, customName, args) + if err != nil { + return nil, err + } + err = rec.AfterParse(args) + if err != nil { + return nil, err + } + return creceiver, nil + } + } + + return NewCustomReceiverDispatcher(currentFormat, customName, args) +} + +func createFilter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *CfgParseParams) (interface{}, error) { + err := checkUnexpectedAttribute(node, outputFormatID, filterLevelsAttrID) + if err != nil { + return nil, err + } + + if !node.hasChildren() { + return nil, errNodeMustHaveChildren + } + + currentFormat, err := getCurrentFormat(node, formatFromParent, formats) + if err != nil { + return nil, err + } + + levelsStr, isLevels := node.attributes[filterLevelsAttrID] + if !isLevels { + return nil, newMissingArgumentError(node.name, filterLevelsAttrID) + } + + levels, err := parseLevels(levelsStr) + if err != nil { + return nil, err + } + + receivers, err := createInnerReceivers(node, currentFormat, formats, cfg) + if err != nil { + return nil, err + } + + return NewFilterDispatcher(currentFormat, receivers, levels...) +} + +func createfileWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *CfgParseParams) (interface{}, error) { + err := checkUnexpectedAttribute(node, outputFormatID, pathID) + if err != nil { + return nil, err + } + + if node.hasChildren() { + return nil, errNodeCannotHaveChildren + } + + currentFormat, err := getCurrentFormat(node, formatFromParent, formats) + if err != nil { + return nil, err + } + + path, isPath := node.attributes[pathID] + if !isPath { + return nil, newMissingArgumentError(node.name, pathID) + } + + fileWriter, err := NewFileWriter(path) + if err != nil { + return nil, err + } + + return NewFormattedWriter(fileWriter, currentFormat) +} + +// Creates new SMTP writer if encountered in the config file. +func createSMTPWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *CfgParseParams) (interface{}, error) { + err := checkUnexpectedAttribute(node, outputFormatID, senderaddressID, senderNameID, hostNameID, hostPortID, userNameID, userPassID, subjectID) + if err != nil { + return nil, err + } + // Node must have children. + if !node.hasChildren() { + return nil, errNodeMustHaveChildren + } + currentFormat, err := getCurrentFormat(node, formatFromParent, formats) + if err != nil { + return nil, err + } + senderAddress, ok := node.attributes[senderaddressID] + if !ok { + return nil, newMissingArgumentError(node.name, senderaddressID) + } + senderName, ok := node.attributes[senderNameID] + if !ok { + return nil, newMissingArgumentError(node.name, senderNameID) + } + // Process child nodes scanning for recipient email addresses and/or CA certificate paths. + var recipientAddresses []string + var caCertDirPaths []string + var mailHeaders []string + for _, childNode := range node.children { + switch childNode.name { + // Extract recipient address from child nodes. + case recipientID: + address, ok := childNode.attributes[addressID] + if !ok { + return nil, newMissingArgumentError(childNode.name, addressID) + } + recipientAddresses = append(recipientAddresses, address) + // Extract CA certificate file path from child nodes. + case cACertDirpathID: + path, ok := childNode.attributes[pathID] + if !ok { + return nil, newMissingArgumentError(childNode.name, pathID) + } + caCertDirPaths = append(caCertDirPaths, path) + + // Extract email headers from child nodes. + case mailHeaderID: + headerName, ok := childNode.attributes[mailHeaderNameID] + if !ok { + return nil, newMissingArgumentError(childNode.name, mailHeaderNameID) + } + + headerValue, ok := childNode.attributes[mailHeaderValueID] + if !ok { + return nil, newMissingArgumentError(childNode.name, mailHeaderValueID) + } + + // Build header line + mailHeaders = append(mailHeaders, fmt.Sprintf("%s: %s", headerName, headerValue)) + default: + return nil, newUnexpectedChildElementError(childNode.name) + } + } + hostName, ok := node.attributes[hostNameID] + if !ok { + return nil, newMissingArgumentError(node.name, hostNameID) + } + + hostPort, ok := node.attributes[hostPortID] + if !ok { + return nil, newMissingArgumentError(node.name, hostPortID) + } + + // Check if the string can really be converted into int. + if _, err := strconv.Atoi(hostPort); err != nil { + return nil, errors.New("invalid host port number") + } + + userName, ok := node.attributes[userNameID] + if !ok { + return nil, newMissingArgumentError(node.name, userNameID) + } + + userPass, ok := node.attributes[userPassID] + if !ok { + return nil, newMissingArgumentError(node.name, userPassID) + } + + // subject is optionally set by configuration. + // default value is defined by DefaultSubjectPhrase constant in the writers_smtpwriter.go + var subjectPhrase = DefaultSubjectPhrase + + subject, ok := node.attributes[subjectID] + if ok { + subjectPhrase = subject + } + + smtpWriter := NewSMTPWriter( + senderAddress, + senderName, + recipientAddresses, + hostName, + hostPort, + userName, + userPass, + caCertDirPaths, + subjectPhrase, + mailHeaders, + ) + + return NewFormattedWriter(smtpWriter, currentFormat) +} + +func createConsoleWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *CfgParseParams) (interface{}, error) { + err := checkUnexpectedAttribute(node, outputFormatID) + if err != nil { + return nil, err + } + + if node.hasChildren() { + return nil, errNodeCannotHaveChildren + } + + currentFormat, err := getCurrentFormat(node, formatFromParent, formats) + if err != nil { + return nil, err + } + + consoleWriter, err := NewConsoleWriter() + if err != nil { + return nil, err + } + + return NewFormattedWriter(consoleWriter, currentFormat) +} + +func createconnWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *CfgParseParams) (interface{}, error) { + if node.hasChildren() { + return nil, errNodeCannotHaveChildren + } + + err := checkUnexpectedAttribute(node, outputFormatID, connWriterAddrAttr, connWriterNetAttr, connWriterReconnectOnMsgAttr, connWriterUseTLSAttr, connWriterInsecureSkipVerifyAttr) + if err != nil { + return nil, err + } + + currentFormat, err := getCurrentFormat(node, formatFromParent, formats) + if err != nil { + return nil, err + } + + addr, isAddr := node.attributes[connWriterAddrAttr] + if !isAddr { + return nil, newMissingArgumentError(node.name, connWriterAddrAttr) + } + + net, isNet := node.attributes[connWriterNetAttr] + if !isNet { + return nil, newMissingArgumentError(node.name, connWriterNetAttr) + } + + reconnectOnMsg := false + reconnectOnMsgStr, isReconnectOnMsgStr := node.attributes[connWriterReconnectOnMsgAttr] + if isReconnectOnMsgStr { + if reconnectOnMsgStr == "true" { + reconnectOnMsg = true + } else if reconnectOnMsgStr == "false" { + reconnectOnMsg = false + } else { + return nil, errors.New("node '" + node.name + "' has incorrect '" + connWriterReconnectOnMsgAttr + "' attribute value") + } + } + + useTLS := false + useTLSStr, isUseTLSStr := node.attributes[connWriterUseTLSAttr] + if isUseTLSStr { + if useTLSStr == "true" { + useTLS = true + } else if useTLSStr == "false" { + useTLS = false + } else { + return nil, errors.New("node '" + node.name + "' has incorrect '" + connWriterUseTLSAttr + "' attribute value") + } + if useTLS { + insecureSkipVerify := false + insecureSkipVerifyStr, isInsecureSkipVerify := node.attributes[connWriterInsecureSkipVerifyAttr] + if isInsecureSkipVerify { + if insecureSkipVerifyStr == "true" { + insecureSkipVerify = true + } else if insecureSkipVerifyStr == "false" { + insecureSkipVerify = false + } else { + return nil, errors.New("node '" + node.name + "' has incorrect '" + connWriterInsecureSkipVerifyAttr + "' attribute value") + } + } + config := tls.Config{InsecureSkipVerify: insecureSkipVerify} + connWriter := newTLSWriter(net, addr, reconnectOnMsg, &config) + return NewFormattedWriter(connWriter, currentFormat) + } + } + + connWriter := NewConnWriter(net, addr, reconnectOnMsg) + + return NewFormattedWriter(connWriter, currentFormat) +} + +func createRollingFileWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *CfgParseParams) (interface{}, error) { + if node.hasChildren() { + return nil, errNodeCannotHaveChildren + } + + rollingTypeStr, isRollingType := node.attributes[rollingFileTypeAttr] + if !isRollingType { + return nil, newMissingArgumentError(node.name, rollingFileTypeAttr) + } + + rollingType, ok := rollingTypeFromString(rollingTypeStr) + if !ok { + return nil, errors.New("unknown rolling file type: " + rollingTypeStr) + } + + currentFormat, err := getCurrentFormat(node, formatFromParent, formats) + if err != nil { + return nil, err + } + + path, isPath := node.attributes[rollingFilePathAttr] + if !isPath { + return nil, newMissingArgumentError(node.name, rollingFilePathAttr) + } + + rollingArchiveStr, archiveAttrExists := node.attributes[rollingFileArchiveAttr] + + var rArchiveType rollingArchiveType + var rArchivePath string + if !archiveAttrExists { + rArchiveType = rollingArchiveNone + rArchivePath = "" + } else { + rArchiveType, ok = rollingArchiveTypeFromString(rollingArchiveStr) + if !ok { + return nil, errors.New("unknown rolling archive type: " + rollingArchiveStr) + } + + if rArchiveType == rollingArchiveNone { + rArchivePath = "" + } else { + rArchivePath, ok = node.attributes[rollingFileArchivePathAttr] + if !ok { + rArchivePath, ok = rollingArchiveTypesDefaultNames[rArchiveType] + if !ok { + return nil, fmt.Errorf("cannot get default filename for archive type = %v", + rArchiveType) + } + } + } + } + + nameMode := rollingNameMode(rollingNameModePostfix) + nameModeStr, ok := node.attributes[rollingFileNameModeAttr] + if ok { + mode, found := rollingNameModeFromString(nameModeStr) + if !found { + return nil, errors.New("unknown rolling filename mode: " + nameModeStr) + } else { + nameMode = mode + } + } + + if rollingType == rollingTypeSize { + err := checkUnexpectedAttribute(node, outputFormatID, rollingFileTypeAttr, rollingFilePathAttr, + rollingFileMaxSizeAttr, rollingFileMaxRollsAttr, rollingFileArchiveAttr, + rollingFileArchivePathAttr, rollingFileNameModeAttr) + if err != nil { + return nil, err + } + + maxSizeStr, ok := node.attributes[rollingFileMaxSizeAttr] + if !ok { + return nil, newMissingArgumentError(node.name, rollingFileMaxSizeAttr) + } + + maxSize, err := strconv.ParseInt(maxSizeStr, 10, 64) + if err != nil { + return nil, err + } + + maxRolls := 0 + maxRollsStr, ok := node.attributes[rollingFileMaxRollsAttr] + if ok { + maxRolls, err = strconv.Atoi(maxRollsStr) + if err != nil { + return nil, err + } + } + + rollingWriter, err := NewRollingFileWriterSize(path, rArchiveType, rArchivePath, maxSize, maxRolls, nameMode) + if err != nil { + return nil, err + } + + return NewFormattedWriter(rollingWriter, currentFormat) + + } else if rollingType == rollingTypeTime { + err := checkUnexpectedAttribute(node, outputFormatID, rollingFileTypeAttr, rollingFilePathAttr, + rollingFileDataPatternAttr, rollingFileArchiveAttr, rollingFileMaxRollsAttr, + rollingFileArchivePathAttr, rollingFileNameModeAttr) + if err != nil { + return nil, err + } + + maxRolls := 0 + maxRollsStr, ok := node.attributes[rollingFileMaxRollsAttr] + if ok { + maxRolls, err = strconv.Atoi(maxRollsStr) + if err != nil { + return nil, err + } + } + + dataPattern, ok := node.attributes[rollingFileDataPatternAttr] + if !ok { + return nil, newMissingArgumentError(node.name, rollingFileDataPatternAttr) + } + + rollingWriter, err := NewRollingFileWriterTime(path, rArchiveType, rArchivePath, maxRolls, dataPattern, rollingIntervalAny, nameMode) + if err != nil { + return nil, err + } + + return NewFormattedWriter(rollingWriter, currentFormat) + } + + return nil, errors.New("incorrect rolling writer type " + rollingTypeStr) +} + +func createbufferedWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *CfgParseParams) (interface{}, error) { + err := checkUnexpectedAttribute(node, outputFormatID, bufferedSizeAttr, bufferedFlushPeriodAttr) + if err != nil { + return nil, err + } + + if !node.hasChildren() { + return nil, errNodeMustHaveChildren + } + + currentFormat, err := getCurrentFormat(node, formatFromParent, formats) + if err != nil { + return nil, err + } + + sizeStr, isSize := node.attributes[bufferedSizeAttr] + if !isSize { + return nil, newMissingArgumentError(node.name, bufferedSizeAttr) + } + + size, err := strconv.Atoi(sizeStr) + if err != nil { + return nil, err + } + + flushPeriod := 0 + flushPeriodStr, isFlushPeriod := node.attributes[bufferedFlushPeriodAttr] + if isFlushPeriod { + flushPeriod, err = strconv.Atoi(flushPeriodStr) + if err != nil { + return nil, err + } + } + + // Inner writer couldn't have its own format, so we pass 'currentFormat' as its parent format + receivers, err := createInnerReceivers(node, currentFormat, formats, cfg) + if err != nil { + return nil, err + } + + formattedWriter, ok := receivers[0].(*formattedWriter) + if !ok { + return nil, errors.New("buffered writer's child is not writer") + } + + // ... and then we check that it hasn't changed + if formattedWriter.Format() != currentFormat { + return nil, errors.New("inner writer cannot have his own format") + } + + bufferedWriter, err := NewBufferedWriter(formattedWriter.Writer(), size, time.Duration(flushPeriod)) + if err != nil { + return nil, err + } + + return NewFormattedWriter(bufferedWriter, currentFormat) +} + +// Returns an error if node has any attributes not listed in expectedAttrs. +func checkUnexpectedAttribute(node *xmlNode, expectedAttrs ...string) error { + for attr := range node.attributes { + isExpected := false + for _, expected := range expectedAttrs { + if attr == expected { + isExpected = true + break + } + } + if !isExpected { + return newUnexpectedAttributeError(node.name, attr) + } + } + + return nil +} + +type expectedElementInfo struct { + name string + mandatory bool + multiple bool +} + +func optionalElement(name string) expectedElementInfo { + return expectedElementInfo{name, false, false} +} +func mandatoryElement(name string) expectedElementInfo { + return expectedElementInfo{name, true, false} +} +func multipleElements(name string) expectedElementInfo { + return expectedElementInfo{name, false, true} +} +func multipleMandatoryElements(name string) expectedElementInfo { + return expectedElementInfo{name, true, true} +} + +func checkExpectedElements(node *xmlNode, elements ...expectedElementInfo) error { + for _, element := range elements { + count := 0 + for _, child := range node.children { + if child.name == element.name { + count++ + } + } + + if count == 0 && element.mandatory { + return errors.New(node.name + " does not have mandatory subnode - " + element.name) + } + if count > 1 && !element.multiple { + return errors.New(node.name + " has more then one subnode - " + element.name) + } + } + + for _, child := range node.children { + isExpected := false + for _, element := range elements { + if child.name == element.name { + isExpected = true + } + } + + if !isExpected { + return errors.New(node.name + " has unexpected child: " + child.name) + } + } + + return nil +} diff --git a/vendor/github.com/cihub/seelog/common_closer.go b/vendor/github.com/cihub/seelog/common_closer.go new file mode 100644 index 00000000..1319c221 --- /dev/null +++ b/vendor/github.com/cihub/seelog/common_closer.go @@ -0,0 +1,25 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog diff --git a/vendor/github.com/cihub/seelog/common_constraints.go b/vendor/github.com/cihub/seelog/common_constraints.go new file mode 100644 index 00000000..7ec2fe5b --- /dev/null +++ b/vendor/github.com/cihub/seelog/common_constraints.go @@ -0,0 +1,162 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" + "fmt" + "strings" +) + +// Represents constraints which form a general rule for log levels selection +type logLevelConstraints interface { + IsAllowed(level LogLevel) bool +} + +// A minMaxConstraints represents constraints which use minimal and maximal allowed log levels. +type minMaxConstraints struct { + min LogLevel + max LogLevel +} + +// NewMinMaxConstraints creates a new minMaxConstraints struct with the specified min and max levels. +func NewMinMaxConstraints(min LogLevel, max LogLevel) (*minMaxConstraints, error) { + if min > max { + return nil, fmt.Errorf("min level can't be greater than max. Got min: %d, max: %d", min, max) + } + if min < TraceLvl || min > CriticalLvl { + return nil, fmt.Errorf("min level can't be less than Trace or greater than Critical. Got min: %d", min) + } + if max < TraceLvl || max > CriticalLvl { + return nil, fmt.Errorf("max level can't be less than Trace or greater than Critical. Got max: %d", max) + } + + return &minMaxConstraints{min, max}, nil +} + +// IsAllowed returns true, if log level is in [min, max] range (inclusive). +func (minMaxConstr *minMaxConstraints) IsAllowed(level LogLevel) bool { + return level >= minMaxConstr.min && level <= minMaxConstr.max +} + +func (minMaxConstr *minMaxConstraints) String() string { + return fmt.Sprintf("Min: %s. Max: %s", minMaxConstr.min, minMaxConstr.max) +} + +//======================================================= + +// A listConstraints represents constraints which use allowed log levels list. +type listConstraints struct { + allowedLevels map[LogLevel]bool +} + +// NewListConstraints creates a new listConstraints struct with the specified allowed levels. +func NewListConstraints(allowList []LogLevel) (*listConstraints, error) { + if allowList == nil { + return nil, errors.New("list can't be nil") + } + + allowLevels, err := createMapFromList(allowList) + if err != nil { + return nil, err + } + err = validateOffLevel(allowLevels) + if err != nil { + return nil, err + } + + return &listConstraints{allowLevels}, nil +} + +func (listConstr *listConstraints) String() string { + allowedList := "List: " + + listLevel := make([]string, len(listConstr.allowedLevels)) + + var logLevel LogLevel + i := 0 + for logLevel = TraceLvl; logLevel <= Off; logLevel++ { + if listConstr.allowedLevels[logLevel] { + listLevel[i] = logLevel.String() + i++ + } + } + + allowedList += strings.Join(listLevel, ",") + + return allowedList +} + +func createMapFromList(allowedList []LogLevel) (map[LogLevel]bool, error) { + allowedLevels := make(map[LogLevel]bool, 0) + for _, level := range allowedList { + if level < TraceLvl || level > Off { + return nil, fmt.Errorf("level can't be less than Trace or greater than Critical. Got level: %d", level) + } + allowedLevels[level] = true + } + return allowedLevels, nil +} +func validateOffLevel(allowedLevels map[LogLevel]bool) error { + if _, ok := allowedLevels[Off]; ok && len(allowedLevels) > 1 { + return errors.New("logLevel Off cant be mixed with other levels") + } + + return nil +} + +// IsAllowed returns true, if log level is in allowed log levels list. +// If the list contains the only item 'common.Off' then IsAllowed will always return false for any input values. +func (listConstr *listConstraints) IsAllowed(level LogLevel) bool { + for l := range listConstr.allowedLevels { + if l == level && level != Off { + return true + } + } + + return false +} + +// AllowedLevels returns allowed levels configuration as a map. +func (listConstr *listConstraints) AllowedLevels() map[LogLevel]bool { + return listConstr.allowedLevels +} + +//======================================================= + +type offConstraints struct { +} + +func NewOffConstraints() (*offConstraints, error) { + return &offConstraints{}, nil +} + +func (offConstr *offConstraints) IsAllowed(level LogLevel) bool { + return false +} + +func (offConstr *offConstraints) String() string { + return "Off constraint" +} diff --git a/vendor/github.com/cihub/seelog/common_context.go b/vendor/github.com/cihub/seelog/common_context.go new file mode 100644 index 00000000..04bc2235 --- /dev/null +++ b/vendor/github.com/cihub/seelog/common_context.go @@ -0,0 +1,194 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "time" +) + +var workingDir = "/" + +func init() { + wd, err := os.Getwd() + if err == nil { + workingDir = filepath.ToSlash(wd) + "/" + } +} + +// Represents runtime caller context. +type LogContextInterface interface { + // Caller's function name. + Func() string + // Caller's line number. + Line() int + // Caller's file short path (in slashed form). + ShortPath() string + // Caller's file full path (in slashed form). + FullPath() string + // Caller's file name (without path). + FileName() string + // True if the context is correct and may be used. + // If false, then an error in context evaluation occurred and + // all its other data may be corrupted. + IsValid() bool + // Time when log function was called. + CallTime() time.Time + // Custom context that can be set by calling logger.SetContext + CustomContext() interface{} +} + +// Returns context of the caller +func currentContext(custom interface{}) (LogContextInterface, error) { + return specifyContext(1, custom) +} + +func extractCallerInfo(skip int) (fullPath string, shortPath string, funcName string, line int, err error) { + pc, fp, ln, ok := runtime.Caller(skip) + if !ok { + err = fmt.Errorf("error during runtime.Caller") + return + } + line = ln + fullPath = fp + if strings.HasPrefix(fp, workingDir) { + shortPath = fp[len(workingDir):] + } else { + shortPath = fp + } + funcName = runtime.FuncForPC(pc).Name() + if strings.HasPrefix(funcName, workingDir) { + funcName = funcName[len(workingDir):] + } + return +} + +// Returns context of the function with placed "skip" stack frames of the caller +// If skip == 0 then behaves like currentContext +// Context is returned in any situation, even if error occurs. But, if an error +// occurs, the returned context is an error context, which contains no paths +// or names, but states that they can't be extracted. +func specifyContext(skip int, custom interface{}) (LogContextInterface, error) { + callTime := time.Now() + if skip < 0 { + err := fmt.Errorf("can not skip negative stack frames") + return &errorContext{callTime, err}, err + } + fullPath, shortPath, funcName, line, err := extractCallerInfo(skip + 2) + if err != nil { + return &errorContext{callTime, err}, err + } + _, fileName := filepath.Split(fullPath) + return &logContext{funcName, line, shortPath, fullPath, fileName, callTime, custom}, nil +} + +// Represents a normal runtime caller context. +type logContext struct { + funcName string + line int + shortPath string + fullPath string + fileName string + callTime time.Time + custom interface{} +} + +func (context *logContext) IsValid() bool { + return true +} + +func (context *logContext) Func() string { + return context.funcName +} + +func (context *logContext) Line() int { + return context.line +} + +func (context *logContext) ShortPath() string { + return context.shortPath +} + +func (context *logContext) FullPath() string { + return context.fullPath +} + +func (context *logContext) FileName() string { + return context.fileName +} + +func (context *logContext) CallTime() time.Time { + return context.callTime +} + +func (context *logContext) CustomContext() interface{} { + return context.custom +} + +// Represents an error context +type errorContext struct { + errorTime time.Time + err error +} + +func (errContext *errorContext) getErrorText(prefix string) string { + return fmt.Sprintf("%s() error: %s", prefix, errContext.err) +} + +func (errContext *errorContext) IsValid() bool { + return false +} + +func (errContext *errorContext) Line() int { + return -1 +} + +func (errContext *errorContext) Func() string { + return errContext.getErrorText("Func") +} + +func (errContext *errorContext) ShortPath() string { + return errContext.getErrorText("ShortPath") +} + +func (errContext *errorContext) FullPath() string { + return errContext.getErrorText("FullPath") +} + +func (errContext *errorContext) FileName() string { + return errContext.getErrorText("FileName") +} + +func (errContext *errorContext) CallTime() time.Time { + return errContext.errorTime +} + +func (errContext *errorContext) CustomContext() interface{} { + return nil +} diff --git a/vendor/github.com/cihub/seelog/common_exception.go b/vendor/github.com/cihub/seelog/common_exception.go new file mode 100644 index 00000000..9acc2750 --- /dev/null +++ b/vendor/github.com/cihub/seelog/common_exception.go @@ -0,0 +1,194 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" + "fmt" + "regexp" + "strings" +) + +// Used in rules creation to validate input file and func filters +var ( + fileFormatValidator = regexp.MustCompile(`[a-zA-Z0-9\\/ _\*\.]*`) + funcFormatValidator = regexp.MustCompile(`[a-zA-Z0-9_\*\.]*`) +) + +// LogLevelException represents an exceptional case used when you need some specific files or funcs to +// override general constraints and to use their own. +type LogLevelException struct { + funcPatternParts []string + filePatternParts []string + + funcPattern string + filePattern string + + constraints logLevelConstraints +} + +// NewLogLevelException creates a new exception. +func NewLogLevelException(funcPattern string, filePattern string, constraints logLevelConstraints) (*LogLevelException, error) { + if constraints == nil { + return nil, errors.New("constraints can not be nil") + } + + exception := new(LogLevelException) + + err := exception.initFuncPatternParts(funcPattern) + if err != nil { + return nil, err + } + exception.funcPattern = strings.Join(exception.funcPatternParts, "") + + err = exception.initFilePatternParts(filePattern) + if err != nil { + return nil, err + } + exception.filePattern = strings.Join(exception.filePatternParts, "") + + exception.constraints = constraints + + return exception, nil +} + +// MatchesContext returns true if context matches the patterns of this LogLevelException +func (logLevelEx *LogLevelException) MatchesContext(context LogContextInterface) bool { + return logLevelEx.match(context.Func(), context.FullPath()) +} + +// IsAllowed returns true if log level is allowed according to the constraints of this LogLevelException +func (logLevelEx *LogLevelException) IsAllowed(level LogLevel) bool { + return logLevelEx.constraints.IsAllowed(level) +} + +// FuncPattern returns the function pattern of a exception +func (logLevelEx *LogLevelException) FuncPattern() string { + return logLevelEx.funcPattern +} + +// FuncPattern returns the file pattern of a exception +func (logLevelEx *LogLevelException) FilePattern() string { + return logLevelEx.filePattern +} + +// initFuncPatternParts checks whether the func filter has a correct format and splits funcPattern on parts +func (logLevelEx *LogLevelException) initFuncPatternParts(funcPattern string) (err error) { + + if funcFormatValidator.FindString(funcPattern) != funcPattern { + return errors.New("func path \"" + funcPattern + "\" contains incorrect symbols. Only a-z A-Z 0-9 _ * . allowed)") + } + + logLevelEx.funcPatternParts = splitPattern(funcPattern) + return nil +} + +// Checks whether the file filter has a correct format and splits file patterns using splitPattern. +func (logLevelEx *LogLevelException) initFilePatternParts(filePattern string) (err error) { + + if fileFormatValidator.FindString(filePattern) != filePattern { + return errors.New("file path \"" + filePattern + "\" contains incorrect symbols. Only a-z A-Z 0-9 \\ / _ * . allowed)") + } + + logLevelEx.filePatternParts = splitPattern(filePattern) + return err +} + +func (logLevelEx *LogLevelException) match(funcPath string, filePath string) bool { + if !stringMatchesPattern(logLevelEx.funcPatternParts, funcPath) { + return false + } + return stringMatchesPattern(logLevelEx.filePatternParts, filePath) +} + +func (logLevelEx *LogLevelException) String() string { + str := fmt.Sprintf("Func: %s File: %s", logLevelEx.funcPattern, logLevelEx.filePattern) + + if logLevelEx.constraints != nil { + str += fmt.Sprintf("Constr: %s", logLevelEx.constraints) + } else { + str += "nil" + } + + return str +} + +// splitPattern splits pattern into strings and asterisks. Example: "ab*cde**f" -> ["ab", "*", "cde", "*", "f"] +func splitPattern(pattern string) []string { + var patternParts []string + var lastChar rune + for _, char := range pattern { + if char == '*' { + if lastChar != '*' { + patternParts = append(patternParts, "*") + } + } else { + if len(patternParts) != 0 && lastChar != '*' { + patternParts[len(patternParts)-1] += string(char) + } else { + patternParts = append(patternParts, string(char)) + } + } + lastChar = char + } + + return patternParts +} + +// stringMatchesPattern check whether testString matches pattern with asterisks. +// Standard regexp functionality is not used here because of performance issues. +func stringMatchesPattern(patternparts []string, testString string) bool { + if len(patternparts) == 0 { + return len(testString) == 0 + } + + part := patternparts[0] + if part != "*" { + index := strings.Index(testString, part) + if index == 0 { + return stringMatchesPattern(patternparts[1:], testString[len(part):]) + } + } else { + if len(patternparts) == 1 { + return true + } + + newTestString := testString + part = patternparts[1] + for { + index := strings.Index(newTestString, part) + if index == -1 { + break + } + + newTestString = newTestString[index+len(part):] + result := stringMatchesPattern(patternparts[2:], newTestString) + if result { + return true + } + } + } + return false +} diff --git a/vendor/github.com/cihub/seelog/common_flusher.go b/vendor/github.com/cihub/seelog/common_flusher.go new file mode 100644 index 00000000..0ef077c8 --- /dev/null +++ b/vendor/github.com/cihub/seelog/common_flusher.go @@ -0,0 +1,31 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +// flusherInterface represents all objects that have to do cleanup +// at certain moments of time (e.g. before app shutdown to avoid data loss) +type flusherInterface interface { + Flush() +} diff --git a/vendor/github.com/cihub/seelog/common_loglevel.go b/vendor/github.com/cihub/seelog/common_loglevel.go new file mode 100644 index 00000000..d54ecf27 --- /dev/null +++ b/vendor/github.com/cihub/seelog/common_loglevel.go @@ -0,0 +1,81 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +// Log level type +type LogLevel uint8 + +// Log levels +const ( + TraceLvl = iota + DebugLvl + InfoLvl + WarnLvl + ErrorLvl + CriticalLvl + Off +) + +// Log level string representations (used in configuration files) +const ( + TraceStr = "trace" + DebugStr = "debug" + InfoStr = "info" + WarnStr = "warn" + ErrorStr = "error" + CriticalStr = "critical" + OffStr = "off" +) + +var levelToStringRepresentations = map[LogLevel]string{ + TraceLvl: TraceStr, + DebugLvl: DebugStr, + InfoLvl: InfoStr, + WarnLvl: WarnStr, + ErrorLvl: ErrorStr, + CriticalLvl: CriticalStr, + Off: OffStr, +} + +// LogLevelFromString parses a string and returns a corresponding log level, if sucessfull. +func LogLevelFromString(levelStr string) (level LogLevel, found bool) { + for lvl, lvlStr := range levelToStringRepresentations { + if lvlStr == levelStr { + return lvl, true + } + } + + return 0, false +} + +// LogLevelToString returns seelog string representation for a specified level. Returns "" for invalid log levels. +func (level LogLevel) String() string { + levelStr, ok := levelToStringRepresentations[level] + if ok { + return levelStr + } + + return "" +} diff --git a/vendor/github.com/cihub/seelog/dispatch_custom.go b/vendor/github.com/cihub/seelog/dispatch_custom.go new file mode 100644 index 00000000..383a7705 --- /dev/null +++ b/vendor/github.com/cihub/seelog/dispatch_custom.go @@ -0,0 +1,242 @@ +// Copyright (c) 2013 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" + "fmt" + "reflect" + "sort" +) + +var registeredReceivers = make(map[string]reflect.Type) + +// RegisterReceiver records a custom receiver type, identified by a value +// of that type (second argument), under the specified name. Registered +// names can be used in the "name" attribute of config items. +// +// RegisterReceiver takes the type of the receiver argument, without taking +// the value into the account. So do NOT enter any data to the second argument +// and only call it like: +// RegisterReceiver("somename", &MyReceiverType{}) +// +// After that, when a '' config tag with this name is used, +// a receiver of the specified type would be instantiated. Check +// CustomReceiver comments for interface details. +// +// NOTE 1: RegisterReceiver fails if you attempt to register different types +// with the same name. +// +// NOTE 2: RegisterReceiver registers those receivers that must be used in +// the configuration files ( items). Basically it is just the way +// you tell seelog config parser what should it do when it meets a +// tag with a specific name and data attributes. +// +// But If you are only using seelog as a proxy to an already instantiated +// CustomReceiver (via LoggerFromCustomReceiver func), you should not call RegisterReceiver. +func RegisterReceiver(name string, receiver CustomReceiver) { + newType := reflect.TypeOf(reflect.ValueOf(receiver).Elem().Interface()) + if t, ok := registeredReceivers[name]; ok && t != newType { + panic(fmt.Sprintf("duplicate types for %s: %s != %s", name, t, newType)) + } + registeredReceivers[name] = newType +} + +func customReceiverByName(name string) (creceiver CustomReceiver, err error) { + rt, ok := registeredReceivers[name] + if !ok { + return nil, fmt.Errorf("custom receiver name not registered: '%s'", name) + } + v, ok := reflect.New(rt).Interface().(CustomReceiver) + if !ok { + return nil, fmt.Errorf("cannot instantiate receiver with name='%s'", name) + } + return v, nil +} + +// CustomReceiverInitArgs represent arguments passed to the CustomReceiver.Init +// func when custom receiver is being initialized. +type CustomReceiverInitArgs struct { + // XmlCustomAttrs represent '' xml config item attributes that + // start with "data-". Map keys will be the attribute names without the "data-". + // Map values will the those attribute values. + // + // E.g. if you have a '' + // you will get map with 2 key-value pairs: "attr1"->"a1", "attr2"->"a2" + // + // Note that in custom items you can only use allowed attributes, like "name" and + // your custom attributes, starting with "data-". Any other will lead to a + // parsing error. + XmlCustomAttrs map[string]string +} + +// CustomReceiver is the interface that external custom seelog message receivers +// must implement in order to be able to process seelog messages. Those receivers +// are set in the xml config file using the tag. Check receivers reference +// wiki section on that. +// +// Use seelog.RegisterReceiver on the receiver type before using it. +type CustomReceiver interface { + // ReceiveMessage is called when the custom receiver gets seelog message from + // a parent dispatcher. + // + // Message, level and context args represent all data that was included in the seelog + // message at the time it was logged. + // + // The formatting is already applied to the message and depends on the config + // like with any other receiver. + // + // If you would like to inform seelog of an error that happened during the handling of + // the message, return a non-nil error. This way you'll end up seeing your error like + // any other internal seelog error. + ReceiveMessage(message string, level LogLevel, context LogContextInterface) error + + // AfterParse is called immediately after your custom receiver is instantiated by + // the xml config parser. So, if you need to do any startup logic after config parsing, + // like opening file or allocating any resources after the receiver is instantiated, do it here. + // + // If this func returns a non-nil error, then the loading procedure will fail. E.g. + // if you are loading a seelog xml config, the parser would not finish the loading + // procedure and inform about an error like with any other config error. + // + // If your custom logger needs some configuration, you can use custom attributes in + // your config. Check CustomReceiverInitArgs.XmlCustomAttrs comments. + // + // IMPORTANT: This func is NOT called when the LoggerFromCustomReceiver func is used + // to create seelog proxy logger using the custom receiver. This func is only called when + // receiver is instantiated from a config. + AfterParse(initArgs CustomReceiverInitArgs) error + + // Flush is called when the custom receiver gets a 'flush' directive from a + // parent receiver. If custom receiver implements some kind of buffering or + // queing, then the appropriate reaction on a flush message is synchronous + // flushing of all those queues/buffers. If custom receiver doesn't have + // such mechanisms, then flush implementation may be left empty. + Flush() + + // Close is called when the custom receiver gets a 'close' directive from a + // parent receiver. This happens when a top-level seelog dispatcher is sending + // 'close' to all child nodes and it means that current seelog logger is being closed. + // If you need to do any cleanup after your custom receiver is done, you should do + // it here. + Close() error +} + +type customReceiverDispatcher struct { + formatter *formatter + innerReceiver CustomReceiver + customReceiverName string + usedArgs CustomReceiverInitArgs +} + +// NewCustomReceiverDispatcher creates a customReceiverDispatcher which dispatches data to a specific receiver created +// using a tag in the config file. +func NewCustomReceiverDispatcher(formatter *formatter, customReceiverName string, cArgs CustomReceiverInitArgs) (*customReceiverDispatcher, error) { + if formatter == nil { + return nil, errors.New("formatter cannot be nil") + } + if len(customReceiverName) == 0 { + return nil, errors.New("custom receiver name cannot be empty") + } + + creceiver, err := customReceiverByName(customReceiverName) + if err != nil { + return nil, err + } + err = creceiver.AfterParse(cArgs) + if err != nil { + return nil, err + } + disp := &customReceiverDispatcher{formatter, creceiver, customReceiverName, cArgs} + + return disp, nil +} + +// NewCustomReceiverDispatcherByValue is basically the same as NewCustomReceiverDispatcher, but using +// a specific CustomReceiver value instead of instantiating a new one by type. +func NewCustomReceiverDispatcherByValue(formatter *formatter, customReceiver CustomReceiver, name string, cArgs CustomReceiverInitArgs) (*customReceiverDispatcher, error) { + if formatter == nil { + return nil, errors.New("formatter cannot be nil") + } + if customReceiver == nil { + return nil, errors.New("customReceiver cannot be nil") + } + disp := &customReceiverDispatcher{formatter, customReceiver, name, cArgs} + + return disp, nil +} + +// CustomReceiver implementation. Check CustomReceiver comments. +func (disp *customReceiverDispatcher) Dispatch( + message string, + level LogLevel, + context LogContextInterface, + errorFunc func(err error)) { + + defer func() { + if err := recover(); err != nil { + errorFunc(fmt.Errorf("panic in custom receiver '%s'.Dispatch: %s", reflect.TypeOf(disp.innerReceiver), err)) + } + }() + + err := disp.innerReceiver.ReceiveMessage(disp.formatter.Format(message, level, context), level, context) + if err != nil { + errorFunc(err) + } +} + +// CustomReceiver implementation. Check CustomReceiver comments. +func (disp *customReceiverDispatcher) Flush() { + disp.innerReceiver.Flush() +} + +// CustomReceiver implementation. Check CustomReceiver comments. +func (disp *customReceiverDispatcher) Close() error { + disp.innerReceiver.Flush() + + err := disp.innerReceiver.Close() + if err != nil { + return err + } + + return nil +} + +func (disp *customReceiverDispatcher) String() string { + datas := "" + skeys := make([]string, 0, len(disp.usedArgs.XmlCustomAttrs)) + for i := range disp.usedArgs.XmlCustomAttrs { + skeys = append(skeys, i) + } + sort.Strings(skeys) + for _, key := range skeys { + datas += fmt.Sprintf("<%s, %s> ", key, disp.usedArgs.XmlCustomAttrs[key]) + } + + str := fmt.Sprintf("Custom receiver %s [fmt='%s'],[data='%s'],[inner='%s']\n", + disp.customReceiverName, disp.formatter.String(), datas, disp.innerReceiver) + + return str +} diff --git a/vendor/github.com/cihub/seelog/dispatch_dispatcher.go b/vendor/github.com/cihub/seelog/dispatch_dispatcher.go new file mode 100644 index 00000000..2bd3b4a4 --- /dev/null +++ b/vendor/github.com/cihub/seelog/dispatch_dispatcher.go @@ -0,0 +1,189 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" + "fmt" + "io" +) + +// A dispatcherInterface is used to dispatch message to all underlying receivers. +// Dispatch logic depends on given context and log level. Any errors are reported using errorFunc. +// Also, as underlying receivers may have a state, dispatcher has a ShuttingDown method which performs +// an immediate cleanup of all data that is stored in the receivers +type dispatcherInterface interface { + flusherInterface + io.Closer + Dispatch(message string, level LogLevel, context LogContextInterface, errorFunc func(err error)) +} + +type dispatcher struct { + formatter *formatter + writers []*formattedWriter + dispatchers []dispatcherInterface +} + +// Creates a dispatcher which dispatches data to a list of receivers. +// Each receiver should be either a Dispatcher or io.Writer, otherwise an error will be returned +func createDispatcher(formatter *formatter, receivers []interface{}) (*dispatcher, error) { + if formatter == nil { + return nil, errors.New("formatter cannot be nil") + } + if receivers == nil || len(receivers) == 0 { + return nil, errors.New("receivers cannot be nil or empty") + } + + disp := &dispatcher{formatter, make([]*formattedWriter, 0), make([]dispatcherInterface, 0)} + for _, receiver := range receivers { + writer, ok := receiver.(*formattedWriter) + if ok { + disp.writers = append(disp.writers, writer) + continue + } + + ioWriter, ok := receiver.(io.Writer) + if ok { + writer, err := NewFormattedWriter(ioWriter, disp.formatter) + if err != nil { + return nil, err + } + disp.writers = append(disp.writers, writer) + continue + } + + dispInterface, ok := receiver.(dispatcherInterface) + if ok { + disp.dispatchers = append(disp.dispatchers, dispInterface) + continue + } + + return nil, errors.New("method can receive either io.Writer or dispatcherInterface") + } + + return disp, nil +} + +func (disp *dispatcher) Dispatch( + message string, + level LogLevel, + context LogContextInterface, + errorFunc func(err error)) { + + for _, writer := range disp.writers { + err := writer.Write(message, level, context) + if err != nil { + errorFunc(err) + } + } + + for _, dispInterface := range disp.dispatchers { + dispInterface.Dispatch(message, level, context, errorFunc) + } +} + +// Flush goes through all underlying writers which implement flusherInterface interface +// and closes them. Recursively performs the same action for underlying dispatchers +func (disp *dispatcher) Flush() { + for _, disp := range disp.Dispatchers() { + disp.Flush() + } + + for _, formatWriter := range disp.Writers() { + flusher, ok := formatWriter.Writer().(flusherInterface) + if ok { + flusher.Flush() + } + } +} + +// Close goes through all underlying writers which implement io.Closer interface +// and closes them. Recursively performs the same action for underlying dispatchers +// Before closing, writers are flushed to prevent loss of any buffered data, so +// a call to Flush() func before Close() is not necessary +func (disp *dispatcher) Close() error { + for _, disp := range disp.Dispatchers() { + disp.Flush() + err := disp.Close() + if err != nil { + return err + } + } + + for _, formatWriter := range disp.Writers() { + flusher, ok := formatWriter.Writer().(flusherInterface) + if ok { + flusher.Flush() + } + + closer, ok := formatWriter.Writer().(io.Closer) + if ok { + err := closer.Close() + if err != nil { + return err + } + } + } + + return nil +} + +func (disp *dispatcher) Writers() []*formattedWriter { + return disp.writers +} + +func (disp *dispatcher) Dispatchers() []dispatcherInterface { + return disp.dispatchers +} + +func (disp *dispatcher) String() string { + str := "formatter: " + disp.formatter.String() + "\n" + + str += " ->Dispatchers:" + + if len(disp.dispatchers) == 0 { + str += "none\n" + } else { + str += "\n" + + for _, disp := range disp.dispatchers { + str += fmt.Sprintf(" ->%s", disp) + } + } + + str += " ->Writers:" + + if len(disp.writers) == 0 { + str += "none\n" + } else { + str += "\n" + + for _, writer := range disp.writers { + str += fmt.Sprintf(" ->%s\n", writer) + } + } + + return str +} diff --git a/vendor/github.com/cihub/seelog/dispatch_filterdispatcher.go b/vendor/github.com/cihub/seelog/dispatch_filterdispatcher.go new file mode 100644 index 00000000..9de8a722 --- /dev/null +++ b/vendor/github.com/cihub/seelog/dispatch_filterdispatcher.go @@ -0,0 +1,66 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "fmt" +) + +// A filterDispatcher writes the given message to underlying receivers only if message log level +// is in the allowed list. +type filterDispatcher struct { + *dispatcher + allowList map[LogLevel]bool +} + +// NewFilterDispatcher creates a new filterDispatcher using a list of allowed levels. +func NewFilterDispatcher(formatter *formatter, receivers []interface{}, allowList ...LogLevel) (*filterDispatcher, error) { + disp, err := createDispatcher(formatter, receivers) + if err != nil { + return nil, err + } + + allows := make(map[LogLevel]bool) + for _, allowLevel := range allowList { + allows[allowLevel] = true + } + + return &filterDispatcher{disp, allows}, nil +} + +func (filter *filterDispatcher) Dispatch( + message string, + level LogLevel, + context LogContextInterface, + errorFunc func(err error)) { + isAllowed, ok := filter.allowList[level] + if ok && isAllowed { + filter.dispatcher.Dispatch(message, level, context, errorFunc) + } +} + +func (filter *filterDispatcher) String() string { + return fmt.Sprintf("filterDispatcher ->\n%s", filter.dispatcher) +} diff --git a/vendor/github.com/cihub/seelog/dispatch_splitdispatcher.go b/vendor/github.com/cihub/seelog/dispatch_splitdispatcher.go new file mode 100644 index 00000000..1d0fe7ea --- /dev/null +++ b/vendor/github.com/cihub/seelog/dispatch_splitdispatcher.go @@ -0,0 +1,47 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "fmt" +) + +// A splitDispatcher just writes the given message to underlying receivers. (Splits the message stream.) +type splitDispatcher struct { + *dispatcher +} + +func NewSplitDispatcher(formatter *formatter, receivers []interface{}) (*splitDispatcher, error) { + disp, err := createDispatcher(formatter, receivers) + if err != nil { + return nil, err + } + + return &splitDispatcher{disp}, nil +} + +func (splitter *splitDispatcher) String() string { + return fmt.Sprintf("splitDispatcher ->\n%s", splitter.dispatcher.String()) +} diff --git a/vendor/github.com/cihub/seelog/doc.go b/vendor/github.com/cihub/seelog/doc.go new file mode 100644 index 00000000..2734c9cb --- /dev/null +++ b/vendor/github.com/cihub/seelog/doc.go @@ -0,0 +1,175 @@ +// Copyright (c) 2014 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +/* +Package seelog implements logging functionality with flexible dispatching, filtering, and formatting. + +Creation + +To create a logger, use one of the following constructors: + func LoggerFromConfigAsBytes + func LoggerFromConfigAsFile + func LoggerFromConfigAsString + func LoggerFromWriterWithMinLevel + func LoggerFromWriterWithMinLevelAndFormat + func LoggerFromCustomReceiver (check https://github.com/cihub/seelog/wiki/Custom-receivers) +Example: + import log "github.com/cihub/seelog" + + func main() { + logger, err := log.LoggerFromConfigAsFile("seelog.xml") + if err != nil { + panic(err) + } + defer logger.Flush() + ... use logger ... + } +The "defer" line is important because if you are using asynchronous logger behavior, without this line you may end up losing some +messages when you close your application because they are processed in another non-blocking goroutine. To avoid that you +explicitly defer flushing all messages before closing. + +Usage + +Logger created using one of the LoggerFrom* funcs can be used directly by calling one of the main log funcs. +Example: + import log "github.com/cihub/seelog" + + func main() { + logger, err := log.LoggerFromConfigAsFile("seelog.xml") + if err != nil { + panic(err) + } + defer logger.Flush() + logger.Trace("test") + logger.Debugf("var = %s", "abc") + } + +Having loggers as variables is convenient if you are writing your own package with internal logging or if you have +several loggers with different options. +But for most standalone apps it is more convenient to use package level funcs and vars. There is a package level +var 'Current' made for it. You can replace it with another logger using 'ReplaceLogger' and then use package level funcs: + import log "github.com/cihub/seelog" + + func main() { + logger, err := log.LoggerFromConfigAsFile("seelog.xml") + if err != nil { + panic(err) + } + log.ReplaceLogger(logger) + defer log.Flush() + log.Trace("test") + log.Debugf("var = %s", "abc") + } +Last lines + log.Trace("test") + log.Debugf("var = %s", "abc") +do the same as + log.Current.Trace("test") + log.Current.Debugf("var = %s", "abc") +In this example the 'Current' logger was replaced using a 'ReplaceLogger' call and became equal to 'logger' variable created from config. +This way you are able to use package level funcs instead of passing the logger variable. + +Configuration + +Main seelog point is to configure logger via config files and not the code. +The configuration is read by LoggerFrom* funcs. These funcs read xml configuration from different sources and try +to create a logger using it. + +All the configuration features are covered in detail in the official wiki: https://github.com/cihub/seelog/wiki. +There are many sections covering different aspects of seelog, but the most important for understanding configs are: + https://github.com/cihub/seelog/wiki/Constraints-and-exceptions + https://github.com/cihub/seelog/wiki/Dispatchers-and-receivers + https://github.com/cihub/seelog/wiki/Formatting + https://github.com/cihub/seelog/wiki/Logger-types +After you understand these concepts, check the 'Reference' section on the main wiki page to get the up-to-date +list of dispatchers, receivers, formats, and logger types. + +Here is an example config with all these features: + + + + + + + + + + + + + + + + + + + + + +This config represents a logger with adaptive timeout between log messages (check logger types reference) which +logs to console, all.log, and errors.log depending on the log level. Its output formats also depend on log level. This logger will only +use log level 'debug' and higher (minlevel is set) for all files with names that don't start with 'test'. For files starting with 'test' +this logger prohibits all levels below 'error'. + +Configuration using code + +Although configuration using code is not recommended, it is sometimes needed and it is possible to do with seelog. Basically, what +you need to do to get started is to create constraints, exceptions and a dispatcher tree (same as with config). Most of the New* +functions in this package are used to provide such capabilities. + +Here is an example of configuration in code, that demonstrates an async loop logger that logs to a simple split dispatcher with +a console receiver using a specified format and is filtered using a top-level min-max constraints and one expection for +the 'main.go' file. So, this is basically a demonstration of configuration of most of the features: + + package main + + import log "github.com/cihub/seelog" + + func main() { + defer log.Flush() + log.Info("Hello from Seelog!") + + consoleWriter, _ := log.NewConsoleWriter() + formatter, _ := log.NewFormatter("%Level %Msg %File%n") + root, _ := log.NewSplitDispatcher(formatter, []interface{}{consoleWriter}) + constraints, _ := log.NewMinMaxConstraints(log.TraceLvl, log.CriticalLvl) + specificConstraints, _ := log.NewListConstraints([]log.LogLevel{log.InfoLvl, log.ErrorLvl}) + ex, _ := log.NewLogLevelException("*", "*main.go", specificConstraints) + exceptions := []*log.LogLevelException{ex} + + logger := log.NewAsyncLoopLogger(log.NewLoggerConfig(constraints, exceptions, root)) + log.ReplaceLogger(logger) + + log.Trace("This should not be seen") + log.Debug("This should not be seen") + log.Info("Test") + log.Error("Test2") + } + +Examples + +To learn seelog features faster you should check the examples package: https://github.com/cihub/seelog-examples +It contains many example configs and usecases. +*/ +package seelog diff --git a/vendor/github.com/cihub/seelog/format.go b/vendor/github.com/cihub/seelog/format.go new file mode 100644 index 00000000..32682f34 --- /dev/null +++ b/vendor/github.com/cihub/seelog/format.go @@ -0,0 +1,461 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "bytes" + "errors" + "fmt" + "strconv" + "strings" + "unicode" + "unicode/utf8" +) + +// FormatterSymbol is a special symbol used in config files to mark special format aliases. +const ( + FormatterSymbol = '%' +) + +const ( + formatterParameterStart = '(' + formatterParameterEnd = ')' +) + +// Time and date formats used for %Date and %Time aliases. +const ( + DateDefaultFormat = "2006-01-02" + TimeFormat = "15:04:05" +) + +var DefaultMsgFormat = "%Ns [%Level] %Msg%n" + +var ( + DefaultFormatter *formatter + msgonlyformatter *formatter +) + +func init() { + var err error + if DefaultFormatter, err = NewFormatter(DefaultMsgFormat); err != nil { + reportInternalError(fmt.Errorf("error during creating DefaultFormatter: %s", err)) + } + if msgonlyformatter, err = NewFormatter("%Msg"); err != nil { + reportInternalError(fmt.Errorf("error during creating msgonlyformatter: %s", err)) + } +} + +// FormatterFunc represents one formatter object that starts with '%' sign in the 'format' attribute +// of the 'format' config item. These special symbols are replaced with context values or special +// strings when message is written to byte receiver. +// +// Check https://github.com/cihub/seelog/wiki/Formatting for details. +// Full list (with descriptions) of formatters: https://github.com/cihub/seelog/wiki/Format-reference +// +// FormatterFunc takes raw log message, level, log context and returns a string, number (of any type) or any object +// that can be evaluated as string. +type FormatterFunc func(message string, level LogLevel, context LogContextInterface) interface{} + +// FormatterFuncCreator is a factory of FormatterFunc objects. It is used to generate parameterized +// formatters (such as %Date or %EscM) and custom user formatters. +type FormatterFuncCreator func(param string) FormatterFunc + +var formatterFuncs = map[string]FormatterFunc{ + "Level": formatterLevel, + "Lev": formatterLev, + "LEVEL": formatterLEVEL, + "LEV": formatterLEV, + "l": formatterl, + "Msg": formatterMsg, + "FullPath": formatterFullPath, + "File": formatterFile, + "RelFile": formatterRelFile, + "Func": FormatterFunction, + "FuncShort": FormatterFunctionShort, + "Line": formatterLine, + "Time": formatterTime, + "UTCTime": formatterUTCTime, + "Ns": formatterNs, + "UTCNs": formatterUTCNs, + "n": formattern, + "t": formattert, +} + +var formatterFuncsParameterized = map[string]FormatterFuncCreator{ + "Date": createDateTimeFormatterFunc, + "UTCDate": createUTCDateTimeFormatterFunc, + "EscM": createANSIEscapeFunc, +} + +func errorAliasReserved(name string) error { + return fmt.Errorf("cannot use '%s' as custom formatter name. Name is reserved", name) +} + +// RegisterCustomFormatter registers a new custom formatter factory with a given name. If returned error is nil, +// then this name (prepended by '%' symbol) can be used in 'format' attributes in configuration and +// it will be treated like the standard parameterized formatter identifiers. +// +// RegisterCustomFormatter needs to be called before creating a logger for it to take effect. The general recommendation +// is to call it once in 'init' func of your application or any initializer func. +// +// For usage examples, check https://github.com/cihub/seelog/wiki/Custom-formatters. +// +// Name must only consist of letters (unicode.IsLetter). +// +// Name must not be one of the already registered standard formatter names +// (https://github.com/cihub/seelog/wiki/Format-reference) and previously registered +// custom format names. To avoid any potential name conflicts (in future releases), it is recommended +// to start your custom formatter name with a namespace (e.g. 'MyCompanySomething') or a 'Custom' keyword. +func RegisterCustomFormatter(name string, creator FormatterFuncCreator) error { + if _, ok := formatterFuncs[name]; ok { + return errorAliasReserved(name) + } + if _, ok := formatterFuncsParameterized[name]; ok { + return errorAliasReserved(name) + } + formatterFuncsParameterized[name] = creator + return nil +} + +// formatter is used to write messages in a specific format, inserting such additional data +// as log level, date/time, etc. +type formatter struct { + fmtStringOriginal string + fmtString string + formatterFuncs []FormatterFunc +} + +// NewFormatter creates a new formatter using a format string +func NewFormatter(formatString string) (*formatter, error) { + fmtr := new(formatter) + fmtr.fmtStringOriginal = formatString + if err := buildFormatterFuncs(fmtr); err != nil { + return nil, err + } + return fmtr, nil +} + +func buildFormatterFuncs(formatter *formatter) error { + var ( + fsbuf = new(bytes.Buffer) + fsolm1 = len(formatter.fmtStringOriginal) - 1 + ) + for i := 0; i <= fsolm1; i++ { + if char := formatter.fmtStringOriginal[i]; char != FormatterSymbol { + fsbuf.WriteByte(char) + continue + } + // Check if the index is at the end of the string. + if i == fsolm1 { + return fmt.Errorf("format error: %c cannot be last symbol", FormatterSymbol) + } + // Check if the formatter symbol is doubled and skip it as nonmatching. + if formatter.fmtStringOriginal[i+1] == FormatterSymbol { + fsbuf.WriteRune(FormatterSymbol) + i++ + continue + } + function, ni, err := formatter.extractFormatterFunc(i + 1) + if err != nil { + return err + } + // Append formatting string "%v". + fsbuf.Write([]byte{37, 118}) + i = ni + formatter.formatterFuncs = append(formatter.formatterFuncs, function) + } + formatter.fmtString = fsbuf.String() + return nil +} + +func (formatter *formatter) extractFormatterFunc(index int) (FormatterFunc, int, error) { + letterSequence := formatter.extractLetterSequence(index) + if len(letterSequence) == 0 { + return nil, 0, fmt.Errorf("format error: lack of formatter after %c at %d", FormatterSymbol, index) + } + + function, formatterLength, ok := formatter.findFormatterFunc(letterSequence) + if ok { + return function, index + formatterLength - 1, nil + } + + function, formatterLength, ok, err := formatter.findFormatterFuncParametrized(letterSequence, index) + if err != nil { + return nil, 0, err + } + if ok { + return function, index + formatterLength - 1, nil + } + + return nil, 0, errors.New("format error: unrecognized formatter at " + strconv.Itoa(index) + ": " + letterSequence) +} + +func (formatter *formatter) extractLetterSequence(index int) string { + letters := "" + + bytesToParse := []byte(formatter.fmtStringOriginal[index:]) + runeCount := utf8.RuneCount(bytesToParse) + for i := 0; i < runeCount; i++ { + rune, runeSize := utf8.DecodeRune(bytesToParse) + bytesToParse = bytesToParse[runeSize:] + + if unicode.IsLetter(rune) { + letters += string(rune) + } else { + break + } + } + return letters +} + +func (formatter *formatter) findFormatterFunc(letters string) (FormatterFunc, int, bool) { + currentVerb := letters + for i := 0; i < len(letters); i++ { + function, ok := formatterFuncs[currentVerb] + if ok { + return function, len(currentVerb), ok + } + currentVerb = currentVerb[:len(currentVerb)-1] + } + + return nil, 0, false +} + +func (formatter *formatter) findFormatterFuncParametrized(letters string, lettersStartIndex int) (FormatterFunc, int, bool, error) { + currentVerb := letters + for i := 0; i < len(letters); i++ { + functionCreator, ok := formatterFuncsParameterized[currentVerb] + if ok { + parameter := "" + parameterLen := 0 + isVerbEqualsLetters := i == 0 // if not, then letter goes after formatter, and formatter is parameterless + if isVerbEqualsLetters { + userParameter := "" + var err error + userParameter, parameterLen, ok, err = formatter.findparameter(lettersStartIndex + len(currentVerb)) + if ok { + parameter = userParameter + } else if err != nil { + return nil, 0, false, err + } + } + + return functionCreator(parameter), len(currentVerb) + parameterLen, true, nil + } + + currentVerb = currentVerb[:len(currentVerb)-1] + } + + return nil, 0, false, nil +} + +func (formatter *formatter) findparameter(startIndex int) (string, int, bool, error) { + if len(formatter.fmtStringOriginal) == startIndex || formatter.fmtStringOriginal[startIndex] != formatterParameterStart { + return "", 0, false, nil + } + + endIndex := strings.Index(formatter.fmtStringOriginal[startIndex:], string(formatterParameterEnd)) + if endIndex == -1 { + return "", 0, false, fmt.Errorf("Unmatched parenthesis or invalid parameter at %d: %s", + startIndex, formatter.fmtStringOriginal[startIndex:]) + } + endIndex += startIndex + + length := endIndex - startIndex + 1 + + return formatter.fmtStringOriginal[startIndex+1 : endIndex], length, true, nil +} + +// Format processes a message with special formatters, log level, and context. Returns formatted string +// with all formatter identifiers changed to appropriate values. +func (formatter *formatter) Format(message string, level LogLevel, context LogContextInterface) string { + if len(formatter.formatterFuncs) == 0 { + return formatter.fmtString + } + + params := make([]interface{}, len(formatter.formatterFuncs)) + for i, function := range formatter.formatterFuncs { + params[i] = function(message, level, context) + } + + return fmt.Sprintf(formatter.fmtString, params...) +} + +func (formatter *formatter) String() string { + return formatter.fmtStringOriginal +} + +//===================================================== + +const ( + wrongLogLevel = "WRONG_LOGLEVEL" + wrongEscapeCode = "WRONG_ESCAPE" +) + +var levelToString = map[LogLevel]string{ + TraceLvl: "Trace", + DebugLvl: "Debug", + InfoLvl: "Info", + WarnLvl: "Warn", + ErrorLvl: "Error", + CriticalLvl: "Critical", + Off: "Off", +} + +var levelToShortString = map[LogLevel]string{ + TraceLvl: "Trc", + DebugLvl: "Dbg", + InfoLvl: "Inf", + WarnLvl: "Wrn", + ErrorLvl: "Err", + CriticalLvl: "Crt", + Off: "Off", +} + +var levelToShortestString = map[LogLevel]string{ + TraceLvl: "t", + DebugLvl: "d", + InfoLvl: "i", + WarnLvl: "w", + ErrorLvl: "e", + CriticalLvl: "c", + Off: "o", +} + +func formatterLevel(message string, level LogLevel, context LogContextInterface) interface{} { + levelStr, ok := levelToString[level] + if !ok { + return wrongLogLevel + } + return levelStr +} + +func formatterLev(message string, level LogLevel, context LogContextInterface) interface{} { + levelStr, ok := levelToShortString[level] + if !ok { + return wrongLogLevel + } + return levelStr +} + +func formatterLEVEL(message string, level LogLevel, context LogContextInterface) interface{} { + return strings.ToTitle(formatterLevel(message, level, context).(string)) +} + +func formatterLEV(message string, level LogLevel, context LogContextInterface) interface{} { + return strings.ToTitle(formatterLev(message, level, context).(string)) +} + +func formatterl(message string, level LogLevel, context LogContextInterface) interface{} { + levelStr, ok := levelToShortestString[level] + if !ok { + return wrongLogLevel + } + return levelStr +} + +func formatterMsg(message string, level LogLevel, context LogContextInterface) interface{} { + return message +} + +func formatterFullPath(message string, level LogLevel, context LogContextInterface) interface{} { + return context.FullPath() +} + +func formatterFile(message string, level LogLevel, context LogContextInterface) interface{} { + return context.FileName() +} + +func formatterRelFile(message string, level LogLevel, context LogContextInterface) interface{} { + return context.ShortPath() +} + +func FormatterFunction(message string, level LogLevel, context LogContextInterface) interface{} { + return context.Func() +} + +func FormatterFunctionShort(message string, level LogLevel, context LogContextInterface) interface{} { + f := context.Func() + spl := strings.Split(f, ".") + return spl[len(spl)-1] +} + +func formatterLine(message string, level LogLevel, context LogContextInterface) interface{} { + return context.Line() +} + +func formatterTime(message string, level LogLevel, context LogContextInterface) interface{} { + return context.CallTime().Format(TimeFormat) +} + +func formatterUTCTime(message string, level LogLevel, context LogContextInterface) interface{} { + return context.CallTime().UTC().Format(TimeFormat) +} + +func formatterNs(message string, level LogLevel, context LogContextInterface) interface{} { + return context.CallTime().UnixNano() +} + +func formatterUTCNs(message string, level LogLevel, context LogContextInterface) interface{} { + return context.CallTime().UTC().UnixNano() +} + +func formattern(message string, level LogLevel, context LogContextInterface) interface{} { + return "\n" +} + +func formattert(message string, level LogLevel, context LogContextInterface) interface{} { + return "\t" +} + +func createDateTimeFormatterFunc(dateTimeFormat string) FormatterFunc { + format := dateTimeFormat + if format == "" { + format = DateDefaultFormat + } + return func(message string, level LogLevel, context LogContextInterface) interface{} { + return context.CallTime().Format(format) + } +} + +func createUTCDateTimeFormatterFunc(dateTimeFormat string) FormatterFunc { + format := dateTimeFormat + if format == "" { + format = DateDefaultFormat + } + return func(message string, level LogLevel, context LogContextInterface) interface{} { + return context.CallTime().UTC().Format(format) + } +} + +func createANSIEscapeFunc(escapeCodeString string) FormatterFunc { + return func(message string, level LogLevel, context LogContextInterface) interface{} { + if len(escapeCodeString) == 0 { + return wrongEscapeCode + } + + return fmt.Sprintf("%c[%sm", 0x1B, escapeCodeString) + } +} diff --git a/vendor/github.com/cihub/seelog/internals_baseerror.go b/vendor/github.com/cihub/seelog/internals_baseerror.go new file mode 100644 index 00000000..c0b271d7 --- /dev/null +++ b/vendor/github.com/cihub/seelog/internals_baseerror.go @@ -0,0 +1,10 @@ +package seelog + +// Base struct for custom errors. +type baseError struct { + message string +} + +func (be baseError) Error() string { + return be.message +} diff --git a/vendor/github.com/cihub/seelog/internals_fsutils.go b/vendor/github.com/cihub/seelog/internals_fsutils.go new file mode 100644 index 00000000..5baa6ba6 --- /dev/null +++ b/vendor/github.com/cihub/seelog/internals_fsutils.go @@ -0,0 +1,403 @@ +package seelog + +import ( + "archive/zip" + "bytes" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "sync" +) + +// File and directory permitions. +const ( + defaultFilePermissions = 0666 + defaultDirectoryPermissions = 0767 +) + +const ( + // Max number of directories can be read asynchronously. + maxDirNumberReadAsync = 1000 +) + +type cannotOpenFileError struct { + baseError +} + +func newCannotOpenFileError(fname string) *cannotOpenFileError { + return &cannotOpenFileError{baseError{message: "Cannot open file: " + fname}} +} + +type notDirectoryError struct { + baseError +} + +func newNotDirectoryError(dname string) *notDirectoryError { + return ¬DirectoryError{baseError{message: dname + " is not directory"}} +} + +// fileFilter is a filtering criteria function for '*os.File'. +// Must return 'false' to set aside the given file. +type fileFilter func(os.FileInfo, *os.File) bool + +// filePathFilter is a filtering creteria function for file path. +// Must return 'false' to set aside the given file. +type filePathFilter func(filePath string) bool + +// GetSubdirNames returns a list of directories found in +// the given one with dirPath. +func getSubdirNames(dirPath string) ([]string, error) { + fi, err := os.Stat(dirPath) + if err != nil { + return nil, err + } + if !fi.IsDir() { + return nil, newNotDirectoryError(dirPath) + } + dd, err := os.Open(dirPath) + // Cannot open file. + if err != nil { + if dd != nil { + dd.Close() + } + return nil, err + } + defer dd.Close() + // TODO: Improve performance by buffering reading. + allEntities, err := dd.Readdir(-1) + if err != nil { + return nil, err + } + subDirs := []string{} + for _, entity := range allEntities { + if entity.IsDir() { + subDirs = append(subDirs, entity.Name()) + } + } + return subDirs, nil +} + +// getSubdirAbsPaths recursively visit all the subdirectories +// starting from the given directory and returns absolute paths for them. +func getAllSubdirAbsPaths(dirPath string) (res []string, err error) { + dps, err := getSubdirAbsPaths(dirPath) + if err != nil { + res = []string{} + return + } + res = append(res, dps...) + for _, dp := range dps { + sdps, err := getAllSubdirAbsPaths(dp) + if err != nil { + return []string{}, err + } + res = append(res, sdps...) + } + return +} + +// getSubdirAbsPaths supplies absolute paths for all subdirectiries in a given directory. +// Input: (I1) dirPath - absolute path of a directory in question. +// Out: (O1) - slice of subdir asbolute paths; (O2) - error of the operation. +// Remark: If error (O2) is non-nil then (O1) is nil and vice versa. +func getSubdirAbsPaths(dirPath string) ([]string, error) { + sdns, err := getSubdirNames(dirPath) + if err != nil { + return nil, err + } + rsdns := []string{} + for _, sdn := range sdns { + rsdns = append(rsdns, filepath.Join(dirPath, sdn)) + } + return rsdns, nil +} + +// getOpenFilesInDir supplies a slice of os.File pointers to files located in the directory. +// Remark: Ignores files for which fileFilter returns false +func getOpenFilesInDir(dirPath string, fFilter fileFilter) ([]*os.File, error) { + dfi, err := os.Open(dirPath) + if err != nil { + return nil, newCannotOpenFileError("Cannot open directory " + dirPath) + } + defer dfi.Close() + // Size of read buffer (i.e. chunk of items read at a time). + rbs := 64 + resFiles := []*os.File{} +L: + for { + // Read directory entities by reasonable chuncks + // to prevent overflows on big number of files. + fis, e := dfi.Readdir(rbs) + switch e { + // It's OK. + case nil: + // Do nothing, just continue cycle. + case io.EOF: + break L + // Something went wrong. + default: + return nil, e + } + // THINK: Maybe, use async running. + for _, fi := range fis { + // NB: On Linux this could be a problem as + // there are lots of file types available. + if !fi.IsDir() { + f, e := os.Open(filepath.Join(dirPath, fi.Name())) + if e != nil { + if f != nil { + f.Close() + } + // THINK: Add nil as indicator that a problem occurred. + resFiles = append(resFiles, nil) + continue + } + // Check filter condition. + if fFilter != nil && !fFilter(fi, f) { + continue + } + resFiles = append(resFiles, f) + } + } + } + return resFiles, nil +} + +func isRegular(m os.FileMode) bool { + return m&os.ModeType == 0 +} + +// getDirFilePaths return full paths of the files located in the directory. +// Remark: Ignores files for which fileFilter returns false. +func getDirFilePaths(dirPath string, fpFilter filePathFilter, pathIsName bool) ([]string, error) { + dfi, err := os.Open(dirPath) + if err != nil { + return nil, newCannotOpenFileError("Cannot open directory " + dirPath) + } + defer dfi.Close() + + var absDirPath string + if !filepath.IsAbs(dirPath) { + absDirPath, err = filepath.Abs(dirPath) + if err != nil { + return nil, fmt.Errorf("cannot get absolute path of directory: %s", err.Error()) + } + } else { + absDirPath = dirPath + } + + // TODO: check if dirPath is really directory. + // Size of read buffer (i.e. chunk of items read at a time). + rbs := 2 << 5 + filePaths := []string{} + + var fp string +L: + for { + // Read directory entities by reasonable chuncks + // to prevent overflows on big number of files. + fis, e := dfi.Readdir(rbs) + switch e { + // It's OK. + case nil: + // Do nothing, just continue cycle. + case io.EOF: + break L + // Indicate that something went wrong. + default: + return nil, e + } + // THINK: Maybe, use async running. + for _, fi := range fis { + // NB: Should work on every Windows and non-Windows OS. + if isRegular(fi.Mode()) { + if pathIsName { + fp = fi.Name() + } else { + // Build full path of a file. + fp = filepath.Join(absDirPath, fi.Name()) + } + // Check filter condition. + if fpFilter != nil && !fpFilter(fp) { + continue + } + filePaths = append(filePaths, fp) + } + } + } + return filePaths, nil +} + +// getOpenFilesByDirectoryAsync runs async reading directories 'dirPaths' and inserts pairs +// in map 'filesInDirMap': Key - directory name, value - *os.File slice. +func getOpenFilesByDirectoryAsync( + dirPaths []string, + fFilter fileFilter, + filesInDirMap map[string][]*os.File, +) error { + n := len(dirPaths) + if n > maxDirNumberReadAsync { + return fmt.Errorf("number of input directories to be read exceeded max value %d", maxDirNumberReadAsync) + } + type filesInDirResult struct { + DirName string + Files []*os.File + Error error + } + dirFilesChan := make(chan *filesInDirResult, n) + var wg sync.WaitGroup + // Register n goroutines which are going to do work. + wg.Add(n) + for i := 0; i < n; i++ { + // Launch asynchronously the piece of work. + go func(dirPath string) { + fs, e := getOpenFilesInDir(dirPath, fFilter) + dirFilesChan <- &filesInDirResult{filepath.Base(dirPath), fs, e} + // Mark the current goroutine as finished (work is done). + wg.Done() + }(dirPaths[i]) + } + // Wait for all goroutines to finish their work. + wg.Wait() + // Close the error channel to let for-range clause + // get all the buffered values without blocking and quit in the end. + close(dirFilesChan) + for fidr := range dirFilesChan { + if fidr.Error == nil { + // THINK: What will happen if the key is already present? + filesInDirMap[fidr.DirName] = fidr.Files + } else { + return fidr.Error + } + } + return nil +} + +func copyFile(sf *os.File, dst string) (int64, error) { + df, err := os.Create(dst) + if err != nil { + return 0, err + } + defer df.Close() + return io.Copy(df, sf) +} + +// fileExists return flag whether a given file exists +// and operation error if an unclassified failure occurs. +func fileExists(path string) (bool, error) { + _, err := os.Stat(path) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, err + } + return true, nil +} + +// createDirectory makes directory with a given name +// making all parent directories if necessary. +func createDirectory(dirPath string) error { + var dPath string + var err error + if !filepath.IsAbs(dirPath) { + dPath, err = filepath.Abs(dirPath) + if err != nil { + return err + } + } else { + dPath = dirPath + } + exists, err := fileExists(dPath) + if err != nil { + return err + } + if exists { + return nil + } + return os.MkdirAll(dPath, os.ModeDir) +} + +// tryRemoveFile gives a try removing the file +// only ignoring an error when the file does not exist. +func tryRemoveFile(filePath string) (err error) { + err = os.Remove(filePath) + if os.IsNotExist(err) { + err = nil + return + } + return +} + +// Unzips a specified zip file. Returns filename->filebytes map. +func unzip(archiveName string) (map[string][]byte, error) { + // Open a zip archive for reading. + r, err := zip.OpenReader(archiveName) + if err != nil { + return nil, err + } + defer r.Close() + + // Files to be added to archive + // map file name to contents + files := make(map[string][]byte) + + // Iterate through the files in the archive, + // printing some of their contents. + for _, f := range r.File { + rc, err := f.Open() + if err != nil { + return nil, err + } + + bts, err := ioutil.ReadAll(rc) + rcErr := rc.Close() + + if err != nil { + return nil, err + } + if rcErr != nil { + return nil, rcErr + } + + files[f.Name] = bts + } + + return files, nil +} + +// Creates a zip file with the specified file names and byte contents. +func createZip(archiveName string, files map[string][]byte) error { + // Create a buffer to write our archive to. + buf := new(bytes.Buffer) + + // Create a new zip archive. + w := zip.NewWriter(buf) + + // Write files + for fpath, fcont := range files { + f, err := w.Create(fpath) + if err != nil { + return err + } + _, err = f.Write([]byte(fcont)) + if err != nil { + return err + } + } + + // Make sure to check the error on Close. + err := w.Close() + if err != nil { + return err + } + + err = ioutil.WriteFile(archiveName, buf.Bytes(), defaultFilePermissions) + if err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/cihub/seelog/internals_xmlnode.go b/vendor/github.com/cihub/seelog/internals_xmlnode.go new file mode 100644 index 00000000..98588493 --- /dev/null +++ b/vendor/github.com/cihub/seelog/internals_xmlnode.go @@ -0,0 +1,175 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "encoding/xml" + "errors" + "fmt" + "io" + "strings" +) + +type xmlNode struct { + name string + attributes map[string]string + children []*xmlNode + value string +} + +func newNode() *xmlNode { + node := new(xmlNode) + node.children = make([]*xmlNode, 0) + node.attributes = make(map[string]string) + return node +} + +func (node *xmlNode) String() string { + str := fmt.Sprintf("<%s", node.name) + + for attrName, attrVal := range node.attributes { + str += fmt.Sprintf(" %s=\"%s\"", attrName, attrVal) + } + + str += ">" + str += node.value + + if len(node.children) != 0 { + for _, child := range node.children { + str += fmt.Sprintf("%s", child) + } + } + + str += fmt.Sprintf("", node.name) + + return str +} + +func (node *xmlNode) unmarshal(startEl xml.StartElement) error { + node.name = startEl.Name.Local + + for _, v := range startEl.Attr { + _, alreadyExists := node.attributes[v.Name.Local] + if alreadyExists { + return errors.New("tag '" + node.name + "' has duplicated attribute: '" + v.Name.Local + "'") + } + node.attributes[v.Name.Local] = v.Value + } + + return nil +} + +func (node *xmlNode) add(child *xmlNode) { + if node.children == nil { + node.children = make([]*xmlNode, 0) + } + + node.children = append(node.children, child) +} + +func (node *xmlNode) hasChildren() bool { + return node.children != nil && len(node.children) > 0 +} + +//============================================= + +func unmarshalConfig(reader io.Reader) (*xmlNode, error) { + xmlParser := xml.NewDecoder(reader) + + config, err := unmarshalNode(xmlParser, nil) + if err != nil { + return nil, err + } + if config == nil { + return nil, errors.New("xml has no content") + } + + nextConfigEntry, err := unmarshalNode(xmlParser, nil) + if nextConfigEntry != nil { + return nil, errors.New("xml contains more than one root element") + } + + return config, nil +} + +func unmarshalNode(xmlParser *xml.Decoder, curToken xml.Token) (node *xmlNode, err error) { + firstLoop := true + for { + var tok xml.Token + if firstLoop && curToken != nil { + tok = curToken + firstLoop = false + } else { + tok, err = getNextToken(xmlParser) + if err != nil || tok == nil { + return + } + } + + switch tt := tok.(type) { + case xml.SyntaxError: + err = errors.New(tt.Error()) + return + case xml.CharData: + value := strings.TrimSpace(string([]byte(tt))) + if node != nil { + node.value += value + } + case xml.StartElement: + if node == nil { + node = newNode() + err := node.unmarshal(tt) + if err != nil { + return nil, err + } + } else { + childNode, childErr := unmarshalNode(xmlParser, tok) + if childErr != nil { + return nil, childErr + } + + if childNode != nil { + node.add(childNode) + } else { + return + } + } + case xml.EndElement: + return + } + } +} + +func getNextToken(xmlParser *xml.Decoder) (tok xml.Token, err error) { + if tok, err = xmlParser.Token(); err != nil { + if err == io.EOF { + err = nil + return + } + return + } + + return +} diff --git a/vendor/github.com/cihub/seelog/log.go b/vendor/github.com/cihub/seelog/log.go new file mode 100644 index 00000000..f775e1fd --- /dev/null +++ b/vendor/github.com/cihub/seelog/log.go @@ -0,0 +1,307 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" + "fmt" + "sync" + "time" +) + +const ( + staticFuncCallDepth = 3 // See 'commonLogger.log' method comments + loggerFuncCallDepth = 3 +) + +// Current is the logger used in all package level convenience funcs like 'Trace', 'Debug', 'Flush', etc. +var Current LoggerInterface + +// Default logger that is created from an empty config: "". It is not closed by a ReplaceLogger call. +var Default LoggerInterface + +// Disabled logger that doesn't produce any output in any circumstances. It is neither closed nor flushed by a ReplaceLogger call. +var Disabled LoggerInterface + +var pkgOperationsMutex *sync.Mutex + +func init() { + pkgOperationsMutex = new(sync.Mutex) + var err error + + if Default == nil { + Default, err = LoggerFromConfigAsBytes([]byte("")) + } + + if Disabled == nil { + Disabled, err = LoggerFromConfigAsBytes([]byte("")) + } + + if err != nil { + panic(fmt.Sprintf("Seelog couldn't start. Error: %s", err.Error())) + } + + Current = Default +} + +func createLoggerFromFullConfig(config *configForParsing) (LoggerInterface, error) { + if config.LogType == syncloggerTypeFromString { + return NewSyncLogger(&config.logConfig), nil + } else if config.LogType == asyncLooploggerTypeFromString { + return NewAsyncLoopLogger(&config.logConfig), nil + } else if config.LogType == asyncTimerloggerTypeFromString { + logData := config.LoggerData + if logData == nil { + return nil, errors.New("async timer data not set") + } + + asyncInt, ok := logData.(asyncTimerLoggerData) + if !ok { + return nil, errors.New("invalid async timer data") + } + + logger, err := NewAsyncTimerLogger(&config.logConfig, time.Duration(asyncInt.AsyncInterval)) + if !ok { + return nil, err + } + + return logger, nil + } else if config.LogType == adaptiveLoggerTypeFromString { + logData := config.LoggerData + if logData == nil { + return nil, errors.New("adaptive logger parameters not set") + } + + adaptData, ok := logData.(adaptiveLoggerData) + if !ok { + return nil, errors.New("invalid adaptive logger parameters") + } + + logger, err := NewAsyncAdaptiveLogger( + &config.logConfig, + time.Duration(adaptData.MinInterval), + time.Duration(adaptData.MaxInterval), + adaptData.CriticalMsgCount, + ) + if err != nil { + return nil, err + } + + return logger, nil + } + return nil, errors.New("invalid config log type/data") +} + +// UseLogger sets the 'Current' package level logger variable to the specified value. +// This variable is used in all Trace/Debug/... package level convenience funcs. +// +// Example: +// +// after calling +// seelog.UseLogger(somelogger) +// the following: +// seelog.Debug("abc") +// will be equal to +// somelogger.Debug("abc") +// +// IMPORTANT: UseLogger do NOT close the previous logger (only flushes it). So if +// you constantly use it to replace loggers and don't close them in other code, you'll +// end up having memory leaks. +// +// To safely replace loggers, use ReplaceLogger. +func UseLogger(logger LoggerInterface) error { + if logger == nil { + return errors.New("logger can not be nil") + } + + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + + oldLogger := Current + Current = logger + + if oldLogger != nil { + oldLogger.Flush() + } + + return nil +} + +// ReplaceLogger acts as UseLogger but the logger that was previously +// used is disposed (except Default and Disabled loggers). +// +// Example: +// import log "github.com/cihub/seelog" +// +// func main() { +// logger, err := log.LoggerFromConfigAsFile("seelog.xml") +// +// if err != nil { +// panic(err) +// } +// +// log.ReplaceLogger(logger) +// defer log.Flush() +// +// log.Trace("test") +// log.Debugf("var = %s", "abc") +// } +func ReplaceLogger(logger LoggerInterface) error { + if logger == nil { + return errors.New("logger can not be nil") + } + + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + + defer func() { + if err := recover(); err != nil { + reportInternalError(fmt.Errorf("recovered from panic during ReplaceLogger: %s", err)) + } + }() + + if Current == Default { + Current.Flush() + } else if Current != nil && !Current.Closed() && Current != Disabled { + Current.Flush() + Current.Close() + } + + Current = logger + + return nil +} + +// Tracef formats message according to format specifier +// and writes to default logger with log level = Trace. +func Tracef(format string, params ...interface{}) { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + Current.traceWithCallDepth(staticFuncCallDepth, newLogFormattedMessage(format, params)) +} + +// Debugf formats message according to format specifier +// and writes to default logger with log level = Debug. +func Debugf(format string, params ...interface{}) { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + Current.debugWithCallDepth(staticFuncCallDepth, newLogFormattedMessage(format, params)) +} + +// Infof formats message according to format specifier +// and writes to default logger with log level = Info. +func Infof(format string, params ...interface{}) { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + Current.infoWithCallDepth(staticFuncCallDepth, newLogFormattedMessage(format, params)) +} + +// Warnf formats message according to format specifier and writes to default logger with log level = Warn +func Warnf(format string, params ...interface{}) error { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + message := newLogFormattedMessage(format, params) + Current.warnWithCallDepth(staticFuncCallDepth, message) + return errors.New(message.String()) +} + +// Errorf formats message according to format specifier and writes to default logger with log level = Error +func Errorf(format string, params ...interface{}) error { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + message := newLogFormattedMessage(format, params) + Current.errorWithCallDepth(staticFuncCallDepth, message) + return errors.New(message.String()) +} + +// Criticalf formats message according to format specifier and writes to default logger with log level = Critical +func Criticalf(format string, params ...interface{}) error { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + message := newLogFormattedMessage(format, params) + Current.criticalWithCallDepth(staticFuncCallDepth, message) + return errors.New(message.String()) +} + +// Trace formats message using the default formats for its operands and writes to default logger with log level = Trace +func Trace(v ...interface{}) { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + Current.traceWithCallDepth(staticFuncCallDepth, newLogMessage(v)) +} + +// Debug formats message using the default formats for its operands and writes to default logger with log level = Debug +func Debug(v ...interface{}) { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + Current.debugWithCallDepth(staticFuncCallDepth, newLogMessage(v)) +} + +// Info formats message using the default formats for its operands and writes to default logger with log level = Info +func Info(v ...interface{}) { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + Current.infoWithCallDepth(staticFuncCallDepth, newLogMessage(v)) +} + +// Warn formats message using the default formats for its operands and writes to default logger with log level = Warn +func Warn(v ...interface{}) error { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + message := newLogMessage(v) + Current.warnWithCallDepth(staticFuncCallDepth, message) + return errors.New(message.String()) +} + +// Error formats message using the default formats for its operands and writes to default logger with log level = Error +func Error(v ...interface{}) error { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + message := newLogMessage(v) + Current.errorWithCallDepth(staticFuncCallDepth, message) + return errors.New(message.String()) +} + +// Critical formats message using the default formats for its operands and writes to default logger with log level = Critical +func Critical(v ...interface{}) error { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + message := newLogMessage(v) + Current.criticalWithCallDepth(staticFuncCallDepth, message) + return errors.New(message.String()) +} + +// Flush immediately processes all currently queued messages and all currently buffered messages. +// It is a blocking call which returns only after the queue is empty and all the buffers are empty. +// +// If Flush is called for a synchronous logger (type='sync'), it only flushes buffers (e.g. '' receivers) +// , because there is no queue. +// +// Call this method when your app is going to shut down not to lose any log messages. +func Flush() { + pkgOperationsMutex.Lock() + defer pkgOperationsMutex.Unlock() + Current.Flush() +} diff --git a/vendor/github.com/cihub/seelog/logger.go b/vendor/github.com/cihub/seelog/logger.go new file mode 100644 index 00000000..fc96aed4 --- /dev/null +++ b/vendor/github.com/cihub/seelog/logger.go @@ -0,0 +1,370 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" + "fmt" + "os" + "sync" +) + +func reportInternalError(err error) { + fmt.Fprintf(os.Stderr, "seelog internal error: %s\n", err) +} + +// LoggerInterface represents structs capable of logging Seelog messages +type LoggerInterface interface { + + // Tracef formats message according to format specifier + // and writes to log with level = Trace. + Tracef(format string, params ...interface{}) + + // Debugf formats message according to format specifier + // and writes to log with level = Debug. + Debugf(format string, params ...interface{}) + + // Infof formats message according to format specifier + // and writes to log with level = Info. + Infof(format string, params ...interface{}) + + // Warnf formats message according to format specifier + // and writes to log with level = Warn. + Warnf(format string, params ...interface{}) error + + // Errorf formats message according to format specifier + // and writes to log with level = Error. + Errorf(format string, params ...interface{}) error + + // Criticalf formats message according to format specifier + // and writes to log with level = Critical. + Criticalf(format string, params ...interface{}) error + + // Trace formats message using the default formats for its operands + // and writes to log with level = Trace + Trace(v ...interface{}) + + // Debug formats message using the default formats for its operands + // and writes to log with level = Debug + Debug(v ...interface{}) + + // Info formats message using the default formats for its operands + // and writes to log with level = Info + Info(v ...interface{}) + + // Warn formats message using the default formats for its operands + // and writes to log with level = Warn + Warn(v ...interface{}) error + + // Error formats message using the default formats for its operands + // and writes to log with level = Error + Error(v ...interface{}) error + + // Critical formats message using the default formats for its operands + // and writes to log with level = Critical + Critical(v ...interface{}) error + + traceWithCallDepth(callDepth int, message fmt.Stringer) + debugWithCallDepth(callDepth int, message fmt.Stringer) + infoWithCallDepth(callDepth int, message fmt.Stringer) + warnWithCallDepth(callDepth int, message fmt.Stringer) + errorWithCallDepth(callDepth int, message fmt.Stringer) + criticalWithCallDepth(callDepth int, message fmt.Stringer) + + // Close flushes all the messages in the logger and closes it. It cannot be used after this operation. + Close() + + // Flush flushes all the messages in the logger. + Flush() + + // Closed returns true if the logger was previously closed. + Closed() bool + + // SetAdditionalStackDepth sets the additional number of frames to skip by runtime.Caller + // when getting function information needed to print seelog format identifiers such as %Func or %File. + // + // This func may be used when you wrap seelog funcs and want to print caller info of you own + // wrappers instead of seelog func callers. In this case you should set depth = 1. If you then + // wrap your wrapper, you should set depth = 2, etc. + // + // NOTE: Incorrect depth value may lead to errors in runtime.Caller evaluation or incorrect + // function/file names in log files. Do not use it if you are not going to wrap seelog funcs. + // You may reset the value to default using a SetAdditionalStackDepth(0) call. + SetAdditionalStackDepth(depth int) error + + // Sets logger context that can be used in formatter funcs and custom receivers + SetContext(context interface{}) +} + +// innerLoggerInterface is an internal logging interface +type innerLoggerInterface interface { + innerLog(level LogLevel, context LogContextInterface, message fmt.Stringer) + Flush() +} + +// [file path][func name][level] -> [allowed] +type allowedContextCache map[string]map[string]map[LogLevel]bool + +// commonLogger contains all common data needed for logging and contains methods used to log messages. +type commonLogger struct { + config *logConfig // Config used for logging + contextCache allowedContextCache // Caches whether log is enabled for specific "full path-func name-level" sets + closed bool // 'true' when all writers are closed, all data is flushed, logger is unusable. Must be accessed while holding closedM + closedM sync.RWMutex + m sync.Mutex // Mutex for main operations + unusedLevels []bool + innerLogger innerLoggerInterface + addStackDepth int // Additional stack depth needed for correct seelog caller context detection + customContext interface{} +} + +func newCommonLogger(config *logConfig, internalLogger innerLoggerInterface) *commonLogger { + cLogger := new(commonLogger) + + cLogger.config = config + cLogger.contextCache = make(allowedContextCache) + cLogger.unusedLevels = make([]bool, Off) + cLogger.fillUnusedLevels() + cLogger.innerLogger = internalLogger + + return cLogger +} + +func (cLogger *commonLogger) SetAdditionalStackDepth(depth int) error { + if depth < 0 { + return fmt.Errorf("negative depth: %d", depth) + } + cLogger.m.Lock() + cLogger.addStackDepth = depth + cLogger.m.Unlock() + return nil +} + +func (cLogger *commonLogger) Tracef(format string, params ...interface{}) { + cLogger.traceWithCallDepth(loggerFuncCallDepth, newLogFormattedMessage(format, params)) +} + +func (cLogger *commonLogger) Debugf(format string, params ...interface{}) { + cLogger.debugWithCallDepth(loggerFuncCallDepth, newLogFormattedMessage(format, params)) +} + +func (cLogger *commonLogger) Infof(format string, params ...interface{}) { + cLogger.infoWithCallDepth(loggerFuncCallDepth, newLogFormattedMessage(format, params)) +} + +func (cLogger *commonLogger) Warnf(format string, params ...interface{}) error { + message := newLogFormattedMessage(format, params) + cLogger.warnWithCallDepth(loggerFuncCallDepth, message) + return errors.New(message.String()) +} + +func (cLogger *commonLogger) Errorf(format string, params ...interface{}) error { + message := newLogFormattedMessage(format, params) + cLogger.errorWithCallDepth(loggerFuncCallDepth, message) + return errors.New(message.String()) +} + +func (cLogger *commonLogger) Criticalf(format string, params ...interface{}) error { + message := newLogFormattedMessage(format, params) + cLogger.criticalWithCallDepth(loggerFuncCallDepth, message) + return errors.New(message.String()) +} + +func (cLogger *commonLogger) Trace(v ...interface{}) { + cLogger.traceWithCallDepth(loggerFuncCallDepth, newLogMessage(v)) +} + +func (cLogger *commonLogger) Debug(v ...interface{}) { + cLogger.debugWithCallDepth(loggerFuncCallDepth, newLogMessage(v)) +} + +func (cLogger *commonLogger) Info(v ...interface{}) { + cLogger.infoWithCallDepth(loggerFuncCallDepth, newLogMessage(v)) +} + +func (cLogger *commonLogger) Warn(v ...interface{}) error { + message := newLogMessage(v) + cLogger.warnWithCallDepth(loggerFuncCallDepth, message) + return errors.New(message.String()) +} + +func (cLogger *commonLogger) Error(v ...interface{}) error { + message := newLogMessage(v) + cLogger.errorWithCallDepth(loggerFuncCallDepth, message) + return errors.New(message.String()) +} + +func (cLogger *commonLogger) Critical(v ...interface{}) error { + message := newLogMessage(v) + cLogger.criticalWithCallDepth(loggerFuncCallDepth, message) + return errors.New(message.String()) +} + +func (cLogger *commonLogger) SetContext(c interface{}) { + cLogger.customContext = c +} + +func (cLogger *commonLogger) traceWithCallDepth(callDepth int, message fmt.Stringer) { + cLogger.log(TraceLvl, message, callDepth) +} + +func (cLogger *commonLogger) debugWithCallDepth(callDepth int, message fmt.Stringer) { + cLogger.log(DebugLvl, message, callDepth) +} + +func (cLogger *commonLogger) infoWithCallDepth(callDepth int, message fmt.Stringer) { + cLogger.log(InfoLvl, message, callDepth) +} + +func (cLogger *commonLogger) warnWithCallDepth(callDepth int, message fmt.Stringer) { + cLogger.log(WarnLvl, message, callDepth) +} + +func (cLogger *commonLogger) errorWithCallDepth(callDepth int, message fmt.Stringer) { + cLogger.log(ErrorLvl, message, callDepth) +} + +func (cLogger *commonLogger) criticalWithCallDepth(callDepth int, message fmt.Stringer) { + cLogger.log(CriticalLvl, message, callDepth) + cLogger.innerLogger.Flush() +} + +func (cLogger *commonLogger) Closed() bool { + cLogger.closedM.RLock() + defer cLogger.closedM.RUnlock() + return cLogger.closed +} + +func (cLogger *commonLogger) fillUnusedLevels() { + for i := 0; i < len(cLogger.unusedLevels); i++ { + cLogger.unusedLevels[i] = true + } + + cLogger.fillUnusedLevelsByContraint(cLogger.config.Constraints) + + for _, exception := range cLogger.config.Exceptions { + cLogger.fillUnusedLevelsByContraint(exception) + } +} + +func (cLogger *commonLogger) fillUnusedLevelsByContraint(constraint logLevelConstraints) { + for i := 0; i < len(cLogger.unusedLevels); i++ { + if constraint.IsAllowed(LogLevel(i)) { + cLogger.unusedLevels[i] = false + } + } +} + +// stackCallDepth is used to indicate the call depth of 'log' func. +// This depth level is used in the runtime.Caller(...) call. See +// common_context.go -> specifyContext, extractCallerInfo for details. +func (cLogger *commonLogger) log(level LogLevel, message fmt.Stringer, stackCallDepth int) { + if cLogger.unusedLevels[level] { + return + } + cLogger.m.Lock() + defer cLogger.m.Unlock() + + if cLogger.Closed() { + return + } + context, _ := specifyContext(stackCallDepth+cLogger.addStackDepth, cLogger.customContext) + // Context errors are not reported because there are situations + // in which context errors are normal Seelog usage cases. For + // example in executables with stripped symbols. + // Error contexts are returned instead. See common_context.go. + /*if err != nil { + reportInternalError(err) + return + }*/ + cLogger.innerLogger.innerLog(level, context, message) +} + +func (cLogger *commonLogger) processLogMsg(level LogLevel, message fmt.Stringer, context LogContextInterface) { + defer func() { + if err := recover(); err != nil { + reportInternalError(fmt.Errorf("recovered from panic during message processing: %s", err)) + } + }() + if cLogger.config.IsAllowed(level, context) { + cLogger.config.RootDispatcher.Dispatch(message.String(), level, context, reportInternalError) + } +} + +func (cLogger *commonLogger) isAllowed(level LogLevel, context LogContextInterface) bool { + funcMap, ok := cLogger.contextCache[context.FullPath()] + if !ok { + funcMap = make(map[string]map[LogLevel]bool, 0) + cLogger.contextCache[context.FullPath()] = funcMap + } + + levelMap, ok := funcMap[context.Func()] + if !ok { + levelMap = make(map[LogLevel]bool, 0) + funcMap[context.Func()] = levelMap + } + + isAllowValue, ok := levelMap[level] + if !ok { + isAllowValue = cLogger.config.IsAllowed(level, context) + levelMap[level] = isAllowValue + } + + return isAllowValue +} + +type logMessage struct { + params []interface{} +} + +type logFormattedMessage struct { + format string + params []interface{} +} + +func newLogMessage(params []interface{}) fmt.Stringer { + message := new(logMessage) + + message.params = params + + return message +} + +func newLogFormattedMessage(format string, params []interface{}) *logFormattedMessage { + message := new(logFormattedMessage) + + message.params = params + message.format = format + + return message +} + +func (message *logMessage) String() string { + return fmt.Sprint(message.params...) +} + +func (message *logFormattedMessage) String() string { + return fmt.Sprintf(message.format, message.params...) +} diff --git a/vendor/github.com/cihub/seelog/writers_bufferedwriter.go b/vendor/github.com/cihub/seelog/writers_bufferedwriter.go new file mode 100644 index 00000000..37d75c82 --- /dev/null +++ b/vendor/github.com/cihub/seelog/writers_bufferedwriter.go @@ -0,0 +1,161 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "bufio" + "errors" + "fmt" + "io" + "sync" + "time" +) + +// bufferedWriter stores data in memory and flushes it every flushPeriod or when buffer is full +type bufferedWriter struct { + flushPeriod time.Duration // data flushes interval (in microseconds) + bufferMutex *sync.Mutex // mutex for buffer operations syncronization + innerWriter io.Writer // inner writer + buffer *bufio.Writer // buffered wrapper for inner writer + bufferSize int // max size of data chunk in bytes +} + +// NewBufferedWriter creates a new buffered writer struct. +// bufferSize -- size of memory buffer in bytes +// flushPeriod -- period in which data flushes from memory buffer in milliseconds. 0 - turn off this functionality +func NewBufferedWriter(innerWriter io.Writer, bufferSize int, flushPeriod time.Duration) (*bufferedWriter, error) { + + if innerWriter == nil { + return nil, errors.New("argument is nil: innerWriter") + } + if flushPeriod < 0 { + return nil, fmt.Errorf("flushPeriod can not be less than 0. Got: %d", flushPeriod) + } + + if bufferSize <= 0 { + return nil, fmt.Errorf("bufferSize can not be less or equal to 0. Got: %d", bufferSize) + } + + buffer := bufio.NewWriterSize(innerWriter, bufferSize) + + /*if err != nil { + return nil, err + }*/ + + newWriter := new(bufferedWriter) + + newWriter.innerWriter = innerWriter + newWriter.buffer = buffer + newWriter.bufferSize = bufferSize + newWriter.flushPeriod = flushPeriod * 1e6 + newWriter.bufferMutex = new(sync.Mutex) + + if flushPeriod != 0 { + go newWriter.flushPeriodically() + } + + return newWriter, nil +} + +func (bufWriter *bufferedWriter) writeBigChunk(bytes []byte) (n int, err error) { + bufferedLen := bufWriter.buffer.Buffered() + + n, err = bufWriter.flushInner() + if err != nil { + return + } + + written, writeErr := bufWriter.innerWriter.Write(bytes) + return bufferedLen + written, writeErr +} + +// Sends data to buffer manager. Waits until all buffers are full. +func (bufWriter *bufferedWriter) Write(bytes []byte) (n int, err error) { + + bufWriter.bufferMutex.Lock() + defer bufWriter.bufferMutex.Unlock() + + bytesLen := len(bytes) + + if bytesLen > bufWriter.bufferSize { + return bufWriter.writeBigChunk(bytes) + } + + if bytesLen > bufWriter.buffer.Available() { + n, err = bufWriter.flushInner() + if err != nil { + return + } + } + + bufWriter.buffer.Write(bytes) + + return len(bytes), nil +} + +func (bufWriter *bufferedWriter) Close() error { + closer, ok := bufWriter.innerWriter.(io.Closer) + if ok { + return closer.Close() + } + + return nil +} + +func (bufWriter *bufferedWriter) Flush() { + + bufWriter.bufferMutex.Lock() + defer bufWriter.bufferMutex.Unlock() + + bufWriter.flushInner() +} + +func (bufWriter *bufferedWriter) flushInner() (n int, err error) { + bufferedLen := bufWriter.buffer.Buffered() + flushErr := bufWriter.buffer.Flush() + + return bufWriter.buffer.Buffered() - bufferedLen, flushErr +} + +func (bufWriter *bufferedWriter) flushBuffer() { + bufWriter.bufferMutex.Lock() + defer bufWriter.bufferMutex.Unlock() + + bufWriter.buffer.Flush() +} + +func (bufWriter *bufferedWriter) flushPeriodically() { + if bufWriter.flushPeriod > 0 { + ticker := time.NewTicker(bufWriter.flushPeriod) + for { + <-ticker.C + bufWriter.flushBuffer() + } + } +} + +func (bufWriter *bufferedWriter) String() string { + return fmt.Sprintf("bufferedWriter size: %d, flushPeriod: %d", bufWriter.bufferSize, bufWriter.flushPeriod) +} diff --git a/vendor/github.com/cihub/seelog/writers_connwriter.go b/vendor/github.com/cihub/seelog/writers_connwriter.go new file mode 100644 index 00000000..d199894e --- /dev/null +++ b/vendor/github.com/cihub/seelog/writers_connwriter.go @@ -0,0 +1,144 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "crypto/tls" + "fmt" + "io" + "net" +) + +// connWriter is used to write to a stream-oriented network connection. +type connWriter struct { + innerWriter io.WriteCloser + reconnectOnMsg bool + reconnect bool + net string + addr string + useTLS bool + configTLS *tls.Config +} + +// Creates writer to the address addr on the network netName. +// Connection will be opened on each write if reconnectOnMsg = true +func NewConnWriter(netName string, addr string, reconnectOnMsg bool) *connWriter { + newWriter := new(connWriter) + + newWriter.net = netName + newWriter.addr = addr + newWriter.reconnectOnMsg = reconnectOnMsg + + return newWriter +} + +// Creates a writer that uses SSL/TLS +func newTLSWriter(netName string, addr string, reconnectOnMsg bool, config *tls.Config) *connWriter { + newWriter := new(connWriter) + + newWriter.net = netName + newWriter.addr = addr + newWriter.reconnectOnMsg = reconnectOnMsg + newWriter.useTLS = true + newWriter.configTLS = config + + return newWriter +} + +func (connWriter *connWriter) Close() error { + if connWriter.innerWriter == nil { + return nil + } + + return connWriter.innerWriter.Close() +} + +func (connWriter *connWriter) Write(bytes []byte) (n int, err error) { + if connWriter.neededConnectOnMsg() { + err = connWriter.connect() + if err != nil { + return 0, err + } + } + + if connWriter.reconnectOnMsg { + defer connWriter.innerWriter.Close() + } + + n, err = connWriter.innerWriter.Write(bytes) + if err != nil { + connWriter.reconnect = true + } + + return +} + +func (connWriter *connWriter) String() string { + return fmt.Sprintf("Conn writer: [%s, %s, %v]", connWriter.net, connWriter.addr, connWriter.reconnectOnMsg) +} + +func (connWriter *connWriter) connect() error { + if connWriter.innerWriter != nil { + connWriter.innerWriter.Close() + connWriter.innerWriter = nil + } + + if connWriter.useTLS { + conn, err := tls.Dial(connWriter.net, connWriter.addr, connWriter.configTLS) + if err != nil { + return err + } + connWriter.innerWriter = conn + + return nil + } + + conn, err := net.Dial(connWriter.net, connWriter.addr) + if err != nil { + return err + } + + tcpConn, ok := conn.(*net.TCPConn) + if ok { + tcpConn.SetKeepAlive(true) + } + + connWriter.innerWriter = conn + + return nil +} + +func (connWriter *connWriter) neededConnectOnMsg() bool { + if connWriter.reconnect { + connWriter.reconnect = false + return true + } + + if connWriter.innerWriter == nil { + return true + } + + return connWriter.reconnectOnMsg +} diff --git a/vendor/github.com/cihub/seelog/writers_consolewriter.go b/vendor/github.com/cihub/seelog/writers_consolewriter.go new file mode 100644 index 00000000..3eb79afa --- /dev/null +++ b/vendor/github.com/cihub/seelog/writers_consolewriter.go @@ -0,0 +1,47 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import "fmt" + +// consoleWriter is used to write to console +type consoleWriter struct { +} + +// Creates a new console writer. Returns error, if the console writer couldn't be created. +func NewConsoleWriter() (writer *consoleWriter, err error) { + newWriter := new(consoleWriter) + + return newWriter, nil +} + +// Create folder and file on WriteLog/Write first call +func (console *consoleWriter) Write(bytes []byte) (int, error) { + return fmt.Print(string(bytes)) +} + +func (console *consoleWriter) String() string { + return "Console writer" +} diff --git a/vendor/github.com/cihub/seelog/writers_filewriter.go b/vendor/github.com/cihub/seelog/writers_filewriter.go new file mode 100644 index 00000000..8d3ae270 --- /dev/null +++ b/vendor/github.com/cihub/seelog/writers_filewriter.go @@ -0,0 +1,92 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "fmt" + "io" + "os" + "path/filepath" +) + +// fileWriter is used to write to a file. +type fileWriter struct { + innerWriter io.WriteCloser + fileName string +} + +// Creates a new file and a corresponding writer. Returns error, if the file couldn't be created. +func NewFileWriter(fileName string) (writer *fileWriter, err error) { + newWriter := new(fileWriter) + newWriter.fileName = fileName + + return newWriter, nil +} + +func (fw *fileWriter) Close() error { + if fw.innerWriter != nil { + err := fw.innerWriter.Close() + if err != nil { + return err + } + fw.innerWriter = nil + } + return nil +} + +// Create folder and file on WriteLog/Write first call +func (fw *fileWriter) Write(bytes []byte) (n int, err error) { + if fw.innerWriter == nil { + if err := fw.createFile(); err != nil { + return 0, err + } + } + return fw.innerWriter.Write(bytes) +} + +func (fw *fileWriter) createFile() error { + folder, _ := filepath.Split(fw.fileName) + var err error + + if 0 != len(folder) { + err = os.MkdirAll(folder, defaultDirectoryPermissions) + if err != nil { + return err + } + } + + // If exists + fw.innerWriter, err = os.OpenFile(fw.fileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, defaultFilePermissions) + + if err != nil { + return err + } + + return nil +} + +func (fw *fileWriter) String() string { + return fmt.Sprintf("File writer: %s", fw.fileName) +} diff --git a/vendor/github.com/cihub/seelog/writers_formattedwriter.go b/vendor/github.com/cihub/seelog/writers_formattedwriter.go new file mode 100644 index 00000000..bf44a410 --- /dev/null +++ b/vendor/github.com/cihub/seelog/writers_formattedwriter.go @@ -0,0 +1,62 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "errors" + "fmt" + "io" +) + +type formattedWriter struct { + writer io.Writer + formatter *formatter +} + +func NewFormattedWriter(writer io.Writer, formatter *formatter) (*formattedWriter, error) { + if formatter == nil { + return nil, errors.New("formatter can not be nil") + } + + return &formattedWriter{writer, formatter}, nil +} + +func (formattedWriter *formattedWriter) Write(message string, level LogLevel, context LogContextInterface) error { + str := formattedWriter.formatter.Format(message, level, context) + _, err := formattedWriter.writer.Write([]byte(str)) + return err +} + +func (formattedWriter *formattedWriter) String() string { + return fmt.Sprintf("writer: %s, format: %s", formattedWriter.writer, formattedWriter.formatter) +} + +func (formattedWriter *formattedWriter) Writer() io.Writer { + return formattedWriter.writer +} + +func (formattedWriter *formattedWriter) Format() *formatter { + return formattedWriter.formatter +} diff --git a/vendor/github.com/cihub/seelog/writers_rollingfilewriter.go b/vendor/github.com/cihub/seelog/writers_rollingfilewriter.go new file mode 100644 index 00000000..2422a67c --- /dev/null +++ b/vendor/github.com/cihub/seelog/writers_rollingfilewriter.go @@ -0,0 +1,625 @@ +// Copyright (c) 2013 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "fmt" + "io/ioutil" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" +) + +// Common constants +const ( + rollingLogHistoryDelimiter = "." +) + +// Types of the rolling writer: roll by date, by time, etc. +type rollingType uint8 + +const ( + rollingTypeSize = iota + rollingTypeTime +) + +// Types of the rolled file naming mode: prefix, postfix, etc. +type rollingNameMode uint8 + +const ( + rollingNameModePostfix = iota + rollingNameModePrefix +) + +var rollingNameModesStringRepresentation = map[rollingNameMode]string{ + rollingNameModePostfix: "postfix", + rollingNameModePrefix: "prefix", +} + +func rollingNameModeFromString(rollingNameStr string) (rollingNameMode, bool) { + for tp, tpStr := range rollingNameModesStringRepresentation { + if tpStr == rollingNameStr { + return tp, true + } + } + + return 0, false +} + +type rollingIntervalType uint8 + +const ( + rollingIntervalAny = iota + rollingIntervalDaily +) + +var rollingInvervalTypesStringRepresentation = map[rollingIntervalType]string{ + rollingIntervalDaily: "daily", +} + +func rollingIntervalTypeFromString(rollingTypeStr string) (rollingIntervalType, bool) { + for tp, tpStr := range rollingInvervalTypesStringRepresentation { + if tpStr == rollingTypeStr { + return tp, true + } + } + + return 0, false +} + +var rollingTypesStringRepresentation = map[rollingType]string{ + rollingTypeSize: "size", + rollingTypeTime: "date", +} + +func rollingTypeFromString(rollingTypeStr string) (rollingType, bool) { + for tp, tpStr := range rollingTypesStringRepresentation { + if tpStr == rollingTypeStr { + return tp, true + } + } + + return 0, false +} + +// Old logs archivation type. +type rollingArchiveType uint8 + +const ( + rollingArchiveNone = iota + rollingArchiveZip +) + +var rollingArchiveTypesStringRepresentation = map[rollingArchiveType]string{ + rollingArchiveNone: "none", + rollingArchiveZip: "zip", +} + +func rollingArchiveTypeFromString(rollingArchiveTypeStr string) (rollingArchiveType, bool) { + for tp, tpStr := range rollingArchiveTypesStringRepresentation { + if tpStr == rollingArchiveTypeStr { + return tp, true + } + } + + return 0, false +} + +// Default names for different archivation types +var rollingArchiveTypesDefaultNames = map[rollingArchiveType]string{ + rollingArchiveZip: "log.zip", +} + +// rollerVirtual is an interface that represents all virtual funcs that are +// called in different rolling writer subtypes. +type rollerVirtual interface { + needsToRoll() (bool, error) // Returns true if needs to switch to another file. + isFileRollNameValid(rname string) bool // Returns true if logger roll file name (postfix/prefix/etc.) is ok. + sortFileRollNamesAsc(fs []string) ([]string, error) // Sorts logger roll file names in ascending order of their creation by logger. + + // Creates a new froll history file using the contents of current file and special filename of the latest roll (prefix/ postfix). + // If lastRollName is empty (""), then it means that there is no latest roll (current is the first one) + getNewHistoryRollFileName(lastRollName string) string + getCurrentModifiedFileName(originalFileName string, first bool) (string, error) // Returns filename modified according to specific logger rules +} + +// rollingFileWriter writes received messages to a file, until time interval passes +// or file exceeds a specified limit. After that the current log file is renamed +// and writer starts to log into a new file. You can set a limit for such renamed +// files count, if you want, and then the rolling writer would delete older ones when +// the files count exceed the specified limit. +type rollingFileWriter struct { + fileName string // current file name. May differ from original in date rolling loggers + originalFileName string // original one + currentDirPath string + currentFile *os.File + currentFileSize int64 + rollingType rollingType // Rolling mode (Files roll by size/date/...) + archiveType rollingArchiveType + archivePath string + maxRolls int + nameMode rollingNameMode + self rollerVirtual // Used for virtual calls +} + +func newRollingFileWriter(fpath string, rtype rollingType, atype rollingArchiveType, apath string, maxr int, namemode rollingNameMode) (*rollingFileWriter, error) { + rw := new(rollingFileWriter) + rw.currentDirPath, rw.fileName = filepath.Split(fpath) + if len(rw.currentDirPath) == 0 { + rw.currentDirPath = "." + } + rw.originalFileName = rw.fileName + + rw.rollingType = rtype + rw.archiveType = atype + rw.archivePath = apath + rw.nameMode = namemode + rw.maxRolls = maxr + return rw, nil +} + +func (rw *rollingFileWriter) hasRollName(file string) bool { + switch rw.nameMode { + case rollingNameModePostfix: + rname := rw.originalFileName + rollingLogHistoryDelimiter + return strings.HasPrefix(file, rname) + case rollingNameModePrefix: + rname := rollingLogHistoryDelimiter + rw.originalFileName + return strings.HasSuffix(file, rname) + } + return false +} + +func (rw *rollingFileWriter) createFullFileName(originalName, rollname string) string { + switch rw.nameMode { + case rollingNameModePostfix: + return originalName + rollingLogHistoryDelimiter + rollname + case rollingNameModePrefix: + return rollname + rollingLogHistoryDelimiter + originalName + } + return "" +} + +func (rw *rollingFileWriter) getSortedLogHistory() ([]string, error) { + files, err := getDirFilePaths(rw.currentDirPath, nil, true) + if err != nil { + return nil, err + } + var validRollNames []string + for _, file := range files { + if file != rw.fileName && rw.hasRollName(file) { + rname := rw.getFileRollName(file) + if rw.self.isFileRollNameValid(rname) { + validRollNames = append(validRollNames, rname) + } + } + } + sortedTails, err := rw.self.sortFileRollNamesAsc(validRollNames) + if err != nil { + return nil, err + } + validSortedFiles := make([]string, len(sortedTails)) + for i, v := range sortedTails { + validSortedFiles[i] = rw.createFullFileName(rw.originalFileName, v) + } + return validSortedFiles, nil +} + +func (rw *rollingFileWriter) createFileAndFolderIfNeeded(first bool) error { + var err error + + if len(rw.currentDirPath) != 0 { + err = os.MkdirAll(rw.currentDirPath, defaultDirectoryPermissions) + + if err != nil { + return err + } + } + + rw.fileName, err = rw.self.getCurrentModifiedFileName(rw.originalFileName, first) + if err != nil { + return err + } + filePath := filepath.Join(rw.currentDirPath, rw.fileName) + + // If exists + stat, err := os.Lstat(filePath) + if err == nil { + rw.currentFile, err = os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND, defaultFilePermissions) + + stat, err = os.Lstat(filePath) + if err != nil { + return err + } + + rw.currentFileSize = stat.Size() + } else { + rw.currentFile, err = os.Create(filePath) + rw.currentFileSize = 0 + } + if err != nil { + return err + } + + return nil +} + +func (rw *rollingFileWriter) deleteOldRolls(history []string) error { + if rw.maxRolls <= 0 { + return nil + } + + rollsToDelete := len(history) - rw.maxRolls + if rollsToDelete <= 0 { + return nil + } + + switch rw.archiveType { + case rollingArchiveZip: + var files map[string][]byte + + // If archive exists + _, err := os.Lstat(rw.archivePath) + if nil == err { + // Extract files and content from it + files, err = unzip(rw.archivePath) + if err != nil { + return err + } + + // Remove the original file + err = tryRemoveFile(rw.archivePath) + if err != nil { + return err + } + } else { + files = make(map[string][]byte) + } + + // Add files to the existing files map, filled above + for i := 0; i < rollsToDelete; i++ { + rollPath := filepath.Join(rw.currentDirPath, history[i]) + bts, err := ioutil.ReadFile(rollPath) + if err != nil { + return err + } + + files[rollPath] = bts + } + + // Put the final file set to zip file. + if err = createZip(rw.archivePath, files); err != nil { + return err + } + } + var err error + // In all cases (archive files or not) the files should be deleted. + for i := 0; i < rollsToDelete; i++ { + // Try best to delete files without breaking the loop. + if err = tryRemoveFile(filepath.Join(rw.currentDirPath, history[i])); err != nil { + reportInternalError(err) + } + } + + return nil +} + +func (rw *rollingFileWriter) getFileRollName(fileName string) string { + switch rw.nameMode { + case rollingNameModePostfix: + return fileName[len(rw.originalFileName+rollingLogHistoryDelimiter):] + case rollingNameModePrefix: + return fileName[:len(fileName)-len(rw.originalFileName+rollingLogHistoryDelimiter)] + } + return "" +} + +func (rw *rollingFileWriter) Write(bytes []byte) (n int, err error) { + if rw.currentFile == nil { + err := rw.createFileAndFolderIfNeeded(true) + if err != nil { + return 0, err + } + } + // needs to roll if: + // * file roller max file size exceeded OR + // * time roller interval passed + nr, err := rw.self.needsToRoll() + if err != nil { + return 0, err + } + if nr { + // First, close current file. + err = rw.currentFile.Close() + if err != nil { + return 0, err + } + // Current history of all previous log files. + // For file roller it may be like this: + // * ... + // * file.log.4 + // * file.log.5 + // * file.log.6 + // + // For date roller it may look like this: + // * ... + // * file.log.11.Aug.13 + // * file.log.15.Aug.13 + // * file.log.16.Aug.13 + // Sorted log history does NOT include current file. + history, err := rw.getSortedLogHistory() + if err != nil { + return 0, err + } + // Renames current file to create a new roll history entry + // For file roller it may be like this: + // * ... + // * file.log.4 + // * file.log.5 + // * file.log.6 + // n file.log.7 <---- RENAMED (from file.log) + // Time rollers that doesn't modify file names (e.g. 'date' roller) skip this logic. + var newHistoryName string + var newRollMarkerName string + if len(history) > 0 { + // Create new rname name using last history file name + newRollMarkerName = rw.self.getNewHistoryRollFileName(rw.getFileRollName(history[len(history)-1])) + } else { + // Create first rname name + newRollMarkerName = rw.self.getNewHistoryRollFileName("") + } + if len(newRollMarkerName) != 0 { + newHistoryName = rw.createFullFileName(rw.fileName, newRollMarkerName) + } else { + newHistoryName = rw.fileName + } + if newHistoryName != rw.fileName { + err = os.Rename(filepath.Join(rw.currentDirPath, rw.fileName), filepath.Join(rw.currentDirPath, newHistoryName)) + if err != nil { + return 0, err + } + } + // Finally, add the newly added history file to the history archive + // and, if after that the archive exceeds the allowed max limit, older rolls + // must the removed/archived. + history = append(history, newHistoryName) + if len(history) > rw.maxRolls { + err = rw.deleteOldRolls(history) + if err != nil { + return 0, err + } + } + + err = rw.createFileAndFolderIfNeeded(false) + if err != nil { + return 0, err + } + } + + rw.currentFileSize += int64(len(bytes)) + return rw.currentFile.Write(bytes) +} + +func (rw *rollingFileWriter) Close() error { + if rw.currentFile != nil { + e := rw.currentFile.Close() + if e != nil { + return e + } + rw.currentFile = nil + } + return nil +} + +// ============================================================================================= +// Different types of rolling writers +// ============================================================================================= + +// -------------------------------------------------- +// Rolling writer by SIZE +// -------------------------------------------------- + +// rollingFileWriterSize performs roll when file exceeds a specified limit. +type rollingFileWriterSize struct { + *rollingFileWriter + maxFileSize int64 +} + +func NewRollingFileWriterSize(fpath string, atype rollingArchiveType, apath string, maxSize int64, maxRolls int, namemode rollingNameMode) (*rollingFileWriterSize, error) { + rw, err := newRollingFileWriter(fpath, rollingTypeSize, atype, apath, maxRolls, namemode) + if err != nil { + return nil, err + } + rws := &rollingFileWriterSize{rw, maxSize} + rws.self = rws + return rws, nil +} + +func (rws *rollingFileWriterSize) needsToRoll() (bool, error) { + return rws.currentFileSize >= rws.maxFileSize, nil +} + +func (rws *rollingFileWriterSize) isFileRollNameValid(rname string) bool { + if len(rname) == 0 { + return false + } + _, err := strconv.Atoi(rname) + return err == nil +} + +type rollSizeFileTailsSlice []string + +func (p rollSizeFileTailsSlice) Len() int { return len(p) } +func (p rollSizeFileTailsSlice) Less(i, j int) bool { + v1, _ := strconv.Atoi(p[i]) + v2, _ := strconv.Atoi(p[j]) + return v1 < v2 +} +func (p rollSizeFileTailsSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +func (rws *rollingFileWriterSize) sortFileRollNamesAsc(fs []string) ([]string, error) { + ss := rollSizeFileTailsSlice(fs) + sort.Sort(ss) + return ss, nil +} + +func (rws *rollingFileWriterSize) getNewHistoryRollFileName(lastRollName string) string { + v := 0 + if len(lastRollName) != 0 { + v, _ = strconv.Atoi(lastRollName) + } + return fmt.Sprintf("%d", v+1) +} + +func (rws *rollingFileWriterSize) getCurrentModifiedFileName(originalFileName string, first bool) (string, error) { + return originalFileName, nil +} + +func (rws *rollingFileWriterSize) String() string { + return fmt.Sprintf("Rolling file writer (By SIZE): filename: %s, archive: %s, archivefile: %s, maxFileSize: %v, maxRolls: %v", + rws.fileName, + rollingArchiveTypesStringRepresentation[rws.archiveType], + rws.archivePath, + rws.maxFileSize, + rws.maxRolls) +} + +// -------------------------------------------------- +// Rolling writer by TIME +// -------------------------------------------------- + +// rollingFileWriterTime performs roll when a specified time interval has passed. +type rollingFileWriterTime struct { + *rollingFileWriter + timePattern string + interval rollingIntervalType + currentTimeFileName string +} + +func NewRollingFileWriterTime(fpath string, atype rollingArchiveType, apath string, maxr int, + timePattern string, interval rollingIntervalType, namemode rollingNameMode) (*rollingFileWriterTime, error) { + + rw, err := newRollingFileWriter(fpath, rollingTypeTime, atype, apath, maxr, namemode) + if err != nil { + return nil, err + } + rws := &rollingFileWriterTime{rw, timePattern, interval, ""} + rws.self = rws + return rws, nil +} + +func (rwt *rollingFileWriterTime) needsToRoll() (bool, error) { + switch rwt.nameMode { + case rollingNameModePostfix: + if rwt.originalFileName+rollingLogHistoryDelimiter+time.Now().Format(rwt.timePattern) == rwt.fileName { + return false, nil + } + case rollingNameModePrefix: + if time.Now().Format(rwt.timePattern)+rollingLogHistoryDelimiter+rwt.originalFileName == rwt.fileName { + return false, nil + } + } + if rwt.interval == rollingIntervalAny { + return true, nil + } + + tprev, err := time.ParseInLocation(rwt.timePattern, rwt.getFileRollName(rwt.fileName), time.Local) + if err != nil { + return false, err + } + + diff := time.Now().Sub(tprev) + switch rwt.interval { + case rollingIntervalDaily: + return diff >= 24*time.Hour, nil + } + return false, fmt.Errorf("unknown interval type: %d", rwt.interval) +} + +func (rwt *rollingFileWriterTime) isFileRollNameValid(rname string) bool { + if len(rname) == 0 { + return false + } + _, err := time.ParseInLocation(rwt.timePattern, rname, time.Local) + return err == nil +} + +type rollTimeFileTailsSlice struct { + data []string + pattern string +} + +func (p rollTimeFileTailsSlice) Len() int { return len(p.data) } + +func (p rollTimeFileTailsSlice) Less(i, j int) bool { + t1, _ := time.ParseInLocation(p.pattern, p.data[i], time.Local) + t2, _ := time.ParseInLocation(p.pattern, p.data[j], time.Local) + return t1.Before(t2) +} + +func (p rollTimeFileTailsSlice) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] } + +func (rwt *rollingFileWriterTime) sortFileRollNamesAsc(fs []string) ([]string, error) { + ss := rollTimeFileTailsSlice{data: fs, pattern: rwt.timePattern} + sort.Sort(ss) + return ss.data, nil +} + +func (rwt *rollingFileWriterTime) getNewHistoryRollFileName(lastRollName string) string { + return "" +} + +func (rwt *rollingFileWriterTime) getCurrentModifiedFileName(originalFileName string, first bool) (string, error) { + if first { + history, err := rwt.getSortedLogHistory() + if err != nil { + return "", err + } + if len(history) > 0 { + return history[len(history)-1], nil + } + } + + switch rwt.nameMode { + case rollingNameModePostfix: + return originalFileName + rollingLogHistoryDelimiter + time.Now().Format(rwt.timePattern), nil + case rollingNameModePrefix: + return time.Now().Format(rwt.timePattern) + rollingLogHistoryDelimiter + originalFileName, nil + } + return "", fmt.Errorf("Unknown rolling writer mode. Either postfix or prefix must be used") +} + +func (rwt *rollingFileWriterTime) String() string { + return fmt.Sprintf("Rolling file writer (By TIME): filename: %s, archive: %s, archivefile: %s, maxInterval: %v, pattern: %s, maxRolls: %v", + rwt.fileName, + rollingArchiveTypesStringRepresentation[rwt.archiveType], + rwt.archivePath, + rwt.interval, + rwt.timePattern, + rwt.maxRolls) +} diff --git a/vendor/github.com/cihub/seelog/writers_smtpwriter.go b/vendor/github.com/cihub/seelog/writers_smtpwriter.go new file mode 100644 index 00000000..31b79438 --- /dev/null +++ b/vendor/github.com/cihub/seelog/writers_smtpwriter.go @@ -0,0 +1,214 @@ +// Copyright (c) 2012 - Cloud Instruments Co., Ltd. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package seelog + +import ( + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "io/ioutil" + "net/smtp" + "path/filepath" + "strings" +) + +const ( + // Default subject phrase for sending emails. + DefaultSubjectPhrase = "Diagnostic message from server: " + + // Message subject pattern composed according to RFC 5321. + rfc5321SubjectPattern = "From: %s <%s>\nSubject: %s\n\n" +) + +// smtpWriter is used to send emails via given SMTP-server. +type smtpWriter struct { + auth smtp.Auth + hostName string + hostPort string + hostNameWithPort string + senderAddress string + senderName string + recipientAddresses []string + caCertDirPaths []string + mailHeaders []string + subject string +} + +// NewSMTPWriter returns a new SMTP-writer. +func NewSMTPWriter(sa, sn string, ras []string, hn, hp, un, pwd string, cacdps []string, subj string, headers []string) *smtpWriter { + return &smtpWriter{ + auth: smtp.PlainAuth("", un, pwd, hn), + hostName: hn, + hostPort: hp, + hostNameWithPort: fmt.Sprintf("%s:%s", hn, hp), + senderAddress: sa, + senderName: sn, + recipientAddresses: ras, + caCertDirPaths: cacdps, + subject: subj, + mailHeaders: headers, + } +} + +func prepareMessage(senderAddr, senderName, subject string, body []byte, headers []string) []byte { + headerLines := fmt.Sprintf(rfc5321SubjectPattern, senderName, senderAddr, subject) + // Build header lines if configured. + if headers != nil && len(headers) > 0 { + headerLines += strings.Join(headers, "\n") + headerLines += "\n" + } + return append([]byte(headerLines), body...) +} + +// getTLSConfig gets paths of PEM files with certificates, +// host server name and tries to create an appropriate TLS.Config. +func getTLSConfig(pemFileDirPaths []string, hostName string) (config *tls.Config, err error) { + if pemFileDirPaths == nil || len(pemFileDirPaths) == 0 { + err = errors.New("invalid PEM file paths") + return + } + pemEncodedContent := []byte{} + var ( + e error + bytes []byte + ) + // Create a file-filter-by-extension, set aside non-pem files. + pemFilePathFilter := func(fp string) bool { + if filepath.Ext(fp) == ".pem" { + return true + } + return false + } + for _, pemFileDirPath := range pemFileDirPaths { + pemFilePaths, err := getDirFilePaths(pemFileDirPath, pemFilePathFilter, false) + if err != nil { + return nil, err + } + + // Put together all the PEM files to decode them as a whole byte slice. + for _, pfp := range pemFilePaths { + if bytes, e = ioutil.ReadFile(pfp); e == nil { + pemEncodedContent = append(pemEncodedContent, bytes...) + } else { + return nil, fmt.Errorf("cannot read file: %s: %s", pfp, e.Error()) + } + } + } + config = &tls.Config{RootCAs: x509.NewCertPool(), ServerName: hostName} + isAppended := config.RootCAs.AppendCertsFromPEM(pemEncodedContent) + if !isAppended { + // Extract this into a separate error. + err = errors.New("invalid PEM content") + return + } + return +} + +// SendMail accepts TLS configuration, connects to the server at addr, +// switches to TLS if possible, authenticates with mechanism a if possible, +// and then sends an email from address from, to addresses to, with message msg. +func sendMailWithTLSConfig(config *tls.Config, addr string, a smtp.Auth, from string, to []string, msg []byte) error { + c, err := smtp.Dial(addr) + if err != nil { + return err + } + // Check if the server supports STARTTLS extension. + if ok, _ := c.Extension("STARTTLS"); ok { + if err = c.StartTLS(config); err != nil { + return err + } + } + // Check if the server supports AUTH extension and use given smtp.Auth. + if a != nil { + if isSupported, _ := c.Extension("AUTH"); isSupported { + if err = c.Auth(a); err != nil { + return err + } + } + } + // Portion of code from the official smtp.SendMail function, + // see http://golang.org/src/pkg/net/smtp/smtp.go. + if err = c.Mail(from); err != nil { + return err + } + for _, addr := range to { + if err = c.Rcpt(addr); err != nil { + return err + } + } + w, err := c.Data() + if err != nil { + return err + } + _, err = w.Write(msg) + if err != nil { + return err + } + err = w.Close() + if err != nil { + return err + } + return c.Quit() +} + +// Write pushes a text message properly composed according to RFC 5321 +// to a post server, which sends it to the recipients. +func (smtpw *smtpWriter) Write(data []byte) (int, error) { + var err error + + if smtpw.caCertDirPaths == nil { + err = smtp.SendMail( + smtpw.hostNameWithPort, + smtpw.auth, + smtpw.senderAddress, + smtpw.recipientAddresses, + prepareMessage(smtpw.senderAddress, smtpw.senderName, smtpw.subject, data, smtpw.mailHeaders), + ) + } else { + config, e := getTLSConfig(smtpw.caCertDirPaths, smtpw.hostName) + if e != nil { + return 0, e + } + err = sendMailWithTLSConfig( + config, + smtpw.hostNameWithPort, + smtpw.auth, + smtpw.senderAddress, + smtpw.recipientAddresses, + prepareMessage(smtpw.senderAddress, smtpw.senderName, smtpw.subject, data, smtpw.mailHeaders), + ) + } + if err != nil { + return 0, err + } + return len(data), nil +} + +// Close closes down SMTP-connection. +func (smtpw *smtpWriter) Close() error { + // Do nothing as Write method opens and closes connection automatically. + return nil +} diff --git a/vendor/github.com/cristim/ec2-instances-info/.gitignore b/vendor/github.com/cristim/ec2-instances-info/.gitignore deleted file mode 100644 index 1fc2e649..00000000 --- a/vendor/github.com/cristim/ec2-instances-info/.gitignore +++ /dev/null @@ -1 +0,0 @@ -instances.json diff --git a/vendor/github.com/cristim/ec2-instances-info/.travis.yml b/vendor/github.com/cristim/ec2-instances-info/.travis.yml deleted file mode 100644 index 0b3d7677..00000000 --- a/vendor/github.com/cristim/ec2-instances-info/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: go - -go: -- 1.9 - -after_success: - - curl --request POST "https://goreportcard.com/checks" --data "repo=github.com/cristim/ec2-instances-info" - -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/73346abd21785c9a053c - # options: [always|never|change] default: always - on_success: change - on_failure: always - on_start: never diff --git a/vendor/github.com/cristim/ec2-instances-info/Makefile b/vendor/github.com/cristim/ec2-instances-info/Makefile deleted file mode 100644 index 9bcc26cc..00000000 --- a/vendor/github.com/cristim/ec2-instances-info/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -BINDATA_FILE := data/generated_bindata.go - -# upstream data -INSTANCES_URL := "https://ec2instances.info/instances.json" - -DEPS := "wget git jq" - -all: generate-bindata run-example -.PHONY: all - -check_deps: ## Verify the system has all dependencies installed - @for DEP in $(shell echo "$(DEPS)"); do \ - command -v "$$DEP" > /dev/null 2>&1 \ - || (echo "Error: dependency '$$DEP' is absent" ; exit 1); \ - done - @echo "all dependencies satisifed: $(DEPS)" -.PHONY: check_deps - -data/instances.json: - @mkdir -p data - @wget --quiet -nv $(INSTANCES_URL) -O data/instances.json - -generate-bindata: check_deps data/instances.json ## Convert instance data into go file - @type go-bindata || go get -u github.com/jteeuwen/go-bindata/... - @go-bindata -o $(BINDATA_FILE) -nometadata -pkg data data/instances.json - @gofmt -l -s -w $(BINDATA_FILE) >/dev/null -.PHONY: prepare_bindata - -run-example: - @go get ./... - @go run examples/instances/instances.go - -clean: - @rm -rf data -.PHONY: clean - -update-data: clean all -.PHONY: update-data - -test: - @go test -.PHONY: test diff --git a/vendor/github.com/cristim/ec2-instances-info/README.md b/vendor/github.com/cristim/ec2-instances-info/README.md deleted file mode 100644 index 9d57e8d4..00000000 --- a/vendor/github.com/cristim/ec2-instances-info/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# ec2-instances-info -[![Build Status](https://travis-ci.org/cristim/ec2-instances-info.svg?branch=master)](https://travis-ci.org/cristim/ec2-instances-info) -[![Go Report Card](https://goreportcard.com/badge/github.com/cristim/ec2-instances-info)](https://goreportcard.com/report/github.com/cristim/ec2-instances-info) -[![GoDoc](https://godoc.org/github.com/cristim/ec2-instances-info?status.svg)](http://godoc.org/github.com/cristim/ec2-instances-info) - -Golang library providing specs and pricing information about AWS EC2 instances, -based on the data that is also powering the comprehensive -[www.ec2instances.info](http://www.ec2instances.info) instance comparison -website. - -## History - -This used to be a part of my other project -[AutoSpotting](https://github.com/cristim/autospotting) which uses it -intensively, but I decided to extract it into a dedicated project sice it may be -useful to someone else out there. - -Some data fields that were not needed in AutoSpotting may not yet be exposed but -they can be added upon demand. - -## Installation or update - -```text -go get -u github.com/cristim/ec2-instances-info/... -``` - -## Usage - -```golang -import "github.com/cristim/ec2-instances-info" - -data, err := ec2instancesinfo.Data() // only needed once - -// This would print all the available instance type names: -for _, i := range *data { - fmt.Println("Instance type", i.InstanceType) -} -``` - -See the examples directory for a working code example. - -## Contributing - -Pull requests and feedback are welcome. - -The data can be updated for new instance type coverage using `make update-data`. diff --git a/vendor/github.com/cristim/ec2-instances-info/ec2_instance_data_test.go b/vendor/github.com/cristim/ec2-instances-info/ec2_instance_data_test.go deleted file mode 100644 index 7f78f9e2..00000000 --- a/vendor/github.com/cristim/ec2-instances-info/ec2_instance_data_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package ec2instancesinfo - -import "testing" - -func TestData(t *testing.T) { - tests := []struct { - name string - instance jsonInstance - wantErr bool - }{ - { - name: "Parsing t2.nano memory, price, and ebs surcharge", - instance: jsonInstance{ - InstanceType: "t2.nano", - Memory: 0.5, - VCPU: 1, - Pricing: map[string]RegionPrices{ - "us-east-1": { - Linux: LinuxPricing{ - OnDemand: 0.0058, - }, - EBSSurcharge: 0.0, - }, - }, - }, - wantErr: false, - }, - { - name: "Parsing m3.2xlarge memory, price, and ebs surcharge", - instance: jsonInstance{ - InstanceType: "m3.2xlarge", - Memory: 30.0, - VCPU: 8, - Pricing: map[string]RegionPrices{ - "us-east-1": { - Linux: LinuxPricing{ - OnDemand: 0.532, - }, - EBSSurcharge: 0.050, - }, - }, - }, - wantErr: false, - }, - { - name: "Parsing p2.16xlarge memory, price, GPUs and EBS surcharge", - instance: jsonInstance{ - InstanceType: "p2.16xlarge", - Memory: 732.0, - VCPU: 64, - GPU: 16, - Pricing: map[string]RegionPrices{ - "us-east-1": { - Linux: LinuxPricing{ - OnDemand: 14.4, - }, - EBSSurcharge: 0, - }, - }, - }, - wantErr: false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := Data() - if (err != nil) != tt.wantErr { - t.Errorf("Data() error = %v, wantErr %v", err, tt.wantErr) - } - - for _, i := range *got { - if i.InstanceType != tt.instance.InstanceType { - continue - } - - if i.Memory != tt.instance.Memory { - t.Errorf("Data(): %v, want memory %v, got %v", - tt.instance.InstanceType, tt.instance.Memory, i.Memory) - } - - if i.VCPU != tt.instance.VCPU { - t.Errorf("Data(): %v, want CPUs %v, got %v", - tt.instance.InstanceType, tt.instance.VCPU, i.VCPU) - } - - if i.Pricing["us-east-1"].Linux.OnDemand != tt.instance.Pricing["us-east-1"].Linux.OnDemand { - t.Errorf("Data(): %v, want price %v, got %v", - tt.instance.InstanceType, - tt.instance.Pricing["us-east-1"].Linux.OnDemand, - i.Pricing["us-east-1"].Linux.OnDemand) - } - - if i.Pricing["us-east-1"].EBSSurcharge != tt.instance.Pricing["us-east-1"].EBSSurcharge { - t.Errorf("Data(): %v, want ebs cost %v, got %v", - tt.instance.InstanceType, - tt.instance.Pricing["us-east-1"].EBSSurcharge, - i.Pricing["us-east-1"].EBSSurcharge) - } - } - }) - } -} diff --git a/vendor/github.com/davecgh/go-spew/.gitignore b/vendor/github.com/davecgh/go-spew/.gitignore deleted file mode 100644 index 00268614..00000000 --- a/vendor/github.com/davecgh/go-spew/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe diff --git a/vendor/github.com/davecgh/go-spew/.travis.yml b/vendor/github.com/davecgh/go-spew/.travis.yml deleted file mode 100644 index 1f4cbf54..00000000 --- a/vendor/github.com/davecgh/go-spew/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: go -go_import_path: github.com/davecgh/go-spew -go: - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - tip -sudo: false -install: - - go get -v github.com/alecthomas/gometalinter - - gometalinter --install -script: - - export PATH=$PATH:$HOME/gopath/bin - - export GORACE="halt_on_error=1" - - test -z "$(gometalinter --disable-all - --enable=gofmt - --enable=golint - --enable=vet - --enable=gosimple - --enable=unconvert - --deadline=4m ./spew | tee /dev/stderr)" - - go test -v -race -tags safe ./spew - - go test -v -race -tags testcgo ./spew -covermode=atomic -coverprofile=profile.cov -after_success: - - go get -v github.com/mattn/goveralls - - goveralls -coverprofile=profile.cov -service=travis-ci diff --git a/vendor/github.com/davecgh/go-spew/README.md b/vendor/github.com/davecgh/go-spew/README.md deleted file mode 100644 index f6ed02c3..00000000 --- a/vendor/github.com/davecgh/go-spew/README.md +++ /dev/null @@ -1,201 +0,0 @@ -go-spew -======= - -[![Build Status](https://img.shields.io/travis/davecgh/go-spew.svg)](https://travis-ci.org/davecgh/go-spew) -[![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) -[![Coverage Status](https://img.shields.io/coveralls/davecgh/go-spew.svg)](https://coveralls.io/r/davecgh/go-spew?branch=master) - -Go-spew implements a deep pretty printer for Go data structures to aid in -debugging. A comprehensive suite of tests with 100% test coverage is provided -to ensure proper functionality. See `test_coverage.txt` for the gocov coverage -report. Go-spew is licensed under the liberal ISC license, so it may be used in -open source or commercial projects. - -If you're interested in reading about how this package came to life and some -of the challenges involved in providing a deep pretty printer, there is a blog -post about it -[here](https://web.archive.org/web/20160304013555/https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/). - -## Documentation - -[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/github.com/davecgh/go-spew/spew) - -Full `go doc` style documentation for the project can be viewed online without -installing this package by using the excellent GoDoc site here: -http://godoc.org/github.com/davecgh/go-spew/spew - -You can also view the documentation locally once the package is installed with -the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to -http://localhost:6060/pkg/github.com/davecgh/go-spew/spew - -## Installation - -```bash -$ go get -u github.com/davecgh/go-spew/spew -``` - -## Quick Start - -Add this import line to the file you're working in: - -```Go -import "github.com/davecgh/go-spew/spew" -``` - -To dump a variable with full newlines, indentation, type, and pointer -information use Dump, Fdump, or Sdump: - -```Go -spew.Dump(myVar1, myVar2, ...) -spew.Fdump(someWriter, myVar1, myVar2, ...) -str := spew.Sdump(myVar1, myVar2, ...) -``` - -Alternatively, if you would prefer to use format strings with a compacted inline -printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most -compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types -and pointer addresses): - -```Go -spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) -spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) -spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) -spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) -``` - -## Debugging a Web Application Example - -Here is an example of how you can use `spew.Sdump()` to help debug a web application. Please be sure to wrap your output using the `html.EscapeString()` function for safety reasons. You should also only use this debugging technique in a development environment, never in production. - -```Go -package main - -import ( - "fmt" - "html" - "net/http" - - "github.com/davecgh/go-spew/spew" -) - -func handler(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/html") - fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:]) - fmt.Fprintf(w, "") -} - -func main() { - http.HandleFunc("/", handler) - http.ListenAndServe(":8080", nil) -} -``` - -## Sample Dump Output - -``` -(main.Foo) { - unexportedField: (*main.Bar)(0xf84002e210)({ - flag: (main.Flag) flagTwo, - data: (uintptr) - }), - ExportedField: (map[interface {}]interface {}) { - (string) "one": (bool) true - } -} -([]uint8) { - 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - 00000020 31 32 |12| -} -``` - -## Sample Formatter Output - -Double pointer to a uint8: -``` - %v: <**>5 - %+v: <**>(0xf8400420d0->0xf8400420c8)5 - %#v: (**uint8)5 - %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 -``` - -Pointer to circular struct with a uint8 field and a pointer to itself: -``` - %v: <*>{1 <*>} - %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} - %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} - %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} -``` - -## Configuration Options - -Configuration of spew is handled by fields in the ConfigState type. For -convenience, all of the top-level functions use a global state available via the -spew.Config global. - -It is also possible to create a ConfigState instance that provides methods -equivalent to the top-level functions. This allows concurrent configuration -options. See the ConfigState documentation for more details. - -``` -* Indent - String to use for each indentation level for Dump functions. - It is a single space by default. A popular alternative is "\t". - -* MaxDepth - Maximum number of levels to descend into nested data structures. - There is no limit by default. - -* DisableMethods - Disables invocation of error and Stringer interface methods. - Method invocation is enabled by default. - -* DisablePointerMethods - Disables invocation of error and Stringer interface methods on types - which only accept pointer receivers from non-pointer variables. This option - relies on access to the unsafe package, so it will not have any effect when - running in environments without access to the unsafe package such as Google - App Engine or with the "safe" build tag specified. - Pointer method invocation is enabled by default. - -* DisablePointerAddresses - DisablePointerAddresses specifies whether to disable the printing of - pointer addresses. This is useful when diffing data structures in tests. - -* DisableCapacities - DisableCapacities specifies whether to disable the printing of capacities - for arrays, slices, maps and channels. This is useful when diffing data - structures in tests. - -* ContinueOnMethod - Enables recursion into types after invoking error and Stringer interface - methods. Recursion after method invocation is disabled by default. - -* SortKeys - Specifies map keys should be sorted before being printed. Use - this to have a more deterministic, diffable output. Note that - only native types (bool, int, uint, floats, uintptr and string) - and types which implement error or Stringer interfaces are supported, - with other types sorted according to the reflect.Value.String() output - which guarantees display stability. Natural map order is used by - default. - -* SpewKeys - SpewKeys specifies that, as a last resort attempt, map keys should be - spewed to strings and sorted by those strings. This is only considered - if SortKeys is true. - -``` - -## Unsafe Package Dependency - -This package relies on the unsafe package to perform some of the more advanced -features, however it also supports a "limited" mode which allows it to work in -environments where the unsafe package is not available. By default, it will -operate in this mode on Google App Engine and when compiled with GopherJS. The -"safe" build tag may also be specified to force the package to build without -using the unsafe package. - -## License - -Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License. diff --git a/vendor/github.com/davecgh/go-spew/cov_report.sh b/vendor/github.com/davecgh/go-spew/cov_report.sh deleted file mode 100644 index 9579497e..00000000 --- a/vendor/github.com/davecgh/go-spew/cov_report.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh - -# This script uses gocov to generate a test coverage report. -# The gocov tool my be obtained with the following command: -# go get github.com/axw/gocov/gocov -# -# It will be installed to $GOPATH/bin, so ensure that location is in your $PATH. - -# Check for gocov. -if ! type gocov >/dev/null 2>&1; then - echo >&2 "This script requires the gocov tool." - echo >&2 "You may obtain it with the following command:" - echo >&2 "go get github.com/axw/gocov/gocov" - exit 1 -fi - -# Only run the cgo tests if gcc is installed. -if type gcc >/dev/null 2>&1; then - (cd spew && gocov test -tags testcgo | gocov report) -else - (cd spew && gocov test | gocov report) -fi diff --git a/vendor/github.com/davecgh/go-spew/spew/common_test.go b/vendor/github.com/davecgh/go-spew/spew/common_test.go deleted file mode 100644 index 0f5ce47d..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/common_test.go +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -// custom type to test Stinger interface on non-pointer receiver. -type stringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with non-pointer receivers. -func (s stringer) String() string { - return "stringer " + string(s) -} - -// custom type to test Stinger interface on pointer receiver. -type pstringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with only pointer receivers. -func (s *pstringer) String() string { - return "stringer " + string(*s) -} - -// xref1 and xref2 are cross referencing structs for testing circular reference -// detection. -type xref1 struct { - ps2 *xref2 -} -type xref2 struct { - ps1 *xref1 -} - -// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular -// reference for testing detection. -type indirCir1 struct { - ps2 *indirCir2 -} -type indirCir2 struct { - ps3 *indirCir3 -} -type indirCir3 struct { - ps1 *indirCir1 -} - -// embed is used to test embedded structures. -type embed struct { - a string -} - -// embedwrap is used to test embedded structures. -type embedwrap struct { - *embed - e *embed -} - -// panicer is used to intentionally cause a panic for testing spew properly -// handles them -type panicer int - -func (p panicer) String() string { - panic("test panic") -} - -// customError is used to test custom error interface invocation. -type customError int - -func (e customError) Error() string { - return fmt.Sprintf("error: %d", int(e)) -} - -// stringizeWants converts a slice of wanted test output into a format suitable -// for a test error message. -func stringizeWants(wants []string) string { - s := "" - for i, want := range wants { - if i > 0 { - s += fmt.Sprintf("want%d: %s", i+1, want) - } else { - s += "want: " + want - } - } - return s -} - -// testFailed returns whether or not a test failed by checking if the result -// of the test is in the slice of wanted strings. -func testFailed(result string, wants []string) bool { - for _, want := range wants { - if result == want { - return false - } - } - return true -} - -type sortableStruct struct { - x int -} - -func (ss sortableStruct) String() string { - return fmt.Sprintf("ss.%d", ss.x) -} - -type unsortableStruct struct { - x int -} - -type sortTestCase struct { - input []reflect.Value - expected []reflect.Value -} - -func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) { - getInterfaces := func(values []reflect.Value) []interface{} { - interfaces := []interface{}{} - for _, v := range values { - interfaces = append(interfaces, v.Interface()) - } - return interfaces - } - - for _, test := range tests { - spew.SortValues(test.input, cs) - // reflect.DeepEqual cannot really make sense of reflect.Value, - // probably because of all the pointer tricks. For instance, - // v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{} - // instead. - input := getInterfaces(test.input) - expected := getInterfaces(test.expected) - if !reflect.DeepEqual(input, expected) { - t.Errorf("Sort mismatch:\n %v != %v", input, expected) - } - } -} - -// TestSortValues ensures the sort functionality for relect.Value based sorting -// works as intended. -func TestSortValues(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - embedA := v(embed{"a"}) - embedB := v(embed{"b"}) - embedC := v(embed{"c"}) - tests := []sortTestCase{ - // No values. - { - []reflect.Value{}, - []reflect.Value{}, - }, - // Bools. - { - []reflect.Value{v(false), v(true), v(false)}, - []reflect.Value{v(false), v(false), v(true)}, - }, - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Uints. - { - []reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))}, - []reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))}, - }, - // Floats. - { - []reflect.Value{v(2.0), v(1.0), v(3.0)}, - []reflect.Value{v(1.0), v(2.0), v(3.0)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // Array - { - []reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})}, - []reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})}, - }, - // Uintptrs. - { - []reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))}, - []reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))}, - }, - // SortableStructs. - { - // Note: not sorted - DisableMethods is set. - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - // Invalid. - { - []reflect.Value{embedB, embedA, embedC}, - []reflect.Value{embedB, embedA, embedC}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithMethods ensures the sort functionality for relect.Value -// based sorting works as intended when using string methods. -func TestSortValuesWithMethods(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: false, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithSpew ensures the sort functionality for relect.Value -// based sorting works as intended when using spew to stringify keys. -func TestSortValuesWithSpew(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: true} - helpTestSortValues(tests, &cs, t) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/dump_test.go b/vendor/github.com/davecgh/go-spew/spew/dump_test.go deleted file mode 100644 index 4a31a2ee..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/dump_test.go +++ /dev/null @@ -1,1042 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Array containing bytes -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Slice containing bytes -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// dumpTest is used to describe a test to be performed against the Dump method. -type dumpTest struct { - in interface{} - wants []string -} - -// dumpTests houses all of the tests to be performed against the Dump method. -var dumpTests = make([]dumpTest, 0) - -// addDumpTest is a helper method to append the passed input and desired result -// to dumpTests -func addDumpTest(in interface{}, wants ...string) { - test := dumpTest{in, wants} - dumpTests = append(dumpTests, test) -} - -func addIntDumpTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addUintDumpTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addBoolDumpTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFloatDumpTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addComplexDumpTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addArrayDumpTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" + - vt + ") 2,\n (" + vt + ") 3\n}" - addDumpTest(v, "([3]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[3]"+vt+")()\n") - - // Array containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := [3]pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2sp := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + - ") (len=" + v2i0Len + ") stringer 1,\n (" + v2t + - ") (len=" + v2i1Len + ") stringer 2,\n (" + v2t + - ") (len=" + v2i2Len + ") " + "stringer 3\n}" - v2s := v2sp - if spew.UnsafeDisabled { - v2s = "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + - ") (len=" + v2i0Len + ") \"1\",\n (" + v2t + ") (len=" + - v2i1Len + ") \"2\",\n (" + v2t + ") (len=" + v2i2Len + - ") " + "\"3\"\n}" - } - addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2sp+")\n") - addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2sp+")\n") - addDumpTest(nv2, "(*[3]"+v2t+")()\n") - - // Array containing interfaces. - v3i0 := "one" - v3 := [3]interface{}{v3i0, int(2), uint(3)} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Array containing bytes. - v4 := [34]byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[34]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[34]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addSliceDumpTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" + - vt + ") 6.28,\n (" + vt + ") 12.56\n}" - addDumpTest(v, "([]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[]"+vt+")()\n") - - // Slice containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := []pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + - v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + - ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + - "stringer 3\n}" - addDumpTest(v2, "([]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*[]"+v2t+")()\n") - - // Slice containing interfaces. - v3i0 := "one" - v3 := []interface{}{v3i0, int(2), uint(3), nil} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3,\n (" + v3t5 + ") \n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Slice containing bytes. - v4 := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Nil slice. - v5 := []int(nil) - nv5 := (*[]int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "[]int" - v5s := "" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addStringDumpTests() { - // Standard string. - v := "test" - vLen := fmt.Sprintf("%d", len(v)) - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "(len=" + vLen + ") \"test\"" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addInterfaceDumpTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addMapDumpTests() { - // Map with string keys and int vals. - k := "one" - kk := "two" - m := map[string]int{k: 1, kk: 2} - klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up - kkLen := fmt.Sprintf("%d", len(kk)) - mLen := fmt.Sprintf("%d", len(m)) - nilMap := map[string]int(nil) - nm := (*map[string]int)(nil) - pm := &m - mAddr := fmt.Sprintf("%p", pm) - pmAddr := fmt.Sprintf("%p", &pm) - mt := "map[string]int" - mt1 := "string" - mt2 := "int" - ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " + - "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen + - ") \"two\": (" + mt2 + ") 2\n}" - ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " + - "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen + - ") \"one\": (" + mt2 + ") 1\n}" - addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n") - addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n", - "(*"+mt+")("+mAddr+")("+ms2+")\n") - addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n", - "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n") - addDumpTest(nm, "(*"+mt+")()\n") - addDumpTest(nilMap, "("+mt+") \n") - - // Map with custom formatter type on pointer receiver only keys and vals. - k2 := pstringer("one") - v2 := pstringer("1") - m2 := map[pstringer]pstringer{k2: v2} - k2Len := fmt.Sprintf("%d", len(k2)) - v2Len := fmt.Sprintf("%d", len(v2)) - m2Len := fmt.Sprintf("%d", len(m2)) - nilMap2 := map[pstringer]pstringer(nil) - nm2 := (*map[pstringer]pstringer)(nil) - pm2 := &m2 - m2Addr := fmt.Sprintf("%p", pm2) - pm2Addr := fmt.Sprintf("%p", &pm2) - m2t := "map[spew_test.pstringer]spew_test.pstringer" - m2t1 := "spew_test.pstringer" - m2t2 := "spew_test.pstringer" - m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " + - "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}" - if spew.UnsafeDisabled { - m2s = "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + - ") " + "\"one\": (" + m2t2 + ") (len=" + v2Len + - ") \"1\"\n}" - } - addDumpTest(m2, "("+m2t+") "+m2s+"\n") - addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n") - addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n") - addDumpTest(nm2, "(*"+m2t+")()\n") - addDumpTest(nilMap2, "("+m2t+") \n") - - // Map with interface keys and values. - k3 := "one" - k3Len := fmt.Sprintf("%d", len(k3)) - m3 := map[interface{}]interface{}{k3: 1} - m3Len := fmt.Sprintf("%d", len(m3)) - nilMap3 := map[interface{}]interface{}(nil) - nm3 := (*map[interface{}]interface{})(nil) - pm3 := &m3 - m3Addr := fmt.Sprintf("%p", pm3) - pm3Addr := fmt.Sprintf("%p", &pm3) - m3t := "map[interface {}]interface {}" - m3t1 := "string" - m3t2 := "int" - m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " + - "\"one\": (" + m3t2 + ") 1\n}" - addDumpTest(m3, "("+m3t+") "+m3s+"\n") - addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n") - addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n") - addDumpTest(nm3, "(*"+m3t+")()\n") - addDumpTest(nilMap3, "("+m3t+") \n") - - // Map with nil interface value. - k4 := "nil" - k4Len := fmt.Sprintf("%d", len(k4)) - m4 := map[string]interface{}{k4: nil} - m4Len := fmt.Sprintf("%d", len(m4)) - nilMap4 := map[string]interface{}(nil) - nm4 := (*map[string]interface{})(nil) - pm4 := &m4 - m4Addr := fmt.Sprintf("%p", pm4) - pm4Addr := fmt.Sprintf("%p", &pm4) - m4t := "map[string]interface {}" - m4t1 := "string" - m4t2 := "interface {}" - m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" + - " \"nil\": (" + m4t2 + ") \n}" - addDumpTest(m4, "("+m4t+") "+m4s+"\n") - addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n") - addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n") - addDumpTest(nm4, "(*"+m4t+")()\n") - addDumpTest(nilMap4, "("+m4t+") \n") -} - -func addStructDumpTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" + - v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 + - ") (len=5) stringer test2\n}" - v3sp := v3s - if spew.UnsafeDisabled { - v3s = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" + - v3t2 + ") (len=5) \"test2\"\n}" - v3sp = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" + - v3t2 + ") (len=5) stringer test2\n}" - } - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3sp+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3sp+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - eLen := fmt.Sprintf("%d", len("embedstr")) - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 + - ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 + - ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" + - " \"embedstr\"\n })\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addUintptrDumpTests() { - // Null pointer. - v := uintptr(0) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - nv2 := (*uintptr)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addUnsafePointerDumpTests() { - // Null pointer. - v := unsafe.Pointer(nil) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addChanDumpTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFuncDumpTests() { - // Function with no params and no returns. - v := addIntDumpTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Function with param and no returns. - v2 := TestDump - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") -} - -func addCircularDumpTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" + - vAddr + ")()\n })\n}" - vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")()\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n") - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr + - ")()\n })\n })\n}" - v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")()\n })\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n") - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr + - ")()\n })\n })\n })\n}" - v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")()\n })\n })\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n") -} - -func addPanicDumpTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addErrorDumpTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -// TestDump executes all of the tests described by dumpTests. -func TestDump(t *testing.T) { - // Setup tests. - addIntDumpTests() - addUintDumpTests() - addBoolDumpTests() - addFloatDumpTests() - addComplexDumpTests() - addArrayDumpTests() - addSliceDumpTests() - addStringDumpTests() - addInterfaceDumpTests() - addMapDumpTests() - addStructDumpTests() - addUintptrDumpTests() - addUnsafePointerDumpTests() - addChanDumpTests() - addFuncDumpTests() - addCircularDumpTests() - addPanicDumpTests() - addErrorDumpTests() - addCgoDumpTests() - - t.Logf("Running %d tests", len(dumpTests)) - for i, test := range dumpTests { - buf := new(bytes.Buffer) - spew.Fdump(buf, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants)) - continue - } - } -} - -func TestDumpSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := "(map[int]string) (len=3) {\n(int) 1: (string) (len=1) " + - "\"1\",\n(int) 2: (string) (len=1) \"2\",\n(int) 3: (string) " + - "(len=1) \"3\"\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = "(map[spew_test.stringer]int) (len=3) {\n" + - "(spew_test.stringer) (len=1) stringer 1: (int) 1,\n" + - "(spew_test.stringer) (len=1) stringer 2: (int) 2,\n" + - "(spew_test.stringer) (len=1) stringer 3: (int) 3\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = "(map[spew_test.pstringer]int) (len=3) {\n" + - "(spew_test.pstringer) (len=1) stringer 1: (int) 1,\n" + - "(spew_test.pstringer) (len=1) stringer 2: (int) 2,\n" + - "(spew_test.pstringer) (len=1) stringer 3: (int) 3\n" + - "}\n" - if spew.UnsafeDisabled { - expected = "(map[spew_test.pstringer]int) (len=3) {\n" + - "(spew_test.pstringer) (len=1) \"1\": (int) 1,\n" + - "(spew_test.pstringer) (len=1) \"2\": (int) 2,\n" + - "(spew_test.pstringer) (len=1) \"3\": (int) 3\n" + - "}\n" - } - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = "(map[spew_test.customError]int) (len=3) {\n" + - "(spew_test.customError) error: 1: (int) 1,\n" + - "(spew_test.customError) error: 2: (int) 2,\n" + - "(spew_test.customError) error: 3: (int) 3\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - -} diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go deleted file mode 100644 index 108baa55..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2013-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when both cgo is supported and "-tags testcgo" is added to the go test -// command line. This means the cgo tests are only added (and hence run) when -// specifially requested. This configuration is used because spew itself -// does not require cgo to run even though it does handle certain cgo types -// specially. Rather than forcing all clients to require cgo and an external -// C compiler just to run the tests, this scheme makes them optional. -// +build cgo,testcgo - -package spew_test - -import ( - "fmt" - - "github.com/davecgh/go-spew/spew/testdata" -) - -func addCgoDumpTests() { - // C char pointer. - v := testdata.GetCgoCharPointer() - nv := testdata.GetCgoNullCharPointer() - pv := &v - vcAddr := fmt.Sprintf("%p", v) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "*testdata._Ctype_char" - vs := "116" - addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(nv, "("+vt+")()\n") - - // C char array. - v2, v2l, v2c := testdata.GetCgoCharArray() - v2Len := fmt.Sprintf("%d", v2l) - v2Cap := fmt.Sprintf("%d", v2c) - v2t := "[6]testdata._Ctype_char" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " + - "{\n 00000000 74 65 73 74 32 00 " + - " |test2.|\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - - // C unsigned char array. - v3, v3l, v3c := testdata.GetCgoUnsignedCharArray() - v3Len := fmt.Sprintf("%d", v3l) - v3Cap := fmt.Sprintf("%d", v3c) - v3t := "[6]testdata._Ctype_unsignedchar" - v3t2 := "[6]testdata._Ctype_uchar" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " + - "{\n 00000000 74 65 73 74 33 00 " + - " |test3.|\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n", "("+v3t2+") "+v3s+"\n") - - // C signed char array. - v4, v4l, v4c := testdata.GetCgoSignedCharArray() - v4Len := fmt.Sprintf("%d", v4l) - v4Cap := fmt.Sprintf("%d", v4c) - v4t := "[6]testdata._Ctype_schar" - v4t2 := "testdata._Ctype_schar" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 + - ") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 + - ") 0\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - - // C uint8_t array. - v5, v5l, v5c := testdata.GetCgoUint8tArray() - v5Len := fmt.Sprintf("%d", v5l) - v5Cap := fmt.Sprintf("%d", v5c) - v5t := "[6]testdata._Ctype_uint8_t" - v5t2 := "[6]testdata._Ctype_uchar" - v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " + - "{\n 00000000 74 65 73 74 35 00 " + - " |test5.|\n}" - addDumpTest(v5, "("+v5t+") "+v5s+"\n", "("+v5t2+") "+v5s+"\n") - - // C typedefed unsigned char array. - v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray() - v6Len := fmt.Sprintf("%d", v6l) - v6Cap := fmt.Sprintf("%d", v6c) - v6t := "[6]testdata._Ctype_custom_uchar_t" - v6t2 := "[6]testdata._Ctype_uchar" - v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " + - "{\n 00000000 74 65 73 74 36 00 " + - " |test6.|\n}" - addDumpTest(v6, "("+v6t+") "+v6s+"\n", "("+v6t2+") "+v6s+"\n") -} diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go deleted file mode 100644 index 52a0971f..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when either cgo is not supported or "-tags testcgo" is not added to the go -// test command line. This file intentionally does not setup any cgo tests in -// this scenario. -// +build !cgo !testcgo - -package spew_test - -func addCgoDumpTests() { - // Don't add any tests for cgo since this file is only compiled when - // there should not be any cgo tests. -} diff --git a/vendor/github.com/davecgh/go-spew/spew/example_test.go b/vendor/github.com/davecgh/go-spew/spew/example_test.go deleted file mode 100644 index c6ec8c6d..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/example_test.go +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - - "github.com/davecgh/go-spew/spew" -) - -type Flag int - -const ( - flagOne Flag = iota - flagTwo -) - -var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", -} - -func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) -} - -type Bar struct { - data uintptr -} - -type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} -} - -// This example demonstrates how to use Dump to dump variables to stdout. -func ExampleDump() { - // The following package level declarations are assumed for this example: - /* - type Flag int - - const ( - flagOne Flag = iota - flagTwo - ) - - var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", - } - - func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) - } - - type Bar struct { - data uintptr - } - - type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} - } - */ - - // Setup some sample data structures for the example. - bar := Bar{uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - f := Flag(5) - b := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - - // Dump! - spew.Dump(s1, f, b) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Flag) Unknown flag (5) - // ([]uint8) (len=34 cap=34) { - // 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - // 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - // 00000020 31 32 |12| - // } - // -} - -// This example demonstrates how to use Printf to display a variable with a -// format string and inline formatting. -func ExamplePrintf() { - // Create a double pointer to a uint 8. - ui8 := uint8(5) - pui8 := &ui8 - ppui8 := &pui8 - - // Create a circular data type. - type circular struct { - ui8 uint8 - c *circular - } - c := circular{ui8: 1} - c.c = &c - - // Print! - spew.Printf("ppui8: %v\n", ppui8) - spew.Printf("circular: %v\n", c) - - // Output: - // ppui8: <**>5 - // circular: {1 <*>{1 <*>}} -} - -// This example demonstrates how to use a ConfigState. -func ExampleConfigState() { - // Modify the indent level of the ConfigState only. The global - // configuration is not modified. - scs := spew.ConfigState{Indent: "\t"} - - // Output using the ConfigState instance. - v := map[string]int{"one": 1} - scs.Printf("v: %v\n", v) - scs.Dump(v) - - // Output: - // v: map[one:1] - // (map[string]int) (len=1) { - // (string) (len=3) "one": (int) 1 - // } -} - -// This example demonstrates how to use ConfigState.Dump to dump variables to -// stdout -func ExampleConfigState_Dump() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances with different indentation. - scs := spew.ConfigState{Indent: "\t"} - scs2 := spew.ConfigState{Indent: " "} - - // Setup some sample data structures for the example. - bar := Bar{uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - - // Dump using the ConfigState instances. - scs.Dump(s1) - scs2.Dump(s1) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // -} - -// This example demonstrates how to use ConfigState.Printf to display a variable -// with a format string and inline formatting. -func ExampleConfigState_Printf() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances and modify the method handling of the - // first ConfigState only. - scs := spew.NewDefaultConfig() - scs2 := spew.NewDefaultConfig() - scs.DisableMethods = true - - // Alternatively - // scs := spew.ConfigState{Indent: " ", DisableMethods: true} - // scs2 := spew.ConfigState{Indent: " "} - - // This is of type Flag which implements a Stringer and has raw value 1. - f := flagTwo - - // Dump using the ConfigState instances. - scs.Printf("f: %v\n", f) - scs2.Printf("f: %v\n", f) - - // Output: - // f: 1 - // f: flagTwo -} diff --git a/vendor/github.com/davecgh/go-spew/spew/format_test.go b/vendor/github.com/davecgh/go-spew/spew/format_test.go deleted file mode 100644 index 87ee9651..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/format_test.go +++ /dev/null @@ -1,1558 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -- Type that has a custom Error interface -- %x passthrough with uint -- %#x passthrough with uint -- %f passthrough with precision -- %f passthrough with width and precision -- %d passthrough with width -- %q passthrough with string -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// formatterTest is used to describe a test to be performed against NewFormatter. -type formatterTest struct { - format string - in interface{} - wants []string -} - -// formatterTests houses all of the tests to be performed against NewFormatter. -var formatterTests = make([]formatterTest, 0) - -// addFormatterTest is a helper method to append the passed input and desired -// result to formatterTests. -func addFormatterTest(format string, in interface{}, wants ...string) { - test := formatterTest{format, in, wants} - formatterTests = append(formatterTests, test) -} - -func addIntFormatterTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"") -} - -func addUintFormatterTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") -} - -func addBoolFormatterTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFloatFormatterTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addComplexFormatterTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addArrayFormatterTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[3]int" - vs := "[1 2 3]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Array containing type with custom formatter on pointer receiver only. - v2 := [3]pstringer{"1", "2", "3"} - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[3]spew_test.pstringer" - v2sp := "[stringer 1 stringer 2 stringer 3]" - v2s := v2sp - if spew.UnsafeDisabled { - v2s = "[1 2 3]" - } - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2sp) - addFormatterTest("%v", &pv2, "<**>"+v2sp) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2sp) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2sp) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2sp) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2sp) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2sp) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2sp) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Array containing interfaces. - v3 := [3]interface{}{"one", int(2), uint(3)} - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "[one 2 3]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addSliceFormatterTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[]float32" - vs := "[3.14 6.28 12.56]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Slice containing type with custom formatter on pointer receiver only. - v2 := []pstringer{"1", "2", "3"} - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[]spew_test.pstringer" - v2s := "[stringer 1 stringer 2 stringer 3]" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Slice containing interfaces. - v3 := []interface{}{"one", int(2), uint(3), nil} - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "[one 2 3 ]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 + - ")]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Nil slice. - var v4 []int - nv4 := (*[]int)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]int" - v4s := "" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStringFormatterTests() { - // Standard string. - v := "test" - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "test" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addInterfaceFormatterTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addMapFormatterTests() { - // Map with string keys and int vals. - v := map[string]int{"one": 1, "two": 2} - nilMap := map[string]int(nil) - nv := (*map[string]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "map[string]int" - vs := "map[one:1 two:2]" - vs2 := "map[two:2 one:1]" - addFormatterTest("%v", v, vs, vs2) - addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs, - "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2) - addFormatterTest("%#v", nilMap, "("+vt+")"+"") - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs, - "(*"+vt+")("+vAddr+")"+vs2) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs, - "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%#+v", nilMap, "("+vt+")"+"") - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Map with custom formatter type on pointer receiver only keys and vals. - v2 := map[pstringer]pstringer{"one": "1"} - nv2 := (*map[pstringer]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "map[spew_test.pstringer]spew_test.pstringer" - v2s := "map[stringer one:stringer 1]" - if spew.UnsafeDisabled { - v2s = "map[one:1]" - } - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Map with interface keys and values. - v3 := map[interface{}]interface{}{"one": 1} - nv3 := (*map[interface{}]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "map[interface {}]interface {}" - v3t1 := "string" - v3t2 := "int" - v3s := "map[one:1]" - v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Map with nil interface value - v4 := map[string]interface{}{"nil": nil} - nv4 := (*map[string]interface{})(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "map[string]interface {}" - v4t1 := "interface {}" - v4s := "map[nil:]" - v4s2 := "map[nil:(" + v4t1 + ")]" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStructFormatterTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{127 255}" - vs2 := "{a:127 b:255}" - vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs3) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs3) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs3) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{{127 255} true}" - v2s2 := "{s1:{a:127 b:255} b:true}" - v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" + - v2t5 + ")true}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s2) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{stringer test stringer test2}" - v3sp := v3s - v3s2 := "{s:stringer test S:stringer test2}" - v3s2p := v3s2 - v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}" - v3s3p := v3s3 - if spew.UnsafeDisabled { - v3s = "{test test2}" - v3sp = "{test stringer test2}" - v3s2 = "{s:test S:test2}" - v3s2p = "{s:test S:stringer test2}" - v3s3 = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")test2}" - v3s3p = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")stringer test2}" - } - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3sp) - addFormatterTest("%v", &pv3, "<**>"+v3sp) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s2) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2p) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2p) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3p) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3p) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3p) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3p) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{<*>{embedstr} <*>{embedstr}}" - v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr + - "){a:embedstr}}" - v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 + - "){a:(" + v4t3 + ")embedstr}}" - v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + - ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s2) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s3) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addUintptrFormatterTests() { - // Null pointer. - v := uintptr(0) - nv := (*uintptr)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addUnsafePointerFormatterTests() { - // Null pointer. - v := unsafe.Pointer(nil) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addChanFormatterTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFuncFormatterTests() { - // Function with no params and no returns. - v := addIntFormatterTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Function with param and no returns. - v2 := TestFormatter - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addCircularFormatterTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{<*>{<*>}}" - vs2 := "{<*>}" - vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")}}" - vs4 := "{c:<*>(" + vAddr + ")}" - vs5 := "{c:(*" + vt + "){c:(*" + vt + ")}}" - vs6 := "{c:(*" + vt + ")}" - vs7 := "{c:(*" + vt + ")(" + vAddr + "){c:(*" + vt + ")(" + vAddr + - ")}}" - vs8 := "{c:(*" + vt + ")(" + vAddr + ")}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs2) - addFormatterTest("%+v", v, vs3) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs4) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs4) - addFormatterTest("%#v", v, "("+vt+")"+vs5) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs6) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs6) - addFormatterTest("%#+v", v, "("+vt+")"+vs7) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs8) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs8) - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{<*>{<*>{<*>}}}" - v2s2 := "{<*>{<*>}}" - v2s3 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + "){ps2:<*>(" + - ts2Addr + ")}}}" - v2s4 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + ")}}" - v2s5 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + "){ps2:(*" + v2t2 + - ")}}}" - v2s6 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + ")}}" - v2s7 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + "){ps2:(*" + v2t2 + ")(" + ts2Addr + - ")}}}" - v2s8 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + ")}}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s2) - addFormatterTest("%v", &pv2, "<**>"+v2s2) - addFormatterTest("%+v", v2, v2s3) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s4) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s4) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s5) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s6) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s6) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s7) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s8) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s8) - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{<*>{<*>{<*>{<*>}}}}" - v3s2 := "{<*>{<*>{<*>}}}" - v3s3 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + "){ps2:<*>(" + tic2Addr + ")}}}}" - v3s4 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + ")}}}" - v3s5 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - "){ps2:(*" + v3t2 + ")}}}}" - v3s6 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - ")}}}" - v3s7 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + "){ps2:(*" + v3t2 + - ")(" + tic2Addr + ")}}}}" - v3s8 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + ")}}}" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s2) - addFormatterTest("%v", &pv3, "<**>"+v3s2) - addFormatterTest("%+v", v3, v3s3) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s4) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s4) - addFormatterTest("%#v", v3, "("+v3t+")"+v3s5) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s6) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s6) - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s7) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s8) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s8) -} - -func addPanicFormatterTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addErrorFormatterTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addPassthroughFormatterTests() { - // %x passthrough with uint. - v := uint(4294967295) - pv := &v - vAddr := fmt.Sprintf("%x", pv) - pvAddr := fmt.Sprintf("%x", &pv) - vs := "ffffffff" - addFormatterTest("%x", v, vs) - addFormatterTest("%x", pv, vAddr) - addFormatterTest("%x", &pv, pvAddr) - - // %#x passthrough with uint. - v2 := int(2147483647) - pv2 := &v2 - v2Addr := fmt.Sprintf("%#x", pv2) - pv2Addr := fmt.Sprintf("%#x", &pv2) - v2s := "0x7fffffff" - addFormatterTest("%#x", v2, v2s) - addFormatterTest("%#x", pv2, v2Addr) - addFormatterTest("%#x", &pv2, pv2Addr) - - // %f passthrough with precision. - addFormatterTest("%.2f", 3.1415, "3.14") - addFormatterTest("%.3f", 3.1415, "3.142") - addFormatterTest("%.4f", 3.1415, "3.1415") - - // %f passthrough with width and precision. - addFormatterTest("%5.2f", 3.1415, " 3.14") - addFormatterTest("%6.3f", 3.1415, " 3.142") - addFormatterTest("%7.4f", 3.1415, " 3.1415") - - // %d passthrough with width. - addFormatterTest("%3d", 127, "127") - addFormatterTest("%4d", 127, " 127") - addFormatterTest("%5d", 127, " 127") - - // %q passthrough with string. - addFormatterTest("%q", "test", "\"test\"") -} - -// TestFormatter executes all of the tests described by formatterTests. -func TestFormatter(t *testing.T) { - // Setup tests. - addIntFormatterTests() - addUintFormatterTests() - addBoolFormatterTests() - addFloatFormatterTests() - addComplexFormatterTests() - addArrayFormatterTests() - addSliceFormatterTests() - addStringFormatterTests() - addInterfaceFormatterTests() - addMapFormatterTests() - addStructFormatterTests() - addUintptrFormatterTests() - addUnsafePointerFormatterTests() - addChanFormatterTests() - addFuncFormatterTests() - addCircularFormatterTests() - addPanicFormatterTests() - addErrorFormatterTests() - addPassthroughFormatterTests() - - t.Logf("Running %d tests", len(formatterTests)) - for i, test := range formatterTests { - buf := new(bytes.Buffer) - spew.Fprintf(buf, test.format, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Formatter #%d format: %s got: %s %s", i, test.format, s, - stringizeWants(test.wants)) - continue - } - } -} - -type testStruct struct { - x int -} - -func (ts testStruct) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -type testStructP struct { - x int -} - -func (ts *testStructP) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -func TestPrintSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sprint(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := "map[1:1 2:2 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 1:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 2:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if spew.UnsafeDisabled { - expected = "map[1:1 2:2 3:3]" - } - if s != expected { - t.Errorf("Sorted keys mismatch 3:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[testStruct]int{{1}: 1, {3}: 3, {2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 4:\n %v %v", s, expected) - } - - if !spew.UnsafeDisabled { - s = cfg.Sprint(map[testStructP]int{{1}: 1, {3}: 3, {2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 5:\n %v %v", s, expected) - } - } - - s = cfg.Sprint(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = "map[error: 1:1 error: 2:2 error: 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 6:\n %v %v", s, expected) - } -} diff --git a/vendor/github.com/davecgh/go-spew/spew/internal_test.go b/vendor/github.com/davecgh/go-spew/spew/internal_test.go deleted file mode 100644 index e312b4fa..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/internal_test.go +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -This test file is part of the spew package rather than than the spew_test -package because it needs access to internals to properly test certain cases -which are not possible via the public interface since they should never happen. -*/ - -package spew - -import ( - "bytes" - "reflect" - "testing" -) - -// dummyFmtState implements a fake fmt.State to use for testing invalid -// reflect.Value handling. This is necessary because the fmt package catches -// invalid values before invoking the formatter on them. -type dummyFmtState struct { - bytes.Buffer -} - -func (dfs *dummyFmtState) Flag(f int) bool { - return f == int('+') -} - -func (dfs *dummyFmtState) Precision() (int, bool) { - return 0, false -} - -func (dfs *dummyFmtState) Width() (int, bool) { - return 0, false -} - -// TestInvalidReflectValue ensures the dump and formatter code handles an -// invalid reflect value properly. This needs access to internal state since it -// should never happen in real code and therefore can't be tested via the public -// API. -func TestInvalidReflectValue(t *testing.T) { - i := 1 - - // Dump invalid reflect value. - v := new(reflect.Value) - buf := new(bytes.Buffer) - d := dumpState{w: buf, cs: &Config} - d.dump(*v) - s := buf.String() - want := "" - if s != want { - t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want) - } - i++ - - // Formatter invalid reflect value. - buf2 := new(dummyFmtState) - f := formatState{value: *v, cs: &Config, fs: buf2} - f.format(*v) - s = buf2.String() - want = "" - if s != want { - t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want) - } -} - -// SortValues makes the internal sortValues function available to the test -// package. -func SortValues(values []reflect.Value, cs *ConfigState) { - sortValues(values, cs) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go b/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go deleted file mode 100644 index 80dc2217..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2013-2016 Dave Collins - -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. - -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is not running on Google App Engine, compiled by GopherJS, and -// "-tags safe" is not added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// +build !js,!appengine,!safe,!disableunsafe,go1.4 - -/* -This test file is part of the spew package rather than than the spew_test -package because it needs access to internals to properly test certain cases -which are not possible via the public interface since they should never happen. -*/ - -package spew - -import ( - "bytes" - "reflect" - "testing" -) - -// changeKind uses unsafe to intentionally change the kind of a reflect.Value to -// the maximum kind value which does not exist. This is needed to test the -// fallback code which punts to the standard fmt library for new types that -// might get added to the language. -func changeKind(v *reflect.Value, readOnly bool) { - flags := flagField(v) - if readOnly { - *flags |= flagRO - } else { - *flags &^= flagRO - } - *flags |= flagKindMask -} - -// TestAddedReflectValue tests functionaly of the dump and formatter code which -// falls back to the standard fmt library for new types that might get added to -// the language. -func TestAddedReflectValue(t *testing.T) { - i := 1 - - // Dump using a reflect.Value that is exported. - v := reflect.ValueOf(int8(5)) - changeKind(&v, false) - buf := new(bytes.Buffer) - d := dumpState{w: buf, cs: &Config} - d.dump(v) - s := buf.String() - want := "(int8) 5" - if s != want { - t.Errorf("TestAddedReflectValue #%d\n got: %s want: %s", i, s, want) - } - i++ - - // Dump using a reflect.Value that is not exported. - changeKind(&v, true) - buf.Reset() - d.dump(v) - s = buf.String() - want = "(int8) " - if s != want { - t.Errorf("TestAddedReflectValue #%d\n got: %s want: %s", i, s, want) - } - i++ - - // Formatter using a reflect.Value that is exported. - changeKind(&v, false) - buf2 := new(dummyFmtState) - f := formatState{value: v, cs: &Config, fs: buf2} - f.format(v) - s = buf2.String() - want = "5" - if s != want { - t.Errorf("TestAddedReflectValue #%d got: %s want: %s", i, s, want) - } - i++ - - // Formatter using a reflect.Value that is not exported. - changeKind(&v, true) - buf2.Reset() - f = formatState{value: v, cs: &Config, fs: buf2} - f.format(v) - s = buf2.String() - want = "" - if s != want { - t.Errorf("TestAddedReflectValue #%d got: %s want: %s", i, s, want) - } -} diff --git a/vendor/github.com/davecgh/go-spew/spew/spew_test.go b/vendor/github.com/davecgh/go-spew/spew/spew_test.go deleted file mode 100644 index b70466c6..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/spew_test.go +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "os" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -// spewFunc is used to identify which public function of the spew package or -// ConfigState a test applies to. -type spewFunc int - -const ( - fCSFdump spewFunc = iota - fCSFprint - fCSFprintf - fCSFprintln - fCSPrint - fCSPrintln - fCSSdump - fCSSprint - fCSSprintf - fCSSprintln - fCSErrorf - fCSNewFormatter - fErrorf - fFprint - fFprintln - fPrint - fPrintln - fSdump - fSprint - fSprintf - fSprintln -) - -// Map of spewFunc values to names for pretty printing. -var spewFuncStrings = map[spewFunc]string{ - fCSFdump: "ConfigState.Fdump", - fCSFprint: "ConfigState.Fprint", - fCSFprintf: "ConfigState.Fprintf", - fCSFprintln: "ConfigState.Fprintln", - fCSSdump: "ConfigState.Sdump", - fCSPrint: "ConfigState.Print", - fCSPrintln: "ConfigState.Println", - fCSSprint: "ConfigState.Sprint", - fCSSprintf: "ConfigState.Sprintf", - fCSSprintln: "ConfigState.Sprintln", - fCSErrorf: "ConfigState.Errorf", - fCSNewFormatter: "ConfigState.NewFormatter", - fErrorf: "spew.Errorf", - fFprint: "spew.Fprint", - fFprintln: "spew.Fprintln", - fPrint: "spew.Print", - fPrintln: "spew.Println", - fSdump: "spew.Sdump", - fSprint: "spew.Sprint", - fSprintf: "spew.Sprintf", - fSprintln: "spew.Sprintln", -} - -func (f spewFunc) String() string { - if s, ok := spewFuncStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown spewFunc (%d)", int(f)) -} - -// spewTest is used to describe a test to be performed against the public -// functions of the spew package or ConfigState. -type spewTest struct { - cs *spew.ConfigState - f spewFunc - format string - in interface{} - want string -} - -// spewTests houses the tests to be performed against the public functions of -// the spew package and ConfigState. -// -// These tests are only intended to ensure the public functions are exercised -// and are intentionally not exhaustive of types. The exhaustive type -// tests are handled in the dump and format tests. -var spewTests []spewTest - -// redirStdout is a helper function to return the standard output from f as a -// byte slice. -func redirStdout(f func()) ([]byte, error) { - tempFile, err := ioutil.TempFile("", "ss-test") - if err != nil { - return nil, err - } - fileName := tempFile.Name() - defer os.Remove(fileName) // Ignore error - - origStdout := os.Stdout - os.Stdout = tempFile - f() - os.Stdout = origStdout - tempFile.Close() - - return ioutil.ReadFile(fileName) -} - -func initSpewTests() { - // Config states with various settings. - scsDefault := spew.NewDefaultConfig() - scsNoMethods := &spew.ConfigState{Indent: " ", DisableMethods: true} - scsNoPmethods := &spew.ConfigState{Indent: " ", DisablePointerMethods: true} - scsMaxDepth := &spew.ConfigState{Indent: " ", MaxDepth: 1} - scsContinue := &spew.ConfigState{Indent: " ", ContinueOnMethod: true} - scsNoPtrAddr := &spew.ConfigState{DisablePointerAddresses: true} - scsNoCap := &spew.ConfigState{DisableCapacities: true} - - // Variables for tests on types which implement Stringer interface with and - // without a pointer receiver. - ts := stringer("test") - tps := pstringer("test") - - type ptrTester struct { - s *struct{} - } - tptr := &ptrTester{s: &struct{}{}} - - // depthTester is used to test max depth handling for structs, array, slices - // and maps. - type depthTester struct { - ic indirCir1 - arr [1]string - slice []string - m map[string]int - } - dt := depthTester{indirCir1{nil}, [1]string{"arr"}, []string{"slice"}, - map[string]int{"one": 1}} - - // Variable for tests on types which implement error interface. - te := customError(10) - - spewTests = []spewTest{ - {scsDefault, fCSFdump, "", int8(127), "(int8) 127\n"}, - {scsDefault, fCSFprint, "", int16(32767), "32767"}, - {scsDefault, fCSFprintf, "%v", int32(2147483647), "2147483647"}, - {scsDefault, fCSFprintln, "", int(2147483647), "2147483647\n"}, - {scsDefault, fCSPrint, "", int64(9223372036854775807), "9223372036854775807"}, - {scsDefault, fCSPrintln, "", uint8(255), "255\n"}, - {scsDefault, fCSSdump, "", uint8(64), "(uint8) 64\n"}, - {scsDefault, fCSSprint, "", complex(1, 2), "(1+2i)"}, - {scsDefault, fCSSprintf, "%v", complex(float32(3), 4), "(3+4i)"}, - {scsDefault, fCSSprintln, "", complex(float64(5), 6), "(5+6i)\n"}, - {scsDefault, fCSErrorf, "%#v", uint16(65535), "(uint16)65535"}, - {scsDefault, fCSNewFormatter, "%v", uint32(4294967295), "4294967295"}, - {scsDefault, fErrorf, "%v", uint64(18446744073709551615), "18446744073709551615"}, - {scsDefault, fFprint, "", float32(3.14), "3.14"}, - {scsDefault, fFprintln, "", float64(6.28), "6.28\n"}, - {scsDefault, fPrint, "", true, "true"}, - {scsDefault, fPrintln, "", false, "false\n"}, - {scsDefault, fSdump, "", complex(-10, -20), "(complex128) (-10-20i)\n"}, - {scsDefault, fSprint, "", complex(-1, -2), "(-1-2i)"}, - {scsDefault, fSprintf, "%v", complex(float32(-3), -4), "(-3-4i)"}, - {scsDefault, fSprintln, "", complex(float64(-5), -6), "(-5-6i)\n"}, - {scsNoMethods, fCSFprint, "", ts, "test"}, - {scsNoMethods, fCSFprint, "", &ts, "<*>test"}, - {scsNoMethods, fCSFprint, "", tps, "test"}, - {scsNoMethods, fCSFprint, "", &tps, "<*>test"}, - {scsNoPmethods, fCSFprint, "", ts, "stringer test"}, - {scsNoPmethods, fCSFprint, "", &ts, "<*>stringer test"}, - {scsNoPmethods, fCSFprint, "", tps, "test"}, - {scsNoPmethods, fCSFprint, "", &tps, "<*>stringer test"}, - {scsMaxDepth, fCSFprint, "", dt, "{{} [] [] map[]}"}, - {scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" + - " ic: (spew_test.indirCir1) {\n \n },\n" + - " arr: ([1]string) (len=1 cap=1) {\n \n },\n" + - " slice: ([]string) (len=1 cap=1) {\n \n },\n" + - " m: (map[string]int) (len=1) {\n \n }\n}\n"}, - {scsContinue, fCSFprint, "", ts, "(stringer test) test"}, - {scsContinue, fCSFdump, "", ts, "(spew_test.stringer) " + - "(len=4) (stringer test) \"test\"\n"}, - {scsContinue, fCSFprint, "", te, "(error: 10) 10"}, - {scsContinue, fCSFdump, "", te, "(spew_test.customError) " + - "(error: 10) 10\n"}, - {scsNoPtrAddr, fCSFprint, "", tptr, "<*>{<*>{}}"}, - {scsNoPtrAddr, fCSSdump, "", tptr, "(*spew_test.ptrTester)({\ns: (*struct {})({\n})\n})\n"}, - {scsNoCap, fCSSdump, "", make([]string, 0, 10), "([]string) {\n}\n"}, - {scsNoCap, fCSSdump, "", make([]string, 1, 10), "([]string) (len=1) {\n(string) \"\"\n}\n"}, - } -} - -// TestSpew executes all of the tests described by spewTests. -func TestSpew(t *testing.T) { - initSpewTests() - - t.Logf("Running %d tests", len(spewTests)) - for i, test := range spewTests { - buf := new(bytes.Buffer) - switch test.f { - case fCSFdump: - test.cs.Fdump(buf, test.in) - - case fCSFprint: - test.cs.Fprint(buf, test.in) - - case fCSFprintf: - test.cs.Fprintf(buf, test.format, test.in) - - case fCSFprintln: - test.cs.Fprintln(buf, test.in) - - case fCSPrint: - b, err := redirStdout(func() { test.cs.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSPrintln: - b, err := redirStdout(func() { test.cs.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSSdump: - str := test.cs.Sdump(test.in) - buf.WriteString(str) - - case fCSSprint: - str := test.cs.Sprint(test.in) - buf.WriteString(str) - - case fCSSprintf: - str := test.cs.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fCSSprintln: - str := test.cs.Sprintln(test.in) - buf.WriteString(str) - - case fCSErrorf: - err := test.cs.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fCSNewFormatter: - fmt.Fprintf(buf, test.format, test.cs.NewFormatter(test.in)) - - case fErrorf: - err := spew.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fFprint: - spew.Fprint(buf, test.in) - - case fFprintln: - spew.Fprintln(buf, test.in) - - case fPrint: - b, err := redirStdout(func() { spew.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fPrintln: - b, err := redirStdout(func() { spew.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fSdump: - str := spew.Sdump(test.in) - buf.WriteString(str) - - case fSprint: - str := spew.Sprint(test.in) - buf.WriteString(str) - - case fSprintf: - str := spew.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fSprintln: - str := spew.Sprintln(test.in) - buf.WriteString(str) - - default: - t.Errorf("%v #%d unrecognized function", test.f, i) - continue - } - s := buf.String() - if test.want != s { - t.Errorf("ConfigState #%d\n got: %s want: %s", i, s, test.want) - continue - } - } -} diff --git a/vendor/github.com/davecgh/go-spew/test_coverage.txt b/vendor/github.com/davecgh/go-spew/test_coverage.txt deleted file mode 100644 index 2cd087a2..00000000 --- a/vendor/github.com/davecgh/go-spew/test_coverage.txt +++ /dev/null @@ -1,61 +0,0 @@ - -github.com/davecgh/go-spew/spew/dump.go dumpState.dump 100.00% (88/88) -github.com/davecgh/go-spew/spew/format.go formatState.format 100.00% (82/82) -github.com/davecgh/go-spew/spew/format.go formatState.formatPtr 100.00% (52/52) -github.com/davecgh/go-spew/spew/dump.go dumpState.dumpPtr 100.00% (44/44) -github.com/davecgh/go-spew/spew/dump.go dumpState.dumpSlice 100.00% (39/39) -github.com/davecgh/go-spew/spew/common.go handleMethods 100.00% (30/30) -github.com/davecgh/go-spew/spew/common.go printHexPtr 100.00% (18/18) -github.com/davecgh/go-spew/spew/common.go unsafeReflectValue 100.00% (13/13) -github.com/davecgh/go-spew/spew/format.go formatState.constructOrigFormat 100.00% (12/12) -github.com/davecgh/go-spew/spew/dump.go fdump 100.00% (11/11) -github.com/davecgh/go-spew/spew/format.go formatState.Format 100.00% (11/11) -github.com/davecgh/go-spew/spew/common.go init 100.00% (10/10) -github.com/davecgh/go-spew/spew/common.go printComplex 100.00% (9/9) -github.com/davecgh/go-spew/spew/common.go valuesSorter.Less 100.00% (8/8) -github.com/davecgh/go-spew/spew/format.go formatState.buildDefaultFormat 100.00% (7/7) -github.com/davecgh/go-spew/spew/format.go formatState.unpackValue 100.00% (5/5) -github.com/davecgh/go-spew/spew/dump.go dumpState.indent 100.00% (4/4) -github.com/davecgh/go-spew/spew/common.go catchPanic 100.00% (4/4) -github.com/davecgh/go-spew/spew/config.go ConfigState.convertArgs 100.00% (4/4) -github.com/davecgh/go-spew/spew/spew.go convertArgs 100.00% (4/4) -github.com/davecgh/go-spew/spew/format.go newFormatter 100.00% (3/3) -github.com/davecgh/go-spew/spew/dump.go Sdump 100.00% (3/3) -github.com/davecgh/go-spew/spew/common.go printBool 100.00% (3/3) -github.com/davecgh/go-spew/spew/common.go sortValues 100.00% (3/3) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sdump 100.00% (3/3) -github.com/davecgh/go-spew/spew/dump.go dumpState.unpackValue 100.00% (3/3) -github.com/davecgh/go-spew/spew/spew.go Printf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Println 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Sprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Sprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Sprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go printFloat 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go NewDefaultConfig 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go printInt 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go printUint 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go valuesSorter.Len 100.00% (1/1) -github.com/davecgh/go-spew/spew/common.go valuesSorter.Swap 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Errorf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Print 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Printf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Println 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.NewFormatter 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Fdump 100.00% (1/1) -github.com/davecgh/go-spew/spew/config.go ConfigState.Dump 100.00% (1/1) -github.com/davecgh/go-spew/spew/dump.go Fdump 100.00% (1/1) -github.com/davecgh/go-spew/spew/dump.go Dump 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Fprintln 100.00% (1/1) -github.com/davecgh/go-spew/spew/format.go NewFormatter 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Errorf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Fprint 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Fprintf 100.00% (1/1) -github.com/davecgh/go-spew/spew/spew.go Print 100.00% (1/1) -github.com/davecgh/go-spew/spew ------------------------------- 100.00% (505/505) - diff --git a/vendor/github.com/go-ini/ini/.gitignore b/vendor/github.com/go-ini/ini/.gitignore deleted file mode 100644 index 12411127..00000000 --- a/vendor/github.com/go-ini/ini/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -testdata/conf_out.ini -ini.sublime-project -ini.sublime-workspace -testdata/conf_reflect.ini -.idea -/.vscode diff --git a/vendor/github.com/go-ini/ini/.travis.yml b/vendor/github.com/go-ini/ini/.travis.yml deleted file mode 100644 index 3cb77dc9..00000000 --- a/vendor/github.com/go-ini/ini/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -sudo: false -language: go -go: - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - -script: - - go get golang.org/x/tools/cmd/cover - - go get github.com/smartystreets/goconvey - - mkdir -p $HOME/gopath/src/gopkg.in - - ln -s $HOME/gopath/src/github.com/go-ini/ini $HOME/gopath/src/gopkg.in/ini.v1 - - cd $HOME/gopath/src/gopkg.in/ini.v1 - - go test -v -cover -race diff --git a/vendor/github.com/go-ini/ini/Makefile b/vendor/github.com/go-ini/ini/Makefile deleted file mode 100644 index af27ff07..00000000 --- a/vendor/github.com/go-ini/ini/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -.PHONY: build test bench vet coverage - -build: vet bench - -test: - go test -v -cover -race - -bench: - go test -v -cover -race -test.bench=. -test.benchmem - -vet: - go vet - -coverage: - go test -coverprofile=c.out && go tool cover -html=c.out && rm c.out diff --git a/vendor/github.com/go-ini/ini/README.md b/vendor/github.com/go-ini/ini/README.md deleted file mode 100644 index 95d920d6..00000000 --- a/vendor/github.com/go-ini/ini/README.md +++ /dev/null @@ -1,44 +0,0 @@ -INI [![Build Status](https://travis-ci.org/go-ini/ini.svg?branch=master)](https://travis-ci.org/go-ini/ini) [![Sourcegraph](https://sourcegraph.com/github.com/go-ini/ini/-/badge.svg)](https://sourcegraph.com/github.com/go-ini/ini?badge) -=== - -![](https://avatars0.githubusercontent.com/u/10216035?v=3&s=200) - -Package ini provides INI file read and write functionality in Go. - -## Features - -- Load from multiple data sources(`[]byte`, file and `io.ReadCloser`) with overwrites. -- Read with recursion values. -- Read with parent-child sections. -- Read with auto-increment key names. -- Read with multiple-line values. -- Read with tons of helper methods. -- Read and convert values to Go types. -- Read and **WRITE** comments of sections and keys. -- Manipulate sections, keys and comments with ease. -- Keep sections and keys in order as you parse and save. - -## Installation - -To use a tagged revision: - -```sh -$ go get gopkg.in/ini.v1 -``` - -To use with latest changes: - -```sh -$ go get github.com/go-ini/ini -``` - -Please add `-u` flag to update in the future. - -## Getting Help - -- [Getting Started](https://ini.unknwon.io/docs/intro/getting_started) -- [API Documentation](https://gowalker.org/gopkg.in/ini.v1) - -## License - -This project is under Apache v2 License. See the [LICENSE](LICENSE) file for the full license text. diff --git a/vendor/github.com/go-ini/ini/bench_test.go b/vendor/github.com/go-ini/ini/bench_test.go deleted file mode 100644 index fc180246..00000000 --- a/vendor/github.com/go-ini/ini/bench_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2017 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini_test - -import ( - "testing" - - "gopkg.in/ini.v1" -) - -func newTestFile(block bool) *ini.File { - c, _ := ini.Load([]byte(_CONF_DATA)) - c.BlockMode = block - return c -} - -func Benchmark_Key_Value(b *testing.B) { - c := newTestFile(true) - for i := 0; i < b.N; i++ { - c.Section("").Key("NAME").Value() - } -} - -func Benchmark_Key_Value_NonBlock(b *testing.B) { - c := newTestFile(false) - for i := 0; i < b.N; i++ { - c.Section("").Key("NAME").Value() - } -} - -func Benchmark_Key_Value_ViaSection(b *testing.B) { - c := newTestFile(true) - sec := c.Section("") - for i := 0; i < b.N; i++ { - sec.Key("NAME").Value() - } -} - -func Benchmark_Key_Value_ViaSection_NonBlock(b *testing.B) { - c := newTestFile(false) - sec := c.Section("") - for i := 0; i < b.N; i++ { - sec.Key("NAME").Value() - } -} - -func Benchmark_Key_Value_Direct(b *testing.B) { - c := newTestFile(true) - key := c.Section("").Key("NAME") - for i := 0; i < b.N; i++ { - key.Value() - } -} - -func Benchmark_Key_Value_Direct_NonBlock(b *testing.B) { - c := newTestFile(false) - key := c.Section("").Key("NAME") - for i := 0; i < b.N; i++ { - key.Value() - } -} - -func Benchmark_Key_String(b *testing.B) { - c := newTestFile(true) - for i := 0; i < b.N; i++ { - _ = c.Section("").Key("NAME").String() - } -} - -func Benchmark_Key_String_NonBlock(b *testing.B) { - c := newTestFile(false) - for i := 0; i < b.N; i++ { - _ = c.Section("").Key("NAME").String() - } -} - -func Benchmark_Key_String_ViaSection(b *testing.B) { - c := newTestFile(true) - sec := c.Section("") - for i := 0; i < b.N; i++ { - _ = sec.Key("NAME").String() - } -} - -func Benchmark_Key_String_ViaSection_NonBlock(b *testing.B) { - c := newTestFile(false) - sec := c.Section("") - for i := 0; i < b.N; i++ { - _ = sec.Key("NAME").String() - } -} - -func Benchmark_Key_SetValue(b *testing.B) { - c := newTestFile(true) - for i := 0; i < b.N; i++ { - c.Section("").Key("NAME").SetValue("10") - } -} - -func Benchmark_Key_SetValue_VisSection(b *testing.B) { - c := newTestFile(true) - sec := c.Section("") - for i := 0; i < b.N; i++ { - sec.Key("NAME").SetValue("10") - } -} diff --git a/vendor/github.com/go-ini/ini/file_test.go b/vendor/github.com/go-ini/ini/file_test.go deleted file mode 100644 index 2a0ca7c7..00000000 --- a/vendor/github.com/go-ini/ini/file_test.go +++ /dev/null @@ -1,294 +0,0 @@ -// Copyright 2017 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini_test - -import ( - "bytes" - "io/ioutil" - "testing" - - . "github.com/smartystreets/goconvey/convey" - "gopkg.in/ini.v1" -) - -func TestEmpty(t *testing.T) { - Convey("Create an empty object", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - // Should only have the default section - So(len(f.Sections()), ShouldEqual, 1) - - // Default section should not contain any key - So(len(f.Section("").Keys()), ShouldBeZeroValue) - }) -} - -func TestFile_NewSection(t *testing.T) { - Convey("Create a new section", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - sec, err := f.NewSection("author") - So(err, ShouldBeNil) - So(sec, ShouldNotBeNil) - So(sec.Name(), ShouldEqual, "author") - - So(f.SectionStrings(), ShouldResemble, []string{ini.DEFAULT_SECTION, "author"}) - - Convey("With duplicated name", func() { - sec, err := f.NewSection("author") - So(err, ShouldBeNil) - So(sec, ShouldNotBeNil) - - // Does nothing if section already exists - So(f.SectionStrings(), ShouldResemble, []string{ini.DEFAULT_SECTION, "author"}) - }) - - Convey("With empty string", func() { - _, err := f.NewSection("") - So(err, ShouldNotBeNil) - }) - }) -} - -func TestFile_NewRawSection(t *testing.T) { - Convey("Create a new raw section", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - sec, err := f.NewRawSection("comments", `1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000`) - So(err, ShouldBeNil) - So(sec, ShouldNotBeNil) - So(sec.Name(), ShouldEqual, "comments") - - So(f.SectionStrings(), ShouldResemble, []string{ini.DEFAULT_SECTION, "comments"}) - So(f.Section("comments").Body(), ShouldEqual, `1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000`) - - Convey("With duplicated name", func() { - sec, err := f.NewRawSection("comments", `1111111111111111111000000000000000001110000`) - So(err, ShouldBeNil) - So(sec, ShouldNotBeNil) - So(f.SectionStrings(), ShouldResemble, []string{ini.DEFAULT_SECTION, "comments"}) - - // Overwrite previous existed section - So(f.Section("comments").Body(), ShouldEqual, `1111111111111111111000000000000000001110000`) - }) - - Convey("With empty string", func() { - _, err := f.NewRawSection("", "") - So(err, ShouldNotBeNil) - }) - }) -} - -func TestFile_NewSections(t *testing.T) { - Convey("Create new sections", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - So(f.NewSections("package", "author"), ShouldBeNil) - So(f.SectionStrings(), ShouldResemble, []string{ini.DEFAULT_SECTION, "package", "author"}) - - Convey("With duplicated name", func() { - So(f.NewSections("author", "features"), ShouldBeNil) - - // Ignore section already exists - So(f.SectionStrings(), ShouldResemble, []string{ini.DEFAULT_SECTION, "package", "author", "features"}) - }) - - Convey("With empty string", func() { - So(f.NewSections("", ""), ShouldNotBeNil) - }) - }) -} - -func TestFile_GetSection(t *testing.T) { - Convey("Get a section", t, func() { - f, err := ini.Load(_FULL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - sec, err := f.GetSection("author") - So(err, ShouldBeNil) - So(sec, ShouldNotBeNil) - So(sec.Name(), ShouldEqual, "author") - - Convey("Section not exists", func() { - _, err := f.GetSection("404") - So(err, ShouldNotBeNil) - }) - }) -} - -func TestFile_Section(t *testing.T) { - Convey("Get a section", t, func() { - f, err := ini.Load(_FULL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - sec := f.Section("author") - So(sec, ShouldNotBeNil) - So(sec.Name(), ShouldEqual, "author") - - Convey("Section not exists", func() { - sec := f.Section("404") - So(sec, ShouldNotBeNil) - So(sec.Name(), ShouldEqual, "404") - }) - }) - - Convey("Get default section in lower case with insensitive load", t, func() { - f, err := ini.InsensitiveLoad([]byte(` -[default] -NAME = ini -VERSION = v1`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("name").String(), ShouldEqual, "ini") - So(f.Section("").Key("version").String(), ShouldEqual, "v1") - }) -} - -func TestFile_Sections(t *testing.T) { - Convey("Get all sections", t, func() { - f, err := ini.Load(_FULL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - secs := f.Sections() - names := []string{ini.DEFAULT_SECTION, "author", "package", "package.sub", "features", "types", "array", "note", "comments", "string escapes", "advance"} - So(len(secs), ShouldEqual, len(names)) - for i, name := range names { - So(secs[i].Name(), ShouldEqual, name) - } - }) -} - -func TestFile_ChildSections(t *testing.T) { - Convey("Get child sections by parent name", t, func() { - f, err := ini.Load([]byte(` -[node] -[node.biz1] -[node.biz2] -[node.biz3] -[node.bizN] -`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - children := f.ChildSections("node") - names := []string{"node.biz1", "node.biz2", "node.biz3", "node.bizN"} - So(len(children), ShouldEqual, len(names)) - for i, name := range names { - So(children[i].Name(), ShouldEqual, name) - } - }) -} - -func TestFile_SectionStrings(t *testing.T) { - Convey("Get all section names", t, func() { - f, err := ini.Load(_FULL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.SectionStrings(), ShouldResemble, []string{ini.DEFAULT_SECTION, "author", "package", "package.sub", "features", "types", "array", "note", "comments", "string escapes", "advance"}) - }) -} - -func TestFile_DeleteSection(t *testing.T) { - Convey("Delete a section", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - f.NewSections("author", "package", "features") - f.DeleteSection("features") - f.DeleteSection("") - So(f.SectionStrings(), ShouldResemble, []string{"author", "package"}) - }) -} - -func TestFile_Append(t *testing.T) { - Convey("Append a data source", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - So(f.Append(_MINIMAL_CONF, []byte(` -[author] -NAME = Unknwon`)), ShouldBeNil) - - Convey("With bad input", func() { - So(f.Append(123), ShouldNotBeNil) - So(f.Append(_MINIMAL_CONF, 123), ShouldNotBeNil) - }) - }) -} - -func TestFile_WriteTo(t *testing.T) { - Convey("Write content to somewhere", t, func() { - f, err := ini.Load(_FULL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - f.Section("author").Comment = `Information about package author -# Bio can be written in multiple lines.` - f.Section("author").Key("NAME").Comment = "This is author name" - f.Section("note").NewBooleanKey("boolean_key") - f.Section("note").NewKey("more", "notes") - - var buf bytes.Buffer - _, err = f.WriteTo(&buf) - So(err, ShouldBeNil) - - golden := "testdata/TestFile_WriteTo.golden" - if *update { - ioutil.WriteFile(golden, buf.Bytes(), 0644) - } - - expected, err := ioutil.ReadFile(golden) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, string(expected)) - }) - - Convey("Support multiline comments", t, func() { - f := ini.Empty() - f.Section("").Key("test").Comment = "Multiline\nComment" - - var buf bytes.Buffer - _, err := f.WriteTo(&buf) - So(err, ShouldBeNil) - - So(buf.String(), ShouldEqual, `; Multiline -; Comment -test = - -`) - - }) -} - -func TestFile_SaveTo(t *testing.T) { - Convey("Write content to somewhere", t, func() { - f, err := ini.Load(_FULL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.SaveTo("testdata/conf_out.ini"), ShouldBeNil) - So(f.SaveToIndent("testdata/conf_out.ini", "\t"), ShouldBeNil) - }) -} diff --git a/vendor/github.com/go-ini/ini/ini_internal_test.go b/vendor/github.com/go-ini/ini/ini_internal_test.go deleted file mode 100644 index 257ef1eb..00000000 --- a/vendor/github.com/go-ini/ini/ini_internal_test.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2017 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func Test_Version(t *testing.T) { - Convey("Get version", t, func() { - So(Version(), ShouldEqual, _VERSION) - }) -} - -func Test_isSlice(t *testing.T) { - Convey("Check if a string is in the slice", t, func() { - ss := []string{"a", "b", "c"} - So(inSlice("a", ss), ShouldBeTrue) - So(inSlice("d", ss), ShouldBeFalse) - }) -} diff --git a/vendor/github.com/go-ini/ini/ini_test.go b/vendor/github.com/go-ini/ini/ini_test.go deleted file mode 100644 index d68c7caa..00000000 --- a/vendor/github.com/go-ini/ini/ini_test.go +++ /dev/null @@ -1,1210 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini_test - -import ( - "bytes" - "flag" - "io/ioutil" - "testing" - - . "github.com/smartystreets/goconvey/convey" - "gopkg.in/ini.v1" -) - -const ( - _CONF_DATA = ` - ; Package name - NAME = ini - ; Package version - VERSION = v1 - ; Package import path - IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - - # Information about package author - # Bio can be written in multiple lines. - [author] - NAME = Unknwon ; Succeeding comment - E-MAIL = fake@localhost - GITHUB = https://github.com/%(NAME)s - BIO = """Gopher. - Coding addict. - Good man. - """ # Succeeding comment` - _MINIMAL_CONF = "testdata/minimal.ini" - _FULL_CONF = "testdata/full.ini" - _NOT_FOUND_CONF = "testdata/404.ini" -) - -var update = flag.Bool("update", false, "Update .golden files") - -func TestLoad(t *testing.T) { - Convey("Load from good data sources", t, func() { - f, err := ini.Load([]byte(` -NAME = ini -VERSION = v1 -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s`), - "testdata/minimal.ini", - ioutil.NopCloser(bytes.NewReader([]byte(` -[author] -NAME = Unknwon -`))), - ) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - // Validate values make sure all sources are loaded correctly - sec := f.Section("") - So(sec.Key("NAME").String(), ShouldEqual, "ini") - So(sec.Key("VERSION").String(), ShouldEqual, "v1") - So(sec.Key("IMPORT_PATH").String(), ShouldEqual, "gopkg.in/ini.v1") - - sec = f.Section("author") - So(sec.Key("NAME").String(), ShouldEqual, "Unknwon") - So(sec.Key("E-MAIL").String(), ShouldEqual, "u@gogs.io") - }) - - Convey("Load from bad data sources", t, func() { - Convey("Invalid input", func() { - _, err := ini.Load(_NOT_FOUND_CONF) - So(err, ShouldNotBeNil) - }) - - Convey("Unsupported type", func() { - _, err := ini.Load(123) - So(err, ShouldNotBeNil) - }) - }) - - Convey("Can't properly parse INI files containing `#` or `;` in value", t, func() { - f, err := ini.Load([]byte(` - [author] - NAME = U#n#k#n#w#o#n - GITHUB = U;n;k;n;w;o;n - `)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - sec := f.Section("author") - nameValue := sec.Key("NAME").String() - githubValue := sec.Key("GITHUB").String() - So(nameValue, ShouldEqual, "U") - So(githubValue, ShouldEqual, "U") - }) - - Convey("Can't parse small python-compatible INI files", t, func() { - f, err := ini.Load([]byte(` -[long] -long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- - foo - bar - foobar - barfoo - -----END RSA PRIVATE KEY----- -`)) - So(err, ShouldNotBeNil) - So(f, ShouldBeNil) - So(err.Error(), ShouldEqual, "key-value delimiter not found: foo\n") - }) - - Convey("Can't parse big python-compatible INI files", t, func() { - f, err := ini.Load([]byte(` -[long] -long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- - 1foo - 2bar - 3foobar - 4barfoo - 5foo - 6bar - 7foobar - 8barfoo - 9foo - 10bar - 11foobar - 12barfoo - 13foo - 14bar - 15foobar - 16barfoo - 17foo - 18bar - 19foobar - 20barfoo - 21foo - 22bar - 23foobar - 24barfoo - 25foo - 26bar - 27foobar - 28barfoo - 29foo - 30bar - 31foobar - 32barfoo - 33foo - 34bar - 35foobar - 36barfoo - 37foo - 38bar - 39foobar - 40barfoo - 41foo - 42bar - 43foobar - 44barfoo - 45foo - 46bar - 47foobar - 48barfoo - 49foo - 50bar - 51foobar - 52barfoo - 53foo - 54bar - 55foobar - 56barfoo - 57foo - 58bar - 59foobar - 60barfoo - 61foo - 62bar - 63foobar - 64barfoo - 65foo - 66bar - 67foobar - 68barfoo - 69foo - 70bar - 71foobar - 72barfoo - 73foo - 74bar - 75foobar - 76barfoo - 77foo - 78bar - 79foobar - 80barfoo - 81foo - 82bar - 83foobar - 84barfoo - 85foo - 86bar - 87foobar - 88barfoo - 89foo - 90bar - 91foobar - 92barfoo - 93foo - 94bar - 95foobar - 96barfoo - -----END RSA PRIVATE KEY----- -`)) - So(err, ShouldNotBeNil) - So(f, ShouldBeNil) - So(err.Error(), ShouldEqual, "key-value delimiter not found: 1foo\n") - }) -} - -func TestLooseLoad(t *testing.T) { - Convey("Load from data sources with option `Loose` true", t, func() { - f, err := ini.LoadSources(ini.LoadOptions{Loose: true}, _NOT_FOUND_CONF, _MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - Convey("Inverse case", func() { - _, err = ini.Load(_NOT_FOUND_CONF) - So(err, ShouldNotBeNil) - }) - }) -} - -func TestInsensitiveLoad(t *testing.T) { - Convey("Insensitive to section and key names", t, func() { - f, err := ini.InsensitiveLoad(_MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("Author").Key("e-mail").String(), ShouldEqual, "u@gogs.io") - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `[author] -e-mail = u@gogs.io - -`) - }) - - Convey("Inverse case", func() { - f, err := ini.Load(_MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("Author").Key("e-mail").String(), ShouldBeEmpty) - }) - }) -} - -func TestLoadSources(t *testing.T) { - Convey("Load from data sources with options", t, func() { - Convey("with true `AllowPythonMultilineValues`", func() { - Convey("Ignore nonexistent files", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true, Loose: true}, _NOT_FOUND_CONF, _MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - Convey("Inverse case", func() { - _, err = ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, _NOT_FOUND_CONF) - So(err, ShouldNotBeNil) - }) - }) - - Convey("Insensitive to section and key names", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true, Insensitive: true}, _MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("Author").Key("e-mail").String(), ShouldEqual, "u@gogs.io") - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `[author] -e-mail = u@gogs.io - -`) - }) - - Convey("Inverse case", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, _MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("Author").Key("e-mail").String(), ShouldBeEmpty) - }) - }) - - Convey("Ignore continuation lines", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: true, - IgnoreContinuation: true, - }, []byte(` -key1=a\b\ -key2=c\d\ -key3=value`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key1").String(), ShouldEqual, `a\b\`) - So(f.Section("").Key("key2").String(), ShouldEqual, `c\d\`) - So(f.Section("").Key("key3").String(), ShouldEqual, "value") - - Convey("Inverse case", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` -key1=a\b\ -key2=c\d\`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key1").String(), ShouldEqual, `a\bkey2=c\d`) - }) - }) - - Convey("Ignore inline comments", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: true, - IgnoreInlineComment: true, - }, []byte(` -key1=value ;comment -key2=value2 #comment2 -key3=val#ue #comment3`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key1").String(), ShouldEqual, `value ;comment`) - So(f.Section("").Key("key2").String(), ShouldEqual, `value2 #comment2`) - So(f.Section("").Key("key3").String(), ShouldEqual, `val#ue #comment3`) - - Convey("Inverse case", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` -key1=value ;comment -key2=value2 #comment2`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key1").String(), ShouldEqual, `value`) - So(f.Section("").Key("key1").Comment, ShouldEqual, `;comment`) - So(f.Section("").Key("key2").String(), ShouldEqual, `value2`) - So(f.Section("").Key("key2").Comment, ShouldEqual, `#comment2`) - }) - }) - - Convey("Allow boolean type keys", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: true, - AllowBooleanKeys: true, - }, []byte(` -key1=hello -#key2 -key3`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").KeyStrings(), ShouldResemble, []string{"key1", "key3"}) - So(f.Section("").Key("key3").MustBool(false), ShouldBeTrue) - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `key1 = hello -# key2 -key3 -`) - }) - - Convey("Inverse case", func() { - _, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` -key1=hello -#key2 -key3`)) - So(err, ShouldNotBeNil) - }) - }) - - Convey("Allow shadow keys", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowShadows: true, AllowPythonMultilineValues: true}, []byte(` -[remote "origin"] -url = https://github.com/Antergone/test1.git -url = https://github.com/Antergone/test2.git -fetch = +refs/heads/*:refs/remotes/origin/*`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test1.git") - So(f.Section(`remote "origin"`).Key("url").ValueWithShadows(), ShouldResemble, []string{ - "https://github.com/Antergone/test1.git", - "https://github.com/Antergone/test2.git", - }) - So(f.Section(`remote "origin"`).Key("fetch").String(), ShouldEqual, "+refs/heads/*:refs/remotes/origin/*") - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `[remote "origin"] -url = https://github.com/Antergone/test1.git -url = https://github.com/Antergone/test2.git -fetch = +refs/heads/*:refs/remotes/origin/* - -`) - }) - - Convey("Inverse case", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` -[remote "origin"] -url = https://github.com/Antergone/test1.git -url = https://github.com/Antergone/test2.git`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test2.git") - }) - }) - - Convey("Unescape double quotes inside value", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: true, - UnescapeValueDoubleQuotes: true, - }, []byte(` -create_repo="创建了仓库 %s"`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("create_repo").String(), ShouldEqual, `创建了仓库 %s`) - - Convey("Inverse case", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` -create_repo="创建了仓库 %s"`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("create_repo").String(), ShouldEqual, `"创建了仓库 %s"`) - }) - }) - - Convey("Unescape comment symbols inside value", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: true, - IgnoreInlineComment: true, - UnescapeValueCommentSymbols: true, - }, []byte(` -key = test value more text -`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key").String(), ShouldEqual, `test value more text`) - }) - - Convey("Can parse small python-compatible INI files", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: true, - Insensitive: true, - UnparseableSections: []string{"core_lesson", "comments"}, - }, []byte(` -[long] -long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- - foo - bar - foobar - barfoo - -----END RSA PRIVATE KEY----- -`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("long").Key("long_rsa_private_key").String(), ShouldEqual, "-----BEGIN RSA PRIVATE KEY-----\nfoo\nbar\nfoobar\nbarfoo\n-----END RSA PRIVATE KEY-----") - }) - - Convey("Can parse big python-compatible INI files", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: true, - Insensitive: true, - UnparseableSections: []string{"core_lesson", "comments"}, - }, []byte(` -[long] -long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- - 1foo - 2bar - 3foobar - 4barfoo - 5foo - 6bar - 7foobar - 8barfoo - 9foo - 10bar - 11foobar - 12barfoo - 13foo - 14bar - 15foobar - 16barfoo - 17foo - 18bar - 19foobar - 20barfoo - 21foo - 22bar - 23foobar - 24barfoo - 25foo - 26bar - 27foobar - 28barfoo - 29foo - 30bar - 31foobar - 32barfoo - 33foo - 34bar - 35foobar - 36barfoo - 37foo - 38bar - 39foobar - 40barfoo - 41foo - 42bar - 43foobar - 44barfoo - 45foo - 46bar - 47foobar - 48barfoo - 49foo - 50bar - 51foobar - 52barfoo - 53foo - 54bar - 55foobar - 56barfoo - 57foo - 58bar - 59foobar - 60barfoo - 61foo - 62bar - 63foobar - 64barfoo - 65foo - 66bar - 67foobar - 68barfoo - 69foo - 70bar - 71foobar - 72barfoo - 73foo - 74bar - 75foobar - 76barfoo - 77foo - 78bar - 79foobar - 80barfoo - 81foo - 82bar - 83foobar - 84barfoo - 85foo - 86bar - 87foobar - 88barfoo - 89foo - 90bar - 91foobar - 92barfoo - 93foo - 94bar - 95foobar - 96barfoo - -----END RSA PRIVATE KEY----- -`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("long").Key("long_rsa_private_key").String(), ShouldEqual, `-----BEGIN RSA PRIVATE KEY----- -1foo -2bar -3foobar -4barfoo -5foo -6bar -7foobar -8barfoo -9foo -10bar -11foobar -12barfoo -13foo -14bar -15foobar -16barfoo -17foo -18bar -19foobar -20barfoo -21foo -22bar -23foobar -24barfoo -25foo -26bar -27foobar -28barfoo -29foo -30bar -31foobar -32barfoo -33foo -34bar -35foobar -36barfoo -37foo -38bar -39foobar -40barfoo -41foo -42bar -43foobar -44barfoo -45foo -46bar -47foobar -48barfoo -49foo -50bar -51foobar -52barfoo -53foo -54bar -55foobar -56barfoo -57foo -58bar -59foobar -60barfoo -61foo -62bar -63foobar -64barfoo -65foo -66bar -67foobar -68barfoo -69foo -70bar -71foobar -72barfoo -73foo -74bar -75foobar -76barfoo -77foo -78bar -79foobar -80barfoo -81foo -82bar -83foobar -84barfoo -85foo -86bar -87foobar -88barfoo -89foo -90bar -91foobar -92barfoo -93foo -94bar -95foobar -96barfoo ------END RSA PRIVATE KEY-----`) - }) - - Convey("Allow unparsable sections", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: true, - Insensitive: true, - UnparseableSections: []string{"core_lesson", "comments"}, - }, []byte(` -Lesson_Location = 87 -Lesson_Status = C -Score = 3 -Time = 00:02:30 - -[CORE_LESSON] -my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data - -[COMMENTS] -<1> This slide has the fuel listed in the wrong units `)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("score").String(), ShouldEqual, "3") - So(f.Section("").Body(), ShouldBeEmpty) - So(f.Section("core_lesson").Body(), ShouldEqual, `my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data`) - So(f.Section("comments").Body(), ShouldEqual, `<1> This slide has the fuel listed in the wrong units `) - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `lesson_location = 87 -lesson_status = C -score = 3 -time = 00:02:30 - -[core_lesson] -my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data - -[comments] -<1> This slide has the fuel listed in the wrong units -`) - }) - - Convey("Inverse case", func() { - _, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` -[CORE_LESSON] -my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data`)) - So(err, ShouldNotBeNil) - }) - }) - - Convey("And false `SpaceBeforeInlineComment`", func() { - Convey("Can't parse INI files containing `#` or `;` in value", func() { - f, err := ini.LoadSources( - ini.LoadOptions{AllowPythonMultilineValues: false, SpaceBeforeInlineComment: false}, - []byte(` -[author] -NAME = U#n#k#n#w#o#n -GITHUB = U;n;k;n;w;o;n -`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - sec := f.Section("author") - nameValue := sec.Key("NAME").String() - githubValue := sec.Key("GITHUB").String() - So(nameValue, ShouldEqual, "U") - So(githubValue, ShouldEqual, "U") - }) - }) - - Convey("And true `SpaceBeforeInlineComment`", func() { - Convey("Can parse INI files containing `#` or `;` in value", func() { - f, err := ini.LoadSources( - ini.LoadOptions{AllowPythonMultilineValues: false, SpaceBeforeInlineComment: true}, - []byte(` -[author] -NAME = U#n#k#n#w#o#n -GITHUB = U;n;k;n;w;o;n -`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - sec := f.Section("author") - nameValue := sec.Key("NAME").String() - githubValue := sec.Key("GITHUB").String() - So(nameValue, ShouldEqual, "U#n#k#n#w#o#n") - So(githubValue, ShouldEqual, "U;n;k;n;w;o;n") - }) - }) - }) - - Convey("with false `AllowPythonMultilineValues`", func() { - Convey("Ignore nonexistent files", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false, Loose: true}, _NOT_FOUND_CONF, _MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - Convey("Inverse case", func() { - _, err = ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, _NOT_FOUND_CONF) - So(err, ShouldNotBeNil) - }) - }) - - Convey("Insensitive to section and key names", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false, Insensitive: true}, _MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("Author").Key("e-mail").String(), ShouldEqual, "u@gogs.io") - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `[author] -e-mail = u@gogs.io - -`) - }) - - Convey("Inverse case", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, _MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("Author").Key("e-mail").String(), ShouldBeEmpty) - }) - }) - - Convey("Ignore continuation lines", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: false, - IgnoreContinuation: true, - }, []byte(` -key1=a\b\ -key2=c\d\ -key3=value`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key1").String(), ShouldEqual, `a\b\`) - So(f.Section("").Key("key2").String(), ShouldEqual, `c\d\`) - So(f.Section("").Key("key3").String(), ShouldEqual, "value") - - Convey("Inverse case", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` -key1=a\b\ -key2=c\d\`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key1").String(), ShouldEqual, `a\bkey2=c\d`) - }) - }) - - Convey("Ignore inline comments", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: false, - IgnoreInlineComment: true, - }, []byte(` -key1=value ;comment -key2=value2 #comment2 -key3=val#ue #comment3`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key1").String(), ShouldEqual, `value ;comment`) - So(f.Section("").Key("key2").String(), ShouldEqual, `value2 #comment2`) - So(f.Section("").Key("key3").String(), ShouldEqual, `val#ue #comment3`) - - Convey("Inverse case", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` -key1=value ;comment -key2=value2 #comment2`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key1").String(), ShouldEqual, `value`) - So(f.Section("").Key("key1").Comment, ShouldEqual, `;comment`) - So(f.Section("").Key("key2").String(), ShouldEqual, `value2`) - So(f.Section("").Key("key2").Comment, ShouldEqual, `#comment2`) - }) - }) - - Convey("Allow boolean type keys", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: false, - AllowBooleanKeys: true, - }, []byte(` -key1=hello -#key2 -key3`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").KeyStrings(), ShouldResemble, []string{"key1", "key3"}) - So(f.Section("").Key("key3").MustBool(false), ShouldBeTrue) - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `key1 = hello -# key2 -key3 -`) - }) - - Convey("Inverse case", func() { - _, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` -key1=hello -#key2 -key3`)) - So(err, ShouldNotBeNil) - }) - }) - - Convey("Allow shadow keys", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false, AllowShadows: true}, []byte(` -[remote "origin"] -url = https://github.com/Antergone/test1.git -url = https://github.com/Antergone/test2.git -fetch = +refs/heads/*:refs/remotes/origin/*`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test1.git") - So(f.Section(`remote "origin"`).Key("url").ValueWithShadows(), ShouldResemble, []string{ - "https://github.com/Antergone/test1.git", - "https://github.com/Antergone/test2.git", - }) - So(f.Section(`remote "origin"`).Key("fetch").String(), ShouldEqual, "+refs/heads/*:refs/remotes/origin/*") - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `[remote "origin"] -url = https://github.com/Antergone/test1.git -url = https://github.com/Antergone/test2.git -fetch = +refs/heads/*:refs/remotes/origin/* - -`) - }) - - Convey("Inverse case", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` -[remote "origin"] -url = https://github.com/Antergone/test1.git -url = https://github.com/Antergone/test2.git`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test2.git") - }) - }) - - Convey("Unescape double quotes inside value", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: false, - UnescapeValueDoubleQuotes: true, - }, []byte(` -create_repo="创建了仓库 %s"`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("create_repo").String(), ShouldEqual, `创建了仓库 %s`) - - Convey("Inverse case", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` -create_repo="创建了仓库 %s"`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("create_repo").String(), ShouldEqual, `"创建了仓库 %s"`) - }) - }) - - Convey("Unescape comment symbols inside value", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: false, - IgnoreInlineComment: true, - UnescapeValueCommentSymbols: true, - }, []byte(` -key = test value more text -`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key").String(), ShouldEqual, `test value more text`) - }) - - Convey("Can't parse small python-compatible INI files", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` -[long] -long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- - foo - bar - foobar - barfoo - -----END RSA PRIVATE KEY----- -`)) - So(err, ShouldNotBeNil) - So(f, ShouldBeNil) - So(err.Error(), ShouldEqual, "key-value delimiter not found: foo\n") - }) - - Convey("Can't parse big python-compatible INI files", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` -[long] -long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- - 1foo - 2bar - 3foobar - 4barfoo - 5foo - 6bar - 7foobar - 8barfoo - 9foo - 10bar - 11foobar - 12barfoo - 13foo - 14bar - 15foobar - 16barfoo - 17foo - 18bar - 19foobar - 20barfoo - 21foo - 22bar - 23foobar - 24barfoo - 25foo - 26bar - 27foobar - 28barfoo - 29foo - 30bar - 31foobar - 32barfoo - 33foo - 34bar - 35foobar - 36barfoo - 37foo - 38bar - 39foobar - 40barfoo - 41foo - 42bar - 43foobar - 44barfoo - 45foo - 46bar - 47foobar - 48barfoo - 49foo - 50bar - 51foobar - 52barfoo - 53foo - 54bar - 55foobar - 56barfoo - 57foo - 58bar - 59foobar - 60barfoo - 61foo - 62bar - 63foobar - 64barfoo - 65foo - 66bar - 67foobar - 68barfoo - 69foo - 70bar - 71foobar - 72barfoo - 73foo - 74bar - 75foobar - 76barfoo - 77foo - 78bar - 79foobar - 80barfoo - 81foo - 82bar - 83foobar - 84barfoo - 85foo - 86bar - 87foobar - 88barfoo - 89foo - 90bar - 91foobar - 92barfoo - 93foo - 94bar - 95foobar - 96barfoo - -----END RSA PRIVATE KEY----- -`)) - So(err, ShouldNotBeNil) - So(f, ShouldBeNil) - So(err.Error(), ShouldEqual, "key-value delimiter not found: 1foo\n") - }) - - Convey("Allow unparsable sections", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowPythonMultilineValues: false, - Insensitive: true, - UnparseableSections: []string{"core_lesson", "comments"}, - }, []byte(` -Lesson_Location = 87 -Lesson_Status = C -Score = 3 -Time = 00:02:30 - -[CORE_LESSON] -my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data - -[COMMENTS] -<1> This slide has the fuel listed in the wrong units `)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("score").String(), ShouldEqual, "3") - So(f.Section("").Body(), ShouldBeEmpty) - So(f.Section("core_lesson").Body(), ShouldEqual, `my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data`) - So(f.Section("comments").Body(), ShouldEqual, `<1> This slide has the fuel listed in the wrong units `) - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `lesson_location = 87 -lesson_status = C -score = 3 -time = 00:02:30 - -[core_lesson] -my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data - -[comments] -<1> This slide has the fuel listed in the wrong units -`) - }) - - Convey("Inverse case", func() { - _, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` -[CORE_LESSON] -my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data`)) - So(err, ShouldNotBeNil) - }) - }) - - Convey("And false `SpaceBeforeInlineComment`", func() { - Convey("Can't parse INI files containing `#` or `;` in value", func() { - f, err := ini.LoadSources( - ini.LoadOptions{AllowPythonMultilineValues: true, SpaceBeforeInlineComment: false}, - []byte(` -[author] -NAME = U#n#k#n#w#o#n -GITHUB = U;n;k;n;w;o;n -`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - sec := f.Section("author") - nameValue := sec.Key("NAME").String() - githubValue := sec.Key("GITHUB").String() - So(nameValue, ShouldEqual, "U") - So(githubValue, ShouldEqual, "U") - }) - }) - - Convey("And true `SpaceBeforeInlineComment`", func() { - Convey("Can parse INI files containing `#` or `;` in value", func() { - f, err := ini.LoadSources( - ini.LoadOptions{AllowPythonMultilineValues: true, SpaceBeforeInlineComment: true}, - []byte(` -[author] -NAME = U#n#k#n#w#o#n -GITHUB = U;n;k;n;w;o;n -`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - sec := f.Section("author") - nameValue := sec.Key("NAME").String() - githubValue := sec.Key("GITHUB").String() - So(nameValue, ShouldEqual, "U#n#k#n#w#o#n") - So(githubValue, ShouldEqual, "U;n;k;n;w;o;n") - }) - }) - }) - }) -} diff --git a/vendor/github.com/go-ini/ini/key_test.go b/vendor/github.com/go-ini/ini/key_test.go deleted file mode 100644 index a13ad95f..00000000 --- a/vendor/github.com/go-ini/ini/key_test.go +++ /dev/null @@ -1,523 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini_test - -import ( - "bytes" - "fmt" - "strings" - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" - "gopkg.in/ini.v1" -) - -func TestKey_AddShadow(t *testing.T) { - Convey("Add shadow to a key", t, func() { - f, err := ini.ShadowLoad([]byte(` -[notes] --: note1`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - So(k.AddShadow("ini.v1"), ShouldBeNil) - So(k.ValueWithShadows(), ShouldResemble, []string{"ini", "ini.v1"}) - - Convey("Add shadow to boolean key", func() { - k, err := f.Section("").NewBooleanKey("published") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - So(k.AddShadow("beta"), ShouldNotBeNil) - }) - - Convey("Add shadow to auto-increment key", func() { - So(f.Section("notes").Key("#1").AddShadow("beta"), ShouldNotBeNil) - }) - }) - - Convey("Shadow is not allowed", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - So(k.AddShadow("ini.v1"), ShouldNotBeNil) - }) -} - -// Helpers for slice tests. -func float64sEqual(values []float64, expected ...float64) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i], ShouldEqual, v) - } -} - -func intsEqual(values []int, expected ...int) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i], ShouldEqual, v) - } -} - -func int64sEqual(values []int64, expected ...int64) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i], ShouldEqual, v) - } -} - -func uintsEqual(values []uint, expected ...uint) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i], ShouldEqual, v) - } -} - -func uint64sEqual(values []uint64, expected ...uint64) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i], ShouldEqual, v) - } -} - -func timesEqual(values []time.Time, expected ...time.Time) { - So(values, ShouldHaveLength, len(expected)) - for i, v := range expected { - So(values[i].String(), ShouldEqual, v.String()) - } -} - -func TestKey_Helpers(t *testing.T) { - Convey("Getting and setting values", t, func() { - f, err := ini.Load(_FULL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - Convey("Get string representation", func() { - sec := f.Section("") - So(sec, ShouldNotBeNil) - So(sec.Key("NAME").Value(), ShouldEqual, "ini") - So(sec.Key("NAME").String(), ShouldEqual, "ini") - So(sec.Key("NAME").Validate(func(in string) string { - return in - }), ShouldEqual, "ini") - So(sec.Key("NAME").Comment, ShouldEqual, "; Package name") - So(sec.Key("IMPORT_PATH").String(), ShouldEqual, "gopkg.in/ini.v1") - - Convey("With ValueMapper", func() { - f.ValueMapper = func(in string) string { - if in == "gopkg.in/%(NAME)s.%(VERSION)s" { - return "github.com/go-ini/ini" - } - return in - } - So(sec.Key("IMPORT_PATH").String(), ShouldEqual, "github.com/go-ini/ini") - }) - }) - - Convey("Get values in non-default section", func() { - sec := f.Section("author") - So(sec, ShouldNotBeNil) - So(sec.Key("NAME").String(), ShouldEqual, "Unknwon") - So(sec.Key("GITHUB").String(), ShouldEqual, "https://github.com/Unknwon") - - sec = f.Section("package") - So(sec, ShouldNotBeNil) - So(sec.Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1") - }) - - Convey("Get auto-increment key names", func() { - keys := f.Section("features").Keys() - for i, k := range keys { - So(k.Name(), ShouldEqual, fmt.Sprintf("#%d", i+1)) - } - }) - - Convey("Get parent-keys that are available to the child section", func() { - parentKeys := f.Section("package.sub").ParentKeys() - for _, k := range parentKeys { - So(k.Name(), ShouldEqual, "CLONE_URL") - } - }) - - Convey("Get overwrite value", func() { - So(f.Section("author").Key("E-MAIL").String(), ShouldEqual, "u@gogs.io") - }) - - Convey("Get sections", func() { - sections := f.Sections() - for i, name := range []string{ini.DEFAULT_SECTION, "author", "package", "package.sub", "features", "types", "array", "note", "comments", "string escapes", "advance"} { - So(sections[i].Name(), ShouldEqual, name) - } - }) - - Convey("Get parent section value", func() { - So(f.Section("package.sub").Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1") - So(f.Section("package.fake.sub").Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1") - }) - - Convey("Get multiple line value", func() { - So(f.Section("author").Key("BIO").String(), ShouldEqual, "Gopher.\nCoding addict.\nGood man.\n") - }) - - Convey("Get values with type", func() { - sec := f.Section("types") - v1, err := sec.Key("BOOL").Bool() - So(err, ShouldBeNil) - So(v1, ShouldBeTrue) - - v1, err = sec.Key("BOOL_FALSE").Bool() - So(err, ShouldBeNil) - So(v1, ShouldBeFalse) - - v2, err := sec.Key("FLOAT64").Float64() - So(err, ShouldBeNil) - So(v2, ShouldEqual, 1.25) - - v3, err := sec.Key("INT").Int() - So(err, ShouldBeNil) - So(v3, ShouldEqual, 10) - - v4, err := sec.Key("INT").Int64() - So(err, ShouldBeNil) - So(v4, ShouldEqual, 10) - - v5, err := sec.Key("UINT").Uint() - So(err, ShouldBeNil) - So(v5, ShouldEqual, 3) - - v6, err := sec.Key("UINT").Uint64() - So(err, ShouldBeNil) - So(v6, ShouldEqual, 3) - - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - v7, err := sec.Key("TIME").Time() - So(err, ShouldBeNil) - So(v7.String(), ShouldEqual, t.String()) - - Convey("Must get values with type", func() { - So(sec.Key("STRING").MustString("404"), ShouldEqual, "str") - So(sec.Key("BOOL").MustBool(), ShouldBeTrue) - So(sec.Key("FLOAT64").MustFloat64(), ShouldEqual, 1.25) - So(sec.Key("INT").MustInt(), ShouldEqual, 10) - So(sec.Key("INT").MustInt64(), ShouldEqual, 10) - So(sec.Key("UINT").MustUint(), ShouldEqual, 3) - So(sec.Key("UINT").MustUint64(), ShouldEqual, 3) - So(sec.Key("TIME").MustTime().String(), ShouldEqual, t.String()) - - dur, err := time.ParseDuration("2h45m") - So(err, ShouldBeNil) - So(sec.Key("DURATION").MustDuration().Seconds(), ShouldEqual, dur.Seconds()) - - Convey("Must get values with default value", func() { - So(sec.Key("STRING_404").MustString("404"), ShouldEqual, "404") - So(sec.Key("BOOL_404").MustBool(true), ShouldBeTrue) - So(sec.Key("FLOAT64_404").MustFloat64(2.5), ShouldEqual, 2.5) - So(sec.Key("INT_404").MustInt(15), ShouldEqual, 15) - So(sec.Key("INT64_404").MustInt64(15), ShouldEqual, 15) - So(sec.Key("UINT_404").MustUint(6), ShouldEqual, 6) - So(sec.Key("UINT64_404").MustUint64(6), ShouldEqual, 6) - - t, err := time.Parse(time.RFC3339, "2014-01-01T20:17:05Z") - So(err, ShouldBeNil) - So(sec.Key("TIME_404").MustTime(t).String(), ShouldEqual, t.String()) - - So(sec.Key("DURATION_404").MustDuration(dur).Seconds(), ShouldEqual, dur.Seconds()) - - Convey("Must should set default as key value", func() { - So(sec.Key("STRING_404").String(), ShouldEqual, "404") - So(sec.Key("BOOL_404").String(), ShouldEqual, "true") - So(sec.Key("FLOAT64_404").String(), ShouldEqual, "2.5") - So(sec.Key("INT_404").String(), ShouldEqual, "15") - So(sec.Key("INT64_404").String(), ShouldEqual, "15") - So(sec.Key("UINT_404").String(), ShouldEqual, "6") - So(sec.Key("UINT64_404").String(), ShouldEqual, "6") - So(sec.Key("TIME_404").String(), ShouldEqual, "2014-01-01T20:17:05Z") - So(sec.Key("DURATION_404").String(), ShouldEqual, "2h45m0s") - }) - }) - }) - }) - - Convey("Get value with candidates", func() { - sec := f.Section("types") - So(sec.Key("STRING").In("", []string{"str", "arr", "types"}), ShouldEqual, "str") - So(sec.Key("FLOAT64").InFloat64(0, []float64{1.25, 2.5, 3.75}), ShouldEqual, 1.25) - So(sec.Key("INT").InInt(0, []int{10, 20, 30}), ShouldEqual, 10) - So(sec.Key("INT").InInt64(0, []int64{10, 20, 30}), ShouldEqual, 10) - So(sec.Key("UINT").InUint(0, []uint{3, 6, 9}), ShouldEqual, 3) - So(sec.Key("UINT").InUint64(0, []uint64{3, 6, 9}), ShouldEqual, 3) - - zt, err := time.Parse(time.RFC3339, "0001-01-01T01:00:00Z") - So(err, ShouldBeNil) - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - So(sec.Key("TIME").InTime(zt, []time.Time{t, time.Now(), time.Now().Add(1 * time.Second)}).String(), ShouldEqual, t.String()) - - Convey("Get value with candidates and default value", func() { - So(sec.Key("STRING_404").In("str", []string{"str", "arr", "types"}), ShouldEqual, "str") - So(sec.Key("FLOAT64_404").InFloat64(1.25, []float64{1.25, 2.5, 3.75}), ShouldEqual, 1.25) - So(sec.Key("INT_404").InInt(10, []int{10, 20, 30}), ShouldEqual, 10) - So(sec.Key("INT64_404").InInt64(10, []int64{10, 20, 30}), ShouldEqual, 10) - So(sec.Key("UINT_404").InUint(3, []uint{3, 6, 9}), ShouldEqual, 3) - So(sec.Key("UINT_404").InUint64(3, []uint64{3, 6, 9}), ShouldEqual, 3) - So(sec.Key("TIME_404").InTime(t, []time.Time{time.Now(), time.Now(), time.Now().Add(1 * time.Second)}).String(), ShouldEqual, t.String()) - }) - }) - - Convey("Get values in range", func() { - sec := f.Section("types") - So(sec.Key("FLOAT64").RangeFloat64(0, 1, 2), ShouldEqual, 1.25) - So(sec.Key("INT").RangeInt(0, 10, 20), ShouldEqual, 10) - So(sec.Key("INT").RangeInt64(0, 10, 20), ShouldEqual, 10) - - minT, err := time.Parse(time.RFC3339, "0001-01-01T01:00:00Z") - So(err, ShouldBeNil) - midT, err := time.Parse(time.RFC3339, "2013-01-01T01:00:00Z") - So(err, ShouldBeNil) - maxT, err := time.Parse(time.RFC3339, "9999-01-01T01:00:00Z") - So(err, ShouldBeNil) - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - So(sec.Key("TIME").RangeTime(t, minT, maxT).String(), ShouldEqual, t.String()) - - Convey("Get value in range with default value", func() { - So(sec.Key("FLOAT64").RangeFloat64(5, 0, 1), ShouldEqual, 5) - So(sec.Key("INT").RangeInt(7, 0, 5), ShouldEqual, 7) - So(sec.Key("INT").RangeInt64(7, 0, 5), ShouldEqual, 7) - So(sec.Key("TIME").RangeTime(t, minT, midT).String(), ShouldEqual, t.String()) - }) - }) - - Convey("Get values into slice", func() { - sec := f.Section("array") - So(strings.Join(sec.Key("STRINGS").Strings(","), ","), ShouldEqual, "en,zh,de") - So(len(sec.Key("STRINGS_404").Strings(",")), ShouldEqual, 0) - - vals1 := sec.Key("FLOAT64S").Float64s(",") - float64sEqual(vals1, 1.1, 2.2, 3.3) - - vals2 := sec.Key("INTS").Ints(",") - intsEqual(vals2, 1, 2, 3) - - vals3 := sec.Key("INTS").Int64s(",") - int64sEqual(vals3, 1, 2, 3) - - vals4 := sec.Key("UINTS").Uints(",") - uintsEqual(vals4, 1, 2, 3) - - vals5 := sec.Key("UINTS").Uint64s(",") - uint64sEqual(vals5, 1, 2, 3) - - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - vals6 := sec.Key("TIMES").Times(",") - timesEqual(vals6, t, t, t) - }) - - Convey("Test string slice escapes", func() { - sec := f.Section("string escapes") - So(sec.Key("key1").Strings(","), ShouldResemble, []string{"value1", "value2", "value3"}) - So(sec.Key("key2").Strings(","), ShouldResemble, []string{"value1, value2"}) - So(sec.Key("key3").Strings(","), ShouldResemble, []string{`val\ue1`, "value2"}) - So(sec.Key("key4").Strings(","), ShouldResemble, []string{`value1\`, `value\\2`}) - So(sec.Key("key5").Strings(",,"), ShouldResemble, []string{"value1,, value2"}) - So(sec.Key("key6").Strings(" "), ShouldResemble, []string{"aaa", "bbb and space", "ccc"}) - }) - - Convey("Get valid values into slice", func() { - sec := f.Section("array") - vals1 := sec.Key("FLOAT64S").ValidFloat64s(",") - float64sEqual(vals1, 1.1, 2.2, 3.3) - - vals2 := sec.Key("INTS").ValidInts(",") - intsEqual(vals2, 1, 2, 3) - - vals3 := sec.Key("INTS").ValidInt64s(",") - int64sEqual(vals3, 1, 2, 3) - - vals4 := sec.Key("UINTS").ValidUints(",") - uintsEqual(vals4, 1, 2, 3) - - vals5 := sec.Key("UINTS").ValidUint64s(",") - uint64sEqual(vals5, 1, 2, 3) - - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - vals6 := sec.Key("TIMES").ValidTimes(",") - timesEqual(vals6, t, t, t) - }) - - Convey("Get values one type into slice of another type", func() { - sec := f.Section("array") - vals1 := sec.Key("STRINGS").ValidFloat64s(",") - So(vals1, ShouldBeEmpty) - - vals2 := sec.Key("STRINGS").ValidInts(",") - So(vals2, ShouldBeEmpty) - - vals3 := sec.Key("STRINGS").ValidInt64s(",") - So(vals3, ShouldBeEmpty) - - vals4 := sec.Key("STRINGS").ValidUints(",") - So(vals4, ShouldBeEmpty) - - vals5 := sec.Key("STRINGS").ValidUint64s(",") - So(vals5, ShouldBeEmpty) - - vals6 := sec.Key("STRINGS").ValidTimes(",") - So(vals6, ShouldBeEmpty) - }) - - Convey("Get valid values into slice without errors", func() { - sec := f.Section("array") - vals1, err := sec.Key("FLOAT64S").StrictFloat64s(",") - So(err, ShouldBeNil) - float64sEqual(vals1, 1.1, 2.2, 3.3) - - vals2, err := sec.Key("INTS").StrictInts(",") - So(err, ShouldBeNil) - intsEqual(vals2, 1, 2, 3) - - vals3, err := sec.Key("INTS").StrictInt64s(",") - So(err, ShouldBeNil) - int64sEqual(vals3, 1, 2, 3) - - vals4, err := sec.Key("UINTS").StrictUints(",") - So(err, ShouldBeNil) - uintsEqual(vals4, 1, 2, 3) - - vals5, err := sec.Key("UINTS").StrictUint64s(",") - So(err, ShouldBeNil) - uint64sEqual(vals5, 1, 2, 3) - - t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z") - So(err, ShouldBeNil) - vals6, err := sec.Key("TIMES").StrictTimes(",") - So(err, ShouldBeNil) - timesEqual(vals6, t, t, t) - }) - - Convey("Get invalid values into slice", func() { - sec := f.Section("array") - vals1, err := sec.Key("STRINGS").StrictFloat64s(",") - So(vals1, ShouldBeEmpty) - So(err, ShouldNotBeNil) - - vals2, err := sec.Key("STRINGS").StrictInts(",") - So(vals2, ShouldBeEmpty) - So(err, ShouldNotBeNil) - - vals3, err := sec.Key("STRINGS").StrictInt64s(",") - So(vals3, ShouldBeEmpty) - So(err, ShouldNotBeNil) - - vals4, err := sec.Key("STRINGS").StrictUints(",") - So(vals4, ShouldBeEmpty) - So(err, ShouldNotBeNil) - - vals5, err := sec.Key("STRINGS").StrictUint64s(",") - So(vals5, ShouldBeEmpty) - So(err, ShouldNotBeNil) - - vals6, err := sec.Key("STRINGS").StrictTimes(",") - So(vals6, ShouldBeEmpty) - So(err, ShouldNotBeNil) - }) - }) -} - -func TestKey_StringsWithShadows(t *testing.T) { - Convey("Get strings of shadows of a key", t, func() { - f, err := ini.ShadowLoad([]byte("")) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NUMS", "1,2") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - k, err = f.Section("").NewKey("NUMS", "4,5,6") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - So(k.StringsWithShadows(","), ShouldResemble, []string{"1", "2", "4", "5", "6"}) - }) -} - -func TestKey_SetValue(t *testing.T) { - Convey("Set value of key", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - So(k.Value(), ShouldEqual, "ini") - - k.SetValue("ini.v1") - So(k.Value(), ShouldEqual, "ini.v1") - }) -} - -func TestKey_NestedValues(t *testing.T) { - Convey("Read and write nested values", t, func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowNestedValues: true, - }, []byte(` -aws_access_key_id = foo -aws_secret_access_key = bar -region = us-west-2 -s3 = - max_concurrent_requests=10 - max_queue_size=1000`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("s3").NestedValues(), ShouldResemble, []string{"max_concurrent_requests=10", "max_queue_size=1000"}) - - var buf bytes.Buffer - _, err = f.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `aws_access_key_id = foo -aws_secret_access_key = bar -region = us-west-2 -s3 = - max_concurrent_requests=10 - max_queue_size=1000 - -`) - }) -} - -func TestRecursiveValues(t *testing.T) { - Convey("Recursive values should not reflect on same key", t, func() { - f, err := ini.Load([]byte(` -NAME = ini -[package] -NAME = %(NAME)s`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - So(f.Section("package").Key("NAME").String(), ShouldEqual, "ini") - }) -} diff --git a/vendor/github.com/go-ini/ini/parser_test.go b/vendor/github.com/go-ini/ini/parser_test.go deleted file mode 100644 index bb0f2665..00000000 --- a/vendor/github.com/go-ini/ini/parser_test.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2016 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini_test - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" - "gopkg.in/ini.v1" -) - -func TestBOM(t *testing.T) { - Convey("Test handling BOM", t, func() { - Convey("UTF-8-BOM", func() { - f, err := ini.Load("testdata/UTF-8-BOM.ini") - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("author").Key("E-MAIL").String(), ShouldEqual, "u@gogs.io") - }) - - Convey("UTF-16-LE-BOM", func() { - f, err := ini.Load("testdata/UTF-16-LE-BOM.ini") - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - }) - - Convey("UTF-16-BE-BOM", func() { - }) - }) -} - -func TestBadLoad(t *testing.T) { - Convey("Load with bad data", t, func() { - Convey("Bad section name", func() { - _, err := ini.Load([]byte("[]")) - So(err, ShouldNotBeNil) - - _, err = ini.Load([]byte("[")) - So(err, ShouldNotBeNil) - }) - - Convey("Bad keys", func() { - _, err := ini.Load([]byte(`"""name`)) - So(err, ShouldNotBeNil) - - _, err = ini.Load([]byte(`"""name"""`)) - So(err, ShouldNotBeNil) - - _, err = ini.Load([]byte(`""=1`)) - So(err, ShouldNotBeNil) - - _, err = ini.Load([]byte(`=`)) - So(err, ShouldNotBeNil) - - _, err = ini.Load([]byte(`name`)) - So(err, ShouldNotBeNil) - }) - - Convey("Bad values", func() { - _, err := ini.Load([]byte(`name="""Unknwon`)) - So(err, ShouldNotBeNil) - }) - }) -} diff --git a/vendor/github.com/go-ini/ini/section_test.go b/vendor/github.com/go-ini/ini/section_test.go deleted file mode 100644 index e9c34788..00000000 --- a/vendor/github.com/go-ini/ini/section_test.go +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini_test - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" - "gopkg.in/ini.v1" -) - -func TestSection_SetBody(t *testing.T) { - Convey("Set body of raw section", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - sec, err := f.NewRawSection("comments", `1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000`) - So(err, ShouldBeNil) - So(sec, ShouldNotBeNil) - So(sec.Body(), ShouldEqual, `1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000`) - - sec.SetBody("1111111111111111111000000000000000001110000") - So(sec.Body(), ShouldEqual, `1111111111111111111000000000000000001110000`) - - Convey("Set for non-raw section", func() { - sec, err := f.NewSection("author") - So(err, ShouldBeNil) - So(sec, ShouldNotBeNil) - So(sec.Body(), ShouldBeEmpty) - - sec.SetBody("1111111111111111111000000000000000001110000") - So(sec.Body(), ShouldBeEmpty) - }) - }) -} - -func TestSection_NewKey(t *testing.T) { - Convey("Create a new key", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - So(k.Name(), ShouldEqual, "NAME") - So(k.Value(), ShouldEqual, "ini") - - Convey("With duplicated name", func() { - k, err := f.Section("").NewKey("NAME", "ini.v1") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - // Overwrite previous existed key - So(k.Value(), ShouldEqual, "ini.v1") - }) - - Convey("With empty string", func() { - _, err := f.Section("").NewKey("", "") - So(err, ShouldNotBeNil) - }) - }) - - Convey("Create keys with same name and allow shadow", t, func() { - f, err := ini.ShadowLoad([]byte("")) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - k, err = f.Section("").NewKey("NAME", "ini.v1") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - So(k.ValueWithShadows(), ShouldResemble, []string{"ini", "ini.v1"}) - }) -} - -func TestSection_NewBooleanKey(t *testing.T) { - Convey("Create a new boolean key", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewBooleanKey("start-ssh-server") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - So(k.Name(), ShouldEqual, "start-ssh-server") - So(k.Value(), ShouldEqual, "true") - - Convey("With empty string", func() { - _, err := f.Section("").NewBooleanKey("") - So(err, ShouldNotBeNil) - }) - }) -} - -func TestSection_GetKey(t *testing.T) { - Convey("Get a key", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - k, err = f.Section("").GetKey("NAME") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - So(k.Name(), ShouldEqual, "NAME") - So(k.Value(), ShouldEqual, "ini") - - Convey("Key not exists", func() { - _, err := f.Section("").GetKey("404") - So(err, ShouldNotBeNil) - }) - - Convey("Key exists in parent section", func() { - k, err := f.Section("parent").NewKey("AGE", "18") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - k, err = f.Section("parent.child.son").GetKey("AGE") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - So(k.Value(), ShouldEqual, "18") - }) - }) -} - -func TestSection_HasKey(t *testing.T) { - Convey("Check if a key exists", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - So(f.Section("").HasKey("NAME"), ShouldBeTrue) - So(f.Section("").Haskey("NAME"), ShouldBeTrue) - So(f.Section("").HasKey("404"), ShouldBeFalse) - So(f.Section("").Haskey("404"), ShouldBeFalse) - }) -} - -func TestSection_HasValue(t *testing.T) { - Convey("Check if contains a value in any key", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - So(f.Section("").HasValue("ini"), ShouldBeTrue) - So(f.Section("").HasValue("404"), ShouldBeFalse) - }) -} - -func TestSection_Key(t *testing.T) { - Convey("Get a key", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - k = f.Section("").Key("NAME") - So(k, ShouldNotBeNil) - So(k.Name(), ShouldEqual, "NAME") - So(k.Value(), ShouldEqual, "ini") - - Convey("Key not exists", func() { - k := f.Section("").Key("404") - So(k, ShouldNotBeNil) - So(k.Name(), ShouldEqual, "404") - }) - - Convey("Key exists in parent section", func() { - k, err := f.Section("parent").NewKey("AGE", "18") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - k = f.Section("parent.child.son").Key("AGE") - So(k, ShouldNotBeNil) - So(k.Value(), ShouldEqual, "18") - }) - }) -} - -func TestSection_Keys(t *testing.T) { - Convey("Get all keys in a section", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - k, err = f.Section("").NewKey("VERSION", "v1") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - k, err = f.Section("").NewKey("IMPORT_PATH", "gopkg.in/ini.v1") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - keys := f.Section("").Keys() - names := []string{"NAME", "VERSION", "IMPORT_PATH"} - So(len(keys), ShouldEqual, len(names)) - for i, name := range names { - So(keys[i].Name(), ShouldEqual, name) - } - }) -} - -func TestSection_ParentKeys(t *testing.T) { - Convey("Get all keys of parent sections", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("package").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - k, err = f.Section("package").NewKey("VERSION", "v1") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - k, err = f.Section("package").NewKey("IMPORT_PATH", "gopkg.in/ini.v1") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - keys := f.Section("package.sub.sub2").ParentKeys() - names := []string{"NAME", "VERSION", "IMPORT_PATH"} - So(len(keys), ShouldEqual, len(names)) - for i, name := range names { - So(keys[i].Name(), ShouldEqual, name) - } - }) -} - -func TestSection_KeyStrings(t *testing.T) { - Convey("Get all key names in a section", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - k, err = f.Section("").NewKey("VERSION", "v1") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - k, err = f.Section("").NewKey("IMPORT_PATH", "gopkg.in/ini.v1") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - So(f.Section("").KeyStrings(), ShouldResemble, []string{"NAME", "VERSION", "IMPORT_PATH"}) - }) -} - -func TestSection_KeyHash(t *testing.T) { - Convey("Get clone of key hash", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - k, err = f.Section("").NewKey("VERSION", "v1") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - k, err = f.Section("").NewKey("IMPORT_PATH", "gopkg.in/ini.v1") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - hash := f.Section("").KeysHash() - relation := map[string]string{ - "NAME": "ini", - "VERSION": "v1", - "IMPORT_PATH": "gopkg.in/ini.v1", - } - for k, v := range hash { - So(v, ShouldEqual, relation[k]) - } - }) -} - -func TestSection_DeleteKey(t *testing.T) { - Convey("Delete a key", t, func() { - f := ini.Empty() - So(f, ShouldNotBeNil) - - k, err := f.Section("").NewKey("NAME", "ini") - So(err, ShouldBeNil) - So(k, ShouldNotBeNil) - - So(f.Section("").HasKey("NAME"), ShouldBeTrue) - f.Section("").DeleteKey("NAME") - So(f.Section("").HasKey("NAME"), ShouldBeFalse) - }) -} diff --git a/vendor/github.com/go-ini/ini/struct_test.go b/vendor/github.com/go-ini/ini/struct_test.go deleted file mode 100644 index 0dbbef22..00000000 --- a/vendor/github.com/go-ini/ini/struct_test.go +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini_test - -import ( - "bytes" - "fmt" - "strings" - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" - "gopkg.in/ini.v1" -) - -type testNested struct { - Cities []string `delim:"|"` - Visits []time.Time - Years []int - Numbers []int64 - Ages []uint - Populations []uint64 - Coordinates []float64 - Note string - Unused int `ini:"-"` -} - -type TestEmbeded struct { - GPA float64 -} - -type testStruct struct { - Name string `ini:"NAME"` - Age int - Male bool - Money float64 - Born time.Time - Time time.Duration `ini:"Duration"` - Others testNested - *TestEmbeded `ini:"grade"` - Unused int `ini:"-"` - Unsigned uint - Omitted bool `ini:"omitthis,omitempty"` - Shadows []string `ini:",,allowshadow"` - ShadowInts []int `ini:"Shadows,,allowshadow"` -} - -const _CONF_DATA_STRUCT = ` -NAME = Unknwon -Age = 21 -Male = true -Money = 1.25 -Born = 1993-10-07T20:17:05Z -Duration = 2h45m -Unsigned = 3 -omitthis = true -Shadows = 1, 2 -Shadows = 3, 4 - -[Others] -Cities = HangZhou|Boston -Visits = 1993-10-07T20:17:05Z, 1993-10-07T20:17:05Z -Years = 1993,1994 -Numbers = 10010,10086 -Ages = 18,19 -Populations = 12345678,98765432 -Coordinates = 192.168,10.11 -Note = Hello world! - -[grade] -GPA = 2.8 - -[foo.bar] -Here = there -When = then -` - -type unsupport struct { - Byte byte -} - -type unsupport2 struct { - Others struct { - Cities byte - } -} - -type Unsupport3 struct { - Cities byte -} - -type unsupport4 struct { - *Unsupport3 `ini:"Others"` -} - -type defaultValue struct { - Name string - Age int - Male bool - Money float64 - Born time.Time - Cities []string -} - -type fooBar struct { - Here, When string -} - -const _INVALID_DATA_CONF_STRUCT = ` -Name = -Age = age -Male = 123 -Money = money -Born = nil -Cities = -` - -func Test_MapToStruct(t *testing.T) { - Convey("Map to struct", t, func() { - Convey("Map file to struct", func() { - ts := new(testStruct) - So(ini.MapTo(ts, []byte(_CONF_DATA_STRUCT)), ShouldBeNil) - - So(ts.Name, ShouldEqual, "Unknwon") - So(ts.Age, ShouldEqual, 21) - So(ts.Male, ShouldBeTrue) - So(ts.Money, ShouldEqual, 1.25) - So(ts.Unsigned, ShouldEqual, 3) - - t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z") - So(err, ShouldBeNil) - So(ts.Born.String(), ShouldEqual, t.String()) - - dur, err := time.ParseDuration("2h45m") - So(err, ShouldBeNil) - So(ts.Time.Seconds(), ShouldEqual, dur.Seconds()) - - So(strings.Join(ts.Others.Cities, ","), ShouldEqual, "HangZhou,Boston") - So(ts.Others.Visits[0].String(), ShouldEqual, t.String()) - So(fmt.Sprint(ts.Others.Years), ShouldEqual, "[1993 1994]") - So(fmt.Sprint(ts.Others.Numbers), ShouldEqual, "[10010 10086]") - So(fmt.Sprint(ts.Others.Ages), ShouldEqual, "[18 19]") - So(fmt.Sprint(ts.Others.Populations), ShouldEqual, "[12345678 98765432]") - So(fmt.Sprint(ts.Others.Coordinates), ShouldEqual, "[192.168 10.11]") - So(ts.Others.Note, ShouldEqual, "Hello world!") - So(ts.TestEmbeded.GPA, ShouldEqual, 2.8) - }) - - Convey("Map section to struct", func() { - foobar := new(fooBar) - f, err := ini.Load([]byte(_CONF_DATA_STRUCT)) - So(err, ShouldBeNil) - - So(f.Section("foo.bar").MapTo(foobar), ShouldBeNil) - So(foobar.Here, ShouldEqual, "there") - So(foobar.When, ShouldEqual, "then") - }) - - Convey("Map to non-pointer struct", func() { - f, err := ini.Load([]byte(_CONF_DATA_STRUCT)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.MapTo(testStruct{}), ShouldNotBeNil) - }) - - Convey("Map to unsupported type", func() { - f, err := ini.Load([]byte(_CONF_DATA_STRUCT)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - f.NameMapper = func(raw string) string { - if raw == "Byte" { - return "NAME" - } - return raw - } - So(f.MapTo(&unsupport{}), ShouldNotBeNil) - So(f.MapTo(&unsupport2{}), ShouldNotBeNil) - So(f.MapTo(&unsupport4{}), ShouldNotBeNil) - }) - - Convey("Map to omitempty field", func() { - ts := new(testStruct) - So(ini.MapTo(ts, []byte(_CONF_DATA_STRUCT)), ShouldBeNil) - - So(ts.Omitted, ShouldEqual, true) - }) - - Convey("Map with shadows", func() { - f, err := ini.LoadSources(ini.LoadOptions{AllowShadows: true}, []byte(_CONF_DATA_STRUCT)) - So(err, ShouldBeNil) - ts := new(testStruct) - So(f.MapTo(ts), ShouldBeNil) - - So(strings.Join(ts.Shadows, " "), ShouldEqual, "1 2 3 4") - So(fmt.Sprintf("%v", ts.ShadowInts), ShouldEqual, "[1 2 3 4]") - }) - - Convey("Map from invalid data source", func() { - So(ini.MapTo(&testStruct{}, "hi"), ShouldNotBeNil) - }) - - Convey("Map to wrong types and gain default values", func() { - f, err := ini.Load([]byte(_INVALID_DATA_CONF_STRUCT)) - So(err, ShouldBeNil) - - t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z") - So(err, ShouldBeNil) - dv := &defaultValue{"Joe", 10, true, 1.25, t, []string{"HangZhou", "Boston"}} - So(f.MapTo(dv), ShouldBeNil) - So(dv.Name, ShouldEqual, "Joe") - So(dv.Age, ShouldEqual, 10) - So(dv.Male, ShouldBeTrue) - So(dv.Money, ShouldEqual, 1.25) - So(dv.Born.String(), ShouldEqual, t.String()) - So(strings.Join(dv.Cities, ","), ShouldEqual, "HangZhou,Boston") - }) - }) - - Convey("Map to struct in strict mode", t, func() { - f, err := ini.Load([]byte(` -name=bruce -age=a30`)) - So(err, ShouldBeNil) - - type Strict struct { - Name string `ini:"name"` - Age int `ini:"age"` - } - s := new(Strict) - - So(f.Section("").StrictMapTo(s), ShouldNotBeNil) - }) - - Convey("Map slice in strict mode", t, func() { - f, err := ini.Load([]byte(` -names=alice, bruce`)) - So(err, ShouldBeNil) - - type Strict struct { - Names []string `ini:"names"` - } - s := new(Strict) - - So(f.Section("").StrictMapTo(s), ShouldBeNil) - So(fmt.Sprint(s.Names), ShouldEqual, "[alice bruce]") - }) -} - -func Test_ReflectFromStruct(t *testing.T) { - Convey("Reflect from struct", t, func() { - type Embeded struct { - Dates []time.Time `delim:"|" comment:"Time data"` - Places []string - Years []int - Numbers []int64 - Ages []uint - Populations []uint64 - Coordinates []float64 - None []int - } - type Author struct { - Name string `ini:"NAME"` - Male bool - Age int `comment:"Author's age"` - Height uint - GPA float64 - Date time.Time - NeverMind string `ini:"-"` - *Embeded `ini:"infos" comment:"Embeded section"` - } - - t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z") - So(err, ShouldBeNil) - a := &Author{"Unknwon", true, 21, 100, 2.8, t, "", - &Embeded{ - []time.Time{t, t}, - []string{"HangZhou", "Boston"}, - []int{1993, 1994}, - []int64{10010, 10086}, - []uint{18, 19}, - []uint64{12345678, 98765432}, - []float64{192.168, 10.11}, - []int{}, - }} - cfg := ini.Empty() - So(ini.ReflectFrom(cfg, a), ShouldBeNil) - - var buf bytes.Buffer - _, err = cfg.WriteTo(&buf) - So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `NAME = Unknwon -Male = true -; Author's age -Age = 21 -Height = 100 -GPA = 2.8 -Date = 1993-10-07T20:17:05Z - -; Embeded section -[infos] -; Time data -Dates = 1993-10-07T20:17:05Z|1993-10-07T20:17:05Z -Places = HangZhou,Boston -Years = 1993,1994 -Numbers = 10010,10086 -Ages = 18,19 -Populations = 12345678,98765432 -Coordinates = 192.168,10.11 -None = - -`) - - Convey("Reflect from non-point struct", func() { - So(ini.ReflectFrom(cfg, Author{}), ShouldNotBeNil) - }) - - Convey("Reflect from struct with omitempty", func() { - cfg := ini.Empty() - type SpecialStruct struct { - FirstName string `ini:"first_name"` - LastName string `ini:"last_name"` - JustOmitMe string `ini:"omitempty"` - LastLogin time.Time `ini:"last_login,omitempty"` - LastLogin2 time.Time `ini:",omitempty"` - NotEmpty int `ini:"omitempty"` - } - - So(ini.ReflectFrom(cfg, &SpecialStruct{FirstName: "John", LastName: "Doe", NotEmpty: 9}), ShouldBeNil) - - var buf bytes.Buffer - _, err = cfg.WriteTo(&buf) - So(buf.String(), ShouldEqual, `first_name = John -last_name = Doe -omitempty = 9 - -`) - }) - }) -} - -type testMapper struct { - PackageName string -} - -func Test_NameGetter(t *testing.T) { - Convey("Test name mappers", t, func() { - So(ini.MapToWithMapper(&testMapper{}, ini.TitleUnderscore, []byte("packag_name=ini")), ShouldBeNil) - - cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) - So(err, ShouldBeNil) - So(cfg, ShouldNotBeNil) - - cfg.NameMapper = ini.AllCapsUnderscore - tg := new(testMapper) - So(cfg.MapTo(tg), ShouldBeNil) - So(tg.PackageName, ShouldEqual, "ini") - }) -} - -type testDurationStruct struct { - Duration time.Duration `ini:"Duration"` -} - -func Test_Duration(t *testing.T) { - Convey("Duration less than 16m50s", t, func() { - ds := new(testDurationStruct) - So(ini.MapTo(ds, []byte("Duration=16m49s")), ShouldBeNil) - - dur, err := time.ParseDuration("16m49s") - So(err, ShouldBeNil) - So(ds.Duration.Seconds(), ShouldEqual, dur.Seconds()) - }) -} diff --git a/vendor/github.com/jmespath/go-jmespath/.gitignore b/vendor/github.com/jmespath/go-jmespath/.gitignore deleted file mode 100644 index 531fcc11..00000000 --- a/vendor/github.com/jmespath/go-jmespath/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -jpgo -jmespath-fuzz.zip -cpu.out -go-jmespath.test diff --git a/vendor/github.com/jmespath/go-jmespath/.travis.yml b/vendor/github.com/jmespath/go-jmespath/.travis.yml deleted file mode 100644 index 1f980775..00000000 --- a/vendor/github.com/jmespath/go-jmespath/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go - -sudo: false - -go: - - 1.4 - -install: go get -v -t ./... -script: make test diff --git a/vendor/github.com/jmespath/go-jmespath/Makefile b/vendor/github.com/jmespath/go-jmespath/Makefile deleted file mode 100644 index a828d284..00000000 --- a/vendor/github.com/jmespath/go-jmespath/Makefile +++ /dev/null @@ -1,44 +0,0 @@ - -CMD = jpgo - -help: - @echo "Please use \`make ' where is one of" - @echo " test to run all the tests" - @echo " build to build the library and jp executable" - @echo " generate to run codegen" - - -generate: - go generate ./... - -build: - rm -f $(CMD) - go build ./... - rm -f cmd/$(CMD)/$(CMD) && cd cmd/$(CMD)/ && go build ./... - mv cmd/$(CMD)/$(CMD) . - -test: - go test -v ./... - -check: - go vet ./... - @echo "golint ./..." - @lint=`golint ./...`; \ - lint=`echo "$$lint" | grep -v "astnodetype_string.go" | grep -v "toktype_string.go"`; \ - echo "$$lint"; \ - if [ "$$lint" != "" ]; then exit 1; fi - -htmlc: - go test -coverprofile="/tmp/jpcov" && go tool cover -html="/tmp/jpcov" && unlink /tmp/jpcov - -buildfuzz: - go-fuzz-build github.com/jmespath/go-jmespath/fuzz - -fuzz: buildfuzz - go-fuzz -bin=./jmespath-fuzz.zip -workdir=fuzz/testdata - -bench: - go test -bench . -cpuprofile cpu.out - -pprof-cpu: - go tool pprof ./go-jmespath.test ./cpu.out diff --git a/vendor/github.com/jmespath/go-jmespath/README.md b/vendor/github.com/jmespath/go-jmespath/README.md deleted file mode 100644 index 187ef676..00000000 --- a/vendor/github.com/jmespath/go-jmespath/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# go-jmespath - A JMESPath implementation in Go - -[![Build Status](https://img.shields.io/travis/jmespath/go-jmespath.svg)](https://travis-ci.org/jmespath/go-jmespath) - - - -See http://jmespath.org for more info. diff --git a/vendor/github.com/jmespath/go-jmespath/api_test.go b/vendor/github.com/jmespath/go-jmespath/api_test.go deleted file mode 100644 index b0b106d3..00000000 --- a/vendor/github.com/jmespath/go-jmespath/api_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package jmespath - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestValidPrecompiledExpressionSearches(t *testing.T) { - assert := assert.New(t) - data := make(map[string]interface{}) - data["foo"] = "bar" - precompiled, err := Compile("foo") - assert.Nil(err) - result, err := precompiled.Search(data) - assert.Nil(err) - assert.Equal("bar", result) -} - -func TestInvalidPrecompileErrors(t *testing.T) { - assert := assert.New(t) - _, err := Compile("not a valid expression") - assert.NotNil(err) -} - -func TestInvalidMustCompilePanics(t *testing.T) { - defer func() { - r := recover() - assert.NotNil(t, r) - }() - MustCompile("not a valid expression") -} diff --git a/vendor/github.com/jmespath/go-jmespath/compliance_test.go b/vendor/github.com/jmespath/go-jmespath/compliance_test.go deleted file mode 100644 index 4ee9c959..00000000 --- a/vendor/github.com/jmespath/go-jmespath/compliance_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" -) - -type TestSuite struct { - Given interface{} - TestCases []TestCase `json:"cases"` - Comment string -} -type TestCase struct { - Comment string - Expression string - Result interface{} - Error string -} - -var whiteListed = []string{ - "compliance/basic.json", - "compliance/current.json", - "compliance/escape.json", - "compliance/filters.json", - "compliance/functions.json", - "compliance/identifiers.json", - "compliance/indices.json", - "compliance/literal.json", - "compliance/multiselect.json", - "compliance/ormatch.json", - "compliance/pipe.json", - "compliance/slice.json", - "compliance/syntax.json", - "compliance/unicode.json", - "compliance/wildcard.json", - "compliance/boolean.json", -} - -func allowed(path string) bool { - for _, el := range whiteListed { - if el == path { - return true - } - } - return false -} - -func TestCompliance(t *testing.T) { - assert := assert.New(t) - - var complianceFiles []string - err := filepath.Walk("compliance", func(path string, _ os.FileInfo, _ error) error { - //if strings.HasSuffix(path, ".json") { - if allowed(path) { - complianceFiles = append(complianceFiles, path) - } - return nil - }) - if assert.Nil(err) { - for _, filename := range complianceFiles { - runComplianceTest(assert, filename) - } - } -} - -func runComplianceTest(assert *assert.Assertions, filename string) { - var testSuites []TestSuite - data, err := ioutil.ReadFile(filename) - if assert.Nil(err) { - err := json.Unmarshal(data, &testSuites) - if assert.Nil(err) { - for _, testsuite := range testSuites { - runTestSuite(assert, testsuite, filename) - } - } - } -} - -func runTestSuite(assert *assert.Assertions, testsuite TestSuite, filename string) { - for _, testcase := range testsuite.TestCases { - if testcase.Error != "" { - // This is a test case that verifies we error out properly. - runSyntaxTestCase(assert, testsuite.Given, testcase, filename) - } else { - runTestCase(assert, testsuite.Given, testcase, filename) - } - } -} - -func runSyntaxTestCase(assert *assert.Assertions, given interface{}, testcase TestCase, filename string) { - // Anything with an .Error means that we expect that JMESPath should return - // an error when we try to evaluate the expression. - _, err := Search(testcase.Expression, given) - assert.NotNil(err, fmt.Sprintf("Expression: %s", testcase.Expression)) -} - -func runTestCase(assert *assert.Assertions, given interface{}, testcase TestCase, filename string) { - lexer := NewLexer() - var err error - _, err = lexer.tokenize(testcase.Expression) - if err != nil { - errMsg := fmt.Sprintf("(%s) Could not lex expression: %s -- %s", filename, testcase.Expression, err.Error()) - assert.Fail(errMsg) - return - } - parser := NewParser() - _, err = parser.Parse(testcase.Expression) - if err != nil { - errMsg := fmt.Sprintf("(%s) Could not parse expression: %s -- %s", filename, testcase.Expression, err.Error()) - assert.Fail(errMsg) - return - } - actual, err := Search(testcase.Expression, given) - if assert.Nil(err, fmt.Sprintf("Expression: %s", testcase.Expression)) { - assert.Equal(testcase.Result, actual, fmt.Sprintf("Expression: %s", testcase.Expression)) - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/interpreter_test.go b/vendor/github.com/jmespath/go-jmespath/interpreter_test.go deleted file mode 100644 index 11c6d0aa..00000000 --- a/vendor/github.com/jmespath/go-jmespath/interpreter_test.go +++ /dev/null @@ -1,221 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -type scalars struct { - Foo string - Bar string -} - -type sliceType struct { - A string - B []scalars - C []*scalars -} - -type benchmarkStruct struct { - Fooasdfasdfasdfasdf string -} - -type benchmarkNested struct { - Fooasdfasdfasdfasdf nestedA -} - -type nestedA struct { - Fooasdfasdfasdfasdf nestedB -} - -type nestedB struct { - Fooasdfasdfasdfasdf nestedC -} - -type nestedC struct { - Fooasdfasdfasdfasdf string -} - -type nestedSlice struct { - A []sliceType -} - -func TestCanSupportEmptyInterface(t *testing.T) { - assert := assert.New(t) - data := make(map[string]interface{}) - data["foo"] = "bar" - result, err := Search("foo", data) - assert.Nil(err) - assert.Equal("bar", result) -} - -func TestCanSupportUserDefinedStructsValue(t *testing.T) { - assert := assert.New(t) - s := scalars{Foo: "one", Bar: "bar"} - result, err := Search("Foo", s) - assert.Nil(err) - assert.Equal("one", result) -} - -func TestCanSupportUserDefinedStructsRef(t *testing.T) { - assert := assert.New(t) - s := scalars{Foo: "one", Bar: "bar"} - result, err := Search("Foo", &s) - assert.Nil(err) - assert.Equal("one", result) -} - -func TestCanSupportStructWithSliceAll(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", B: []scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("B[].Foo", data) - assert.Nil(err) - assert.Equal([]interface{}{"f1", "correct"}, result) -} - -func TestCanSupportStructWithSlicingExpression(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", B: []scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("B[:].Foo", data) - assert.Nil(err) - assert.Equal([]interface{}{"f1", "correct"}, result) -} - -func TestCanSupportStructWithFilterProjection(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", B: []scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("B[? `true` ].Foo", data) - assert.Nil(err) - assert.Equal([]interface{}{"f1", "correct"}, result) -} - -func TestCanSupportStructWithSlice(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", B: []scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("B[-1].Foo", data) - assert.Nil(err) - assert.Equal("correct", result) -} - -func TestCanSupportStructWithOrExpressions(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", C: nil} - result, err := Search("C || A", data) - assert.Nil(err) - assert.Equal("foo", result) -} - -func TestCanSupportStructWithSlicePointer(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", C: []*scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("C[-1].Foo", data) - assert.Nil(err) - assert.Equal("correct", result) -} - -func TestWillAutomaticallyCapitalizeFieldNames(t *testing.T) { - assert := assert.New(t) - s := scalars{Foo: "one", Bar: "bar"} - // Note that there's a lower cased "foo" instead of "Foo", - // but it should still correspond to the Foo field in the - // scalars struct - result, err := Search("foo", &s) - assert.Nil(err) - assert.Equal("one", result) -} - -func TestCanSupportStructWithSliceLowerCased(t *testing.T) { - assert := assert.New(t) - data := sliceType{A: "foo", B: []scalars{{"f1", "b1"}, {"correct", "b2"}}} - result, err := Search("b[-1].foo", data) - assert.Nil(err) - assert.Equal("correct", result) -} - -func TestCanSupportStructWithNestedPointers(t *testing.T) { - assert := assert.New(t) - data := struct{ A *struct{ B int } }{} - result, err := Search("A.B", data) - assert.Nil(err) - assert.Nil(result) -} - -func TestCanSupportFlattenNestedSlice(t *testing.T) { - assert := assert.New(t) - data := nestedSlice{A: []sliceType{ - {B: []scalars{{Foo: "f1a"}, {Foo: "f1b"}}}, - {B: []scalars{{Foo: "f2a"}, {Foo: "f2b"}}}, - }} - result, err := Search("A[].B[].Foo", data) - assert.Nil(err) - assert.Equal([]interface{}{"f1a", "f1b", "f2a", "f2b"}, result) -} - -func TestCanSupportFlattenNestedEmptySlice(t *testing.T) { - assert := assert.New(t) - data := nestedSlice{A: []sliceType{ - {}, {B: []scalars{{Foo: "a"}}}, - }} - result, err := Search("A[].B[].Foo", data) - assert.Nil(err) - assert.Equal([]interface{}{"a"}, result) -} - -func TestCanSupportProjectionsWithStructs(t *testing.T) { - assert := assert.New(t) - data := nestedSlice{A: []sliceType{ - {A: "first"}, {A: "second"}, {A: "third"}, - }} - result, err := Search("A[*].A", data) - assert.Nil(err) - assert.Equal([]interface{}{"first", "second", "third"}, result) -} - -func TestCanSupportSliceOfStructsWithFunctions(t *testing.T) { - assert := assert.New(t) - data := []scalars{scalars{"a1", "b1"}, scalars{"a2", "b2"}} - result, err := Search("length(@)", data) - assert.Nil(err) - assert.Equal(result.(float64), 2.0) -} - -func BenchmarkInterpretSingleFieldStruct(b *testing.B) { - intr := newInterpreter() - parser := NewParser() - ast, _ := parser.Parse("fooasdfasdfasdfasdf") - data := benchmarkStruct{"foobarbazqux"} - for i := 0; i < b.N; i++ { - intr.Execute(ast, &data) - } -} - -func BenchmarkInterpretNestedStruct(b *testing.B) { - intr := newInterpreter() - parser := NewParser() - ast, _ := parser.Parse("fooasdfasdfasdfasdf.fooasdfasdfasdfasdf.fooasdfasdfasdfasdf.fooasdfasdfasdfasdf") - data := benchmarkNested{ - nestedA{ - nestedB{ - nestedC{"foobarbazqux"}, - }, - }, - } - for i := 0; i < b.N; i++ { - intr.Execute(ast, &data) - } -} - -func BenchmarkInterpretNestedMaps(b *testing.B) { - jsonData := []byte(`{"fooasdfasdfasdfasdf": {"fooasdfasdfasdfasdf": {"fooasdfasdfasdfasdf": {"fooasdfasdfasdfasdf": "foobarbazqux"}}}}`) - var data interface{} - json.Unmarshal(jsonData, &data) - - intr := newInterpreter() - parser := NewParser() - ast, _ := parser.Parse("fooasdfasdfasdfasdf.fooasdfasdfasdfasdf.fooasdfasdfasdfasdf.fooasdfasdfasdfasdf") - for i := 0; i < b.N; i++ { - intr.Execute(ast, data) - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/lexer_test.go b/vendor/github.com/jmespath/go-jmespath/lexer_test.go deleted file mode 100644 index d13a042d..00000000 --- a/vendor/github.com/jmespath/go-jmespath/lexer_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package jmespath - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -var lexingTests = []struct { - expression string - expected []token -}{ - {"*", []token{{tStar, "*", 0, 1}}}, - {".", []token{{tDot, ".", 0, 1}}}, - {"[?", []token{{tFilter, "[?", 0, 2}}}, - {"[]", []token{{tFlatten, "[]", 0, 2}}}, - {"(", []token{{tLparen, "(", 0, 1}}}, - {")", []token{{tRparen, ")", 0, 1}}}, - {"[", []token{{tLbracket, "[", 0, 1}}}, - {"]", []token{{tRbracket, "]", 0, 1}}}, - {"{", []token{{tLbrace, "{", 0, 1}}}, - {"}", []token{{tRbrace, "}", 0, 1}}}, - {"||", []token{{tOr, "||", 0, 2}}}, - {"|", []token{{tPipe, "|", 0, 1}}}, - {"29", []token{{tNumber, "29", 0, 2}}}, - {"2", []token{{tNumber, "2", 0, 1}}}, - {"0", []token{{tNumber, "0", 0, 1}}}, - {"-20", []token{{tNumber, "-20", 0, 3}}}, - {"foo", []token{{tUnquotedIdentifier, "foo", 0, 3}}}, - {`"bar"`, []token{{tQuotedIdentifier, "bar", 0, 3}}}, - // Escaping the delimiter - {`"bar\"baz"`, []token{{tQuotedIdentifier, `bar"baz`, 0, 7}}}, - {",", []token{{tComma, ",", 0, 1}}}, - {":", []token{{tColon, ":", 0, 1}}}, - {"<", []token{{tLT, "<", 0, 1}}}, - {"<=", []token{{tLTE, "<=", 0, 2}}}, - {">", []token{{tGT, ">", 0, 1}}}, - {">=", []token{{tGTE, ">=", 0, 2}}}, - {"==", []token{{tEQ, "==", 0, 2}}}, - {"!=", []token{{tNE, "!=", 0, 2}}}, - {"`[0, 1, 2]`", []token{{tJSONLiteral, "[0, 1, 2]", 1, 9}}}, - {"'foo'", []token{{tStringLiteral, "foo", 1, 3}}}, - {"'a'", []token{{tStringLiteral, "a", 1, 1}}}, - {`'foo\'bar'`, []token{{tStringLiteral, "foo'bar", 1, 7}}}, - {"@", []token{{tCurrent, "@", 0, 1}}}, - {"&", []token{{tExpref, "&", 0, 1}}}, - // Quoted identifier unicode escape sequences - {`"\u2713"`, []token{{tQuotedIdentifier, "✓", 0, 3}}}, - {`"\\"`, []token{{tQuotedIdentifier, `\`, 0, 1}}}, - {"`\"foo\"`", []token{{tJSONLiteral, "\"foo\"", 1, 5}}}, - // Combinations of tokens. - {"foo.bar", []token{ - {tUnquotedIdentifier, "foo", 0, 3}, - {tDot, ".", 3, 1}, - {tUnquotedIdentifier, "bar", 4, 3}, - }}, - {"foo[0]", []token{ - {tUnquotedIdentifier, "foo", 0, 3}, - {tLbracket, "[", 3, 1}, - {tNumber, "0", 4, 1}, - {tRbracket, "]", 5, 1}, - }}, - {"foo[?a gopher.go - package main - - import ( - "fmt" - "github.com/namsral/flag" - ) - - func main() { - var age int - flag.IntVar(&age, "age", 0, "age of gopher") - flag.Parse() - fmt.Print("age:", age) - } -$ go run gopher.go -age 1 -age: 1 -``` - -Same code but using an environment variable: - -```go -$ export AGE=2 -$ go run gopher.go -age: 2 -``` - - -Same code but using a configuration file: - -```go -$ cat > gopher.conf -age 3 - -$ go run gopher.go -config gopher.conf -age: 3 -``` - -The following table shows how flags are translated to environment variables and configuration files: - -| Type | Flag | Environment | File | -| ------ | :------------ |:------------ |:------------ | -| int | -age 2 | AGE=2 | age 2 | -| bool | -female | FEMALE=true | female true | -| float | -length 175.5 | LENGTH=175.5 | length 175.5 | -| string | -name Gloria | NAME=Gloria | name Gloria | - -This package is a port of Go's [flag][] package from the standard library with the addition of two functions `ParseEnv` and `ParseFile`. - -[flag]: http://golang.org/src/pkg/flag - - -Goals ------ - -- Compatability with the original `flag` package -- Support the [twelve-factor app methodology][] -- Uniform user experience between the three input methods - - -Why? ---- - -Why not use one of the many INI, JSON or YAML parsers? - -I find it best practice to have simple configuration options to control the behaviour of an applications when it starts up. Use basic types like ints, floats and strings for configuration options and store more complex data structures in the "datastore" layer. - - -Usage ---- - -It's intended for projects which require a simple configuration made available through command-line flags, configuration files and shell environments. It's similar to the original `flag` package. - -Example: - -```go -import "github.com/namsral/flag" - -flag.String(flag.DefaultConfigFlagname, "", "path to config file") -flag.Int("age", 24, "help message for age") - -flag.Parse() -``` - -Order of precedence: - -1. Command line options -2. Environment variables -3. Configuration file -4. Default values - - -#### Parsing Configuration Files - -Create a configuration file: - -```go -$ cat > ./gopher.conf -# empty newlines and lines beginning with a "#" character are ignored. -name bob - -# keys and values can also be separated by the "=" character -age=20 - -# booleans can be empty, set with 0, 1, true, false, etc -hacker -``` - -Add a "config" flag: - -```go -flag.String(flag.DefaultConfigFlagname, "", "path to config file") -``` - -Run the command: - -```go -$ go run ./gopher.go -config ./gopher.conf -``` - -The default flag name for the configuration file is "config" and can be changed -by setting `flag.DefaultConfigFlagname`: - -```go -flag.DefaultConfigFlagname = "conf" -flag.Parse() -``` - -#### Parsing Environment Variables - -Environment variables are parsed 1-on-1 with defined flags: - -```go -$ export AGE=44 -$ go run ./gopher.go -age=44 -``` - - -You can also parse prefixed environment variables by setting a prefix name when creating a new empty flag set: - -```go -fs := flag.NewFlagSetWithEnvPrefix(os.Args[0], "GO", 0) -fs.Int("age", 24, "help message for age") -fs.Parse(os.Args[1:]) -... -$ go export GO_AGE=33 -$ go run ./gopher.go -age=33 -``` - - -For more examples see the [examples][] directory in the project repository. - -[examples]: https://github.com/namsral/flag/tree/master/examples - -That's it. - - -License ---- - - -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/namsral/flag/example_test.go b/vendor/github.com/namsral/flag/example_test.go deleted file mode 100644 index 04a0d20e..00000000 --- a/vendor/github.com/namsral/flag/example_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// These examples demonstrate more intricate uses of the flag package. -package flag_test - -import ( - "errors" - "flag" - "fmt" - "strings" - "time" -) - -// Example 1: A single string flag called "species" with default value "gopher". -var species = flag.String("species", "gopher", "the species we are studying") - -// Example 2: Two flags sharing a variable, so we can have a shorthand. -// The order of initialization is undefined, so make sure both use the -// same default value. They must be set up with an init function. -var gopherType string - -func init() { - const ( - defaultGopher = "pocket" - usage = "the variety of gopher" - ) - flag.StringVar(&gopherType, "gopher_type", defaultGopher, usage) - flag.StringVar(&gopherType, "g", defaultGopher, usage+" (shorthand)") -} - -// Example 3: A user-defined flag type, a slice of durations. -type interval []time.Duration - -// String is the method to format the flag's value, part of the flag.Value interface. -// The String method's output will be used in diagnostics. -func (i *interval) String() string { - return fmt.Sprint(*i) -} - -// Set is the method to set the flag value, part of the flag.Value interface. -// Set's argument is a string to be parsed to set the flag. -// It's a comma-separated list, so we split it. -func (i *interval) Set(value string) error { - // If we wanted to allow the flag to be set multiple times, - // accumulating values, we would delete this if statement. - // That would permit usages such as - // -deltaT 10s -deltaT 15s - // and other combinations. - if len(*i) > 0 { - return errors.New("interval flag already set") - } - for _, dt := range strings.Split(value, ",") { - duration, err := time.ParseDuration(dt) - if err != nil { - return err - } - *i = append(*i, duration) - } - return nil -} - -// Define a flag to accumulate durations. Because it has a special type, -// we need to use the Var function and therefore create the flag during -// init. - -var intervalFlag interval - -func init() { - // Tie the command-line flag to the intervalFlag variable and - // set a usage message. - flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events") -} - -func Example() { - // All the interesting pieces are with the variables declared above, but - // to enable the flag package to see the flags defined there, one must - // execute, typically at the start of main (not init!): - // flag.Parse() - // We don't run it here because this is not a main function and - // the testing suite has already parsed the flags. -} diff --git a/vendor/github.com/namsral/flag/export_test.go b/vendor/github.com/namsral/flag/export_test.go deleted file mode 100644 index 12d3dc76..00000000 --- a/vendor/github.com/namsral/flag/export_test.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flag - -import "os" - -// Additional routines compiled into the package only during testing. - -// ResetForTesting clears all flag state and sets the usage function as directed. -// After calling ResetForTesting, parse errors in flag handling will not -// exit the program. -func ResetForTesting(usage func()) { - CommandLine = NewFlagSet(os.Args[0], ContinueOnError) - Usage = usage -} diff --git a/vendor/github.com/namsral/flag/extras.go b/vendor/github.com/namsral/flag/extras.go index f9378995..ea7b9ad1 100644 --- a/vendor/github.com/namsral/flag/extras.go +++ b/vendor/github.com/namsral/flag/extras.go @@ -26,7 +26,7 @@ func (f *FlagSet) ParseEnv(environ []string) error { if i < 1 { continue } - env[s[0:i]] = s[i+1 : len(s)] + env[s[0:i]] = s[i+1:] } for _, flag := range m { diff --git a/vendor/github.com/namsral/flag/extras_test.go b/vendor/github.com/namsral/flag/extras_test.go deleted file mode 100644 index 8c378eda..00000000 --- a/vendor/github.com/namsral/flag/extras_test.go +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flag_test - -import ( - "os" - "syscall" - "testing" - "time" - - . "github.com/namsral/flag" -) - -// Test parsing a environment variables -func TestParseEnv(t *testing.T) { - - syscall.Setenv("BOOL", "") - syscall.Setenv("BOOL2", "true") - syscall.Setenv("INT", "22") - syscall.Setenv("INT64", "0x23") - syscall.Setenv("UINT", "24") - syscall.Setenv("UINT64", "25") - syscall.Setenv("STRING", "hello") - syscall.Setenv("FLOAT64", "2718e28") - syscall.Setenv("DURATION", "2m") - - f := NewFlagSet(os.Args[0], ContinueOnError) - - boolFlag := f.Bool("bool", false, "bool value") - bool2Flag := f.Bool("bool2", false, "bool2 value") - intFlag := f.Int("int", 0, "int value") - int64Flag := f.Int64("int64", 0, "int64 value") - uintFlag := f.Uint("uint", 0, "uint value") - uint64Flag := f.Uint64("uint64", 0, "uint64 value") - stringFlag := f.String("string", "0", "string value") - float64Flag := f.Float64("float64", 0, "float64 value") - durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value") - - err := f.ParseEnv(os.Environ()) - if err != nil { - t.Fatal("expected no error; got ", err) - } - if *boolFlag != true { - t.Error("bool flag should be true, is ", *boolFlag) - } - if *bool2Flag != true { - t.Error("bool2 flag should be true, is ", *bool2Flag) - } - if *intFlag != 22 { - t.Error("int flag should be 22, is ", *intFlag) - } - if *int64Flag != 0x23 { - t.Error("int64 flag should be 0x23, is ", *int64Flag) - } - if *uintFlag != 24 { - t.Error("uint flag should be 24, is ", *uintFlag) - } - if *uint64Flag != 25 { - t.Error("uint64 flag should be 25, is ", *uint64Flag) - } - if *stringFlag != "hello" { - t.Error("string flag should be `hello`, is ", *stringFlag) - } - if *float64Flag != 2718e28 { - t.Error("float64 flag should be 2718e28, is ", *float64Flag) - } - if *durationFlag != 2*time.Minute { - t.Error("duration flag should be 2m, is ", *durationFlag) - } -} - -// Test parsing a configuration file -func TestParseFile(t *testing.T) { - - f := NewFlagSet(os.Args[0], ContinueOnError) - - boolFlag := f.Bool("bool", false, "bool value") - bool2Flag := f.Bool("bool2", false, "bool2 value") - intFlag := f.Int("int", 0, "int value") - int64Flag := f.Int64("int64", 0, "int64 value") - uintFlag := f.Uint("uint", 0, "uint value") - uint64Flag := f.Uint64("uint64", 0, "uint64 value") - stringFlag := f.String("string", "0", "string value") - float64Flag := f.Float64("float64", 0, "float64 value") - durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value") - - err := f.ParseFile("./testdata/test.conf") - if err != nil { - t.Fatal("expected no error; got ", err) - } - if *boolFlag != true { - t.Error("bool flag should be true, is ", *boolFlag) - } - if *bool2Flag != true { - t.Error("bool2 flag should be true, is ", *bool2Flag) - } - if *intFlag != 22 { - t.Error("int flag should be 22, is ", *intFlag) - } - if *int64Flag != 0x23 { - t.Error("int64 flag should be 0x23, is ", *int64Flag) - } - if *uintFlag != 24 { - t.Error("uint flag should be 24, is ", *uintFlag) - } - if *uint64Flag != 25 { - t.Error("uint64 flag should be 25, is ", *uint64Flag) - } - if *stringFlag != "hello" { - t.Error("string flag should be `hello`, is ", *stringFlag) - } - if *float64Flag != 2718e28 { - t.Error("float64 flag should be 2718e28, is ", *float64Flag) - } - if *durationFlag != 2*time.Minute { - t.Error("duration flag should be 2m, is ", *durationFlag) - } -} - -func TestParseFileUnknownFlag(t *testing.T) { - f := NewFlagSet("test", ContinueOnError) - if err := f.ParseFile("./testdata/bad_test.conf"); err == nil { - t.Error("parse did not fail for unknown flag; ", err) - } -} - -func TestDefaultConfigFlagname(t *testing.T) { - f := NewFlagSet("test", ContinueOnError) - - f.Bool("bool", false, "bool value") - f.Bool("bool2", false, "bool2 value") - f.Int("int", 0, "int value") - f.Int64("int64", 0, "int64 value") - f.Uint("uint", 0, "uint value") - f.Uint64("uint64", 0, "uint64 value") - stringFlag := f.String("string", "0", "string value") - f.Float64("float64", 0, "float64 value") - f.Duration("duration", 5*time.Second, "time.Duration value") - - f.String(DefaultConfigFlagname, "./testdata/test.conf", "config path") - - if err := os.Unsetenv("STRING"); err != nil { - t.Error(err) - } - - if err := f.Parse([]string{}); err != nil { - t.Error("parse failed; ", err) - } - - if *stringFlag != "hello" { - t.Error("string flag should be `hello`, is", *stringFlag) - } -} - -func TestDefaultConfigFlagnameMissingFile(t *testing.T) { - f := NewFlagSet("test", ContinueOnError) - f.String(DefaultConfigFlagname, "./testdata/missing", "config path") - - if err := os.Unsetenv("STRING"); err != nil { - t.Error(err) - } - if err := f.Parse([]string{}); err == nil { - t.Error("expected error of missing config file, got nil") - } -} - -func TestFlagSetParseErrors(t *testing.T) { - fs := NewFlagSet("test", ContinueOnError) - fs.Int("int", 0, "int value") - - args := []string{"-int", "bad"} - expected := `invalid value "bad" for flag -int: strconv.ParseInt: parsing "bad": invalid syntax` - if err := fs.Parse(args); err == nil || err.Error() != expected { - t.Errorf("expected error %q parsing from args, got: %v", expected, err) - } - - if err := os.Setenv("INT", "bad"); err != nil { - t.Fatalf("error setting env: %s", err.Error()) - } - expected = `invalid value "bad" for environment variable int: strconv.ParseInt: parsing "bad": invalid syntax` - if err := fs.Parse([]string{}); err == nil || err.Error() != expected { - t.Errorf("expected error %q parsing from env, got: %v", expected, err) - } - if err := os.Unsetenv("INT"); err != nil { - t.Fatalf("error unsetting env: %s", err.Error()) - } - - fs.String("config", "", "config filename") - args = []string{"-config", "testdata/bad_test.conf"} - expected = `invalid value "bad" for configuration variable int: strconv.ParseInt: parsing "bad": invalid syntax` - if err := fs.Parse(args); err == nil || err.Error() != expected { - t.Errorf("expected error %q parsing from config, got: %v", expected, err) - } -} - -func TestTestingPackageFlags(t *testing.T) { - f := NewFlagSet("test", ContinueOnError) - if err := f.Parse([]string{"-test.v", "-test.count", "1"}); err != nil { - t.Error(err) - } -} diff --git a/vendor/github.com/namsral/flag/flag_test.go b/vendor/github.com/namsral/flag/flag_test.go deleted file mode 100644 index 65ad4e92..00000000 --- a/vendor/github.com/namsral/flag/flag_test.go +++ /dev/null @@ -1,418 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flag_test - -import ( - "bytes" - "fmt" - "os" - "sort" - "strings" - "testing" - "time" - - . "github.com/namsral/flag" -) - -func boolString(s string) string { - if s == "0" { - return "false" - } - return "true" -} - -func TestEverything(t *testing.T) { - ResetForTesting(nil) - Bool("test_bool", false, "bool value") - Int("test_int", 0, "int value") - Int64("test_int64", 0, "int64 value") - Uint("test_uint", 0, "uint value") - Uint64("test_uint64", 0, "uint64 value") - String("test_string", "0", "string value") - Float64("test_float64", 0, "float64 value") - Duration("test_duration", 0, "time.Duration value") - - m := make(map[string]*Flag) - desired := "0" - visitor := func(f *Flag) { - if len(f.Name) > 5 && f.Name[0:5] == "test_" { - m[f.Name] = f - ok := false - switch { - case f.Value.String() == desired: - ok = true - case f.Name == "test_bool" && f.Value.String() == boolString(desired): - ok = true - case f.Name == "test_duration" && f.Value.String() == desired+"s": - ok = true - } - if !ok { - t.Error("Visit: bad value", f.Value.String(), "for", f.Name) - } - } - } - VisitAll(visitor) - if len(m) != 8 { - t.Error("VisitAll misses some flags") - for k, v := range m { - t.Log(k, *v) - } - } - m = make(map[string]*Flag) - Visit(visitor) - if len(m) != 0 { - t.Errorf("Visit sees unset flags") - for k, v := range m { - t.Log(k, *v) - } - } - // Now set all flags - Set("test_bool", "true") - Set("test_int", "1") - Set("test_int64", "1") - Set("test_uint", "1") - Set("test_uint64", "1") - Set("test_string", "1") - Set("test_float64", "1") - Set("test_duration", "1s") - desired = "1" - Visit(visitor) - if len(m) != 8 { - t.Error("Visit fails after set") - for k, v := range m { - t.Log(k, *v) - } - } - // Now test they're visited in sort order. - var flagNames []string - Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) }) - if !sort.StringsAreSorted(flagNames) { - t.Errorf("flag names not sorted: %v", flagNames) - } -} - -func TestGet(t *testing.T) { - ResetForTesting(nil) - Bool("test_bool", true, "bool value") - Int("test_int", 1, "int value") - Int64("test_int64", 2, "int64 value") - Uint("test_uint", 3, "uint value") - Uint64("test_uint64", 4, "uint64 value") - String("test_string", "5", "string value") - Float64("test_float64", 6, "float64 value") - Duration("test_duration", 7, "time.Duration value") - - visitor := func(f *Flag) { - if len(f.Name) > 5 && f.Name[0:5] == "test_" { - g, ok := f.Value.(Getter) - if !ok { - t.Errorf("Visit: value does not satisfy Getter: %T", f.Value) - return - } - switch f.Name { - case "test_bool": - ok = g.Get() == true - case "test_int": - ok = g.Get() == int(1) - case "test_int64": - ok = g.Get() == int64(2) - case "test_uint": - ok = g.Get() == uint(3) - case "test_uint64": - ok = g.Get() == uint64(4) - case "test_string": - ok = g.Get() == "5" - case "test_float64": - ok = g.Get() == float64(6) - case "test_duration": - ok = g.Get() == time.Duration(7) - } - if !ok { - t.Errorf("Visit: bad value %T(%v) for %s", g.Get(), g.Get(), f.Name) - } - } - } - VisitAll(visitor) -} - -func TestUsage(t *testing.T) { - called := false - ResetForTesting(func() { called = true }) - if CommandLine.Parse([]string{"-x"}) == nil { - t.Error("parse did not fail for unknown flag") - } - if !called { - t.Error("did not call Usage for unknown flag") - } -} - -func testParse(f *FlagSet, t *testing.T) { - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - boolFlag := f.Bool("bool", false, "bool value") - bool2Flag := f.Bool("bool2", false, "bool2 value") - intFlag := f.Int("int", 0, "int value") - int64Flag := f.Int64("int64", 0, "int64 value") - uintFlag := f.Uint("uint", 0, "uint value") - uint64Flag := f.Uint64("uint64", 0, "uint64 value") - stringFlag := f.String("string", "0", "string value") - float64Flag := f.Float64("float64", 0, "float64 value") - durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value") - extra := "one-extra-argument" - args := []string{ - "-bool", - "-bool2=true", - "--int", "22", - "--int64", "0x23", - "-uint", "24", - "--uint64", "25", - "-string", "hello", - "-float64", "2718e28", - "-duration", "2m", - extra, - } - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolFlag != true { - t.Error("bool flag should be true, is ", *boolFlag) - } - if *bool2Flag != true { - t.Error("bool2 flag should be true, is ", *bool2Flag) - } - if *intFlag != 22 { - t.Error("int flag should be 22, is ", *intFlag) - } - if *int64Flag != 0x23 { - t.Error("int64 flag should be 0x23, is ", *int64Flag) - } - if *uintFlag != 24 { - t.Error("uint flag should be 24, is ", *uintFlag) - } - if *uint64Flag != 25 { - t.Error("uint64 flag should be 25, is ", *uint64Flag) - } - if *stringFlag != "hello" { - t.Error("string flag should be `hello`, is ", *stringFlag) - } - if *float64Flag != 2718e28 { - t.Error("float64 flag should be 2718e28, is ", *float64Flag) - } - if *durationFlag != 2*time.Minute { - t.Error("duration flag should be 2m, is ", *durationFlag) - } - if len(f.Args()) != 1 { - t.Error("expected one argument, got", len(f.Args())) - } else if f.Args()[0] != extra { - t.Errorf("expected argument %q got %q", extra, f.Args()[0]) - } -} - -func TestParse(t *testing.T) { - ResetForTesting(func() { t.Error("bad parse") }) - testParse(CommandLine, t) -} - -func TestFlagSetParse(t *testing.T) { - testParse(NewFlagSet("test", ContinueOnError), t) -} - -// Declare a user-defined flag type. -type flagVar []string - -func (f *flagVar) String() string { - return fmt.Sprint([]string(*f)) -} - -func (f *flagVar) Set(value string) error { - *f = append(*f, value) - return nil -} - -func TestUserDefined(t *testing.T) { - var flags FlagSet - flags.Init("test", ContinueOnError) - var v flagVar - flags.Var(&v, "v", "usage") - if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil { - t.Error(err) - } - if len(v) != 3 { - t.Fatal("expected 3 args; got ", len(v)) - } - expect := "[1 2 3]" - if v.String() != expect { - t.Errorf("expected value %q got %q", expect, v.String()) - } -} - -func TestUserDefinedForCommandLine(t *testing.T) { - const help = "HELP" - var result string - ResetForTesting(func() { result = help }) - Usage() - if result != help { - t.Fatalf("got %q; expected %q", result, help) - } -} - -// Declare a user-defined boolean flag type. -type boolFlagVar struct { - count int -} - -func (b *boolFlagVar) String() string { - return fmt.Sprintf("%d", b.count) -} - -func (b *boolFlagVar) Set(value string) error { - if value == "true" { - b.count++ - } - return nil -} - -func (b *boolFlagVar) IsBoolFlag() bool { - return b.count < 4 -} - -func TestUserDefinedBool(t *testing.T) { - var flags FlagSet - flags.Init("test", ContinueOnError) - var b boolFlagVar - var err error - flags.Var(&b, "b", "usage") - if err = flags.Parse([]string{"-b", "-b", "-b", "-b=true", "-b=false", "-b", "barg", "-b"}); err != nil { - if b.count < 4 { - t.Error(err) - } - } - - if b.count != 4 { - t.Errorf("want: %d; got: %d", 4, b.count) - } - - if err == nil { - t.Error("expected error; got none") - } -} - -func TestSetOutput(t *testing.T) { - var flags FlagSet - var buf bytes.Buffer - flags.SetOutput(&buf) - flags.Init("test", ContinueOnError) - flags.Parse([]string{"-unknown"}) - if out := buf.String(); !strings.Contains(out, "-unknown") { - t.Logf("expected output mentioning unknown; got %q", out) - } -} - -// This tests that one can reset the flags. This still works but not well, and is -// superseded by FlagSet. -func TestChangingArgs(t *testing.T) { - ResetForTesting(func() { t.Fatal("bad parse") }) - oldArgs := os.Args - defer func() { os.Args = oldArgs }() - os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"} - before := Bool("before", false, "") - if err := CommandLine.Parse(os.Args[1:]); err != nil { - t.Fatal(err) - } - cmd := Arg(0) - os.Args = Args() - after := Bool("after", false, "") - Parse() - args := Args() - - if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" { - t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args) - } -} - -// Test that -help invokes the usage message and returns ErrHelp. -func TestHelp(t *testing.T) { - var helpCalled = false - fs := NewFlagSet("help test", ContinueOnError) - fs.Usage = func() { helpCalled = true } - var flag bool - fs.BoolVar(&flag, "flag", false, "regular flag") - // Regular flag invocation should work - err := fs.Parse([]string{"-flag=true"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - if !flag { - t.Error("flag was not set by -flag") - } - if helpCalled { - t.Error("help called for regular flag") - helpCalled = false // reset for next test - } - // Help flag should work as expected. - err = fs.Parse([]string{"-help"}) - if err == nil { - t.Fatal("error expected") - } - if err != ErrHelp { - t.Fatal("expected ErrHelp; got ", err) - } - if !helpCalled { - t.Fatal("help was not called") - } - // If we define a help flag, that should override. - var help bool - fs.BoolVar(&help, "help", false, "help flag") - helpCalled = false - err = fs.Parse([]string{"-help"}) - if err != nil { - t.Fatal("expected no error for defined -help; got ", err) - } - if helpCalled { - t.Fatal("help was called; should not have been for defined help flag") - } -} - -const defaultOutput = ` -A for bootstrapping, allow 'any' type - -Alongflagname - disable bounds checking - -C a boolean defaulting to true (default true) - -D path - set relative path for local imports - -F number - a non-zero number (default 2.7) - -G float - a float that defaults to zero - -N int - a non-zero int (default 27) - -Z int - an int that defaults to zero - -maxT timeout - set timeout for dial -` - -func TestPrintDefaults(t *testing.T) { - fs := NewFlagSet("print defaults test", ContinueOnError) - var buf bytes.Buffer - fs.SetOutput(&buf) - fs.Bool("A", false, "for bootstrapping, allow 'any' type") - fs.Bool("Alongflagname", false, "disable bounds checking") - fs.Bool("C", true, "a boolean defaulting to true") - fs.String("D", "", "set relative `path` for local imports") - fs.Float64("F", 2.7, "a non-zero `number`") - fs.Float64("G", 0, "a float that defaults to zero") - fs.Int("N", 27, "a non-zero int") - fs.Int("Z", 0, "an int that defaults to zero") - fs.Duration("maxT", 0, "set `timeout` for dial") - fs.PrintDefaults() - got := buf.String() - if got != defaultOutput { - t.Errorf("got %q want %q\n", got, defaultOutput) - } -} diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore deleted file mode 100644 index daf913b1..00000000 --- a/vendor/github.com/pkg/errors/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml deleted file mode 100644 index 588ceca1..00000000 --- a/vendor/github.com/pkg/errors/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: go -go_import_path: github.com/pkg/errors -go: - - 1.4.3 - - 1.5.4 - - 1.6.2 - - 1.7.1 - - tip - -script: - - go test -v ./... diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 273db3c9..00000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Contributing - -We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. - -Before proposing a change, please discuss your change by raising an issue. - -## Licence - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade..00000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/bench_test.go b/vendor/github.com/pkg/errors/bench_test.go deleted file mode 100644 index 0416a3cb..00000000 --- a/vendor/github.com/pkg/errors/bench_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// +build go1.7 - -package errors - -import ( - "fmt" - "testing" - - stderrors "errors" -) - -func noErrors(at, depth int) error { - if at >= depth { - return stderrors.New("no error") - } - return noErrors(at+1, depth) -} -func yesErrors(at, depth int) error { - if at >= depth { - return New("ye error") - } - return yesErrors(at+1, depth) -} - -func BenchmarkErrors(b *testing.B) { - var toperr error - type run struct { - stack int - std bool - } - runs := []run{ - {10, false}, - {10, true}, - {100, false}, - {100, true}, - {1000, false}, - {1000, true}, - } - for _, r := range runs { - part := "pkg/errors" - if r.std { - part = "errors" - } - name := fmt.Sprintf("%s-stack-%d", part, r.stack) - b.Run(name, func(b *testing.B) { - var err error - f := yesErrors - if r.std { - f = noErrors - } - b.ReportAllocs() - for i := 0; i < b.N; i++ { - err = f(0, r.stack) - } - b.StopTimer() - toperr = err - }) - } -} diff --git a/vendor/github.com/pkg/errors/errors_test.go b/vendor/github.com/pkg/errors/errors_test.go deleted file mode 100644 index 1d8c6355..00000000 --- a/vendor/github.com/pkg/errors/errors_test.go +++ /dev/null @@ -1,226 +0,0 @@ -package errors - -import ( - "errors" - "fmt" - "io" - "reflect" - "testing" -) - -func TestNew(t *testing.T) { - tests := []struct { - err string - want error - }{ - {"", fmt.Errorf("")}, - {"foo", fmt.Errorf("foo")}, - {"foo", New("foo")}, - {"string with format specifiers: %v", errors.New("string with format specifiers: %v")}, - } - - for _, tt := range tests { - got := New(tt.err) - if got.Error() != tt.want.Error() { - t.Errorf("New.Error(): got: %q, want %q", got, tt.want) - } - } -} - -func TestWrapNil(t *testing.T) { - got := Wrap(nil, "no error") - if got != nil { - t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWrap(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"}, - } - - for _, tt := range tests { - got := Wrap(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) - } - } -} - -type nilError struct{} - -func (nilError) Error() string { return "nil error" } - -func TestCause(t *testing.T) { - x := New("error") - tests := []struct { - err error - want error - }{{ - // nil error is nil - err: nil, - want: nil, - }, { - // explicit nil error is nil - err: (error)(nil), - want: nil, - }, { - // typed nil is nil - err: (*nilError)(nil), - want: (*nilError)(nil), - }, { - // uncaused error is unaffected - err: io.EOF, - want: io.EOF, - }, { - // caused error returns cause - err: Wrap(io.EOF, "ignored"), - want: io.EOF, - }, { - err: x, // return from errors.New - want: x, - }, { - WithMessage(nil, "whoops"), - nil, - }, { - WithMessage(io.EOF, "whoops"), - io.EOF, - }, { - WithStack(nil), - nil, - }, { - WithStack(io.EOF), - io.EOF, - }} - - for i, tt := range tests { - got := Cause(tt.err) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want) - } - } -} - -func TestWrapfNil(t *testing.T) { - got := Wrapf(nil, "no error") - if got != nil { - t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWrapf(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"}, - {Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"}, - } - - for _, tt := range tests { - got := Wrapf(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) - } - } -} - -func TestErrorf(t *testing.T) { - tests := []struct { - err error - want string - }{ - {Errorf("read error without format specifiers"), "read error without format specifiers"}, - {Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"}, - } - - for _, tt := range tests { - got := tt.err.Error() - if got != tt.want { - t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want) - } - } -} - -func TestWithStackNil(t *testing.T) { - got := WithStack(nil) - if got != nil { - t.Errorf("WithStack(nil): got %#v, expected nil", got) - } -} - -func TestWithStack(t *testing.T) { - tests := []struct { - err error - want string - }{ - {io.EOF, "EOF"}, - {WithStack(io.EOF), "EOF"}, - } - - for _, tt := range tests { - got := WithStack(tt.err).Error() - if got != tt.want { - t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want) - } - } -} - -func TestWithMessageNil(t *testing.T) { - got := WithMessage(nil, "no error") - if got != nil { - t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWithMessage(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"}, - } - - for _, tt := range tests { - got := WithMessage(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want) - } - } - -} - -// errors.New, etc values are not expected to be compared by value -// but the change in errors#27 made them incomparable. Assert that -// various kinds of errors have a functional equality operator, even -// if the result of that equality is always false. -func TestErrorEquality(t *testing.T) { - vals := []error{ - nil, - io.EOF, - errors.New("EOF"), - New("EOF"), - Errorf("EOF"), - Wrap(io.EOF, "EOF"), - Wrapf(io.EOF, "EOF%d", 2), - WithMessage(nil, "whoops"), - WithMessage(io.EOF, "whoops"), - WithStack(io.EOF), - WithStack(nil), - } - - for i := range vals { - for j := range vals { - _ = vals[i] == vals[j] // mustn't panic - } - } -} diff --git a/vendor/github.com/pkg/errors/example_test.go b/vendor/github.com/pkg/errors/example_test.go deleted file mode 100644 index c1fc13e3..00000000 --- a/vendor/github.com/pkg/errors/example_test.go +++ /dev/null @@ -1,205 +0,0 @@ -package errors_test - -import ( - "fmt" - - "github.com/pkg/errors" -) - -func ExampleNew() { - err := errors.New("whoops") - fmt.Println(err) - - // Output: whoops -} - -func ExampleNew_printf() { - err := errors.New("whoops") - fmt.Printf("%+v", err) - - // Example output: - // whoops - // github.com/pkg/errors_test.ExampleNew_printf - // /home/dfc/src/github.com/pkg/errors/example_test.go:17 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 -} - -func ExampleWithMessage() { - cause := errors.New("whoops") - err := errors.WithMessage(cause, "oh noes") - fmt.Println(err) - - // Output: oh noes: whoops -} - -func ExampleWithStack() { - cause := errors.New("whoops") - err := errors.WithStack(cause) - fmt.Println(err) - - // Output: whoops -} - -func ExampleWithStack_printf() { - cause := errors.New("whoops") - err := errors.WithStack(cause) - fmt.Printf("%+v", err) - - // Example Output: - // whoops - // github.com/pkg/errors_test.ExampleWithStack_printf - // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55 - // testing.runExample - // /usr/lib/go/src/testing/example.go:114 - // testing.RunExamples - // /usr/lib/go/src/testing/example.go:38 - // testing.(*M).Run - // /usr/lib/go/src/testing/testing.go:744 - // main.main - // github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /usr/lib/go/src/runtime/proc.go:183 - // runtime.goexit - // /usr/lib/go/src/runtime/asm_amd64.s:2086 - // github.com/pkg/errors_test.ExampleWithStack_printf - // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56 - // testing.runExample - // /usr/lib/go/src/testing/example.go:114 - // testing.RunExamples - // /usr/lib/go/src/testing/example.go:38 - // testing.(*M).Run - // /usr/lib/go/src/testing/testing.go:744 - // main.main - // github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /usr/lib/go/src/runtime/proc.go:183 - // runtime.goexit - // /usr/lib/go/src/runtime/asm_amd64.s:2086 -} - -func ExampleWrap() { - cause := errors.New("whoops") - err := errors.Wrap(cause, "oh noes") - fmt.Println(err) - - // Output: oh noes: whoops -} - -func fn() error { - e1 := errors.New("error") - e2 := errors.Wrap(e1, "inner") - e3 := errors.Wrap(e2, "middle") - return errors.Wrap(e3, "outer") -} - -func ExampleCause() { - err := fn() - fmt.Println(err) - fmt.Println(errors.Cause(err)) - - // Output: outer: middle: inner: error - // error -} - -func ExampleWrap_extended() { - err := fn() - fmt.Printf("%+v\n", err) - - // Example output: - // error - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:47 - // github.com/pkg/errors_test.ExampleCause_printf - // /home/dfc/src/github.com/pkg/errors/example_test.go:63 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:104 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer -} - -func ExampleWrapf() { - cause := errors.New("whoops") - err := errors.Wrapf(cause, "oh noes #%d", 2) - fmt.Println(err) - - // Output: oh noes #2: whoops -} - -func ExampleErrorf_extended() { - err := errors.Errorf("whoops: %s", "foo") - fmt.Printf("%+v", err) - - // Example output: - // whoops: foo - // github.com/pkg/errors_test.ExampleErrorf - // /home/dfc/src/github.com/pkg/errors/example_test.go:101 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:102 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 -} - -func Example_stackTrace() { - type stackTracer interface { - StackTrace() errors.StackTrace - } - - err, ok := errors.Cause(fn()).(stackTracer) - if !ok { - panic("oops, err does not implement stackTracer") - } - - st := err.StackTrace() - fmt.Printf("%+v", st[0:2]) // top two frames - - // Example output: - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:47 - // github.com/pkg/errors_test.Example_stackTrace - // /home/dfc/src/github.com/pkg/errors/example_test.go:127 -} - -func ExampleCause_printf() { - err := errors.Wrap(func() error { - return func() error { - return errors.Errorf("hello %s", fmt.Sprintf("world")) - }() - }(), "failed") - - fmt.Printf("%v", err) - - // Output: failed: hello world -} diff --git a/vendor/github.com/pkg/errors/format_test.go b/vendor/github.com/pkg/errors/format_test.go deleted file mode 100644 index 15fd7d89..00000000 --- a/vendor/github.com/pkg/errors/format_test.go +++ /dev/null @@ -1,535 +0,0 @@ -package errors - -import ( - "errors" - "fmt" - "io" - "regexp" - "strings" - "testing" -) - -func TestFormatNew(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - New("error"), - "%s", - "error", - }, { - New("error"), - "%v", - "error", - }, { - New("error"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatNew\n" + - "\t.+/github.com/pkg/errors/format_test.go:26", - }, { - New("error"), - "%q", - `"error"`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatErrorf(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Errorf("%s", "error"), - "%s", - "error", - }, { - Errorf("%s", "error"), - "%v", - "error", - }, { - Errorf("%s", "error"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatErrorf\n" + - "\t.+/github.com/pkg/errors/format_test.go:56", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWrap(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Wrap(New("error"), "error2"), - "%s", - "error2: error", - }, { - Wrap(New("error"), "error2"), - "%v", - "error2: error", - }, { - Wrap(New("error"), "error2"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:82", - }, { - Wrap(io.EOF, "error"), - "%s", - "error: EOF", - }, { - Wrap(io.EOF, "error"), - "%v", - "error: EOF", - }, { - Wrap(io.EOF, "error"), - "%+v", - "EOF\n" + - "error\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:96", - }, { - Wrap(Wrap(io.EOF, "error1"), "error2"), - "%+v", - "EOF\n" + - "error1\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:103\n", - }, { - Wrap(New("error with space"), "context"), - "%q", - `"context: error with space"`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWrapf(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Wrapf(io.EOF, "error%d", 2), - "%s", - "error2: EOF", - }, { - Wrapf(io.EOF, "error%d", 2), - "%v", - "error2: EOF", - }, { - Wrapf(io.EOF, "error%d", 2), - "%+v", - "EOF\n" + - "error2\n" + - "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:134", - }, { - Wrapf(New("error"), "error%d", 2), - "%s", - "error2: error", - }, { - Wrapf(New("error"), "error%d", 2), - "%v", - "error2: error", - }, { - Wrapf(New("error"), "error%d", 2), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:149", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWithStack(t *testing.T) { - tests := []struct { - error - format string - want []string - }{{ - WithStack(io.EOF), - "%s", - []string{"EOF"}, - }, { - WithStack(io.EOF), - "%v", - []string{"EOF"}, - }, { - WithStack(io.EOF), - "%+v", - []string{"EOF", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:175"}, - }, { - WithStack(New("error")), - "%s", - []string{"error"}, - }, { - WithStack(New("error")), - "%v", - []string{"error"}, - }, { - WithStack(New("error")), - "%+v", - []string{"error", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189"}, - }, { - WithStack(WithStack(io.EOF)), - "%+v", - []string{"EOF", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197"}, - }, { - WithStack(WithStack(Wrapf(io.EOF, "message"))), - "%+v", - []string{"EOF", - "message", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205"}, - }, { - WithStack(Errorf("error%d", 1)), - "%+v", - []string{"error1", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216"}, - }} - - for i, tt := range tests { - testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) - } -} - -func TestFormatWithMessage(t *testing.T) { - tests := []struct { - error - format string - want []string - }{{ - WithMessage(New("error"), "error2"), - "%s", - []string{"error2: error"}, - }, { - WithMessage(New("error"), "error2"), - "%v", - []string{"error2: error"}, - }, { - WithMessage(New("error"), "error2"), - "%+v", - []string{ - "error", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:244", - "error2"}, - }, { - WithMessage(io.EOF, "addition1"), - "%s", - []string{"addition1: EOF"}, - }, { - WithMessage(io.EOF, "addition1"), - "%v", - []string{"addition1: EOF"}, - }, { - WithMessage(io.EOF, "addition1"), - "%+v", - []string{"EOF", "addition1"}, - }, { - WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), - "%v", - []string{"addition2: addition1: EOF"}, - }, { - WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), - "%+v", - []string{"EOF", "addition1", "addition2"}, - }, { - Wrap(WithMessage(io.EOF, "error1"), "error2"), - "%+v", - []string{"EOF", "error1", "error2", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:272"}, - }, { - WithMessage(Errorf("error%d", 1), "error2"), - "%+v", - []string{"error1", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:278", - "error2"}, - }, { - WithMessage(WithStack(io.EOF), "error"), - "%+v", - []string{ - "EOF", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:285", - "error"}, - }, { - WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"), - "%+v", - []string{ - "EOF", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", - "inside-error", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", - "outside-error"}, - }} - - for i, tt := range tests { - testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) - } -} - -func TestFormatGeneric(t *testing.T) { - starts := []struct { - err error - want []string - }{ - {New("new-error"), []string{ - "new-error", - "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:315"}, - }, {Errorf("errorf-error"), []string{ - "errorf-error", - "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:319"}, - }, {errors.New("errors-new-error"), []string{ - "errors-new-error"}, - }, - } - - wrappers := []wrapper{ - { - func(err error) error { return WithMessage(err, "with-message") }, - []string{"with-message"}, - }, { - func(err error) error { return WithStack(err) }, - []string{ - "github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" + - ".+/github.com/pkg/errors/format_test.go:333", - }, - }, { - func(err error) error { return Wrap(err, "wrap-error") }, - []string{ - "wrap-error", - "github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" + - ".+/github.com/pkg/errors/format_test.go:339", - }, - }, { - func(err error) error { return Wrapf(err, "wrapf-error%d", 1) }, - []string{ - "wrapf-error1", - "github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" + - ".+/github.com/pkg/errors/format_test.go:346", - }, - }, - } - - for s := range starts { - err := starts[s].err - want := starts[s].want - testFormatCompleteCompare(t, s, err, "%+v", want, false) - testGenericRecursive(t, err, want, wrappers, 3) - } -} - -func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) { - got := fmt.Sprintf(format, arg) - gotLines := strings.SplitN(got, "\n", -1) - wantLines := strings.SplitN(want, "\n", -1) - - if len(wantLines) > len(gotLines) { - t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want) - return - } - - for i, w := range wantLines { - match, err := regexp.MatchString(w, gotLines[i]) - if err != nil { - t.Fatal(err) - } - if !match { - t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want) - } - } -} - -var stackLineR = regexp.MustCompile(`\.`) - -// parseBlocks parses input into a slice, where: -// - incase entry contains a newline, its a stacktrace -// - incase entry contains no newline, its a solo line. -// -// Detecting stack boundaries only works incase the WithStack-calls are -// to be found on the same line, thats why it is optionally here. -// -// Example use: -// -// for _, e := range blocks { -// if strings.ContainsAny(e, "\n") { -// // Match as stack -// } else { -// // Match as line -// } -// } -// -func parseBlocks(input string, detectStackboundaries bool) ([]string, error) { - var blocks []string - - stack := "" - wasStack := false - lines := map[string]bool{} // already found lines - - for _, l := range strings.Split(input, "\n") { - isStackLine := stackLineR.MatchString(l) - - switch { - case !isStackLine && wasStack: - blocks = append(blocks, stack, l) - stack = "" - lines = map[string]bool{} - case isStackLine: - if wasStack { - // Detecting two stacks after another, possible cause lines match in - // our tests due to WithStack(WithStack(io.EOF)) on same line. - if detectStackboundaries { - if lines[l] { - if len(stack) == 0 { - return nil, errors.New("len of block must not be zero here") - } - - blocks = append(blocks, stack) - stack = l - lines = map[string]bool{l: true} - continue - } - } - - stack = stack + "\n" + l - } else { - stack = l - } - lines[l] = true - case !isStackLine && !wasStack: - blocks = append(blocks, l) - default: - return nil, errors.New("must not happen") - } - - wasStack = isStackLine - } - - // Use up stack - if stack != "" { - blocks = append(blocks, stack) - } - return blocks, nil -} - -func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) { - gotStr := fmt.Sprintf(format, arg) - - got, err := parseBlocks(gotStr, detectStackBoundaries) - if err != nil { - t.Fatal(err) - } - - if len(got) != len(want) { - t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q", - n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr) - } - - for i := range got { - if strings.ContainsAny(want[i], "\n") { - // Match as stack - match, err := regexp.MatchString(want[i], got[i]) - if err != nil { - t.Fatal(err) - } - if !match { - t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n", - n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want)) - } - } else { - // Match as message - if got[i] != want[i] { - t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i]) - } - } - } -} - -type wrapper struct { - wrap func(err error) error - want []string -} - -func prettyBlocks(blocks []string, prefix ...string) string { - var out []string - - for _, b := range blocks { - out = append(out, fmt.Sprintf("%v", b)) - } - - return " " + strings.Join(out, "\n ") -} - -func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) { - if len(beforeWant) == 0 { - panic("beforeWant must not be empty") - } - for _, w := range list { - if len(w.want) == 0 { - panic("want must not be empty") - } - - err := w.wrap(beforeErr) - - // Copy required cause append(beforeWant, ..) modified beforeWant subtly. - beforeCopy := make([]string, len(beforeWant)) - copy(beforeCopy, beforeWant) - - beforeWant := beforeCopy - last := len(beforeWant) - 1 - var want []string - - // Merge two stacks behind each other. - if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") { - want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...) - } else { - want = append(beforeWant, w.want...) - } - - testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false) - if maxDepth > 0 { - testGenericRecursive(t, err, want, list, maxDepth-1) - } - } -} diff --git a/vendor/github.com/pkg/errors/stack_test.go b/vendor/github.com/pkg/errors/stack_test.go deleted file mode 100644 index 510c27a9..00000000 --- a/vendor/github.com/pkg/errors/stack_test.go +++ /dev/null @@ -1,292 +0,0 @@ -package errors - -import ( - "fmt" - "runtime" - "testing" -) - -var initpc, _, _, _ = runtime.Caller(0) - -func TestFrameLine(t *testing.T) { - var tests = []struct { - Frame - want int - }{{ - Frame(initpc), - 9, - }, { - func() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) - }(), - 20, - }, { - func() Frame { - var pc, _, _, _ = runtime.Caller(1) - return Frame(pc) - }(), - 28, - }, { - Frame(0), // invalid PC - 0, - }} - - for _, tt := range tests { - got := tt.Frame.line() - want := tt.want - if want != got { - t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got) - } - } -} - -type X struct{} - -func (x X) val() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) -} - -func (x *X) ptr() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) -} - -func TestFrameFormat(t *testing.T) { - var tests = []struct { - Frame - format string - want string - }{{ - Frame(initpc), - "%s", - "stack_test.go", - }, { - Frame(initpc), - "%+s", - "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go", - }, { - Frame(0), - "%s", - "unknown", - }, { - Frame(0), - "%+s", - "unknown", - }, { - Frame(initpc), - "%d", - "9", - }, { - Frame(0), - "%d", - "0", - }, { - Frame(initpc), - "%n", - "init", - }, { - func() Frame { - var x X - return x.ptr() - }(), - "%n", - `\(\*X\).ptr`, - }, { - func() Frame { - var x X - return x.val() - }(), - "%n", - "X.val", - }, { - Frame(0), - "%n", - "", - }, { - Frame(initpc), - "%v", - "stack_test.go:9", - }, { - Frame(initpc), - "%+v", - "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go:9", - }, { - Frame(0), - "%v", - "unknown:0", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.Frame, tt.format, tt.want) - } -} - -func TestFuncname(t *testing.T) { - tests := []struct { - name, want string - }{ - {"", ""}, - {"runtime.main", "main"}, - {"github.com/pkg/errors.funcname", "funcname"}, - {"funcname", "funcname"}, - {"io.copyBuffer", "copyBuffer"}, - {"main.(*R).Write", "(*R).Write"}, - } - - for _, tt := range tests { - got := funcname(tt.name) - want := tt.want - if got != want { - t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got) - } - } -} - -func TestTrimGOPATH(t *testing.T) { - var tests = []struct { - Frame - want string - }{{ - Frame(initpc), - "github.com/pkg/errors/stack_test.go", - }} - - for i, tt := range tests { - pc := tt.Frame.pc() - fn := runtime.FuncForPC(pc) - file, _ := fn.FileLine(pc) - got := trimGOPATH(fn.Name(), file) - testFormatRegexp(t, i, got, "%s", tt.want) - } -} - -func TestStackTrace(t *testing.T) { - tests := []struct { - err error - want []string - }{{ - New("ooh"), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:172", - }, - }, { - Wrap(New("ooh"), "ahh"), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New - }, - }, { - Cause(Wrap(New("ooh"), "ahh")), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New - }, - }, { - func() error { return New("ooh") }(), []string{ - `github.com/pkg/errors.(func·009|TestStackTrace.func1)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller - }, - }, { - Cause(func() error { - return func() error { - return Errorf("hello %s", fmt.Sprintf("world")) - }() - }()), []string{ - `github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf - `github.com/pkg/errors.(func·011|TestStackTrace.func2)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller - }, - }} - for i, tt := range tests { - x, ok := tt.err.(interface { - StackTrace() StackTrace - }) - if !ok { - t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err) - continue - } - st := x.StackTrace() - for j, want := range tt.want { - testFormatRegexp(t, i, st[j], "%+v", want) - } - } -} - -func stackTrace() StackTrace { - const depth = 8 - var pcs [depth]uintptr - n := runtime.Callers(1, pcs[:]) - var st stack = pcs[0:n] - return st.StackTrace() -} - -func TestStackTraceFormat(t *testing.T) { - tests := []struct { - StackTrace - format string - want string - }{{ - nil, - "%s", - `\[\]`, - }, { - nil, - "%v", - `\[\]`, - }, { - nil, - "%+v", - "", - }, { - nil, - "%#v", - `\[\]errors.Frame\(nil\)`, - }, { - make(StackTrace, 0), - "%s", - `\[\]`, - }, { - make(StackTrace, 0), - "%v", - `\[\]`, - }, { - make(StackTrace, 0), - "%+v", - "", - }, { - make(StackTrace, 0), - "%#v", - `\[\]errors.Frame{}`, - }, { - stackTrace()[:2], - "%s", - `\[stack_test.go stack_test.go\]`, - }, { - stackTrace()[:2], - "%v", - `\[stack_test.go:225 stack_test.go:272\]`, - }, { - stackTrace()[:2], - "%+v", - "\n" + - "github.com/pkg/errors.stackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:225\n" + - "github.com/pkg/errors.TestStackTraceFormat\n" + - "\t.+/github.com/pkg/errors/stack_test.go:276", - }, { - stackTrace()[:2], - "%#v", - `\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want) - } -}