|
| 1 | +// (c) Copyright IBM Corp. 2024 |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "encoding/json" |
| 8 | + "errors" |
| 9 | + "fmt" |
| 10 | + "io" |
| 11 | + "log" |
| 12 | + "net/http" |
| 13 | + "os" |
| 14 | + |
| 15 | + "github.com/Azure/azure-sdk-for-go/sdk/azcore" |
| 16 | + "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" |
| 17 | + "github.com/google/uuid" |
| 18 | + instana "github.com/instana/go-sensor" |
| 19 | + "github.com/instana/go-sensor/instrumentation/instacosmos" |
| 20 | +) |
| 21 | + |
| 22 | +// The following variables are database id and container name created in azure. |
| 23 | +// this values needs to be changed to if the database and container are created |
| 24 | +// with different names. |
| 25 | +const ( |
| 26 | + database = "trace-data" |
| 27 | + container = "spans" |
| 28 | +) |
| 29 | + |
| 30 | +// environment variables to be exported |
| 31 | +const ( |
| 32 | + CONNECTION_URL = "COSMOS_CONNECTION_URL" |
| 33 | + KEY = "COSMOS_KEY" |
| 34 | +) |
| 35 | + |
| 36 | +type SpanType string |
| 37 | + |
| 38 | +const ( |
| 39 | + EntrySpan SpanType = "entry" |
| 40 | + ExitSpan SpanType = "exit" |
| 41 | +) |
| 42 | + |
| 43 | +// Span is the item to be inserted in the azure container. |
| 44 | +type Span struct { |
| 45 | + ID string `json:"id"` |
| 46 | + SpanID string `json:"SpanID"` |
| 47 | + Type SpanType `json:"type"` |
| 48 | + Description string `json:"description"` |
| 49 | +} |
| 50 | + |
| 51 | +var ( |
| 52 | + collector instana.TracerLogger |
| 53 | +) |
| 54 | + |
| 55 | +var ( |
| 56 | + endpoint = "" |
| 57 | + key = "" |
| 58 | +) |
| 59 | + |
| 60 | +func init() { |
| 61 | + validateAzureCreds() |
| 62 | + collector = instana.InitCollector(&instana.Options{ |
| 63 | + Service: "sample-app-cosmos", |
| 64 | + }) |
| 65 | +} |
| 66 | + |
| 67 | +func main() { |
| 68 | + http.HandleFunc("/cosmos-test", instana.TracingHandlerFunc(collector, "/cosmos-test", handler)) |
| 69 | + log.Fatal(http.ListenAndServe("localhost:9990", nil)) |
| 70 | +} |
| 71 | + |
| 72 | +func handler(w http.ResponseWriter, r *http.Request) { |
| 73 | + |
| 74 | + erStr := r.URL.Query().Get("error") |
| 75 | + needError := erStr == "true" |
| 76 | + |
| 77 | + itemResponse, err := cosmosTest(r.Context(), needError) |
| 78 | + if err != nil { |
| 79 | + var responseErr *azcore.ResponseError |
| 80 | + errors.As(err, &responseErr) |
| 81 | + defer responseErr.RawResponse.Body.Close() |
| 82 | + errBytes, err := io.ReadAll(responseErr.RawResponse.Body) |
| 83 | + if err != nil { |
| 84 | + log.Fatal("Failed to read error body") |
| 85 | + } |
| 86 | + log.Println("Error:", string(errBytes)) |
| 87 | + sendErrResp(w, responseErr.StatusCode) |
| 88 | + } else { |
| 89 | + sendOkResp(w) |
| 90 | + log.Printf("Status %d. ActivityId %s. Consuming %v Request Units.\n", |
| 91 | + itemResponse.RawResponse.StatusCode, |
| 92 | + itemResponse.ActivityID, |
| 93 | + itemResponse.RequestCharge) |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +func sendErrResp(w http.ResponseWriter, statusCode int) { |
| 98 | + w.WriteHeader(statusCode) |
| 99 | + _, _ = w.Write([]byte(`{message:"something went wrong"}`)) |
| 100 | +} |
| 101 | + |
| 102 | +func sendOkResp(w http.ResponseWriter) { |
| 103 | + w.WriteHeader(http.StatusOK) |
| 104 | + _, _ = w.Write([]byte("{message:Status OK! Check terminal for full log!}")) |
| 105 | +} |
| 106 | + |
| 107 | +func cosmosTest(ctx context.Context, needError bool) (azcosmos.ItemResponse, error) { |
| 108 | + |
| 109 | + // Create a CosmosDB client |
| 110 | + client, err := getClient(collector) |
| 111 | + if err != nil { |
| 112 | + log.Fatal("Failed to create Azure Cosmos DB client: ", err) |
| 113 | + } |
| 114 | + |
| 115 | + // Create container client |
| 116 | + containerClient, err := client.NewContainer(database, container) |
| 117 | + if err != nil { |
| 118 | + log.Fatal("Failed to create a container client:", err) |
| 119 | + } |
| 120 | + |
| 121 | + id := uuid.New().String() |
| 122 | + partitionKey := fmt.Sprintf("span-%s", id) |
| 123 | + |
| 124 | + // Specifies the value of the partition key |
| 125 | + pk := containerClient.NewPartitionKeyString(partitionKey) |
| 126 | + |
| 127 | + if needError { |
| 128 | + partitionKey = "invalidPartitionKey" |
| 129 | + } |
| 130 | + |
| 131 | + span := Span{ |
| 132 | + ID: id, |
| 133 | + SpanID: partitionKey, |
| 134 | + Type: EntrySpan, |
| 135 | + Description: "sample span", |
| 136 | + } |
| 137 | + |
| 138 | + b, err := json.Marshal(span) |
| 139 | + if err != nil { |
| 140 | + log.Fatal("Failed to marshal span data:", err) |
| 141 | + } |
| 142 | + |
| 143 | + // setting item options upon creating ie. consistency level |
| 144 | + itemOptions := azcosmos.ItemOptions{ |
| 145 | + ConsistencyLevel: azcosmos.ConsistencyLevelSession.ToPtr(), |
| 146 | + } |
| 147 | + |
| 148 | + itemResponse, err := containerClient.CreateItem(ctx, pk, b, &itemOptions) |
| 149 | + return itemResponse, err |
| 150 | +} |
| 151 | + |
| 152 | +func getClient(sensor instana.TracerLogger) (instacosmos.Client, error) { |
| 153 | + cred, err := instacosmos.NewKeyCredential(key) |
| 154 | + if err != nil { |
| 155 | + return nil, err |
| 156 | + } |
| 157 | + |
| 158 | + client, err := instacosmos.NewClientWithKey(sensor, endpoint, cred, &azcosmos.ClientOptions{}) |
| 159 | + if err != nil { |
| 160 | + return nil, err |
| 161 | + } |
| 162 | + |
| 163 | + return client, nil |
| 164 | +} |
| 165 | + |
| 166 | +func validateAzureCreds() { |
| 167 | + endpoint, _ = os.LookupEnv(CONNECTION_URL) |
| 168 | + key, _ = os.LookupEnv(KEY) |
| 169 | + |
| 170 | + if endpoint == "" || key == "" { |
| 171 | + log.Fatal("Azure credentials are not provided") |
| 172 | + } |
| 173 | +} |
0 commit comments