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.
Related
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!
Objective
Add a command to dropbox's CLI tool to get the shared link for the given path (file or folder).
The changes are here: github fork.
Background
The dropbox-go-sdk has a function that takes a path, and returns a new shared link, or returns an error containing the existing shared link.
I don't know how to use the error to extract the existing shared link.
Code
on github, and snippet here:
dbx := sharing.New(config)
res, err := dbx.CreateSharedLinkWithSettings(arg)
if err != nil {
switch e := err.(type) {
case sharing.CreateSharedLinkWithSettingsAPIError:
fmt.Printf("%v", e.EndpointError)
default:
return err
}
}
This prints the following:
&{{shared_link_already_exists} <nil> <nil>}found unknown shared link typeError: shared_link_already_exists/...
tracing:
CreateSharedLinkWithSettings --> CreateSharedLinkWithSettingsAPIError --> CreateSharedLinkWithSettingsError --> SharedLinkAlreadyExistsMetadata --> IsSharedLinkMetadata
IsSharedLinkMetadata contains the Url that I'm looking for.
More Info
The API docs point to CreateSharedLinkWithSettings, which should pass back the information in the error including the existing Url.
I struggle to understand how to deal with the error and extract the url from it.
The dbxcli has some code doing a similar operation, but again, not sure how it's working enough to apply it to the code I'm working on. Is it a Struct? Map? I don't know what this thing is called. There's some weird magic err.(type) stuff happening in the code. How do I access the data?
dbx := sharing.New(config)
res, err := dbx.CreateSharedLinkWithSettings(arg)
if err != nil {
switch e := err.(type) {
case sharing.CreateSharedLinkWithSettingsAPIError:
fmt.Printf("%v", e.EndpointError)
// type cast to the specific error and access the field you want.
settingsError := err.(sharing.CreateSharedLinkWithSettingsAPIError)
fmt.Println(settingsError.EndpointError.SharedLinkAlreadyExists.Metadata.Url)
default:
return err
}
}
The question was answered in the comments by #jimb. The answer is you access the fields like any other golang data structure - nothing special.
The errors I got when trying to access the fields were because the fields were not there.
The problem with the code was dependency issues. The code depends on an older version of the go-sdk and I referenced the latest version.
This question serves as a good explanation for how real golang programmers handle errors in their code with examples. I wasn't able to find this online, so I won't close the question.
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
I need to get the currently logged in user(s) on the local Windows machine, using Golang. I'm not looking for the user currently running the application, which can be got from the built-in function user.Current().
I can call query user from cmd and this gives me the list (string manipulation required, but that is not a problem) of users I need.
The code I have tried is:
out, err := exec.Command("query", "user")
if err != nil {
panic(err)
}
// ...do something with 'out'
This produces the error panic: exit status 1. The same occurs if I do:
out, err := exec.Command("cmd", "/C", "query", "user")
...
As usually with such kind of questions,
the solution is to proceed like this:
Research (using MSDN and other sources) on how to achieve the
stated goal using Win32 API.
Use the built-in syscall package (or, if available/desirable,
helper 3rd-party packages) to make those calls from Go.
The first step can be this
which yields the solution
which basically is "use WTS".
The way to go is to
Connect to the WTS subsystem¹.
Enumerate the currently active sessions.
Query each one for the information about the
identity of the user associated with it.
The second step is trickier but basically you'd need to research
how others do that.
See this
and this
and this for a few examples.
You might also look at files named _windows*.go in
the Go source of the syscall package.
¹ Note that even on a single-user machine, everything
related to seat/session management comes through WTS
(however castrated it is depending on a particular flavor of Windows). This is true since at least XP/W2k3.
package main
import (
"fmt"
"os/exec"
)
func main() {
out, err := exec.Command("cmd", "/C", "query user").Output()
if err != nil {
fmt.Println("Error: ", err)
}
fmt.Println(string(out))
}
I'm currently in the process of still learning go but I recently got to a point where in one of my tests I wanted to create a quick backup application that will reference a config file and switch what "plugin" to use for the backup. So what I got to at this point is to create (as example, written from my head and syntax may be incorrect):
type BackupStorage interface{
Put (d []byte) (n int, err Error)
Get (l []byte) (d []byte, err Error)
}
At this point I would assume I should use reflection to switch on the type and return the specific backup function, although that does not seem right.
The second alternative I came to was to still use my BackupStorage interface and create "plugin" packages to dictate which import will be used, but how do I switch that then based on a config file variable. And I'd like to do this because some stuff on one machine may backup only to s3 where as others may backup to both s3 and google drive etc.
With the basic example above what I have in mind is this:
Implement 2 BackupStorage "plugins" (Google Drive / S3) with the flexibility to add more at any time, but have my code be generic enough to execute on whatever storage backend is selected in config files.
As I mentioned above I'm still learning and any explanations would be appreciated or examples on how to accomplish this. I don't mind the "your doing it wrong" as long as there is a proper explanation on why it's wrong and how to do it right.
You have the right idea to start, implement everything you need via an interface, and then you can plug in any concrete backup "plugin" that implements that interface.
Once you can run your backup via an interface, you can simply assign an instance of the backend you want based on whatever conditions you set.
var storage Backupper
type Backupper interface {
Backup()
}
type GDrive struct {
config string
}
func (g *GDrive) Backup() {
fmt.Println("Doing backup to Google Drive")
}
func main() {
storage = &GDrive{}
storage.Backup()
}
Or with multiple options: http://play.golang.org/p/RlmXjf55Yh