Best Keploy code snippet using telemetry.marshalEvent
restfuncs.go
Source:restfuncs.go
1// -*- Mode: Go; indent-tabs-mode: t -*-2//3// Copyright (C) 2017-2018 Canonical Ltd4// Copyright (C) 2018-2020 IOTech Ltd5//6// SPDX-License-Identifier: Apache-2.07package controller8import (9 "encoding/json"10 "fmt"11 "io/ioutil"12 "net/http"13 "runtime"14 "github.com/edgexfoundry/device-sdk-go/internal/autodiscovery"15 "github.com/edgexfoundry/device-sdk-go/internal/common"16 "github.com/edgexfoundry/device-sdk-go/internal/container"17 "github.com/edgexfoundry/device-sdk-go/internal/handler"18 "github.com/edgexfoundry/device-sdk-go/internal/handler/callback"19 "github.com/edgexfoundry/go-mod-core-contracts/clients"20 contract "github.com/edgexfoundry/go-mod-core-contracts/models"21 "github.com/gorilla/mux"22)23const (24 statusOK string = "OK"25 statusNotImplemented string = "Discovery not implemented"26 statusUnavailable string = "Discovery disabled by configuration"27 statusLocked string = "OperatingState disabled"28)29type ConfigRespMap struct {30 Configuration map[string]interface{}31}32func (c *RestController) statusFunc(w http.ResponseWriter, _ *http.Request) {33 w.Header().Set(clients.ContentType, clients.ContentTypeText)34 w.Write([]byte("pong"))35}36func (c *RestController) versionFunc(w http.ResponseWriter, _ *http.Request) {37 res := struct {38 Version string `json:"version"`39 }{handler.VersionHandler()}40 w.Header().Add(clients.ContentType, clients.ContentTypeJSON)41 w.WriteHeader(http.StatusOK)42 c.encode(res, w)43}44func (c *RestController) discoveryFunc(w http.ResponseWriter, req *http.Request) {45 ds := container.DeviceServiceFrom(c.dic.Get)46 if c.checkServiceLocked(w, req, ds.AdminState) {47 return48 }49 if ds.OperatingState == contract.Disabled {50 http.Error(w, statusLocked, http.StatusLocked) // status=42351 return52 }53 configuration := container.ConfigurationFrom(c.dic.Get)54 if !configuration.Device.Discovery.Enabled {55 http.Error(w, statusUnavailable, http.StatusServiceUnavailable) // status=50356 return57 }58 discovery := container.ProtocolDiscoveryFrom(c.dic.Get)59 if discovery == nil {60 http.Error(w, statusNotImplemented, http.StatusNotImplemented) // status=50161 return62 }63 go autodiscovery.DiscoveryWrapper(discovery, c.LoggingClient)64 w.WriteHeader(http.StatusAccepted) //status=20265}66func (c *RestController) transformFunc(w http.ResponseWriter, req *http.Request) {67 if c.checkServiceLocked(w, req, container.DeviceServiceFrom(c.dic.Get).AdminState) {68 return69 }70 vars := mux.Vars(req)71 _, appErr := handler.TransformHandler(vars, c.LoggingClient)72 if appErr != nil {73 w.WriteHeader(appErr.Code())74 } else {75 w.Write([]byte(statusOK))76 }77}78func (c *RestController) callbackFunc(w http.ResponseWriter, req *http.Request) {79 defer req.Body.Close()80 dec := json.NewDecoder(req.Body)81 cbAlert := contract.CallbackAlert{}82 err := dec.Decode(&cbAlert)83 if err != nil {84 http.Error(w, err.Error(), http.StatusBadRequest)85 c.LoggingClient.Error(fmt.Sprintf("Invalid callback request: %v", err))86 return87 }88 appErr := callback.CallbackHandler(cbAlert, req.Method, c.dic)89 if appErr != nil {90 http.Error(w, appErr.Message(), appErr.Code())91 } else {92 w.Write([]byte(statusOK))93 }94}95func (c *RestController) commandFunc(w http.ResponseWriter, req *http.Request) {96 if c.checkServiceLocked(w, req, container.DeviceServiceFrom(c.dic.Get).AdminState) {97 return98 }99 vars := mux.Vars(req)100 body, ok := c.readBodyAsString(w, req)101 if !ok {102 return103 }104 event, appErr := handler.CommandHandler(vars, body, req.Method, req.URL.RawQuery, c.dic)105 if appErr != nil {106 http.Error(w, fmt.Sprintf("%s %s", appErr.Message(), req.URL.Path), appErr.Code())107 } else if event != nil {108 ec := container.CoredataEventClientFrom(c.dic.Get)109 if event.HasBinaryValue() {110 // TODO: Add conditional toggle in case caller of command does not require this response.111 // Encode response as application/CBOR.112 if len(event.EncodedEvent) <= 0 {113 var err error114 event.EncodedEvent, err = ec.MarshalEvent(event.Event)115 if err != nil {116 c.LoggingClient.Error("DeviceCommand: Error encoding event", "device", event.Device, "error", err)117 } else {118 c.LoggingClient.Trace("DeviceCommand: EventClient.MarshalEvent encoded event", "device", event.Device, "event", event)119 }120 } else {121 c.LoggingClient.Trace("DeviceCommand: EventClient.MarshalEvent passed through encoded event", "device", event.Device, "event", event)122 }123 // TODO: Resolve why this header is not included in response from Core-Command to originating caller (while the written body is).124 w.Header().Set(clients.ContentType, clients.ContentTypeCBOR)125 w.Write(event.EncodedEvent)126 } else {127 w.Header().Set(clients.ContentType, clients.ContentTypeJSON)128 json.NewEncoder(w).Encode(event)129 }130 // push to Core Data131 go common.SendEvent(event, c.LoggingClient, container.CoredataEventClientFrom(c.dic.Get))132 }133}134func (c *RestController) commandAllFunc(w http.ResponseWriter, req *http.Request) {135 if c.checkServiceLocked(w, req, container.DeviceServiceFrom(c.dic.Get).AdminState) {136 return137 }138 vars := mux.Vars(req)139 c.LoggingClient.Debug(fmt.Sprintf("execute the Get command %s from all operational devices", vars[common.CommandVar]))140 body, ok := c.readBodyAsString(w, req)141 if !ok {142 return143 }144 events, appErr := handler.CommandAllHandler(vars[common.CommandVar], body, req.Method, req.URL.RawQuery, c.dic)145 if appErr != nil {146 http.Error(w, appErr.Message(), appErr.Code())147 } else if len(events) > 0 {148 // push to Core Data149 for _, event := range events {150 if event != nil {151 go common.SendEvent(event, c.LoggingClient, container.CoredataEventClientFrom(c.dic.Get))152 }153 }154 w.Header().Set(clients.ContentType, clients.ContentTypeJSON)155 json.NewEncoder(w).Encode(events)156 }157}158func (c *RestController) checkServiceLocked(w http.ResponseWriter, req *http.Request, locked contract.AdminState) bool {159 if locked == contract.Locked {160 msg := fmt.Sprintf("Service is locked; %s %s", req.Method, req.URL)161 c.LoggingClient.Error(msg)162 http.Error(w, msg, http.StatusLocked) // status=423163 return true164 }165 return false166}167func (c *RestController) readBodyAsString(w http.ResponseWriter, req *http.Request) (string, bool) {168 defer req.Body.Close()169 body, err := ioutil.ReadAll(req.Body)170 if err != nil {171 msg := fmt.Sprintf("error reading request body for: %s %s", req.Method, req.URL)172 c.LoggingClient.Error(msg)173 return "", false174 }175 if len(body) == 0 && req.Method == http.MethodPut {176 msg := fmt.Sprintf("no request body provided; %s %s", req.Method, req.URL)177 c.LoggingClient.Error(msg)178 http.Error(w, msg, http.StatusBadRequest) // status=400179 return "", false180 }181 return string(body), true182}183func (c *RestController) metricsFunc(w http.ResponseWriter, _ *http.Request) {184 var t common.Telemetry185 // The device service is to be considered the System Of Record (SOR) for accurate information.186 // (Here, we fetch metrics for a given device service that's been generated by device-sdk-go.)187 var rtm runtime.MemStats188 // Read full memory stats189 runtime.ReadMemStats(&rtm)190 // Miscellaneous memory stats191 t.Alloc = rtm.Alloc192 t.TotalAlloc = rtm.TotalAlloc193 t.Sys = rtm.Sys194 t.Mallocs = rtm.Mallocs195 t.Frees = rtm.Frees196 // Live objects = Mallocs - Frees197 t.LiveObjects = t.Mallocs - t.Frees198 c.encode(t, w)199 return200}201func (c *RestController) configFunc(w http.ResponseWriter, _ *http.Request) {202 configuration := container.ConfigurationFrom(c.dic.Get)203 c.encode(configuration, w)204}205// Helper function for encoding the response when servicing a REST call.206func (c *RestController) encode(i interface{}, w http.ResponseWriter) {207 w.Header().Add(clients.ContentType, clients.ContentTypeJSON)208 enc := json.NewEncoder(w)209 err := enc.Encode(i)210 if err != nil {211 c.LoggingClient.Error("Error encoding the data: " + err.Error())212 http.Error(w, err.Error(), http.StatusInternalServerError)213 return214 }215}...
telemetry.go
Source:telemetry.go
...38 EventType: "Ping",39 CreatedAt: time.Now().Unix(),40 }41 if count == 0 {42 bin, err := marshalEvent(event, ac.logger)43 if err != nil {44 break45 }46 resp, err := http.Post("https://telemetry.keploy.io/analytics", "application/json", bytes.NewBuffer(bin))47 if err != nil {48 ac.logger.Fatal("failed to send request for analytics", zap.Error(err))49 break50 }51 id, err := unmarshalResp(resp, ac.logger)52 if err != nil {53 break54 }55 ac.InstallationID = id56 ac.db.Insert(id)57 } else {58 ac.SendTelemetry("Ping", http.Client{}, context.TODO())59 }60 time.Sleep(5 * time.Minute)61 }62 }()63}64func (ac *Telemetry) Normalize(client http.Client, ctx context.Context) {65 ac.SendTelemetry("NormaliseTC", client, ctx)66}67func (ac *Telemetry) DeleteTc(client http.Client, ctx context.Context) {68 ac.SendTelemetry("DeleteTC", client, ctx)69}70func (ac *Telemetry) EditTc(client http.Client, ctx context.Context) {71 ac.SendTelemetry("EditTC", client, ctx)72}73func (ac *Telemetry) Testrun(success int, failure int, client http.Client, ctx context.Context) {74 ac.SendTelemetry("TestRun", client, ctx, map[string]interface{}{"Passed-Tests": success, "Failed-Tests": failure})75}76func (ac *Telemetry) GetApps(apps int, client http.Client, ctx context.Context) {77 ac.SendTelemetry("GetApps", client, ctx, map[string]interface{}{"Apps": apps})78}79func (ac *Telemetry) SendTelemetry(eventType string, client http.Client, ctx context.Context, output ...map[string]interface{}) {80 if ac.Enabled {81 event := models.Event{82 EventType: eventType,83 CreatedAt: time.Now().Unix(),84 }85 if len(output) != 0 {86 event.Meta = output[0]87 }88 if ac.InstallationID == "" {89 sr := ac.db.Find()90 ac.InstallationID = sr91 }92 event.InstallationID = ac.InstallationID93 bin, err := marshalEvent(event, ac.logger)94 if err != nil {95 ac.logger.Error("failed to marshal event", zap.Error(err))96 return97 }98 req, err := http.NewRequest(http.MethodPost, "https://telemetry.keploy.io/analytics", bytes.NewBuffer(bin))99 if err != nil {100 ac.logger.Fatal("failed to create request for analytics", zap.Error(err))101 return102 }103 req.Header.Set("Content-Type", "application/json; charset=utf-8")104 if !ac.OffMode {105 req = req.WithContext(ctx)106 resp, err := client.Do(req)107 if err != nil {...
utils.go
Source:utils.go
...7 "net/http"8 "go.keploy.io/server/pkg/models"9 "go.uber.org/zap"10)11func marshalEvent(event models.Event, log *zap.Logger) (bin []byte, err error) {12 bin, err = json.Marshal(event)13 if err != nil {14 log.Fatal("failed to marshal event struct into json", zap.Error(err))15 }16 return17}18func unmarshalResp(resp *http.Response, log *zap.Logger) (id string, err error) {19 defer func(Body io.ReadCloser) {20 err = Body.Close()21 if err != nil {22 log.Error("failed to close connecton reader", zap.String("url", "http://localhost:3030/analytics"), zap.Error(err))23 return24 }25 }(resp.Body)...
marshalEvent
Using AI Code Generation
1import (2func main() {3 telemetry := telemetry.NewTelemetry()4 event := telemetry.NewEvent()5 event.SetType("test")6 event.SetData("test data")7 marshalledEvent := telemetry.MarshalEvent(event)8 fmt.Println(marshalledEvent)9}10import (11func main() {12 telemetry := telemetry.NewTelemetry()13 event := telemetry.NewEvent()14 event.SetType("test")15 event.SetData("test data")16 marshalledEvent := telemetry.MarshalEvent(event)17 fmt.Println(marshalledEvent)18 unmarshalledEvent := telemetry.UnmarshalEvent(marshalledEvent)19 fmt.Println(unmarshalledEvent)20}21import (22func main() {23 telemetry := telemetry.NewTelemetry()24 event := telemetry.NewEvent()25 event.SetType("test")26 event.SetData("test data")27 marshalledEvent := telemetry.MarshalEvent(event)28 fmt.Println(marshalledEvent)29 unmarshalledEvent := telemetry.UnmarshalEvent(marshalledEvent)30 fmt.Println(unmarshalledEvent)31 err := telemetry.SendEvent(unmarshalledEvent)32 if err != nil {33 fmt.Println(err)34 }35}
marshalEvent
Using AI Code Generation
1import (2func main() {3 var data = []byte(`{4 "Fields": {5 {6 "state": {7 "counters": {8 }9 }10 }11 }12}`)13 event, err := telemetry.UnmarshalEvent(data)14 if err != nil {15 fmt.Println("error:", err)16 }17 fmt.Println(event)18}19import (20func main() {21 var data = []byte(`{22 "Fields": {23 {24 "state": {25 "counters": {26 }27 }28 }29 }30}`)31 event, err := telemetry.UnmarshalEvent(data)32 if err != nil {33 fmt.Println("error:", err)34 }35 fmt.Println(event)36}37The examples below are used to demonstrate how to use the goarista/telemetry package to write a telemetry client. The examples use the [gNMI](
marshalEvent
Using AI Code Generation
1import (2func main() {3 telemetryObj := telemetry.Telemetry{}4 event := telemetry.Event{EventType:"TestEvent",EventTime:"2018-01-01 00:00:00",EventValue: 1}5 jsonEvent, _ := telemetryObj.MarshalEvent(event)6 fmt.Println(jsonEvent)7}8import (9type Telemetry struct {10}11type Event struct {12}13func (t *Telemetry) MarshalEvent(event Event) ([]byte, error) {14 return json.Marshal(event)15}16{"EventType":"TestEvent","EventTime":"2018-01-01 00:00:00","EventValue":1}
marshalEvent
Using AI Code Generation
1import (2type Event struct {3 Data interface{} `json:"data"`4}5type Telemetry struct {6}7func main() {8 telemetry := Telemetry{}9 event := Event{}10 telemetry.Events = append(telemetry.Events, event)11 jsonBytes, _ := json.Marshal(telemetry)12 fmt.Println(string(jsonBytes))13 fmt.Println(reflect.TypeOf(telemetry))14}15{"events":[{"id":"1","name":"event1","data":"data1"}]}16import (17type Event struct {18 Data interface{} `json:"data"`19}20type Telemetry struct {21}22func main() {23 telemetry := Telemetry{}24 event := Event{}
marshalEvent
Using AI Code Generation
1import (2type Telemetry struct {3}4func (t *Telemetry) marshalEvent() ([]byte, error) {5 jsonTelemetry, err := json.Marshal(t)6 if err != nil {7 }8}9func main() {10 t := Telemetry{11 }12 jsonTelemetry, err := t.marshalEvent()13 if err != nil {14 fmt.Println("Error marshaling event:", err)15 }16 fmt.Println(string(jsonTelemetry))17}18{"timestamp":"2019-09-11 10:00:00","source":"example.com","severity":"INFO","message":"This is a test message"}19import (20type Telemetry struct {21}22func (t *Telemetry) unmarshalEvent(jsonTelemetry []byte) error {23 err := json.Unmarshal(jsonTelemetry, t)24 if err != nil {25 }26}27func main() {28 t := Telemetry{}29 err := t.unmarshalEvent([]byte(`{"timestamp":"2019-09-
marshalEvent
Using AI Code Generation
1func main() {2 e.Time = time.Now()3 e.Tags = []string{"test", "test1"}4 e.Data = map[string]interface{}{"test": "test"}5 t.MarshalEvent(e)6}7func main() {8 e.Time = time.Now()9 e.Tags = []string{"test", "test1"}10 e.Data = map[string]interface{}{"test": "test"}11 t.MarshalEvent(e)12 t.UnmarshalEvent()13}14func main() {15 e.Time = time.Now()16 e.Tags = []string{"test", "test1"}17 e.Data = map[string]interface{}{"test": "test"}18 t.MarshalEvent(e)19 t.UnmarshalEvent()20 t.MarshalEvent(e)21}22func main() {23 e.Time = time.Now()24 e.Tags = []string{"test", "test1"}25 e.Data = map[string]interface{}{"test": "test"}26 t.MarshalEvent(e)27 t.UnmarshalEvent()28 t.MarshalEvent(e)29 t.UnmarshalEvent()30}31func main() {32 e.Time = time.Now()33 e.Tags = []string{"test", "test1"}34 e.Data = map[string]interface{}{"test": "test"}35 t.MarshalEvent(e)36 t.UnmarshalEvent()37 t.MarshalEvent(e)38 t.UnmarshalEvent()39 t.MarshalEvent(e)40}41func main() {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!