Skip to content
This repository has been archived by the owner on Jul 31, 2023. It is now read-only.

Add resource package #878

Merged
merged 10 commits into from
Oct 29, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 158 additions & 0 deletions resource/resource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
// Copyright 2018, OpenCensus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package resource defines the resource type and provides helpers to derive them as well
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Explain what a resource type is rather than saying resource package contains the type.

// as the generic population through environment variables.
package resource

import (
"context"
"fmt"
"os"
"regexp"
"strconv"
"strings"
)

const (
envVarType = "OC_RESOURCE_TYPE"
envVarTags = "OC_RESOURCE_TAGS"
)

// Resource describes an entity about which data is exposed.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we be more specific than "data"?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe give some examples

type Resource struct {
Type string
Tags map[string]string
}

// EncodeTags encodes a tags to a string as provided via the OC_RESOURCE_TAGS environment variable.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

encodes a tags map?

func EncodeTags(tags map[string]string) (s string) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't have named return variables if name is not self documenting.

s/s string/string

i := 0
for k, v := range tags {
if i > 0 {
s += ","
}
s += k + "=" + strconv.Quote(v)
i++
}
return s
}

// We accept domain names and paths as tag keys. Values may be quoted or unquoted in general.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Document this restriction somewhere in the godoc.

// If a value contains whitespaces, =, or " characters, it must always be quoted.
var tagRegex = regexp.MustCompile(`\s*([a-zA-Z0-9-_./]+)=(?:(".*?")|([^\s="]+))\s*,`)

func DecodeTags(s string) (map[string]string, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add godoc.

m := map[string]string{}
// Ensure a trailing comma, which allows us to keep the regex simpler
s = strings.TrimRight(strings.TrimSpace(s), ",") + ","

for len(s) > 0 {
match := tagRegex.FindStringSubmatch(s)
if len(match) == 0 {
return nil, fmt.Errorf("invalid tag formatting, remainder: %s", s)
}
v := match[2]
if v == "" {
v = match[3]
} else {
var err error
if v, err = strconv.Unquote(v); err != nil {
return nil, fmt.Errorf("invalid tag formatting, remainder: %s, err: %s", s, err)
}
}
m[match[1]] = v

s = s[len(match[0]):]
}
return m, nil
}

// FromEnvVars loads resource information from the OC_TYPE and OC_RESOURCE_TAGS environment variables.
func FromEnvVars(context.Context) (*Resource, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can call this just FromEnv and dropping the var, similar to the standard library style: https://golang.org/pkg/os/#Setenv.

res := &Resource{
Type: strings.TrimSpace(os.Getenv(envVarType)),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if this env var is not set?

Copy link
Contributor Author

@fabxc fabxc Sep 24, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will be the empty string, i.e. equivalent to net setting Type. If it doesn't get populated later on, e.g. by the agent, exporters can decide how to handle this.

}
tags := strings.TrimSpace(os.Getenv(envVarTags))
if tags == "" {
return res, nil
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If EnvVarType is empty, wouldn't it make more sense to return a nil resource here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The type is not mandatory per our specs so I don't think we necessarily have to handle it specially here.
In general the empty resource is equivalent to the unset resource. Just that an empty struct requires less special handling by the caller, which seems preferable.

}
var err error
fabxc marked this conversation as resolved.
Show resolved Hide resolved
if res.Tags, err = DecodeTags(tags); err != nil {
return nil, err
}
return res, nil
}

// Merge resource information from b into a. In case of a collision, a takes precedence.
func Merge(a, b *Resource) *Resource {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this important to be public? People can call the Chained version.

if a == nil {
return b
}
if b == nil {
return a
}
res := &Resource{
Type: a.Type,
Tags: map[string]string{},
}
for k, v := range a.Tags {
res.Tags[k] = v
}
if res.Type == "" {
res.Type = b.Type
}
for k, v := range b.Tags {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you first added all the b tags and then the a tags then you wouldn't need to check for the existence of the key in the map before overwriting.

if _, ok := res.Tags[k]; !ok {
res.Tags[k] = v
}
}
return res
}

// Detector attempts to detect resource information.
// If the detector cannot find specific information, the respective Resource fields should
// be left empty but no error should be returned.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to imply its not valid to return nil, nil (saying that you should leave fields empty), though that seems like it would be the most natural way to return "this detector does not apply in the current environment".

// An error should only be returned if unexpected errors occur during lookup.
type Detector func(context.Context) (*Resource, error)

// NewDetectorFromResource returns a detector that will always return resource r.
func NewDetectorFromResource(r *Resource) Detector {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not necessary needed? as @rakyll always told me this is 1 line for users to write.

return func(context.Context) (*Resource, error) {
return r, nil
}
}

// ChainedDetector returns a Detector that calls all input detectors sequentially an
// merges each result with the previous one.
// It returns on the first error that a sub-detector encounters.
fabxc marked this conversation as resolved.
Show resolved Hide resolved
func ChainedDetector(detectors ...Detector) Detector {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe FromDetectors? I will let @rakyll propose a good name for this.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about MultiDetector a la io.MultiReader?

return func(ctx context.Context) (*Resource, error) {
fabxc marked this conversation as resolved.
Show resolved Hide resolved
return DetectAll(ctx, detectors...)
}
}

// Detectall calls all input detectors sequentially an merges each result with the previous one.
// It returns on the first error that a sub-detector encounters.
func DetectAll(ctx context.Context, detectors ...Detector) (*Resource, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does DetectAll need to be public?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd say so. Seems like a useful helper function that library users may inevitably rebuild for testing or similar.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ChainedDetector(d1, d2, ...)(ctx) does the same. why do we need two ways?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ChainedDetector is implemented using DetectAll (:

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keep the method just make it private detectAll().

var res *Resource
for _, d := range detectors {
r, err := d(ctx)
if err != nil {
return nil, err
}
res = Merge(res, r)
}
return res, nil
}
116 changes: 116 additions & 0 deletions resource/resource_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Copyright 2018, OpenCensus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package resource

import (
"reflect"
"testing"
)

func TestMerge(t *testing.T) {
cases := []struct {
a, b, expect *Resource
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/expect/want

}{
{
a: &Resource{
Type: "t1",
Tags: map[string]string{"a": "1", "b": "2"},
},
b: &Resource{
Type: "t2",
Tags: map[string]string{"a": "1", "b": "3", "c": "4"},
},
expect: &Resource{
Type: "t1",
Tags: map[string]string{"a": "1", "b": "2", "c": "4"},
},
},
{
a: nil,
b: &Resource{
Type: "t1",
Tags: map[string]string{"a": "1"},
},
expect: &Resource{
Type: "t1",
Tags: map[string]string{"a": "1"},
},
},
{
a: &Resource{
Type: "t1",
Tags: map[string]string{"a": "1"},
},
b: nil,
expect: &Resource{
Type: "t1",
Tags: map[string]string{"a": "1"},
},
},
}
for _, c := range cases {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use t.Run to create sub tests, so they can be individually run and output is more readable.

res := Merge(c.a, c.b)
if !reflect.DeepEqual(res, c.expect) {
t.Fatalf("unexpected result: want %+v, got %+v", c.expect, res)
}
}
}

func TestDecodeTags(t *testing.T) {
cases := []struct {
s string
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/s/encoded

expect map[string]string
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wantTags

fail bool
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wantFail

}{
{
s: `example.org/test-1="test ¥ \"" ,un=quøted, Abc=Def`,
expect: map[string]string{"example.org/test-1": "test ¥ \"", "un": "quøted", "Abc": "Def"},
}, {
s: `single=key`,
expect: map[string]string{"single": "key"},
},
{s: `invalid-char-ü=test`, fail: true},
{s: `missing="trailing-quote`, fail: true},
{s: `missing=leading-quote"`, fail: true},
{s: `extra=chars, a`, fail: true},
{s: `a, extra=chars`, fail: true},
{s: `a, extra=chars`, fail: true},
}
for i, c := range cases {
t.Logf("test %d: %s", i, c.s)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto, don't Log. Use t.Run.


res, err := DecodeTags(c.s)
if err != nil && !c.fail {
t.Fatalf("unexpected error: %s", err)
}
if c.fail && err == nil {
t.Fatalf("expected failure but got none, result: %v", res)
}
if !reflect.DeepEqual(res, c.expect) {
t.Fatalf("expected result %v, got %v", c.expect, res)
}
}
}

func TestEncodeTags(t *testing.T) {
s := EncodeTags(map[string]string{
"example.org/test-1": "test ¥ \"",
"un": "quøted",
"Abc": "Def",
})
if exp := `example.org/test-1="test ¥ \"",un="quøted",Abc="Def"`; s != exp {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have a more canonical pattern here:

got := EncodeTags(...)

if want  := `example.org/test-1="test ¥ \"",un="quøted",Abc="Def"`; got != want {
		t.Fatalf("got %q; want %q", got, want)
	}

t.Fatalf("expected %q, got %q", exp, s)
}
}
fabxc marked this conversation as resolved.
Show resolved Hide resolved