Configuring OTLP exporter through environment variables - go

Currently I am trying to configure my OTLP exporter using environment variables. This is supposed to be possible as per the official docs.
In particular, I want to focus on the OTEL_EXPORTER_OTLP_ENDPOINT one, which is allowed for the OTLPtrace exporter. According to the comments in their code, the environment variable takes precedence over any other value set in the code.
I wrote a very basic HTTP application in Go, which is instrumented with OpenTelemetry. When I specify the exporter endpoint explicitly in the code like:
exporter, err := otlptrace.New(
context.Background(),
otlptracegrpc.NewClient(
otlptracegrpc.WithInsecure(),
otlptracegrpc.WithEndpoint("My Endpoint"),
),
)
The instrumentation works just fine like that. However if I remove the otlptracegrpc.NewClient configuration from the code, it does not pick up the values set in the environment, which are set like:
OTEL_EXPORTER_OTLP_ENDPOINT="my endpoint"
So when I run this application in my debugger I can see that the exporter client has an empty value as the endpoint, yet I can pick them up within my program as:
exporterEndpoint := os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT")
This I interpret as the variables being actually present at the time the code is being executed, which was my main fear.
Why is this? Am I missing something here? Should I populate the environment variable differently (I see there are "options" for the environment variable in the official docs, but no examples)?

From what I see from your code, you're trying to contact the OTLP exporter through a gRPC call. If you see, in their documentation they wrote this in line 71:
This option has no effect if WithGRPCConn is used.
This means that you can completely avoid passing this variable at all to the otlptracegrpc.NewClient function. I instantiate a gRPC client with this code and it works:
func newOtlpExporter(ctx context.Context) (trace.SpanExporter, error) {
client := otlptracegrpc.NewClient(otlptracegrpc.WithInsecure(), otlptracegrpc.WithDialOption(grpc.WithBlock()))
exporter, err := otlptrace.New(ctx, client)
if err != nil {
panic(err)
}
return exporter, err
}
Back to your question, you're right with your guess but only if you're sending metrics, traces, and so on through HTTPS calls.
Let me know if this helps to solve the issue or if anything else is needed!
Edit 1
I overlooked this. The comment you linked in the question is taken from the wrong file. The correct line is this: https://github.com/open-telemetry/opentelemetry-go/blob/48a05478e238698e02b4025ac95a11ecd6bcc5ad/exporters/otlp/otlptrace/otlptracegrpc/options.go#L71
As you can see, the comment is clearer and you have only two options:
Provide your own endpoint address
Use the default one which is localhost:0.0.0.0:4317
Let me know if helps!

Related

Writing new key to configuration file with Viper

First easy project with Go here.
Based on user input, I need to add new keys to my existing configuration file.
I manage to read it correctly with Viper and use it throughout the application, but WriteConfig doesn't seem to work.
Here's a snippet:
oldConfig := viper.AllSettings()
fmt.Printf("All settings #1 %+v\n\n", oldConfig)
viper.Set("setting1", chosenSetting1)
viper.Set("setting2", chosenSetting2)
newConfig := viper.AllSettings()
fmt.Printf("All settings #2 %+v\n\n", newConfig)
err := viper.WriteConfig()
if err != nil {
log.Fatalln(err)
}
newConfig includes new settings as expected, but WriteConfig doesn't apply changes to the config file.
I've read in Viper repo that writing functions are quite controversial and a bit buggy in terms of treating existing or non-existing files, but I expect them to work in simple cases like this.
I also tried other functions (i.e. SafeWriteConfig) with no success.
I'm using Go 1.16.2 and Viper 1.7.1.
What am I doing wrong?
viper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'
you first need to specify the path to the config file
or try this method bellow
viper.SafeWriteConfigAs("/path/to/my/.config") // will error since it has already been written
try WriteConfigAs(filename) ; you will be able to name the file to write to.
If there is no error in WriteConfig, it's probably that the changes are not written to the file you expect.
viper.ConfigFileUsed() should return the path used by default.

google cloud functions default environment variables not set

Are there any conditions to the default environment variables being set on google cloud function?
I have the following code:
func init() {
projectID := os.Getenv("GCP_PROJECT")
log.Printf("projectID: %s\n", projectID)
functionName := os.Getenv("FUNCTION_NAME")
log.Printf("functoinName: %s\n", functionName)
region := os.Getenv("FUNCTION_REGION")
log.Printf("region: %s\n", region)
}
and the values are empty.
Even if I do:
func GameUpdate(ctx context.Context, e FirestoreEvent) error {
functionName := os.Getenv("FUNCTION_NAME")
log.Printf("functoinName: %s\n", functionName)
}
They are still empty.
According to documentation, I would expect them to be set and available. But they are not :|
EDIT:
I am using go 1.13 as runtime and as Armatorix mentioned, these env variables are not available in that runtime...
Why I needed them was to write a wrapper for cloud.google.com/go/logging to be able to tag the severity of the logs.
I ended up prepending my stdout logs with [INFO]/[ERROR], and creating a tag from it \[([A-Z]+)\].*. Bonus is that I don't have to do a network call in my function to ship the logs.
Still disappointing that these environment variables are not available.
So I've read the same documentation.
Here you've got the info that it works like this with go1.11 (And it works, I tested it out).
BUT for go1.13 these are not set. You can still do it manually.
Also I've checked which envs are set on 1.13 version.
From os.Envrion()
PATH=/layers/google.go.build/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
FUNCTION_SIGNATURE_TYPE=http
DEBIAN_FRONTEND=noninteractive
HOME=/root
K_REVISION=9
FUNCTION_TARGET=HelloWorld
PORT=8080
GOROOT=/usr/local/go/
CGO_ENABLED=1
PWD=/srv
K_SERVICE=function-1
So the env that you probably want to use is K_SERVICE
I have created a Feature Request on your behalf, in order for Cloud Functions Engineering team to implement the automatic set of these Environment Variables to the newer Runtime Versions, such as Node.js 10 and Go1.13.
You may "star" the issue so that it gets visibility and also include yourself in the "CC" section, in order to receive further updates posted on this thread.
I hope this helps.
I created a library for that very purpose:
github.com/ncruces/go-gcf/logging
But you're right, on the Go 1.13 runtime, those environment variables are missing. On the migration guide they suggest setting them when you deploy.
Later I found that the recommended way of doing this is to use structured logging.
// Structured logging can be used to set severity levels.
// See https://cloud.google.com/logging/docs/structured-logging.
fmt.Println(`{"message": "This has ERROR severity", "severity": "error"}`)
So now, I'm in the process of "deprecating" my library, and creating a new one, with a simpler approach:
github.com/ncruces/go-gcp/glog
This is simple enough that a library isn't really required, but it helps to correctly JSON escape message.

Using client-go to `kubectl apply` against the Kubernetes API directly with multiple types in a single YAML file

I'm using https://github.com/kubernetes/client-go and all works well.
I have a manifest (YAML) for the official Kubernetes Dashboard: https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-beta4/aio/deploy/recommended.yaml
I want to mimic kubectl apply of this manifest in Go code, using client-go.
I understand that I need to do some (un)marshalling of the YAML bytes into the correct API types defined in package: https://github.com/kubernetes/api
I have successfully Createed single API types to my cluster, but how do I do this for a manifest that contains a list of types that are not the same? Is there a resource kind: List* that supports these different types?
My current workaround is to split the YAML file using csplit with --- as the delimiter
csplit /path/to/recommended.yaml /---/ '{*}' --prefix='dashboard.' --suffix-format='%03d.yaml'
Next, I loop over the new (14) parts that were created, read their bytes, switch on the type of the object returned by the UniversalDeserializer's decoder and call the correct API methods using my k8s clientset.
I would like to do this to programmatically to make updates to any new versions of the dashboard into my cluster. I will also need to do this for the Metrics Server and many other resources. The alternative (maybe simpler) method is to ship my code with kubectl installed to the container image and directly call kubectl apply -f -; but that means I also need to write the kube config to disk or maybe pass it inline so that kubectl can use it.
I found this issue to be helpful: https://github.com/kubernetes/client-go/issues/193
The decoder lives here: https://github.com/kubernetes/apimachinery/tree/master/pkg/runtime/serializer
It's exposed in client-go here: https://github.com/kubernetes/client-go/blob/master/kubernetes/scheme/register.go#L69
I've also taken a look at the RunConvert method that is used by kubectl: https://github.com/kubernetes/kubernetes/blob/master/pkg/kubectl/cmd/convert/convert.go#L139 and assume that I can provide my own genericclioptions.IOStreams to get the output?
It looks like RunConvert is on a deprecation path
I've also looked at other questions tagged [client-go] but most use old examples or use a YAML file with a single kind defined, and the API has changed since.
Edit: Because I need to do this for more than one cluster and am creating clusters programmatically (AWS EKS API + CloudFormation/eksctl), I would like to minimize the overhead of creating ServiceAccounts across many cluster contexts, across many AWS accounts. Ideally, the only authentication step involved in creating my clientset is using aws-iam-authenticator to get a token using cluster data (name, region, CA cert, etc). There hasn't been a release of aws-iam-authenticator for a while, but the contents of master allow for the use of a third-party role cross-account role and external ID to be passed. IMO, this is cleaner than using a ServiceAccount (and IRSA) because there are other AWS services the application (the backend API which creates and applies add-ons to these clusters) needs to interact with.
Edit: I have recently found https://github.com/ericchiang/k8s. It's definitely simpler to use than client-go, at a high-level, but doesn't support this behavior.
It sounds like you've figured out how to deserialize YAML files into Kubernetes runtime.Objects, but the problem is dynamically deploying a runtime.Object without writing special code for each Kind.
kubectl achieves this by interacting with the REST API directly. Specifically, via resource.Helper.
In my code, I have something like:
import (
meta "k8s.io/apimachinery/pkg/api/meta"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/apimachinery/pkg/runtime"
)
func createObject(kubeClientset kubernetes.Interface, restConfig rest.Config, obj runtime.Object) error {
// Create a REST mapper that tracks information about the available resources in the cluster.
groupResources, err := restmapper.GetAPIGroupResources(kubeClientset.Discovery())
if err != nil {
return err
}
rm := restmapper.NewDiscoveryRESTMapper(groupResources)
// Get some metadata needed to make the REST request.
gvk := obj.GetObjectKind().GroupVersionKind()
gk := schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}
mapping, err := rm.RESTMapping(gk, gvk.Version)
if err != nil {
return err
}
name, err := meta.NewAccessor().Name(obj)
if err != nil {
return err
}
// Create a client specifically for creating the object.
restClient, err := newRestClient(restConfig, mapping.GroupVersionKind.GroupVersion())
if err != nil {
return err
}
// Use the REST helper to create the object in the "default" namespace.
restHelper := resource.NewHelper(restClient, mapping)
return restHelper.Create("default", false, obj, &metav1.CreateOptions{})
}
func newRestClient(restConfig rest.Config, gv schema.GroupVersion) (rest.Interface, error) {
restConfig.ContentConfig = resource.UnstructuredPlusDefaultContentConfig()
restConfig.GroupVersion = &gv
if len(gv.Group) == 0 {
restConfig.APIPath = "/api"
} else {
restConfig.APIPath = "/apis"
}
return rest.RESTClientFor(&restConfig)
}
I was able to get this working in one of my projects. I had to use much of the source code from kubectl's apply command to get it working correctly.
https://github.com/billiford/go-clouddriver/blob/master/pkg/kubernetes/client.go#L63

ask LookupTXT function in golang

How do I change the IP address of the DNS server?
In situation, I set Google DNS server in Windows Network Settins.
And I use LookupTXT function in Golang for getting DNS txt request.
But LookupTXT parameter is just the query string.
Any help or pointers would be highly appreciated. Thanks!
This is not straigtforward to do using golang at this point. You can however use a third party DNS package that allows configuring the resolver. First install the package:
go get github.com/bogdanovich/dns_resolver
Here is an example using it and the google resolvers 8.8.8.8 and 8.8.4.4:
package main
import (
"log"
"github.com/bogdanovich/dns_resolver"
)
func main() {
resolver := dns_resolver.New([]string{"8.8.8.8", "8.8.4.4"})
// In case of i/o timeout
resolver.RetryTimes = 5
ip, err := resolver.LookupHost("google.com")
if err != nil {
log.Fatal(err.Error())
}
log.Println(ip)
// Output [216.58.192.46]
}
Source
There is an open issue in golang here, so hopefully it becomes easier to do it with the builtin net package: https://github.com/golang/go/issues/12503. It could just be a documentation problem, as it is possible now, I just can't find an example.
EDIT: actually that package only supports lookupHost: https://github.com/bogdanovich/dns_resolver/blob/master/dns_resolver.go#L51-L79
So a PR would be required to add a TXT resolver.
2nd Edit: I made a PR with txt lookup here. That project hasn't been touched in years though so it may never get accepted.

Use package file to write to Cloud Storage?

Golang provides the file package to access Cloud Storage.
The package's Create function requires the io.WriteCloser interface. However, I have not found a single sample or documentation showing how to actually save a file to Cloud Storage.
Can anybody help? Is there a higher level implementation of io.WriteCloser that would allow us to store files in Cloud Storage? Any sample code?
We've obviously tried to Google it ourselves but found nothing and now hope for the community to help.
It's perhaps true than the behavior is not well defined in the documentation.
If you check the code: https://code.google.com/p/appengine-go/source/browse/appengine/file/write.go#133
In each call to Write the data is sent to the cloud (line 139). So you don't need to save. (You should close the file when you're done, through.)
Anyway, I'm confused with your wording: "The package's Create function requires the io.WriteCloser interface." That's not true. The package's Create functions returns a io.WriteCloser, that is, a thingy you can write to and close.
yourFile, _, err := Create(ctx, "filename", nil)
// Check err != nil here.
defer func() {
err := yourFile.Close()
// Check err != nil here.
}()
yourFile.Write([]byte("This will be sent to the file immediately."))
fmt.Fprintln(yourFile, "This too.")
io.Copy(yourFile, someReader)
This is how interfaces work in Go. They just provide you with a set of methods you can call, hiding the actual implementation from you; and, when you just depend on a particular interface instead of a particular implementation, you can combine in multiple ways, as fmt.Fprintln and io.Copy do.

Resources