func TestSNMPGet2(t *testing.T) { get1 := Data{ Name: "oid1", Oid: "ifNumber", } h := Host{ Address: testutil.GetLocalHost() + ":31161", Community: "telegraf", Version: 2, Timeout: 2.0, Retries: 2, Collect: []string{"oid1"}, } s := Snmp{ SnmptranslateFile: "./testdata/oids.txt", Host: []Host{h}, Get: []Data{get1}, } var acc testutil.Accumulator err := s.Gather(&acc) require.NoError(t, err) acc.AssertContainsTaggedFields(t, "ifNumber", map[string]interface{}{ "ifNumber": int(4), }, map[string]string{ "instance": "0", "host": testutil.GetLocalHost(), }, ) }
func TestGatherGlob(t *testing.T) { dir := getTestdataDir() fs := NewFileStat() fs.Md5 = true fs.Files = []string{ dir + "*.log", } acc := testutil.Accumulator{} fs.Gather(&acc) tags1 := map[string]string{ "file": dir + "log1.log", } fields1 := map[string]interface{}{ "size_bytes": int64(0), "exists": int64(1), "md5_sum": "d41d8cd98f00b204e9800998ecf8427e", } acc.AssertContainsTaggedFields(t, "filestat", fields1, tags1) tags2 := map[string]string{ "file": dir + "log2.log", } fields2 := map[string]interface{}{ "size_bytes": int64(0), "exists": int64(1), "md5_sum": "d41d8cd98f00b204e9800998ecf8427e", } acc.AssertContainsTaggedFields(t, "filestat", fields2, tags2) }
// Test that test_a.log line gets parsed even though we don't have the correct // pattern available for test_b.log func TestGrokParseLogFilesOneBad(t *testing.T) { thisdir := getCurrentDir() p := &grok.Parser{ Patterns: []string{"%{TEST_LOG_A}", "%{TEST_LOG_BAD}"}, CustomPatternFiles: []string{thisdir + "grok/testdata/test-patterns"}, } assert.NoError(t, p.Compile()) logparser := &LogParserPlugin{ FromBeginning: true, Files: []string{thisdir + "grok/testdata/test_a.log"}, GrokParser: p, } acc := testutil.Accumulator{} acc.SetDebug(true) assert.NoError(t, logparser.Start(&acc)) time.Sleep(time.Millisecond * 500) logparser.Stop() acc.AssertContainsTaggedFields(t, "logparser_grok", map[string]interface{}{ "clientip": "192.168.1.1", "myfloat": float64(1.25), "response_time": int64(5432), "myint": int64(101), }, map[string]string{"response_code": "200"}) }
// Test that the proper values are ignored or collected for class=Cassandra func TestHttpJsonCassandraMultiValue(t *testing.T) { cassandra := genJolokiaClientStub(validCassandraMultiValueJSON, 200, Servers, []string{ReadLatencyMetric}) var acc testutil.Accumulator err := cassandra.Gather(&acc) assert.Nil(t, err) assert.Equal(t, 1, len(acc.Metrics)) fields := map[string]interface{}{ "ReadLatency_999thPercentile": 20.0, "ReadLatency_99thPercentile": 10.0, "ReadLatency_Count": 400.0, "ReadLatency_DurationUnit": "microseconds", "ReadLatency_Max": 30.0, "ReadLatency_MeanRate": 3.0, "ReadLatency_Min": 1.0, "ReadLatency_RateUnit": "events/second", } tags := map[string]string{ "cassandra_host": "10.10.10.10", "mname": "ReadLatency", "keyspace": "test_keyspace1", "scope": "test_table", } acc.AssertContainsTaggedFields(t, "cassandraTable", fields, tags) }
// Test that the proper values are ignored or collected for class=Java func TestHttpJsonJavaMultiValue(t *testing.T) { cassandra := genJolokiaClientStub(validJavaMultiValueJSON, 200, MultipleServers, []string{HeapMetric}) var acc testutil.Accumulator acc.SetDebug(true) err := cassandra.Gather(&acc) assert.Nil(t, err) assert.Equal(t, 2, len(acc.Metrics)) fields := map[string]interface{}{ "HeapMemoryUsage_init": 67108864.0, "HeapMemoryUsage_committed": 456130560.0, "HeapMemoryUsage_max": 477626368.0, "HeapMemoryUsage_used": 203288528.0, } tags1 := map[string]string{ "cassandra_host": "10.10.10.10", "mname": "HeapMemoryUsage", } tags2 := map[string]string{ "cassandra_host": "10.10.10.11", "mname": "HeapMemoryUsage", } acc.AssertContainsTaggedFields(t, "javaMemory", fields, tags1) acc.AssertContainsTaggedFields(t, "javaMemory", fields, tags2) }
func TestMultipleEvents(t *testing.T) { var acc testutil.Accumulator md := &MandrillWebhook{Path: "/mandrill", acc: &acc} resp := postWebhooks(md, "["+SendEventJSON()+","+HardBounceEventJSON()+"]") if resp.Code != http.StatusOK { t.Errorf("POST send returned HTTP status code %v.\nExpected %v", resp.Code, http.StatusOK) } fields := map[string]interface{}{ "id": "id1", } tags := map[string]string{ "event": "send", } acc.AssertContainsTaggedFields(t, "mandrill_webhooks", fields, tags) fields = map[string]interface{}{ "id": "id2", } tags = map[string]string{ "event": "hard_bounce", } acc.AssertContainsTaggedFields(t, "mandrill_webhooks", fields, tags) }
func TestPhpFpmGeneratesMetrics_From_Http(t *testing.T) { sv := statServer{} ts := httptest.NewServer(sv) defer ts.Close() r := &phpfpm{ Urls: []string{ts.URL}, } var acc testutil.Accumulator err := r.Gather(&acc) require.NoError(t, err) tags := map[string]string{ "pool": "www", } fields := map[string]interface{}{ "accepted_conn": int64(3), "listen_queue": int64(1), "max_listen_queue": int64(0), "listen_queue_len": int64(0), "idle_processes": int64(1), "active_processes": int64(1), "total_processes": int64(2), "max_active_processes": int64(1), "max_children_reached": int64(2), "slow_requests": int64(1), } acc.AssertContainsTaggedFields(t, "phpfpm", fields, tags) }
func TestRunParser(t *testing.T) { var testmsg = []byte(testMsg) listener, in := newTestTcpListener() acc := testutil.Accumulator{} listener.acc = &acc defer close(listener.done) listener.parser, _ = parsers.NewInfluxParser() listener.wg.Add(1) go listener.tcpParser() in <- testmsg time.Sleep(time.Millisecond * 25) listener.Gather(&acc) if a := acc.NFields(); a != 1 { t.Errorf("got %v, expected %v", a, 1) } acc.AssertContainsTaggedFields(t, "cpu_load_short", map[string]interface{}{"value": float64(12)}, map[string]string{"host": "server01"}, ) }
func TestZfsGeneratesMetrics(t *testing.T) { var acc testutil.Accumulator z := &Zfs{ KstatMetrics: []string{"vdev_cache_stats"}, sysctl: mock_sysctl, zpool: mock_zpool, } err := z.Gather(&acc) require.NoError(t, err) //four pool, vdev_cache_stats metrics tags := map[string]string{ "pools": "freenas-boot::red1::temp1::temp2", } intMetrics := getKstatMetricsVdevOnly() acc.AssertContainsTaggedFields(t, "zfs", intMetrics, tags) acc.Metrics = nil z = &Zfs{ KstatMetrics: []string{"zfetchstats", "vdev_cache_stats"}, sysctl: mock_sysctl, zpool: mock_zpool, } err = z.Gather(&acc) require.NoError(t, err) //four pool, vdev_cache_stats and zfetchstatus metrics intMetrics = getKstatMetricsVdevAndZfetch() acc.AssertContainsTaggedFields(t, "zfs", intMetrics, tags) }
func TestSNMPEasyGet6(t *testing.T) { h := Host{ Address: "127.0.0.1:31161", Community: "telegraf", Version: 2, Timeout: 2.0, Retries: 2, GetOids: []string{"1.3.6.1.2.1.2.1.0"}, } s := Snmp{ SnmptranslateFile: "./testdata/oids.txt", Host: []Host{h}, } var acc testutil.Accumulator err := s.Gather(&acc) require.NoError(t, err) acc.AssertContainsTaggedFields(t, "ifNumber", map[string]interface{}{ "ifNumber": int(4), }, map[string]string{ "instance": "0", "host": "127.0.0.1", }, ) }
func TestSNMPGet1(t *testing.T) { get1 := Data{ Name: "oid1", Unit: "octets", Oid: ".1.3.6.1.2.1.2.2.1.16.1", } h := Host{ Address: "127.0.0.1:31161", Community: "telegraf", Version: 2, Timeout: 2.0, Retries: 2, Collect: []string{"oid1"}, } s := Snmp{ Host: []Host{h}, Get: []Data{get1}, } var acc testutil.Accumulator err := s.Gather(&acc) require.NoError(t, err) acc.AssertContainsTaggedFields(t, "oid1", map[string]interface{}{ "oid1": uint(543846), }, map[string]string{ "unit": "octets", "host": "127.0.0.1", }, ) }
func TestTailFromEnd(t *testing.T) { tmpfile, err := ioutil.TempFile("", "") require.NoError(t, err) defer os.Remove(tmpfile.Name()) _, err = tmpfile.WriteString("cpu,mytag=foo usage_idle=100\n") require.NoError(t, err) tt := NewTail() tt.Files = []string{tmpfile.Name()} p, _ := parsers.NewInfluxParser() tt.SetParser(p) defer tt.Stop() defer tmpfile.Close() acc := testutil.Accumulator{} require.NoError(t, tt.Start(&acc)) time.Sleep(time.Millisecond * 100) _, err = tmpfile.WriteString("cpu,othertag=foo usage_idle=100\n") require.NoError(t, err) require.NoError(t, tt.Gather(&acc)) time.Sleep(time.Millisecond * 50) acc.AssertContainsTaggedFields(t, "cpu", map[string]interface{}{ "usage_idle": float64(100), }, map[string]string{ "othertag": "foo", }) assert.Len(t, acc.Metrics, 1) }
func TestMetricContainsServerAndDomainAndRecordTypeTags(t *testing.T) { if testing.Short() { t.Skip("Skipping network-dependent test in short mode.") } var dnsConfig = DnsQuery{ Servers: servers, Domains: domains, } var acc testutil.Accumulator tags := map[string]string{ "server": "8.8.8.8", "domain": "google.com", "record_type": "NS", } fields := map[string]interface{}{} err := dnsConfig.Gather(&acc) assert.NoError(t, err) metric, ok := acc.Get("dns_query") require.True(t, ok) queryTime, _ := metric.Fields["query_time_ms"].(float64) fields["query_time_ms"] = queryTime acc.AssertContainsTaggedFields(t, "dns_query", fields, tags) }
func TestMissingDelayColumnNTPQ(t *testing.T) { resetVars() tt := tester{ ret: []byte(missingDelayNTPQ), err: nil, } n := &NTPQ{ runQ: tt.runqTest, } acc := testutil.Accumulator{} assert.NoError(t, n.Gather(&acc)) fields := map[string]interface{}{ "when": int64(101), "poll": int64(256), "reach": int64(37), "offset": float64(233.010), "jitter": float64(17.462), } tags := map[string]string{ "remote": "*uschi5-ntp-002.", "refid": "10.177.80.46", "type": "u", } acc.AssertContainsTaggedFields(t, "ntpq", fields, tags) }
func TestTailFromBeginning(t *testing.T) { tmpfile, err := ioutil.TempFile("", "") require.NoError(t, err) defer os.Remove(tmpfile.Name()) tt := NewTail() tt.FromBeginning = true tt.Files = []string{tmpfile.Name()} p, _ := parsers.NewInfluxParser() tt.SetParser(p) defer tt.Stop() defer tmpfile.Close() acc := testutil.Accumulator{} require.NoError(t, tt.Start(&acc)) _, err = tmpfile.WriteString("cpu,mytag=foo usage_idle=100\n") require.NoError(t, err) require.NoError(t, tt.Gather(&acc)) // arbitrary sleep to wait for message to show up time.Sleep(time.Millisecond * 250) acc.AssertContainsTaggedFields(t, "cpu", map[string]interface{}{ "usage_idle": float64(100), }, map[string]string{ "mytag": "foo", }) }
// in case 'Destination net unreachable' ping app return receive packet which is not what we need // it's not contain valid metric so treat it as lost one func TestTTLExpiredPingGather(t *testing.T) { var acc testutil.Accumulator p := Ping{ Urls: []string{"www.google.com"}, pingHost: mockTTLExpiredPinger, } p.Gather(&acc) tags := map[string]string{"url": "www.google.com"} fields := map[string]interface{}{ "packets_transmitted": 4, "packets_received": 1, "reply_received": 0, "percent_packet_loss": 75.0, "percent_reply_loss": 100.0, } acc.AssertContainsTaggedFields(t, "ping", fields, tags) assert.False(t, acc.HasFloatField("ping", "errors"), "Fatal ping should not have packet measurements") assert.False(t, acc.HasIntField("ping", "average_response_ms"), "Fatal ping should not have packet measurements") assert.False(t, acc.HasIntField("ping", "maximum_response_ms"), "Fatal ping should not have packet measurements") assert.False(t, acc.HasIntField("ping", "minimum_response_ms"), "Fatal ping should not have packet measurements") }
func TestGather(t *testing.T) { duration, _ := time.ParseDuration("1m") internalDuration := internal.Duration{ Duration: duration, } c := &CloudWatch{ Region: "us-east-1", Namespace: "AWS/ELB", Delay: internalDuration, Period: internalDuration, RateLimit: 10, } var acc testutil.Accumulator c.client = &mockCloudWatchClient{} c.Gather(&acc) fields := map[string]interface{}{} fields["latency_minimum"] = 0.1 fields["latency_maximum"] = 0.3 fields["latency_average"] = 0.2 fields["latency_sum"] = 123.0 fields["latency_sample_count"] = 100.0 tags := map[string]string{} tags["unit"] = "seconds" tags["region"] = "us-east-1" tags["load_balancer_name"] = "p-example" assert.True(t, acc.HasMeasurement("cloudwatch_aws_elb")) acc.AssertContainsTaggedFields(t, "cloudwatch_aws_elb", fields, tags) }
func TestBadIntNTPQ(t *testing.T) { tt := tester{ ret: []byte(badIntParseNTPQ), err: nil, } n := &NTPQ{ runQ: tt.runqTest, } acc := testutil.Accumulator{} assert.NoError(t, n.Gather(&acc)) fields := map[string]interface{}{ "when": int64(101), "reach": int64(37), "delay": float64(51.016), "offset": float64(233.010), "jitter": float64(17.462), } tags := map[string]string{ "remote": "uschi5-ntp-002.", "state_prefix": "*", "refid": "10.177.80.46", "stratum": "2", "type": "u", } acc.AssertContainsTaggedFields(t, "ntpq", fields, tags) }
func TestGather(t *testing.T) { c := Chrony{ path: "chronyc", } // overwriting exec commands with mock commands execCommand = fakeExecCommand defer func() { execCommand = exec.Command }() var acc testutil.Accumulator err := c.Gather(&acc) if err != nil { t.Fatal(err) } tags := map[string]string{ "reference_id": "192.168.1.22", "leap_status": "normal", "stratum": "3", } fields := map[string]interface{}{ "last_offset": 0.000012651, "rms_offset": 0.000025577, "frequency": -16.001, "residual_freq": 0.0, "skew": 0.006, "root_delay": 0.001655, "root_dispersion": 0.003307, "update_interval": 507.2, } acc.AssertContainsTaggedFields(t, "chrony", fields, tags) }
func TestZfsPoolMetrics(t *testing.T) { var acc testutil.Accumulator z := &Zfs{ KstatMetrics: []string{"vdev_cache_stats"}, sysctl: mock_sysctl, zpool: mock_zpool, } err := z.Gather(&acc) require.NoError(t, err) require.False(t, acc.HasMeasurement("zfs_pool")) acc.Metrics = nil z = &Zfs{ KstatMetrics: []string{"vdev_cache_stats"}, PoolMetrics: true, sysctl: mock_sysctl, zpool: mock_zpool, } err = z.Gather(&acc) require.NoError(t, err) //one pool, all metrics tags := map[string]string{ "pool": "freenas-boot", "health": "ONLINE", } poolMetrics := getFreeNasBootPoolMetrics() acc.AssertContainsTaggedFields(t, "zfs_pool", poolMetrics, tags) }
func TestRaindropsGeneratesMetrics(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var rsp string if r.URL.Path == "/_raindrops" { rsp = sampleResponse } else { panic("Cannot handle request") } fmt.Fprintln(w, rsp) })) defer ts.Close() n := &Raindrops{ Urls: []string{fmt.Sprintf("%s/_raindrops", ts.URL)}, http_client: &http.Client{Transport: &http.Transport{ ResponseHeaderTimeout: time.Duration(3 * time.Second), }}, } var acc testutil.Accumulator err := n.Gather(&acc) require.NoError(t, err) fields := map[string]interface{}{ "calling": uint64(100), "writing": uint64(200), } addr, err := url.Parse(ts.URL) if err != nil { panic(err) } host, port, err := net.SplitHostPort(addr.Host) if err != nil { host = addr.Host if addr.Scheme == "http" { port = "80" } else if addr.Scheme == "https" { port = "443" } else { port = "" } } tags := map[string]string{"server": host, "port": port} acc.AssertContainsTaggedFields(t, "raindrops", fields, tags) tags = map[string]string{ "port": "8081", "ip": "0.0.0.0", } fields = map[string]interface{}{ "active": uint64(3), "queued": uint64(4), } acc.AssertContainsTaggedFields(t, "raindrops_listen", fields, tags) }
func TestLineProtocolParseMultiple(t *testing.T) { parser, _ := parsers.NewInfluxParser() e := &Exec{ runner: newRunnerMock([]byte(lineProtocolMulti), nil), Commands: []string{"line-protocol"}, parser: parser, } var acc testutil.Accumulator err := e.Gather(&acc) require.NoError(t, err) fields := map[string]interface{}{ "usage_idle": float64(99), "usage_busy": float64(1), } tags := map[string]string{ "host": "foo", "datacenter": "us-east", } cpuTags := []string{"cpu0", "cpu1", "cpu2", "cpu3", "cpu4", "cpu5", "cpu6"} for _, cpu := range cpuTags { tags["cpu"] = cpu acc.AssertContainsTaggedFields(t, "cpu", fields, tags) } }
func TestRunParser(t *testing.T) { log.SetOutput(ioutil.Discard) var testmsg = []byte("cpu_load_short,host=server01 value=12.0 1422568543702900257") listener, in := newTestUdpListener() acc := testutil.Accumulator{} listener.acc = &acc defer close(listener.done) listener.parser, _ = parsers.NewInfluxParser() listener.wg.Add(1) go listener.udpParser() in <- testmsg time.Sleep(time.Millisecond * 25) listener.Gather(&acc) if a := acc.NFields(); a != 1 { t.Errorf("got %v, expected %v", a, 1) } acc.AssertContainsTaggedFields(t, "cpu_load_short", map[string]interface{}{"value": float64(12)}, map[string]string{"host": "server01"}, ) }
func TestInfluxDB(t *testing.T) { fakeInfluxServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/endpoint" { _, _ = w.Write([]byte(influxReturn)) } else { w.WriteHeader(http.StatusNotFound) } })) defer fakeInfluxServer.Close() plugin := &influxdb.InfluxDB{ URLs: []string{fakeInfluxServer.URL + "/endpoint"}, } var acc testutil.Accumulator require.NoError(t, plugin.Gather(&acc)) require.Len(t, acc.Metrics, 34) fields := map[string]interface{}{ "heap_inuse": int64(18046976), "heap_released": int64(3473408), "mspan_inuse": int64(97440), "total_alloc": int64(201739016), "sys": int64(38537464), "mallocs": int64(570251), "frees": int64(381008), "heap_idle": int64(15802368), "pause_total_ns": int64(5132914), "lookups": int64(77), "heap_sys": int64(33849344), "mcache_sys": int64(16384), "next_gc": int64(20843042), "gcc_pu_fraction": float64(4.287178819113636e-05), "other_sys": int64(1229737), "alloc": int64(17034016), "stack_inuse": int64(753664), "stack_sys": int64(753664), "buck_hash_sys": int64(1461583), "gc_sys": int64(1112064), "num_gc": int64(27), "heap_alloc": int64(17034016), "heap_objects": int64(189243), "mspan_sys": int64(114688), "mcache_inuse": int64(4800), "last_gc": int64(1460434886475114239), } tags := map[string]string{ "url": fakeInfluxServer.URL + "/endpoint", } acc.AssertContainsTaggedFields(t, "influxdb_memstats", fields, tags) acc.AssertContainsTaggedFields(t, "influxdb", map[string]interface{}{ "n_shards": 1, }, map[string]string{}) }
func TestWinPerfcountersCollect2(t *testing.T) { var instances = make([]string, 2) var counters = make([]string, 1) var perfobjects = make([]perfobject, 1) objectname := "Processor Information" instances[0] = "_Total" instances[1] = "0,0" counters[0] = "Performance Limit Flags" var measurement string = "test" var warnonmissing bool = false var failonmissing bool = true var includetotal bool = false PerfObject := perfobject{ ObjectName: objectname, Instances: instances, Counters: counters, Measurement: measurement, WarnOnMissing: warnonmissing, FailOnMissing: failonmissing, IncludeTotal: includetotal, } perfobjects[0] = PerfObject m := Win_PerfCounters{PrintValid: false, TestName: "Collect2", Object: perfobjects} var acc testutil.Accumulator err := m.Gather(&acc) require.NoError(t, err) time.Sleep(2000 * time.Millisecond) err = m.Gather(&acc) tags := map[string]string{ "instance": instances[0], "objectname": objectname, } fields := map[string]interface{}{ counters[0]: float32(0), } acc.AssertContainsTaggedFields(t, measurement, fields, tags) tags = map[string]string{ "instance": instances[1], "objectname": objectname, } fields = map[string]interface{}{ counters[0]: float32(0), } acc.AssertContainsTaggedFields(t, measurement, fields, tags) }
func TestHaproxyGeneratesMetricsWithoutAuthentication(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, csvOutputSample) })) defer ts.Close() r := &haproxy{ Servers: []string{ts.URL}, } var acc testutil.Accumulator err := r.Gather(&acc) require.NoError(t, err) tags := map[string]string{ "proxy": "be_app", "server": ts.Listener.Addr().String(), "sv": "host0", } fields := map[string]interface{}{ "active_servers": uint64(1), "backup_servers": uint64(0), "bin": uint64(510913516), "bout": uint64(2193856571), "check_duration": uint64(10), "cli_abort": uint64(73), "ctime": uint64(2), "downtime": uint64(0), "dresp": uint64(0), "econ": uint64(0), "eresp": uint64(1), "http_response.1xx": uint64(0), "http_response.2xx": uint64(119534), "http_response.3xx": uint64(48051), "http_response.4xx": uint64(2345), "http_response.5xx": uint64(1056), "lbtot": uint64(171013), "qcur": uint64(0), "qmax": uint64(0), "qtime": uint64(0), "rate": uint64(3), "rate_max": uint64(12), "rtime": uint64(312), "scur": uint64(1), "smax": uint64(32), "srv_abort": uint64(1), "stot": uint64(171014), "ttime": uint64(2341), "wredis": uint64(0), "wretr": uint64(1), } acc.AssertContainsTaggedFields(t, "haproxy", fields, tags) }
// Test that the proper values are ignored or collected func TestNormalResponse(t *testing.T) { graylog := genMockGrayLog(validJSON, 200) for _, service := range graylog { var acc testutil.Accumulator err := service.Gather(&acc) require.NoError(t, err) for k, v := range expectedFields { acc.AssertContainsTaggedFields(t, k, v, validTags[k]) } } }
func TestRedis_ParseMetrics(t *testing.T) { var acc testutil.Accumulator tags := map[string]string{"host": "redis.net"} rdr := bufio.NewReader(strings.NewReader(testOutput)) err := gatherInfoOutput(rdr, &acc, tags) require.NoError(t, err) tags = map[string]string{"host": "redis.net", "replication_role": "master"} fields := map[string]interface{}{ "uptime": uint64(238), "clients": uint64(1), "used_memory": uint64(1003936), "used_memory_rss": uint64(811008), "used_memory_peak": uint64(1003936), "used_memory_lua": uint64(33792), "rdb_changes_since_last_save": uint64(0), "total_connections_received": uint64(2), "total_commands_processed": uint64(1), "instantaneous_ops_per_sec": uint64(0), "sync_full": uint64(0), "sync_partial_ok": uint64(0), "sync_partial_err": uint64(0), "expired_keys": uint64(0), "evicted_keys": uint64(0), "keyspace_hits": uint64(1), "keyspace_misses": uint64(1), "pubsub_channels": uint64(0), "pubsub_patterns": uint64(0), "latest_fork_usec": uint64(0), "connected_slaves": uint64(0), "master_repl_offset": uint64(0), "repl_backlog_active": uint64(0), "repl_backlog_size": uint64(1048576), "repl_backlog_histlen": uint64(0), "mem_fragmentation_ratio": float64(0.81), "instantaneous_input_kbps": float64(876.16), "instantaneous_output_kbps": float64(3010.23), "used_cpu_sys": float64(0.14), "used_cpu_user": float64(0.05), "used_cpu_sys_children": float64(0.00), "used_cpu_user_children": float64(0.00), "keyspace_hitrate": float64(0.50), } keyspaceTags := map[string]string{"host": "redis.net", "replication_role": "master", "database": "db0"} keyspaceFields := map[string]interface{}{ "avg_ttl": uint64(0), "expires": uint64(0), "keys": uint64(2), } acc.AssertContainsTaggedFields(t, "redis", fields, tags) acc.AssertContainsTaggedFields(t, "redis_keyspace", keyspaceFields, keyspaceTags) }
func TestNginxGeneratesMetrics(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var rsp string if r.URL.Path == "/stub_status" { rsp = sampleResponse } else { panic("Cannot handle request") } fmt.Fprintln(w, rsp) })) defer ts.Close() n := &Nginx{ Urls: []string{fmt.Sprintf("%s/stub_status", ts.URL)}, } var acc testutil.Accumulator err := n.Gather(&acc) require.NoError(t, err) fields := map[string]interface{}{ "active": uint64(585), "accepts": uint64(85340), "handled": uint64(85340), "requests": uint64(35085), "reading": uint64(4), "writing": uint64(135), "waiting": uint64(446), } addr, err := url.Parse(ts.URL) if err != nil { panic(err) } host, port, err := net.SplitHostPort(addr.Host) if err != nil { host = addr.Host if addr.Scheme == "http" { port = "80" } else if addr.Scheme == "https" { port = "443" } else { port = "" } } tags := map[string]string{"server": host, "port": port} acc.AssertContainsTaggedFields(t, "nginx", fields, tags) }
func TestSNMPEasyGet5(t *testing.T) { if testing.Short() { t.Skip("Skipping integration test in short mode") } get1 := Data{ Name: "oid1", Unit: "octets", Oid: "ifSpeed", Instance: "1", } h := Host{ Address: testutil.GetLocalHost() + ":31161", Community: "telegraf", Version: 2, Timeout: 2.0, Retries: 2, Collect: []string{"oid1"}, GetOids: []string{".1.3.6.1.2.1.2.1.0"}, } s := Snmp{ SnmptranslateFile: "./testdata/oids.txt", Host: []Host{h}, Get: []Data{get1}, } var acc testutil.Accumulator err := s.Gather(&acc) require.NoError(t, err) acc.AssertContainsTaggedFields(t, "ifSpeed", map[string]interface{}{ "ifSpeed": uint(10000000), }, map[string]string{ "unit": "octets", "instance": "1", "host": testutil.GetLocalHost(), }, ) acc.AssertContainsTaggedFields(t, "ifNumber", map[string]interface{}{ "ifNumber": int(4), }, map[string]string{ "instance": "0", "host": testutil.GetLocalHost(), }, ) }