-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathomslog.go
138 lines (122 loc) · 3.86 KB
/
omslog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
// Required parameters
var (
// Update customerId to your Operations Management Suite workspace ID
omscustomerID = "xxxxxxxx-xxx-xxx-xxx-xxxxxxxxxxxx"
// For sharedKey, use either the primary or the secondary Connected Sources client authentication key
omssharedKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
// HTTP timeout for posting events to OMS Log Analytics
omsPostTimeout = 5 * time.Second
)
const (
method = "POST"
contentType = "application/json"
resource = "/api/logs"
)
type omsMessage struct {
SourceSystem string `json:"sourceSystem,omitempty"`
ContainerID string `json:"containerId"`
ContainerName string `json:"containerName"`
TimeGenerated string `json:"timeGenerated"`
LogEntry string `json:"logEntry"`
}
type OmsLogClient interface {
PostData(*[]byte, string) error
}
// OmsLogClient posts messages to OMS
type omslogclient struct {
customerID string
sharedKey string
url string
httpPostTimeout time.Duration
client *http.Client
}
func init() {
http.DefaultClient.Timeout = time.Second * 30
}
// New instance of the OmsLogClient
func NewOmsLogClient(customerID string, sharedKey string, postTimeout time.Duration ) OmsLogClient {
return &omslogclient{
customerID: customerID,
sharedKey: sharedKey,
url: "https://" + customerID + ".ods.opinsights.azure.com" + resource + "?api-version=2016-04-01",
httpPostTimeout: postTimeout,
client: &http.Client{ Timeout: postTimeout },
}
}
// PostData posts message to OMS
func (c *omslogclient) PostData(msg *[]byte, logType string) error {
// Headers
contentLength := len(*msg)
rfc1123date := time.Now().UTC().Format(time.RFC1123)
rfc1123date = strings.Replace(rfc1123date, "UTC", "GMT", 1)
//Signature
signature, err := c.buildSignature(rfc1123date, contentLength, method, contentType, resource)
if err != nil {
return err
}
// Create request
req, err := http.NewRequest("POST", c.url, bytes.NewBuffer(*msg))
if err != nil {
return err
}
req.Header.Set("Authorization", signature)
req.Header.Set("Log-Type", logType)
req.Header["x-ms-date"] = []string{rfc1123date}
req.Header.Set("Content-Type", "application/json")
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 || resp.StatusCode < 200 {
return fmt.Errorf("Post Error. HTTP response code:%d message:%s", resp.StatusCode, resp.Status)
}
fmt.Printf("API POST success! HTTP response code: %d", resp.StatusCode)
return nil
}
func (c *omslogclient) buildSignature(date string, contentLength int, method string, contentType string, resource string) (string, error) {
xHeaders := "x-ms-date:" + date
stringToHash := method + "\n" + strconv.Itoa(contentLength) + "\n" + contentType + "\n" + xHeaders + "\n" + resource
bytesToHash := []byte(stringToHash)
keyBytes, err := base64.StdEncoding.DecodeString(c.sharedKey)
if err != nil {
return "", err
}
hasher := hmac.New(sha256.New, keyBytes)
hasher.Write(bytesToHash)
encodedHash := base64.StdEncoding.EncodeToString(hasher.Sum(nil))
authorization := fmt.Sprintf("SharedKey %s:%s", c.customerID, encodedHash)
return authorization, err
}
func main() {
omsclient := NewOmsLogClient(omscustomerID, omssharedKey, omsPostTimeout)
// An example JSON data message to post
msg := &omsMessage{
SourceSystem: "MySystemName",
ContainerID: "1234567890",
ContainerName: "mycontainer",
TimeGenerated: time.Now().Format(time.RFC3339),
LogEntry: "Golang API sample code log event",
}
buffer, err := json.Marshal(msg)
if err != nil {
fmt.Println("JSON convert error:", err)
}
postErr := omsclient.PostData(&buffer, "ContainerLog")
if postErr != nil {
fmt.Println("API POST error:", postErr)
}
}