Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Amazon ECS Resource Detector #466

Merged
merged 7 commits into from
Nov 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ updates:
schedule:
interval: "weekly"
day: "sunday"
-
package-ecosystem: "gomod"
directory: "/detectors/aws/ecs"
labels:
- dependencies
- go
- "Skip Changelog"
schedule:
interval: "weekly"
day: "sunday"
-
package-ecosystem: "gomod"
directory: "/detectors/gcp"
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

- `otelhttp.{Get,Head,Post,PostForm}` convenience wrappers for their `http` counterparts. (#390)
- The AWS detector now adds the cloud zone, host image ID, host type, and host name to the returned `Resource`. (#410)
- Add Amazon ECS Resource Detector for AWS X-Ray. (#466)

### Changed

Expand Down
106 changes: 106 additions & 0 deletions detectors/aws/ecs/ecs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright The OpenTelemetry Authors
//
// 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 ecs

import (
"context"
"errors"
"io/ioutil"
"os"
"strings"

"go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/semconv"
)

const (
TypeStr = "ecs"
metadataV3EnvVar = "ECS_CONTAINER_METADATA_URI"
metadataV4EnvVar = "ECS_CONTAINER_METADATA_URI_V4"
containerIDLength = 64
defaultCgroupPath = "/proc/self/cgroup"
)

var (
empty = resource.Empty()
errCannotReadContainerID = errors.New("failed to read container ID from cGroupFile")
errCannotReadCGroupFile = errors.New("ECS resource detector failed to read cGroupFile")
errNotOnECS = errors.New("process is not on ECS, cannot detect environment variables from ECS")
)

// Create interface for methods needing to be mocked
type detectorUtils interface {
getContainerName() (string, error)
getContainerID() (string, error)
}

// struct implements detectorUtils interface
type ecsDetectorUtils struct{}

// resource detector collects resource information from Elastic Container Service environment
type ResourceDetector struct {
utils detectorUtils
}

// compile time assertion that ecsDetectorUtils implements detectorUtils interface
var _ detectorUtils = (*ecsDetectorUtils)(nil)

// compile time assertion that resource detector implements the resource.Detector interface.
var _ resource.Detector = (*ResourceDetector)(nil)

// Detect finds associated resources when running on ECS environment.
func (detector *ResourceDetector) Detect(ctx context.Context) (*resource.Resource, error) {
metadataURIV3 := os.Getenv(metadataV3EnvVar)
metadataURIV4 := os.Getenv(metadataV4EnvVar)

if len(metadataURIV3) == 0 && len(metadataURIV4) == 0 {
return empty, errNotOnECS
}
hostName, err := detector.utils.getContainerName()
if err != nil {
return empty, err
}
containerID, err := detector.utils.getContainerID()
if err != nil {
return empty, err
}
labels := []label.KeyValue{
semconv.ContainerNameKey.String(hostName),
semconv.ContainerIDKey.String(containerID),
}

return resource.NewWithAttributes(labels...), nil
}

// returns docker container ID from default c group path
func (ecsUtils ecsDetectorUtils) getContainerID() (string, error) {
fileData, err := ioutil.ReadFile(defaultCgroupPath)
if err != nil {
return "", errCannotReadCGroupFile
}
splitData := strings.Split(strings.TrimSpace(string(fileData)), "\n")
for _, str := range splitData {
if len(str) > containerIDLength {
return str[len(str)-containerIDLength:], nil
}
}
return "", errCannotReadContainerID
}

// returns host name reported by the kernel
func (ecsUtils ecsDetectorUtils) getContainerName() (string, error) {
return os.Hostname()
}
92 changes: 92 additions & 0 deletions detectors/aws/ecs/ecs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright The OpenTelemetry Authors
//
// 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 ecs

import (
"context"
"os"
"testing"

"github.com/bmizerany/assert"
"github.com/stretchr/testify/mock"

"go.opentelemetry.io/otel/label"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/semconv"
)

// Create interface for functions that need to be mocked
type MockDetectorUtils struct {
mock.Mock
}

func (detectorUtils *MockDetectorUtils) getContainerID() (string, error) {
args := detectorUtils.Called()
return args.String(0), args.Error(1)
}

func (detectorUtils *MockDetectorUtils) getContainerName() (string, error) {
args := detectorUtils.Called()
return args.String(0), args.Error(1)
}

//succesfully return resource when process is running on Amazon ECS environment
func TestDetect(t *testing.T) {
os.Clearenv()
os.Setenv(metadataV3EnvVar, "3")
os.Setenv(metadataV4EnvVar, "4")

detectorUtils := new(MockDetectorUtils)

detectorUtils.On("getContainerName").Return("container-Name", nil)
detectorUtils.On("getContainerID").Return("0123456789A", nil)

labels := []label.KeyValue{
semconv.ContainerNameKey.String("container-Name"),
semconv.ContainerIDKey.String("0123456789A"),
}
expectedResource := resource.NewWithAttributes(labels...)
detector := ResourceDetector{detectorUtils}
resource, _ := detector.Detect(context.Background())

assert.Equal(t, resource, expectedResource, "Resource returned is incorrect")
}

//returns empty resource when detector cannot read container ID
func TestDetectCannotReadContainerID(t *testing.T) {
os.Clearenv()
os.Setenv(metadataV3EnvVar, "3")
os.Setenv(metadataV4EnvVar, "4")
detectorUtils := new(MockDetectorUtils)

detectorUtils.On("getContainerName").Return("container-Name", nil)
detectorUtils.On("getContainerID").Return("", errCannotReadContainerID)

detector := ResourceDetector{detectorUtils}
resource, err := detector.Detect(context.Background())

assert.Equal(t, errCannotReadContainerID, err)
assert.Equal(t, 0, len(resource.Attributes()))
}

//returns empty resource when process is not running ECS
func TestReturnsIfNoEnvVars(t *testing.T) {
os.Clearenv()
detector := ResourceDetector{}
resource, err := detector.Detect(context.Background())

assert.Equal(t, errNotOnECS, err)
assert.Equal(t, 0, len(resource.Attributes()))
}
11 changes: 11 additions & 0 deletions detectors/aws/ecs/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/kkelvinlo/opentelemetry-go-contrib/detectors/aws/ecs

go 1.15

require (
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869
github.com/kr/pretty v0.2.1 // indirect
github.com/stretchr/testify v1.6.1
go.opentelemetry.io/otel v0.14.0
go.opentelemetry.io/otel/sdk v0.14.0
)
30 changes: 30 additions & 0 deletions detectors/aws/ecs/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
github.com/DataDog/sketches-go v0.0.1/go.mod h1:Q5DbzQ+3AkgGwymQO7aZFNP7ns2lZKGtvRBzRXfdi60=
github.com/benbjohnson/clock v1.0.3/go.mod h1:bGMdMPoPVvcYyt1gHDf4J2KE153Yf9BuiUKYMaxlTDM=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.5.3 h1:x95R7cp+rSeeqAMI2knLtQ0DKlaBhv2NrtrOvafPHRo=
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
go.opentelemetry.io/otel v0.14.0 h1:YFBEfjCk9MTjaytCNSUkp9Q8lF7QJezA06T71FbQxLQ=
go.opentelemetry.io/otel v0.14.0/go.mod h1:vH5xEuwy7Rts0GNtsCW3HYQoZDY+OmBJ6t1bFGGlxgw=
go.opentelemetry.io/otel/sdk v0.14.0 h1:Pqgd85y5XhyvHQlOxkKW+FD4DAX7AoeaNIDKC2VhfHQ=
go.opentelemetry.io/otel/sdk v0.14.0/go.mod h1:kGO5pEMSNqSJppHAm8b73zztLxB5fgDQnD56/dl5xqE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=