/** * Yats - yats * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Paolo Lulli * @copyright Paolo Lulli 2024 */ package main import ( "encoding/base64" "encoding/json" "fmt" "os" "path/filepath" "yats/internal/client" "yats/internal/io" "yats/internal/model" "yats/internal/util" flag "github.com/spf13/pflag" ) // MaxPageSize Server returns pages of max 100 results var MaxPageSize = 100 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 := client.GetClientConfig(configPath) var yatsClient = client.YatsClient{Config: cfg} generatePki := flag.BoolP("pki-init", "", 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") midnightOfDay := flag.BoolP("date", "", false, "midnight of day at GMT") 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 = util.CalculateCutDate(*fromOption, sinceSeconds, sinceMinutes, sinceHours, sinceDays, sinceYears, midnightOfDay) } else { fromTimestamp = 0 } if *toOption != 0 { toTimestamp = util.CalculateCutDate(*toOption, sinceSeconds, sinceMinutes, sinceHours, sinceDays, sinceYears, midnightOfDay) } 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 { util.MakeDirIfItDoesNotExist(cfg.ClientCertDir) secretPin := io.ReadSecretPin("Insert PIN from email") csrFile := filepath.Join(cfg.ClientCertDir, cfg.ClientCn+".csr") csr, err := yatsClient.CreateCsr(csrFile) if err != nil { fmt.Println(err) os.Exit(1) } base64EncodedCsr := base64.StdEncoding.EncodeToString(csr) certRequest := client.CertificateRequest{ Csr: base64EncodedCsr, SecretPin: secretPin, ClientCn: cfg.ClientCn, } jsonResponse := yatsClient.PkiPostCsr(yatsClient.Config.PkiEndpoint, certRequest) var certificateResponse client.CertificateResponse json.Unmarshal(jsonResponse, &certificateResponse) certPem, err := base64.StdEncoding.DecodeString(certificateResponse.Base64Certificate) certificateFile := filepath.Join(cfg.ClientCertDir, cfg.ClientCn+".crt") os.WriteFile(certificateFile, certPem, 0644) fmt.Printf("Certificate written on: [%s]", certificateFile) 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) eventListModel, maxpage, _ := responseToEventArray(listEvents) var composedList []model.EventModel composedList = append(composedList, eventListModel...) for continueSearching(len(eventListModel), maxpage, toTimestamp) { listEvents = yatsClient.EventList(*sourceOption, maxpage/1000, toTimestamp) eventListModel, maxpage, _ = responseToEventArray(listEvents) composedList = append(composedList, eventListModel...) } if *reformatOutput { for _, event := range composedList { eventTime := util.FormattedUtcTimeInSec(event.Etime) fmt.Printf("%s %s\n", eventTime, event.Name) } } else { fmt.Printf("%s", listEvents) } os.Exit(0) } if "" != *listMetrics { listResponse, err := yatsClient.MetricList(*sourceOption, *listMetrics, fromTimestamp, toTimestamp) if err != nil { fmt.Println(err) os.Exit(1) } metricListModel, maxpage, _ := responseToMetricArray(listResponse) //fmt.Printf("maxpage : %s, fromTimeStamp: %s, toTimeStamp: %s", maxpage, fromTimestamp, toTimestamp) var composedList []model.MetricModel composedList = append(composedList, metricListModel...) for continueSearching(len(metricListModel), maxpage/1000, toTimestamp) { //fmt.Printf("maxpage : %s, toTimeStamp: %s", maxpage, toTimestamp) listResponse, _ = yatsClient.MetricList(*sourceOption, *listMetrics, maxpage/1000, toTimestamp) metricListModel, maxpage, _ = responseToMetricArray(listResponse) composedList = append(composedList, metricListModel...) } if *reformatOutput { if err == nil { for _, metric := range composedList { fmt.Printf("%d %s=%s\n", metric.Mtime, metric.Name, metric.Value) } } else { fmt.Println(err) } os.Exit(0) } if *logOutput { if err == nil { for _, metric := range composedList { 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 { if err == nil { metric := composedList[0] dataMap, errNoValue := io.MapFromBase64(metric.Value) if errNoValue { return } var keys []string for k := range dataMap { keys = append(keys, k) } //sort.Strings(keys) fmt.Printf("\"timestamp\"") for _, k := range keys { fmt.Printf("%s\"%s\"", recordSeparator, k) } fmt.Printf("%s", rowSeparator) for indexRow, row := range composedList { rowMap, errNoValue := io.MapFromBase64(row.Value) if errNoValue { return } metricTime := util.FormattedUtcTimeInSec(composedList[indexRow].Mtime) //metricTime := formattedUtcTimeInSec(metric.Mtime) fmt.Printf("%s", metricTime) //fmt.Printf("%d%s", metric.Mtime, recordSeparator) for _, k := range keys { fmt.Printf("%s\"%v\"", recordSeparator, rowMap[k]) } fmt.Printf("%s", rowSeparator) } } else { fmt.Println(err) } os.Exit(0) } for _, metric := range composedList { fmt.Printf("%d %s=%s\n", metric.Mtime, metric.Name, metric.Value) } os.Exit(0) } if "" != *listPositions { listResponse := yatsClient.PositionList(*sourceOption, fromTimestamp, toTimestamp) fmt.Printf("%s", listResponse) os.Exit(0) } } func responseToMetricArray(listResponse string) ([]model.MetricModel, int64, bool) { dataJson, errDataPortion := io.GetDataJson(listResponse) maxpage := io.GetMaxpage(listResponse) //fmt.Println("maxpage:", maxpage) if errDataPortion { fmt.Printf("Could not parse data attribute: %v", errDataPortion) return nil, 0, true } var metricListModel []model.MetricModel err := json.Unmarshal(dataJson, &metricListModel) if err == nil { return metricListModel, maxpage, true } return metricListModel, maxpage, false } func responseToEventArray(listResponse string) ([]model.EventModel, int64, bool) { dataJson, errDataPortion := io.GetDataJson(listResponse) maxpage := io.GetMaxpage(listResponse) if errDataPortion { fmt.Printf("Could not parse data attribute: %v", errDataPortion) return nil, 0, true } var eventListModel []model.EventModel err := json.Unmarshal(dataJson, &eventListModel) if err == nil { return eventListModel, maxpage, true } return eventListModel, maxpage, false } func continueSearching(arrayLen int, maxpage int64, toTimestamp int64) bool { //fmt.Printf("DEBUG::arrayLen: %d maxpage: %d toTimestamp: %d\n", arrayLen, maxpage, toTimestamp) if arrayLen < MaxPageSize { //fmt.Printf("DEBUG::false -1\n") return false } if toTimestamp == 0 { //fmt.Printf("DEBUG::false 0\n") return true } if toTimestamp > maxpage { return true } //fmt.Printf("DEBUG::true\n") return false }