Ejemplo n.º 1
0
func ExampleECR_BatchGetImage() {
	svc := ecr.New(session.New())

	params := &ecr.BatchGetImageInput{
		ImageIds: []*ecr.ImageIdentifier{ // Required
			{ // Required
				ImageDigest: aws.String("ImageDigest"),
				ImageTag:    aws.String("ImageTag"),
			},
			// More values...
		},
		RepositoryName: aws.String("RepositoryName"), // Required
		RegistryId:     aws.String("RegistryId"),
	}
	resp, err := svc.BatchGetImage(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Ejemplo n.º 2
0
func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) {
	sess := session.New()
	svc := NewOutputService1ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	buf := bytes.NewReader([]byte("{\"Str\": \"myname\", \"Num\": 123, \"FalseBool\": false, \"TrueBool\": true, \"Float\": 1.2, \"Double\": 1.3, \"Long\": 200, \"Char\": \"a\"}"))
	req, out := svc.OutputService1TestCaseOperation1Request(nil)
	req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}

	// set headers

	// unmarshal response
	jsonrpc.UnmarshalMeta(req)
	jsonrpc.Unmarshal(req)
	assert.NoError(t, req.Error)

	// assert response
	assert.NotNil(t, out) // ensure out variable is used
	assert.Equal(t, "a", *out.Char)
	assert.Equal(t, 1.3, *out.Double)
	assert.Equal(t, false, *out.FalseBool)
	assert.Equal(t, 1.2, *out.Float)
	assert.Equal(t, int64(200), *out.Long)
	assert.Equal(t, int64(123), *out.Num)
	assert.Equal(t, "myname", *out.Str)
	assert.Equal(t, true, *out.TrueBool)

}
Ejemplo n.º 3
0
func TestInputService4ProtocolTestNestedBlobsCase1(t *testing.T) {
	sess := session.New()
	svc := NewInputService4ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	input := &InputService4TestShapeInputService4TestCaseOperation1Input{
		ListParam: [][]byte{
			[]byte("foo"),
			[]byte("bar"),
		},
	}
	req, _ := svc.InputService4TestCaseOperation1Request(input)
	r := req.HTTPRequest

	// build request
	jsonrpc.Build(req)
	assert.NoError(t, req.Error)

	// assert body
	assert.NotNil(t, r.Body)
	body, _ := ioutil.ReadAll(r.Body)
	awstesting.AssertJSON(t, `{"ListParam":["Zm9v","YmFy"]}`, util.Trim(string(body)))

	// assert URL
	awstesting.AssertURL(t, "https://test/", r.URL.String())

	// assert headers
	assert.Equal(t, "application/x-amz-json-1.1", r.Header.Get("Content-Type"))
	assert.Equal(t, "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"))

}
Ejemplo n.º 4
0
func TestInputService5ProtocolTestRecursiveShapesCase3(t *testing.T) {
	sess := session.New()
	svc := NewInputService5ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	input := &InputService5TestShapeInputShape{
		RecursiveStruct: &InputService5TestShapeRecursiveStructType{
			RecursiveStruct: &InputService5TestShapeRecursiveStructType{
				RecursiveStruct: &InputService5TestShapeRecursiveStructType{
					RecursiveStruct: &InputService5TestShapeRecursiveStructType{
						NoRecurse: aws.String("foo"),
					},
				},
			},
		},
	}
	req, _ := svc.InputService5TestCaseOperation3Request(input)
	r := req.HTTPRequest

	// build request
	jsonrpc.Build(req)
	assert.NoError(t, req.Error)

	// assert body
	assert.NotNil(t, r.Body)
	body, _ := ioutil.ReadAll(r.Body)
	awstesting.AssertJSON(t, `{"RecursiveStruct":{"RecursiveStruct":{"RecursiveStruct":{"RecursiveStruct":{"NoRecurse":"foo"}}}}}`, util.Trim(string(body)))

	// assert URL
	awstesting.AssertURL(t, "https://test/", r.URL.String())

	// assert headers
	assert.Equal(t, "application/x-amz-json-1.1", r.Header.Get("Content-Type"))
	assert.Equal(t, "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"))

}
Ejemplo n.º 5
0
func TestInputService2ProtocolTestTimestampValuesCase1(t *testing.T) {
	sess := session.New()
	svc := NewInputService2ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	input := &InputService2TestShapeInputService2TestCaseOperation1Input{
		TimeArg: aws.Time(time.Unix(1422172800, 0)),
	}
	req, _ := svc.InputService2TestCaseOperation1Request(input)
	r := req.HTTPRequest

	// build request
	jsonrpc.Build(req)
	assert.NoError(t, req.Error)

	// assert body
	assert.NotNil(t, r.Body)
	body, _ := ioutil.ReadAll(r.Body)
	awstesting.AssertJSON(t, `{"TimeArg":1422172800}`, util.Trim(string(body)))

	// assert URL
	awstesting.AssertURL(t, "https://test/", r.URL.String())

	// assert headers
	assert.Equal(t, "application/x-amz-json-1.1", r.Header.Get("Content-Type"))
	assert.Equal(t, "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target"))

}
Ejemplo n.º 6
0
func TestOutputService4ProtocolTestListsCase2(t *testing.T) {
	sess := session.New()
	svc := NewOutputService4ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	buf := bytes.NewReader([]byte("{\"ListMember\": [\"a\", null], \"ListMemberMap\": [{}, null, null, {}], \"ListMemberStruct\": [{}, null, null, {}]}"))
	req, out := svc.OutputService4TestCaseOperation2Request(nil)
	req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}

	// set headers

	// unmarshal response
	jsonrpc.UnmarshalMeta(req)
	jsonrpc.Unmarshal(req)
	assert.NoError(t, req.Error)

	// assert response
	assert.NotNil(t, out) // ensure out variable is used
	assert.Equal(t, "a", *out.ListMember[0])
	assert.Nil(t, out.ListMember[1])
	assert.Nil(t, out.ListMemberMap[1])
	assert.Nil(t, out.ListMemberMap[2])
	assert.Nil(t, out.ListMemberStruct[1])
	assert.Nil(t, out.ListMemberStruct[2])

}
Ejemplo n.º 7
0
func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) {
	server := initTestServer("2014-12-16T01:51:37Z", false)
	defer server.Close()

	p := &ec2rolecreds.EC2RoleProvider{
		Client:       ec2metadata.New(session.New(), &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.")
}
Ejemplo n.º 8
0
func TestNewDefaultSession(t *testing.T) {
	s := session.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)
}
Ejemplo n.º 9
0
func TestMetadataAvailable(t *testing.T) {
	server := initTestServer(
		"/latest/meta-data/instance-id",
		"instance-id",
	)
	defer server.Close()
	c := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})

	available := c.Available()

	assert.True(t, available)
}
Ejemplo n.º 10
0
func TestEndpoint(t *testing.T) {
	c := ec2metadata.New(session.New())
	op := &request.Operation{
		Name:       "GetMetadata",
		HTTPMethod: "GET",
		HTTPPath:   path.Join("/", "meta-data", "testpath"),
	}

	req := c.NewRequest(op, nil, nil)
	assert.Equal(t, "http://169.254.169.254/latest", req.ClientInfo.Endpoint)
	assert.Equal(t, "http://169.254.169.254/latest/meta-data/testpath", req.HTTPRequest.URL.String())
}
Ejemplo n.º 11
0
func TestGetMetadata(t *testing.T) {
	server := initTestServer(
		"/latest/meta-data/some/path",
		"success", // real response includes suffix
	)
	defer server.Close()
	c := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})

	resp, err := c.GetMetadata("some/path")

	assert.NoError(t, err)
	assert.Equal(t, "success", resp)
}
Ejemplo n.º 12
0
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(session.New(), cfg)
			_, err := svc.Region()
			assert.NoError(t, err)
			wg.Done()
		}()
	}
	wg.Wait()
}
Ejemplo n.º 13
0
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(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})

	region, err := c.Region()

	assert.NoError(t, err)
	assert.Equal(t, "us-west-2", region)
}
Ejemplo n.º 14
0
func TestEC2RoleProvider(t *testing.T) {
	server := initTestServer("2014-12-16T01:51:37Z", false)
	defer server.Close()

	p := &ec2rolecreds.EC2RoleProvider{
		Client: ec2metadata.New(session.New(), &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")
}
Ejemplo n.º 15
0
func TestClientNotOverrideDefaultHTTPClientTimeout(t *testing.T) {
	origClient := *http.DefaultClient
	http.DefaultClient.Transport = &http.Transport{}
	defer func() {
		http.DefaultClient = &origClient
	}()

	svc := ec2metadata.New(session.New())

	assert.Equal(t, http.DefaultClient, svc.Config.HTTPClient)

	tr, ok := svc.Config.HTTPClient.Transport.(*http.Transport)
	assert.True(t, ok)
	assert.NotNil(t, tr)
	assert.Nil(t, tr.Dial)
}
Ejemplo n.º 16
0
func TestMetadataNotAvailable(t *testing.T) {
	c := ec2metadata.New(session.New())
	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
	})

	available := c.Available()

	assert.False(t, available)
}
Ejemplo n.º 17
0
func ExampleECR_CreateRepository() {
	svc := ecr.New(session.New())

	params := &ecr.CreateRepositoryInput{
		RepositoryName: aws.String("RepositoryName"), // Required
	}
	resp, err := svc.CreateRepository(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Ejemplo n.º 18
0
func TestOutputService6ProtocolTestIgnoresExtraDataCase1(t *testing.T) {
	sess := session.New()
	svc := NewOutputService6ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	buf := bytes.NewReader([]byte("{\"foo\": \"bar\"}"))
	req, out := svc.OutputService6TestCaseOperation1Request(nil)
	req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}

	// set headers

	// unmarshal response
	jsonrpc.UnmarshalMeta(req)
	jsonrpc.Unmarshal(req)
	assert.NoError(t, req.Error)

	// assert response
	assert.NotNil(t, out) // ensure out variable is used

}
Ejemplo n.º 19
0
func BenchmarkEC3RoleProvider(b *testing.B) {
	server := initTestServer("2014-12-16T01:51:37Z", false)
	defer server.Close()

	p := &ec2rolecreds.EC2RoleProvider{
		Client: ec2metadata.New(session.New(), &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)
		}
	}
}
Ejemplo n.º 20
0
func ExampleECR_InitiateLayerUpload() {
	svc := ecr.New(session.New())

	params := &ecr.InitiateLayerUploadInput{
		RepositoryName: aws.String("RepositoryName"), // Required
		RegistryId:     aws.String("RegistryId"),
	}
	resp, err := svc.InitiateLayerUpload(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Ejemplo n.º 21
0
func ExampleECR_GetDownloadUrlForLayer() {
	svc := ecr.New(session.New())

	params := &ecr.GetDownloadUrlForLayerInput{
		LayerDigest:    aws.String("LayerDigest"),    // Required
		RepositoryName: aws.String("RepositoryName"), // Required
		RegistryId:     aws.String("RegistryId"),
	}
	resp, err := svc.GetDownloadUrlForLayer(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Ejemplo n.º 22
0
func TestEC2RoleProviderFailAssume(t *testing.T) {
	server := initTestServer("2014-12-16T01:51:37Z", true)
	defer server.Close()

	p := &ec2rolecreds.EC2RoleProvider{
		Client: ec2metadata.New(session.New(), &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")
}
Ejemplo n.º 23
0
func TestOutputService3ProtocolTestTimestampMembersCase1(t *testing.T) {
	sess := session.New()
	svc := NewOutputService3ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	buf := bytes.NewReader([]byte("{\"TimeMember\": 1398796238, \"StructMember\": {\"foo\": 1398796238}}"))
	req, out := svc.OutputService3TestCaseOperation1Request(nil)
	req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}

	// set headers

	// unmarshal response
	jsonrpc.UnmarshalMeta(req)
	jsonrpc.Unmarshal(req)
	assert.NoError(t, req.Error)

	// assert response
	assert.NotNil(t, out) // ensure out variable is used
	assert.Equal(t, time.Unix(1.398796238e+09, 0).UTC().String(), out.StructMember.Foo.String())
	assert.Equal(t, time.Unix(1.398796238e+09, 0).UTC().String(), out.TimeMember.String())

}
Ejemplo n.º 24
0
func ExampleECR_SetRepositoryPolicy() {
	svc := ecr.New(session.New())

	params := &ecr.SetRepositoryPolicyInput{
		PolicyText:     aws.String("RepositoryPolicyText"), // Required
		RepositoryName: aws.String("RepositoryName"),       // Required
		Force:          aws.Bool(true),
		RegistryId:     aws.String("RegistryId"),
	}
	resp, err := svc.SetRepositoryPolicy(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Ejemplo n.º 25
0
func ExampleECR_ListImages() {
	svc := ecr.New(session.New())

	params := &ecr.ListImagesInput{
		RepositoryName: aws.String("RepositoryName"), // Required
		MaxResults:     aws.Int64(1),
		NextToken:      aws.String("NextToken"),
		RegistryId:     aws.String("RegistryId"),
	}
	resp, err := svc.ListImages(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Ejemplo n.º 26
0
func ExampleECR_GetAuthorizationToken() {
	svc := ecr.New(session.New())

	params := &ecr.GetAuthorizationTokenInput{
		RegistryIds: []*string{
			aws.String("RegistryId"), // Required
			// More values...
		},
	}
	resp, err := svc.GetAuthorizationToken(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Ejemplo n.º 27
0
func TestOutputService2ProtocolTestBlobMembersCase1(t *testing.T) {
	sess := session.New()
	svc := NewOutputService2ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})

	buf := bytes.NewReader([]byte("{\"BlobMember\": \"aGkh\", \"StructMember\": {\"foo\": \"dGhlcmUh\"}}"))
	req, out := svc.OutputService2TestCaseOperation1Request(nil)
	req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}

	// set headers

	// unmarshal response
	jsonrpc.UnmarshalMeta(req)
	jsonrpc.Unmarshal(req)
	assert.NoError(t, req.Error)

	// assert response
	assert.NotNil(t, out) // ensure out variable is used
	assert.Equal(t, "hi!", string(out.BlobMember))
	assert.Equal(t, "there!", string(out.StructMember.Foo))

}
Ejemplo n.º 28
0
func main() {
	// configure aws client
	sess := session.New()
	svc := ecr.New(sess, aws.NewConfig().WithRegion(getRegion(sess)))

	// this lets us handle multiple registries
	params := &ecr.GetAuthorizationTokenInput{
		RegistryIds: getRegistryIds(),
	}

	// request the token
	resp, err := svc.GetAuthorizationToken(params)
	check(err)

	// fields to send to template
	fields := make([]Auth, len(resp.AuthorizationData))
	for i, auth := range resp.AuthorizationData {

		// extract base64 token
		data, err := base64.StdEncoding.DecodeString(*auth.AuthorizationToken)
		check(err)

		// extract username and password
		token := strings.SplitN(string(data), ":", 2)

		// object to pass to template
		fields[i] = Auth{
			Token:         *auth.AuthorizationToken,
			User:          token[0],
			Pass:          token[1],
			ProxyEndpoint: *(auth.ProxyEndpoint),
			ExpiresAt:     *(auth.ExpiresAt),
		}
	}

	// run the template
	err = getTemplate().Execute(os.Stdout, fields)
	check(err)
}
Ejemplo n.º 29
0
func main() {
	svc := ecr.New(session.New())

	// this would be how to get tokens for multiple registries
	// params := &ecr.GetAuthorizationTokenInput{
	// 	RegistryIds: []*string{
	// 		aws.String("123"),
	// 		aws.String("456"),
	// 	},
	// }
	resp, err := svc.GetAuthorizationToken(nil)
	check(err)

	// fields to send to template
	fields := make([]Auth, len(resp.AuthorizationData))
	for i, auth := range resp.AuthorizationData {

		// extract base64 token
		data, err := base64.StdEncoding.DecodeString(*auth.AuthorizationToken)
		check(err)

		// extract username and password
		token := strings.SplitN(string(data), ":", 2)

		// object to pass to template
		fields[i] = Auth{
			Token:         *auth.AuthorizationToken,
			User:          token[0],
			Pass:          token[1],
			ProxyEndpoint: *(auth.ProxyEndpoint),
			ExpiresAt:     *(auth.ExpiresAt),
		}
	}

	// run the template
	err = getTemplate().Execute(os.Stdout, fields)
	check(err)
}
Ejemplo n.º 30
0
func ExampleECR_UploadLayerPart() {
	svc := ecr.New(session.New())

	params := &ecr.UploadLayerPartInput{
		LayerPartBlob:  []byte("PAYLOAD"),            // Required
		PartFirstByte:  aws.Int64(1),                 // Required
		PartLastByte:   aws.Int64(1),                 // Required
		RepositoryName: aws.String("RepositoryName"), // Required
		UploadId:       aws.String("UploadId"),       // Required
		RegistryId:     aws.String("RegistryId"),
	}
	resp, err := svc.UploadLayerPart(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}