I'm deploying some kubernetes object with a client of type dynamic.Interface during the creation of these object, kubernetes return this information.
I0530 17:31:13.728423 8992 request.go:665] Waited for 1.144205975s due to client-side throttling, not priority and fairness, request: GET:https://xx.xx.xx.xx:6443/apis/batch/v1beta1
I0530 17:31:23.729687 8992 request.go:665] Waited for 6.377372125s due to client-side throttling, not priority and fairness, request: GET:https://xx.xx.xx.xx:6443/apis/snapshot.storage.k8s.io/v1beta1
There are useful but the package display them without asking me the permission and I want to controll that. Is there a way to delete them, and get a string or en error, or at least increase the log level to display. I instantiate the dynamic client like this:
config, err := buildConfigFromFlags(context, kubeconfig)
if err != nil {
return nil, fmt.Errorf("Cannot create the config to communicate with kuberntes, %s", err)
}
dclient, err := dynamic.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("Cannot login into kubernetes (DClient): %s", err)
}
Thanks
Related
While trying to run the msgraph-sdk-go training code from here: https://github.com/microsoftgraph/msgraph-training-go, I'm getting InvalidAuthenticationTokenmsg: Access token is empty while executing the Graph API calls.
I configured a Microsoft developer account with instant sandbox for trial purpose.
I created an app registration as mentioned in the tutorial here and granted required permissions for the app.
The code is able to get the AppToken, but for calls to get Users, it fails with the above error. Am I missing something here?
I tried below code from the example for msgraph-training
func (g *GraphHelper) InitializeGraphForAppAuth() error {
clientId := os.Getenv("CLIENT_ID")
tenantId := os.Getenv("TENANT_ID")
clientSecret := os.Getenv("CLIENT_SECRET")
credential, err := azidentity.NewClientSecretCredential(tenantId, clientId, clientSecret, nil)
if err != nil {
return err
}
g.clientSecretCredential = credential
// Create an auth provider using the credential
authProvider, err := auth.NewAzureIdentityAuthenticationProviderWithScopes(g.clientSecretCredential, []string{
"https://graph.microsoft.com/.default",
})
if err != nil {
return err
}
// Create a request adapter using the auth provider
adapter, err := msgraphsdk.NewGraphRequestAdapter(authProvider)
if err != nil {
return err
}
// Create a Graph client using request adapter
client := msgraphsdk.NewGraphServiceClient(adapter)
g.appClient = client
return nil
}
// This part works, and I get the AppToken with required scope, once decoded.
func (g *GraphHelper) GetAppToken() (*string, error) {
token, err := g.clientSecretCredential.GetToken(context.Background(), policy.TokenRequestOptions{
Scopes: []string{
"https://graph.microsoft.com/.default",
},
})
if err != nil {
return nil, err
}
fmt.Println("expires on : ", token.ExpiresOn)
return &token.Token, nil
}
// The GetUsers function errors out
func (g *GraphHelper) GetUsers() (models.UserCollectionResponseable, error) {
var topValue int32 = 25
query := users.UsersRequestBuilderGetQueryParameters{
// Only request specific properties
Select: []string{"displayName", "id", "mail"},
// Get at most 25 results
Top: &topValue,
// Sort by display name
Orderby: []string{"displayName"},
}
resp, err := g.appClient.Users().
Get(context.Background(),
&users.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: &query,
})
if err != nil {
fmt.Println("Users.Get got Error", err.Error(), resp)
printOdataError(err)
}
resp, err = g.appClient.Users().
Get(context.Background(),
nil)
if err != nil {
fmt.Println("Users.Get got Error with nil", err.Error(), resp)
}
return resp, err
}
I have added the User.Read.All permission in the app as mentioned in the tutorial.
Instead of getting the list of users, I'm getting below error:
Users.Get got Error error status code received from the API <nil>
error: error status code received from the API
code: InvalidAuthenticationTokenmsg: Access token is empty.Users.Get got Error with nil error status code received from the API <nil>
As you are using client Credential Flow ,you can verify your permission in azure portal , if you have User.Read.All delegated permission , Removes the delegated ones and add the corresponding application ones and don't forget to click on grant administrator consent after that. It should then work.
Hope this helps
Thanks.
Okay, so the fix that did work for me after trial and error was a version mismatch in the example and the actual application I was trying out.
The version of the beta msgraph application I was using was v0.49, whereas the msgraphsdk tutorial was using v0.48. The go mod command picked up the latest v0.49 initially I guess, I updated the go.mod file to use v0.48 after looking at the go.mod file from msgraph-training repository and things started working.
Hope this helps someone else later on.
I'd like to connect from Go to the running instance of the Memgraph database. I'm using Docker and I've installed the Memgraph Platform. What exactly do I need to do?
The procedure for connecting fro Go to Memgraph is rather simple. For this you need to use Bolt protocol. Here are the needed steps:
First, create a new directory for your app, /MyApp, and position yourself in it. Next, create a program.go file with the following code:
package main
import (
"fmt"
"github.com/neo4j/neo4j-go-driver/v4/neo4j"
)
func main() {
dbUri := "bolt://localhost:7687"
driver, err := neo4j.NewDriver(dbUri, neo4j.BasicAuth("username", "password", ""))
if err != nil {
panic(err)
}
// Handle driver lifetime based on your application lifetime requirements driver's lifetime is usually
// bound by the application lifetime, which usually implies one driver instance per application
defer driver.Close()
item, err := insertItem(driver)
if err != nil {
panic(err)
}
fmt.Printf("%v\n", item.Message)
}
func insertItem(driver neo4j.Driver) (*Item, error) {
// Sessions are short-lived, cheap to create and NOT thread safe. Typically create one or more sessions
// per request in your web application. Make sure to call Close on the session when done.
// For multi-database support, set sessionConfig.DatabaseName to requested database
// Session config will default to write mode, if only reads are to be used configure session for
// read mode.
session := driver.NewSession(neo4j.SessionConfig{})
defer session.Close()
result, err := session.WriteTransaction(createItemFn)
if err != nil {
return nil, err
}
return result.(*Item), nil
}
func createItemFn(tx neo4j.Transaction) (interface{}, error) {
records, err := tx.Run(
"CREATE (a:Greeting) SET a.message = $message RETURN 'Node ' + id(a) + ': ' + a.message",
map[string]interface{}{"message": "Hello, World!"})
// In face of driver native errors, make sure to return them directly.
// Depending on the error, the driver may try to execute the function again.
if err != nil {
return nil, err
}
record, err := records.Single()
if err != nil {
return nil, err
}
// You can also retrieve values by name, with e.g. `id, found := record.Get("n.id")`
return &Item{
Message: record.Values[0].(string),
}, nil
}
type Item struct {
Message string
}
Now, create a go.mod file using the go mod init example.com/hello command.
I've mentioned the Bolt driver earlier. You need to add it with go get github.com/neo4j/neo4j-go-driver/v4#v4.3.1. You can run your program with go run .\program.go.
The complete documentation is located at Memgraph site.
when I was using go111, I had traces of all my Datastore calls (similar to image below). But as soon as I upgraded to go115 and started using cloud.google.com/go/datastore, I lost this information completely. I tried to set up telemetry by adding in my main:
projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
exporter, err := texporter.NewExporter(texporter.WithProjectID(projectID))
if err != nil {
log.Fatalf(bgCtx, "texporter.NewExporter of '%v': %v", projectID, err)
}
tp := sdktrace.NewTracerProvider(sdktrace.WithBatcher(exporter))
defer tp.ForceFlush(bgCtx)
otel.SetTracerProvider(tp)
But this didn't work. Am I missing anything to tell the datastore library to export those calls?
Thank you!
I finally found https://github.com/GoogleCloudPlatform/golang-samples/blob/master/trace/trace_quickstart/main.go
and realized I was missing the following:
trace.RegisterExporter(exporter)
This solved my problem. Then I also added the following on localhost
trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})
To make sure all requests are traced:
httpHandler := &ochttp.Handler{
// Use the Google Cloud propagation format.
Propagation: &propagation.HTTPFormat{},
}
if err := http.ListenAndServe(":"+port, httpHandler); err != nil {
I'm new to smart contract developing, and trying to make it work for handling assets. My assets are called GOcerts.
I have used the token UTXO smart contract as a basis to start learning, and added changes and functions depending on my needs.
I have added an aditional function called ClaimGO(), which is supposed to delete the asset and create and store two new assets in the ledger. But function DeleteState and putState do not seem to be storing anything on the ledger, because when I query the ledger after calling the function, is like if nothing had changed the ledger state.
The implementation of the ClaimGO function is as follows:
//ClaimGO claims an amount X of GOcert Y. This function is implemented following the UTXO model
func (s *SmartContract) ClaimGO(ctx contractapi.TransactionContextInterface, goCertInputKey string, amount int) ([]GOCERT, error) {
//1. Get ID of submitting client identity
clientID, err := ctx.GetClientIdentity().GetID()
if err != nil {
return nil, fmt.Errorf("failed to get client id: %v", err)
}
//2. Validate GOcert input
goCertInputCompositeKey, err := ctx.GetStub().CreateCompositeKey("goCert", []string{clientID, goCertInputKey})
if err != nil {
return nil, fmt.Errorf("failed to create composite key: %v", err)
}
goCertInput := GOCERT{}
//2.1 Validate that client has a GOcert matching the input key
goCertAsBytes, err := ctx.GetStub().GetState(goCertInputCompositeKey)
if err != nil {
return nil, fmt.Errorf("failed to read goCertInputCompositeKey %s from world state: %v", goCertInputCompositeKey, err)
}
errr := json.Unmarshal(goCertAsBytes, &goCertInput)
if errr != nil {
return nil, fmt.Errorf("goCertInput %s not found for client %s: %v\n, gocertInput: %#v\n gocerAsbytes: %v", goCertInputKey, clientID, errr, goCertInput, goCertAsBytes)
}
txID := ctx.GetStub().GetTxID()
pbKey := goCertInput.ProdBatchKey
expDate := goCertInput.ExpirationDate
//erase previous GOcert
err = ctx.GetStub().DelState(goCertInputCompositeKey)
if err != nil {
return nil, err
}
log.Printf("goCertInput deleted: %+v", goCertInput)
var goCertOutputs []GOCERT
//goCertOutput1 is the GO with the cancelled amount
goCertOutput1 := GOCERT{}
goCertOutput1.Amount = amount
goCertOutput1.ExpirationDate = expDate
goCertOutput1.Owner = clientID
goCertOutput1.ProdBatchKey = pbKey
goCertOutput1.State = "Cancelled"
goCertOutput1.Key = fmt.Sprintf("%s.%d", txID, 0)
goCertOutputs = append(goCertOutputs, goCertOutput1)
goCertAsBytes, _ := json.Marshal(goCertOutput1)
goCertOutputCompositeKey, err := ctx.GetStub().CreateCompositeKey("goCert", []string{goCertOutput1.Owner, goCertOutput1.Key})
err = ctx.GetStub().PutState(goCertOutputCompositeKey, goCertAsBytes)
if err != nil {
return nil, err
}
log.Printf("goCertOutput created: %+v", goCertOutput1)
//goCertOutput 2 is the GO with the remaining amount that has not been claimed yet
goCertOutput2 := GOCERT{}
goCertOutput2.Amount = goCertInput.Amount - amount
goCertOutput2.ExpirationDate = expDate
goCertOutput2.Owner = clientID
goCertOutput2.ProdBatchKey = pbKey
goCertOutput2.State = "Issued"
goCertOutput2.Key = fmt.Sprintf("%s.%d", txID, 1)
goCertOutputs = append(goCertOutputs, goCertOutput2)
goCertAsBytes2, _ := json.Marshal(goCertOutput2)
goCertOutputCompositeKey2, err := ctx.GetStub().CreateCompositeKey("goCert", []string{goCertOutput2.Owner, goCertOutput2.Key})
err = ctx.GetStub().PutState(goCertOutputCompositeKey2, goCertAsBytes2)
if err != nil {
return nil, err
}
log.Printf("goCertOutput created: %+v", goCertOutput2)
return goCertOutputs, nil
}
I'm trying the smart contract with the Hyperledger Fabric test-network. Using the logspout tool, I can see that the two log messages are displayed, so I know that the code is being executed correctly. The issue is that, eve though it executes with no errors, the functions DeleteState and PutState are not actually changing anything on the ledger.
Any help on what could be the issue will be highly appreciated.
Thank you very much.
The ledger doesn't actually get updated until after a transaction is endorsed, submitted to the orderer, committed in a block, and distributed to peers so they can update their local ledger state. It is still possible for the transaction to fail to commit successfully after sending to the orderer if some endorsement requirements have not been met.
If you are using the peer chaincode query command to do your invocation, the transaction is not sent to the orderer so no ledger update occurs. If you are using the peer chaincode invoke command then the endorsed transaction will be sent to the orderer and update the ledger.
However, query commands following an invoke command will not see the ledger update caused by the invoke until the peer they execute on has received the committed block from the orderer and updated its local ledger state. To have the peer chaincode invoke command wait for transactions to be committed in peer ledgers before exiting, use the --waitForEvent command-line flag.
Run peer chaincode invoke --help for details of the available command-line flags.
I'm trying to figure out a way to get the error cause while JSON decoding http.Response.Body
if err := json.NewDecoder(resp.Body).Decode(&lResp); err != nil {
// Get the cause of err
}
The type of err (and errors.Cause(err) using either github.com/pkg/errors or github.com/friendsofgo/errors) is *errors.errorString.
So what I'm able to do right now is the exact opposite of checking for the error type, namely:
if strings.HasSuffix(cause.Error(), "(Client.Timeout exceeded while reading body)") {
//...
}
I can try to use ioutil.ReadAll() and then I'll get *http.httpError as an error when the timeout occurs.
The primary reason is that I don't want to get the partially read JSON structure in the error - only the cause of the error and with current way, it's being done (the error returned) I get:
main.ListingResponse.DataSources: struct CustomType{ /* partially read JSON struct ... */ }.net/http: request canceled (Client.Timeout exceeded while reading body)
Ok, so I ended up reading the response body into into a []byte and then unmarshalling it with json.Unmarshal()
bb, err := ioutil.ReadAll(resp.Body)
if err != nil {
var netError net.Error
if errors.As(err, &netError) {
log.Printf("netError %v", netError)
// handle net.Error...
return nil, netError
}
// handle general errors...
return nil, netError
}
var lResp LResponse
if err := json.Unmarshal(bb, &lResp); err != nil {
return nil, errors.Wrap(err, "failed to unmarshal LResponse")
}
I'm still looking for a solution to use json.NewDecoder(resp.Body).Decode(&str) to avoid copying whole body into memory.
If anyone knows the way to do it, please add your answer.