yats.git

ref: 89777a764361663ff609027a4848f29a7134fe05

client/main.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/**
 * Yats - yats
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Paolo Lulli <kevwe.com>
 * @copyright Paolo Lulli 2024
 */
package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"os"
	"time"
	"yats/config"

	flag "github.com/spf13/pflag"
)

type YatsClient struct {
	config config.ClientConfiguration
}

func main() {
	var configPath string
	recordSeparator := ","
	rowSeparator := ";\n"

	if len(os.Args) == 1 {
		fmt.Printf("Usage: \n\n%s --help | -h\n", os.Args[0])
		os.Exit(1)
	}

	configPath = os.Getenv("HOME") + "/.yats-client.json"

	cfg := config.GetClientConfig(configPath)
	var yatsClient = YatsClient{config: cfg}

	generatePki := flag.BoolP("csr", "c", false, "create CSR")

	sourceOption := flag.StringP("source", "s", "", "source application")

	isShowPermsOption := flag.BoolP("show-permissions", "S", false, "show user permissions")

	fromOption := flag.Int64("from", 0, "from tstamp")
	toOption := flag.Int64("to", 0, "to tstamp")

	timestampOption := flag.Int64("timestamp", 0, "timeStamp")

	writeEvent := flag.StringP("write-event", "E", "", "write event with name")
	writeMetric := flag.StringP("write-metric", "M", "", "write metric with name")
	metricValue := flag.StringP("metric-value", "v", "", "metric value")
	writePosition := flag.StringP("write-position", "P", "", "write position name")

	listEvents := flag.BoolP("list-events", "e", false, "list events")
	listMetrics := flag.StringP("list-metrics", "m", "", "list metrics with name")
	listPositions := flag.StringP("list-positions", "p", "", "list positions with name")

	longitudeOption := flag.Float64P("longitude", "o", 0, "longitude")
	latitudeOption := flag.Float64P("latitude", "a", 0, "latitude")

	sinceSeconds := flag.BoolP("sec", "", false, "seconds ago")
	sinceMinutes := flag.BoolP("min", "", false, "minutes ago")
	sinceHours := flag.BoolP("hour", "", false, "hours ago")
	sinceDays := flag.BoolP("day", "", false, "days ago")
	sinceYears := flag.BoolP("year", "", false, "years ago")

	reformatOutput := flag.BoolP("format", "f", false, "format output")
	logOutput := flag.BoolP("value-only", "l", false, "log value only output")
	decodeBase64Output := flag.BoolP("base64-decode", "b", false, "decode base64 output")
	unpackJsonPayload := flag.BoolP("unpack-json", "u", false, "unpack base64/json output")

	flag.Parse()

	var fromTimestamp int64
	var toTimestamp int64

	if *fromOption != 0 {
		fromTimestamp = calculateCutDate(*fromOption, sinceSeconds, sinceMinutes, sinceHours, sinceDays, sinceYears)
	} else {
		fromTimestamp = 0
	}

	if *toOption != 0 {
		toTimestamp = calculateCutDate(*toOption, sinceSeconds, sinceMinutes, sinceHours, sinceDays, sinceYears)
	} else {
		toTimestamp = 0
	}

	if *isShowPermsOption {
		listResponse, err := yatsClient.PermissionsList()
		if err == nil {
			fmt.Printf("%s", listResponse)
		} else {
			fmt.Println(err)
		}
		os.Exit(0)
	}

	if *generatePki {
		yatsClient.CreateCsr()
		os.Exit(0)
	}

	if "" != *writeEvent {
		saveEventResponse, err := yatsClient.EventSave(*writeEvent, *timestampOption)
		if err == nil {
			fmt.Printf("%s", saveEventResponse)
		} else {
			fmt.Println(err)
		}
		os.Exit(0)
	}

	if "" != *writeMetric {
		listResponse, err := yatsClient.MetricSave(*writeMetric, *metricValue, *timestampOption)
		if err == nil {
			fmt.Printf("%s", listResponse)
		} else {
			fmt.Println(err)
		}
		os.Exit(0)
	}

	if "" != *writePosition {
		savePositionResponse, err := yatsClient.PositionSave(*writePosition, *latitudeOption, *longitudeOption, *timestampOption)
		if err == nil {
			fmt.Printf("%s", savePositionResponse)
		} else {
			fmt.Println(err)
		}
		os.Exit(0)
	}

	if *listEvents {
		listEvents := yatsClient.EventList(*sourceOption, fromTimestamp, toTimestamp)
		if *reformatOutput {
			dataJson, errDataPortion := getDataJson(listEvents)
			if errDataPortion {
				fmt.Printf("Could not parse data attribute: %v", errDataPortion)
				return
			}

			var eventListModel []EventModel
			err := json.Unmarshal(dataJson, &eventListModel)

			if err == nil {
				for _, event := range eventListModel {
					unixTimeUTC := time.Unix(event.Etime/1000, 0)
					unitTimeInRFC3339 := unixTimeUTC.Format(time.RFC3339)
					fmt.Printf("%s %s\n", unitTimeInRFC3339, event.Name)
				}
			} else {
				fmt.Println(err)
			}
		} else {
			fmt.Printf("%s", listEvents)
		}
		os.Exit(0)
	}

	if "" != *listMetrics {
		listResponse, err := yatsClient.MetricList(*sourceOption, *listMetrics, fromTimestamp, toTimestamp)

		if err == nil {
			if *reformatOutput {

				dataJson, errDataPortion := getDataJson(listResponse)
				if errDataPortion {
					fmt.Printf("Could not parse data attribute: %v", errDataPortion)
					return
				}

				var metricListModel []MetricModel
				err := json.Unmarshal(dataJson, &metricListModel)

				if err == nil {
					for _, metric := range metricListModel {
						fmt.Printf("%d %s=%s\n", metric.Mtime, metric.Name, metric.Value)
					}
				} else {
					fmt.Println(err)
				}
				os.Exit(0)
			}
			if *logOutput {
				dataJson, errDataPortion := getDataJson(listResponse)
				if errDataPortion {
					fmt.Printf("Could not parse data attribute: %v", errDataPortion)
					return
				}

				var metricListModel []MetricModel
				err := json.Unmarshal(dataJson, &metricListModel)

				if err == nil {
					for _, metric := range metricListModel {
						if *decodeBase64Output {
							decodedBytes, err := base64.StdEncoding.DecodeString(metric.Value)
							if err != nil {
								fmt.Println("Error decoding string:", err)
								return
							}
							fmt.Println(string(decodedBytes))
						} else {
							fmt.Printf("%s\n", metric.Value)
						}
					}
				} else {
					fmt.Println(err)
				}
				os.Exit(0)
			}

			if *unpackJsonPayload {
				dataJson, errDataPortion := getDataJson(listResponse)
				if errDataPortion {
					fmt.Printf("Could not parse data attribute: %v", errDataPortion)
					return
				}

				var metricListModel []MetricModel
				err := json.Unmarshal(dataJson, &metricListModel)

				if err == nil {
					metric := metricListModel[0]
					dataMap, errNoValue := loadBase64ValueAsMap(metric)
					if errNoValue {
						return
					}

					var keys []string
					for k := range dataMap {
						keys = append(keys, k)
					}

					for _, k := range keys {
						fmt.Printf("\"%v\"%s", k, recordSeparator)
					}
					fmt.Printf("%s", rowSeparator)
					for _, row := range metricListModel {
						rowMap, errNoValue := loadBase64ValueAsMap(row)
						if errNoValue {
							return
						}
						for _, k := range keys {
							fmt.Printf("\"%v\"%s", rowMap[k], recordSeparator)
						}
						fmt.Printf("%s", rowSeparator)
					}
				} else {
					fmt.Println(err)
				}
				os.Exit(0)
			}

			fmt.Printf("%s", listResponse)

		} else {
			fmt.Println(err)
		}
		os.Exit(0)
	}

	if "" != *listPositions {
		listResponse := yatsClient.PositionList(*sourceOption, fromTimestamp, toTimestamp)
		fmt.Printf("%s", listResponse)
		os.Exit(0)
	}
}

func loadBase64ValueAsMap(metric MetricModel) (map[string]any, bool) {
	decodedBytes, err := base64.StdEncoding.DecodeString(metric.Value)
	if err != nil {
		fmt.Println("Error decoding string:", err)
		return nil, true
	}

	decoded := string(decodedBytes)
	var dataMap map[string]any
	json.Unmarshal([]byte(decoded), &dataMap)
	return dataMap, false
}

func getDataJson(list string) ([]byte, bool) {
	var result map[string]interface{}
	json.Unmarshal([]byte(list), &result)
	innerData := result["data"]

	dataJson, er := json.Marshal(innerData)
	if er != nil {
		fmt.Printf("Parsing response: %v", er)
		return nil, true
	}
	return dataJson, false
}

func calculateCutDate(ts int64, sinceSeconds *bool, sinceMinutes *bool, sinceHours *bool, sinceDays *bool, sinceYears *bool) int64 {
	if 0 != ts {
		if *sinceSeconds {
			return time.Now().Unix() - ts
		}
		if *sinceMinutes {
			return time.Now().Unix() - ts*60
		}
		if *sinceHours {
			return time.Now().Unix() - ts*60*60
		}
		if *sinceDays {
			return time.Now().Unix() - ts*60*60*24
		}
		if *sinceYears {
			return time.Now().Unix() - ts*60*60*24*365
		}
	}
	return ts
}