How to use Uptime method of main Package

Best Syzkaller code snippet using main.Uptime

main.go

Source:main.go Github

copy

Full Screen

...20 kingpin "gopkg.in/alecthomas/kingpin.v2"21)22var SystemConfig TykPumpConfiguration23var AnalyticsStore storage.AnalyticsStorage24var UptimeStorage storage.AnalyticsStorage25var Pumps []pumps.Pump26var UptimePump pumps.UptimePump27var AnalyticsSerializers []serializer.AnalyticsSerializer28var log = logger.GetLogger()29var mainPrefix = "main"30var (31 help = kingpin.CommandLine.HelpFlag.Short('h')32 conf = kingpin.Flag("conf", "path to the config file").Short('c').Default("pump.conf").String()33 demoMode = kingpin.Flag("demo", "pass orgID string to generate demo data").Default("").String()34 demoApiMode = kingpin.Flag("demo-api", "pass apiID string to generate demo data").Default("").String()35 demoApiVersionMode = kingpin.Flag("demo-api-version", "pass apiID string to generate demo data").Default("").String()36 debugMode = kingpin.Flag("debug", "enable debug mode").Bool()37 version = kingpin.Version(pumps.VERSION)38)39func Init() {40 SystemConfig = TykPumpConfiguration{}41 kingpin.Parse()42 LoadConfig(conf, &SystemConfig)43 if SystemConfig.LogFormat == "json" {44 log.Formatter = &logrus.JSONFormatter{}45 }46 envDemo := os.Getenv("TYK_PMP_BUILDDEMODATA")47 if envDemo != "" {48 log.Warning("Demo mode active via environemnt variable")49 demoMode = &envDemo50 }51 //Serializer init52 AnalyticsSerializers = []serializer.AnalyticsSerializer{serializer.NewAnalyticsSerializer(serializer.MSGP_SERIALIZER), serializer.NewAnalyticsSerializer(serializer.PROTOBUF_SERIALIZER)}53 log.WithFields(logrus.Fields{54 "prefix": mainPrefix,55 }).Info("## Tyk Analytics Pump, ", pumps.VERSION, " ##")56 // If no environment variable is set, check the configuration file:57 if os.Getenv("TYK_LOGLEVEL") == "" {58 level := strings.ToLower(SystemConfig.LogLevel)59 switch level {60 case "", "info":61 // default, do nothing62 case "error":63 log.Level = logrus.ErrorLevel64 case "warn":65 log.Level = logrus.WarnLevel66 case "debug":67 log.Level = logrus.DebugLevel68 default:69 log.WithFields(logrus.Fields{70 "prefix": "main",71 }).Fatalf("Invalid log level %q specified in config, must be error, warn, debug or info. ", level)72 }73 }74 // If debug mode flag is set, override previous log level parameter:75 if *debugMode {76 log.Level = logrus.DebugLevel77 }78}79func setupAnalyticsStore() {80 switch SystemConfig.AnalyticsStorageType {81 case "redis":82 AnalyticsStore = &storage.RedisClusterStorageManager{}83 UptimeStorage = &storage.RedisClusterStorageManager{}84 default:85 AnalyticsStore = &storage.RedisClusterStorageManager{}86 UptimeStorage = &storage.RedisClusterStorageManager{}87 }88 AnalyticsStore.Init(SystemConfig.AnalyticsStorageConfig)89 // Copy across the redis configuration90 uptimeConf := SystemConfig.AnalyticsStorageConfig91 // Swap key prefixes for uptime purger92 uptimeConf.RedisKeyPrefix = "host-checker:"93 UptimeStorage.Init(uptimeConf)94}95func storeVersion() {96 var versionStore = &storage.RedisClusterStorageManager{}97 versionConf := SystemConfig.AnalyticsStorageConfig98 versionStore.KeyPrefix = "version-check-"99 versionStore.Config = versionConf100 versionStore.Connect()101 versionStore.SetKey("pump", pumps.VERSION, 0)102}103func initialisePumps() {104 Pumps = []pumps.Pump{}105 for key, pmp := range SystemConfig.Pumps {106 pumpTypeName := pmp.Type107 if pumpTypeName == "" {108 pumpTypeName = key109 }110 pmpType, err := pumps.GetPumpByName(pumpTypeName)111 if err != nil {112 log.WithFields(logrus.Fields{113 "prefix": mainPrefix,114 }).Error("Pump load error (skipping): ", err)115 } else {116 thisPmp := pmpType.New()117 thisPmp.SetFilters(pmp.Filters)118 thisPmp.SetTimeout(pmp.Timeout)119 thisPmp.SetOmitDetailedRecording(pmp.OmitDetailedRecording)120 thisPmp.SetMaxRecordSize(pmp.MaxRecordSize)121 initErr := thisPmp.Init(pmp.Meta)122 if initErr != nil {123 log.WithField("pump", thisPmp.GetName()).Error("Pump init error (skipping): ", initErr)124 } else {125 log.WithFields(logrus.Fields{126 "prefix": mainPrefix,127 }).Info("Init Pump: ", key)128 Pumps = append(Pumps, thisPmp)129 }130 }131 }132 if len(Pumps) == 0 {133 log.WithFields(logrus.Fields{134 "prefix": mainPrefix,135 }).Fatal("No pumps configured")136 }137 if !SystemConfig.DontPurgeUptimeData {138 initialiseUptimePump()139 }140}141func initialiseUptimePump() {142 log.WithFields(logrus.Fields{143 "prefix": mainPrefix,144 }).Info("'dont_purge_uptime_data' set to false, attempting to start Uptime pump! ")145 switch SystemConfig.UptimePumpConfig.UptimeType {146 case "sql":147 UptimePump = &pumps.SQLPump{IsUptime: true}148 UptimePump.Init(SystemConfig.UptimePumpConfig.SQLConf)149 default:150 UptimePump = &pumps.MongoPump{IsUptime: true}151 UptimePump.Init(SystemConfig.UptimePumpConfig.MongoConf)152 }153 log.WithFields(logrus.Fields{154 "prefix": mainPrefix,155 "type": SystemConfig.UptimePumpConfig.Type,156 }).Info("Init Uptime Pump: ", UptimePump.GetName())157}158func StartPurgeLoop(wg *sync.WaitGroup, ctx context.Context, secInterval int, chunkSize int64, expire time.Duration, omitDetails bool) {159 for range time.Tick(time.Duration(secInterval) * time.Second) {160 job := instrument.NewJob("PumpRecordsPurge")161 startTime := time.Now()162 for i := -1; i < 10; i++ {163 var analyticsKeyName string164 if i == -1 {165 //if it's the first iteration, we look for tyk-system-analytics to maintain backwards compatibility or if analytics_config.enable_multiple_analytics_keys is disabled in the gateway166 analyticsKeyName = storage.ANALYTICS_KEYNAME167 } else {168 analyticsKeyName = fmt.Sprintf("%v_%v", storage.ANALYTICS_KEYNAME, i)169 }170 for _, serializerMethod := range AnalyticsSerializers {171 analyticsKeyName += serializerMethod.GetSuffix()172 AnalyticsValues := AnalyticsStore.GetAndDeleteSet(analyticsKeyName, chunkSize, expire)173 if len(AnalyticsValues) > 0 {174 PreprocessAnalyticsValues(AnalyticsValues, serializerMethod, analyticsKeyName, omitDetails, job, startTime, secInterval)175 }176 }177 }178 job.Timing("purge_time_all", time.Since(startTime).Nanoseconds())179 if !SystemConfig.DontPurgeUptimeData {180 UptimeValues := UptimeStorage.GetAndDeleteSet(storage.UptimeAnalytics_KEYNAME, chunkSize, expire)181 UptimePump.WriteUptimeData(UptimeValues)182 }183 if checkShutdown(ctx, wg) {184 return185 }186 }187}188func PreprocessAnalyticsValues(AnalyticsValues []interface{}, serializerMethod serializer.AnalyticsSerializer, analyticsKeyName string, omitDetails bool, job *health.Job, startTime time.Time, secInterval int) {189 keys := make([]interface{}, len(AnalyticsValues))190 for i, v := range AnalyticsValues {191 decoded := analytics.AnalyticsRecord{}192 err := serializerMethod.Decode([]byte(v.(string)), &decoded)193 log.WithFields(logrus.Fields{194 "prefix": mainPrefix,195 }).Debug("Decoded Record: ", decoded)...

Full Screen

Full Screen

main_test.go

Source:main_test.go Github

copy

Full Screen

1package main2import (3 "encoding/json"4 "testing"5 //"fmt"6)7func Test_counter2prometheusWrapper(t *testing.T) {8 type CounterTestData struct {9 testCaseDesc string10 jsonRawMsg map[string]json.RawMessage11 correctOutput string12 }13 ctds := []CounterTestData{14 CounterTestData{"Test of one properly formatted output string.",15 map[string]json.RawMessage{"MAIN.shm_records": json.RawMessage(`{"description":"SHM records","flag":"c","format":"i","value":29382}`)},16 `# HELP varnish_main_shm_records SHM records17# TYPE varnish_main_shm_records counter18varnish_main_shm_records 2938219`},20 CounterTestData{"Test of multiple properly formatted output strings.",21 map[string]json.RawMessage{22 "SMA.s0.c_req": json.RawMessage(`{"description":"Allocator requests","flag":"c","format":"i","value":0}`),23 "SMA.Transient.c_req": json.RawMessage(`{"description":"Allocator requests","flag":"c","format":"i","value":0}`),24 "MAIN.shm_records": json.RawMessage(`{"description":"SHM records","flag":"c","format":"i","value":29382}`),25 "MAIN.shm_writes": json.RawMessage(`{"description":"SHM writes","flag":"c","format":"i","value":29382}`),26 "MEMPOOL.busyobj.live": json.RawMessage(`{"description":"In use","flag":"g","format":"i","value":0}`),27 "MEMPOOL.req0.live": json.RawMessage(`{"description":"In use","flag":"g","format":"i","value":0}`),28 "MEMPOOL.sess0.live": json.RawMessage(`{"description":"In use","flag":"g","format":"i","value":0}`),29 "MEMPOOL.req1.live": json.RawMessage(`{"description":"In use","flag":"g","format":"i","value":0}`),30 "MEMPOOL.sess1.live": json.RawMessage(`{"description":"In use","flag":"g","format":"i","value":0}`),31 },32 `# HELP varnish_main_shm_records SHM records33# TYPE varnish_main_shm_records counter34varnish_main_shm_records 2938235# HELP varnish_main_shm_writes SHM writes36# TYPE varnish_main_shm_writes counter37varnish_main_shm_writes 2938238# HELP varnish_mempool_live In use39# TYPE varnish_mempool_live gauge40varnish_mempool_live{id="busyobj"} 041varnish_mempool_live{id="req0"} 042varnish_mempool_live{id="req1"} 043varnish_mempool_live{id="sess0"} 044varnish_mempool_live{id="sess1"} 045# HELP varnish_sma_c_req Allocator requests46# TYPE varnish_sma_c_req counter47varnish_sma_c_req{id="Transient"} 048varnish_sma_c_req{id="s0"} 049`},50 CounterTestData{"Testing valid flag value g which needs to translate to \"gauge\" in the TYPE line.",51 map[string]json.RawMessage{"MGT.uptime": json.RawMessage(`{"description":"Management process uptime","flag":"b","format":"d","value":17067}`)},52 `# HELP varnish_mgt_uptime Management process uptime53# TYPE varnish_mgt_uptime gauge54varnish_mgt_uptime 1706755`},56 CounterTestData{"Testing valid flag value b which needs to translate to \"gauge\" in the TYPE line.",57 map[string]json.RawMessage{"MGT.uptime": json.RawMessage(`{"description":"Management process uptime","flag":"b","format":"d","value":17067}`)},58 `# HELP varnish_mgt_uptime Management process uptime59# TYPE varnish_mgt_uptime gauge60varnish_mgt_uptime 1706761`},62 CounterTestData{"Testing invalid flag value x which needs to translate to \"untyped\" in the TYPE line.",63 map[string]json.RawMessage{"MGT.uptime": json.RawMessage(`{"description":"Management process uptime","flag":"x","format":"d","value":17067}`)},64 `# HELP varnish_mgt_uptime Management process uptime65# TYPE varnish_mgt_uptime untyped66varnish_mgt_uptime 1706767`},68 CounterTestData{"Testing invalid multiple letter flag value yy which needs to translate to \"untyped\" in the TYPE line.",69 map[string]json.RawMessage{"MGT.uptime": json.RawMessage(`{"description":"Management process uptime","flag":"yy","format":"d","value":17067}`)},70 `# HELP varnish_mgt_uptime Management process uptime71# TYPE varnish_mgt_uptime untyped72varnish_mgt_uptime 1706773`},74 CounterTestData{"Largest uint64",75 map[string]json.RawMessage{"MGT.uptime": json.RawMessage(`{"description":"Management process uptime","flag":"c","format":"d","value":18446744073709551615}`)},76 `# HELP varnish_mgt_uptime Management process uptime77# TYPE varnish_mgt_uptime counter78varnish_mgt_uptime 1844674407370955161579`},80 CounterTestData{"Test for missing string values and zero number values.",81 map[string]json.RawMessage{"MGT.uptime": json.RawMessage(`{"description":"Management process uptime","flag":"","format":"","value":0}`)},82 `# HELP varnish_mgt_uptime Management process uptime83# TYPE varnish_mgt_uptime untyped84varnish_mgt_uptime 085`},86 } // Closing brace for CounterTestData array87 for _, ctd := range ctds { // ctds is an array of CounterTestData.88 if ctd.correctOutput != counter2prometheusWrapper(ctd.jsonRawMsg) {89 t.Errorf("Error: correct output != CounterTestData test case\n\n=Test case description=\n%s\n\n=correctOutput=\n%s\n=test result=\n%+v\n\n",90 ctd.testCaseDesc, ctd.correctOutput, counter2prometheusWrapper(ctd.jsonRawMsg))91 }92 }93}94func Test_counter2prometheus(t *testing.T) {95 type tc struct {96 in string97 out string98 }99 tcs := []tc{100 {"foo", "varnish_unknown_foo"},101 {"foo.Bar.baZ", "varnish_foo_Bar_baZ"},102 {"MGT.uptime", "varnish_mgt_uptime"},103 {"VBE.default.goto.00000000.(8.8.8.8).(http://example.com:80).(ttl:10.000000).bereq_bodybytes", `varnish_backend_bereq_bodybytes{backend="goto",vcl="default",domain="http://example.com:80",ip="8.8.8.8",ttl="10.000000",id="00000000"}`},104 {"KVSTORE.vha6_stats.boot.broadcast_candidates", `varnish_kvstore_counter{vcl="boot",space="vha6_stats",name="broadcast_candidates"}`},105 {"KVSTORE.vha6_stats.boot.broadcast_candidates", `varnish_kvstore_counter{vcl="boot",space="vha6_stats",name="broadcast_candidates"}`},106 {"SMA.Transient.c_ykey_purged", `varnish_sma_c_ykey_purged{id="Transient"}`},107 {"MSE_BOOK.NamedBook.c_insert_timeout", `varnish_mse_c_insert_timeout{id="NamedBook",type="book"}`},108 {"MSE_STORE.NamedStore.c_insert_timeout", `varnish_mse_c_insert_timeout{id="NamedStore",type="store"}`},109 {"MSE.mse.n_lru_nuked", `varnish_mse_n_lru_nuked{id="mse",type="env"}`},110 }111 for _, tc := range tcs {112 counter := counter2prometheus(tc.in, VCounter{})113 fullName := counter.Name + counter.Counters[0].Labels114 if tc.out != fullName {115 t.Errorf("for %s:\n\texpected %s\n\tgot %s", tc.in, tc.out, fullName)116 }117 }118}...

Full Screen

Full Screen

Uptime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(time.Now().Unix())4 fmt.Println(time.Now().UnixNano())5 fmt.Println(time.Now().Format(time.RFC3339))6 fmt.Println(time.Now().UTC().Format(time.RFC3339))7 fmt.Println(time.Now().UnixNano())8 fmt.Println(time.Now().UnixNano() / 1000000)9 fmt.Println(time.Now().UnixNano() / 1000000000)10 fmt.Println(time.Now().UnixNano() / 1000000000)11 fmt.Println(time.Now().UnixNano() / int64(time.Millisec

Full Screen

Full Screen

Uptime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(uptime.Uptime())4 time.Sleep(5 * time.Second)5 fmt.Println(uptime.Uptime())6}

Full Screen

Full Screen

Uptime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Uptime: ", time.Now().Sub(startTime))4}5Recommended Posts: Go | time.Since() function6Go | time.Unix() function7Go | time.UnixNano() function8Go | time.Now() function9Go | time.Parse() function10Go | time.ParseDuration() function11Go | time.ParseInLocation() function12Go | time.Sleep() function13Go | time.Tick() function14Go | time.Until() function15Go | time.After() function16Go | time.AfterFunc() function17Go | time.Date() function18Go | time.UTC() function19Go | time.Local() function20Go | time.FixedZone() function21Go | time.LoadLocation() function22Go | time.NewTicker() function23Go | time.NewTimer() function24Go | time.New() function25Go | time.NewDate() function26Go | time.NewTime() function27Go | time.NewDuration() function28Go | time.NewLocation() function29Go | time.NewZone() function30Go | time.NewFixedZone() function31Go | time.NewLoadLocation() function32Go | time.NewUnix() function33Go | time.NewUnixNano() function34Go | time.NewSince() function35Go | time.NewUntil() function36Go | time.NewAfter() function37Go | time.NewAfterFunc() function38Go | time.NewParse() function39Go | time.NewParseInLocation() function40Go | time.NewParseDuration() function41Go | time.NewSleep() function42Go | time.NewTick() function43Go | time.NewFormat() function44Go | time.NewFormatDuration() function45Go | time.NewFormatNano() function46Go | time.NewFormatMicro() function47Go | time.NewFormatMilli() function48Go | time.NewFormatSecond() function49Go | time.NewFormatMinute() function50Go | time.NewFormatHour() function51Go | time.NewFormatTime() function52Go | time.NewFormatDate() function53Go | time.NewFormatDateTime() function54Go | time.NewFormatDateTimeNano() function55Go | time.NewFormatDateTimeMicro() function56Go | time.NewFormatDateTimeMilli() function57Go | time.NewFormatDateTimeSecond() function

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful