forked from snowplow/snowplow-tracking-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snowplowtrk.go
291 lines (257 loc) · 7.47 KB
/
snowplowtrk.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//
// Copyright (c) 2016-2022 Snowplow Analytics Ltd. All rights reserved.
//
// This program is licensed to you under the Apache License Version 2.0,
// and you may not use this file except in compliance with the Apache License Version 2.0.
// You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the Apache License Version 2.0 is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
//
package main
import (
"encoding/json"
"errors"
"net/http"
"os"
"strings"
"time"
storagememory "github.com/snowplow/snowplow-golang-tracker/v3/pkg/storage/memory"
gt "github.com/snowplow/snowplow-golang-tracker/v3/tracker"
"github.com/urfave/cli"
)
const (
appVersion = "0.7.0"
appName = "snowplowtrk"
appUsage = "Snowplow Analytics Tracking CLI"
appCopyright = "(c) 2016-2022 Snowplow Analytics, LTD"
)
type selfDescJSON struct {
Schema string `json:"schema"`
Data map[string]interface{} `json:"data"`
}
func main() {
app := cli.NewApp()
app.Name = appName
app.Usage = appUsage
app.Version = appVersion
app.Copyright = appCopyright
app.Compiled = time.Now()
app.Authors = []cli.Author{
{
Name: "Joshua Beemster",
Email: "[email protected]",
},
{
Name: "Ronny Yabar",
},
}
// Set CLI Flags
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "collector, c",
Usage: "Collector Domain (Required)",
},
cli.StringFlag{
Name: "appid, id",
Usage: "Application Id (Optional)",
Value: appName,
},
cli.StringFlag{
Name: "method, m",
Usage: "Method[POST|GET] (Optional)",
Value: "GET",
},
cli.StringFlag{
Name: "protocol, p",
Usage: "Protocol[http|https] (Optional)",
Value: "https",
},
cli.StringFlag{
Name: "sdjson, sdj",
Usage: "SelfDescribing JSON of the standard form { 'schema': 'iglu:xxx', 'data': { ... } }",
},
cli.StringFlag{
Name: "schema, s",
Usage: "Schema URI, of the form iglu:xxx",
},
cli.StringFlag{
Name: "json, j",
Usage: "Non-SelfDescribing JSON, of the form { ... }",
},
cli.StringFlag{
Name: "ipaddress, ip",
Usage: "Track a custom IP Address (Optional)",
Value: "",
},
cli.StringFlag{
Name: "contexts, ctx",
Usage: "Array of SelfDescribing JSON to add as context to the outbound event",
Value: "[]",
},
}
// Set CLI Action
app.Action = func(c *cli.Context) error {
collector := c.String("collector")
appid := c.String("appid")
method := c.String("method")
protocol := c.String("protocol")
sdjson := c.String("sdjson")
schema := c.String("schema")
jsonData := c.String("json")
ipAddress := c.String("ipaddress")
contexts := c.String("contexts")
// Check that collector domain exists
if collector == "" {
return cli.NewExitError("fatal: --collector needs to be specified", 1)
}
// Fetch the SelfDescribing JSON
sdj, err := getSdJSON(sdjson, schema, jsonData)
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
// Process the contexts array
contextArr, err := getContexts(contexts)
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
// Create channel to block for events
trackerChan := make(chan int, 1)
// Send the event
tracker := initTracker(collector, appid, method, protocol, ipAddress, trackerChan, nil)
statusCode := trackSelfDescribingEvent(tracker, trackerChan, sdj, contextArr)
// Parse return code
returnCode := parseStatusCode(statusCode)
if returnCode != 0 {
return cli.NewExitError("error: event failed to send, check your collector endpoint and try again", returnCode)
}
return nil
}
app.Run(os.Args)
}
// --- CLI
// getSdJSON takes the three applicable arguments
// and attempts to return a SelfDescribingJson.
func getSdJSON(sdjson string, schema string, jsonData string) (*gt.SelfDescribingJson, error) {
if sdjson == "" && schema == "" && jsonData == "" {
return nil, errors.New("fatal: --sdjson or --schema URI plus a --json needs to be specified")
} else if sdjson != "" {
// Process SelfDescribingJson String
res := selfDescJSON{}
d := json.NewDecoder(strings.NewReader(sdjson))
d.UseNumber()
err := d.Decode(&res)
if err != nil {
return nil, err
}
return gt.InitSelfDescribingJson(res.Schema, res.Data), nil
} else if schema != "" && jsonData == "" {
return nil, errors.New("fatal: --json needs to be specified")
} else if schema == "" && jsonData != "" {
return nil, errors.New("fatal: --schema URI needs to be specified")
} else {
// Process Schema and Json Strings
jsonDataMap, err := stringToMap(jsonData)
if err != nil {
return nil, err
}
return gt.InitSelfDescribingJson(schema, jsonDataMap), nil
}
}
// getContexts parses a JSON array string and attempts to convert it into
// an array of SelfDescribingJson objects to track.
func getContexts(contexts string) ([]gt.SelfDescribingJson, error) {
res := []selfDescJSON{}
d := json.NewDecoder(strings.NewReader(contexts))
d.UseNumber()
err := d.Decode(&res)
if err != nil {
return nil, err
}
sdjArr := make([]gt.SelfDescribingJson, len(res))
for i, context := range res {
sdj := gt.InitSelfDescribingJson(
context.Schema,
context.Data,
)
sdjArr[i] = *sdj
}
return sdjArr, nil
}
// --- Tracker
// initTracker creates a new Tracker ready for use
// by the application.
func initTracker(collector string, appid string, method string, protocol string, ipAddress string, trackerChan chan int, httpClient *http.Client) *gt.Tracker {
// Create callback function
callback := func(s []gt.CallbackResult, f []gt.CallbackResult) {
status := 0
if len(s) == 1 {
status = s[0].Status
} else if len(f) == 1 {
status = f[0].Status
}
trackerChan <- status
}
// Create Tracker
emitter := gt.InitEmitter(gt.RequireCollectorUri(collector),
gt.RequireStorage(storagememory.Init()),
gt.OptionCallback(callback),
gt.OptionRequestType(method),
gt.OptionProtocol(protocol),
gt.OptionHttpClient(httpClient),
)
subject := gt.InitSubject()
if ipAddress != "" {
subject.SetIpAddress(ipAddress)
}
tracker := gt.InitTracker(
gt.RequireEmitter(emitter),
gt.OptionSubject(subject),
gt.OptionAppId(appid),
)
return tracker
}
// trackSelfDescribingEvent will pass an event to
// the tracker for sending.
func trackSelfDescribingEvent(tracker *gt.Tracker, trackerChan chan int, sdj *gt.SelfDescribingJson, contexts []gt.SelfDescribingJson) int {
tracker.TrackSelfDescribingEvent(gt.SelfDescribingEvent{
Event: sdj,
Contexts: contexts,
})
returnCode := <-trackerChan
// Ensure that the event is removed
tracker.Emitter.Storage.DeleteAllEventRows()
return returnCode
}
// --- Utilities
// parseStatusCode gets the function return code
// based on the HTTP response of the event.
func parseStatusCode(statusCode int) int {
var returnCode int
result := statusCode / 100
switch result {
case 2, 3:
returnCode = 0
case 4:
returnCode = 4
case 5:
returnCode = 5
default:
returnCode = 1
}
return returnCode
}
// stringToMap attempts to convert a string (assumed JSON)
// to a map.
func stringToMap(str string) (map[string]interface{}, error) {
var jsonDataMap map[string]interface{}
d := json.NewDecoder(strings.NewReader(str))
d.UseNumber()
err := d.Decode(&jsonDataMap)
if err != nil {
return nil, err
}
return jsonDataMap, nil
}