repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-xray-sdk-go
aws
Go
// 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-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" xraySvc "github.com/aws/aws-sdk-go/service/xray" "github.com/aws/aws-xray-sdk-go/daemoncfg" "github.com/aws/aws-xray-sdk-go/internal/logger" ) // proxy is an implementation of svcProxy that forwards requests to the XRay daemon type proxy struct { // XRay client for sending unsigned proxied requests to the daemon xray *xraySvc.XRay } // NewProxy returns a Proxy func newProxy(d *daemoncfg.DaemonEndpoints) (svcProxy, error) { if d == nil { d = daemoncfg.GetDaemonEndpoints() } logger.Infof("X-Ray proxy using address : %v", d.TCPAddr.String()) url := "http://" + d.TCPAddr.String() // Endpoint resolver for proxying requests through the daemon f := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { return endpoints.ResolvedEndpoint{ URL: url, }, nil } // Dummy session for unsigned requests sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-1"), Credentials: credentials.NewStaticCredentials("", "", ""), EndpointResolver: endpoints.ResolverFunc(f), }) if err != nil { return nil, err } x := xraySvc.New(sess) // Remove Signer and replace with No-Op handler x.Handlers.Sign.Clear() x.Handlers.Sign.PushBack(func(*request.Request) { // Do nothing }) p := &proxy{xray: x} return p, nil } // GetSamplingTargets calls the XRay daemon for sampling targets func (p *proxy) GetSamplingTargets(s []*xraySvc.SamplingStatisticsDocument) (*xraySvc.GetSamplingTargetsOutput, error) { input := &xraySvc.GetSamplingTargetsInput{ SamplingStatisticsDocuments: s, } output, err := p.xray.GetSamplingTargets(input) if err != nil { return nil, err } return output, nil } // GetSamplingRules calls the XRay daemon for sampling rules func (p *proxy) GetSamplingRules() ([]*xraySvc.SamplingRuleRecord, error) { input := &xraySvc.GetSamplingRulesInput{} output, err := p.xray.GetSamplingRules(input) if err != nil { return nil, err } rules := output.SamplingRuleRecords return rules, nil }
95
aws-xray-sdk-go
aws
Go
// 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/utils" // Reservoirs allow a specified (`perSecond`) amount of `Take()`s per second. // reservoir is a set of properties common to all reservoirs type reservoir struct { // Total size of reservoir capacity int64 // Reservoir consumption for current epoch used int64 // Unix epoch. Reservoir usage is reset every second. currentEpoch int64 } // CentralizedReservoir is a reservoir distributed among all running instances of the SDK type CentralizedReservoir struct { // Quota assigned to client quota int64 // Quota refresh timestamp refreshedAt int64 // Quota expiration timestamp expiresAt int64 // Polling interval for quota interval int64 // True if reservoir has been borrowed from this epoch borrowed bool // Common reservoir properties *reservoir } // expired returns true if current time is past expiration timestamp. False otherwise. func (r *CentralizedReservoir) expired(now int64) bool { return now > r.expiresAt } // borrow returns true if the reservoir has not been borrowed from this epoch func (r *CentralizedReservoir) borrow(now int64) bool { if now != r.currentEpoch { r.reset(now) } s := r.borrowed r.borrowed = true return !s && r.reservoir.capacity != 0 } // Take consumes quota from reservoir, if any remains, and returns true. False otherwise. func (r *CentralizedReservoir) Take(now int64) bool { if now != r.currentEpoch { r.reset(now) } // Consume from quota, if available if r.quota > r.used { r.used++ return true } return false } func (r *CentralizedReservoir) reset(now int64) { r.currentEpoch, r.used, r.borrowed = now, 0, false } // Reservoir is a reservoir local to the running instance of the SDK type Reservoir struct { // Provides system time clock utils.Clock *reservoir } // Take attempts to consume a unit from the local reservoir. Returns true if unit taken, false otherwise. func (r *Reservoir) Take() bool { // Reset counters if new second if now := r.clock.Now().Unix(); now != r.currentEpoch { r.used = 0 r.currentEpoch = now } // Take from reservoir, if available if r.used >= r.capacity { return false } // Increment reservoir usage r.used++ return true }
111
aws-xray-sdk-go
aws
Go
// 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" "testing" "github.com/aws/aws-xray-sdk-go/utils" "github.com/stretchr/testify/assert" ) const Interval = 100 func takeOverTime(r *Reservoir, millis int) int { taken := 0 for i := 0; i < millis/Interval; i++ { if r.Take() { taken++ } r.clock.Increment(0, 1e6*Interval) } return taken } const TestDuration = 1500 // Asserts consumption from reservoir once per second func TestOnePerSecond(t *testing.T) { clock := &utils.MockClock{} cap := 1 res := &Reservoir{ clock: clock, reservoir: &reservoir{ capacity: int64(cap), }, } taken := takeOverTime(res, TestDuration) assert.True(t, int(math.Ceil(TestDuration/1000.0)) == taken) } // Asserts consumption from reservoir ten times per second func TestTenPerSecond(t *testing.T) { clock := &utils.MockClock{} cap := 10 res := &Reservoir{ clock: clock, reservoir: &reservoir{ capacity: int64(cap), }, } taken := takeOverTime(res, TestDuration) assert.True(t, int(math.Ceil(float64(TestDuration*cap)/1000.0)) == taken) } func TestTakeQuotaAvailable(t *testing.T) { capacity := int64(100) used := int64(0) quota := int64(9) clock := &utils.MockClock{ NowTime: 1500000000, } r := &CentralizedReservoir{ quota: quota, reservoir: &reservoir{ capacity: capacity, used: used, currentEpoch: clock.Now().Unix(), }, } s := r.Take(clock.Now().Unix()) assert.Equal(t, true, s) assert.Equal(t, int64(1), r.used) } func TestTakeQuotaUnavailable(t *testing.T) { capacity := int64(100) used := int64(100) quota := int64(9) clock := &utils.MockClock{ NowTime: 1500000000, } r := &CentralizedReservoir{ quota: quota, reservoir: &reservoir{ capacity: capacity, used: used, currentEpoch: clock.Now().Unix(), }, } s := r.Take(clock.Now().Unix()) assert.Equal(t, false, s) assert.Equal(t, int64(100), r.used) } func TestExpiredReservoir(t *testing.T) { clock := &utils.MockClock{ NowTime: 1500000001, } r := &CentralizedReservoir{ expiresAt: 1500000000, } expired := r.expired(clock.Now().Unix()) assert.Equal(t, true, expired) } // Assert that the borrow flag is reset every second func TestBorrowFlagReset(t *testing.T) { clock := &utils.MockClock{ NowTime: 1500000000, } r := &CentralizedReservoir{ reservoir: &reservoir{ capacity: 10, }, } s := r.borrow(clock.Now().Unix()) assert.True(t, s) s = r.borrow(clock.Now().Unix()) assert.False(t, s) // Increment clock by 1 clock = &utils.MockClock{ NowTime: 1500000001, } // Reset borrow flag r.Take(clock.Now().Unix()) s = r.borrow(clock.Now().Unix()) assert.True(t, s) } // Assert that the reservoir does not allow borrowing if the reservoir capacity // is zero. func TestBorrowZeroCapacity(t *testing.T) { clock := &utils.MockClock{ NowTime: 1500000000, } r := &CentralizedReservoir{ reservoir: &reservoir{ capacity: 0, }, } s := r.borrow(clock.Now().Unix()) assert.False(t, s) } func TestResetQuotaUsageRotation(t *testing.T) { capacity := int64(100) used := int64(0) quota := int64(5) clock := &utils.MockClock{ NowTime: 1500000000, } r := &CentralizedReservoir{ quota: quota, reservoir: &reservoir{ capacity: capacity, used: used, currentEpoch: clock.Now().Unix(), }, } // Consume quota for second for i := 0; i < 5; i++ { taken := r.Take(clock.Now().Unix()) assert.Equal(t, true, taken) assert.Equal(t, int64(i+1), r.used) } // Take() should be false since no unused quota left taken := r.Take(clock.Now().Unix()) assert.Equal(t, false, taken) assert.Equal(t, int64(5), r.used) // Increment epoch to reset unused quota clock = &utils.MockClock{ NowTime: 1500000001, } // Take() should be true since ununsed quota is available taken = r.Take(clock.Now().Unix()) assert.Equal(t, int64(1500000001), r.currentEpoch) assert.Equal(t, true, taken) assert.Equal(t, int64(1), r.used) } func TestResetReservoirUsageRotation(t *testing.T) { capacity := int64(5) used := int64(0) clock := &utils.MockClock{ NowTime: 1500000000, } r := &Reservoir{ clock: clock, reservoir: &reservoir{ capacity: capacity, used: used, currentEpoch: clock.Now().Unix(), }, } // Consume reservoir for second for i := 0; i < 5; i++ { taken := r.Take() assert.Equal(t, true, taken) assert.Equal(t, int64(i+1), r.used) } // Take() should be false since no reservoir left taken := r.Take() assert.Equal(t, false, taken) assert.Equal(t, int64(5), r.used) // Increment epoch to reset reservoir clock = &utils.MockClock{ NowTime: 1500000001, } r.clock = clock // Take() should be true since reservoir is available taken = r.Take() assert.Equal(t, int64(1500000001), r.currentEpoch) assert.Equal(t, true, taken) assert.Equal(t, int64(1), r.used) }
252
aws-xray-sdk-go
aws
Go
// 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 // Decision contains sampling decision and the rule matched for an incoming request type Decision struct { Sample bool Rule *string } // Request represents parameters used to make a sampling decision. type Request struct { Host string Method string URL string ServiceName string ServiceType string }
25
aws-xray-sdk-go
aws
Go
// 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 ( "sync" "github.com/aws/aws-xray-sdk-go/internal/logger" "github.com/aws/aws-xray-sdk-go/pattern" "github.com/aws/aws-xray-sdk-go/utils" xraySvc "github.com/aws/aws-sdk-go/service/xray" ) // Properties is the base set of properties that define a sampling rule. type Properties struct { ServiceName string `json:"service_name"` Host string `json:"host"` HTTPMethod string `json:"http_method"` URLPath string `json:"url_path"` FixedTarget int64 `json:"fixed_target"` Rate float64 `json:"rate"` } // AppliesTo returns true if the sampling rule matches against given parameters. False Otherwise. // Assumes lock is already held, if required. func (p *Properties) AppliesTo(host, path, method string) bool { return (host == "" || pattern.WildcardMatchCaseInsensitive(p.Host, host)) && (path == "" || pattern.WildcardMatchCaseInsensitive(p.URLPath, path)) && (method == "" || pattern.WildcardMatchCaseInsensitive(p.HTTPMethod, method)) } // AppliesTo returns true if the sampling rule matches against given sampling request. False Otherwise. // Assumes lock is already held, if required. func (r *CentralizedRule) AppliesTo(request *Request) bool { return (request.Host == "" || pattern.WildcardMatchCaseInsensitive(r.Host, request.Host)) && (request.URL == "" || pattern.WildcardMatchCaseInsensitive(r.URLPath, request.URL)) && (request.Method == "" || pattern.WildcardMatchCaseInsensitive(r.HTTPMethod, request.Method)) && (request.ServiceName == "" || pattern.WildcardMatchCaseInsensitive(r.ServiceName, request.ServiceName)) && (request.ServiceType == "" || pattern.WildcardMatchCaseInsensitive(r.serviceType, request.ServiceType)) } // CentralizedRule represents a centralized sampling rule type CentralizedRule struct { // Centralized reservoir for keeping track of reservoir usage reservoir *CentralizedReservoir // Rule name identifying this rule ruleName string // Priority of matching against rule priority int64 // Number of requests matched against this rule requests int64 // Number of requests sampled using this rule sampled int64 // Number of requests burrowed borrows int64 // Timestamp for last match against this rule usedAt int64 // Common sampling rule properties *Properties // ServiceType for the sampling rule serviceType string // ResourceARN for the sampling rule resourceARN string // Attributes for the sampling rule attributes map[string]*string // Provides system time clock utils.Clock // Provides random numbers rand utils.Rand mu sync.RWMutex } // stale returns true if the quota is due for a refresh. False otherwise. func (r *CentralizedRule) stale(now int64) bool { r.mu.RLock() defer r.mu.RUnlock() return r.requests != 0 && now >= r.reservoir.refreshedAt+r.reservoir.interval } // Sample returns true if the request should be sampled. False otherwise. func (r *CentralizedRule) Sample() *Decision { now := r.clock.Now().Unix() sd := &Decision{ Rule: &r.ruleName, } r.mu.Lock() defer r.mu.Unlock() r.requests++ // Fallback to bernoulli sampling if quota has expired if r.reservoir.expired(now) { if r.reservoir.borrow(now) { logger.Debugf( "Sampling target has expired for rule %s. Borrowing a request.", r.ruleName, ) sd.Sample = true r.borrows++ return sd } logger.Debugf( "Sampling target has expired for rule %s. Using fixed rate.", r.ruleName, ) sd.Sample = r.bernoulliSample() return sd } // Take from reservoir quota, if possible if r.reservoir.Take(now) { r.sampled++ sd.Sample = true return sd } logger.Debugf( "Sampling target has been exhausted for rule %s. Using fixed rate.", r.ruleName, ) // Use bernoulli sampling if quota expended sd.Sample = r.bernoulliSample() return sd } // bernoulliSample uses bernoulli sampling rate to make a sampling decision func (r *CentralizedRule) bernoulliSample() bool { if r.rand.Float64() < r.Rate { r.sampled++ return true } return false } // snapshot takes a snapshot of the sampling statistics counters, returning // xraySvc.SamplingStatistics. It also resets statistics counters. func (r *CentralizedRule) snapshot() *xraySvc.SamplingStatisticsDocument { r.mu.Lock() name := &r.ruleName // Copy statistics counters since xraySvc.SamplingStatistics expects // pointers to counters, and ours are mutable. requests, sampled, borrows := r.requests, r.sampled, r.borrows // Reset counters r.requests, r.sampled, r.borrows = 0, 0, 0 r.mu.Unlock() now := r.clock.Now() s := &xraySvc.SamplingStatisticsDocument{ RequestCount: &requests, SampledCount: &sampled, BorrowCount: &borrows, RuleName: name, Timestamp: &now, } return s } // Rule is local sampling rule. type Rule struct { reservoir *Reservoir // Provides random numbers rand utils.Rand // Common sampling rule properties *Properties mu sync.RWMutex } // Sample is used to provide sampling decision. func (r *Rule) Sample() *Decision { var sd Decision r.mu.Lock() if r.reservoir.Take() { sd.Sample = true } else { sd.Sample = r.rand.Float64() < r.Rate } r.mu.Unlock() return &sd }
218
aws-xray-sdk-go
aws
Go
// 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" "time" "github.com/aws/aws-xray-sdk-go/utils" ) // 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 { return ManifestFromJSONBytes(b) } 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 } initSamplingRules(s) return s, nil } // Init local reservoir and add random number generator func initSamplingRules(srm *RuleManifest) { // Init user-defined rules for _, r := range srm.Rules { r.rand = &utils.DefaultRand{} r.reservoir = &Reservoir{ clock: &utils.DefaultClock{}, reservoir: &reservoir{ capacity: r.FixedTarget, used: 0, currentEpoch: time.Now().Unix(), }, } } // Init default rule srm.Default.rand = &utils.DefaultRand{} srm.Default.reservoir = &Reservoir{ clock: &utils.DefaultClock{}, reservoir: &reservoir{ capacity: srm.Default.FixedTarget, used: 0, currentEpoch: time.Now().Unix(), }, } } // processManifest returns the provided manifest if valid, or an error if the provided manifest is invalid. func processManifest(srm *RuleManifest) error { if srm == nil { return errors.New("sampling rule manifest must not be nil") } if srm.Version != 1 && srm.Version != 2 { return fmt.Errorf("sampling rule manifest version %d not supported", srm.Version) } if srm.Default == nil { 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") } c := &utils.DefaultClock{} srm.Default.reservoir = &Reservoir{ clock: c, reservoir: &reservoir{ capacity: srm.Default.FixedTarget, }, } if srm.Rules != nil { for _, r := range srm.Rules { if srm.Version == 1 { if err := validateVersion1(r); err != nil { return err } r.Host = r.ServiceName // V1 sampling rule contains service name and not host r.ServiceName = "" } if srm.Version == 2 { if err := validateVersion2(r); err != nil { return err } } r.reservoir = &Reservoir{ clock: c, reservoir: &reservoir{ capacity: r.FixedTarget, }, } } } return nil } func validateVersion2(rule *Rule) error { if rule.FixedTarget < 0 || rule.Rate < 0 { return errors.New("all rules must have non-negative values for fixed_target and rate") } if rule.ServiceName != "" || rule.Host == "" || rule.HTTPMethod == "" || rule.URLPath == "" { return errors.New("all non-default rules must have values for url_path, host, and http_method") } return nil } func validateVersion1(rule *Rule) error { if rule.FixedTarget < 0 || rule.Rate < 0 { return errors.New("all rules must have non-negative values for fixed_target and rate") } if rule.Host != "" || rule.ServiceName == "" || rule.HTTPMethod == "" || rule.URLPath == "" { return errors.New("all non-default rules must have values for url_path, service_name, and http_method") } return nil }
160
aws-xray-sdk-go
aws
Go
// 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 ( "testing" "time" "github.com/aws/aws-xray-sdk-go/utils" "github.com/stretchr/testify/assert" ) func TestStaleRule(t *testing.T) { cr := &CentralizedRule{ requests: 5, reservoir: &CentralizedReservoir{ refreshedAt: 1500000000, interval: 10, }, } s := cr.stale(1500000010) assert.True(t, s) } func TestFreshRule(t *testing.T) { cr := &CentralizedRule{ requests: 5, reservoir: &CentralizedReservoir{ refreshedAt: 1500000000, interval: 10, }, } s := cr.stale(1500000009) assert.False(t, s) } func TestInactiveRule(t *testing.T) { cr := &CentralizedRule{ requests: 0, reservoir: &CentralizedReservoir{ refreshedAt: 1500000000, interval: 10, }, } s := cr.stale(1500000011) assert.False(t, s) } func TestExpiredReservoirBernoulliSample(t *testing.T) { // One second past expiration clock := &utils.MockClock{ NowTime: 1500000061, } // Set random to be within sampling rate rand := &utils.MockRand{ F64: 0.05, } p := &Properties{ Rate: 0.06, } // Expired reservoir cr := &CentralizedReservoir{ expiresAt: 1500000060, borrowed: true, reservoir: &reservoir{ used: 0, capacity: 10, currentEpoch: 1500000061, }, } csr := &CentralizedRule{ ruleName: "r1", reservoir: cr, Properties: p, clock: clock, rand: rand, } sd := csr.Sample() assert.True(t, sd.Sample) assert.Equal(t, "r1", *sd.Rule) assert.Equal(t, int64(1), csr.sampled) assert.Equal(t, int64(1), csr.requests) } func TestTakeFromQuotaSample(t *testing.T) { clock := &utils.MockClock{ NowTime: 1500000000, } // Reservoir with unused quota r := &reservoir{ currentEpoch: clock.Now().Unix(), used: 0, } cr := &CentralizedReservoir{ quota: 10, expiresAt: 1500000060, reservoir: r, } csr := &CentralizedRule{ ruleName: "r1", reservoir: cr, clock: clock, } sd := csr.Sample() assert.True(t, sd.Sample) assert.Equal(t, "r1", *sd.Rule) assert.Equal(t, int64(1), csr.sampled) assert.Equal(t, int64(1), csr.requests) assert.Equal(t, int64(1), csr.reservoir.used) } func TestBernoulliSamplePositve(t *testing.T) { clock := &utils.MockClock{ NowTime: 1500000000, } // Reservoir with unused quota r := &reservoir{ currentEpoch: clock.Now().Unix(), used: 10, } // Set random to be within sampling rate rand := &utils.MockRand{ F64: 0.05, } p := &Properties{ Rate: 0.06, } cr := &CentralizedReservoir{ quota: 10, expiresAt: 1500000060, reservoir: r, } csr := &CentralizedRule{ ruleName: "r1", reservoir: cr, Properties: p, rand: rand, clock: clock, } sd := csr.Sample() assert.True(t, sd.Sample) assert.Equal(t, "r1", *sd.Rule) assert.Equal(t, int64(1), csr.sampled) assert.Equal(t, int64(1), csr.requests) assert.Equal(t, int64(10), csr.reservoir.used) } func TestBernoulliSampleNegative(t *testing.T) { clock := &utils.MockClock{ NowTime: 1500000000, } // Reservoir with unused quota r := &reservoir{ currentEpoch: clock.Now().Unix(), used: 10, } // Set random to be outside sampling rate rand := &utils.MockRand{ F64: 0.07, } p := &Properties{ Rate: 0.06, } cr := &CentralizedReservoir{ quota: 10, expiresAt: 1500000060, reservoir: r, } csr := &CentralizedRule{ ruleName: "r1", reservoir: cr, Properties: p, rand: rand, clock: clock, } sd := csr.Sample() assert.False(t, sd.Sample) assert.Equal(t, "r1", *sd.Rule) assert.Equal(t, int64(0), csr.sampled) assert.Equal(t, int64(1), csr.requests) assert.Equal(t, int64(10), csr.reservoir.used) } // Test sampling from local reservoir func TestReservoirSample(t *testing.T) { clock := &utils.MockClock{ NowTime: 1500000000, } r := &reservoir{ capacity: 10, used: 5, currentEpoch: 1500000000, } lr := &Reservoir{ clock: clock, reservoir: r, } lsr := &Rule{ reservoir: lr, } sd := lsr.Sample() assert.True(t, sd.Sample) assert.Nil(t, sd.Rule) assert.Equal(t, int64(6), lsr.reservoir.used) } // Test bernoulli sampling for local sampling rule func TestLocalBernoulliSample(t *testing.T) { clock := &utils.MockClock{ NowTime: 1500000000, } r := &reservoir{ capacity: 10, used: 10, currentEpoch: 1500000000, } lr := &Reservoir{ clock: clock, reservoir: r, } // 6% sampling rate p := &Properties{ Rate: 0.06, } // Set random to be outside sampling rate rand := &utils.MockRand{ F64: 0.07, } lsr := &Rule{ reservoir: lr, rand: rand, Properties: p, } sd := lsr.Sample() assert.False(t, sd.Sample) assert.Nil(t, sd.Rule) assert.Equal(t, int64(10), lsr.reservoir.used) } func TestSnapshot(t *testing.T) { clock := &utils.MockClock{ NowTime: 1500000000, } csr := &CentralizedRule{ ruleName: "rule1", requests: 100, sampled: 12, borrows: 2, clock: clock, } ss := csr.snapshot() // Assert counters were reset assert.Equal(t, int64(0), csr.requests) assert.Equal(t, int64(0), csr.sampled) assert.Equal(t, int64(0), csr.borrows) // Assert on SamplingStatistics counters now := time.Unix(1500000000, 0) assert.Equal(t, int64(100), *ss.RequestCount) assert.Equal(t, int64(12), *ss.SampledCount) assert.Equal(t, int64(2), *ss.BorrowCount) assert.Equal(t, "rule1", *ss.RuleName) assert.Equal(t, now, *ss.Timestamp) } // Benchmarks func BenchmarkCentralizedRule_Sample(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { clock := &utils.MockClock{ NowTime: 1500000000, } // Reservoir with unused quota r := &reservoir{ currentEpoch: clock.Now().Unix(), used: 0, } cr := &CentralizedReservoir{ quota: 10, expiresAt: 1500000060, reservoir: r, } csr := &CentralizedRule{ ruleName: "r1", reservoir: cr, clock: clock, } csr.Sample() } }) }
346
aws-xray-sdk-go
aws
Go
// 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(request *Request) *Decision }
15
aws-xray-sdk-go
aws
Go
// 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 ( "path/filepath" "testing" "github.com/stretchr/testify/assert" ) func TestNewLocalizedStrategy(t *testing.T) { ss, err := NewLocalizedStrategy() assert.NotNil(t, ss) assert.Nil(t, err) } func TestNewLocalizedStrategyFromFilePath1(t *testing.T) { // V1 sampling testFile, err := filepath.Abs(filepath.Join("testdata", "rule-v1-sampling.json")) if err != nil { t.Fatal(err) } ss, err := NewLocalizedStrategyFromFilePath(testFile) assert.NotNil(t, ss) assert.Equal(t, 1, ss.manifest.Version) assert.Equal(t, 1, len(ss.manifest.Rules)) assert.Equal(t, "", ss.manifest.Rules[0].ServiceName) assert.Equal(t, "*", ss.manifest.Rules[0].Host) // always host set for V1 and V2 sampling rule assert.Equal(t, "*", ss.manifest.Rules[0].HTTPMethod) assert.Equal(t, "/checkout", ss.manifest.Rules[0].URLPath) assert.Equal(t, int64(10), ss.manifest.Rules[0].FixedTarget) assert.Equal(t, 0.05, ss.manifest.Rules[0].Rate) assert.Nil(t, err) } func TestNewLocalizedStrategyFromFilePath2(t *testing.T) { // V2 sampling testFile, err := filepath.Abs(filepath.Join("testdata", "rule-v2-sampling.json")) if err != nil { t.Fatal(err) } ss, err := NewLocalizedStrategyFromFilePath(testFile) assert.NotNil(t, ss) assert.Equal(t, 2, ss.manifest.Version) assert.Equal(t, 1, len(ss.manifest.Rules)) assert.Equal(t, "", ss.manifest.Rules[0].ServiceName) assert.Equal(t, "*", ss.manifest.Rules[0].Host) assert.Equal(t, "*", ss.manifest.Rules[0].HTTPMethod) assert.Equal(t, "/checkout", ss.manifest.Rules[0].URLPath) assert.Equal(t, int64(10), ss.manifest.Rules[0].FixedTarget) assert.Equal(t, 0.05, ss.manifest.Rules[0].Rate) assert.Nil(t, err) } func TestNewLocalizedStrategyFromFilePathInvalidRulesV1(t *testing.T) { // V1 contains host testFile, err := filepath.Abs(filepath.Join("testdata", "rule-v1-contains-host.json")) if err != nil { t.Fatal(err) } ss, err := NewLocalizedStrategyFromFilePath(testFile) assert.Nil(t, ss) assert.NotNil(t, err) } func TestNewLocalizedStrategyFromFilePathInvalidRulesV2(t *testing.T) { // V2 contains service_name testFile, err := filepath.Abs(filepath.Join("testdata", "rule-v2-contains-service-name.json")) if err != nil { t.Fatal(err) } ss, err := NewLocalizedStrategyFromFilePath(testFile) assert.Nil(t, ss) assert.NotNil(t, err) } func TestNewLocalizedStrategyFromFilePathWithInvalidJSON(t *testing.T) { // Test V1 sampling rule testFile, err := filepath.Abs(filepath.Join("testdata", "rule-v1-invalid.json")) if err != nil { t.Fatal(err) } ss, err := NewLocalizedStrategyFromFilePath(testFile) assert.Nil(t, ss) assert.NotNil(t, err) } func TestNewLocalizedStrategyFromJSONBytes(t *testing.T) { ruleBytes := []byte(`{ "version": 1, "default": { "fixed_target": 1, "rate": 0.05 }, "rules": [ ] }`) ss, err := NewLocalizedStrategyFromJSONBytes(ruleBytes) assert.NotNil(t, ss) assert.Nil(t, err) } func TestNewLocalizedStrategyFromInvalidJSONBytes(t *testing.T) { ruleBytes := []byte(`{ "version": 1, "default": { "fixed_target": 1, "rate": }, "rules": [ ] }`) ss, err := NewLocalizedStrategyFromJSONBytes(ruleBytes) assert.Nil(t, ss) assert.NotNil(t, err) } // Benchmarks func BenchmarkNewLocalizedStrategyFromJSONBytes(b *testing.B) { ruleBytes := []byte(`{ "version": 1, "default": { "fixed_target": 1, "rate": }, "rules": [ ] }`) for i := 0; i < b.N; i++ { _, err := NewLocalizedStrategyFromJSONBytes(ruleBytes) if err != nil { return } } }
140
aws-xray-sdk-go
aws
Go
// 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 utils import ( "time" ) // Clock provides an interface to implement method for getting current time. type Clock interface { Now() time.Time Increment(int64, int64) time.Time } // DefaultClock is an implementation of Clock interface. type DefaultClock struct{} // Now returns current time. func (t *DefaultClock) Now() time.Time { return time.Now() } // This method returns the current time but can be used to provide different implementation func (t *DefaultClock) Increment(_, _ int64) time.Time { return time.Now() }
33
aws-xray-sdk-go
aws
Go
// 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 utils import ( "sync/atomic" "time" ) // MockClock is a struct to record current time. type MockClock struct { NowTime int64 NowNanos int64 } // Now function returns NowTime value. func (c *MockClock) Now() time.Time { return time.Unix(c.NowTime, c.NowNanos) } // Increment is a method to increase current time. func (c *MockClock) Increment(s int64, ns int64) time.Time { sec := atomic.AddInt64(&c.NowTime, s) nSec := atomic.AddInt64(&c.NowNanos, ns) return time.Unix(sec, nSec) }
34
aws-xray-sdk-go
aws
Go
// 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 utils // MockRand is an implementation of Rand interface. type MockRand struct { F64 float64 Int int Int64 int64 } // Float64 returns value of F64. func (r *MockRand) Float64() float64 { return r.F64 } // Intn returns value of Int. func (r *MockRand) Intn(n int) int { return r.Int } // Int63n returns value of Int64. func (r *MockRand) Int63n(n int64) int64 { return r.Int64 }
32
aws-xray-sdk-go
aws
Go
// 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 utils import ( crand "crypto/rand" "encoding/binary" "math/rand" "sync" "time" ) // check lockedSource implements rand.Source var _ rand.Source = (*lockedSource)(nil) var _ rand.Source64 = (*lockedSource64)(nil) type lockedSource struct { mu sync.Mutex src rand.Source } func (src *lockedSource) Int63() int64 { src.mu.Lock() defer src.mu.Unlock() return src.src.Int63() } func (src *lockedSource) Seed(seed int64) { src.mu.Lock() defer src.mu.Unlock() src.src.Seed(seed) } type lockedSource64 struct { mu sync.Mutex src rand.Source64 } func (src *lockedSource64) Int63() int64 { src.mu.Lock() defer src.mu.Unlock() return src.src.Int63() } func (src *lockedSource64) Uint64() uint64 { src.mu.Lock() defer src.mu.Unlock() return src.src.Uint64() } func (src *lockedSource64) Seed(seed int64) { src.mu.Lock() defer src.mu.Unlock() src.src.Seed(seed) } func newSeed() int64 { var seed int64 if err := binary.Read(crand.Reader, binary.BigEndian, &seed); err != nil { // fallback to timestamp seed = time.Now().UnixNano() } return seed } func newGlobalRand() *rand.Rand { src := rand.NewSource(newSeed()) if src64, ok := src.(rand.Source64); ok { return rand.New(&lockedSource64{src: src64}) } return rand.New(&lockedSource{src: src}) } // Rand is an interface for a set of methods that return random value. type Rand interface { Int63n(n int64) int64 Intn(n int) int Float64() float64 } // DefaultRand is an implementation of Rand interface. // It is safe for concurrent use by multiple goroutines. type DefaultRand struct{} var globalRand = newGlobalRand() // Int63n returns, as an int64, a non-negative pseudo-random number in [0,n) // from the default Source. func (r *DefaultRand) Int63n(n int64) int64 { return globalRand.Int63n(n) } // Intn returns, as an int, a non-negative pseudo-random number in [0,n) // from the default Source. func (r *DefaultRand) Intn(n int) int { return globalRand.Intn(n) } // Float64 returns, as a float64, a pseudo-random number in [0.0,1.0) // from the default Source. func (r *DefaultRand) Float64() float64 { return globalRand.Float64() }
110
aws-xray-sdk-go
aws
Go
// 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 utils import ( "time" ) // Timer is the same as time.Timer except that it has jitters. // A Timer must be created with NewTimer. type Timer struct { t *time.Timer d time.Duration jitter time.Duration } // NewTimer creates a new Timer that will send the current time on its channel. func NewTimer(d, jitter time.Duration) *Timer { t := time.NewTimer(d - time.Duration(globalRand.Int63n(int64(jitter)))) jitteredTimer := Timer{ t: t, d: d, jitter: jitter, } return &jitteredTimer } // C is channel. func (j *Timer) C() <-chan time.Time { return j.t.C } // Reset resets the timer. // Reset should be invoked only on stopped or expired timers with drained channels. func (j *Timer) Reset() { j.t.Reset(j.d - time.Duration(globalRand.Int63n(int64(j.jitter)))) }
46
aws-xray-sdk-go
aws
Go
// 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-sdk-go/aws/session" "github.com/aws/aws-xray-sdk-go/internal/logger" "github.com/aws/aws-xray-sdk-go/resources" ) // RequestIDKey is the key name of the request id. const RequestIDKey string = "request_id" // ExtendedRequestIDKey is the key name of the extend request id. const ExtendedRequestIDKey string = "id_2" // S3ExtendedRequestIDHeaderKey is the key name of the s3 extend request id. const S3ExtendedRequestIDHeaderKey string = "x-amz-id-2" // TraceIDHeaderKey is the HTTP header name used for tracing. const TraceIDHeaderKey = "x-amzn-trace-id" 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(TraceIDHeaderKey, 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 xRayAfterSendHandler = request.NamedHandler{ Name: "XRayAfterSendHandler", Fn: func(r *request.Request) { curseg := GetSegment(r.HTTPRequest.Context()) if curseg != nil && curseg.Name == "attempt" { // An error could have prevented the connect subsegment from closing, // so clean it up here. curseg.RLock() temp := make([]*Segment, len(curseg.rawSubsegments)) copy(temp, curseg.rawSubsegments) curseg.RUnlock() for _, subsegment := range temp { if subsegment.getName() == "connect" && subsegment.safeInProgress() { subsegment.Close(nil) return } } } }, } 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(handlers *request.Handlers, completionWhitelistFilename string) { handlers.Validate.PushFrontNamed(xRayBeforeValidateHandler) handlers.Build.PushBackNamed(xRayAfterBuildHandler) handlers.Sign.PushFrontNamed(xRayBeforeSignHandler) handlers.Send.PushBackNamed(xRayAfterSendHandler) handlers.Unmarshal.PushFrontNamed(xRayBeforeUnmarshalHandler) handlers.Unmarshal.PushBackNamed(xRayAfterUnmarshalHandler) handlers.Retry.PushFrontNamed(xRayBeforeRetryHandler) handlers.AfterRetry.PushBackNamed(xRayAfterRetryHandler) handlers.Complete.PushFrontNamed(xrayCompleteHandler(completionWhitelistFilename)) } // 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.Handlers, "") } // 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.Handlers, filename) } // AWSSession adds X-Ray tracing to an AWS session. Clients created under this // session will inherit X-Ray tracing. func AWSSession(s *session.Session) *session.Session { pushHandlers(&s.Handlers, "") return s } // AWSSessionWithWhitelist allows a custom parameter whitelist JSON file to be // defined. func AWSSessionWithWhitelist(s *session.Session, filename string) *session.Session { pushHandlers(&s.Handlers, filename) return s } 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 { logger.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 { logger.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 { 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 { logger.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 { logger.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 { logger.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 } } }
443
aws-xray-sdk-go
aws
Go
// 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" "encoding/json" "net/http" "net/http/httptest" "sync" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/lambda" "github.com/stretchr/testify/assert" ) func TestAWS(t *testing.T) { // Runs a suite of tests against two different methods of registering // handlers on an AWS client. type test func(context.Context, *TestDaemon, *testing.T, *lambda.Lambda) tests := []struct { name string test test failConn bool }{ {"failed connection", testClientFailedConnection, true}, {"successful connection", testClientSuccessfulConnection, false}, {"without segment", testClientWithoutSegment, false}, {"test data race", testAWSDataRace, false}, } onClient := func(s *session.Session) *lambda.Lambda { svc := lambda.New(s) AWS(svc.Client) return svc } onSession := func(s *session.Session) *lambda.Lambda { return lambda.New(AWSSession(s)) } const whitelist = "../resources/AWSWhitelist.json" onClientWithWhitelist := func(s *session.Session) *lambda.Lambda { svc := lambda.New(s) AWSWithWhitelist(svc.Client, whitelist) return svc } onSessionWithWhitelist := func(s *session.Session) *lambda.Lambda { return lambda.New(AWSSessionWithWhitelist(s, whitelist)) } type constructor func(*session.Session) *lambda.Lambda constructors := []struct { name string constructor constructor }{ {"AWS()", onClient}, {"AWSSession()", onSession}, {"AWSWithWhitelist()", onClientWithWhitelist}, {"AWSSessionWithWhitelist()", onSessionWithWhitelist}, } // Run all combinations of constructors + tests. for _, cons := range constructors { cons := cons t.Run(cons.name, func(t *testing.T) { for _, test := range tests { test := test ctx, td := NewTestDaemon() defer td.Close() t.Run(test.name, func(t *testing.T) { session, cleanup := fakeSession(t, test.failConn) defer cleanup() test.test(ctx, td, t, cons.constructor(session)) }) } }) } } func fakeSession(t *testing.T, failConn bool) (*session.Session, func()) { var maxRetries = 0 cfg := &aws.Config{ Region: aws.String("fake-moon-1"), Credentials: credentials.NewStaticCredentials("akid", "secret", "noop"), MaxRetries: &maxRetries, } var ts *httptest.Server if !failConn { ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { b := []byte(`{}`) w.WriteHeader(http.StatusOK) w.Write(b) })) cfg.Endpoint = aws.String(ts.URL) } s, err := session.NewSession(cfg) assert.NoError(t, err) return s, func() { if ts != nil { ts.Close() } } } func testClientSuccessfulConnection(ctx context.Context, td *TestDaemon, t *testing.T, svc *lambda.Lambda) { ctx, root := BeginSegment(ctx, "Test") _, err := svc.ListFunctionsWithContext(ctx, &lambda.ListFunctionsInput{}) root.Close(nil) assert.NoError(t, err) seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if !assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { return } assert.False(t, subseg.Fault) assert.NotEmpty(t, subseg.Subsegments) attemptSubseg := &Segment{} for _, sub := range subseg.Subsegments { tempSeg := &Segment{} assert.NoError(t, json.Unmarshal(sub, &tempSeg)) if tempSeg.Name == "attempt" { attemptSubseg = tempSeg break } } assert.Equal(t, "attempt", attemptSubseg.Name) assert.Zero(t, attemptSubseg.openSegments) // Connect subsegment will contain multiple child subsegments. // The subsegment should fail since the endpoint is not valid, // and should not be InProgress. connectSubseg := &Segment{} assert.NotEmpty(t, attemptSubseg.Subsegments) assert.NoError(t, json.Unmarshal(attemptSubseg.Subsegments[0], &connectSubseg)) assert.Equal(t, "connect", connectSubseg.Name) assert.False(t, connectSubseg.InProgress) assert.NotZero(t, connectSubseg.EndTime) assert.NotEmpty(t, connectSubseg.Subsegments) // Ensure that the 'connect' subsegments are completed. for _, sub := range connectSubseg.Subsegments { tempSeg := &Segment{} assert.NoError(t, json.Unmarshal(sub, &tempSeg)) assert.False(t, tempSeg.InProgress) assert.NotZero(t, tempSeg.EndTime) } } func testClientFailedConnection(ctx context.Context, td *TestDaemon, t *testing.T, svc *lambda.Lambda) { ctx, root := BeginSegment(ctx, "Test") _, err := svc.ListFunctionsWithContext(ctx, &lambda.ListFunctionsInput{}) root.Close(nil) assert.Error(t, err) seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if !assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { return } assert.True(t, subseg.Fault) // Should contain 'marshal' and 'attempt' subsegments only. assert.Len(t, subseg.Subsegments, 3) attemptSubseg := &Segment{} assert.NoError(t, json.Unmarshal(subseg.Subsegments[1], &attemptSubseg)) assert.Equal(t, "attempt", attemptSubseg.Name) assert.Zero(t, attemptSubseg.openSegments) // Connect subsegment will contain multiple child subsegments. // The subsegment should fail since the endpoint is not valid, // and should not be InProgress. connectSubseg := &Segment{} assert.NotEmpty(t, attemptSubseg.Subsegments) assert.NoError(t, json.Unmarshal(attemptSubseg.Subsegments[0], &connectSubseg)) assert.Equal(t, "connect", connectSubseg.Name) assert.False(t, connectSubseg.InProgress) assert.NotZero(t, connectSubseg.EndTime) assert.NotEmpty(t, connectSubseg.Subsegments) } func testClientWithoutSegment(ctx context.Context, td *TestDaemon, t *testing.T, svc *lambda.Lambda) { _, err := svc.ListFunctionsWithContext(ctx, &lambda.ListFunctionsInput{}) assert.NoError(t, err) } func testAWSDataRace(ctx context.Context, td *TestDaemon, t *testing.T, svc *lambda.Lambda) { ctx, cancel := context.WithCancel(ctx) defer cancel() ctx, seg := BeginSegment(ctx, "TestSegment") var wg sync.WaitGroup for i := 0; i < 5; i++ { if i != 3 && i != 2 { wg.Add(1) } go func(i int) { if i != 3 && i != 2 { time.Sleep(time.Nanosecond) defer wg.Done() } _, seg := BeginSubsegment(ctx, "TestSubsegment1") time.Sleep(time.Nanosecond) seg.Close(nil) svc.ListFunctionsWithContext(ctx, &lambda.ListFunctionsInput{}) if i == 3 || i == 2 { cancel() // cancel context } }(i) } wg.Wait() seg.Close(nil) }
242
aws-xray-sdk-go
aws
Go
// 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 }
62
aws-xray-sdk-go
aws
Go
// 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" "encoding/json" "errors" "sync" "testing" "github.com/aws/aws-xray-sdk-go/strategy/exception" "github.com/stretchr/testify/assert" ) func TestSimpleCapture(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, root := BeginSegment(ctx, "Test") err := Capture(ctx, "TestService", func(context.Context) error { root.Close(nil) return nil }) assert.NoError(t, err) seg, err := td.Recv() if !assert.NoError(t, err) { return } assert.Equal(t, "Test", seg.Name) assert.Equal(t, root.TraceID, seg.TraceID) assert.Equal(t, root.ID, seg.ID) assert.Equal(t, root.StartTime, seg.StartTime) assert.Equal(t, root.EndTime, seg.EndTime) assert.NotNil(t, seg.Subsegments) var subseg *Segment if assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { assert.Equal(t, "TestService", subseg.Name) } } func TestErrorCapture(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, root := BeginSegment(ctx, "Test") defaultStrategy, err := exception.NewDefaultFormattingStrategy() if !assert.NoError(t, err) { return } captureErr := Capture(ctx, "ErrorService", func(context.Context) error { defer root.Close(nil) return defaultStrategy.Error("MyError") }) if !assert.Error(t, captureErr) { return } seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if !assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { return } assert.Equal(t, captureErr.Error(), subseg.Cause.Exceptions[0].Message) assert.Equal(t, true, subseg.Fault) assert.Equal(t, "error", subseg.Cause.Exceptions[0].Type) assert.Equal(t, "TestErrorCapture.func1", subseg.Cause.Exceptions[0].Stack[0].Label) assert.Equal(t, "Capture", subseg.Cause.Exceptions[0].Stack[1].Label) } func TestPanicCapture(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, root := BeginSegment(ctx, "Test") var captureErr error func() { defer func() { if p := recover(); p != nil { captureErr = errors.New(p.(string)) } root.Close(captureErr) }() _ = Capture(ctx, "PanicService", func(context.Context) error { panic("MyPanic") }) }() seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if !assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { return } assert.Equal(t, captureErr.Error(), subseg.Cause.Exceptions[0].Message) assert.Equal(t, "panic", subseg.Cause.Exceptions[0].Type) assert.Equal(t, "TestPanicCapture.func1.2", subseg.Cause.Exceptions[0].Stack[0].Label) assert.Equal(t, "Capture", subseg.Cause.Exceptions[0].Stack[1].Label) assert.Equal(t, "TestPanicCapture.func1", subseg.Cause.Exceptions[0].Stack[2].Label) assert.Equal(t, "TestPanicCapture", subseg.Cause.Exceptions[0].Stack[3].Label) } func TestNoSegmentCapture(t *testing.T) { ctx, _ := NewTestDaemon() _, seg := BeginSubsegment(ctx, "Name") seg.Close(nil) } func TestCaptureAsync(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() var wg sync.WaitGroup wg.Add(1) ctx, root := BeginSegment(ctx, "Test") CaptureAsync(ctx, "TestService", func(context.Context) error { defer wg.Done() root.Close(nil) return nil }) seg, err := td.Recv() if !assert.NoError(t, err) { return } wg.Wait() assert.Equal(t, "Test", seg.Name) assert.Equal(t, root.TraceID, seg.TraceID) assert.Equal(t, root.ID, seg.ID) assert.Equal(t, root.StartTime, seg.StartTime) assert.Equal(t, root.EndTime, seg.EndTime) assert.NotNil(t, seg.Subsegments) var subseg *Segment if assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { assert.Equal(t, "TestService", subseg.Name) } } // Benchmarks func BenchmarkCapture(b *testing.B) { ctx, seg := BeginSegment(context.Background(), "TestCaptureSeg") for i := 0; i < b.N; i++ { Capture(ctx, "TestCaptureSubSeg", func(ctx context.Context) error { return nil }) } seg.Close(nil) }
162
aws-xray-sdk-go
aws
Go
// 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" "net/url" "strconv" "github.com/aws/aws-xray-sdk-go/internal/logger" ) 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) logger.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 = stripQueryFromURL(*r.URL) r.Header.Set(TraceIDHeaderKey, 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 } func stripQueryFromURL(u url.URL) string { u.RawQuery = "" return u.String() }
126
aws-xray-sdk-go
aws
Go
// 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" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/http/httptest" "sync" "testing" "github.com/stretchr/testify/assert" "golang.org/x/net/http2" ) func newRequest(ctx context.Context, method, url string, body io.Reader) (context.Context, *Segment, *http.Request, error) { req, err := http.NewRequest(method, url, body) if err != nil { return nil, nil, nil, err } ctx, root := BeginSegment(ctx, "Test") req = req.WithContext(ctx) return ctx, root, req, nil } func httpDoTest(ctx context.Context, client *http.Client, method, url string, body io.Reader) error { _, root, req, err := newRequest(ctx, method, url, body) if err != nil { return err } defer root.Close(nil) resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() _, _ = io.Copy(ioutil.Discard, resp.Body) return nil } func TestNilClient(t *testing.T) { c := Client(nil) assert.Equal(t, http.DefaultClient.Jar, c.Jar) assert.Equal(t, http.DefaultClient.Timeout, c.Timeout) assert.Equal(t, &roundtripper{Base: http.DefaultTransport}, c.Transport) } func TestRoundTripper(t *testing.T) { ht := http.DefaultTransport rt := RoundTripper(ht) assert.Equal(t, &roundtripper{Base: http.DefaultTransport}, rt) } func TestRoundTrip(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() const content = `200 - Nothing to see` const responseContentLength = len(content) ch := make(chan XRayHeaders, 1) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ch <- ParseHeadersForTest(r.Header) w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte(content)); err != nil { panic(err) } })) defer ts.Close() client := Client(nil) err := httpDoTest(ctx, client, http.MethodGet, ts.URL, nil) if !assert.NoError(t, err) { return } seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, http.MethodGet, subseg.HTTP.Request.Method) assert.Equal(t, ts.URL, subseg.HTTP.Request.URL) assert.Equal(t, http.StatusOK, subseg.HTTP.Response.Status) assert.Equal(t, responseContentLength, subseg.HTTP.Response.ContentLength) assert.False(t, subseg.Throttle) assert.False(t, subseg.Error) assert.False(t, subseg.Fault) } headers := <-ch assert.Equal(t, headers.RootTraceID, seg.TraceID) var connectSeg *Segment for _, sub := range subseg.Subsegments { var seg *Segment if !assert.NoError(t, json.Unmarshal(sub, &seg)) { continue } if seg.Name == "connect" { connectSeg = seg } } // Ensure that a 'connect' subsegment was created and closed assert.Equal(t, "connect", connectSeg.Name) assert.False(t, connectSeg.InProgress) assert.NotZero(t, connectSeg.EndTime) assert.NotEmpty(t, connectSeg.Subsegments) // Ensure that the 'connect' subsegments are completed. for _, sub := range connectSeg.Subsegments { var seg *Segment if !assert.NoError(t, json.Unmarshal(sub, &seg)) { continue } assert.False(t, seg.InProgress) assert.NotZero(t, seg.EndTime) } } func TestRoundTripWithQueryParameter(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() const content = `200 - Nothing to see` const responseContentLength = len(content) const queryParam = `?key=value` ch := make(chan XRayHeaders, 1) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Contains(t, r.URL.String(), queryParam) ch <- ParseHeadersForTest(r.Header) w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte(content)); err != nil { panic(err) } })) defer ts.Close() client := Client(nil) err := httpDoTest(ctx, client, http.MethodGet, ts.URL+queryParam, nil) if !assert.NoError(t, err) { return } seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, http.MethodGet, subseg.HTTP.Request.Method) assert.Equal(t, ts.URL, subseg.HTTP.Request.URL) assert.Equal(t, http.StatusOK, subseg.HTTP.Response.Status) assert.Equal(t, responseContentLength, subseg.HTTP.Response.ContentLength) assert.False(t, subseg.Throttle) assert.False(t, subseg.Error) assert.False(t, subseg.Fault) } headers := <-ch assert.Equal(t, headers.RootTraceID, seg.TraceID) } func TestRoundTripWithError(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() const content = `403 - Nothing to see` const responseContentLength = len(content) ch := make(chan XRayHeaders, 1) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ch <- ParseHeadersForTest(r.Header) w.WriteHeader(http.StatusForbidden) if _, err := w.Write([]byte(content)); err != nil { panic(err) } })) defer ts.Close() client := Client(nil) err := httpDoTest(ctx, client, http.MethodGet, ts.URL, nil) if !assert.NoError(t, err) { return } seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, http.MethodGet, subseg.HTTP.Request.Method) assert.Equal(t, ts.URL, subseg.HTTP.Request.URL) assert.Equal(t, http.StatusForbidden, subseg.HTTP.Response.Status) assert.Equal(t, responseContentLength, subseg.HTTP.Response.ContentLength) assert.False(t, subseg.Throttle) assert.True(t, subseg.Error) assert.False(t, subseg.Fault) } headers := <-ch assert.Equal(t, headers.RootTraceID, seg.TraceID) } func TestRoundTripWithThrottle(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() const content = `429 - Nothing to see` const responseContentLength = len(content) ch := make(chan XRayHeaders, 1) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ch <- ParseHeadersForTest(r.Header) w.WriteHeader(http.StatusTooManyRequests) if _, err := w.Write([]byte(content)); err != nil { panic(err) } })) defer ts.Close() client := Client(nil) err := httpDoTest(ctx, client, http.MethodGet, ts.URL, nil) if !assert.NoError(t, err) { return } seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, http.MethodGet, subseg.HTTP.Request.Method) assert.Equal(t, ts.URL, subseg.HTTP.Request.URL) assert.Equal(t, http.StatusTooManyRequests, subseg.HTTP.Response.Status) assert.Equal(t, responseContentLength, subseg.HTTP.Response.ContentLength) assert.True(t, subseg.Throttle) assert.True(t, subseg.Error) assert.False(t, subseg.Fault) } headers := <-ch assert.Equal(t, headers.RootTraceID, seg.TraceID) } func TestRoundTripFault(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() const content = `503 - Nothing to see` const responseContentLength = len(content) ch := make(chan XRayHeaders, 1) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ch <- ParseHeadersForTest(r.Header) w.WriteHeader(http.StatusServiceUnavailable) if _, err := w.Write([]byte(content)); err != nil { panic(err) } })) defer ts.Close() client := Client(nil) err := httpDoTest(ctx, client, http.MethodGet, ts.URL, nil) if !assert.NoError(t, err) { return } seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, http.MethodGet, subseg.HTTP.Request.Method) assert.Equal(t, ts.URL, subseg.HTTP.Request.URL) assert.Equal(t, http.StatusServiceUnavailable, subseg.HTTP.Response.Status) assert.Equal(t, responseContentLength, subseg.HTTP.Response.ContentLength) assert.False(t, subseg.Throttle) assert.False(t, subseg.Error) assert.True(t, subseg.Fault) } headers := <-ch assert.Equal(t, headers.RootTraceID, seg.TraceID) } func TestBadRoundTrip(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() client := Client(nil) doErr := httpDoTest(ctx, client, http.MethodGet, "unknown-scheme://localhost:8000", nil) assert.Error(t, doErr) seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { assert.Contains(t, fmt.Sprintf("%v", doErr), subseg.Cause.Exceptions[0].Message) } } func TestBadRoundTripDial(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() client := Client(nil) doErr := httpDoTest(ctx, client, http.MethodGet, "http://domain.invalid:8000", nil) assert.Error(t, doErr) seg, err := td.Recv() if !assert.NoError(t, err) { return } var subseg *Segment if assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) { assert.Contains(t, fmt.Sprintf("%v", doErr), subseg.Cause.Exceptions[0].Message) // Also ensure that the 'connect' subsegment is closed and showing fault var connectSeg *Segment if assert.NoError(t, json.Unmarshal(subseg.Subsegments[0], &connectSeg)) { assert.Equal(t, "connect", connectSeg.Name) assert.NotZero(t, connectSeg.EndTime) assert.False(t, connectSeg.InProgress) assert.True(t, connectSeg.Fault) assert.NotEmpty(t, connectSeg.Subsegments) } } } func TestRoundTripReuseDatarace(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte(`200 - Nothing to see`)); err != nil { panic(err) } })) defer ts.Close() client := Client(nil) var wg sync.WaitGroup n := 100 wg.Add(n) for i := 0; i < n; i++ { go func() { defer wg.Done() ctx, cancel := context.WithCancel(ctx) defer cancel() err := httpDoTest(ctx, client, http.MethodGet, ts.URL, nil) assert.NoError(t, err) }() } wg.Wait() } func TestRoundTripReuseTLSDatarace(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte(`200 - Nothing to see`)); err != nil { panic(err) } })) defer ts.Close() client := Client(ts.Client()) var wg sync.WaitGroup n := 100 wg.Add(n) for i := 0; i < n; i++ { go func() { defer wg.Done() ctx, cancel := context.WithCancel(ctx) defer cancel() err := httpDoTest(ctx, client, http.MethodGet, ts.URL, nil) assert.NoError(t, err) }() } wg.Wait() } func TestRoundTripReuseHTTP2Datarace(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !r.ProtoAtLeast(2, 0) { panic("want http/2, got " + r.Proto) } w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte(`200 - Nothing to see`)); err != nil { panic(err) } })) // configure http/2 if err := http2.ConfigureServer(ts.Config, nil); !assert.NoError(t, err) { return } ts.TLS = ts.Config.TLSConfig ts.StartTLS() defer ts.Close() client := ts.Client() if err := http2.ConfigureTransport(client.Transport.(*http.Transport)); !assert.NoError(t, err) { return } client = Client(client) var wg sync.WaitGroup n := 100 wg.Add(n) for i := 0; i < n; i++ { go func() { defer wg.Done() ctx, cancel := context.WithCancel(ctx) defer cancel() err := httpDoTest(ctx, client, http.MethodGet, ts.URL, nil) assert.NoError(t, err) }() } wg.Wait() } // Benchmarks func BenchmarkClient(b *testing.B) { for i := 0; i < b.N; i++ { Client(nil) } }
463
aws-xray-sdk-go
aws
Go
// 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" "os" "sync" "github.com/aws/aws-xray-sdk-go/daemoncfg" "github.com/aws/aws-xray-sdk-go/internal/logger" "github.com/aws/aws-xray-sdk-go/xraylog" "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" ) // SDKVersion records the current X-Ray Go SDK version. const SDKVersion = "1.8.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"` RuleName string `json:"sampling_rule_name,omitempty"` } // SetLogger sets the logger instance used by xray. // Only set from init() functions as SetLogger is not goroutine safe. func SetLogger(l xraylog.Logger) { logger.Logger = l } var globalCfg = newGlobalConfig() func newGlobalConfig() *globalConfig { ret := &globalConfig{} daemonEndpoint, err := daemoncfg.GetDaemonEndpointsFromEnv() if err != nil { panic(err) } if daemonEndpoint == nil { daemonEndpoint = daemoncfg.GetDefaultDaemonEndpoints() } ret.daemonAddr = daemonEndpoint.UDPAddr ss, err := sampling.NewCentralizedStrategy() 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 emt, err := NewDefaultEmitter(ret.daemonAddr) if err != nil { panic(err) } ret.emitter = emt cms := os.Getenv("AWS_XRAY_CONTEXT_MISSING") if cms != "" { if cms == ctxmissing.RuntimeErrorStrategy { cm := ctxmissing.NewDefaultRuntimeErrorStrategy() ret.contextMissingStrategy = cm } else if cms == ctxmissing.LogErrorStrategy { cm := ctxmissing.NewDefaultLogErrorStrategy() ret.contextMissingStrategy = cm } else if cms == ctxmissing.IgnoreErrorStrategy { cm := ctxmissing.NewDefaultIgnoreErrorStrategy() ret.contextMissingStrategy = cm } } else { cm := ctxmissing.NewDefaultLogErrorStrategy() ret.contextMissingStrategy = cm } return ret } type globalConfig struct { sync.RWMutex daemonAddr *net.UDPAddr emitter Emitter serviceVersion string samplingStrategy sampling.Strategy streamingStrategy StreamingStrategy exceptionFormattingStrategy exception.FormattingStrategy contextMissingStrategy ctxmissing.Strategy } // Config is a set of X-Ray configurations. type Config struct { DaemonAddr string ServiceVersion string Emitter Emitter SamplingStrategy sampling.Strategy StreamingStrategy StreamingStrategy ExceptionFormattingStrategy exception.FormattingStrategy ContextMissingStrategy ctxmissing.Strategy // LogLevel and LogFormat are deprecated and no longer have any effect. // See SetLogger() and the associated xraylog.Logger interface to control // logging. 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 daemonEndpoints, er := daemoncfg.GetDaemonEndpointsFromString(c.DaemonAddr) if daemonEndpoints != nil { if c.Emitter != nil { c.Emitter.RefreshEmitterWithAddress(daemonEndpoints.UDPAddr) } if c.SamplingStrategy != nil { configureStrategy(c.SamplingStrategy, daemonEndpoints) } } else if er != nil { errors = append(errors, er) } 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 } else if cms == ctxmissing.IgnoreErrorStrategy { cm := ctxmissing.NewDefaultIgnoreErrorStrategy() c.ContextMissingStrategy = cm } } 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 } func configureStrategy(s sampling.Strategy, daemonEndpoints *daemoncfg.DaemonEndpoints) { if s == nil { return } strategy, ok := s.(*sampling.CentralizedStrategy) if ok { strategy.LoadDaemonEndpoints(daemonEndpoints) } } // Configure overrides default configuration options with customer-defined values. func Configure(c Config) error { globalCfg.Lock() defer globalCfg.Unlock() var errors exception.MultiError if c.SamplingStrategy != nil { globalCfg.samplingStrategy = c.SamplingStrategy } if c.Emitter != nil { globalCfg.emitter = c.Emitter } daemonEndpoints, er := daemoncfg.GetDaemonEndpointsFromString(c.DaemonAddr) if daemonEndpoints != nil { globalCfg.daemonAddr = daemonEndpoints.UDPAddr globalCfg.emitter.RefreshEmitterWithAddress(globalCfg.daemonAddr) configureStrategy(globalCfg.samplingStrategy, daemonEndpoints) } else if er != nil { errors = append(errors, er) } 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 cms == ctxmissing.IgnoreErrorStrategy { cm := ctxmissing.NewDefaultIgnoreErrorStrategy() globalCfg.contextMissingStrategy = cm } } else if c.ContextMissingStrategy != nil { globalCfg.contextMissingStrategy = c.ContextMissingStrategy } if c.ServiceVersion != "" { globalCfg.serviceVersion = c.ServiceVersion } switch len(errors) { case 0: return nil case 1: return errors[0] default: return errors } } 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 }
283
aws-xray-sdk-go
aws
Go
// 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" "strings" "testing" "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" "github.com/stretchr/testify/assert" ) type TestSamplingStrategy struct{} type TestExceptionFormattingStrategy struct{} type TestStreamingStrategy struct{} type TestContextMissingStrategy struct{} type TestEmitter struct{} func (tss *TestSamplingStrategy) ShouldTrace(request *sampling.Request) *sampling.Decision { return &sampling.Decision{ Sample: true, } } func (tefs *TestExceptionFormattingStrategy) Error(message string) *exception.XRayError { return &exception.XRayError{} } func (tefs *TestExceptionFormattingStrategy) Errorf(message string, args ...interface{}) *exception.XRayError { return &exception.XRayError{} } func (tefs *TestExceptionFormattingStrategy) Panic(message string) *exception.XRayError { return &exception.XRayError{} } func (tefs *TestExceptionFormattingStrategy) Panicf(message string, args ...interface{}) *exception.XRayError { return &exception.XRayError{} } func (tefs *TestExceptionFormattingStrategy) ExceptionFromError(err error) exception.Exception { return exception.Exception{} } func (sms *TestStreamingStrategy) RequiresStreaming(seg *Segment) bool { return false } func (sms *TestStreamingStrategy) StreamCompletedSubsegments(seg *Segment) [][]byte { var test [][]byte return test } func (te *TestEmitter) Emit(seg *Segment) {} func (te *TestEmitter) RefreshEmitterWithAddress(raddr *net.UDPAddr) {} func (cms *TestContextMissingStrategy) ContextMissing(v interface{}) { fmt.Printf("Test ContextMissing Strategy %v\n", v) } func stashEnv() []string { env := os.Environ() os.Clearenv() return env } func popEnv(env []string) { os.Clearenv() for _, e := range env { p := strings.SplitN(e, "=", 2) os.Setenv(p[0], p[1]) } } func ResetConfig() { ss, _ := sampling.NewCentralizedStrategy() efs, _ := exception.NewDefaultFormattingStrategy() sms, _ := NewDefaultStreamingStrategy() cms := ctxmissing.NewDefaultRuntimeErrorStrategy() udpAddr := &net.UDPAddr{ IP: net.IPv4(127, 0, 0, 1), Port: 2000, } e, _ := NewDefaultEmitter(udpAddr) Configure(Config{ DaemonAddr: "127.0.0.1:2000", LogLevel: "info", LogFormat: "%Date(2006-01-02T15:04:05Z07:00) [%Level] %Msg%n", SamplingStrategy: ss, StreamingStrategy: sms, Emitter: e, ExceptionFormattingStrategy: efs, ContextMissingStrategy: cms, }) } func TestEnvironmentDaemonAddress(t *testing.T) { os.Setenv("AWS_XRAY_DAEMON_ADDRESS", "192.168.2.100:2000") defer os.Unsetenv("AWS_XRAY_DAEMON_ADDRESS") cfg := newGlobalConfig() daemonAddr := &net.UDPAddr{IP: net.IPv4(192, 168, 2, 100), Port: 2000} assert.Equal(t, daemonAddr, cfg.daemonAddr) } func TestInvalidEnvironmentDaemonAddress(t *testing.T) { os.Setenv("AWS_XRAY_DAEMON_ADDRESS", "This is not a valid address") defer os.Unsetenv("AWS_XRAY_DAEMON_ADDRESS") assert.Panics(t, func() { _ = newGlobalConfig() }) } func TestDefaultConfigureParameters(t *testing.T) { daemonAddr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 2000} efs, _ := exception.NewDefaultFormattingStrategy() sms, _ := NewDefaultStreamingStrategy() cms := ctxmissing.NewDefaultLogErrorStrategy() assert.Equal(t, daemonAddr, globalCfg.daemonAddr) assert.Equal(t, efs, globalCfg.exceptionFormattingStrategy) assert.Equal(t, "", globalCfg.serviceVersion) assert.Equal(t, sms, globalCfg.streamingStrategy) assert.Equal(t, cms, globalCfg.contextMissingStrategy) } func TestSetConfigureParameters(t *testing.T) { daemonAddr := "127.0.0.1:3000" logLevel := "error" logFormat := "[%Level] %Msg%n" serviceVersion := "TestVersion" ss := &TestSamplingStrategy{} efs := &TestExceptionFormattingStrategy{} sms := &TestStreamingStrategy{} cms := &TestContextMissingStrategy{} Configure(Config{ DaemonAddr: daemonAddr, ServiceVersion: serviceVersion, SamplingStrategy: ss, ExceptionFormattingStrategy: efs, StreamingStrategy: sms, ContextMissingStrategy: cms, LogLevel: logLevel, LogFormat: logFormat, }) assert.Equal(t, &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 3000}, globalCfg.daemonAddr) assert.Equal(t, ss, globalCfg.samplingStrategy) assert.Equal(t, efs, globalCfg.exceptionFormattingStrategy) assert.Equal(t, sms, globalCfg.streamingStrategy) assert.Equal(t, cms, globalCfg.contextMissingStrategy) assert.Equal(t, serviceVersion, globalCfg.serviceVersion) ResetConfig() } func TestSetDaemonAddressEnvironmentVariable(t *testing.T) { env := stashEnv() defer popEnv(env) daemonAddr := "127.0.0.1:3000" os.Setenv("AWS_XRAY_DAEMON_ADDRESS", "127.0.0.1:4000") Configure(Config{DaemonAddr: daemonAddr}) assert.Equal(t, &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 4000}, globalCfg.daemonAddr) os.Unsetenv("AWS_XRAY_DAEMON_ADDRESS") ResetConfig() } func TestSetContextMissingEnvironmentVariable(t *testing.T) { env := stashEnv() defer popEnv(env) cms := ctxmissing.NewDefaultLogErrorStrategy() r := ctxmissing.NewDefaultRuntimeErrorStrategy() os.Setenv("AWS_XRAY_CONTEXT_MISSING", "RUNTIME_ERROR") Configure(Config{ContextMissingStrategy: cms}) assert.Equal(t, r, globalCfg.contextMissingStrategy) os.Unsetenv("AWS_XRAY_CONTEXT_MISSING") ResetConfig() } func TestConfigureWithContext(t *testing.T) { daemonAddr := "127.0.0.1:3000" logLevel := "error" logFormat := "[%Level] %Msg%n" serviceVersion := "TestVersion" ss := &TestSamplingStrategy{} efs := &TestExceptionFormattingStrategy{} sms := &TestStreamingStrategy{} cms := &TestContextMissingStrategy{} de := &TestEmitter{} ctx, err := ContextWithConfig(context.Background(), Config{ DaemonAddr: daemonAddr, ServiceVersion: serviceVersion, SamplingStrategy: ss, ExceptionFormattingStrategy: efs, StreamingStrategy: sms, Emitter: de, ContextMissingStrategy: cms, LogLevel: logLevel, LogFormat: logFormat, }) cfg := GetRecorder(ctx) assert.Nil(t, err) assert.Equal(t, daemonAddr, cfg.DaemonAddr) assert.Equal(t, logLevel, cfg.LogLevel) assert.Equal(t, logFormat, cfg.LogFormat) assert.Equal(t, ss, cfg.SamplingStrategy) assert.Equal(t, efs, cfg.ExceptionFormattingStrategy) assert.Equal(t, sms, cfg.StreamingStrategy) assert.Equal(t, de, cfg.Emitter) assert.Equal(t, cms, cfg.ContextMissingStrategy) assert.Equal(t, serviceVersion, cfg.ServiceVersion) ResetConfig() } func TestSelectiveConfigWithContext(t *testing.T) { daemonAddr := "127.0.0.1:3000" serviceVersion := "TestVersion" cms := &TestContextMissingStrategy{} ctx, err := ContextWithConfig(context.Background(), Config{ DaemonAddr: daemonAddr, ServiceVersion: serviceVersion, ContextMissingStrategy: cms, }) cfg := GetRecorder(ctx) assert.Nil(t, err) assert.Equal(t, daemonAddr, cfg.DaemonAddr) assert.Equal(t, cms, cfg.ContextMissingStrategy) assert.Equal(t, serviceVersion, cfg.ServiceVersion) ResetConfig() } // Benchmarks func BenchmarkConfigure(b *testing.B) { logLevel := "error" logFormat := "[%Level] %Msg%n" serviceVersion := "TestVersion" ss := &TestSamplingStrategy{} efs := &TestExceptionFormattingStrategy{} sms := &TestStreamingStrategy{} cms := &TestContextMissingStrategy{} configure := Config{ ServiceVersion: serviceVersion, SamplingStrategy: ss, ExceptionFormattingStrategy: efs, StreamingStrategy: sms, ContextMissingStrategy: cms, LogLevel: logLevel, LogFormat: logFormat, } for i := 0; i < b.N; i++ { Configure(configure) } }
286
aws-xray-sdk-go
aws
Go
// 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{} const ( // fasthttpContextKey records the key for Segment value // this was necessary because fasthttp only accepts strings as keys in contexts fasthttpContextKey = "xray-ck" // fasthttpContextConfigKey records the key for Config value fasthttpContextConfigKey = "xray-rck" ) // 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 } if r, ok := ctx.Value(fasthttpContextConfigKey).(*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 } if seg, ok := ctx.Value(fasthttpContextKey).(*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 := GetSegment(ctx); seg != nil { 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 }
128
aws-xray-sdk-go
aws
Go
// 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" "testing" "github.com/aws/aws-xray-sdk-go/strategy/exception" "github.com/stretchr/testify/assert" ) func TestTraceID(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "test") defer seg.Close(nil) traceID := TraceID(ctx) assert.Equal(t, seg.TraceID, traceID) } func TestEmptyTraceID(t *testing.T) { traceID := TraceID(context.Background()) assert.Empty(t, traceID) } func TestRequestWasNotTraced(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "test") defer seg.Close(nil) assert.Equal(t, seg.RequestWasTraced, RequestWasTraced(ctx)) } func TestDetachContext(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, cancel := context.WithCancel(ctx) defer cancel() ctx1, seg := BeginSegment(ctx, "test") defer seg.Close(nil) ctx2 := DetachContext(ctx1) cancel() assert.Equal(t, seg, GetSegment(ctx2)) select { case <-ctx2.Done(): assert.Error(t, ctx2.Err()) default: // ctx1 is canceled, but ctx2 is not. } } func TestValidAnnotations(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, root := BeginSegment(ctx, "Test") var err exception.MultiError if e := AddAnnotation(ctx, "string", "str"); e != nil { err = append(err, e) } if e := AddAnnotation(ctx, "int", 1); e != nil { err = append(err, e) } if e := AddAnnotation(ctx, "bool", true); e != nil { err = append(err, e) } if e := AddAnnotation(ctx, "float", 1.1); e != nil { err = append(err, e) } root.Close(err) seg, e := td.Recv() if !assert.NoError(t, e) { return } assert.Equal(t, "str", seg.Annotations["string"]) assert.Equal(t, 1.0, seg.Annotations["int"]) //json encoder turns this into a float64 assert.Equal(t, 1.1, seg.Annotations["float"]) assert.Equal(t, true, seg.Annotations["bool"]) } func TestInvalidAnnotations(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, root := BeginSegment(ctx, "Test") type MyObject struct{} err := AddAnnotation(ctx, "Object", &MyObject{}) root.Close(err) assert.Error(t, err) seg, err := td.Recv() if assert.NoError(t, err) { assert.NotContains(t, seg.Annotations, "Object") } } func TestSimpleMetadata(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, root := BeginSegment(ctx, "Test") var err exception.MultiError if e := AddMetadata(ctx, "string", "str"); e != nil { err = append(err, e) } if e := AddMetadata(ctx, "int", 1); e != nil { err = append(err, e) } if e := AddMetadata(ctx, "bool", true); e != nil { err = append(err, e) } if e := AddMetadata(ctx, "float", 1.1); e != nil { err = append(err, e) } assert.Nil(t, err) root.Close(err) seg, e := td.Recv() if !assert.NoError(t, e) { return } assert.Equal(t, "str", seg.Metadata["default"]["string"]) assert.Equal(t, 1.0, seg.Metadata["default"]["int"]) //json encoder turns this into a float64 assert.Equal(t, 1.1, seg.Metadata["default"]["float"]) assert.Equal(t, true, seg.Metadata["default"]["bool"]) } func TestAddError(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, root := BeginSegment(ctx, "Test") err := AddError(ctx, errors.New("New Error")) assert.NoError(t, err) root.Close(err) seg, err := td.Recv() if !assert.NoError(t, err) { return } assert.Equal(t, "New Error", seg.Cause.Exceptions[0].Message) assert.Equal(t, "errors.errorString", seg.Cause.Exceptions[0].Type) } // Benchmarks func BenchmarkGetRecorder(b *testing.B) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "TestSeg") for i := 0; i < b.N; i++ { GetRecorder(ctx) } seg.Close(nil) } func BenchmarkGetSegment(b *testing.B) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "TestSeg") for i := 0; i < b.N; i++ { GetSegment(ctx) } seg.Close(nil) } func BenchmarkDetachContext(b *testing.B) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "TestSeg") for i := 0; i < b.N; i++ { DetachContext(ctx) } seg.Close(nil) } func BenchmarkAddAnnotation(b *testing.B) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "TestSeg") for i := 0; i < b.N; i++ { err := AddAnnotation(ctx, "key", "value") if err != nil { return } } seg.Close(nil) } func BenchmarkAddMetadata(b *testing.B) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "TestSeg") for i := 0; i < b.N; i++ { err := AddMetadata(ctx, "key", "value") if err != nil { return } } seg.Close(nil) }
218
aws-xray-sdk-go
aws
Go
// 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" "net" "sync" "github.com/aws/aws-xray-sdk-go/internal/logger" ) // Header is added before sending segments to daemon. const Header = `{"format": "json", "version": 1}` + "\n" // DefaultEmitter provides the naive implementation of emitting trace entities. type DefaultEmitter struct { sync.Mutex conn *net.UDPConn addr *net.UDPAddr } // NewDefaultEmitter initializes and returns a // pointer to an instance of DefaultEmitter. func NewDefaultEmitter(raddr *net.UDPAddr) (*DefaultEmitter, error) { initLambda() d := &DefaultEmitter{addr: raddr} return d, nil } // RefreshEmitterWithAddress dials UDP based on the input UDP address. func (de *DefaultEmitter) RefreshEmitterWithAddress(raddr *net.UDPAddr) { de.Lock() de.refresh(raddr) de.Unlock() } func (de *DefaultEmitter) refresh(raddr *net.UDPAddr) (err error) { de.conn, err = net.DialUDP("udp", nil, raddr) de.addr = raddr if err != nil { logger.Errorf("Error dialing emitter address %v: %s", raddr, err) return err } logger.Infof("Emitter using address: %v", raddr) return nil } // Emit segment or subsegment if root segment is sampled. // seg has a write lock acquired by the caller. func (de *DefaultEmitter) Emit(seg *Segment) { HeaderBytes := []byte(Header) if seg == nil || !seg.ParentSegment.Sampled { return } for _, p := range packSegments(seg, nil) { logger.Debug(string(p)) de.Lock() if de.conn == nil { if err := de.refresh(de.addr); err != nil { de.Unlock() return } } _, err := de.conn.Write(append(HeaderBytes, p...)) if err != nil { logger.Error(err) } de.Unlock() } } // seg has a write lock acquired by the caller. 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, err := json.Marshal(s) if err != nil { logger.Errorf("JSON error while marshalling (Sub)Segment: %v", err) } return b } for _, s := range seg.rawSubsegments { s.Lock() outSegments = packSegments(s, outSegments) if b := trimSubsegment(s); b != nil { seg.Subsegments = append(seg.Subsegments, b) } s.Unlock() } if seg.isOrphan() { if b := trimSubsegment(seg); b != nil { outSegments = append(outSegments, b) } } return outSegments }
122
aws-xray-sdk-go
aws
Go
// 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" "fmt" "math/rand" "net" "testing" "time" "github.com/stretchr/testify/assert" ) func TestNoNeedStreamingStrategy(t *testing.T) { seg := &Segment{} subSeg := &Segment{} assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &seg)) assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &subSeg)) subSeg.ParentSegment = seg subSeg.parent = seg seg.ParentSegment = seg seg.Sampled = true seg.totalSubSegments = 1 seg.rawSubsegments = append(seg.rawSubsegments, subSeg) assert.Equal(t, 1, len(packSegments(seg, nil))) } func TestStreamingSegmentsOnChildNode(t *testing.T) { seg := &Segment{} subSeg := &Segment{} assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &seg)) assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &subSeg)) subSeg.parent = seg seg.ParentSegment = seg subSeg.ParentSegment = seg.ParentSegment seg.Sampled = true seg.totalSubSegments = 22 for i := 0; i < 22; i++ { seg.rawSubsegments = append(seg.rawSubsegments, subSeg) } out := packSegments(seg, nil) s := &Segment{} json.Unmarshal(out[2], s) assert.Equal(t, 20, len(s.Subsegments)) assert.Equal(t, 3, len(out)) } func TestStreamingSegmentsOnGrandchildNode(t *testing.T) { root := &Segment{} a := &Segment{} b := &Segment{} c := &Segment{} d := &Segment{} assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &root)) assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &a)) assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &b)) assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &c)) assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &d)) root.ParentSegment = root root.Sampled = true a.ParentSegment = root b.ParentSegment = root c.ParentSegment = root d.ParentSegment = root a.parent = root b.parent = root c.parent = a d.parent = b root.totalSubSegments = 42 root.rawSubsegments = append(root.rawSubsegments, a) root.rawSubsegments = append(root.rawSubsegments, b) for i := 0; i < 20; i++ { a.rawSubsegments = append(a.rawSubsegments, c) } for i := 0; i < 20; i++ { b.rawSubsegments = append(b.rawSubsegments, d) } assert.Equal(t, 23, len(packSegments(root, nil))) } func TestStreamingSegmentsTreeHasOnlyOneBranch(t *testing.T) { dss, _ := NewDefaultStreamingStrategyWithMaxSubsegmentCount(1) Configure(Config{StreamingStrategy: dss}) segOne := &Segment{} segTwo := &Segment{} segThree := &Segment{} segFour := &Segment{} assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &segOne)) assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &segTwo)) assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &segThree)) assert.NoError(t, json.Unmarshal([]byte(getTestSegment()), &segFour)) segOne.ParentSegment = segOne segOne.Sampled = true segTwo.ParentSegment = segOne segTwo.parent = segOne segThree.ParentSegment = segOne segThree.parent = segTwo segFour.ParentSegment = segOne segFour.parent = segThree segOne.totalSubSegments = 3 segOne.rawSubsegments = append(segOne.rawSubsegments, segTwo) segTwo.rawSubsegments = append(segTwo.rawSubsegments, segThree) segThree.rawSubsegments = append(segThree.rawSubsegments, segFour) assert.Equal(t, 3, len(packSegments(segOne, nil))) ResetConfig() } func randomString(strlen int) string { rand.Seed(time.Now().UTC().UnixNano()) const chars = "0123456789abcdef" result := make([]byte, strlen) for i := 0; i < strlen; i++ { result[i] = chars[rand.Intn(len(chars))] } return string(result) } func getTestSegment() string { t := time.Now().Unix() hextime := fmt.Sprintf("%X", t) traceID := "1-" + hextime + "-" + randomString(24) message := fmt.Sprintf("{\"trace_id\": \"%s\", \"id\": \"%s\", \"start_time\": 1461096053.37518, "+ "\"end_time\": 1461096053.4042, "+ "\"name\": \"hello-1.mbfzqxzcpe.us-east-1.elasticbeanstalk.com\"}", traceID, randomString(16)) return message } // Benchmarks func BenchmarkDefaultEmitter_packSegments(b *testing.B) { seg := &Segment{} subSeg := &Segment{} subSeg.parent = seg seg.ParentSegment = seg subSeg.ParentSegment = seg.ParentSegment seg.Sampled = true seg.totalSubSegments = 22 for i := 0; i < 22; i++ { seg.rawSubsegments = append(seg.rawSubsegments, subSeg) } for i := 0; i < b.N; i++ { packSegments(seg, nil) } } func BenchmarkDefaultEmitter(b *testing.B) { seg := &Segment{ ParentSegment: &Segment{ Sampled: false, }, } b.RunParallel(func(pb *testing.PB) { emitter, err := NewDefaultEmitter(&net.UDPAddr{ IP: net.IPv4(127, 0, 0, 1), Port: 2000, }) if err != nil { b.Fatal(err) } for pb.Next() { emitter.Emit(seg) } }) }
183
aws-xray-sdk-go
aws
Go
// 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" "sync/atomic" "github.com/aws/aws-xray-sdk-go/internal/logger" ) var defaultMaxSubsegmentCount uint32 = 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 uint32 } // 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") } c := uint32(maxSubsegmentCount) return &DefaultStreamingStrategy{MaxSubsegmentCount: c}, 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 atomic.LoadUint32(&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 { logger.Debug("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] atomic.AddUint32(&seg.ParentSegment.totalSubSegments, ^uint32(0)) // Add extra information into child subsegment child.Lock() child.beforeEmitSubsegment(seg) cb, err := json.Marshal(child) if err != nil { logger.Errorf("JSON error while marshalling subsegment: %v", err) } outSegments = append(outSegments, cb) logger.Debugf("Streaming subsegment named '%s' from segment tree.", child.Name) child.Unlock() break } logger.Debug("Finished streaming subsegments.") return outSegments }
87
aws-xray-sdk-go
aws
Go
// 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 ( "testing" "github.com/stretchr/testify/assert" ) func TestDefaultStreamingStrategyMaxSegmentSize(t *testing.T) { dss, _ := NewDefaultStreamingStrategy() assert.Equal(t, dss.MaxSubsegmentCount, defaultMaxSubsegmentCount) } func TestDefaultStreamingStrategyMaxSegmentSizeParameterValidation(t *testing.T) { dss, e := NewDefaultStreamingStrategyWithMaxSubsegmentCount(-1) assert.Nil(t, dss) assert.Error(t, e, "maxSubsegmentCount must be a non-negative integer") }
28
aws-xray-sdk-go
aws
Go
// 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 "net" // Emitter provides an interface for implementing emitting trace entities. type Emitter interface { Emit(seg *Segment) RefreshEmitterWithAddress(raddr *net.UDPAddr) }
18
aws-xray-sdk-go
aws
Go
package xray import ( "context" "fmt" "net/http" "net/url" "github.com/aws/aws-xray-sdk-go/header" "github.com/valyala/fasthttp" ) type FastHTTPHandler interface { Handler(SegmentNamer, fasthttp.RequestHandler) fasthttp.RequestHandler } type fasthttpHandler struct { cfg *Config } // NewFastHTTPInstrumentor returns a struct that provides Handle method // that satisfy fasthttp.RequestHandler interface. func NewFastHTTPInstrumentor(cfg *Config) FastHTTPHandler { return &fasthttpHandler{ cfg: cfg, } } // Handler wraps the provided fasthttp.RequestHandler func (h *fasthttpHandler) Handler(sn SegmentNamer, handler fasthttp.RequestHandler) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { auxCtx := context.Background() if h.cfg != nil { auxCtx = context.WithValue(context.Background(), fasthttpContextConfigKey, h.cfg) ctx.SetUserValue(fasthttpContextConfigKey, h.cfg) } name := sn.Name(string(ctx.Request.Host())) traceHeader := header.FromString(string(ctx.Request.Header.Peek(TraceIDHeaderKey))) req, err := fasthttpToNetHTTPRequest(ctx) if err != nil { ctx.Logger().Printf("%s", err.Error()) ctx.Error("Internal Server Error", fasthttp.StatusInternalServerError) return } _, seg := NewSegmentFromHeader(auxCtx, name, req, traceHeader) defer seg.Close(nil) ctx.SetUserValue(fasthttpContextKey, seg) httpCaptureRequest(seg, req) fasthttpTrace(seg, handler, ctx, traceHeader) } } // fasthttpToNetHTTPRequest convert a fasthttp.Request to http.Request func fasthttpToNetHTTPRequest(ctx *fasthttp.RequestCtx) (*http.Request, error) { requestURI := string(ctx.RequestURI()) rURL, err := url.ParseRequestURI(requestURI) if err != nil { return nil, fmt.Errorf("cannot parse requestURI %q: %s", requestURI, err) } req := &http.Request{ URL: rURL, Host: string(ctx.Host()), RequestURI: requestURI, Method: string(ctx.Method()), RemoteAddr: ctx.RemoteAddr().String(), } hdr := make(http.Header) ctx.Request.Header.VisitAll(func(k, v []byte) { sk := string(k) sv := string(v) switch sk { case "Transfer-Encoding": req.TransferEncoding = append(req.TransferEncoding, sv) default: hdr.Set(sk, sv) } }) req.Header = hdr req.TLS = ctx.TLSConnectionState() return req, nil } func fasthttpTrace(seg *Segment, h fasthttp.RequestHandler, ctx *fasthttp.RequestCtx, traceHeader *header.Header) { ctx.Request.Header.Set(TraceIDHeaderKey, generateTraceIDHeaderValue(seg, traceHeader)) h(ctx) seg.Lock() seg.GetHTTP().GetResponse().ContentLength = ctx.Response.Header.ContentLength() seg.Unlock() HttpCaptureResponse(seg, ctx.Response.StatusCode()) }
99
aws-xray-sdk-go
aws
Go
package xray import ( "net" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/valyala/fasthttp" ) func TestFastHTTPHandler(t *testing.T) { ctx1, td := NewTestDaemon() cfg := GetRecorder(ctx1) defer td.Close() fh := NewFastHTTPInstrumentor(cfg) handler := fh.Handler(NewFixedSegmentNamer("test"), func(ctx *fasthttp.RequestCtx) {}) rc := genericRequestCtx() handler(rc) seg, err := td.Recv() if !assert.NoError(t, err) { return } assert.Equal(t, http.StatusOK, rc.Response.StatusCode()) assert.Equal(t, http.MethodPost, seg.HTTP.Request.Method) assert.Equal(t, "http://localhost/path", seg.HTTP.Request.URL) assert.Equal(t, "1.2.3.5", seg.HTTP.Request.ClientIP) assert.Equal(t, "UA_test", seg.HTTP.Request.UserAgent) } // genericRequestCtx helper function to build fasthttp.RequestCtx func genericRequestCtx() *fasthttp.RequestCtx { b := `{"body": "content"}` req := fasthttp.Request{} req.SetBodyString(b) req.SetRequestURI("/path") req.SetHost("localhost") req.Header.SetContentType("application/json") req.Header.SetContentLength(len(b)) req.Header.SetMethod(http.MethodPost) req.Header.SetUserAgent("UA_test") rc := &fasthttp.RequestCtx{} rc.Init(&req, nil, nil) remoteAddr := &net.TCPAddr{ IP: []byte{1, 2, 3, 5}, Port: 0, } rc.SetRemoteAddr(remoteAddr) return rc } func BenchmarkFasthttpHandler(b *testing.B) { ctx1, td := NewTestDaemon() cfg := GetRecorder(ctx1) defer td.Close() fh := NewFastHTTPInstrumentor(cfg) handler := fh.Handler(NewFixedSegmentNamer("test"), func(ctx *fasthttp.RequestCtx) {}) for i := 0; i < b.N; i++ { rc := genericRequestCtx() handler(rc) } }
71
aws-xray-sdk-go
aws
Go
package xray import ( "bytes" "context" "errors" "net/http" "net/url" "strconv" "strings" "github.com/aws/aws-xray-sdk-go/internal/logger" "google.golang.org/grpc/codes" "github.com/golang/protobuf/proto" "google.golang.org/grpc/status" "github.com/aws/aws-xray-sdk-go/header" "google.golang.org/grpc" "google.golang.org/grpc/metadata" ) // UnaryClientInterceptor provides gRPC unary client interceptor. func UnaryClientInterceptor(clientInterceptorOptions ...GrpcOption) grpc.UnaryClientInterceptor { var option grpcOption for _, interceptorOption := range clientInterceptorOptions { interceptorOption.apply(&option) } return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { var segmentName string if option.segmentNamer == nil { segmentName = inferServiceName(method) } else { segmentName = option.segmentNamer.Name(cc.Target()) } if option.config != nil { ctx = context.WithValue(ctx, RecorderContextKey{}, option.config) } return Capture(ctx, segmentName, func(ctx context.Context) error { seg := GetSegment(ctx) if seg == nil { return errors.New("failed to record gRPC transaction: segment cannot be found") } ctx = metadata.AppendToOutgoingContext(ctx, TraceIDHeaderKey, seg.DownstreamHeader().String()) seg.Lock() seg.Namespace = "remote" seg.GetHTTP().GetRequest().URL = "grpc://" + cc.Target() + method seg.GetHTTP().GetRequest().Method = http.MethodPost seg.Unlock() err := invoker(ctx, method, req, reply, cc, opts...) recordContentLength(seg, reply) if err != nil { classifyErrorStatus(seg, err) } return err }) } } // UnaryServerInterceptor provides gRPC unary server interceptor. func UnaryServerInterceptor(serverInterceptorOptions ...GrpcOption) grpc.UnaryServerInterceptor { var option grpcOption for _, options := range serverInterceptorOptions { options.apply(&option) } return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { md, ok := metadata.FromIncomingContext(ctx) var traceID string if ok && len(md.Get(TraceIDHeaderKey)) == 1 { traceID = md.Get(TraceIDHeaderKey)[0] } traceHeader := header.FromString(traceID) var host string if len(md.Get(":authority")) == 1 { host = md.Get(":authority")[0] } requestURL := url.URL{ Scheme: "grpc", Host: host, Path: info.FullMethod, } var name string if option.segmentNamer == nil { name = inferServiceName(info.FullMethod) } else { name = option.segmentNamer.Name(host) } if option.config != nil { ctx = context.WithValue(ctx, RecorderContextKey{}, option.config) } var seg *Segment ctx, seg = NewSegmentFromHeader(ctx, name, &http.Request{ Host: host, URL: &requestURL, Method: http.MethodPost, }, traceHeader) defer seg.Close(nil) seg.Lock() seg.GetHTTP().GetRequest().ClientIP, seg.GetHTTP().GetRequest().XForwardedFor = clientIPFromGrpcMetadata(md) seg.GetHTTP().GetRequest().URL = requestURL.String() seg.GetHTTP().GetRequest().Method = http.MethodPost if len(md.Get("user-agent")) == 1 { seg.GetHTTP().GetRequest().UserAgent = md.Get("user-agent")[0] } seg.Unlock() resp, err = handler(ctx, req) if err != nil { classifyErrorStatus(seg, err) } recordContentLength(seg, resp) if headerErr := addResponseTraceHeader(ctx, seg, traceHeader); headerErr != nil { logger.Debug("fail to set the grpc trace header") } return resp, err } } func classifyErrorStatus(seg *Segment, err error) { seg.Lock() defer seg.Unlock() grpcStatus, ok := status.FromError(err) if !ok { seg.Fault = true return } switch grpcStatus.Code() { case codes.Canceled, codes.InvalidArgument, codes.NotFound, codes.AlreadyExists, codes.PermissionDenied, codes.Unauthenticated, codes.FailedPrecondition, codes.Aborted, codes.OutOfRange: seg.Error = true case codes.Unknown, codes.DeadlineExceeded, codes.Unimplemented, codes.Internal, codes.Unavailable, codes.DataLoss: seg.Fault = true case codes.ResourceExhausted: seg.Throttle = true } } func clientIPFromGrpcMetadata(md metadata.MD) (string, bool) { if len(md.Get("x-forwarded-for")) != 1 { return "", false } forwardedFor := md.Get("x-forwarded-for")[0] if forwardedFor != "" { return strings.TrimSpace(strings.Split(forwardedFor, ",")[0]), true } return "", false } func recordContentLength(seg *Segment, reply interface{}) { seg.Lock() defer seg.Unlock() if protoMessage, isProtoMessage := reply.(proto.Message); isProtoMessage { seg.GetHTTP().GetResponse().ContentLength = proto.Size(protoMessage) } } func addResponseTraceHeader(ctx context.Context, seg *Segment, incomingTraceHeader *header.Header) error { var respHeader bytes.Buffer respHeader.WriteString("Root=") respHeader.WriteString(seg.TraceID) if incomingTraceHeader.SamplingDecision == header.Requested { respHeader.WriteString(";Sampled=") respHeader.WriteString(strconv.Itoa(btoi(seg.Sampled))) } headers := metadata.New(map[string]string{ TraceIDHeaderKey: respHeader.String(), }) return grpc.SetHeader(ctx, headers) } func inferServiceName(fullMethodName string) string { fullMethodName = fullMethodName[1:] return fullMethodName[:strings.Index(fullMethodName, "/")] } type GrpcOption interface { apply(option *grpcOption) } type grpcOption struct { config *Config segmentNamer SegmentNamer } func newFuncGrpcOption(f func(option *grpcOption)) GrpcOption { return funcGrpcOption{f: f} } type funcGrpcOption struct { f func(option *grpcOption) } func (f funcGrpcOption) apply(option *grpcOption) { f.f(option) } // WithRecorder configures the instrumentation by given xray.Config. func WithRecorder(cfg *Config) GrpcOption { return newFuncGrpcOption(func(option *grpcOption) { option.config = cfg }) } // WithSegmentNamer makes the interceptor use the segment namer to name the segment. func WithSegmentNamer(sn SegmentNamer) GrpcOption { return newFuncGrpcOption(func(option *grpcOption) { option.segmentNamer = sn }) }
226
aws-xray-sdk-go
aws
Go
package xray import ( "context" "encoding/json" "net" "regexp" "sync" "testing" "time" "github.com/aws/aws-xray-sdk-go/header" "github.com/golang/protobuf/proto" "github.com/stretchr/testify/require" pb "github.com/grpc-ecosystem/go-grpc-middleware/testing/testproto" "github.com/stretchr/testify/assert" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/grpc/test/bufconn" ) type testGRPCPingService struct { counter int32 mut sync.Mutex pb.TestServiceServer } func (s *testGRPCPingService) Ping(_ context.Context, req *pb.PingRequest) (*pb.PingResponse, error) { time.Sleep(time.Duration(req.SleepTimeMs) * time.Millisecond) s.mut.Lock() s.counter++ counter := s.counter s.mut.Unlock() return &pb.PingResponse{ Value: req.Value, Counter: counter, }, nil } func (s *testGRPCPingService) PingError(_ context.Context, req *pb.PingRequest) (*pb.Empty, error) { code := codes.Code(req.ErrorCodeReturned) return nil, status.Errorf(code, "Userspace error.") } func newGrpcServer(t *testing.T, opts ...grpc.ServerOption) *bufconn.Listener { const bufSize = 1024 * 1024 lis := bufconn.Listen(bufSize) s := grpc.NewServer(opts...) pb.RegisterTestServiceServer(s, &testGRPCPingService{}) go func() { if err := s.Serve(lis); err != nil { t.Fatal(err) } }() return lis } func newGrpcClient(ctx context.Context, t *testing.T, lis *bufconn.Listener, opts ...grpc.DialOption) (client pb.TestServiceClient, closeFunc func()) { var bufDialer = func(ctx context.Context, address string) (net.Conn, error) { return lis.Dial() } opts = append(opts, grpc.WithContextDialer(bufDialer), grpc.WithInsecure()) conn, err := grpc.DialContext( ctx, "bufnet", opts..., ) if err != nil { t.Fatal(err) } closeFunc = func() { if err := conn.Close(); err != nil { t.Fatal(err) } } client = pb.NewTestServiceClient(conn) return } type testCase struct { name string // responseErrorStatusCode makes the test suite call grpc method `PingError` to trigger the testing server to // return an error response. // If responseErrorStatusCode is codes.OK, the test suite call `Ping` to get a success response responseErrorStatusCode codes.Code expectedThrottle bool expectedError bool expectedFault bool } func (t testCase) isTestForSuccessResponse() bool { return t.responseErrorStatusCode == codes.OK } func (t testCase) getExpectedURL() string { if t.isTestForSuccessResponse() { return "grpc://bufnet/mwitkow.testproto.TestService/Ping" } return "grpc://bufnet/mwitkow.testproto.TestService/PingError" } func (t testCase) getExpectedContentLength() int { if t.isTestForSuccessResponse() { return proto.Size(&pb.PingResponse{Value: "something", Counter: 1}) } return 0 } func TestGrpcUnaryClientInterceptor(t *testing.T) { lis := newGrpcServer( t, grpc.UnaryInterceptor(UnaryServerInterceptor()), ) client, closeFunc := newGrpcClient(context.Background(), t, lis, grpc.WithUnaryInterceptor(UnaryClientInterceptor())) defer closeFunc() testCases := []testCase{ { name: "success response", responseErrorStatusCode: codes.OK, expectedThrottle: false, expectedError: false, expectedFault: false, }, { name: "error response", responseErrorStatusCode: codes.Unauthenticated, expectedThrottle: false, expectedError: true, expectedFault: true, }, { name: "throttle response", responseErrorStatusCode: codes.ResourceExhausted, expectedThrottle: true, expectedFault: true, expectedError: false, }, { name: "fault response", responseErrorStatusCode: codes.Internal, expectedThrottle: false, expectedError: false, expectedFault: true, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx2, root := BeginSegment(ctx, "Test") var err error if tc.isTestForSuccessResponse() { _, err = client.Ping( ctx2, &pb.PingRequest{ Value: "something", SleepTimeMs: 9999, }, ) require.NoError(t, err) } else { _, err = client.PingError( ctx2, &pb.PingRequest{Value: "something", ErrorCodeReturned: uint32(tc.responseErrorStatusCode)}) require.Error(t, err) } root.Close(nil) seg, err := td.Recv() require.NoError(t, err) var subseg *Segment assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, tc.getExpectedURL(), subseg.HTTP.Request.URL) assert.Equal(t, false, subseg.HTTP.Request.XForwardedFor) assert.Equal(t, tc.expectedThrottle, subseg.Throttle) assert.Equal(t, tc.expectedError, subseg.Error) assert.Equal(t, tc.expectedFault, subseg.Fault) assert.Equal(t, tc.getExpectedContentLength(), subseg.HTTP.Response.ContentLength) }) } t.Run("default namer", func(t *testing.T) { lis := newGrpcServer( t, grpc.UnaryInterceptor(UnaryServerInterceptor()), ) client, closeFunc := newGrpcClient( context.Background(), t, lis, grpc.WithUnaryInterceptor(UnaryClientInterceptor())) defer closeFunc() ctx, td := NewTestDaemon() defer td.Close() ctx, root := BeginSegment(ctx, "Test") _, err := client.Ping(ctx, &pb.PingRequest{Value: "something", SleepTimeMs: 9999}) assert.NoError(t, err) root.Close(nil) seg, err := td.Recv() require.NoError(t, err) var subseg *Segment assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) assert.Equal(t, "mwitkow.testproto.TestService", subseg.Name) assert.Equal(t, "grpc://bufnet/mwitkow.testproto.TestService/Ping", subseg.HTTP.Request.URL) }) t.Run("custom namer", func(t *testing.T) { lis := newGrpcServer( t, grpc.UnaryInterceptor(UnaryServerInterceptor()), ) client, closeFunc := newGrpcClient( context.Background(), t, lis, grpc.WithUnaryInterceptor( UnaryClientInterceptor( WithSegmentNamer(NewFixedSegmentNamer("custom"))))) defer closeFunc() ctx, td := NewTestDaemon() defer td.Close() ctx, root := BeginSegment(ctx, "Test") _, err := client.Ping(ctx, &pb.PingRequest{Value: "something", SleepTimeMs: 9999}) assert.NoError(t, err) root.Close(nil) seg, err := td.Recv() require.NoError(t, err) var subseg *Segment assert.NoError(t, json.Unmarshal(seg.Subsegments[0], &subseg)) assert.Equal(t, "custom", subseg.Name) assert.Equal(t, "grpc://bufnet/mwitkow.testproto.TestService/Ping", subseg.HTTP.Request.URL) }) } func TestUnaryServerInterceptor(t *testing.T) { testCases := []testCase{ { name: "success response", responseErrorStatusCode: codes.OK, expectedThrottle: false, expectedError: false, expectedFault: false, }, { name: "error response", responseErrorStatusCode: codes.Unauthenticated, expectedThrottle: false, expectedError: true, expectedFault: false, }, { name: "throttle response", responseErrorStatusCode: codes.ResourceExhausted, expectedThrottle: true, expectedError: false, expectedFault: false, }, { name: "fault response", responseErrorStatusCode: codes.Internal, expectedThrottle: false, expectedError: false, expectedFault: true, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { // Ideally we shouldn't be creating a local test daemon for each test case. // However, how the shared channel in the test daemon doesn't guarantee // segment isolation across test cases. Therefore, for now a local test daemon // is a workaround. ctx, td := NewTestDaemon() defer td.Close() lis := newGrpcServer( t, grpc.UnaryInterceptor( UnaryServerInterceptor( WithRecorder(GetRecorder(ctx)), WithSegmentNamer(NewFixedSegmentNamer("test")))), ) client, closeFunc := newGrpcClient(context.Background(), t, lis) defer closeFunc() var respHeaders metadata.MD if tc.isTestForSuccessResponse() { _, err := client.Ping( context.Background(), &pb.PingRequest{Value: "something", SleepTimeMs: 9999}, grpc.Header(&respHeaders), ) require.NoError(t, err) } else { _, err := client.PingError( context.Background(), &pb.PingRequest{Value: "something", ErrorCodeReturned: uint32(tc.responseErrorStatusCode)}, grpc.Header(&respHeaders), ) require.Error(t, err) } seg, err := td.Recv() require.NoError(t, err) assert.Equal(t, tc.getExpectedURL(), seg.HTTP.Request.URL) assert.Equal(t, false, seg.HTTP.Request.XForwardedFor) assert.Regexp(t, regexp.MustCompile(`^grpc-go/`), seg.HTTP.Request.UserAgent) assert.Equal(t, "TestVersion", seg.Service.Version) assert.Equal(t, tc.expectedThrottle, seg.Throttle) assert.Equal(t, tc.expectedError, seg.Error) assert.Equal(t, tc.expectedFault, seg.Fault) assert.Equal(t, tc.getExpectedContentLength(), seg.HTTP.Response.ContentLength) respTraceHeaderSlice := respHeaders[TraceIDHeaderKey] require.NotNil(t, respTraceHeaderSlice) require.Len(t, respTraceHeaderSlice, 1) respTraceHeader := header.FromString(respTraceHeaderSlice[0]) assert.Equal(t, seg.TraceID, respTraceHeader.TraceID) assert.Equal(t, header.Unknown, respTraceHeader.SamplingDecision) }) } // test that the interceptor by default will name the segment by the gRPC service name t.Run("default namer", func(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() lis := newGrpcServer( t, grpc.UnaryInterceptor( UnaryServerInterceptor( WithRecorder(GetRecorder(ctx)))), ) client, closeFunc := newGrpcClient(context.Background(), t, lis) defer closeFunc() _, err := client.Ping(context.Background(), &pb.PingRequest{Value: "something", SleepTimeMs: 9999}) assert.NoError(t, err) segment, err := td.Recv() assert.NoError(t, err) assert.Equal(t, "mwitkow.testproto.TestService", segment.Name) }) t.Run("chained interceptor", func(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() lis := newGrpcServer( t, grpc.ChainUnaryInterceptor( func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { resp, err := handler(ctx, req) assert.NoError(t, grpc.SetHeader(ctx, metadata.Pairs("foo", "bar"))) return resp, err }, UnaryServerInterceptor(WithRecorder(GetRecorder(ctx))), ), ) client, closeFunc := newGrpcClient(context.Background(), t, lis) defer closeFunc() var respHeaders metadata.MD _, err := client.Ping(context.Background(), &pb.PingRequest{Value: "something", SleepTimeMs: 9999}, grpc.Header(&respHeaders)) require.NoError(t, err) assert.Equal(t, []string{"bar"}, respHeaders["foo"]) assert.NotNil(t, respHeaders[TraceIDHeaderKey]) }) } func TestUnaryServerAndClientInterceptor(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() lis := newGrpcServer( t, grpc.UnaryInterceptor( UnaryServerInterceptor( WithRecorder(GetRecorder(ctx)), WithSegmentNamer(NewFixedSegmentNamer("test")))), ) client, closeFunc := newGrpcClient(context.Background(), t, lis, grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { ctx = metadata.AppendToOutgoingContext(ctx, TraceIDHeaderKey, "Root=fakeid; Parent=reqid; Sampled=1") return invoker(ctx, method, req, reply, cc, opts...) })) defer closeFunc() _, err := client.Ping( context.Background(), &pb.PingRequest{Value: "something", SleepTimeMs: 9999}, ) if !assert.NoError(t, err) { return } seg, err := td.Recv() if !assert.NoError(t, err) { return } assert.Equal(t, "fakeid", seg.TraceID) assert.Equal(t, "reqid", seg.ParentID) assert.Equal(t, true, seg.Sampled) assert.Equal(t, "TestVersion", seg.Service.Version) } func TestInferServiceName(t *testing.T) { assert.Equal(t, "com.example.Service", inferServiceName("/com.example.Service/method")) }
430
aws-xray-sdk-go
aws
Go
// 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" "strconv" "strings" "github.com/aws/aws-xray-sdk-go/header" "github.com/aws/aws-xray-sdk-go/pattern" ) // 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 { 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 { 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 { cfg := GetRecorder(ctx) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { name := sn.Name(r.Host) traceHeader := header.FromString(r.Header.Get(TraceIDHeaderKey)) ctx := context.WithValue(r.Context(), RecorderContextKey{}, cfg) c, seg := NewSegmentFromHeader(ctx, name, r, traceHeader) defer seg.Close(nil) 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(TraceIDHeaderKey)) ctx, seg := NewSegmentFromHeader(r.Context(), name, r, traceHeader) defer seg.Close(nil) 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) { httpCaptureRequest(seg, r) traceIDHeaderValue := generateTraceIDHeaderValue(seg, traceHeader) w.Header().Set(TraceIDHeaderKey, traceIDHeaderValue) capturer := &responseCapturer{w, 200, 0} resp := capturer.wrappedResponseWriter() h.ServeHTTP(resp, r) seg.Lock() seg.GetHTTP().GetResponse().ContentLength, _ = strconv.Atoi(capturer.Header().Get("Content-Length")) seg.Unlock() HttpCaptureResponse(seg, capturer.status) } 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 } func btoi(b bool) int { if b { return 1 } return 0 } // generateTraceIDHeaderValue generates value for _x_amzn_trace_id header key func generateTraceIDHeaderValue(seg *Segment, traceHeader *header.Header) string { seg.Lock() defer seg.Unlock() var respHeader bytes.Buffer respHeader.WriteString("Root=") respHeader.WriteString(seg.TraceID) if traceHeader.ParentID != "" { respHeader.WriteString(";Parent=") respHeader.WriteString(traceHeader.ParentID) } if traceHeader.SamplingDecision == header.NotSampled { respHeader.WriteString(";Sampled=0") } else if traceHeader.SamplingDecision == header.Sampled { respHeader.WriteString(";Sampled=1") } else if traceHeader.SamplingDecision == header.Requested { respHeader.WriteString(";Sampled=") respHeader.WriteString(strconv.Itoa(btoi(seg.Sampled))) } return respHeader.String() } // HttpCaptureResponse fill response by http status code func HttpCaptureResponse(seg *Segment, statusCode int) { seg.Lock() defer seg.Unlock() seg.GetHTTP().GetResponse().Status = statusCode if statusCode >= 400 && statusCode < 500 { seg.Error = true } if statusCode == 429 { seg.Throttle = true } if statusCode >= 500 && statusCode < 600 { seg.Fault = true } } // httpCaptureRequest fill request data by http.Request func httpCaptureRequest(seg *Segment, r *http.Request) { seg.Lock() defer seg.Unlock() 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() }
205
aws-xray-sdk-go
aws
Go
// 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.13 package xray import ( "context" "net" "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestRootHandler(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte(`200 - OK`)); err != nil { panic(err) } }) ts := httptest.NewUnstartedServer(Handler(NewFixedSegmentNamer("test"), handler)) ts.Config.BaseContext = func(_ net.Listener) context.Context { return ctx } ts.Start() defer ts.Close() req, err := http.NewRequest(http.MethodPost, ts.URL, strings.NewReader("")) if !assert.NoError(t, err) { return } req.Header.Set("User-Agent", "UnitTest") resp, err := http.DefaultClient.Do(req) if !assert.NoError(t, err) { return } defer resp.Body.Close() assert.Equal(t, http.StatusOK, resp.StatusCode) seg, err := td.Recv() if !assert.NoError(t, err) { return } assert.Equal(t, http.StatusOK, seg.HTTP.Response.Status) assert.Equal(t, http.MethodPost, seg.HTTP.Request.Method) assert.Equal(t, ts.URL+"/", seg.HTTP.Request.URL) assert.Equal(t, "127.0.0.1", seg.HTTP.Request.ClientIP) assert.Equal(t, "UnitTest", seg.HTTP.Request.UserAgent) } func TestNonRootHandler(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) ts := httptest.NewUnstartedServer(Handler(NewFixedSegmentNamer("test"), handler)) ts.Config.BaseContext = func(_ net.Listener) context.Context { return ctx } ts.Start() defer ts.Close() req, err := http.NewRequest(http.MethodPost, ts.URL, strings.NewReader("")) if !assert.NoError(t, err) { return } req.Header.Set("User-Agent", "UnitTest") req.Header.Set(TraceIDHeaderKey, "Root=fakeid; Parent=reqid; Sampled=1") resp, err := http.DefaultClient.Do(req) if !assert.NoError(t, err) { return } defer resp.Body.Close() assert.Equal(t, http.StatusOK, resp.StatusCode) seg, err := td.Recv() if !assert.NoError(t, err) { return } assert.Equal(t, "fakeid", seg.TraceID) assert.Equal(t, "reqid", seg.ParentID) assert.Equal(t, true, seg.Sampled) }
105
aws-xray-sdk-go
aws
Go
// 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 ( "io" "net/http" "net/http/httptest" "reflect" "strings" "testing" "github.com/aws/aws-xray-sdk-go/header" "github.com/stretchr/testify/assert" ) func TestNewFixedSegmentName(t *testing.T) { n := NewFixedSegmentNamer("test") assert.Equal(t, "test", n.FixedName) } func TestNewDynamicSegmentName(t *testing.T) { n := NewDynamicSegmentNamer("test", "a/b/c") assert.Equal(t, "test", n.FallbackName) assert.Equal(t, "a/b/c", n.RecognizedHosts) } func TestHandlerWithContextForRootHandler(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte(`200 - OK`)); err != nil { panic(err) } }) ts := httptest.NewServer(HandlerWithContext(ctx, NewFixedSegmentNamer("test"), handler)) defer ts.Close() req, err := http.NewRequest(http.MethodPost, ts.URL, strings.NewReader("")) if !assert.NoError(t, err) { return } req.Header.Set("User-Agent", "UnitTest") resp, err := http.DefaultClient.Do(req) if !assert.NoError(t, err) { return } resp.Body.Close() assert.Equal(t, http.StatusOK, resp.StatusCode) // make sure all connections are closed. ts.Close() seg, err := td.Recv() if !assert.NoError(t, err) { return } assert.Equal(t, http.StatusOK, seg.HTTP.Response.Status) assert.Equal(t, "POST", seg.HTTP.Request.Method) assert.Equal(t, ts.URL+"/", seg.HTTP.Request.URL) assert.Equal(t, "127.0.0.1", seg.HTTP.Request.ClientIP) assert.Equal(t, "UnitTest", seg.HTTP.Request.UserAgent) assert.Equal(t, "TestVersion", seg.Service.Version) } func TestHandlerWithContextForNonRootHandler(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) ts := httptest.NewServer(HandlerWithContext(ctx, NewFixedSegmentNamer("test"), handler)) defer ts.Close() req, err := http.NewRequest(http.MethodDelete, ts.URL, strings.NewReader("")) if !assert.NoError(t, err) { return } req.Header.Set(TraceIDHeaderKey, "Root=fakeid; Parent=reqid; Sampled=1") resp, err := http.DefaultClient.Do(req) if !assert.NoError(t, err) { return } resp.Body.Close() assert.Equal(t, http.StatusOK, resp.StatusCode) // make sure all connections are closed. ts.Close() seg, err := td.Recv() if !assert.NoError(t, err) { return } assert.Equal(t, "fakeid", seg.TraceID) assert.Equal(t, "reqid", seg.ParentID) assert.Equal(t, true, seg.Sampled) assert.Equal(t, "TestVersion", seg.Service.Version) } func TestXRayHandlerPreservesOptionalInterfaces(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, isCloseNotifier := w.(http.CloseNotifier) _, isFlusher := w.(http.Flusher) _, isHijacker := w.(http.Hijacker) _, isPusher := w.(http.Pusher) _, isReaderFrom := w.(io.ReaderFrom) assert.True(t, isCloseNotifier) assert.True(t, isFlusher) assert.True(t, isHijacker) assert.True(t, isReaderFrom) // Pusher is only available when using http/2, so should not be present assert.False(t, isPusher) w.WriteHeader(202) }) ts := httptest.NewServer(HandlerWithContext(ctx, NewFixedSegmentNamer("test"), handler)) defer ts.Close() req := httptest.NewRequest(http.MethodGet, ts.URL, strings.NewReader("")) _, err := http.DefaultTransport.RoundTrip(req) assert.NoError(t, err) } // Benchmarks func BenchmarkHandler(b *testing.B) { ctx, td := NewTestDaemon() defer td.Close() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { }) for i := 0; i < b.N; i++ { ts := httptest.NewServer(HandlerWithContext(ctx, NewFixedSegmentNamer("test"), handler)) req := httptest.NewRequest(http.MethodGet, ts.URL, strings.NewReader("")) http.DefaultTransport.RoundTrip(req) ts.Close() } } func TestGenerateTraceIDHeaderValue(t *testing.T) { type args struct { seg *Segment traceHeader *header.Header } tests := []struct { name string args func(t *testing.T) args want1 string }{ { name: "TraceID with sampling decision", args: func(*testing.T) args { return args{ seg: &Segment{ TraceID: "x-traceid", Sampled: true, }, traceHeader: &header.Header{ SamplingDecision: header.Requested, }, } }, want1: "Root=x-traceid;Sampled=1", }, { name: "TraceID without Sampled", args: func(*testing.T) args { return args{ seg: &Segment{ TraceID: "x-traceid", Sampled: true, }, traceHeader: &header.Header{}, } }, want1: "Root=x-traceid", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tArgs := tt.args(t) got1 := generateTraceIDHeaderValue(tArgs.seg, tArgs.traceHeader) if !reflect.DeepEqual(got1, tt.want1) { t.Errorf("Segment.TraceHeaderID got1 = %v, want1: %v", got1, tt.want1) } }) } } func TestHTTPCaptureResponse(t *testing.T) { type args struct { seg *Segment statusCode int } tests := []struct { name string inspect func(r *Segment, t *testing.T) //inspects receiver after test run args func(t *testing.T) args }{ { name: "StatudCode 400 >= 400 and < 500 is a error", inspect: func(s *Segment, t *testing.T) { if !s.Error { t.Errorf("Segment error, got = false, want1: true") } }, args: func(*testing.T) args { return args{ seg: &Segment{}, statusCode: 401, } }, }, { name: "StatudCode 429 set error/throttle", inspect: func(s *Segment, t *testing.T) { if !s.Error { t.Errorf("Segment error, got = false, want1: true") } if !s.Throttle { t.Errorf("Segment.Throttle error, got = false, want1: true") } }, args: func(*testing.T) args { return args{ seg: &Segment{}, statusCode: 429, } }, }, { name: "StatusCode 500 is a fault error", inspect: func(s *Segment, t *testing.T) { if !s.Fault { t.Errorf("Segment.Fault error, got = false, want1: true") } }, args: func(*testing.T) args { return args{ seg: &Segment{}, statusCode: 500, } }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tArgs := tt.args(t) HttpCaptureResponse(tArgs.seg, tArgs.statusCode) if tt.inspect != nil { tt.inspect(tArgs.seg, t) } if tArgs.seg.GetHTTP().GetResponse().Status != tArgs.statusCode { t.Errorf("Status code error, got = %d, want1: %d", tArgs.seg.GetHTTP().GetResponse().Status, tArgs.statusCode) } }) } }
290
aws-xray-sdk-go
aws
Go
// 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" "sync" ) // HTTPSubsegments is a set of context in different HTTP operation. // Note: from ClientTrace godoc // Functions may be called concurrently from different goroutines // // HTTPSubsegments must operate as though all functions on it can be called in // different goroutines and must protect against races type HTTPSubsegments struct { opCtx context.Context connCtx context.Context dnsCtx context.Context connectCtx context.Context tlsCtx context.Context reqCtx context.Context responseCtx context.Context mu sync.Mutex } // 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) { xt.mu.Lock() defer xt.mu.Unlock() if GetSegment(xt.opCtx).safeInProgress() { 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) { xt.mu.Lock() defer xt.mu.Unlock() if GetSegment(xt.opCtx).safeInProgress() && xt.connCtx != nil { 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) { xt.mu.Lock() defer xt.mu.Unlock() if xt.dnsCtx != nil && GetSegment(xt.opCtx).safeInProgress() { 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) { xt.mu.Lock() defer xt.mu.Unlock() if GetSegment(xt.opCtx).safeInProgress() && xt.connCtx != nil { 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) { xt.mu.Lock() defer xt.mu.Unlock() if xt.connectCtx != nil && GetSegment(xt.opCtx).safeInProgress() { 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() { xt.mu.Lock() defer xt.mu.Unlock() if GetSegment(xt.opCtx).safeInProgress() && xt.connCtx != nil { 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) { xt.mu.Lock() defer xt.mu.Unlock() if xt.tlsCtx != nil && GetSegment(xt.opCtx).safeInProgress() { 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) { xt.mu.Lock() defer xt.mu.Unlock() if xt.connCtx != nil && GetSegment(xt.opCtx).safeInProgress() { // GetConn may not have been called (client_test.TestBadRoundTrip) if info != nil { if info.Reused { GetSegment(xt.opCtx).RemoveSubsegment(GetSegment(xt.connCtx)) // Remove the connCtx context since it is no longer needed. xt.connCtx = nil } 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) } } else if xt.connCtx != nil && GetSegment(xt.connCtx).safeInProgress() { 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) { xt.mu.Lock() defer xt.mu.Unlock() if xt.reqCtx != nil && GetSegment(xt.opCtx).safeInProgress() { GetSegment(xt.reqCtx).Close(info.Err) resCtx, _ := BeginSubsegment(xt.opCtx, "response") xt.responseCtx = resCtx } // In case the GotConn http trace handler wasn't called, // we close the connection subsegment since a connection // had to have been acquired before attempting to write // the request. if xt.connCtx != nil && GetSegment(xt.connCtx).safeInProgress() { GetSegment(xt.connCtx).Close(nil) } } // GotFirstResponseByte closes the response subsegment if the HTTP // operation subsegment is still in progress. func (xt *HTTPSubsegments) GotFirstResponseByte() { xt.mu.Lock() defer xt.mu.Unlock() resCtx := xt.responseCtx if resCtx != nil && GetSegment(xt.opCtx).safeInProgress() { GetSegment(resCtx).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 }
258
aws-xray-sdk-go
aws
Go
// 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" "github.com/aws/aws-xray-sdk-go/internal/logger" ) // 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 { logger.Debugf("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 { logger.Debugf("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 } 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 }
92
aws-xray-sdk-go
aws
Go
package xray import ( "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/aws/aws-xray-sdk-go/header" "github.com/stretchr/testify/assert" ) const ExampleTraceHeader string = "Root=1-57ff426a-80c11c39b0c928905eb0828d;Parent=1234abcd1234abcd;Sampled=1" func TestLambdaSegmentEmit(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() // go-lint warns "should not use basic type string as key in context.WithValue", // but it must be string type because the trace header comes from aws/aws-lambda-go. // https://github.com/aws/aws-lambda-go/blob/b5b7267d297de263cc5b61f8c37543daa9c95ffd/lambda/function.go#L65 ctx = context.WithValue(ctx, LambdaTraceHeaderKey, "Root=fakeid; Parent=reqid; Sampled=1") _, subseg := BeginSubsegment(ctx, "test-lambda") subseg.Close(nil) seg, e := td.Recv() assert.NoError(t, e) assert.Equal(t, "fakeid", seg.TraceID) assert.Equal(t, "reqid", seg.ParentID) assert.Equal(t, true, seg.Sampled) assert.Equal(t, "subsegment", seg.Type) } func TestLambdaMix(t *testing.T) { // Setup ctx, td := NewTestDaemon() defer td.Close() ctx = context.WithValue(ctx, LambdaTraceHeaderKey, ExampleTraceHeader) // First ctx1, _ := BeginSubsegment(ctx, "test-lambda-1") testHelper(ctx1, t, td, true) // Second ctx2, _ := BeginSubsegmentWithoutSampling(ctx, "test-lambda-2") testHelper(ctx2, t, td, false) // Third ctx3, _ := BeginSubsegment(ctx, "test-lambda-3") testHelper(ctx3, t, td, true) // Forth ctx4, _ := BeginSubsegmentWithoutSampling(ctx, "test-lambda-4") testHelper(ctx4, t, td, false) } /* This helper function creates a request and validates the response using the context provided. */ func testHelper(ctx context.Context, t *testing.T, td *TestDaemon, sampled bool) { var subseg = GetSegment(ctx) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte(`200 - OK`)); err != nil { panic(err) } }) // Create Test Server ts := httptest.NewServer(HandlerWithContext(context.Background(), NewFixedSegmentNamer("RequestSegment"), handler)) defer ts.Close() // Perform Request req, _ := http.NewRequestWithContext(ctx, http.MethodPost, ts.URL, strings.NewReader("")) req.Header.Add(TraceIDHeaderKey, generateHeader(subseg).String()) resp, _ := http.DefaultClient.Do(req) // Close the test server down ts.Close() // Ensure the return value is valid assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, subseg.TraceID, header.FromString(resp.Header.Get("x-amzn-trace-id")).TraceID) assert.Equal(t, subseg.ID, header.FromString(resp.Header.Get("x-amzn-trace-id")).ParentID) subseg.Close(nil) emittedSeg, e := td.Recv() if sampled { assert.Equal(t, header.Sampled, header.FromString(resp.Header.Get("x-amzn-trace-id")).SamplingDecision) assert.NoError(t, e) assert.Equal(t, true, emittedSeg.Sampled) assert.Equal(t, subseg.Name, emittedSeg.Name) } else { assert.Equal(t, header.NotSampled, header.FromString(resp.Header.Get("x-amzn-trace-id")).SamplingDecision) assert.Equal(t, (*Segment)(nil), emittedSeg) } } func generateHeader(seg *Segment) header.Header { var samplingDecision = header.Sampled if !seg.Sampled { samplingDecision = header.NotSampled } return header.Header{ TraceID: seg.TraceID, ParentID: seg.ID, SamplingDecision: samplingDecision, AdditionalData: make(map[string]string), } }
117
aws-xray-sdk-go
aws
Go
package xray import ( "io" "net/http" ) 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) } // Returns a wrapped http.ResponseWriter that implements the same optional interfaces // that the underlying ResponseWriter has. // Handle every possible combination so that code that checks for the existence of each // optional interface functions properly. // Based on https://github.com/felixge/httpsnoop/blob/eadd4fad6aac69ae62379194fe0219f3dbc80fd3/wrap_generated_gteq_1.8.go#L66 func (w *responseCapturer) wrappedResponseWriter() http.ResponseWriter { closeNotifier, isCloseNotifier := w.ResponseWriter.(http.CloseNotifier) flush, isFlusher := w.ResponseWriter.(http.Flusher) hijack, isHijacker := w.ResponseWriter.(http.Hijacker) push, isPusher := w.ResponseWriter.(http.Pusher) readFrom, isReaderFrom := w.ResponseWriter.(io.ReaderFrom) switch { case !isCloseNotifier && !isFlusher && !isHijacker && !isPusher && !isReaderFrom: return struct { http.ResponseWriter }{w} case isCloseNotifier && !isFlusher && !isHijacker && !isPusher && !isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier }{w, closeNotifier} case !isCloseNotifier && isFlusher && !isHijacker && !isPusher && !isReaderFrom: return struct { http.ResponseWriter http.Flusher }{w, flush} case !isCloseNotifier && !isFlusher && isHijacker && !isPusher && !isReaderFrom: return struct { http.ResponseWriter http.Hijacker }{w, hijack} case !isCloseNotifier && !isFlusher && !isHijacker && isPusher && !isReaderFrom: return struct { http.ResponseWriter http.Pusher }{w, push} case !isCloseNotifier && !isFlusher && !isHijacker && !isPusher && isReaderFrom: return struct { http.ResponseWriter io.ReaderFrom }{w, readFrom} case isCloseNotifier && isFlusher && !isHijacker && !isPusher && !isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Flusher }{w, closeNotifier, flush} case isCloseNotifier && !isFlusher && isHijacker && !isPusher && !isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Hijacker }{w, closeNotifier, hijack} case isCloseNotifier && !isFlusher && !isHijacker && isPusher && !isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Pusher }{w, closeNotifier, push} case isCloseNotifier && !isFlusher && !isHijacker && !isPusher && isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier io.ReaderFrom }{w, closeNotifier, readFrom} case !isCloseNotifier && isFlusher && isHijacker && !isPusher && !isReaderFrom: return struct { http.ResponseWriter http.Flusher http.Hijacker }{w, flush, hijack} case !isCloseNotifier && isFlusher && !isHijacker && isPusher && !isReaderFrom: return struct { http.ResponseWriter http.Flusher http.Pusher }{w, flush, push} case !isCloseNotifier && isFlusher && !isHijacker && !isPusher && isReaderFrom: return struct { http.ResponseWriter http.Flusher io.ReaderFrom }{w, flush, readFrom} case !isCloseNotifier && !isFlusher && isHijacker && isPusher && !isReaderFrom: return struct { http.ResponseWriter http.Hijacker http.Pusher }{w, hijack, push} case !isCloseNotifier && !isFlusher && isHijacker && !isPusher && isReaderFrom: return struct { http.ResponseWriter http.Hijacker io.ReaderFrom }{w, hijack, readFrom} case !isCloseNotifier && !isFlusher && !isHijacker && isPusher && isReaderFrom: return struct { http.ResponseWriter http.Pusher io.ReaderFrom }{w, push, readFrom} case isCloseNotifier && isFlusher && isHijacker && !isPusher && !isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Flusher http.Hijacker }{w, closeNotifier, flush, hijack} case isCloseNotifier && isFlusher && !isHijacker && isPusher && !isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Flusher http.Pusher }{w, closeNotifier, flush, push} case isCloseNotifier && isFlusher && !isHijacker && !isPusher && isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Flusher io.ReaderFrom }{w, closeNotifier, flush, readFrom} case isCloseNotifier && !isFlusher && isHijacker && isPusher && !isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Hijacker http.Pusher }{w, closeNotifier, hijack, push} case isCloseNotifier && !isFlusher && isHijacker && !isPusher && isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Hijacker io.ReaderFrom }{w, closeNotifier, hijack, readFrom} case isCloseNotifier && !isFlusher && !isHijacker && isPusher && isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Pusher io.ReaderFrom }{w, closeNotifier, push, readFrom} case !isCloseNotifier && isFlusher && isHijacker && isPusher && !isReaderFrom: return struct { http.ResponseWriter http.Flusher http.Hijacker http.Pusher }{w, flush, hijack, push} case !isCloseNotifier && isFlusher && isHijacker && !isPusher && isReaderFrom: return struct { http.ResponseWriter http.Flusher http.Hijacker io.ReaderFrom }{w, flush, hijack, readFrom} case !isCloseNotifier && isFlusher && !isHijacker && isPusher && isReaderFrom: return struct { http.ResponseWriter http.Flusher http.Pusher io.ReaderFrom }{w, flush, push, readFrom} case !isCloseNotifier && !isFlusher && isHijacker && isPusher && isReaderFrom: return struct { http.ResponseWriter http.Hijacker http.Pusher io.ReaderFrom }{w, hijack, push, readFrom} case isCloseNotifier && isFlusher && isHijacker && isPusher && !isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Flusher http.Hijacker http.Pusher }{w, closeNotifier, flush, hijack, push} case isCloseNotifier && isFlusher && isHijacker && !isPusher && isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Flusher http.Hijacker io.ReaderFrom }{w, closeNotifier, flush, hijack, readFrom} case isCloseNotifier && isFlusher && !isHijacker && isPusher && isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Flusher http.Pusher io.ReaderFrom }{w, closeNotifier, flush, push, readFrom} case isCloseNotifier && !isFlusher && isHijacker && isPusher && isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Hijacker http.Pusher io.ReaderFrom }{w, closeNotifier, hijack, push, readFrom} case !isCloseNotifier && isFlusher && isHijacker && isPusher && isReaderFrom: return struct { http.ResponseWriter http.Flusher http.Hijacker http.Pusher io.ReaderFrom }{w, flush, hijack, push, readFrom} case isCloseNotifier && isFlusher && isHijacker && isPusher && isReaderFrom: return struct { http.ResponseWriter http.CloseNotifier http.Flusher http.Hijacker http.Pusher io.ReaderFrom }{w, closeNotifier, flush, hijack, push, readFrom} default: return struct { http.ResponseWriter }{w} } }
283
aws-xray-sdk-go
aws
Go
// 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" "net/http" "os" "runtime" "strings" "sync/atomic" "time" "github.com/aws/aws-xray-sdk-go/header" "github.com/aws/aws-xray-sdk-go/internal/logger" "github.com/aws/aws-xray-sdk-go/internal/plugins" "github.com/aws/aws-xray-sdk-go/strategy/sampling" ) // 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) } func noOpTraceID() string { return "1-00000000-000000000000000000000000" } func noOpSegmentID() string { return "0000000000000000" } // BeginFacadeSegment creates a Segment for a given name and context. // NOTE: This is an internal API only to be used in Lambda context within the SDK. Consider using BeginSegment instead. func BeginFacadeSegment(ctx context.Context, name string, h *header.Header) (context.Context, *Segment) { seg := basicSegment(name, h) if h == nil { // generates segment and trace id based on sampling decision and AWS_XRAY_NOOP_ID env variable idGeneration(seg) } 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) { return BeginSegmentWithSampling(ctx, name, nil, nil) } func BeginSegmentWithSampling(ctx context.Context, name string, r *http.Request, traceHeader *header.Header) (context.Context, *Segment) { // If SDK is disabled then return with an empty segment if SdkDisabled() { seg := &Segment{} return context.WithValue(ctx, ContextKey, seg), seg } if dName := os.Getenv("AWS_XRAY_TRACING_NAME"); dName != "" { name = dName } 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 } if r == nil || traceHeader == nil { // No header or request information provided so we can only evaluate sampling based on the serviceName sd := seg.ParentSegment.GetConfiguration().SamplingStrategy.ShouldTrace(&sampling.Request{ServiceName: name}) seg.Sampled = sd.Sample logger.Debugf("SamplingStrategy decided: %t", seg.Sampled) seg.AddRuleName(sd) } else { // Sampling strategy for http calls seg.Sampled = traceHeader.SamplingDecision == header.Sampled switch traceHeader.SamplingDecision { case header.Sampled: logger.Debug("Incoming header decided: Sampled=true") case header.NotSampled: logger.Debug("Incoming header decided: Sampled=false") } if traceHeader.SamplingDecision != header.Sampled && traceHeader.SamplingDecision != header.NotSampled { samplingRequest := &sampling.Request{ Host: r.Host, URL: r.URL.Path, Method: r.Method, ServiceName: seg.Name, ServiceType: plugins.InstancePluginMetadata.Origin, } sd := seg.ParentSegment.GetConfiguration().SamplingStrategy.ShouldTrace(samplingRequest) seg.Sampled = sd.Sample logger.Debugf("SamplingStrategy decided: %t", seg.Sampled) seg.AddRuleName(sd) } } // check whether segment is dummy or not based on sampling decision if !seg.ParentSegment.Sampled { seg.Dummy = true } // Dummy segments don't get sent and don't need a goroutine to cancel them. if !seg.Dummy { // Create a new context for to cancel segment. // Start new goroutine to listen for segment close/cancel events. // Cancel simply calls `segment.Close()`. // // This way, even if the client consumes the `ctx.Done()` event, the // X-Ray SDK has a way of canceling (closing) the segment in the // `segment.Close()` method using this new cancellation context. ctx1, cancelCtx := context.WithCancel(ctx) seg.cancelCtx = cancelCtx go func() { <-ctx1.Done() seg.handleContextDone() }() } // generates segment and trace id based on sampling decision and AWS_XRAY_NOOP_ID env variable idGeneration(seg) return context.WithValue(ctx, ContextKey, seg), seg } func idGeneration(seg *Segment) { noOpID := os.Getenv("AWS_XRAY_NOOP_ID") if noOpID != "" && strings.ToLower(noOpID) == "false" { seg.TraceID = NewTraceID() seg.ID = NewSegmentID() } else { if !seg.Sampled { seg.TraceID = noOpTraceID() seg.ID = noOpSegmentID() } else { seg.TraceID = NewTraceID() seg.ID = NewSegmentID() } } } func basicSegment(name string, h *header.Header) *Segment { if len(name) > 200 { name = name[:200] } seg := &Segment{parent: nil} logger.Debugf("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 seg.Dummy = false if h == nil { 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().Emitter = globalCfg.emitter 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.Emitter != nil { seg.GetConfiguration().Emitter = cfg.Emitter } else { seg.GetConfiguration().Emitter = globalCfg.emitter } if cfg.ServiceVersion != "" { seg.GetConfiguration().ServiceVersion = cfg.ServiceVersion } else { seg.GetConfiguration().ServiceVersion = globalCfg.serviceVersion } } seg.Unlock() } func BeginSubsegmentWithoutSampling(ctx context.Context, name string) (context.Context, *Segment) { newCtx, subseg := BeginSubsegment(ctx, name) subseg.Dummy = true subseg.Sampled = false return newCtx, subseg } // BeginSubsegment creates a subsegment for a given name and context. func BeginSubsegment(ctx context.Context, name string) (context.Context, *Segment) { // If SDK is disabled then return with an empty segment if SdkDisabled() { seg := &Segment{} return context.WithValue(ctx, ContextKey, seg), seg } if len(name) > 200 { name = name[:200] } var 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} logger.Debugf("Beginning subsegment named %s", name) seg.Lock() defer seg.Unlock() seg.ParentSegment = parent.ParentSegment // generates subsegment id based on sampling decision and AWS_XRAY_NOOP_ID env variable noOpID := os.Getenv("AWS_XRAY_NOOP_ID") if noOpID != "" && strings.ToLower(noOpID) == "false" { seg.ID = NewSegmentID() } else { if !seg.ParentSegment.Sampled { seg.ID = noOpSegmentID() } else { seg.ID = NewSegmentID() } } // check whether segment is dummy or not based on sampling decision if !seg.ParentSegment.Sampled { seg.Dummy = true } atomic.AddUint32(&seg.ParentSegment.totalSubSegments, 1) parent.Lock() parent.rawSubsegments = append(parent.rawSubsegments, seg) parent.openSegments++ parent.Unlock() seg.Name = name seg.StartTime = float64(time.Now().UnixNano()) / float64(time.Second) seg.InProgress = true seg.Sampled = seg.ParentSegment.Sampled seg.TraceID = seg.ParentSegment.TraceID seg.ParentID = seg.ParentSegment.ID 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, r *http.Request, h *header.Header) (context.Context, *Segment) { con, seg := BeginSegmentWithSampling(ctx, name, r, h) if h.TraceID != "" { seg.TraceID = h.TraceID } if h.ParentID != "" { seg.ParentID = h.ParentID } seg.IncomingHeader = h seg.RequestWasTraced = true return con, seg } // Check if SDK is disabled func SdkDisabled() bool { disableKey := os.Getenv("AWS_XRAY_SDK_DISABLED") return strings.ToLower(disableKey) == "true" } // Close a segment. func (seg *Segment) Close(err error) { // If SDK is disabled then return if SdkDisabled() { return } if seg == nil { logger.Debugf("No input subsegment to end. No-op") return } seg.Lock() if seg.parent != nil { logger.Debugf("Closing subsegment named %s", seg.Name) } else { logger.Debugf("Closing segment named %s", seg.Name) } seg.EndTime = float64(time.Now().UnixNano()) / float64(time.Second) seg.InProgress = false if err != nil { seg.addError(err) } cancelSegCtx := seg.cancelCtx seg.Unlock() // If a goroutine was started to close the extra context (made for // cancelling the segment), stop the goroutine before we close the segment // and lose access to it. if cancelSegCtx != nil { cancelSegCtx() } // If segment is dummy we return if seg.Dummy { return } seg.send() } // CloseAndStream closes a subsegment and sends it. func (seg *Segment) CloseAndStream(err error) { // If SDK is disabled then return if SdkDisabled() { return } if seg.parent != nil { logger.Debugf("Ending subsegment named: %s", seg.Name) seg.Lock() seg.EndTime = float64(time.Now().UnixNano()) / float64(time.Second) seg.InProgress = false seg.Emitted = true seg.Unlock() if seg.parent.RemoveSubsegment(seg) { logger.Debugf("Removing subsegment named: %s", seg.Name) } } seg.Lock() defer seg.Unlock() if err != nil { seg.addError(err) } // If segment is dummy we return if seg.Dummy { return } seg.beforeEmitSubsegment(seg.parent) seg.emit() } // RemoveSubsegment removes a subsegment child from a segment or subsegment. func (seg *Segment) RemoveSubsegment(remove *Segment) bool { seg.Lock() 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.openSegments-- if seg.ParentSegment != seg { seg.Unlock() atomic.AddUint32(&seg.ParentSegment.totalSubSegments, ^uint32(0)) } else { seg.Unlock() } return true } } seg.Unlock() return false } func (seg *Segment) isOrphan() bool { return seg.parent == nil || seg.Type == "subsegment" } func (seg *Segment) emit() { seg.ParentSegment.GetConfiguration().Emitter.Emit(seg) } func (seg *Segment) handleContextDone() { seg.Lock() seg.ContextDone = true if !seg.InProgress && !seg.Emitted { seg.Unlock() seg.send() } else { seg.Unlock() } } // send tries to emit the current (Sub)Segment. If the (Sub)Segment is ready to send, // it emits out. If it is ready but has non-nil parent, it traverses to parent and checks whether parent is // ready to send and sends entire subtree from the parent. The locking and traversal of the tree // is from child to parent. This method is thread safe. func (seg *Segment) send() { s := seg s.Lock() for { if s.flush() { s.Unlock() break } tmp := s.parent s.Unlock() s = tmp s.Lock() s.openSegments-- } } // flush emits (Sub)Segment, if it is ready to send. // The caller of flush should have write lock on seg instance. func (seg *Segment) flush() bool { if (seg.openSegments == 0 && seg.EndTime > 0) || seg.ContextDone { if seg.isOrphan() { seg.Emitted = true seg.emit() } else if seg.parent != nil && seg.parent.Facade { seg.Emitted = true seg.beforeEmitSubsegment(seg.parent) logger.Debugf("emit lambda subsegment named: %v", seg.Name) seg.emit() } else { return false } } return true } func (seg *Segment) safeInProgress() bool { seg.RLock() b := seg.InProgress seg.RUnlock() return b } // getName returns name of the segment. This method is thread safe. func (seg *Segment) getName() string { seg.RLock() n := seg.Name seg.RUnlock() return n } 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().Runtime = runtime.Compiler seg.GetService().RuntimeVersion = runtime.Version() } func (seg *Segment) beforeEmitSubsegment(s *Segment) { // Only called within a subsegment locked code block seg.TraceID = s.root().TraceID seg.ParentID = s.ID seg.Type = "subsegment" seg.RequestWasTraced = s.RequestWasTraced } // AddAnnotation allows adding an annotation to the segment. func (seg *Segment) AddAnnotation(key string, value interface{}) error { // If SDK is disabled then return if SdkDisabled() { return nil } seg.Lock() defer seg.Unlock() // If segment is dummy we return if seg.Dummy { return nil } 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) } 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 { // If SDK is disabled then return if SdkDisabled() { return nil } seg.Lock() defer seg.Unlock() // If segment is dummy we return if seg.Dummy { return nil } 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 { // If SDK is disabled then return if SdkDisabled() { return nil } seg.Lock() defer seg.Unlock() // If segment is dummy we return if seg.Dummy { return nil } 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 { // If SDK is disabled then return if SdkDisabled() { return nil } seg.Lock() defer seg.Unlock() seg.addError(err) return nil } func (seg *Segment) addError(err error) { seg.Fault = true seg.GetCause().WorkingDirectory, _ = os.Getwd() seg.GetCause().Exceptions = append(seg.GetCause().Exceptions, seg.ParentSegment.GetConfiguration().ExceptionFormattingStrategy.ExceptionFromError(err)) }
681
aws-xray-sdk-go
aws
Go
// 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" "encoding/json" "sync" "github.com/aws/aws-xray-sdk-go/header" "github.com/aws/aws-xray-sdk-go/strategy/exception" "github.com/aws/aws-xray-sdk-go/strategy/sampling" ) // Segment provides the resource's name, details about the request, and details about the work done. type Segment struct { sync.RWMutex parent *Segment openSegments int totalSubSegments uint32 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). // cancels the context bound to this Segment, after Segment is closed cancelCtx context.CancelFunc // 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:"-"` // Dummy Segment flag Dummy bool } // 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"` RuntimeVersion string `json:"runtime_version,omitempty"` Runtime string `json:"runtime,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 := &header.Header{} // If SDK is disabled then return with an empty header if SdkDisabled() { return r } if parent := s.ParentSegment.IncomingHeader; parent != nil { *r = *parent // copy parent incoming header } 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 } // AddRuleName adds rule name, if present from sampling decision to xray context. func (s *Segment) AddRuleName(sd *sampling.Decision) { if sd.Rule != nil { sdk := s.GetAWS()["xray"].(SDK) sdk.RuleName = *sd.Rule s.GetAWS()["xray"] = sdk } }
229
aws-xray-sdk-go
aws
Go
// 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" "net/http" "net/url" "os" "sync" "testing" "time" "github.com/aws/aws-xray-sdk-go/header" "github.com/stretchr/testify/assert" ) func TestSegmentDataRace(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, cancel := context.WithCancel(ctx) defer cancel() var wg sync.WaitGroup n := 100 wg.Add(n) for i := 0; i < n; i++ { // flaky data race test, so we run it multiple times _, seg := BeginSegment(ctx, "TestSegment") go func() { defer wg.Done() seg.Close(nil) }() } cancel() wg.Wait() } func TestSubsegmentDataRace(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "TestSegment") defer seg.Close(nil) var wg sync.WaitGroup n := 5 wg.Add(n) for i := 0; i < n; i++ { go func() { defer wg.Done() ctx, seg := BeginSubsegment(ctx, "TestSubsegment1") _, seg2 := BeginSubsegment(ctx, "TestSubsegment2") seg2.Close(nil) seg.Close(nil) }() } wg.Wait() } func TestSubsegmentDataRaceWithContextCancel(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, cancel := context.WithCancel(ctx) defer cancel() ctx, seg := BeginSegment(ctx, "TestSegment") wg := sync.WaitGroup{} for i := 0; i < 4; i++ { if i != 3 { wg.Add(1) } go func(i int) { if i != 3 { time.Sleep(1) defer wg.Done() } _, seg := BeginSubsegment(ctx, "TestSubsegment1") seg.Close(nil) if i == 3 { cancel() // Context is cancelled abruptly } }(i) } wg.Wait() seg.Close(nil) } func TestSegmentDownstreamHeader(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := NewSegmentFromHeader(ctx, "TestSegment", &http.Request{URL: &url.URL{}}, &header.Header{ TraceID: "fakeid", ParentID: "reqid", }) defer seg.Close(nil) var wg sync.WaitGroup n := 2 wg.Add(n) for i := 0; i < n; i++ { go func() { _, seg2 := BeginSubsegment(ctx, "TestSubsegment") seg2.DownstreamHeader() // simulate roundtripper.RoundTrip sets TraceIDHeaderKey wg.Done() }() } wg.Wait() } func TestParentSegmentTotalCount(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "test") var wg sync.WaitGroup n := 2 wg.Add(2 * n) for i := 0; i < n; i++ { go func(ctx context.Context) { // add async nested subsegments c1, _ := BeginSubsegment(ctx, "TestSubsegment1") c2, _ := BeginSubsegment(c1, "TestSubsegment2") go func(ctx context.Context) { // add async nested subsegments c1, _ := BeginSubsegment(ctx, "TestSubsegment1") BeginSubsegment(c1, "TestSubsegment2") wg.Done() }(c2) // passing context wg.Done() }(ctx) } wg.Wait() assert.Equal(t, 4*uint32(n), seg.ParentSegment.totalSubSegments, "totalSubSegments count should be correctly registered on the parent segment") } func TestSegment_Close(t *testing.T) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "test") seg.Close(nil) // for backwards compatibility, closing the Segment should not cancel the returned Context assert.NoError(t, ctx.Err()) } func TestSegment_isDummy(t *testing.T) { ctx, root := BeginSegment(context.Background(), "Segment") ctxSubSeg1, subSeg1 := BeginSubsegment(ctx, "Subsegment1") _, subSeg2 := BeginSubsegment(ctxSubSeg1, "Subsegment2") subSeg2.Close(nil) subSeg1.Close(nil) root.Close(nil) assert.False(t, root.Dummy) assert.False(t, subSeg1.Dummy) assert.False(t, subSeg2.Dummy) } func TestSDKDisable_inOrder(t *testing.T) { os.Setenv("AWS_XRAY_SDK_DISABLED", "TRue") ctx, td := NewTestDaemon() defer td.Close() ctx, root := BeginSegment(ctx, "Segment") ctxSubSeg1, subSeg1 := BeginSubsegment(ctx, "Subsegment1") _, subSeg2 := BeginSubsegment(ctxSubSeg1, "Subsegment2") subSeg2.Close(nil) subSeg1.Close(nil) root.Close(nil) assert.Equal(t, root, &Segment{}) assert.Equal(t, subSeg1, &Segment{}) assert.Equal(t, subSeg2, &Segment{}) os.Setenv("AWS_XRAY_SDK_DISABLED", "FALSE") } func TestSDKDisable_outOrder(t *testing.T) { os.Setenv("AWS_XRAY_SDK_DISABLED", "TRUE") ctx, td := NewTestDaemon() defer td.Close() _, subSeg := BeginSubsegment(ctx, "Subsegment1") _, seg := BeginSegment(context.Background(), "Segment") subSeg.Close(nil) seg.Close(nil) assert.Equal(t, subSeg, &Segment{}) assert.Equal(t, seg, &Segment{}) os.Setenv("AWS_XRAY_SDK_DISABLED", "FALSE") } func TestSDKDisable_otherMethods(t *testing.T) { os.Setenv("AWS_XRAY_SDK_DISABLED", "true") ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "Segment") _, subSeg := BeginSubsegment(ctx, "Subsegment1") if err := seg.AddAnnotation("key", "value"); err != nil { return } if err := seg.AddMetadata("key", "value"); err != nil { return } seg.DownstreamHeader() subSeg.Close(nil) seg.Close(nil) assert.Equal(t, seg, &Segment{}) assert.Equal(t, subSeg, &Segment{}) os.Setenv("AWS_XRAY_SDK_DISABLED", "FALSE") } func TestIDGeneration_noOPTrue(t *testing.T) { os.Setenv("AWS_XRAY_NOOP_ID", "true") seg := &Segment{parent: nil} seg.Sampled = false idGeneration(seg) assert.Equal(t, seg.Sampled, false) assert.Equal(t, seg.TraceID, "1-00000000-000000000000000000000000") assert.Equal(t, seg.ID, "0000000000000000") os.Unsetenv("AWS_XRAY_NOOP_ID") } func TestIDGeneration_noOpFalse(t *testing.T) { os.Setenv("AWS_XRAY_NOOP_ID", "FALSE") seg := &Segment{parent: nil} seg.Sampled = false idGeneration(seg) assert.Equal(t, seg.Sampled, false) assert.NotEqual(t, seg.TraceID, "1-00000000-000000000000000000000000") assert.NotEqual(t, seg.ID, "0000000000000000") os.Unsetenv("AWS_XRAY_NOOP_ID") } func TestIDGeneration_samplingFalse(t *testing.T) { seg := &Segment{parent: nil} seg.Sampled = false idGeneration(seg) assert.Equal(t, seg.Sampled, false) assert.Equal(t, seg.TraceID, "1-00000000-000000000000000000000000") assert.Equal(t, seg.ID, "0000000000000000") } func TestIDGeneration_samplingTrue(t *testing.T) { seg := &Segment{parent: nil} seg.Sampled = true idGeneration(seg) assert.Equal(t, seg.Sampled, true) assert.NotEqual(t, seg.TraceID, "1-00000000-000000000000000000000000") assert.NotEqual(t, seg.ID, "0000000000000000") } func TestIDGeneration_segSubSeg(t *testing.T) { os.Setenv("AWS_XRAY_NOOP_ID", "true") ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "Segment") _, subSeg := BeginSubsegment(ctx, "Subegment1") subSeg.Close(nil) seg.Close(nil) assert.Equal(t, seg.Sampled, true) assert.NotEqual(t, seg.TraceID, "1-00000000-000000000000000000000000") assert.NotEqual(t, seg.ID, "0000000000000000") assert.NotEqual(t, subSeg.ID, "0000000000000000") os.Unsetenv("AWS_XRAY_NOOP_ID") } // Benchmarks func BenchmarkBeginSegment(b *testing.B) { ctx, td := NewTestDaemon() defer td.Close() for i := 0; i < b.N; i++ { _, seg := BeginSegment(ctx, "TestBenchSeg") seg.Close(nil) } } func BenchmarkBeginSubsegment(b *testing.B) { ctx, td := NewTestDaemon() defer td.Close() ctx, seg := BeginSegment(ctx, "TestBenchSeg") for i := 0; i < b.N; i++ { _, subSeg := BeginSubsegment(ctx, "TestBenchSubSeg") subSeg.Close(nil) } seg.Sampled = false seg.Close(nil) } func BenchmarkAddError(b *testing.B) { ctx, td := NewTestDaemon() defer td.Close() _, seg := BeginSegment(ctx, "TestBenchSeg") for i := 0; i < b.N; i++ { seg.AddError(errors.New("new error")) } seg.Sampled = false seg.Close(nil) } func BenchmarkIdGeneration_noOpTrue(b *testing.B) { os.Setenv("AWS_XRAY_NOOP_ID", "true") seg := &Segment{parent: nil} for i := 0; i < b.N; i++ { idGeneration(seg) } os.Unsetenv("AWS_XRAY_NOOP_ID") } func BenchmarkIdGeneration_noOpFalse(b *testing.B) { os.Setenv("AWS_XRAY_NOOP_ID", "false") seg := &Segment{parent: nil} for i := 0; i < b.N; i++ { idGeneration(seg) } os.Unsetenv("AWS_XRAY_NOOP_ID") } func TestBeginSegmentNameFromEnv(t *testing.T) { os.Setenv("AWS_XRAY_TRACING_NAME", "test_env") _, n := BeginSegment(context.Background(), "test") assert.Equal(t, "test_env", n.Name) os.Unsetenv("AWS_XRAY_TRACING_NAME") n.Close(nil) }
346
aws-xray-sdk-go
aws
Go
// 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" "testing" "github.com/DATA-DOG/go-sqlmock" "github.com/stretchr/testify/assert" ) // utility functions for testing SQL func mockPostgreSQL(mock sqlmock.Sqlmock, err error) { row := sqlmock.NewRows([]string{"version()", "current_user", "current_database()"}). AddRow("test version", "test user", "test database"). RowError(0, err) mock.ExpectPrepare(`SELECT version\(\), current_user, current_database\(\)`).ExpectQuery().WillReturnRows(row) } func mockMySQL(mock sqlmock.Sqlmock, err error) { row := sqlmock.NewRows([]string{"version()", "current_user()", "database()"}). AddRow("test version", "test user", "test database"). RowError(0, err) mock.ExpectPrepare(`SELECT version\(\), current_user\(\), database\(\)`).ExpectQuery().WillReturnRows(row) } func mockMSSQL(mock sqlmock.Sqlmock, err error) { row := sqlmock.NewRows([]string{"@@version", "current_user", "db_name()"}). AddRow("test version", "test user", "test database"). RowError(0, err) mock.ExpectPrepare(`SELECT @@version, current_user, db_name\(\)`).ExpectQuery().WillReturnRows(row) } func mockOracle(mock sqlmock.Sqlmock, err error) { row := sqlmock.NewRows([]string{"version", "user", "ora_database_name"}). AddRow("test version", "test user", "test database"). RowError(0, err) mock.ExpectPrepare(`SELECT version FROM v\$instance UNION SELECT user, ora_database_name FROM dual`).ExpectQuery().WillReturnRows(row) } func capturePing(dsn string) (*Segment, error) { ctx, td := NewTestDaemon() defer td.Close() db, err := SQLContext("sqlmock", dsn) if err != nil { return nil, err } defer db.Close() ctx, root := BeginSegment(ctx, "test") if err := db.PingContext(ctx); err != nil { return nil, err } root.Close(nil) seg, err := td.Recv() if err != nil { return nil, err } var subseg *Segment if err := json.Unmarshal(seg.Subsegments[0], &subseg); err != nil { return nil, err } return subseg, nil } func TestDSN(t *testing.T) { tc := []struct { dsn string url string str string name string }{ { dsn: "postgres://user@host:5432/database", url: "postgres://user@host:5432/database", name: "test database@host", }, { dsn: "postgres://user:password@host:5432/database", url: "postgres://user@host:5432/database", name: "test database@host", }, { dsn: "postgres://host:5432/database?password=password", url: "postgres://host:5432/database", name: "test database@host", }, { dsn: "user:password@host:5432/database", url: "user@host:5432/database", name: "test database@host", }, { dsn: "host:5432/database?password=password", url: "host:5432/database", name: "test database@host", }, { dsn: "user%2Fpassword@host:5432/database", url: "user@host:5432/database", name: "test database@host", }, { dsn: "user/password@host:5432/database", url: "user@host:5432/database", name: "test database@host", }, { dsn: "user=user database=database", str: "user=user database=database", name: "test database", }, { dsn: "user=user password=password database=database", str: "user=user database=database", name: "test database", }, { dsn: "odbc:server=localhost;user id=sa;password={foo}};bar};otherthing=thing", str: "odbc:server=localhost;user id=sa;otherthing=thing", name: "test database", }, { dsn: "postgres://host:5432/database?X-Amz-Security-Token=token", url: "postgres://host:5432/database", name: "test database@host", }, { dsn: "host:5432/database?X-Amz-Security-Token=token", url: "host:5432/database", name: "test database@host", }, } for _, tt := range tc { tt := tt t.Run(tt.dsn, func(t *testing.T) { db, mock, err := sqlmock.NewWithDSN(tt.dsn) if err != nil { t.Fatal(err) } defer db.Close() mockPostgreSQL(mock, nil) subseg, err := capturePing(tt.dsn) if err != nil { t.Fatal(err) } assert.NoError(t, mock.ExpectationsWereMet()) assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, "Postgres", subseg.SQL.DatabaseType) assert.Equal(t, tt.url, subseg.SQL.URL) assert.Equal(t, tt.str, subseg.SQL.ConnectionString) assert.Equal(t, "test version", subseg.SQL.DatabaseVersion) assert.Equal(t, "test user", subseg.SQL.User) assert.Equal(t, tt.name, subseg.Name) assert.False(t, subseg.Throttle) assert.False(t, subseg.Error) assert.False(t, subseg.Fault) }) } } func TestPostgreSQL(t *testing.T) { dsn := "test-postgre" db, mock, err := sqlmock.NewWithDSN(dsn) if err != nil { t.Fatal(err) } defer db.Close() mockPostgreSQL(mock, nil) subseg, err := capturePing(dsn) if err != nil { t.Fatal(err) } assert.NoError(t, mock.ExpectationsWereMet()) assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, "Postgres", subseg.SQL.DatabaseType) assert.Equal(t, "", subseg.SQL.URL) assert.Equal(t, dsn, subseg.SQL.ConnectionString) assert.Equal(t, "test version", subseg.SQL.DatabaseVersion) assert.Equal(t, "test user", subseg.SQL.User) assert.False(t, subseg.Throttle) assert.False(t, subseg.Error) assert.False(t, subseg.Fault) } func TestMySQL(t *testing.T) { dsn := "test-mysql" db, mock, err := sqlmock.NewWithDSN(dsn) if err != nil { t.Fatal(err) } defer db.Close() mockPostgreSQL(mock, errors.New("syntax error")) mockMySQL(mock, nil) subseg, err := capturePing(dsn) if err != nil { t.Fatal(err) } assert.NoError(t, mock.ExpectationsWereMet()) assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, "MySQL", subseg.SQL.DatabaseType) assert.Equal(t, "", subseg.SQL.URL) assert.Equal(t, dsn, subseg.SQL.ConnectionString) assert.Equal(t, "test version", subseg.SQL.DatabaseVersion) assert.Equal(t, "test user", subseg.SQL.User) assert.False(t, subseg.Throttle) assert.False(t, subseg.Error) assert.False(t, subseg.Fault) } func TestMSSQL(t *testing.T) { dsn := "test-mssql" db, mock, err := sqlmock.NewWithDSN(dsn) if err != nil { t.Fatal(err) } defer db.Close() mockPostgreSQL(mock, errors.New("syntax error")) mockMySQL(mock, errors.New("syntax error")) mockMSSQL(mock, nil) subseg, err := capturePing(dsn) if err != nil { t.Fatal(err) } assert.NoError(t, mock.ExpectationsWereMet()) assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, "MS SQL", subseg.SQL.DatabaseType) assert.Equal(t, "", subseg.SQL.URL) assert.Equal(t, dsn, subseg.SQL.ConnectionString) assert.Equal(t, "test version", subseg.SQL.DatabaseVersion) assert.Equal(t, "test user", subseg.SQL.User) assert.False(t, subseg.Throttle) assert.False(t, subseg.Error) assert.False(t, subseg.Fault) } func TestOracle(t *testing.T) { dsn := "test-oracle" db, mock, err := sqlmock.NewWithDSN(dsn) if err != nil { t.Fatal(err) } defer db.Close() mockPostgreSQL(mock, errors.New("syntax error")) mockMySQL(mock, errors.New("syntax error")) mockMSSQL(mock, errors.New("syntax error")) mockOracle(mock, nil) subseg, err := capturePing(dsn) if err != nil { t.Fatal(err) } assert.NoError(t, mock.ExpectationsWereMet()) assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, "Oracle", subseg.SQL.DatabaseType) assert.Equal(t, "", subseg.SQL.URL) assert.Equal(t, dsn, subseg.SQL.ConnectionString) assert.Equal(t, "test version", subseg.SQL.DatabaseVersion) assert.Equal(t, "test user", subseg.SQL.User) assert.False(t, subseg.Throttle) assert.False(t, subseg.Error) assert.False(t, subseg.Fault) } func TestUnknownDatabase(t *testing.T) { dsn := "test-unknown" db, mock, err := sqlmock.NewWithDSN(dsn) if err != nil { t.Fatal(err) } defer db.Close() mockPostgreSQL(mock, errors.New("syntax error")) mockMySQL(mock, errors.New("syntax error")) mockMSSQL(mock, errors.New("syntax error")) mockOracle(mock, errors.New("syntax error")) subseg, err := capturePing(dsn) if err != nil { t.Fatal(err) } assert.NoError(t, mock.ExpectationsWereMet()) assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, "Unknown", subseg.SQL.DatabaseType) assert.Equal(t, "", subseg.SQL.URL) assert.Equal(t, dsn, subseg.SQL.ConnectionString) assert.Equal(t, "Unknown", subseg.SQL.DatabaseVersion) assert.Equal(t, "Unknown", subseg.SQL.User) assert.False(t, subseg.Throttle) assert.False(t, subseg.Error) assert.False(t, subseg.Fault) } func TestStripPasswords(t *testing.T) { tc := []struct { in string want string }{ { in: "user=user database=database", want: "user=user database=database", }, { in: "user=user password=password database=database", want: "user=user database=database", }, { in: "odbc:server=localhost;user id=sa;password={foo}};bar};otherthing=thing", want: "odbc:server=localhost;user id=sa;otherthing=thing", }, // see https://github.com/aws/aws-xray-sdk-go/issues/181 { in: "password=", want: "", }, { in: "pwd=", want: "", }, // test cases for https://github.com/go-sql-driver/mysql { in: "user:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true", want: "user@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true", }, { in: "user@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true", want: "user@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true", }, { in: "user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci", want: "user@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci", }, { in: "user@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci", want: "user@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci", }, { in: "user:password@/", want: "user@/", }, } for _, tt := range tc { got := stripPasswords(tt.in) if got != tt.want { t.Errorf("%s: want %s, got %s", tt.in, tt.want, got) } } }
375
aws-xray-sdk-go
aws
Go
// 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" "errors" "fmt" "net" "net/url" "reflect" "strconv" "strings" "sync" "time" ) // we can't know that the original driver will return driver.ErrSkip in advance. // so we add this message to the query if it returns driver.ErrSkip. const msgErrSkip = " -- skip fast-path; continue as if unimplemented" // namedValueChecker is the same as driver.NamedValueChecker. // Copied from database/sql/driver/driver.go for supporting Go 1.8. type namedValueChecker interface { // CheckNamedValue is called before passing arguments to the driver // and is called in place of any ColumnConverter. CheckNamedValue must do type // validation and conversion as appropriate for the driver. CheckNamedValue(*driver.NamedValue) error } var ( muInitializedDrivers sync.Mutex initializedDrivers map[string]struct{} attrHook func(attr *dbAttribute) // for testing ) func initXRayDriver(driver, dsn string) error { muInitializedDrivers.Lock() defer muInitializedDrivers.Unlock() if initializedDrivers == nil { initializedDrivers = map[string]struct{}{} } if _, ok := initializedDrivers[driver]; ok { return nil } db, err := sql.Open(driver, dsn) if err != nil { return err } sql.Register(driver+":xray", &driverDriver{ Driver: db.Driver(), baseName: driver, }) initializedDrivers[driver] = struct{}{} db.Close() return nil } // SQLContext 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: `<schema>://<user>:<password>@<host>:<port>/<database>` func SQLContext(driver, dsn string) (*sql.DB, error) { if err := initXRayDriver(driver, dsn); err != nil { return nil, err } return sql.Open(driver+":xray", dsn) } type driverDriver struct { driver.Driver baseName string // the name of the base driver } func (d *driverDriver) Open(dsn string) (driver.Conn, error) { rawConn, err := d.Driver.Open(dsn) if err != nil { return nil, err } attr, err := newDBAttribute(context.Background(), d.baseName, d.Driver, rawConn, dsn, false) if err != nil { rawConn.Close() return nil, err } conn := &driverConn{ Conn: rawConn, attr: attr, } return conn, nil } type driverConn struct { driver.Conn attr *dbAttribute } func (conn *driverConn) Ping(ctx context.Context) error { return Capture(ctx, conn.attr.dbname+conn.attr.host, func(ctx context.Context) error { conn.attr.populate(ctx, "PING") if p, ok := conn.Conn.(driver.Pinger); ok { return p.Ping(ctx) } return nil }) } func (conn *driverConn) Prepare(query string) (driver.Stmt, error) { panic("not supported") } func (conn *driverConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { var stmt driver.Stmt var err error if connCtx, ok := conn.Conn.(driver.ConnPrepareContext); ok { stmt, err = connCtx.PrepareContext(ctx, query) } else { stmt, err = conn.Conn.Prepare(query) if err == nil { select { default: case <-ctx.Done(): stmt.Close() return nil, ctx.Err() } } } if err != nil { return nil, err } return &driverStmt{ Stmt: stmt, attr: conn.attr, query: query, conn: conn, }, nil } func (conn *driverConn) Begin() (driver.Tx, error) { panic("not supported") } func (conn *driverConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { var tx driver.Tx var err error if connCtx, ok := conn.Conn.(driver.ConnBeginTx); ok { tx, err = connCtx.BeginTx(ctx, opts) } else { if opts.Isolation != driver.IsolationLevel(sql.LevelDefault) { return nil, errors.New("xray: driver does not support non-default isolation level") } if opts.ReadOnly { return nil, errors.New("xray: driver does not support read-only transactions") } tx, err = conn.Conn.Begin() if err == nil { select { default: case <-ctx.Done(): tx.Rollback() return nil, ctx.Err() } } } if err != nil { return nil, err } return &driverTx{Tx: tx}, nil } func (conn *driverConn) Exec(query string, args []driver.Value) (driver.Result, error) { panic("not supported") } func (conn *driverConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { var err error var result driver.Result if execerCtx, ok := conn.Conn.(driver.ExecerContext); ok { Capture(ctx, conn.attr.dbname+conn.attr.host, func(ctx context.Context) error { result, err = execerCtx.ExecContext(ctx, query, args) if err == driver.ErrSkip { conn.attr.populate(ctx, query+msgErrSkip) return nil } conn.attr.populate(ctx, query) return err }) } else { select { default: case <-ctx.Done(): return nil, ctx.Err() } execer, ok := conn.Conn.(driver.Execer) if !ok { return nil, driver.ErrSkip } dargs, err0 := namedValuesToValues(args) if err0 != nil { return nil, err0 } Capture(ctx, conn.attr.dbname+conn.attr.host, func(ctx context.Context) error { var err error result, err = execer.Exec(query, dargs) if err == driver.ErrSkip { conn.attr.populate(ctx, query+msgErrSkip) return nil } conn.attr.populate(ctx, query) return err }) } return result, err } func (conn *driverConn) Query(query string, args []driver.Value) (driver.Rows, error) { panic("not supported") } func (conn *driverConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { var err error var rows driver.Rows if queryerCtx, ok := conn.Conn.(driver.QueryerContext); ok { Capture(ctx, conn.attr.dbname+conn.attr.host, func(ctx context.Context) error { rows, err = queryerCtx.QueryContext(ctx, query, args) if err == driver.ErrSkip { conn.attr.populate(ctx, query+msgErrSkip) return nil } conn.attr.populate(ctx, query) return err }) } else { select { default: case <-ctx.Done(): return nil, ctx.Err() } queryer, ok := conn.Conn.(driver.Queryer) if !ok { return nil, driver.ErrSkip } dargs, err0 := namedValuesToValues(args) if err0 != nil { return nil, err0 } err = Capture(ctx, conn.attr.dbname+conn.attr.host, func(ctx context.Context) error { rows, err = queryer.Query(query, dargs) if err == driver.ErrSkip { conn.attr.populate(ctx, query+msgErrSkip) return nil } conn.attr.populate(ctx, query) return err }) } return rows, err } func (conn *driverConn) Close() error { return conn.Conn.Close() } // copied from https://github.com/golang/go/blob/e6ebbe0d20fe877b111cf4ccf8349cba129d6d3a/src/database/sql/convert.go#L93-L99 // defaultCheckNamedValue wraps the default ColumnConverter to have the same // function signature as the CheckNamedValue in the driver.NamedValueChecker // interface. func defaultCheckNamedValue(nv *driver.NamedValue) (err error) { nv.Value, err = driver.DefaultParameterConverter.ConvertValue(nv.Value) return err } // CheckNamedValue for implementing driver.NamedValueChecker // This function may be unnecessary because `proxy.Stmt` already implements `NamedValueChecker`, // but it is implemented just in case. func (conn *driverConn) CheckNamedValue(nv *driver.NamedValue) (err error) { if nvc, ok := conn.Conn.(namedValueChecker); ok { return nvc.CheckNamedValue(nv) } // fallback to default return defaultCheckNamedValue(nv) } type dbAttribute struct { connectionString string url string databaseType string databaseVersion string driverVersion string user string dbname string host string } func newDBAttribute(ctx context.Context, driverName string, d driver.Driver, conn driver.Conn, dsn string, filtered bool) (*dbAttribute, error) { var attr dbAttribute // 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, err = url.Parse(fmt.Sprintf("%s//%s%%2F%s", u.Scheme, u.Host, u.Path[1:])) if err != nil { return nil, err } } // 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 and X-Amz-Security-Token (present in RDS IAM authentication) from query parameters q := u.Query() q.Del("password") q.Del("X-Amz-Security-Token") u.RawQuery = q.Encode() // In the case of known DSL sub segment name will be dbname@host host, _, _ := net.SplitHostPort(u.Host) if len(host) > 0 { attr.host = "@" + host } else { attr.host = host } attr.url = u.String() if !strings.Contains(dsn, "//") { attr.url = attr.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. if filtered { attr.connectionString = dsn } else { attr.connectionString = stripPasswords(dsn) } } // Detect database type and use that to populate attributes var detectors []func(ctx context.Context, conn driver.Conn, attr *dbAttribute) error switch driverName { 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(ctx, conn, &attr) == nil { break } attr.databaseType = "Unknown" attr.databaseVersion = "Unknown" attr.user = "Unknown" attr.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 } if vd, ok := d.(versionedDriver); ok { attr.driverVersion = vd.Version() } else { t := reflect.TypeOf(d) for t.Kind() == reflect.Ptr { t = t.Elem() } attr.driverVersion = t.PkgPath() } if attrHook != nil { attrHook(&attr) } return &attr, nil } func postgresDetector(ctx context.Context, conn driver.Conn, attr *dbAttribute) error { attr.databaseType = "Postgres" return queryRow( ctx, conn, "SELECT version(), current_user, current_database()", &attr.databaseVersion, &attr.user, &attr.dbname, ) } func mysqlDetector(ctx context.Context, conn driver.Conn, attr *dbAttribute) error { attr.databaseType = "MySQL" return queryRow( ctx, conn, "SELECT version(), current_user(), database()", &attr.databaseVersion, &attr.user, &attr.dbname, ) } func mssqlDetector(ctx context.Context, conn driver.Conn, attr *dbAttribute) error { attr.databaseType = "MS SQL" return queryRow( ctx, conn, "SELECT @@version, current_user, db_name()", &attr.databaseVersion, &attr.user, &attr.dbname, ) } func oracleDetector(ctx context.Context, conn driver.Conn, attr *dbAttribute) error { attr.databaseType = "Oracle" return queryRow( ctx, conn, "SELECT version FROM v$instance UNION SELECT user, ora_database_name FROM dual", &attr.databaseVersion, &attr.user, &attr.dbname, ) } // minimum implementation of (*sql.DB).QueryRow func queryRow(ctx context.Context, conn driver.Conn, query string, dest ...*string) error { var err error // prepare var stmt driver.Stmt if connCtx, ok := conn.(driver.ConnPrepareContext); ok { stmt, err = connCtx.PrepareContext(ctx, query) } else { stmt, err = conn.Prepare(query) if err == nil { select { default: case <-ctx.Done(): stmt.Close() return ctx.Err() } } } if err != nil { return err } defer stmt.Close() // execute query var rows driver.Rows if queryCtx, ok := stmt.(driver.StmtQueryContext); ok { rows, err = queryCtx.QueryContext(ctx, []driver.NamedValue{}) } else { select { default: case <-ctx.Done(): return ctx.Err() } rows, err = stmt.Query([]driver.Value{}) } if err != nil { return err } defer rows.Close() // scan if len(dest) != len(rows.Columns()) { return fmt.Errorf("xray: expected %d destination arguments in Scan, not %d", len(rows.Columns()), len(dest)) } cols := make([]driver.Value, len(rows.Columns())) if err := rows.Next(cols); err != nil { return err } for i, src := range cols { d := dest[i] switch s := src.(type) { case string: *d = s case []byte: *d = string(s) case time.Time: *d = s.Format(time.RFC3339Nano) case int64: *d = strconv.FormatInt(s, 10) case float64: *d = strconv.FormatFloat(s, 'g', -1, 64) case bool: *d = strconv.FormatBool(s) default: return fmt.Errorf("sql: Scan error on column index %d, name %q: type missmatch", i, rows.Columns()[i]) } } return nil } func (attr *dbAttribute) populate(ctx context.Context, query string) { seg := GetSegment(ctx) if seg == nil { processNilSegment(ctx) return } seg.Lock() seg.Namespace = "remote" seg.GetSQL().ConnectionString = attr.connectionString seg.GetSQL().URL = attr.url seg.GetSQL().DatabaseType = attr.databaseType seg.GetSQL().DatabaseVersion = attr.databaseVersion seg.GetSQL().DriverVersion = attr.driverVersion seg.GetSQL().User = attr.user seg.GetSQL().SanitizedQuery = query seg.Unlock() } type driverTx struct { driver.Tx } func (tx *driverTx) Commit() error { return tx.Tx.Commit() } func (tx *driverTx) Rollback() error { return tx.Tx.Rollback() } type driverStmt struct { driver.Stmt conn *driverConn attr *dbAttribute query string } func (stmt *driverStmt) Close() error { return stmt.Stmt.Close() } func (stmt *driverStmt) NumInput() int { return stmt.Stmt.NumInput() } func (stmt *driverStmt) Exec(args []driver.Value) (driver.Result, error) { panic("not supported") } func (stmt *driverStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { var result driver.Result var err error if execerContext, ok := stmt.Stmt.(driver.StmtExecContext); ok { err = Capture(ctx, stmt.attr.dbname+stmt.attr.host, func(ctx context.Context) error { stmt.populate(ctx) var err error result, err = execerContext.ExecContext(ctx, args) return err }) } else { select { default: case <-ctx.Done(): return nil, ctx.Err() } dargs, err0 := namedValuesToValues(args) if err0 != nil { return nil, err0 } err = Capture(ctx, stmt.attr.dbname+stmt.attr.host, func(ctx context.Context) error { stmt.populate(ctx) var err error result, err = stmt.Stmt.Exec(dargs) return err }) } if err != nil { return nil, err } return result, nil } func (stmt *driverStmt) Query(args []driver.Value) (driver.Rows, error) { panic("not supported") } func (stmt *driverStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { var result driver.Rows var err error if queryCtx, ok := stmt.Stmt.(driver.StmtQueryContext); ok { err = Capture(ctx, stmt.attr.dbname+stmt.attr.host, func(ctx context.Context) error { stmt.populate(ctx) var err error result, err = queryCtx.QueryContext(ctx, args) return err }) } else { select { default: case <-ctx.Done(): return nil, ctx.Err() } dargs, err0 := namedValuesToValues(args) if err0 != nil { return nil, err0 } err = Capture(ctx, stmt.attr.dbname+stmt.attr.host, func(ctx context.Context) error { stmt.populate(ctx) var err error result, err = stmt.Stmt.Query(dargs) return err }) } if err != nil { return nil, err } return result, nil } func (stmt *driverStmt) ColumnConverter(idx int) driver.ValueConverter { if conv, ok := stmt.Stmt.(driver.ColumnConverter); ok { return conv.ColumnConverter(idx) } return driver.DefaultParameterConverter } func (stmt *driverStmt) populate(ctx context.Context) { stmt.attr.populate(ctx, stmt.query) seg := GetSegment(ctx) if seg == nil { processNilSegment(ctx) return } seg.Lock() seg.GetSQL().Preparation = "statement" seg.Unlock() } // CheckNamedValue for implementing NamedValueChecker func (stmt *driverStmt) CheckNamedValue(nv *driver.NamedValue) (err error) { if nvc, ok := stmt.Stmt.(namedValueChecker); ok { return nvc.CheckNamedValue(nv) } // When converting data in sql/driver/convert.go, it is checked first whether the `stmt` // implements `NamedValueChecker`, and then checks if `conn` implements NamedValueChecker. // In the case of "go-sql-proxy", the `proxy.Stmt` "implements" `CheckNamedValue` here, // so we also check both `stmt` and `conn` inside here. if nvc, ok := stmt.conn.Conn.(namedValueChecker); ok { return nvc.CheckNamedValue(nv) } // fallback to default return defaultCheckNamedValue(nv) } func namedValuesToValues(args []driver.NamedValue) ([]driver.Value, error) { var err error ret := make([]driver.Value, len(args)) for _, arg := range args { if len(arg.Name) > 0 { err = errors.New("xray: driver does not support the use of Named Parameters") } ret[arg.Ordinal-1] = arg.Value } return ret, err } 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 { break } else { inBraces = b == '{' } if err := buf.UnreadByte(); err != nil { panic(err) } case '}': b, err := buf.ReadByte() if err != nil { break } if b == '}' { tok.WriteByte(b) } else { inBraces = false if err := buf.UnreadByte(); err != nil { panic(err) } } case '@': if strings.Contains(res.String(), ":") { resLen := res.Len() if resLen > 0 && res.Bytes()[resLen-1] == ':' { res.Truncate(resLen - 1) } isPassword = true flush() res.WriteByte(c) } } } inBraces = false flush() return res.String() } func processNilSegment(ctx context.Context) { cfg := GetRecorder(ctx) failedMessage := "failed to get segment from context since segment is nil" if cfg != nil && cfg.ContextMissingStrategy != nil { cfg.ContextMissingStrategy.ContextMissing(failedMessage) } else { globalCfg.ContextMissingStrategy().ContextMissing(failedMessage) } }
768
aws-xray-sdk-go
aws
Go
// 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.10 package xray import ( "context" "database/sql/driver" "sync" ) // SQLConnector wraps the connector, and traces SQL executions. // Unlike SQLContext, SQLConnector doesn't filter the password of the dsn. // So, you have to filter the password before passing the dsn to SQLConnector. func SQLConnector(dsn string, connector driver.Connector) driver.Connector { d := &driverDriver{ Driver: connector.Driver(), baseName: "unknown", } return &driverConnector{ Connector: connector, driver: d, name: dsn, filtered: true, // initialized attr lazy because we have no context here. } } func (conn *driverConn) ResetSession(ctx context.Context) error { if sr, ok := conn.Conn.(driver.SessionResetter); ok { return sr.ResetSession(ctx) } return nil } type driverConnector struct { driver.Connector driver *driverDriver filtered bool name string mu sync.RWMutex attr *dbAttribute } func (c *driverConnector) Connect(ctx context.Context) (driver.Conn, error) { var rawConn driver.Conn attr, err := c.getAttr(ctx) if err != nil { return nil, err } err = Capture(ctx, attr.dbname+attr.host, func(ctx context.Context) error { attr.populate(ctx, "CONNECT") var err error rawConn, err = c.Connector.Connect(ctx) return err }) if err != nil { return nil, err } conn := &driverConn{ Conn: rawConn, attr: attr, } return conn, nil } func (c *driverConnector) getAttr(ctx context.Context) (*dbAttribute, error) { c.mu.RLock() attr := c.attr c.mu.RUnlock() if attr != nil { return attr, nil } c.mu.Lock() defer c.mu.Unlock() if c.attr != nil { return c.attr, nil } conn, err := c.Connector.Connect(ctx) if err != nil { return nil, err } defer conn.Close() attr, err = newDBAttribute(ctx, c.driver.baseName, c.driver.Driver, conn, c.name, c.filtered) if err != nil { return nil, err } c.attr = attr return attr, nil } func (c *driverConnector) Driver() driver.Driver { return c.driver } type fallbackConnector struct { driver driver.Driver name string } func (c *fallbackConnector) Connect(ctx context.Context) (driver.Conn, error) { conn, err := c.driver.Open(c.name) if err != nil { return nil, err } select { default: case <-ctx.Done(): conn.Close() return nil, ctx.Err() } return conn, nil } func (c *fallbackConnector) Driver() driver.Driver { return c.driver } func (d *driverDriver) OpenConnector(name string) (driver.Connector, error) { var c driver.Connector if dctx, ok := d.Driver.(driver.DriverContext); ok { var err error c, err = dctx.OpenConnector(name) if err != nil { return nil, err } } else { c = &fallbackConnector{ driver: d.Driver, name: name, } } c = &driverConnector{ Connector: c, driver: d, filtered: false, name: name, // initialized attr lazy because we have no context here. } return c, nil }
153
aws-xray-sdk-go
aws
Go
// 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.10 package xray import ( "database/sql" "database/sql/driver" "encoding/json" "testing" "github.com/DATA-DOG/go-sqlmock" "github.com/stretchr/testify/assert" ) type versionedDriver struct { driver.Driver version string } func (d *versionedDriver) Version() string { return d.version } func TestDriverVersion(t *testing.T) { dsn := "test-versioned-driver" db, mock, err := sqlmock.NewWithDSN(dsn) if err != nil { t.Fatal(err) } defer db.Close() mockPostgreSQL(mock, nil) // implement versionedDriver driver := &versionedDriver{ Driver: db.Driver(), version: "3.1415926535", } connector := &fallbackConnector{ driver: driver, name: dsn, } sqlConnector := SQLConnector("sanitized-dsn", connector) db = sql.OpenDB(sqlConnector) defer db.Close() ctx, td := NewTestDaemon() defer td.Close() // Execute SQL ctx, root := BeginSegment(ctx, "test") if err := db.PingContext(ctx); err != nil { t.Fatal(err) } root.Close(nil) assert.NoError(t, mock.ExpectationsWereMet()) // assertion seg, err := td.Recv() if err != nil { t.Fatal(err) } var subseg *Segment if err := json.Unmarshal(seg.Subsegments[0], &subseg); err != nil { t.Fatal(err) } assert.Equal(t, "sanitized-dsn", subseg.SQL.ConnectionString) assert.Equal(t, "3.1415926535", subseg.SQL.DriverVersion) }
77
aws-xray-sdk-go
aws
Go
// 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.11 package xray import ( "testing" "github.com/DATA-DOG/go-sqlmock" "github.com/stretchr/testify/assert" ) func TestMySQLPasswordConnectionString(t *testing.T) { tc := []struct { dsn string url string str string }{ { dsn: "username:password@protocol(address:1234)/dbname?param=value", url: "username@protocol(address:1234)/dbname?param=value", str: "username@protocol(address:1234)/dbname?param=value", }, { dsn: "username@protocol(address:1234)/dbname?param=value", url: "username@protocol(address:1234)/dbname?param=value", str: "username@protocol(address:1234)/dbname?param=value", }, } for _, tt := range tc { tt := tt t.Run(tt.dsn, func(t *testing.T) { db, mock, err := sqlmock.NewWithDSN(tt.dsn) if err != nil { t.Fatal(err) } defer db.Close() mockMySQL(mock, nil) subseg, err := capturePing(tt.dsn) if err != nil { t.Fatal(err) } assert.NoError(t, mock.ExpectationsWereMet()) assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, "MySQL", subseg.SQL.DatabaseType) if subseg.SQL.URL != "" { assert.Equal(t, tt.url, subseg.SQL.URL) } if subseg.SQL.ConnectionString != "" { assert.Equal(t, tt.str, subseg.SQL.ConnectionString) } }) } }
65
aws-xray-sdk-go
aws
Go
// 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.11 package xray import ( "testing" "github.com/DATA-DOG/go-sqlmock" "github.com/stretchr/testify/assert" ) func TestMySQLPasswordConnectionString(t *testing.T) { tc := []struct { dsn string url string str string }{ { dsn: "username:password@protocol(address:1234)/dbname?param=value", url: "username@protocol(address:1234)/dbname?param=value", }, { dsn: "username@protocol(address:1234)/dbname?param=value", url: "username@protocol(address:1234)/dbname?param=value", }, } for _, tt := range tc { tt := tt t.Run(tt.dsn, func(t *testing.T) { db, mock, err := sqlmock.NewWithDSN(tt.dsn) if err != nil { t.Fatal(err) } defer db.Close() mockMySQL(mock, nil) subseg, err := capturePing(tt.dsn) if err != nil { t.Fatal(err) } assert.NoError(t, mock.ExpectationsWereMet()) assert.Equal(t, "remote", subseg.Namespace) assert.Equal(t, "MySQL", subseg.SQL.DatabaseType) assert.Equal(t, tt.url, subseg.SQL.URL) assert.Equal(t, tt.str, subseg.SQL.ConnectionString) }) } }
59
aws-xray-sdk-go
aws
Go
// 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 }
16
aws-xray-sdk-go
aws
Go
// 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" "fmt" "net" "net/http" "sync" "time" "github.com/aws/aws-xray-sdk-go/header" ) func NewTestDaemon() (context.Context, *TestDaemon) { c := make(chan *result, 200) conn, err := net.ListenPacket("udp", "127.0.0.1:0") if err != nil { if conn, err = net.ListenPacket("udp6", "[::1]:0"); err != nil { panic(fmt.Sprintf("xray: failed to listen: %v", err)) } } ctx, cancel := context.WithCancel(context.Background()) d := &TestDaemon{ ch: c, conn: conn, ctx: ctx, cancel: cancel, } emitter, err := NewDefaultEmitter(conn.LocalAddr().(*net.UDPAddr)) if err != nil { panic(fmt.Sprintf("xray: failed to created emitter: %v", err)) } ctx, err = ContextWithConfig(ctx, Config{ Emitter: emitter, DaemonAddr: conn.LocalAddr().String(), ServiceVersion: "TestVersion", SamplingStrategy: &TestSamplingStrategy{}, ContextMissingStrategy: &TestContextMissingStrategy{}, StreamingStrategy: &TestStreamingStrategy{}, }) if err != nil { panic(fmt.Sprintf("xray: failed to configure: %v", err)) } go d.run(c) return ctx, d } type TestDaemon struct { ch <-chan *result conn net.PacketConn ctx context.Context cancel context.CancelFunc closeOnce sync.Once } type result struct { Segment *Segment Error error } func (td *TestDaemon) Close() { td.closeOnce.Do(func() { td.cancel() td.conn.Close() }) } func (td *TestDaemon) run(c chan *result) { buffer := make([]byte, 64*1024) for { n, _, err := td.conn.ReadFrom(buffer) if err != nil { select { case c <- &result{nil, err}: case <-td.ctx.Done(): return } continue } idx := bytes.IndexByte(buffer, '\n') buffered := buffer[idx+1 : n] seg := &Segment{} err = json.Unmarshal(buffered, &seg) if err != nil { select { case c <- &result{nil, err}: case <-td.ctx.Done(): return } continue } seg.Sampled = true select { case c <- &result{seg, nil}: case <-td.ctx.Done(): return } } } func (td *TestDaemon) Recv() (*Segment, error) { ctx, cancel := context.WithTimeout(td.ctx, 500*time.Millisecond) defer cancel() select { case r := <-td.ch: return r.Segment, r.Error case <-ctx.Done(): return nil, ctx.Err() } } type XRayHeaders struct { RootTraceID string ParentID string Sampled bool } func ParseHeadersForTest(h http.Header) XRayHeaders { traceHeader := header.FromString(h.Get(TraceIDHeaderKey)) return XRayHeaders{ RootTraceID: traceHeader.TraceID, ParentID: traceHeader.ParentID, Sampled: traceHeader.SamplingDecision == header.Sampled, } }
141
aws-xray-sdk-go
aws
Go
// 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 xraylog import ( "fmt" "io" "sync" "time" ) // Logger is the logging interface used by xray. fmt.Stringer is used to // defer expensive serialization operations until the message is actually // logged (i.e. don't bother serializing debug messages if they aren't going // to show up). type Logger interface { // Log can be called concurrently from multiple goroutines so make sure // your implementation is goroutine safe. Log(level LogLevel, msg fmt.Stringer) } // LogLevel represents the severity of a log message, where a higher value // means more severe. The integer value should not be serialized as it is // subject to change. type LogLevel int const ( // LogLevelDebug is usually only enabled when debugging. LogLevelDebug LogLevel = iota + 1 // LogLevelInfo is general operational entries about what's going on inside the application. LogLevelInfo // LogLevelWarn is non-critical entries that deserve eyes. LogLevelWarn // LogLevelError is used for errors that should definitely be noted. LogLevelError ) func (ll LogLevel) String() string { switch ll { case LogLevelDebug: return "DEBUG" case LogLevelInfo: return "INFO" case LogLevelWarn: return "WARN" case LogLevelError: return "ERROR" default: return fmt.Sprintf("UNKNOWNLOGLEVEL<%d>", ll) } } // NewDefaultLogger makes a Logger object that writes newline separated // messages to w, if the level of the message is at least minLogLevel. // The default logger synchronizes around Write() calls to the underlying // io.Writer. func NewDefaultLogger(w io.Writer, minLogLevel LogLevel) Logger { return &defaultLogger{w: w, minLevel: minLogLevel} } type defaultLogger struct { mu sync.Mutex w io.Writer minLevel LogLevel } func (l *defaultLogger) Log(ll LogLevel, msg fmt.Stringer) { if ll < l.minLevel { return } l.mu.Lock() defer l.mu.Unlock() fmt.Fprintf(l.w, "%s [%s] %s\n", time.Now().Format(time.RFC3339), ll, msg) } // NullLogger can be used to disable logging (pass to xray.SetLogger()). var NullLogger = nullLogger{} type nullLogger struct{} func (nl nullLogger) Log(ll LogLevel, msg fmt.Stringer) { }
93
constructs-go
aws
Go
package constructs import ( _init_ "github.com/aws/constructs-go/constructs/v3/jsii" _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) // Represents the building block of the construct graph. // // All constructs besides the root construct must be created within the scope of // another construct. type Construct interface { IConstruct // Perform final modifications before synthesis. // // This method can be implemented by derived constructs in order to perform // final changes before synthesis. prepare() will be called after child // constructs have been prepared. // // This is an advanced framework feature. Only use this if you // understand the implications. OnPrepare() // Allows this construct to emit artifacts into the cloud assembly during synthesis. // // This method is usually implemented by framework-level constructs such as `Stack` and `Asset` // as they participate in synthesizing the cloud assembly. OnSynthesize(session ISynthesisSession) // Validate the current construct. // // This method can be implemented by derived constructs in order to perform // validation logic. It is called on all constructs before synthesis. // // Returns: An array of validation error messages, or an empty array if there the construct is valid. // Deprecated: use `Node.addValidation()` to subscribe validation functions on this construct // instead of overriding this method. OnValidate() *[]*string // Returns a string representation of this construct. ToString() *string } // The jsii proxy struct for Construct type jsiiProxy_Construct struct { jsiiProxy_IConstruct } // Creates a new construct node. func NewConstruct(scope Construct, id *string, options *ConstructOptions) Construct { _init_.Initialize() if err := validateNewConstructParameters(scope, id, options); err != nil { panic(err) } j := jsiiProxy_Construct{} _jsii_.Create( "constructs.Construct", []interface{}{scope, id, options}, &j, ) return &j } // Creates a new construct node. func NewConstruct_Override(c Construct, scope Construct, id *string, options *ConstructOptions) { _init_.Initialize() _jsii_.Create( "constructs.Construct", []interface{}{scope, id, options}, c, ) } func (c *jsiiProxy_Construct) OnPrepare() { _jsii_.InvokeVoid( c, "onPrepare", nil, // no parameters ) } func (c *jsiiProxy_Construct) OnSynthesize(session ISynthesisSession) { if err := c.validateOnSynthesizeParameters(session); err != nil { panic(err) } _jsii_.InvokeVoid( c, "onSynthesize", []interface{}{session}, ) } func (c *jsiiProxy_Construct) OnValidate() *[]*string { var returns *[]*string _jsii_.Invoke( c, "onValidate", nil, // no parameters &returns, ) return returns } func (c *jsiiProxy_Construct) ToString() *string { var returns *string _jsii_.Invoke( c, "toString", nil, // no parameters &returns, ) return returns }
120
constructs-go
aws
Go
package constructs import ( _init_ "github.com/aws/constructs-go/constructs/v3/jsii" _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) // Metadata keys used by constructs. type ConstructMetadata interface { } // The jsii proxy struct for ConstructMetadata type jsiiProxy_ConstructMetadata struct { _ byte // padding } func ConstructMetadata_DISABLE_STACK_TRACE_IN_METADATA() *string { _init_.Initialize() var returns *string _jsii_.StaticGet( "constructs.ConstructMetadata", "DISABLE_STACK_TRACE_IN_METADATA", &returns, ) return returns } func ConstructMetadata_ERROR_METADATA_KEY() *string { _init_.Initialize() var returns *string _jsii_.StaticGet( "constructs.ConstructMetadata", "ERROR_METADATA_KEY", &returns, ) return returns } func ConstructMetadata_INFO_METADATA_KEY() *string { _init_.Initialize() var returns *string _jsii_.StaticGet( "constructs.ConstructMetadata", "INFO_METADATA_KEY", &returns, ) return returns } func ConstructMetadata_WARNING_METADATA_KEY() *string { _init_.Initialize() var returns *string _jsii_.StaticGet( "constructs.ConstructMetadata", "WARNING_METADATA_KEY", &returns, ) return returns }
61
constructs-go
aws
Go
package constructs // Options for creating constructs. type ConstructOptions struct { // A factory for attaching `Node`s to the construct. NodeFactory INodeFactory `field:"optional" json:"nodeFactory" yaml:"nodeFactory"` }
10
constructs-go
aws
Go
package constructs // In what order to return constructs. type ConstructOrder string const ( // Depth-first, pre-order. ConstructOrder_PREORDER ConstructOrder = "PREORDER" // Depth-first, post-order (leaf nodes first). ConstructOrder_POSTORDER ConstructOrder = "POSTORDER" )
14
constructs-go
aws
Go
//go:build !no_runtime_type_checking package constructs import ( "fmt" _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) func (c *jsiiProxy_Construct) validateOnSynthesizeParameters(session ISynthesisSession) error { if session == nil { return fmt.Errorf("parameter session is required, but nil was provided") } return nil } func validateNewConstructParameters(scope Construct, id *string, options *ConstructOptions) error { if scope == nil { return fmt.Errorf("parameter scope is required, but nil was provided") } if id == nil { return fmt.Errorf("parameter id is required, but nil was provided") } if err := _jsii_.ValidateStruct(options, func() string { return "parameter options" }); err != nil { return err } return nil }
35
constructs-go
aws
Go
//go:build no_runtime_type_checking package constructs // Building without runtime type checking enabled, so all the below just return nil func (c *jsiiProxy_Construct) validateOnSynthesizeParameters(session ISynthesisSession) error { return nil } func validateNewConstructParameters(scope Construct, id *string, options *ConstructOptions) error { return nil }
15
constructs-go
aws
Go
package constructs // A single dependency. type Dependency struct { // Source the dependency. Source IConstruct `field:"required" json:"source" yaml:"source"` // Target of the dependency. Target IConstruct `field:"required" json:"target" yaml:"target"` }
12
constructs-go
aws
Go
package constructs import ( _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) // Represents an Aspect. type IAspect interface { // All aspects can visit an IConstruct. Visit(node IConstruct) } // The jsii proxy for IAspect type jsiiProxy_IAspect struct { _ byte // padding } func (i *jsiiProxy_IAspect) Visit(node IConstruct) { if err := i.validateVisitParameters(node); err != nil { panic(err) } _jsii_.InvokeVoid( i, "visit", []interface{}{node}, ) }
29
constructs-go
aws
Go
//go:build !no_runtime_type_checking package constructs import ( "fmt" ) func (i *jsiiProxy_IAspect) validateVisitParameters(node IConstruct) error { if node == nil { return fmt.Errorf("parameter node is required, but nil was provided") } return nil }
17
constructs-go
aws
Go
//go:build no_runtime_type_checking package constructs // Building without runtime type checking enabled, so all the below just return nil func (i *jsiiProxy_IAspect) validateVisitParameters(node IConstruct) error { return nil }
11
constructs-go
aws
Go
package constructs // Represents a construct. type IConstruct interface { } // The jsii proxy for IConstruct type jsiiProxy_IConstruct struct { _ byte // padding }
13
constructs-go
aws
Go
package constructs import ( _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) // A factory for attaching `Node`s to the construct. type INodeFactory interface { // Returns a new `Node` associated with `host`. CreateNode(host Construct, scope IConstruct, id *string) Node } // The jsii proxy for INodeFactory type jsiiProxy_INodeFactory struct { _ byte // padding } func (i *jsiiProxy_INodeFactory) CreateNode(host Construct, scope IConstruct, id *string) Node { if err := i.validateCreateNodeParameters(host, scope, id); err != nil { panic(err) } var returns Node _jsii_.Invoke( i, "createNode", []interface{}{host, scope, id}, &returns, ) return returns }
34
constructs-go
aws
Go
//go:build !no_runtime_type_checking package constructs import ( "fmt" ) func (i *jsiiProxy_INodeFactory) validateCreateNodeParameters(host Construct, scope IConstruct, id *string) error { if host == nil { return fmt.Errorf("parameter host is required, but nil was provided") } if scope == nil { return fmt.Errorf("parameter scope is required, but nil was provided") } if id == nil { return fmt.Errorf("parameter id is required, but nil was provided") } return nil }
25
constructs-go
aws
Go
//go:build no_runtime_type_checking package constructs // Building without runtime type checking enabled, so all the below just return nil func (i *jsiiProxy_INodeFactory) validateCreateNodeParameters(host Construct, scope IConstruct, id *string) error { return nil }
11
constructs-go
aws
Go
package constructs import ( _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) // Represents a single session of synthesis. // // Passed into `construct.onSynthesize()` methods. type ISynthesisSession interface { // The output directory for this synthesis session. Outdir() *string } // The jsii proxy for ISynthesisSession type jsiiProxy_ISynthesisSession struct { _ byte // padding } func (j *jsiiProxy_ISynthesisSession) Outdir() *string { var returns *string _jsii_.Get( j, "outdir", &returns, ) return returns }
30
constructs-go
aws
Go
package constructs import ( _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) // Implement this interface in order for the construct to be able to validate itself. type IValidation interface { // Validate the current construct. // // This method can be implemented by derived constructs in order to perform // validation logic. It is called on all constructs before synthesis. // // Returns: An array of validation error messages, or an empty array if there the construct is valid. Validate() *[]*string } // The jsii proxy for IValidation type jsiiProxy_IValidation struct { _ byte // padding } func (i *jsiiProxy_IValidation) Validate() *[]*string { var returns *[]*string _jsii_.Invoke( i, "validate", nil, // no parameters &returns, ) return returns }
36
constructs-go
aws
Go
// A programming model for composable configuration package constructs import ( "reflect" _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) func init() { _jsii_.RegisterClass( "constructs.Construct", reflect.TypeOf((*Construct)(nil)).Elem(), []_jsii_.Member{ _jsii_.MemberMethod{JsiiMethod: "onPrepare", GoMethod: "OnPrepare"}, _jsii_.MemberMethod{JsiiMethod: "onSynthesize", GoMethod: "OnSynthesize"}, _jsii_.MemberMethod{JsiiMethod: "onValidate", GoMethod: "OnValidate"}, _jsii_.MemberMethod{JsiiMethod: "toString", GoMethod: "ToString"}, }, func() interface{} { j := jsiiProxy_Construct{} _jsii_.InitJsiiProxy(&j.jsiiProxy_IConstruct) return &j }, ) _jsii_.RegisterClass( "constructs.ConstructMetadata", reflect.TypeOf((*ConstructMetadata)(nil)).Elem(), nil, // no members func() interface{} { return &jsiiProxy_ConstructMetadata{} }, ) _jsii_.RegisterStruct( "constructs.ConstructOptions", reflect.TypeOf((*ConstructOptions)(nil)).Elem(), ) _jsii_.RegisterEnum( "constructs.ConstructOrder", reflect.TypeOf((*ConstructOrder)(nil)).Elem(), map[string]interface{}{ "PREORDER": ConstructOrder_PREORDER, "POSTORDER": ConstructOrder_POSTORDER, }, ) _jsii_.RegisterStruct( "constructs.Dependency", reflect.TypeOf((*Dependency)(nil)).Elem(), ) _jsii_.RegisterInterface( "constructs.IAspect", reflect.TypeOf((*IAspect)(nil)).Elem(), []_jsii_.Member{ _jsii_.MemberMethod{JsiiMethod: "visit", GoMethod: "Visit"}, }, func() interface{} { return &jsiiProxy_IAspect{} }, ) _jsii_.RegisterInterface( "constructs.IConstruct", reflect.TypeOf((*IConstruct)(nil)).Elem(), nil, // no members func() interface{} { return &jsiiProxy_IConstruct{} }, ) _jsii_.RegisterInterface( "constructs.INodeFactory", reflect.TypeOf((*INodeFactory)(nil)).Elem(), []_jsii_.Member{ _jsii_.MemberMethod{JsiiMethod: "createNode", GoMethod: "CreateNode"}, }, func() interface{} { return &jsiiProxy_INodeFactory{} }, ) _jsii_.RegisterInterface( "constructs.ISynthesisSession", reflect.TypeOf((*ISynthesisSession)(nil)).Elem(), []_jsii_.Member{ _jsii_.MemberProperty{JsiiProperty: "outdir", GoGetter: "Outdir"}, }, func() interface{} { return &jsiiProxy_ISynthesisSession{} }, ) _jsii_.RegisterInterface( "constructs.IValidation", reflect.TypeOf((*IValidation)(nil)).Elem(), []_jsii_.Member{ _jsii_.MemberMethod{JsiiMethod: "validate", GoMethod: "Validate"}, }, func() interface{} { return &jsiiProxy_IValidation{} }, ) _jsii_.RegisterStruct( "constructs.MetadataEntry", reflect.TypeOf((*MetadataEntry)(nil)).Elem(), ) _jsii_.RegisterClass( "constructs.Node", reflect.TypeOf((*Node)(nil)).Elem(), []_jsii_.Member{ _jsii_.MemberMethod{JsiiMethod: "addDependency", GoMethod: "AddDependency"}, _jsii_.MemberMethod{JsiiMethod: "addError", GoMethod: "AddError"}, _jsii_.MemberMethod{JsiiMethod: "addInfo", GoMethod: "AddInfo"}, _jsii_.MemberMethod{JsiiMethod: "addMetadata", GoMethod: "AddMetadata"}, _jsii_.MemberProperty{JsiiProperty: "addr", GoGetter: "Addr"}, _jsii_.MemberMethod{JsiiMethod: "addValidation", GoMethod: "AddValidation"}, _jsii_.MemberMethod{JsiiMethod: "addWarning", GoMethod: "AddWarning"}, _jsii_.MemberMethod{JsiiMethod: "applyAspect", GoMethod: "ApplyAspect"}, _jsii_.MemberProperty{JsiiProperty: "children", GoGetter: "Children"}, _jsii_.MemberProperty{JsiiProperty: "defaultChild", GoGetter: "DefaultChild"}, _jsii_.MemberProperty{JsiiProperty: "dependencies", GoGetter: "Dependencies"}, _jsii_.MemberMethod{JsiiMethod: "findAll", GoMethod: "FindAll"}, _jsii_.MemberMethod{JsiiMethod: "findChild", GoMethod: "FindChild"}, _jsii_.MemberProperty{JsiiProperty: "id", GoGetter: "Id"}, _jsii_.MemberProperty{JsiiProperty: "locked", GoGetter: "Locked"}, _jsii_.MemberProperty{JsiiProperty: "metadata", GoGetter: "Metadata"}, _jsii_.MemberProperty{JsiiProperty: "path", GoGetter: "Path"}, _jsii_.MemberMethod{JsiiMethod: "prepare", GoMethod: "Prepare"}, _jsii_.MemberProperty{JsiiProperty: "root", GoGetter: "Root"}, _jsii_.MemberProperty{JsiiProperty: "scope", GoGetter: "Scope"}, _jsii_.MemberProperty{JsiiProperty: "scopes", GoGetter: "Scopes"}, _jsii_.MemberMethod{JsiiMethod: "setContext", GoMethod: "SetContext"}, _jsii_.MemberMethod{JsiiMethod: "synthesize", GoMethod: "Synthesize"}, _jsii_.MemberMethod{JsiiMethod: "tryFindChild", GoMethod: "TryFindChild"}, _jsii_.MemberMethod{JsiiMethod: "tryGetContext", GoMethod: "TryGetContext"}, _jsii_.MemberMethod{JsiiMethod: "tryRemoveChild", GoMethod: "TryRemoveChild"}, _jsii_.MemberProperty{JsiiProperty: "uniqueId", GoGetter: "UniqueId"}, _jsii_.MemberMethod{JsiiMethod: "validate", GoMethod: "Validate"}, }, func() interface{} { return &jsiiProxy_Node{} }, ) _jsii_.RegisterStruct( "constructs.SynthesisOptions", reflect.TypeOf((*SynthesisOptions)(nil)).Elem(), ) _jsii_.RegisterStruct( "constructs.ValidationError", reflect.TypeOf((*ValidationError)(nil)).Elem(), ) }
148
constructs-go
aws
Go
package constructs // An entry in the construct metadata table. type MetadataEntry struct { // The data. Data interface{} `field:"required" json:"data" yaml:"data"` // The metadata entry type. Type *string `field:"required" json:"type" yaml:"type"` // Stack trace. // // Can be omitted by setting the context key // `ConstructMetadata.DISABLE_STACK_TRACE_IN_METADATA` to 1. Trace *[]*string `field:"optional" json:"trace" yaml:"trace"` }
17
constructs-go
aws
Go
package constructs import ( _init_ "github.com/aws/constructs-go/constructs/v3/jsii" _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) // Represents the construct node in the scope tree. type Node interface { // Returns an opaque tree-unique address for this construct. // // Addresses are 42 characters hexadecimal strings. They begin with "c8" // followed by 40 lowercase hexadecimal characters (0-9a-f). // // Addresses are calculated using a SHA-1 of the components of the construct // path. // // To enable refactorings of construct trees, constructs with the ID `Default` // will be excluded from the calculation. In those cases constructs in the // same tree may have the same addreess. // // Example: // c83a2846e506bcc5f10682b564084bca2d275709ee // Addr() *string // All direct children of this construct. Children() *[]IConstruct // Returns the child construct that has the id `Default` or `Resource"`. // // This is usually the construct that provides the bulk of the underlying functionality. // Useful for modifications of the underlying construct that are not available at the higher levels. // Override the defaultChild property. // // This should only be used in the cases where the correct // default child is not named 'Resource' or 'Default' as it // should be. // // If you set this to undefined, the default behavior of finding // the child named 'Resource' or 'Default' will be used. // // Returns: a construct or undefined if there is no default child. DefaultChild() IConstruct SetDefaultChild(val IConstruct) // Return all dependencies registered on this node or any of its children. Dependencies() *[]*Dependency // The id of this construct within the current scope. // // This is a a scope-unique id. To obtain an app-unique id for this construct, use `uniqueId`. Id() *string // Returns true if this construct or the scopes in which it is defined are locked. Locked() *bool // An immutable array of metadata objects associated with this construct. // // This can be used, for example, to implement support for deprecation notices, source mapping, etc. Metadata() *[]*MetadataEntry // The full, absolute path of this construct in the tree. // // Components are separated by '/'. Path() *string // Returns the root of the construct tree. // // Returns: The root of the construct tree. Root() IConstruct // Returns the scope in which this construct is defined. // // The value is `undefined` at the root of the construct scope tree. Scope() IConstruct // All parent scopes of this construct. // // Returns: a list of parent scopes. The last element in the list will always // be the current construct and the first element will be the root of the // tree. Scopes() *[]IConstruct // A tree-global unique alphanumeric identifier for this construct. // // Includes // all components of the tree. // Deprecated: please avoid using this property and use `addr` to form unique names. // This algorithm uses MD5, which is not FIPS-complient and also excludes the // identity of the root construct from the calculation. UniqueId() *string // Add an ordering dependency on another Construct. // // All constructs in the dependency's scope will be deployed before any // construct in this construct's scope. AddDependency(dependencies ...IConstruct) // Adds an { "error": <message> } metadata entry to this construct. // // The toolkit will fail synthesis when errors are reported. AddError(message *string) // Adds a { "info": <message> } metadata entry to this construct. // // The toolkit will display the info message when apps are synthesized. AddInfo(message *string) // Adds a metadata entry to this construct. // // Entries are arbitrary values and will also include a stack trace to allow tracing back to // the code location for when the entry was added. It can be used, for example, to include source // mapping in CloudFormation templates to improve diagnostics. AddMetadata(type_ *string, data interface{}, fromFunction interface{}) // Adds a validation to this construct. // // When `node.validate()` is called, the `validate()` method will be called on // all validations and all errors will be returned. AddValidation(validation IValidation) // Adds a { "warning": <message> } metadata entry to this construct. // // The toolkit will display the warning when an app is synthesized, or fail // if run in --strict mode. AddWarning(message *string) // Applies the aspect to this Constructs node. ApplyAspect(aspect IAspect) // Return this construct and all of its children in the given order. FindAll(order ConstructOrder) *[]IConstruct // Return a direct child by id. // // Throws an error if the child is not found. // // Returns: Child with the given id. FindChild(id *string) IConstruct // Invokes "prepare" on all constructs (depth-first, post-order) in the tree under `node`. Prepare() // This can be used to set contextual values. // // Context must be set before any children are added, since children may consult context info during construction. // If the key already exists, it will be overridden. SetContext(key *string, value interface{}) // Synthesizes a CloudAssembly from a construct tree. Synthesize(options *SynthesisOptions) // Return a direct child by id, or undefined. // // Returns: the child if found, or undefined. TryFindChild(id *string) IConstruct // Retrieves a value from tree context. // // Context is usually initialized at the root, but can be overridden at any point in the tree. // // Returns: The context value or `undefined` if there is no context value for thie key. TryGetContext(key *string) interface{} // Remove the child with the given name, if present. // // Returns: Whether a child with the given name was deleted. // Experimental. TryRemoveChild(childName *string) *bool // Validates tree (depth-first, pre-order) and returns the list of all errors. // // An empty list indicates that there are no errors. Validate() *[]*ValidationError } // The jsii proxy struct for Node type jsiiProxy_Node struct { _ byte // padding } func (j *jsiiProxy_Node) Addr() *string { var returns *string _jsii_.Get( j, "addr", &returns, ) return returns } func (j *jsiiProxy_Node) Children() *[]IConstruct { var returns *[]IConstruct _jsii_.Get( j, "children", &returns, ) return returns } func (j *jsiiProxy_Node) DefaultChild() IConstruct { var returns IConstruct _jsii_.Get( j, "defaultChild", &returns, ) return returns } func (j *jsiiProxy_Node) Dependencies() *[]*Dependency { var returns *[]*Dependency _jsii_.Get( j, "dependencies", &returns, ) return returns } func (j *jsiiProxy_Node) Id() *string { var returns *string _jsii_.Get( j, "id", &returns, ) return returns } func (j *jsiiProxy_Node) Locked() *bool { var returns *bool _jsii_.Get( j, "locked", &returns, ) return returns } func (j *jsiiProxy_Node) Metadata() *[]*MetadataEntry { var returns *[]*MetadataEntry _jsii_.Get( j, "metadata", &returns, ) return returns } func (j *jsiiProxy_Node) Path() *string { var returns *string _jsii_.Get( j, "path", &returns, ) return returns } func (j *jsiiProxy_Node) Root() IConstruct { var returns IConstruct _jsii_.Get( j, "root", &returns, ) return returns } func (j *jsiiProxy_Node) Scope() IConstruct { var returns IConstruct _jsii_.Get( j, "scope", &returns, ) return returns } func (j *jsiiProxy_Node) Scopes() *[]IConstruct { var returns *[]IConstruct _jsii_.Get( j, "scopes", &returns, ) return returns } func (j *jsiiProxy_Node) UniqueId() *string { var returns *string _jsii_.Get( j, "uniqueId", &returns, ) return returns } func NewNode(host Construct, scope IConstruct, id *string) Node { _init_.Initialize() if err := validateNewNodeParameters(host, scope, id); err != nil { panic(err) } j := jsiiProxy_Node{} _jsii_.Create( "constructs.Node", []interface{}{host, scope, id}, &j, ) return &j } func NewNode_Override(n Node, host Construct, scope IConstruct, id *string) { _init_.Initialize() _jsii_.Create( "constructs.Node", []interface{}{host, scope, id}, n, ) } func (j *jsiiProxy_Node)SetDefaultChild(val IConstruct) { _jsii_.Set( j, "defaultChild", val, ) } // Returns the node associated with a construct. func Node_Of(construct IConstruct) Node { _init_.Initialize() if err := validateNode_OfParameters(construct); err != nil { panic(err) } var returns Node _jsii_.StaticInvoke( "constructs.Node", "of", []interface{}{construct}, &returns, ) return returns } func Node_PATH_SEP() *string { _init_.Initialize() var returns *string _jsii_.StaticGet( "constructs.Node", "PATH_SEP", &returns, ) return returns } func (n *jsiiProxy_Node) AddDependency(dependencies ...IConstruct) { args := []interface{}{} for _, a := range dependencies { args = append(args, a) } _jsii_.InvokeVoid( n, "addDependency", args, ) } func (n *jsiiProxy_Node) AddError(message *string) { if err := n.validateAddErrorParameters(message); err != nil { panic(err) } _jsii_.InvokeVoid( n, "addError", []interface{}{message}, ) } func (n *jsiiProxy_Node) AddInfo(message *string) { if err := n.validateAddInfoParameters(message); err != nil { panic(err) } _jsii_.InvokeVoid( n, "addInfo", []interface{}{message}, ) } func (n *jsiiProxy_Node) AddMetadata(type_ *string, data interface{}, fromFunction interface{}) { if err := n.validateAddMetadataParameters(type_, data); err != nil { panic(err) } _jsii_.InvokeVoid( n, "addMetadata", []interface{}{type_, data, fromFunction}, ) } func (n *jsiiProxy_Node) AddValidation(validation IValidation) { if err := n.validateAddValidationParameters(validation); err != nil { panic(err) } _jsii_.InvokeVoid( n, "addValidation", []interface{}{validation}, ) } func (n *jsiiProxy_Node) AddWarning(message *string) { if err := n.validateAddWarningParameters(message); err != nil { panic(err) } _jsii_.InvokeVoid( n, "addWarning", []interface{}{message}, ) } func (n *jsiiProxy_Node) ApplyAspect(aspect IAspect) { if err := n.validateApplyAspectParameters(aspect); err != nil { panic(err) } _jsii_.InvokeVoid( n, "applyAspect", []interface{}{aspect}, ) } func (n *jsiiProxy_Node) FindAll(order ConstructOrder) *[]IConstruct { var returns *[]IConstruct _jsii_.Invoke( n, "findAll", []interface{}{order}, &returns, ) return returns } func (n *jsiiProxy_Node) FindChild(id *string) IConstruct { if err := n.validateFindChildParameters(id); err != nil { panic(err) } var returns IConstruct _jsii_.Invoke( n, "findChild", []interface{}{id}, &returns, ) return returns } func (n *jsiiProxy_Node) Prepare() { _jsii_.InvokeVoid( n, "prepare", nil, // no parameters ) } func (n *jsiiProxy_Node) SetContext(key *string, value interface{}) { if err := n.validateSetContextParameters(key, value); err != nil { panic(err) } _jsii_.InvokeVoid( n, "setContext", []interface{}{key, value}, ) } func (n *jsiiProxy_Node) Synthesize(options *SynthesisOptions) { if err := n.validateSynthesizeParameters(options); err != nil { panic(err) } _jsii_.InvokeVoid( n, "synthesize", []interface{}{options}, ) } func (n *jsiiProxy_Node) TryFindChild(id *string) IConstruct { if err := n.validateTryFindChildParameters(id); err != nil { panic(err) } var returns IConstruct _jsii_.Invoke( n, "tryFindChild", []interface{}{id}, &returns, ) return returns } func (n *jsiiProxy_Node) TryGetContext(key *string) interface{} { if err := n.validateTryGetContextParameters(key); err != nil { panic(err) } var returns interface{} _jsii_.Invoke( n, "tryGetContext", []interface{}{key}, &returns, ) return returns } func (n *jsiiProxy_Node) TryRemoveChild(childName *string) *bool { if err := n.validateTryRemoveChildParameters(childName); err != nil { panic(err) } var returns *bool _jsii_.Invoke( n, "tryRemoveChild", []interface{}{childName}, &returns, ) return returns } func (n *jsiiProxy_Node) Validate() *[]*ValidationError { var returns *[]*ValidationError _jsii_.Invoke( n, "validate", nil, // no parameters &returns, ) return returns }
541
constructs-go
aws
Go
//go:build !no_runtime_type_checking package constructs import ( "fmt" _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) func (n *jsiiProxy_Node) validateAddErrorParameters(message *string) error { if message == nil { return fmt.Errorf("parameter message is required, but nil was provided") } return nil } func (n *jsiiProxy_Node) validateAddInfoParameters(message *string) error { if message == nil { return fmt.Errorf("parameter message is required, but nil was provided") } return nil } func (n *jsiiProxy_Node) validateAddMetadataParameters(type_ *string, data interface{}) error { if type_ == nil { return fmt.Errorf("parameter type_ is required, but nil was provided") } if data == nil { return fmt.Errorf("parameter data is required, but nil was provided") } return nil } func (n *jsiiProxy_Node) validateAddValidationParameters(validation IValidation) error { if validation == nil { return fmt.Errorf("parameter validation is required, but nil was provided") } return nil } func (n *jsiiProxy_Node) validateAddWarningParameters(message *string) error { if message == nil { return fmt.Errorf("parameter message is required, but nil was provided") } return nil } func (n *jsiiProxy_Node) validateApplyAspectParameters(aspect IAspect) error { if aspect == nil { return fmt.Errorf("parameter aspect is required, but nil was provided") } return nil } func (n *jsiiProxy_Node) validateFindChildParameters(id *string) error { if id == nil { return fmt.Errorf("parameter id is required, but nil was provided") } return nil } func (n *jsiiProxy_Node) validateSetContextParameters(key *string, value interface{}) error { if key == nil { return fmt.Errorf("parameter key is required, but nil was provided") } if value == nil { return fmt.Errorf("parameter value is required, but nil was provided") } return nil } func (n *jsiiProxy_Node) validateSynthesizeParameters(options *SynthesisOptions) error { if options == nil { return fmt.Errorf("parameter options is required, but nil was provided") } if err := _jsii_.ValidateStruct(options, func() string { return "parameter options" }); err != nil { return err } return nil } func (n *jsiiProxy_Node) validateTryFindChildParameters(id *string) error { if id == nil { return fmt.Errorf("parameter id is required, but nil was provided") } return nil } func (n *jsiiProxy_Node) validateTryGetContextParameters(key *string) error { if key == nil { return fmt.Errorf("parameter key is required, but nil was provided") } return nil } func (n *jsiiProxy_Node) validateTryRemoveChildParameters(childName *string) error { if childName == nil { return fmt.Errorf("parameter childName is required, but nil was provided") } return nil } func validateNode_OfParameters(construct IConstruct) error { if construct == nil { return fmt.Errorf("parameter construct is required, but nil was provided") } return nil } func validateNewNodeParameters(host Construct, scope IConstruct, id *string) error { if host == nil { return fmt.Errorf("parameter host is required, but nil was provided") } if scope == nil { return fmt.Errorf("parameter scope is required, but nil was provided") } if id == nil { return fmt.Errorf("parameter id is required, but nil was provided") } return nil }
142
constructs-go
aws
Go
//go:build no_runtime_type_checking package constructs // Building without runtime type checking enabled, so all the below just return nil func (n *jsiiProxy_Node) validateAddErrorParameters(message *string) error { return nil } func (n *jsiiProxy_Node) validateAddInfoParameters(message *string) error { return nil } func (n *jsiiProxy_Node) validateAddMetadataParameters(type_ *string, data interface{}) error { return nil } func (n *jsiiProxy_Node) validateAddValidationParameters(validation IValidation) error { return nil } func (n *jsiiProxy_Node) validateAddWarningParameters(message *string) error { return nil } func (n *jsiiProxy_Node) validateApplyAspectParameters(aspect IAspect) error { return nil } func (n *jsiiProxy_Node) validateFindChildParameters(id *string) error { return nil } func (n *jsiiProxy_Node) validateSetContextParameters(key *string, value interface{}) error { return nil } func (n *jsiiProxy_Node) validateSynthesizeParameters(options *SynthesisOptions) error { return nil } func (n *jsiiProxy_Node) validateTryFindChildParameters(id *string) error { return nil } func (n *jsiiProxy_Node) validateTryGetContextParameters(key *string) error { return nil } func (n *jsiiProxy_Node) validateTryRemoveChildParameters(childName *string) error { return nil } func validateNode_OfParameters(construct IConstruct) error { return nil } func validateNewNodeParameters(host Construct, scope IConstruct, id *string) error { return nil }
63
constructs-go
aws
Go
package constructs // Options for synthesis. type SynthesisOptions struct { // The output directory into which to synthesize the cloud assembly. Outdir *string `field:"required" json:"outdir" yaml:"outdir"` // Additional context passed into the synthesis session object when `construct.synth` is called. SessionContext *map[string]interface{} `field:"optional" json:"sessionContext" yaml:"sessionContext"` // Whether synthesis should skip the validation phase. SkipValidation *bool `field:"optional" json:"skipValidation" yaml:"skipValidation"` }
14
constructs-go
aws
Go
package constructs // An error returned during the validation phase. type ValidationError struct { // The error message. Message *string `field:"required" json:"message" yaml:"message"` // The construct which emitted the error. Source Construct `field:"required" json:"source" yaml:"source"` }
12
constructs-go
aws
Go
// Package jsii contains the functionaility needed for jsii packages to // initialize their dependencies and themselves. Users should never need to use this package // directly. If you find you need to - please report a bug at // https://github.com/aws/jsii/issues/new/choose package jsii import ( _ "embed" _jsii_ "github.com/aws/jsii-runtime-go/runtime" ) //go:embed constructs-3.4.342.tgz var tarball []byte // Initialize loads the necessary packages in the @jsii/kernel to support the enclosing module. // The implementation is idempotent (and hence safe to be called over and over). func Initialize() { // Load this library into the kernel _jsii_.Load("constructs", "3.4.342", tarball) }
22
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main const ( shortDescription = "Launch and manage containerized applications on AWS." )
9
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package main contains the root command. package main import ( "errors" "os" "github.com/aws/copilot-cli/cmd/copilot/template" "github.com/aws/copilot-cli/internal/pkg/cli" "github.com/aws/copilot-cli/internal/pkg/term/color" "github.com/aws/copilot-cli/internal/pkg/term/log" "github.com/aws/copilot-cli/internal/pkg/version" "github.com/spf13/cobra" ) type actionRecommender interface { RecommendActions() string } type exitCodeError interface { ExitCode() int } func init() { color.DisableColorBasedOnEnvVar() cobra.EnableCommandSorting = false // Maintain the order in which we add commands. } func main() { cmd := buildRootCmd() if err := cmd.Execute(); err != nil { var ac actionRecommender var exitCodeErr exitCodeError if errors.As(err, &ac) { log.Infoln(ac.RecommendActions()) } if errors.As(err, &exitCodeErr) { log.Infoln(err.Error()) os.Exit(exitCodeErr.ExitCode()) } log.Errorln(err.Error()) os.Exit(1) } } func buildRootCmd() *cobra.Command { cmd := &cobra.Command{ Use: "copilot", Short: shortDescription, Example: ` Displays the help menu for the "init" command. /code $ copilot init --help`, PersistentPreRun: func(cmd *cobra.Command, args []string) { // If we don't set a Run() function the help menu doesn't show up. // See https://github.com/spf13/cobra/issues/790 }, SilenceUsage: true, SilenceErrors: true, } cmd.SetOut(log.OutputWriter) cmd.SetErr(log.DiagnosticWriter) // Sets version for --version flag. Version command gives more detailed // version information. cmd.Version = version.Version cmd.SetVersionTemplate("copilot version: {{.Version}}\n") // NOTE: Order for each grouping below is significant in that it affects help menu output ordering. // "Getting Started" command group. cmd.AddCommand(cli.BuildInitCmd()) cmd.AddCommand(cli.BuildDocsCmd()) // "Develop" command group. cmd.AddCommand(cli.BuildAppCmd()) cmd.AddCommand(cli.BuildEnvCmd()) cmd.AddCommand(cli.BuildSvcCmd()) cmd.AddCommand(cli.BuildJobCmd()) cmd.AddCommand(cli.BuildTaskCmd()) // "Extend" command group cmd.AddCommand(cli.BuildStorageCmd()) cmd.AddCommand(cli.BuildSecretCmd()) // "Settings" command group. cmd.AddCommand(cli.BuildVersionCmd()) cmd.AddCommand(cli.BuildCompletionCmd(cmd)) // "Release" command group. cmd.AddCommand(cli.BuildPipelineCmd()) cmd.AddCommand(cli.BuildDeployCmd()) cmd.SetUsageTemplate(template.RootUsage) return cmd }
100
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Package template provides usage templates to render help menus. package template import ( "strings" termcolor "github.com/aws/copilot-cli/internal/pkg/term/color" "github.com/fatih/color" "github.com/spf13/cobra" ) func isInGroup(cmd *cobra.Command, group string) bool { return cmd.Annotations["group"] == group } func filterCmdsByGroup(cmds []*cobra.Command, group string) []*cobra.Command { var filtered []*cobra.Command for _, cmd := range cmds { if isInGroup(cmd, group) { filtered = append(filtered, cmd) } } return filtered } func h1(text string) string { var s strings.Builder color.New(color.Bold, color.Underline).Fprintf(&s, text) return s.String() } func h2(text string) string { var s strings.Builder color.New(color.Bold).Fprintf(&s, text) return s.String() } func code(text string) string { lines := strings.Split(text, "\n") var startCodeBlockIdx, codeBlockPadding int for i, line := range lines { if strings.HasPrefix(strings.TrimSpace(line), "/code ") { codeIndex := strings.Index(line, "/code ") lines[i] = line[:codeIndex] + termcolor.HighlightCode(strings.ReplaceAll(line[codeIndex:], "/code ", "")) } if strings.HasPrefix(strings.TrimSpace(line), "/startcodeblock") { startCodeBlockIdx = i codeBlockPadding = strings.Index(line, "/startcodeblock") } if strings.HasPrefix(strings.TrimSpace(line), "/endcodeblock") { colored := termcolor.HighlightCodeBlock(strings.Join(lines[startCodeBlockIdx+1:i], "\n")) coloredLines := strings.Split(colored, "\n") for j, val := range coloredLines { padding := "" if j == 0 || j == len(coloredLines)-1 { padding = strings.Repeat(" ", codeBlockPadding) } lines[startCodeBlockIdx+j] = padding + val } } } return strings.Join(lines, "\n") } func mkSlice(args ...interface{}) []interface{} { return args } func split(s string, sep string) []string { return strings.Split(s, sep) } func inc(n int) int { return n + 1 }
81
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package template import ( "fmt" "github.com/spf13/cobra" "github.com/aws/copilot-cli/internal/pkg/cli/group" ) // RootUsage is the text template for the root command. var RootUsage = fmt.Sprintf("{{h1 \"Commands\"}}{{ $cmds := .Commands }}{{$groups := mkSlice \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" }}{{range $group := $groups }} \n", group.GettingStarted, group.Develop, group.Release, group.Extend, group.Settings) + ` {{h2 $group}}{{$groupCmds := (filterCmdsByGroup $cmds $group)}} {{- range $j, $cmd := $groupCmds}}{{$lines := split $cmd.Short "\n"}} {{- range $i, $line := $lines}} {{if eq $i 0}}{{rpad $cmd.Name $cmd.NamePadding}} {{$line}} {{- else}}{{rpad "" $cmd.NamePadding}} {{$line}} {{- end}}{{end}}{{if and (gt (len $lines) 1) (ne (inc $j) (len $groupCmds))}} {{- end}}{{end}} {{end}}{{if .HasAvailableLocalFlags}} {{h1 "Flags"}} {{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} {{h1 "Global Flags"}} {{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasExample}} {{h1 "Examples"}}{{code .Example}}{{end}} ` // Usage is the text template for a single command. const Usage = `{{h1 "Usage"}}{{if .Runnable}} {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} {{.CommandPath}} [command] {{h1 "Available Commands"}}{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}} {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} {{h1 "Flags"}} {{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} {{h1 "Global Flags"}} {{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasExample}} {{h1 "Examples"}}{{code .Example}}{{end}} ` func init() { cobra.AddTemplateFunc("filterCmdsByGroup", filterCmdsByGroup) cobra.AddTemplateFunc("h1", h1) cobra.AddTemplateFunc("h2", h2) cobra.AddTemplateFunc("code", code) cobra.AddTemplateFunc("mkSlice", mkSlice) cobra.AddTemplateFunc("split", split) cobra.AddTemplateFunc("inc", inc) }
60
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package addons_test import ( "fmt" "testing" "time" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var cli *client.CLI var ( appName string svcName string rdsStorageName string rdsStorageType string rdsEngine string rdsInitialDB string s3StorageName string s3StorageType string ) // The Addons suite runs creates a new application with additional resources. func TestAddons(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Addons Suite") } var _ = BeforeSuite(func() { ecsCli, err := client.NewCLI() cli = ecsCli Expect(err).NotTo(HaveOccurred()) appName = fmt.Sprintf("e2e-addons-%d", time.Now().Unix()) svcName = "hello" rdsStorageName = "mycluster" rdsStorageType = "Aurora" rdsEngine = "PostgreSQL" rdsInitialDB = "initdb" s3StorageName = "mybucket" s3StorageType = "S3" }) var _ = AfterSuite(func() { _, err := cli.AppDelete() _ = client.NewAWS().DeleteAllDBClusterSnapshots() Expect(err).NotTo(HaveOccurred()) })
58
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package addons_test import ( "fmt" "net/http" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("addons flow", func() { Context("when creating a new app", Ordered, func() { var ( initErr error ) BeforeAll(func() { _, initErr = cli.AppInit(&client.AppInitRequest{ AppName: appName, }) }) It("app init succeeds", func() { Expect(initErr).NotTo(HaveOccurred()) }) It("app init creates an copilot directory and workspace file", func() { Expect("./copilot").Should(BeADirectory()) Expect("./copilot/.workspace").Should(BeAnExistingFile()) }) It("app ls includes new app", func() { Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName)) }) It("app show includes app name", func() { appShowOutput, err := cli.AppShow(appName) Expect(err).NotTo(HaveOccurred()) Expect(appShowOutput.Name).To(Equal(appName)) Expect(appShowOutput.URI).To(BeEmpty()) }) }) Context("when adding a new environment", Ordered, func() { var ( testEnvInitErr error ) BeforeAll(func() { _, testEnvInitErr = cli.EnvInit(&client.EnvInitRequest{ AppName: appName, EnvName: "test", Profile: "test", }) }) It("should succeed", func() { Expect(testEnvInitErr).NotTo(HaveOccurred()) }) }) Context("when deploying the environment", Ordered, func() { var envDeployErr error BeforeAll(func() { _, envDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{ AppName: appName, Name: "test", }) }) It("should succeed", func() { Expect(envDeployErr).NotTo(HaveOccurred()) }) }) Context("when adding a svc", Ordered, func() { var ( svcInitErr error ) BeforeAll(func() { _, svcInitErr = cli.SvcInit(&client.SvcInitRequest{ Name: svcName, SvcType: "Load Balanced Web Service", Dockerfile: "./hello/Dockerfile", SvcPort: "80", }) }) It("svc init should succeed", func() { Expect(svcInitErr).NotTo(HaveOccurred()) }) It("svc init should create svc manifests", func() { Expect("./copilot/hello/manifest.yml").Should(BeAnExistingFile()) }) It("svc ls should list the service", func() { svcList, svcListError := cli.SvcList(appName) Expect(svcListError).NotTo(HaveOccurred()) Expect(len(svcList.Services)).To(Equal(1)) svcsByName := map[string]client.WkldDescription{} for _, svc := range svcList.Services { svcsByName[svc.Name] = svc } for _, svc := range []string{svcName} { Expect(svcsByName[svc].AppName).To(Equal(appName)) Expect(svcsByName[svc].Name).To(Equal(svc)) } }) }) Context("when adding an RDS storage", Ordered, func() { var testStorageInitErr error BeforeAll(func() { _, testStorageInitErr = cli.StorageInit(&client.StorageInitRequest{ StorageName: rdsStorageName, StorageType: rdsStorageType, WorkloadName: svcName, Lifecycle: "workload", RDSEngine: rdsEngine, InitialDBName: rdsInitialDB, }) }) It("storage init should succeed", func() { Expect(testStorageInitErr).NotTo(HaveOccurred()) }) It("storage init should create an addon template", func() { addonFilePath := fmt.Sprintf("./copilot/%s/addons/%s.yml", svcName, rdsStorageName) Expect(addonFilePath).Should(BeAnExistingFile()) }) }) Context("when adding a S3 storage", Ordered, func() { var testStorageInitErr error BeforeAll(func() { _, testStorageInitErr = cli.StorageInit(&client.StorageInitRequest{ StorageName: s3StorageName, StorageType: s3StorageType, WorkloadName: svcName, Lifecycle: "workload", }) }) It("storage init should succeed", func() { Expect(testStorageInitErr).NotTo(HaveOccurred()) }) It("storage init should create an addon template", func() { addonFilePath := fmt.Sprintf("./copilot/%s/addons/%s.yml", svcName, s3StorageName) Expect(addonFilePath).Should(BeAnExistingFile()) }) }) Context("when deploying svc", Ordered, func() { var ( svcDeployErr error svcInitErr error initErr error ) BeforeAll(func() { _, svcDeployErr = cli.SvcDeploy(&client.SvcDeployInput{ Name: svcName, EnvName: "test", ImageTag: "gallopinggurdey", }) }) It("svc deploy should succeed", func() { Expect(svcDeployErr).NotTo(HaveOccurred()) }) It("should be able to make a GET request", func() { svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{ AppName: appName, Name: svcName, }) Expect(svcShowErr).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(1)) // Make a GET request to the API. route := svc.Routes[0] Expect(route.Environment).To(Equal("test")) Eventually(func() (int, error) { resp, fetchErr := http.Get(route.URL) return resp.StatusCode, fetchErr }, "30s", "1s").Should(Equal(200)) }) It("initial database should have been created for the Aurora stroage", func() { svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{ AppName: appName, Name: svcName, }) Expect(svcShowErr).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(1)) // Make a GET request to the API to make sure initial database exists. route := svc.Routes[0] Expect(route.Environment).To(Equal("test")) endpoint := fmt.Sprintf("%s/%s", "databases", rdsInitialDB) Eventually(func() (int, error) { url := fmt.Sprintf("%s/%s", route.URL, endpoint) resp, fetchErr := http.Get(url) return resp.StatusCode, fetchErr }, "30s", "1s").Should(Equal(200)) }) It("should be able to peek into s3 bucket", func() { svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{ AppName: appName, Name: svcName, }) Expect(svcShowErr).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(1)) // Make a GET request to the API to make sure we can access the s3 bucket. route := svc.Routes[0] Expect(route.Environment).To(Equal("test")) Eventually(func() (int, error) { url := fmt.Sprintf("%s/%s", route.URL, "peeks3") resp, fetchErr := http.Get(url) return resp.StatusCode, fetchErr }, "30s", "1s").Should(Equal(200)) }) It("svc logs should display logs", func() { var svcLogs []client.SvcLogsOutput var svcLogsErr error Eventually(func() ([]client.SvcLogsOutput, error) { svcLogs, svcLogsErr = cli.SvcLogs(&client.SvcLogsRequest{ AppName: appName, Name: svcName, EnvName: "test", Since: "1h", }) return svcLogs, svcLogsErr }, "60s", "10s").ShouldNot(BeEmpty()) for _, logLine := range svcLogs { Expect(logLine.Message).NotTo(Equal("")) Expect(logLine.LogStreamName).NotTo(Equal("")) Expect(logLine.Timestamp).NotTo(Equal(0)) Expect(logLine.IngestionTime).NotTo(Equal(0)) } }) It("svc delete should not delete local files", func() { _, err := cli.SvcDelete(svcName) Expect(err).NotTo(HaveOccurred()) Expect("./copilot/hello/addons").Should(BeADirectory()) Expect("./copilot/hello/manifest.yml").Should(BeAnExistingFile()) Expect("./copilot/.workspace").Should(BeAnExistingFile()) // Need to recreate the service for AfterSuite testing. _, svcInitErr = cli.SvcInit(&client.SvcInitRequest{ Name: svcName, SvcType: "Load Balanced Web Service", Dockerfile: "./hello/Dockerfile", SvcPort: "80", }) Expect(svcInitErr).NotTo(HaveOccurred()) }) It("app delete does remove .workspace but keep local files", func() { _, err := cli.AppDelete() Expect(err).NotTo(HaveOccurred()) Expect("./copilot").Should(BeADirectory()) Expect("./copilot/hello/addons").Should(BeADirectory()) Expect("./copilot/hello/manifest.yml").Should(BeAnExistingFile()) Expect("./copilot/environments/test/manifest.yml").Should(BeAnExistingFile()) Expect("./copilot/.workspace").ShouldNot(BeAnExistingFile()) // Need to recreate the app for AfterSuite testing. _, initErr = cli.AppInit(&client.AppInitRequest{ AppName: appName, }) Expect(initErr).NotTo(HaveOccurred()) }) }) })
291
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package app_with_domain_test import ( "fmt" "os" "strings" "testing" "time" "github.com/aws/aws-sdk-go/service/cloudformation" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) const ( waitingInterval = 60 * time.Second domainName = "app-with-domain.copilot-e2e-tests.ecs.aws.dev" ) var cli *client.CLI var appName string func TestAppWithDomain(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Custom Domain Suite") } var _ = BeforeSuite(func() { copilotCLI, err := client.NewCLI() cli = copilotCLI Expect(err).NotTo(HaveOccurred()) err = os.Setenv("DOMAINNAME", domainName) Expect(err).NotTo(HaveOccurred()) appName = fmt.Sprintf("t%d", time.Now().Unix()) }) var _ = AfterSuite(func() { _, err := cli.AppDelete() Expect(err).NotTo(HaveOccurred()) }) // isStackSetOperationInProgress returns if the current stack set is in operation. func isStackSetOperationInProgress(s string) bool { return strings.Contains(s, cloudformation.ErrCodeOperationInProgressException) } // isImagePushingToECRInProgress returns if we are pushing images to ECR. Pushing images concurrently would fail because // of credential verification issue. func isImagePushingToECRInProgress(s string) bool { return strings.Contains(s, "denied: Your authorization token has expired. Reauthenticate and try again.") || strings.Contains(s, "no basic auth credentials") }
57
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package app_with_domain_test import ( "fmt" "io" "net/http" "strings" "sync" "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/aws/copilot-cli/e2e/internal/client" ) var _ = Describe("App With Domain", func() { Context("when creating a new app", Ordered, func() { var appInitErr error BeforeAll(func() { _, appInitErr = cli.AppInit(&client.AppInitRequest{ AppName: appName, Domain: domainName, }) }) It("app init succeeds", func() { Expect(appInitErr).NotTo(HaveOccurred()) }) It("app init creates a copilot directory", func() { Expect("./copilot").Should(BeADirectory()) }) It("app ls includes new application", func() { Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName)) }) It("app show includes domain name", func() { appShowOutput, err := cli.AppShow(appName) Expect(err).NotTo(HaveOccurred()) Expect(appShowOutput.Name).To(Equal(appName)) Expect(appShowOutput.URI).To(Equal(domainName)) }) }) Context("when adding new environments", func() { fatalErrors := make(chan error) wgDone := make(chan bool) It("env init should succeed for adding test and prod environments", func() { var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() for { content, err := cli.EnvInit(&client.EnvInitRequest{ AppName: appName, EnvName: "test", Profile: "test", }) if err == nil { break } if !isStackSetOperationInProgress(content) { fatalErrors <- err } time.Sleep(waitingInterval) } }() go func() { defer wg.Done() for { content, err := cli.EnvInit(&client.EnvInitRequest{ AppName: appName, EnvName: "prod", Profile: "prod", }) if err == nil { break } if !isStackSetOperationInProgress(content) { fatalErrors <- err } time.Sleep(waitingInterval) } }() go func() { wg.Wait() close(wgDone) close(fatalErrors) }() select { case <-wgDone: case err := <-fatalErrors: Expect(err).NotTo(HaveOccurred()) } }) }) Context("when deploying the environments", func() { fatalErrors := make(chan error) wgDone := make(chan bool) It("env deploy should succeed for deploying test and prod environments", func() { var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() _, err := cli.EnvDeploy(&client.EnvDeployRequest{ AppName: appName, Name: "test", }) if err != nil { fatalErrors <- err } }() go func() { defer wg.Done() _, err := cli.EnvDeploy(&client.EnvDeployRequest{ AppName: appName, Name: "prod", }) if err != nil { fatalErrors <- err } }() go func() { wg.Wait() close(wgDone) close(fatalErrors) }() select { case <-wgDone: case err := <-fatalErrors: Expect(err).NotTo(HaveOccurred()) } }) }) Context("when initializing Load Balanced Web Services", func() { var svcInitErr error It("svc init should succeed for creating the hello service", func() { _, svcInitErr = cli.SvcInit(&client.SvcInitRequest{ Name: "hello", SvcType: "Load Balanced Web Service", Dockerfile: "./src/Dockerfile", SvcPort: "3000", }) Expect(svcInitErr).NotTo(HaveOccurred()) }) It("svc init should succeed for creating the frontend service", func() { _, svcInitErr = cli.SvcInit(&client.SvcInitRequest{ Name: "frontend", SvcType: "Load Balanced Web Service", Dockerfile: "./src/Dockerfile", SvcPort: "3000", }) Expect(svcInitErr).NotTo(HaveOccurred()) }) }) Context("when deploying a Load Balanced Web Service", func() { It("deployments should succeed", func() { fatalErrors := make(chan error) wgDone := make(chan bool) var wg sync.WaitGroup wg.Add(3) // deploy hello to test. go func() { defer wg.Done() for { content, err := cli.SvcDeploy(&client.SvcDeployInput{ Name: "hello", EnvName: "test", ImageTag: "hello", }) if err == nil { break } if !isStackSetOperationInProgress(content) && !isImagePushingToECRInProgress(content) { fatalErrors <- err } time.Sleep(waitingInterval) } }() // deploy frontend to test. go func() { defer wg.Done() for { content, err := cli.SvcDeploy(&client.SvcDeployInput{ Name: "frontend", EnvName: "test", ImageTag: "frontend", }) if err == nil { break } if !isStackSetOperationInProgress(content) && !isImagePushingToECRInProgress(content) { fatalErrors <- err } time.Sleep(waitingInterval) } }() // deploy hello to prod. go func() { defer wg.Done() for { content, err := cli.SvcDeploy(&client.SvcDeployInput{ Name: "hello", EnvName: "prod", ImageTag: "hello", }) if err == nil { break } if !isStackSetOperationInProgress(content) && !isImagePushingToECRInProgress(content) { fatalErrors <- err } time.Sleep(waitingInterval) } }() go func() { wg.Wait() close(wgDone) close(fatalErrors) }() select { case <-wgDone: case err := <-fatalErrors: Expect(err).NotTo(HaveOccurred()) } }) It("svc show should contain the expected domain and the request should succeed", func() { // Check hello service svc, err := cli.SvcShow(&client.SvcShowRequest{ Name: "hello", AppName: appName, }) Expect(err).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(2)) wantedURLs := map[string]string{ "test": fmt.Sprintf("https://test.%s", domainName), "prod": fmt.Sprintf("https://prod.%s", domainName), } for _, route := range svc.Routes { // Validate route has the expected HTTPS endpoint. Expect(route.URL).To(Equal(wantedURLs[route.Environment])) // Make sure the response is OK. var resp *http.Response var fetchErr error Eventually(func() (int, error) { resp, fetchErr = http.Get(route.URL) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) // HTTP should route to HTTPS. Eventually(func() (int, error) { resp, fetchErr = http.Get(strings.Replace(route.URL, "https", "http", 1)) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) } // Check frontend service. svc, err = cli.SvcShow(&client.SvcShowRequest{ Name: "frontend", AppName: appName, }) Expect(err).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(1)) wantedURLs = map[string]string{ "test": fmt.Sprintf("https://%s or https://frontend.%s", domainName, domainName), } // Validate route has the expected HTTPS endpoint. route := svc.Routes[0] Expect(route.URL).To(Equal(wantedURLs[route.Environment])) // Make sure the response is OK. var resp *http.Response var fetchErr error urls := strings.Split(route.URL, " or ") expectedRootResponseBody := "This is Copilot express app" expectedAdminResponseBody := "This is Copilot express app for admin" for _, url := range urls { Eventually(func() (int, error) { resp, fetchErr = http.Get(url) if fetchErr != nil { return 0, fetchErr } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return 0, err } if string(body) != expectedRootResponseBody { return 0, fmt.Errorf("the message content is %q, but expected %q", string(body), expectedRootResponseBody) } return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) // HTTP should route to HTTPS. Eventually(func() (int, error) { resp, fetchErr = http.Get(strings.Replace(url, "https", "http", 1)) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) Eventually(func() (int, error) { resp, fetchErr = http.Get(fmt.Sprintf("%s/admin", url)) if fetchErr != nil { return 0, fetchErr } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return 0, err } if string(body) != expectedAdminResponseBody { return 0, fmt.Errorf("the message content is %q, but expected %q", string(body), expectedAdminResponseBody) } return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) // HTTP should route to HTTPS. Eventually(func() (int, error) { resp, fetchErr = http.Get(strings.Replace(url, "https", "http", 1)) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) } }) }) })
338
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package apprunner_test import ( "fmt" "os" "testing" "time" "github.com/aws/copilot-cli/e2e/internal/client" "github.com/aws/copilot-cli/e2e/internal/command" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var cli *client.CLI var appName string var ssmName string var secretName string const feSvcName = "front-end" const beSvcName = "back-end" const envName = "test" /* * The Init Suite runs through the copilot init workflow for a brand new application. It creates a single environment, deploys a service to it, and then tears it down. */ func TestInit(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "App Runner Suite") } var _ = BeforeSuite(func() { var err error cli, err = client.NewCLI() Expect(err).NotTo(HaveOccurred()) appName = fmt.Sprintf("e2e-apprunner-%d", time.Now().Unix()) ssmName = fmt.Sprintf("%s-%s", appName, "ssm") err = os.Setenv("SSM_NAME", ssmName) Expect(err).NotTo(HaveOccurred()) secretName = fmt.Sprintf("%s-%s", appName, "secretsmanager") err = os.Setenv("SECRETS_MANAGER_NAME", secretName) Expect(err).NotTo(HaveOccurred()) err = command.Run("aws", []string{"ssm", "put-parameter", "--name", ssmName, "--overwrite", "--value", "abcd1234", "--type", "String"}) Expect(err).NotTo(HaveOccurred()) err = command.Run("aws", []string{"ssm", "add-tags-to-resource", "--resource-type", "Parameter", "--resource-id", ssmName, "--tags", "[{\"Key\":\"copilot-application\",\"Value\":\"" + appName + "\"},{\"Key\":\"copilot-environment\", \"Value\":\"" + envName + "\"}]"}) Expect(err).NotTo(HaveOccurred()) _ = command.Run("aws", []string{"secretsmanager", "create-secret", "--name", secretName, "--secret-string", "\"{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}\"", "--tags", "[{\"Key\":\"copilot-application\",\"Value\":\"" + appName + "\"},{\"Key\":\"copilot-environment\", \"Value\":\"" + envName + "\"}]"}) }) var _ = AfterSuite(func() { _, appDeleteErr := cli.AppDelete() ssmDeleteErr := command.Run("aws", []string{"ssm", "delete-parameter", "--name", ssmName}) secretsDeleteErr := command.Run("aws", []string{"secretsmanager", "delete-secret", "--secret-id", secretName, "--force-delete-without-recovery"}) _ = client.NewAWS().DeleteAllDBClusterSnapshots() Expect(appDeleteErr).NotTo(HaveOccurred()) Expect(ssmDeleteErr).NotTo(HaveOccurred()) Expect(secretsDeleteErr).NotTo(HaveOccurred()) })
68
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package apprunner_test import ( "fmt" "net/http" "strings" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) type countAssertionTracker struct { expected int actual int } var _ = Describe("App Runner", Ordered, func() { var ( initErr error ) BeforeAll(func() { _, initErr = cli.Init(&client.InitRequest{ AppName: appName, WorkloadName: feSvcName, ImageTag: "gallopinggurdey", Dockerfile: "./front-end/Dockerfile", WorkloadType: "Request-Driven Web Service", Deploy: true, SvcPort: "80", }) }) Context("run init with app runner", func() { It("init does not return an error", func() { Expect(initErr).NotTo(HaveOccurred()) }) }) Context("run svc ls to ensure the service was created", func() { var ( svcList *client.SvcListOutput svcListError error ) BeforeAll(func() { svcList, svcListError = cli.SvcList(appName) }) It("should not return an error", func() { Expect(svcListError).NotTo(HaveOccurred()) }) It("should return one service", func() { Expect(len(svcList.Services)).To(Equal(1)) Expect(svcList.Services[0].Name).To(Equal(feSvcName)) Expect(svcList.Services[0].AppName).To(Equal(appName)) Expect(svcList.Services[0].Type).To(Equal("Request-Driven Web Service")) }) }) Context("run svc status to ensure that the service is healthy", func() { var ( out *client.SvcStatusOutput svcStatusError error ) BeforeAll(func() { out, svcStatusError = cli.SvcStatus(&client.SvcStatusRequest{ Name: feSvcName, AppName: appName, EnvName: envName, }) }) It("should not return an error", func() { Expect(svcStatusError).NotTo(HaveOccurred()) }) It("should return app runner service status", func() { Expect(out.Status).To(Equal("RUNNING")) }) }) Context("create and deploy a backend service", func() { var ( initErr error deployErr error ) BeforeAll(func() { _, initErr = cli.SvcInit(&client.SvcInitRequest{ Name: beSvcName, SvcType: "Request-Driven Web Service", Dockerfile: "./back-end/Dockerfile", SvcPort: "80", IngressType: "Environment", }) _, deployErr = cli.SvcDeploy(&client.SvcDeployInput{ EnvName: envName, Name: beSvcName, }) }) It("should not return an error", func() { Expect(initErr).NotTo(HaveOccurred()) Expect(deployErr).NotTo(HaveOccurred()) }) }) Context("run svc show to retrieve the service configuration, resources, secrets, and endpoint, then query the service", func() { var ( svc *client.SvcShowOutput svcShowError error backendSvc *client.SvcShowOutput backendShowErr error ) BeforeAll(func() { svc, svcShowError = cli.SvcShow(&client.SvcShowRequest{ Name: feSvcName, AppName: appName, Resources: true, }) backendSvc, backendShowErr = cli.SvcShow(&client.SvcShowRequest{ Name: beSvcName, AppName: appName, Resources: true, }) }) It("should not return an error", func() { Expect(svcShowError).NotTo(HaveOccurred()) Expect(backendShowErr).NotTo(HaveOccurred()) }) It("should return correct configuration", func() { Expect(svc.SvcName).To(Equal(feSvcName)) Expect(svc.AppName).To(Equal(appName)) Expect(len(svc.Configs)).To(Equal(1)) Expect(svc.Configs[0].Environment).To(Equal(envName)) Expect(svc.Configs[0].CPU).To(Equal("1024")) Expect(svc.Configs[0].Memory).To(Equal("2048")) Expect(svc.Configs[0].Port).To(Equal("80")) Expect(backendSvc.SvcName).To(Equal(beSvcName)) Expect(backendSvc.AppName).To(Equal(appName)) Expect(backendSvc.Configs[0].Environment).To(Equal(envName)) }) It("should return correct environment variables", func() { fmt.Printf("\n\nenvironment variables: %+v\n\n", svc.Variables) expectedVars := map[string]string{ "COPILOT_APPLICATION_NAME": appName, "COPILOT_ENVIRONMENT_NAME": envName, "COPILOT_SERVICE_NAME": feSvcName, "COPILOT_SERVICE_DISCOVERY_ENDPOINT": fmt.Sprintf("%s.%s.local", envName, appName), } for _, variable := range svc.Variables { Expect(variable.Value).To(Equal(expectedVars[variable.Name])) } }) It("should return correct secrets", func() { fmt.Printf("\n\nsecrets: %+v\n\n", svc.Secrets) for _, envVar := range svc.Secrets { if envVar.Name == "my-ssm-param" { Expect(envVar.Value).To(Equal(ssmName)) } if envVar.Name == "USER_CREDS" { valueFromARN := envVar.Value // E.g. arn:aws:secretsmanager:ap-northeast-1:1111111111:secret:e2e-apprunner-my-secret Expect(strings.Contains(valueFromARN, secretName)).To(BeTrue()) } } }) It("should return the correct resources", func() { Expect(len(svc.Resources)).To(Equal(1)) Expect(svc.Resources[envName]).NotTo(BeNil()) expectedTypes := map[string]*countAssertionTracker{ "AWS::IAM::Role": {3, 0}, "AWS::AppRunner::Service": {1, 0}, "AWS::EC2::SecurityGroup": {1, 0}, "AWS::EC2::SecurityGroupIngress": {1, 0}, "AWS::AppRunner::VpcConnector": {1, 0}, "Custom::EnvControllerFunction": {1, 0}, "AWS::Lambda::Function": {1, 0}, } for _, r := range svc.Resources[envName] { if expectedTypes[r.Type] == nil { expectedTypes[r.Type] = &countAssertionTracker{0, 0} } expectedTypes[r.Type].actual++ } for t, v := range expectedTypes { Expect(v.actual).To( Equal(v.expected), fmt.Sprintf("Expected %v resources of type %v, received %v", v.expected, t, v.actual)) } }) It("should return svc endpoints and service discovery should work", func() { Expect(len(svc.Routes)).To(Equal(1)) route := svc.Routes[0] Expect(route.Environment).To(Equal(envName)) Expect(route.URL).NotTo(BeEmpty()) Expect(route.Ingress).To(Equal("internet")) beRoute := backendSvc.Routes[0] Expect(beRoute.Environment).To(Equal(envName)) Expect(beRoute.URL).NotTo(BeEmpty()) Expect(beRoute.Ingress).To(Equal("environment")) Eventually(func() (int, error) { resp, fetchErr := http.Get(route.URL) return resp.StatusCode, fetchErr }, "30s", "1s").Should(Equal(200)) Eventually(func() (int, error) { resp, fetchErr := http.Get(fmt.Sprintf("%s/proxy?url=%s/hello-world", route.URL, beRoute.URL)) return resp.StatusCode, fetchErr }, "30s", "1s").Should(Equal(200)) }) }) It("svc logs should display logs", func() { var svcLogs []client.SvcLogsOutput var svcLogsErr error Eventually(func() ([]client.SvcLogsOutput, error) { svcLogs, svcLogsErr = cli.SvcLogs(&client.SvcLogsRequest{ AppName: appName, Name: feSvcName, EnvName: "test", Since: "1h", }) return svcLogs, svcLogsErr }, "300s", "10s").ShouldNot(BeEmpty()) for _, logLine := range svcLogs { Expect(logLine.Message).NotTo(Equal("")) Expect(logLine.LogStreamName).NotTo(Equal("")) Expect(logLine.Timestamp).NotTo(Equal(0)) Expect(logLine.IngestionTime).NotTo(Equal(0)) } }) Context("run pause and then resume the service", func() { var ( svcPauseError error pausedSvcStatus *client.SvcStatusOutput pausedSvcStatusError error svcResumeError error resumedSvcStatus *client.SvcStatusOutput resumedSvcStatusError error ) BeforeAll(func() { _, svcPauseError = cli.SvcPause(&client.SvcPauseRequest{ AppName: appName, EnvName: envName, Name: feSvcName, }) pausedSvcStatus, pausedSvcStatusError = cli.SvcStatus(&client.SvcStatusRequest{ Name: feSvcName, AppName: appName, EnvName: envName, }) _, svcResumeError = cli.SvcResume(&client.SvcResumeRequest{ AppName: appName, EnvName: envName, Name: feSvcName, }) resumedSvcStatus, resumedSvcStatusError = cli.SvcStatus(&client.SvcStatusRequest{ Name: feSvcName, AppName: appName, EnvName: envName, }) }) It("should not an return error", func() { Expect(svcPauseError).NotTo(HaveOccurred()) Expect(pausedSvcStatusError).NotTo(HaveOccurred()) Expect(svcResumeError).NotTo(HaveOccurred()) Expect(resumedSvcStatusError).NotTo(HaveOccurred()) }) It("should successfully pause service", func() { Expect(pausedSvcStatus.Status).To(Equal("PAUSED")) }) It("should successfully resume service", func() { Expect(resumedSvcStatus.Status).To(Equal("RUNNING")) }) }) Context("force deploy the service", func() { var ( svcDeployError error svcStatus *client.SvcStatusOutput svcStatusError error ) BeforeAll(func() { _, svcDeployError = cli.SvcDeploy(&client.SvcDeployInput{ EnvName: envName, Name: feSvcName, Force: true, }) svcStatus, svcStatusError = cli.SvcStatus(&client.SvcStatusRequest{ Name: feSvcName, AppName: appName, EnvName: envName, }) }) It("should not an return error", func() { Expect(svcDeployError).NotTo(HaveOccurred()) Expect(svcStatusError).NotTo(HaveOccurred()) }) It("should successfully force deploy service", func() { Expect(svcStatus.Status).To(Equal("RUNNING")) }) }) })
333
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "errors" "log" "net/http" ) // HealthCheck returns a 200. func HealthCheck(w http.ResponseWriter, req *http.Request) { log.Println("🚑 healthcheck ok!") w.WriteHeader(http.StatusOK) } // HelloWorld writes a hello world message. func HelloWorld(w http.ResponseWriter, req *http.Request) { log.Printf("Received request to %s", req.URL.Path) w.WriteHeader(http.StatusOK) w.Write([]byte("hello-world")) } func main() { http.Handle("/", http.HandlerFunc(HealthCheck)) http.Handle("/hello-world", http.HandlerFunc(HelloWorld)) err := http.ListenAndServe(":80", nil) if !errors.Is(err, http.ErrServerClosed) { log.Fatalf("listen and serve: %s", err) } }
34
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "errors" "fmt" "io" "log" "net/http" "os" "time" ) // SimpleGet writes the name of the service to the response. func SimpleGet(w http.ResponseWriter, req *http.Request) { log.Println("Get Succeeded") w.WriteHeader(http.StatusOK) w.Write([]byte(os.Getenv("COPILOT_APPLICATION_NAME") + "-" + os.Getenv("COPILOT_ENVIRONMENT_NAME") + "-" + os.Getenv("COPILOT_SERVICE_NAME"))) } // ProxyRequest makes a GET request to the query param "url" // from the request and writes the response from the url to the response. func ProxyRequest(w http.ResponseWriter, r *http.Request) { url := r.URL.Query().Get("url") log.Printf("Proxying request to %q", url) ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() handleErr := func(format string, a ...any) { msg := fmt.Sprintf(format, a...) log.Println(msg) w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(msg)) } req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { handleErr("build request: %s", err) return } log.Println("Built request") resp, err := http.DefaultClient.Do(req) if err != nil { handleErr("do request: %s", err) return } defer resp.Body.Close() log.Println("Did request") body, err := io.ReadAll(resp.Body) if err != nil { handleErr("read response: %s", err) return } log.Printf("Response:\n%s", string(body)) w.WriteHeader(http.StatusOK) w.Write(body) } func main() { http.Handle("/", http.HandlerFunc(SimpleGet)) http.Handle("/proxy", http.HandlerFunc(ProxyRequest)) err := http.ListenAndServe(":80", nil) if !errors.Is(err, http.ErrServerClosed) { log.Fatalf("listen and serve: %s", err) } }
76
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cloudfront_test import ( "fmt" "os" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var cli *client.CLI var appName string var bucketName string var s3Client *s3.S3 var s3Manager *s3manager.Uploader var staticPath string const domainName = "cloudfront.copilot-e2e-tests.ecs.aws.dev" var timeNow = time.Now().Unix() func TestCloudFront(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "CloudFront Suite") } var _ = BeforeSuite(func() { copilotCLI, err := client.NewCLI() Expect(err).NotTo(HaveOccurred()) cli = copilotCLI appName = fmt.Sprintf("t%d", timeNow) bucketName = appName err = os.Setenv("BUCKETNAME", bucketName) Expect(err).NotTo(HaveOccurred()) err = os.Setenv("DOMAINNAME", domainName) Expect(err).NotTo(HaveOccurred()) err = os.Setenv("TIMENOW", fmt.Sprint(timeNow)) Expect(err).NotTo(HaveOccurred()) staticPath = "static/index.html" sess, err := session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, }) Expect(err).NotTo(HaveOccurred()) s3Client = s3.New(sess) s3Manager = s3manager.NewUploader(sess) }) var _ = AfterSuite(func() { _, appDeleteErr := cli.AppDelete() s3Err := cleanUpS3Resources() Expect(appDeleteErr).NotTo(HaveOccurred()) Expect(s3Err).NotTo(HaveOccurred()) }) func cleanUpS3Resources() error { _, err := s3Client.DeleteObject(&s3.DeleteObjectInput{ Bucket: aws.String(bucketName), Key: aws.String(staticPath), }) if err != nil { return err } _, err = s3Client.DeleteBucket(&s3.DeleteBucketInput{ Bucket: aws.String(bucketName), }) return err }
78
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cloudfront_test import ( "bytes" "fmt" "net/http" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/copilot-cli/e2e/internal/client" ) var _ = Describe("CloudFront", func() { Context("when creating an S3 bucket and upload static files", Ordered, func() { It("bucket creation should succeed", func() { _, err := s3Client.CreateBucket(&s3.CreateBucketInput{ Bucket: aws.String(bucketName), ObjectOwnership: aws.String(s3.ObjectOwnershipBucketOwnerEnforced), }) Expect(err).NotTo(HaveOccurred()) }) It("upload should succeed", func() { _, err := s3Manager.Upload(&s3manager.UploadInput{ Bucket: aws.String(bucketName), Key: aws.String(staticPath), Body: bytes.NewBufferString("hello static"), }) Expect(err).NotTo(HaveOccurred()) }) }) Context("when creating a new app", Ordered, func() { var appInitErr error BeforeAll(func() { _, appInitErr = cli.AppInit(&client.AppInitRequest{ AppName: appName, Domain: domainName, }) }) It("app init succeeds", func() { Expect(appInitErr).NotTo(HaveOccurred()) }) It("app init creates a copilot directory", func() { Expect("./copilot").Should(BeADirectory()) }) It("app ls includes new application", func() { Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName)) }) It("app show includes domain name", func() { appShowOutput, err := cli.AppShow(appName) Expect(err).NotTo(HaveOccurred()) Expect(appShowOutput.Name).To(Equal(appName)) Expect(appShowOutput.URI).To(Equal(domainName)) }) }) Context("when adding new environment", Ordered, func() { var err error BeforeAll(func() { _, err = cli.EnvInit(&client.EnvInitRequest{ AppName: appName, EnvName: "test", Profile: "test", }) }) It("env init should succeed", func() { Expect(err).NotTo(HaveOccurred()) }) }) Context("when deploying the environments", Ordered, func() { var envDeployErr error BeforeAll(func() { _, envDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{ AppName: appName, Name: "test", }) }) It("env deploy should succeed", func() { Expect(envDeployErr).NotTo(HaveOccurred()) }) }) Context("when initializing Load Balanced Web Services", Ordered, func() { var svcInitErr error BeforeAll(func() { _, svcInitErr = cli.SvcInit(&client.SvcInitRequest{ Name: "frontend", SvcType: "Load Balanced Web Service", Dockerfile: "./src/Dockerfile", SvcPort: "80", }) }) It("svc init should succeed for creating the frontend service", func() { Expect(svcInitErr).NotTo(HaveOccurred()) }) }) Context("when deploying a Load Balanced Web Service", func() { It("deployment should succeed", func() { _, err := cli.SvcDeploy(&client.SvcDeployInput{ Name: "frontend", EnvName: "test", ImageTag: "frontend", }) Expect(err).NotTo(HaveOccurred()) }) It("updating s3 bucket policy should succeed", func() { out, err := cli.EnvShow(&client.EnvShowRequest{ AppName: appName, EnvName: "test", }) Expect(err).NotTo(HaveOccurred()) var accountID string var cfDistID string for _, resource := range out.Resources { switch resource["logicalID"] { case "PublicLoadBalancer": parsed, err := arn.Parse(resource["physicalID"]) Expect(err).NotTo(HaveOccurred()) accountID = parsed.AccountID case "CloudFrontDistribution": cfDistID = resource["physicalID"] } } Expect(accountID).ToNot(BeEmpty()) Expect(cfDistID).ToNot(BeEmpty()) _, err = s3Client.PutBucketPolicy(&s3.PutBucketPolicyInput{ Bucket: aws.String(bucketName), Policy: aws.String(fmt.Sprintf(`{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCloudFrontServicePrincipalReadOnly", "Effect": "Allow", "Principal": { "Service": "cloudfront.amazonaws.com" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::%s/static/*", "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::%s:distribution/%s" } } } ] } `, bucketName, accountID, cfDistID)), }) Expect(err).NotTo(HaveOccurred()) }) It("svc show should contain the expected domain and the request should succeed", func() { svc, err := cli.SvcShow(&client.SvcShowRequest{ Name: "frontend", AppName: appName, }) Expect(err).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(1)) route := svc.Routes[0] wantedURLs := map[string]string{ "test": fmt.Sprintf("https://frontend-%d.%s", timeNow, domainName), } // Validate route has the expected HTTPS endpoint. Expect(route.URL).To(Equal(wantedURLs[route.Environment])) // Make sure the service response is OK. var resp *http.Response var fetchErr error Eventually(func() (int, error) { resp, fetchErr = http.Get(route.URL) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) // HTTP should work. Eventually(func() (int, error) { resp, fetchErr = http.Get(strings.Replace(route.URL, "https", "http", 1)) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) // Static assets should be accessible. Eventually(func() (int, error) { resp, fetchErr = http.Get(fmt.Sprintf("%s/%s", route.URL, staticPath)) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) }) }) })
204
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package customized_env_test import ( "fmt" "testing" "time" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var cli *client.CLI var aws *client.AWS var appName string var vpcStackName string var vpcStackTemplatePath string var vpcImport client.EnvInitRequestVPCImport var vpcConfig client.EnvInitRequestVPCConfig /** The Customized Env Suite creates multiple environments with customized resources, deploys a service to it, and then tears it down. */ func Test_Customized_Env(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Customized Env Svc Suite") } var _ = BeforeSuite(func() { vpcStackName = fmt.Sprintf("e2e-customizedenv-vpc-stack-%d", time.Now().Unix()) vpcStackTemplatePath = "file://vpc.yml" ecsCli, err := client.NewCLI() Expect(err).NotTo(HaveOccurred()) cli = ecsCli aws = client.NewAWS() appName = fmt.Sprintf("e2e-customizedenv-%d", time.Now().Unix()) vpcConfig = client.EnvInitRequestVPCConfig{ CIDR: "10.1.0.0/16", PrivateSubnetCIDRs: "10.1.2.0/24,10.1.3.0/24", PublicSubnetCIDRs: "10.1.0.0/24,10.1.1.0/24", } }) var _ = AfterSuite(func() { _, appDeleteErr := cli.AppDelete() // Delete VPC stack. vpcDeleteErr := aws.DeleteStack(vpcStackName) Expect(appDeleteErr).NotTo(HaveOccurred()) Expect(vpcDeleteErr).NotTo(HaveOccurred()) })
56
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package customized_env_test import ( "errors" "fmt" "net/http" "os" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/aws/copilot-cli/e2e/internal/client" ) const resourceTypeVPC = "AWS::EC2::VPC" var _ = Describe("Customized Env", func() { Context("when creating a new app", Ordered, func() { var appInitErr error BeforeAll(func() { _, appInitErr = cli.AppInit(&client.AppInitRequest{ AppName: appName, Tags: map[string]string{ "e2e-test": "customized-env", }, }) }) It("app init succeeds", func() { Expect(appInitErr).NotTo(HaveOccurred()) }) It("app init creates a copilot directory", func() { Expect("./copilot").Should(BeADirectory()) }) It("app ls includes new app", func() { Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName)) }) It("app show includes app name", func() { appShowOutput, err := cli.AppShow(appName) Expect(err).NotTo(HaveOccurred()) Expect(appShowOutput.Name).To(Equal(appName)) Expect(appShowOutput.URI).To(BeEmpty()) }) }) Context("when deploying resources to be imported", Ordered, func() { BeforeAll(func() { err := aws.CreateStack(vpcStackName, vpcStackTemplatePath) Expect(err).NotTo(HaveOccurred(), "create vpc cloudformation stack") err = aws.WaitStackCreateComplete(vpcStackName) Expect(err).NotTo(HaveOccurred(), "vpc stack create complete") }) It("parse vpc stack output", func() { outputs, err := aws.VPCStackOutput(vpcStackName) Expect(err).NotTo(HaveOccurred(), "get VPC stack output") for _, output := range outputs { switch output.OutputKey { case "PrivateSubnets": vpcImport.PrivateSubnetIDs = output.OutputValue case "VpcId": vpcImport.ID = output.OutputValue case "PublicSubnets": vpcImport.PublicSubnetIDs = output.OutputValue } } if !vpcImport.IsSet() { err = errors.New("vpc resources are not configured properly") } Expect(err).NotTo(HaveOccurred(), "invalid vpc stack output") }) }) Context("when adding cross account environments", Ordered, func() { var ( testEnvInitErr error prodEnvInitErr error sharedEnvInitErr error ) BeforeAll(func() { _, testEnvInitErr = cli.EnvInit(&client.EnvInitRequest{ AppName: appName, EnvName: "test", Profile: "test", VPCImport: vpcImport, CustomizedEnv: true, }) _, prodEnvInitErr = cli.EnvInit(&client.EnvInitRequest{ AppName: appName, EnvName: "prod", Profile: "prod", VPCConfig: vpcConfig, CustomizedEnv: true, }) _, sharedEnvInitErr = cli.EnvInit(&client.EnvInitRequest{ AppName: appName, EnvName: "shared", Profile: "shared", VPCImport: vpcImport, CustomizedEnv: true, }) }) It("env init should succeed for test, prod and shared envs", func() { Expect(testEnvInitErr).NotTo(HaveOccurred()) Expect(prodEnvInitErr).NotTo(HaveOccurred()) Expect(sharedEnvInitErr).NotTo(HaveOccurred()) }) It("should create environment manifests", func() { Expect("./copilot/environments/test/manifest.yml").Should(BeAnExistingFile()) Expect("./copilot/environments/prod/manifest.yml").Should(BeAnExistingFile()) Expect("./copilot/environments/shared/manifest.yml").Should(BeAnExistingFile()) }) It("env ls should list all three envs", func() { envListOutput, err := cli.EnvList(appName) Expect(err).NotTo(HaveOccurred()) Expect(len(envListOutput.Envs)).To(Equal(3)) envs := map[string]client.EnvDescription{} for _, env := range envListOutput.Envs { envs[env.Name] = env Expect(env.ExecutionRole).NotTo(BeEmpty()) Expect(env.ManagerRole).NotTo(BeEmpty()) } Expect(envs["test"]).NotTo(BeNil()) Expect(envs["shared"]).NotTo(BeNil()) Expect(envs["prod"]).NotTo(BeNil()) }) It("should show only bootstrap resources in env show", func() { testEnvShowOutput, testEnvShowError := cli.EnvShow(&client.EnvShowRequest{ AppName: appName, EnvName: "test", }) prodEnvShowOutput, prodEnvShowError := cli.EnvShow(&client.EnvShowRequest{ AppName: appName, EnvName: "prod", }) sharedEnvShowOutput, sharedEnvShowError := cli.EnvShow(&client.EnvShowRequest{ AppName: appName, EnvName: "shared", }) Expect(testEnvShowError).NotTo(HaveOccurred()) Expect(prodEnvShowError).NotTo(HaveOccurred()) Expect(sharedEnvShowError).NotTo(HaveOccurred()) Expect(testEnvShowOutput.Environment.Name).To(Equal("test")) Expect(testEnvShowOutput.Environment.App).To(Equal(appName)) Expect(prodEnvShowOutput.Environment.Name).To(Equal("prod")) Expect(prodEnvShowOutput.Environment.App).To(Equal(appName)) Expect(sharedEnvShowOutput.Environment.Name).To(Equal("shared")) Expect(sharedEnvShowOutput.Environment.App).To(Equal(appName)) // Contains only bootstrap resources - two IAM roles. Expect(len(testEnvShowOutput.Resources)).To(Equal(2)) Expect(len(prodEnvShowOutput.Resources)).To(Equal(2)) Expect(len(sharedEnvShowOutput.Resources)).To(Equal(2)) }) }) Context("when deploying the environments", Ordered, func() { var ( testEnvDeployErr, prodEnvDeployErr, sharedEnvDeployErr error ) BeforeAll(func() { _, testEnvDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{ AppName: appName, Name: "test", }) _, prodEnvDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{ AppName: appName, Name: "prod", }) _, sharedEnvDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{ AppName: appName, Name: "shared", }) }) It("should succeed", func() { Expect(testEnvDeployErr).NotTo(HaveOccurred()) Expect(prodEnvDeployErr).NotTo(HaveOccurred()) Expect(sharedEnvDeployErr).NotTo(HaveOccurred()) }) It("should show correct resources in env show", func() { testEnvShowOutput, testEnvShowError := cli.EnvShow(&client.EnvShowRequest{ AppName: appName, EnvName: "test", }) Expect(testEnvShowError).NotTo(HaveOccurred()) // Test environment imports VPC resources. Therefore, resource of type "AWS::EC2::VPC" is not expected. Expect(len(testEnvShowOutput.Resources)).To(BeNumerically(">", 2)) for _, resource := range testEnvShowOutput.Resources { Expect(resource["type"]).NotTo(Equal(resourceTypeVPC)) } prodEnvShowOutput, prodEnvShowError := cli.EnvShow(&client.EnvShowRequest{ AppName: appName, EnvName: "prod", }) Expect(prodEnvShowError).NotTo(HaveOccurred()) // Prod environment adjusts VPC resources. Therefore, resource of type "AWS::EC2::VPC" is expected. Expect(len(prodEnvShowOutput.Resources)).To(BeNumerically(">", 2)) var prodEnvHasVPCResource bool for _, resource := range prodEnvShowOutput.Resources { if resource["type"] == resourceTypeVPC { prodEnvHasVPCResource = true break } } Expect(prodEnvHasVPCResource).To(BeTrue()) sharedEnvShowOutput, sharedEnvShowError := cli.EnvShow(&client.EnvShowRequest{ AppName: appName, EnvName: "shared", }) Expect(sharedEnvShowError).NotTo(HaveOccurred()) // Shared environment imports VPC resources. Therefore, resource of type "AWS::EC2::VPC" is not expected. Expect(len(sharedEnvShowOutput.Resources)).To(BeNumerically(">", 2)) for _, resource := range sharedEnvShowOutput.Resources { Expect(resource["type"]).NotTo(Equal(resourceTypeVPC)) } }) }) Context("when adding a svc", Ordered, func() { var ( frontEndInitErr error ) BeforeAll(func() { _, frontEndInitErr = cli.SvcInit(&client.SvcInitRequest{ Name: "front-end", SvcType: "Load Balanced Web Service", Dockerfile: "./front-end/Dockerfile", SvcPort: "80", }) }) It("svc init should succeed", func() { Expect(frontEndInitErr).NotTo(HaveOccurred()) }) It("svc init should create a svc manifest", func() { Expect("./copilot/front-end/manifest.yml").Should(BeAnExistingFile()) }) It("should copy private placement to the manifest for test environment", func() { f, err := os.OpenFile("./copilot/front-end/manifest.yml", os.O_WRONLY|os.O_APPEND, 0644) Expect(err).NotTo(HaveOccurred(), "should be able to open the file to append content") // "test" is the only environment where we import a VPC. _, err = f.WriteString(` environments: test: network: vpc: placement: 'private' `) Expect(err).NotTo(HaveOccurred(), "should be able to write 'private' placement to manifest file") err = f.Close() Expect(err).NotTo(HaveOccurred(), "should have been able to close the manifest file") }) It("svc ls should list the svc", func() { svcList, svcListError := cli.SvcList(appName) Expect(svcListError).NotTo(HaveOccurred()) Expect(len(svcList.Services)).To(Equal(1)) Expect(svcList.Services[0].Name).To(Equal("front-end")) }) }) Context("when deploying a svc to test, prod, and shared envs", Ordered, func() { var ( testDeployErr error prodEndDeployErr error sharedDeployErr error svcName string ) BeforeAll(func() { svcName = "front-end" _, testDeployErr = cli.SvcDeploy(&client.SvcDeployInput{ Name: svcName, EnvName: "test", ImageTag: "gallopinggurdey", }) _, prodEndDeployErr = cli.SvcDeploy(&client.SvcDeployInput{ Name: svcName, EnvName: "prod", ImageTag: "gallopinggurdey", }) _, sharedDeployErr = cli.SvcDeploy(&client.SvcDeployInput{ Name: svcName, EnvName: "shared", ImageTag: "gallopinggurdey", }) }) It("svc deploy should succeed to all three environments", func() { Expect(testDeployErr).NotTo(HaveOccurred()) Expect(prodEndDeployErr).NotTo(HaveOccurred()) Expect(sharedDeployErr).NotTo(HaveOccurred()) }) It("svc show should include a valid URL and description for test, prod and shared envs", func() { svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{ AppName: appName, Name: svcName, }) Expect(svcShowErr).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(3)) // Group routes by environment envRoutes := map[string]client.SvcShowRoutes{} for _, route := range svc.Routes { envRoutes[route.Environment] = route } Expect(len(svc.ServiceDiscoveries)).To(Equal(3)) var envs, endpoints, wantedEndpoints []string for _, sd := range svc.ServiceDiscoveries { envs = append(envs, sd.Environment[0]) endpoints = append(endpoints, sd.Endpoint) wantedEndpoints = append(wantedEndpoints, fmt.Sprintf("%s.%s.%s.local:80", svc.SvcName, sd.Environment[0], appName)) } Expect(envs).To(ConsistOf("test", "prod", "shared")) Expect(endpoints).To(ConsistOf(wantedEndpoints)) // Call each environment's endpoint and ensure it returns a 200 for _, env := range []string{"test", "prod", "shared"} { route := envRoutes[env] Expect(route.Environment).To(Equal(env)) Eventually(func() (int, error) { resp, fetchErr := http.Get(route.URL) return resp.StatusCode, fetchErr }, "30s", "1s").Should(Equal(200)) } }) It("svc logs should display logs", func() { for _, envName := range []string{"test", "prod", "shared"} { var svcLogs []client.SvcLogsOutput var svcLogsErr error Eventually(func() ([]client.SvcLogsOutput, error) { svcLogs, svcLogsErr = cli.SvcLogs(&client.SvcLogsRequest{ AppName: appName, Name: svcName, EnvName: envName, Since: "1h", }) return svcLogs, svcLogsErr }, "60s", "10s").ShouldNot(BeEmpty()) for _, logLine := range svcLogs { Expect(logLine.Message).NotTo(Equal("")) Expect(logLine.LogStreamName).NotTo(Equal("")) Expect(logLine.Timestamp).NotTo(Equal(0)) Expect(logLine.IngestionTime).NotTo(Equal(0)) } } }) It("env show should display info for test, prod, and shared envs", func() { envs := map[string]client.EnvDescription{} for _, envName := range []string{"test", "prod", "shared"} { envShowOutput, envShowErr := cli.EnvShow(&client.EnvShowRequest{ AppName: appName, EnvName: envName, }) Expect(envShowErr).NotTo(HaveOccurred()) Expect(envShowOutput.Environment.Name).To(Equal(envName)) Expect(envShowOutput.Environment.App).To(Equal(appName)) Expect(len(envShowOutput.Services)).To(Equal(1)) Expect(envShowOutput.Services[0].Name).To(Equal(svcName)) Expect(envShowOutput.Services[0].Type).To(Equal("Load Balanced Web Service")) Expect(len(envShowOutput.Tags)).To(Equal(3)) Expect(envShowOutput.Tags["copilot-application"]).To(Equal(appName)) Expect(envShowOutput.Tags["copilot-environment"]).To(Equal(envName)) Expect(envShowOutput.Tags["e2e-test"]).To(Equal("customized-env")) envs[envShowOutput.Environment.Name] = envShowOutput.Environment } Expect(envs["test"]).NotTo(BeNil()) Expect(envs["prod"]).NotTo(BeNil()) Expect(envs["shared"]).NotTo(BeNil()) }) }) })
399
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package exec_test import ( "fmt" "testing" "time" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var cli *client.CLI var appName, envName, svcName, groupName string // The Exec suite runs creates a new service and task and exec into them. func TestExec(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Exec Suite") } var _ = BeforeSuite(func() { ecsCli, err := client.NewCLI() cli = ecsCli Expect(err).NotTo(HaveOccurred()) appName = fmt.Sprintf("e2e-exec-%d", time.Now().Unix()) groupName = fmt.Sprintf("e2e-exec-task-%d", time.Now().Unix()) svcName = "hello" envName = "test" }) var _ = AfterSuite(func() { _, err := cli.AppDelete() Expect(err).NotTo(HaveOccurred()) })
39
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package exec_test import ( "fmt" "io" "net/http" "strings" "time" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("exec flow", func() { Context("when creating a new app", Ordered, func() { var ( initErr error ) BeforeAll(func() { _, initErr = cli.AppInit(&client.AppInitRequest{ AppName: appName, }) }) It("app init succeeds", func() { Expect(initErr).NotTo(HaveOccurred()) }) It("app init creates an copilot directory and workspace file", func() { Expect("./copilot").Should(BeADirectory()) Expect("./copilot/.workspace").Should(BeAnExistingFile()) }) It("app ls includes new app", func() { Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName)) }) It("app show includes app name", func() { appShowOutput, err := cli.AppShow(appName) Expect(err).NotTo(HaveOccurred()) Expect(appShowOutput.Name).To(Equal(appName)) Expect(appShowOutput.URI).To(BeEmpty()) }) }) Context("when adding a new environment", Ordered, func() { var ( testEnvInitErr error ) BeforeAll(func() { _, testEnvInitErr = cli.EnvInit(&client.EnvInitRequest{ AppName: appName, EnvName: envName, Profile: envName, }) }) It("env init should succeed", func() { Expect(testEnvInitErr).NotTo(HaveOccurred()) }) }) Context("when deploying the environment", Ordered, func() { var envDeployErr error BeforeAll(func() { _, envDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{ AppName: appName, Name: envName, }) }) It("should succeed", func() { Expect(envDeployErr).NotTo(HaveOccurred()) }) }) Context("when adding a svc", Ordered, func() { var ( svcInitErr error ) BeforeAll(func() { _, svcInitErr = cli.SvcInit(&client.SvcInitRequest{ Name: svcName, SvcType: "Load Balanced Web Service", Dockerfile: "./hello/Dockerfile", SvcPort: "80", }) }) It("svc init should succeed", func() { Expect(svcInitErr).NotTo(HaveOccurred()) }) It("svc init should create svc manifests", func() { Expect("./copilot/hello/manifest.yml").Should(BeAnExistingFile()) }) It("svc ls should list the service", func() { svcList, svcListError := cli.SvcList(appName) Expect(svcListError).NotTo(HaveOccurred()) Expect(len(svcList.Services)).To(Equal(1)) svcsByName := map[string]client.WkldDescription{} for _, svc := range svcList.Services { svcsByName[svc.Name] = svc } for _, svc := range []string{svcName} { Expect(svcsByName[svc].AppName).To(Equal(appName)) Expect(svcsByName[svc].Name).To(Equal(svc)) } }) }) Context("when deploying svc", Ordered, func() { const newContent = "HELP I AM TRAPPED INSIDE A SHELL" var ( appDeployErr error taskID1 string taskID2 string ) BeforeAll(func() { _, appDeployErr = cli.SvcDeploy(&client.SvcDeployInput{ Name: svcName, EnvName: envName, ImageTag: "gallopinggurdey", }) }) It("svc deploy should succeed", func() { Expect(appDeployErr).NotTo(HaveOccurred()) }) It("svc status should show two tasks running", func() { svc, svcStatusErr := cli.SvcStatus(&client.SvcStatusRequest{ AppName: appName, Name: svcName, EnvName: envName, }) Expect(svcStatusErr).NotTo(HaveOccurred()) // Service should be active. Expect(svc.Service.Status).To(Equal("ACTIVE")) // Should have correct number of running tasks. Expect(len(svc.Tasks)).To(Equal(2)) taskID1 = svc.Tasks[0].ID taskID2 = svc.Tasks[1].ID }) It("svc show should include a valid URL and description for test env", func() { svc, err := cli.SvcShow(&client.SvcShowRequest{ AppName: appName, Name: svcName, }) Expect(err).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(1)) Expect(len(svc.ServiceConnects)).To(Equal(0)) route := svc.Routes[0] Expect(route.Environment).To(Equal(envName)) var resp *http.Response var fetchErr error Eventually(func() (int, error) { resp, fetchErr = http.Get(route.URL) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) // Read the response - our deployed service should return a body with its // name as the value. bodyBytes, err := io.ReadAll(resp.Body) Expect(err).NotTo(HaveOccurred()) Expect(string(bodyBytes)).To(Equal(svcName)) }) It("session manager should be installed", func() { // Use custom SSM plugin as the public version is not compatible to Alpine Linux. err := client.BashExec("chmod +x ./session-manager-plugin") Expect(err).NotTo(HaveOccurred()) err = client.BashExec("mv ./session-manager-plugin /bin/session-manager-plugin") Expect(err).NotTo(HaveOccurred()) }) It("svc exec should be able to modify the content of the website", func() { _, err := cli.SvcExec(&client.SvcExecRequest{ Name: svcName, AppName: appName, TaskID: taskID1, Command: fmt.Sprintf(`/bin/sh -c "echo '%s' > /usr/share/nginx/html/index.html"`, newContent), EnvName: envName, }) Expect(err).NotTo(HaveOccurred()) _, err = cli.SvcExec(&client.SvcExecRequest{ Name: svcName, AppName: appName, TaskID: taskID2, Command: fmt.Sprintf(`/bin/sh -c "echo '%s' > /usr/share/nginx/html/index.html"`, newContent), EnvName: envName, }) Expect(err).NotTo(HaveOccurred()) }) It("website content should be modified", func() { svc, err := cli.SvcShow(&client.SvcShowRequest{ AppName: appName, Name: svcName, }) Expect(err).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(1)) route := svc.Routes[0] for i := 0; i < 5; i++ { var resp *http.Response var fetchErr error Eventually(func() (int, error) { resp, fetchErr = http.Get(route.URL) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) // Our deployed service should return a body with the new content // as the value. bodyBytes, err := io.ReadAll(resp.Body) Expect(err).NotTo(HaveOccurred()) Expect(strings.TrimSpace(string(bodyBytes))).To(Equal(newContent)) time.Sleep(3 * time.Second) } }) // It("svc logs should include exec logs", func() { // var validTaskExecLogsCount int // for i := 0; i < 10; i++ { // var svcLogs []client.SvcLogsOutput // var svcLogsErr error // Eventually(func() ([]client.SvcLogsOutput, error) { // svcLogs, svcLogsErr = cli.SvcLogs(&client.SvcLogsRequest{ // AppName: appName, // Name: svcName, // EnvName: envName, // Since: "1m", // }) // return svcLogs, svcLogsErr // }, "60s", "10s").ShouldNot(BeEmpty()) // var prevExecLogStreamName string // for _, logLine := range svcLogs { // Expect(logLine.Message).NotTo(Equal("")) // Expect(logLine.LogStreamName).NotTo(Equal("")) // Expect(logLine.Timestamp).NotTo(Equal(0)) // Expect(logLine.IngestionTime).NotTo(Equal(0)) // if strings.Contains(logLine.LogStreamName, "ecs-execute-command") && // logLine.LogStreamName != prevExecLogStreamName { // validTaskExecLogsCount++ // prevExecLogStreamName = logLine.LogStreamName // } // } // if validTaskExecLogsCount == 2 { // break // } // validTaskExecLogsCount = 0 // time.Sleep(5 * time.Second) // } // Expect(validTaskExecLogsCount).To(Equal(2)) // }) }) Context("when running a one-off task", Ordered, func() { var ( taskRunErr error ) BeforeAll(func() { _, taskRunErr = cli.TaskRun(&client.TaskRunInput{ GroupName: groupName, Dockerfile: "./DockerfileTask", AppName: appName, Env: envName, }) }) It("should succeed", func() { Expect(taskRunErr).NotTo(HaveOccurred()) }) It("task exec should work", func() { var resp string var err error Eventually(func() (string, error) { resp, err = cli.TaskExec(&client.TaskExecRequest{ Name: groupName, AppName: appName, Command: "ls", EnvName: envName, }) return resp, err }, "120s", "20s").Should(ContainSubstring("hello")) }) }) })
297
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package import_certs import ( "fmt" "os" "testing" "time" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var cli *client.CLI var appName string var importedCert string func TestAppWithDomain(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Import Certificates Suite") } var _ = BeforeSuite(func() { arn, ok := os.LookupEnv("IMPORTED_CERT_ARN") Expect(ok).Should(Equal(true)) importedCert = arn copilotCLI, err := client.NewCLI() Expect(err).NotTo(HaveOccurred()) cli = copilotCLI appName = fmt.Sprintf("e2e-import-certs-%d", time.Now().Unix()) }) var _ = AfterSuite(func() { _, err := cli.AppDelete() Expect(err).NotTo(HaveOccurred()) })
40
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package import_certs import ( "net/http" "strings" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/aws/copilot-cli/e2e/internal/client" ) var _ = Describe("Import Certificates", func() { Context("when creating a new app", Ordered, func() { var appInitErr error BeforeAll(func() { _, appInitErr = cli.AppInit(&client.AppInitRequest{ AppName: appName, }) }) It("app init succeeds", func() { Expect(appInitErr).NotTo(HaveOccurred()) }) It("app init creates a copilot directory", func() { Expect("./copilot").Should(BeADirectory()) }) It("app ls includes new application", func() { Eventually(cli.AppList, "30s", "5s").Should(ContainSubstring(appName)) }) }) Context("when adding new environment", Ordered, func() { var ( err error ) BeforeAll(func() { _, err = cli.EnvInit(&client.EnvInitRequest{ AppName: appName, EnvName: "test", Profile: "test", CertificateImport: importedCert, }) }) It("env init should succeed", func() { Expect(err).NotTo(HaveOccurred()) }) }) Context("when deploying the environments", Ordered, func() { var envDeployErr error BeforeAll(func() { _, envDeployErr = cli.EnvDeploy(&client.EnvDeployRequest{ AppName: appName, Name: "test", }) }) It("env deploy should succeed", func() { Expect(envDeployErr).NotTo(HaveOccurred()) }) }) Context("when initializing Load Balanced Web Services", func() { var svcInitErr error It("svc init should succeed for creating the frontend service", func() { _, svcInitErr = cli.SvcInit(&client.SvcInitRequest{ Name: "frontend", SvcType: "Load Balanced Web Service", Dockerfile: "./src/Dockerfile", SvcPort: "80", }) Expect(svcInitErr).NotTo(HaveOccurred()) }) }) Context("when deploying a Load Balanced Web Service", func() { It("deployment should succeed", func() { _, err := cli.SvcDeploy(&client.SvcDeployInput{ Name: "frontend", EnvName: "test", ImageTag: "frontend", }) Expect(err).NotTo(HaveOccurred()) }) It("svc show should contain the expected domain and the request should succeed", func() { // Check frontend service svc, err := cli.SvcShow(&client.SvcShowRequest{ Name: "frontend", AppName: appName, }) Expect(err).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(1)) wantedURLs := map[string]string{ "test": "https://frontend.import-certs.copilot-e2e-tests.ecs.aws.dev", } for _, route := range svc.Routes { // Validate route has the expected HTTPS endpoint. Expect(route.URL).To(Equal(wantedURLs[route.Environment])) // Make sure the response is OK. var resp *http.Response var fetchErr error Eventually(func() (int, error) { resp, fetchErr = http.Get(route.URL) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) // HTTP should route to HTTPS. Eventually(func() (int, error) { resp, fetchErr = http.Get(strings.Replace(route.URL, "https", "http", 1)) return resp.StatusCode, fetchErr }, "60s", "1s").Should(Equal(200)) } }) }) })
126
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package init_test import ( "fmt" "testing" "time" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var cli *client.CLI var appName string var envName string /** The Init Suite runs through the copilot init workflow for a brand new application. It creates a single environment, deploys a service to it, and then tears it down. */ func TestInit(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Init Suite") } var _ = BeforeSuite(func() { ecsCli, err := client.NewCLI() cli = ecsCli Expect(err).NotTo(HaveOccurred()) appName = fmt.Sprintf("e2e-init-%d", time.Now().Unix()) envName = "test" }) var _ = AfterSuite(func() { _, err := cli.SvcDelete("front-end") Expect(err).NotTo(HaveOccurred()) _, err = cli.JobDelete("mailer") Expect(err).NotTo(HaveOccurred()) _, err = cli.EnvDelete("test") Expect(err).NotTo(HaveOccurred()) _, err = cli.AppDelete() Expect(err).NotTo(HaveOccurred()) })
51
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package init_test import ( "fmt" "net/http" "strings" "github.com/aws/copilot-cli/e2e/internal/client" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("init flow", Ordered, func() { var ( svcName string jobName string initErr error jobInitErr error ) BeforeAll(func() { svcName = "front-end" _, initErr = cli.Init(&client.InitRequest{ AppName: appName, WorkloadName: svcName, ImageTag: "gallopinggurdey", Dockerfile: "./front-end/Dockerfile", WorkloadType: "Load Balanced Web Service", Deploy: true, SvcPort: "80", }) jobName = "mailer" _, jobInitErr = cli.Init(&client.InitRequest{ AppName: appName, WorkloadName: jobName, ImageTag: "thepostalservice", Dockerfile: "./mailer/Dockerfile", WorkloadType: "Scheduled Job", Deploy: true, Schedule: "@every 5m", }) }) Context("creating a brand new app, svc, job, and deploying to a test environment", func() { It("init does not return an error", func() { Expect(initErr).NotTo(HaveOccurred()) }) It("init with job does not return an error", func() { Expect(jobInitErr).NotTo(HaveOccurred()) }) }) Context("svc ls", Ordered, func() { var ( svcList *client.SvcListOutput svcListError error ) BeforeAll(func() { svcList, svcListError = cli.SvcList(appName) }) It("should not return an error", func() { Expect(svcListError).NotTo(HaveOccurred()) }) It("should return one service", func() { Expect(len(svcList.Services)).To(Equal(1)) Expect(svcList.Services[0].Name).To(Equal(svcName)) Expect(svcList.Services[0].AppName).To(Equal(appName)) }) }) Context("job ls", Ordered, func() { var ( jobList *client.JobListOutput jobListErr error ) BeforeAll(func() { jobList, jobListErr = cli.JobList(appName) }) It("should not return a job list error", func() { Expect(jobListErr).NotTo(HaveOccurred()) }) It("should return one job", func() { Expect(len(jobList.Jobs)).To(Equal(1)) Expect(jobList.Jobs[0].Name).To(Equal(jobName)) Expect(jobList.Jobs[0].AppName).To(Equal(appName)) }) }) Context("svc show", Ordered, func() { var ( svc *client.SvcShowOutput svcShowErr error ) BeforeAll(func() { svc, svcShowErr = cli.SvcShow(&client.SvcShowRequest{ AppName: appName, Name: svcName, }) }) It("should not return an error", func() { Expect(svcShowErr).NotTo(HaveOccurred()) }) It("should return the correct configuration", func() { Expect(svc.SvcName).To(Equal(svcName)) Expect(svc.AppName).To(Equal(appName)) }) It("should return a valid route", func() { Expect(len(svc.Routes)).To(Equal(1)) Expect(svc.Routes[0].Environment).To(Equal("test")) Eventually(func() (int, error) { resp, fetchErr := http.Get(svc.Routes[0].URL) return resp.StatusCode, fetchErr }, "30s", "1s").Should(Equal(200)) }) It("should return a valid service discovery namespace", func() { Expect(len(svc.ServiceDiscoveries)).To(Equal(1)) Expect(svc.ServiceDiscoveries[0].Environment).To(Equal([]string{"test"})) Expect(svc.ServiceDiscoveries[0].Endpoint).To(Equal(fmt.Sprintf("%s.%s.%s.local:80", svcName, envName, appName))) }) It("should return the correct environment variables", func() { Expect(len(svc.Variables)).To(Equal(5)) expectedVars := map[string]string{ "COPILOT_APPLICATION_NAME": appName, "COPILOT_ENVIRONMENT_NAME": "test", "COPILOT_LB_DNS": strings.TrimPrefix(svc.Routes[0].URL, "http://"), "COPILOT_SERVICE_NAME": svcName, "COPILOT_SERVICE_DISCOVERY_ENDPOINT": fmt.Sprintf("%s.%s.local", envName, appName), } for _, variable := range svc.Variables { Expect(variable.Value).To(Equal(expectedVars[variable.Name])) } }) }) Context("svc logs", func() { It("should return valid log lines", func() { var svcLogs []client.SvcLogsOutput var svcLogsErr error Eventually(func() ([]client.SvcLogsOutput, error) { svcLogs, svcLogsErr = cli.SvcLogs(&client.SvcLogsRequest{ AppName: appName, Name: svcName, EnvName: "test", Since: "1h", }) return svcLogs, svcLogsErr }, "60s", "10s").ShouldNot(BeEmpty()) for _, logLine := range svcLogs { Expect(logLine.Message).NotTo(Equal("")) Expect(logLine.LogStreamName).NotTo(Equal("")) Expect(logLine.Timestamp).NotTo(Equal(0)) Expect(logLine.IngestionTime).NotTo(Equal(0)) } }) }) Context("force a new svc deploy", Ordered, func() { var err error BeforeAll(func() { _, err = cli.SvcDeploy(&client.SvcDeployInput{ Name: svcName, EnvName: "test", Force: true, ImageTag: "gallopinggurdey", }) }) It("should not return an error", func() { Expect(err).NotTo(HaveOccurred()) }) It("should return a valid route", func() { svc, svcShowErr := cli.SvcShow(&client.SvcShowRequest{ AppName: appName, Name: svcName, }) Expect(svcShowErr).NotTo(HaveOccurred()) Expect(len(svc.Routes)).To(Equal(1)) Expect(svc.Routes[0].Environment).To(Equal("test")) Eventually(func() (int, error) { resp, fetchErr := http.Get(svc.Routes[0].URL) return resp.StatusCode, fetchErr }, "30s", "1s").Should(Equal(200)) }) }) })
204
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package client import ( "bytes" "encoding/json" "fmt" "strconv" "strings" cmd "github.com/aws/copilot-cli/e2e/internal/command" ) // IAM policy ARNs. const ( codeCommitPowerUserPolicyARN = "arn:aws:iam::aws:policy/AWSCodeCommitPowerUser" ) // AWS is a wrapper around aws commands. type AWS struct{} // VPCStackOutput is the output for VPC stack. type VPCStackOutput struct { OutputKey string OutputValue string ExportName string } // dbClusterSnapshot represents part of the response to `aws rds describe-db-cluster-snapshots` type dbClusterSnapshot struct { Identifier string `json:"DBClusterSnapshotIdentifier"` Cluster string `json:"DBClusterIdentifier"` } // NewAWS returns a wrapper around AWS commands. func NewAWS() *AWS { return &AWS{} } /*CreateStack runs: aws cloudformation create-stack --stack-name $name --template-body $templatePath */ func (a *AWS) CreateStack(name, templatePath string) error { command := strings.Join([]string{ "cloudformation", "create-stack", "--stack-name", name, "--template-body", templatePath, }, " ") return a.exec(command) } /*WaitStackCreateComplete runs: aws cloudformation wait stack-create-complete --stack-name $name */ func (a *AWS) WaitStackCreateComplete(name string) error { command := strings.Join([]string{ "cloudformation", "wait", "stack-create-complete", "--stack-name", name, }, " ") return a.exec(command) } // CreateCodeCommitRepo creates a repository with AWS CodeCommit and returns // the HTTP git clone url. func (a *AWS) CreateCodeCommitRepo(name string) (cloneURL string, err error) { out := new(bytes.Buffer) args := strings.Join([]string{ "codecommit", "create-repository", "--repository-name", name, }, " ") if err := a.exec(args, cmd.Stdout(out)); err != nil { return "", fmt.Errorf("create commit repository %s cmd: %v", name, err) } data := struct { RepositoryMetadata struct { CloneURLHTTP string `json:"cloneUrlHttp"` } `json:"repositoryMetadata"` }{} if err := json.Unmarshal(out.Bytes(), &data); err != nil { return "", fmt.Errorf("unmarshal json response from create commit repository: %v", err) } return data.RepositoryMetadata.CloneURLHTTP, nil } // DeleteCodeCommitRepo delete a CodeCommit repository. func (a *AWS) DeleteCodeCommitRepo(name string) error { args := strings.Join([]string{ "codecommit", "delete-repository", "--repository-name", name, }, " ") if err := a.exec(args); err != nil { return fmt.Errorf("delete repository %s: %v", name, err) } return nil } // IAMServiceCreds represents service-specific IAM credentials. type IAMServiceCreds struct { UserName string `json:"ServiceUserName"` // Git username. Password string `json:"ServicePassword"` // Git password. CredentialID string `json:"ServiceSpecificCredentialId"` // ID for the creds in order to delete them. } // CreateCodeCommitIAMUser creates an IAM user that can push and pull from codecommit. // Returns the credentials needed to interact with codecommit. func (a *AWS) CreateCodeCommitIAMUser(userName string) (*IAMServiceCreds, error) { if err := a.createIAMUser("/copilot/e2etests/", userName); err != nil { return nil, err } if err := a.attachUserPolicy(userName, codeCommitPowerUserPolicyARN); err != nil { return nil, err } return a.createCodeCommitCreds(userName) } // DeleteCodeCommitIAMUser deletes an IAM user that can access codecommit. func (a *AWS) DeleteCodeCommitIAMUser(userName, credentialID string) error { if err := a.deleteServiceSpecificCreds(userName, credentialID); err != nil { return err } if err := a.detachUserPolicy(userName, codeCommitPowerUserPolicyARN); err != nil { return err } return a.deleteIAMUser(userName) } func (a *AWS) createIAMUser(path, userName string) error { args := strings.Join([]string{ "iam", "create-user", "--path", path, "--user-name", userName, }, " ") if err := a.exec(args); err != nil { return fmt.Errorf("create IAM user under path %s and name %s: %v", path, userName, err) } return nil } func (a *AWS) attachUserPolicy(userName, policyARN string) error { args := strings.Join([]string{ "iam", "attach-user-policy", "--user-name", userName, "--policy-arn", policyARN, }, " ") if err := a.exec(args); err != nil { return fmt.Errorf("attach policy arn %s to user %s: %v", policyARN, userName, err) } return nil } func (a *AWS) createCodeCommitCreds(userName string) (*IAMServiceCreds, error) { out := new(bytes.Buffer) args := strings.Join([]string{ "iam", "create-service-specific-credential", "--user-name", userName, "--service-name", "codecommit.amazonaws.com", }, " ") if err := a.exec(args, cmd.Stdout(out)); err != nil { return nil, fmt.Errorf("create commit credentials for user %s: %v", userName, err) } data := struct { Creds IAMServiceCreds `json:"ServiceSpecificCredential"` }{} if err := json.Unmarshal(out.Bytes(), &data); err != nil { return nil, fmt.Errorf("unmarshal credentials for codecommit: %v", err) } return &data.Creds, nil } func (a *AWS) deleteServiceSpecificCreds(userName, credentialID string) error { args := strings.Join([]string{ "iam", "delete-service-specific-credential", "--user-name", userName, "--service-specific-credential-id", credentialID, }, " ") if err := a.exec(args); err != nil { return fmt.Errorf("delete service specific creds %s for user %s: %v", credentialID, userName, err) } return nil } func (a *AWS) detachUserPolicy(userName, policyARN string) error { args := strings.Join([]string{ "iam", "detach-user-policy", "--user-name", userName, "--policy-arn", policyARN, }, " ") if err := a.exec(args); err != nil { return fmt.Errorf("detach user policy %s for user %s: %v", policyARN, userName, err) } return nil } func (a *AWS) deleteIAMUser(userName string) error { args := strings.Join([]string{ "iam", "delete-user", "--user-name", userName, }, " ") if err := a.exec(args); err != nil { return fmt.Errorf("delete iam user %s: %v", userName, err) } return nil } /*VPCStackOutput runs: aws cloudformation describe-stacks --stack-name $name | jq -r .Stacks[0].Outputs */ func (a *AWS) VPCStackOutput(name string) ([]VPCStackOutput, error) { command := strings.Join([]string{ "cloudformation", "describe-stacks", "--stack-name", name, "|", "jq", "-r", ".Stacks[0].Outputs", }, " ") var b bytes.Buffer err := a.exec(command, cmd.Stdout(&b)) if err != nil { return nil, err } var outputs []VPCStackOutput err = json.Unmarshal(b.Bytes(), &outputs) if err != nil { return nil, err } return outputs, nil } /*DeleteStack runs: aws cloudformation delete-stack --stack-name $name */ func (a *AWS) DeleteStack(name string) error { command := strings.Join([]string{ "cloudformation", "delete-stack", "--stack-name", name, }, " ") return a.exec(command) } /*WaitStackDeleteComplete runs: aws cloudformation wait stack-delete-complete --stack-name $name */ func (a *AWS) WaitStackDeleteComplete(name string) error { command := strings.Join([]string{ "cloudformation", "wait", "stack-delete-complete", "--stack-name", name, }, " ") return a.exec(command) } /*CreateECRRepo runs: aws ecr create-repository --repository-name $name | jq -r .repository.repositoryUri */ func (a *AWS) CreateECRRepo(name string) (string, error) { command := strings.Join([]string{ "ecr", "create-repository", "--repository-name", name, "|", "jq", "-r", ".repository.repositoryUri", }, " ") var b bytes.Buffer err := a.exec(command, cmd.Stdout(&b)) if err != nil { return "", err } return strings.TrimSpace(b.String()), nil } /*ECRLoginPassword runs: aws ecr get-login-password */ func (a *AWS) ECRLoginPassword() (string, error) { command := strings.Join([]string{ "ecr", "get-login-password", }, " ") var b bytes.Buffer err := a.exec(command, cmd.Stdout(&b)) if err != nil { return "", err } return strings.TrimSpace(b.String()), nil } /*DeleteECRRepo runs: aws ecr delete-repository --repository-name $name --force */ func (a *AWS) DeleteECRRepo(name string) error { command := strings.Join([]string{ "ecr", "delete-repository", "--repository-name", name, "--force", }, " ") return a.exec(command) } func (a *AWS) exec(command string, opts ...cmd.Option) error { return BashExec(fmt.Sprintf("aws %s", command), opts...) } /*GetFileSystemSize runs: aws efs describe-file-systems | jq -r '.FileSystems[0].SizeInBytes.Value', which returns the size in bytes of the first filesystem returned by the call. */ func (a *AWS) GetFileSystemSize() (int, error) { command := strings.Join([]string{ "efs", "describe-file-systems", "|", "jq", "-r", "'.FileSystems[0].SizeInBytes.Value'", }, " ") var b bytes.Buffer err := a.exec(command, cmd.Stdout(&b)) if err != nil { return 0, err } return strconv.Atoi(strings.TrimSpace(b.String())) } // DeleteAllDBClusterSnapshots removes all "manual" RDS cluster snapshots to avoid running into snapshot limits. func (a *AWS) DeleteAllDBClusterSnapshots() error { command := strings.Join([]string{ "rds", "describe-db-cluster-snapshots", }, " ") var b bytes.Buffer err := a.exec(command, cmd.Stdout(&b)) if err != nil { return err } var snapshotResponse struct { Snapshots []dbClusterSnapshot `json:"DBClusterSnapshots"` } if err = json.Unmarshal(b.Bytes(), &snapshotResponse); err != nil { return err } for _, s := range snapshotResponse.Snapshots { deleteCmd := strings.Join([]string{ "rds", "delete-db-cluster-snapshot", "--db-cluster-snapshot-identifier", s.Identifier, }, " ") var err = a.exec(deleteCmd) if err != nil { return err } } return nil } type environmentFile struct { Value string `json:"value"` Type string `json:"type"` } type containerDefinition struct { Name string `json:"name"` EnvironmentFiles []environmentFile `json:"environmentFiles"` } // GetEnvFilesFromTaskDefinition describes the given task definition, then returns a map of all // existing environment files where the keys are container names and the values are S3 locations. func (a *AWS) GetEnvFilesFromTaskDefinition(taskDefinitionName string) (map[string]string, error) { command := strings.Join([]string{ "ecs", "describe-task-definition", "--task-definition", taskDefinitionName, }, " ") var b bytes.Buffer err := a.exec(command, cmd.Stdout(&b)) if err != nil { return nil, err } var containerDefinitions struct { TaskDefinition struct { ContainerDefinitions []containerDefinition `json:"containerDefinitions"` } `json:"taskDefinition"` } if err = json.Unmarshal(b.Bytes(), &containerDefinitions); err != nil { return nil, err } envFiles := make(map[string]string) for _, container := range containerDefinitions.TaskDefinition.ContainerDefinitions { if len(container.EnvironmentFiles) > 0 { envFiles[container.Name] = container.EnvironmentFiles[0].Value } } return envFiles, nil }
430
copilot-cli
aws
Go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package client import ( cmd "github.com/aws/copilot-cli/e2e/internal/command" ) // BashExec execute bash commands. func BashExec(command string, opts ...cmd.Option) error { args := []string{"-c", command} err := cmd.Run("bash", args, opts...) if err != nil { return err } return nil }
19