func TestHANAPublish(t *testing.T) {
	var buf bytes.Buffer
	metrics := []plugin.PluginMetricType{
		*plugin.NewPluginMetricType([]string{"test_string"}, time.Now(), "", "example_string"),
		*plugin.NewPluginMetricType([]string{"test_int"}, time.Now(), "", 1),
		*plugin.NewPluginMetricType([]string{"test_string_slice"}, time.Now(), "", []string{"str1", "str2"}),
		*plugin.NewPluginMetricType([]string{"test_string_slice"}, time.Now(), "", []int{1, 2}),
		*plugin.NewPluginMetricType([]string{"test_uint8"}, time.Now(), "", uint8(1)),
	}
	config := make(map[string]ctypes.ConfigValue)
	enc := gob.NewEncoder(&buf)
	enc.Encode(metrics)

	Convey("TestHANAPublish", t, func() {
		config["username"] = ctypes.ConfigValueStr{Value: "root"}
		config["password"] = ctypes.ConfigValueStr{Value: "root"}
		config["database"] = ctypes.ConfigValueStr{Value: "SNAP_TEST"}
		config["host"] = ctypes.ConfigValueStr{Value: "localhost"}
		config["port"] = ctypes.ConfigValueStr{Value: "1433"}
		config["table name"] = ctypes.ConfigValueStr{Value: "info"}
		sp := NewHANAPublisher()
		cp, _ := sp.GetConfigPolicy()
		cfg, _ := cp.Get([]string{""}).Process(config)
		err := sp.Publish("", buf.Bytes(), *cfg)
		Convey("So not passing in a content type should result in an error", func() {
			So(err, ShouldResemble, errors.New("Unknown content type ''"))
		})
		err = sp.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
		Convey("So publishing metrics should not result in an error", func() {
			So(err, ShouldBeNil)
		})
	})
}
// integration test
func TestRiemannPublish(t *testing.T) {
	// This integration test requires a Riemann Server
	broker := os.Getenv("SNAP_TEST_RIEMANN")
	if broker == "" {
		fmt.Println("Skipping integration tests")
		return
	}

	var buf bytes.Buffer
	buf.Reset()
	r := NewRiemannPublisher()
	config := make(map[string]ctypes.ConfigValue)
	config["broker"] = ctypes.ConfigValueStr{Value: broker}
	cp, _ := r.GetConfigPolicy()
	cfg, _ := cp.Get([]string{""}).Process(config)
	metrics := []plugin.PluginMetricType{
		*plugin.NewPluginMetricType([]string{"intel", "cpu", "temp"}, time.Now(), "bacon-powered", nil, nil, 100),
	}
	enc := gob.NewEncoder(&buf)
	enc.Encode(metrics)
	err := r.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
	Convey("Publish metric to Riemann", t, func() {
		Convey("So err should not be returned", func() {
			So(err, ShouldBeNil)
		})
		Convey("So metric retrieved equals metric published", func() {
			c, _ := raidman.Dial("tcp", broker)
			events, _ := c.Query("host = \"bacon-powered\"")
			So(len(events), ShouldBeGreaterThan, 0)
		})
	})
}
func TestPostgreSQLPublish(t *testing.T) {
	var buf bytes.Buffer
	//mock.ExpectBegin()
	expTime := time.Now()
	metrics := []plugin.PluginMetricType{
		*plugin.NewPluginMetricType([]string{"test_string"}, expTime, "", nil, nil, "example_string"),
		*plugin.NewPluginMetricType([]string{"test_int"}, expTime, "", nil, nil, 1),
		*plugin.NewPluginMetricType([]string{"test_int"}, expTime, "", nil, nil, true),
		*plugin.NewPluginMetricType([]string{"test_float"}, expTime, "", nil, nil, 1.12),
		*plugin.NewPluginMetricType([]string{"test_string_slice"}, expTime, "", nil, nil, []string{"str1", "str2"}),
		*plugin.NewPluginMetricType([]string{"test_string_slice"}, expTime, "", nil, nil, []int{1, 2}),
		*plugin.NewPluginMetricType([]string{"test_uint8"}, expTime, "", nil, nil, uint8(1)),
	}
	config := make(map[string]ctypes.ConfigValue)
	enc := gob.NewEncoder(&buf)
	enc.Encode(metrics)

	Convey("TestPostgreSQLPublish", t, func() {
		config["hostname"] = ctypes.ConfigValueStr{Value: "localhost"}
		config["port"] = ctypes.ConfigValueInt{Value: 5432}
		config["username"] = ctypes.ConfigValueStr{Value: "postgres"}
		config["password"] = ctypes.ConfigValueStr{Value: ""}
		config["database"] = ctypes.ConfigValueStr{Value: "snap_test"}
		config["table_name"] = ctypes.ConfigValueStr{Value: "info"}
		sp := NewPostgreSQLPublisher()
		So(sp, ShouldNotBeNil)
		err := sp.Publish("", buf.Bytes(), config)
		So(err, ShouldResemble, errors.New("Unknown content type ''"))
		err = sp.Publish(plugin.SnapGOBContentType, buf.Bytes(), config)
		meta := Meta()
		So(meta, ShouldNotBeNil)
	})
}
Ejemplo n.º 4
0
func TestPublishMetrics(t *testing.T) {
	Convey("Given an available file publisher plugin", t, func() {
		// adjust HB timeouts for test
		plugin.PingTimeoutLimit = 1
		plugin.PingTimeoutDurationDefault = time.Second * 1

		// Create controller
		config := NewConfig()
		c := New(OptSetConfig(config))
		lpe := newListenToPluginEvent()
		c.eventManager.RegisterHandler("TestPublishMetrics", lpe)
		c.pluginRunner.(*runner).monitor.duration = time.Millisecond * 100
		c.Start()
		time.Sleep(1 * time.Second)

		// Load plugin
		_, err := load(c, path.Join(SnapPath, "plugin", "snap-publisher-file"))
		<-lpe.done
		So(err, ShouldBeNil)
		So(len(c.pluginManager.all()), ShouldEqual, 1)
		lp, err2 := c.pluginManager.get("publisher:file:3")
		So(err2, ShouldBeNil)
		So(lp.Name(), ShouldResemble, "file")
		So(lp.ConfigPolicy, ShouldNotBeNil)

		Convey("Subscribe to file publisher with good config", func() {
			n := cdata.NewNode()
			config.Plugins.Publisher.Plugins[lp.Name()] = newPluginConfigItem(optAddPluginConfigItem("file", ctypes.ConfigValueStr{Value: "/tmp/snap-TestPublishMetrics.out"}))
			pool, errp := c.pluginRunner.AvailablePlugins().getOrCreatePool("publisher:file:3")
			So(errp, ShouldBeNil)
			pool.subscribe("1", unboundSubscriptionType)
			err := c.pluginRunner.runPlugin(lp.Details)
			So(err, ShouldBeNil)
			time.Sleep(2500 * time.Millisecond)

			Convey("Publish to file", func() {
				metrics := []plugin.PluginMetricType{
					*plugin.NewPluginMetricType([]string{"foo"}, time.Now(), "", nil, nil, 1),
				}
				var buf bytes.Buffer
				enc := gob.NewEncoder(&buf)
				enc.Encode(metrics)
				contentType := plugin.SnapGOBContentType
				errs := c.PublishMetrics(contentType, buf.Bytes(), "file", 3, n.Table())
				So(errs, ShouldBeNil)
				ap := c.AvailablePlugins()
				So(ap, ShouldNotBeEmpty)
			})
		})
		c.Stop()
		time.Sleep(100 * time.Millisecond)

	})
}
func TestOpentsdbPublish(t *testing.T) {
	config := make(map[string]ctypes.ConfigValue)

	Convey("Snap Plugin integration testing with OpenTSDB", t, func() {
		var buf bytes.Buffer
		buf.Reset()
		enc := gob.NewEncoder(&buf)

		config["host"] = ctypes.ConfigValueStr{Value: os.Getenv("SNAP_OPENTSDB_HOST")}
		config["port"] = ctypes.ConfigValueInt{Value: 4242}

		op := NewOpentsdbPublisher()
		cp, _ := op.GetConfigPolicy()
		cfg, _ := cp.Get([]string{""}).Process(config)

		Convey("Publish float metrics to OpenTSDB", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"/psutil/load/load15"}, time.Now(), "mac1", nil, nil, 23.1),
				*plugin.NewPluginMetricType([]string{"/psutil/vm/available"}, time.Now().Add(2*time.Second), "mac2", nil, nil, 23.2),
				*plugin.NewPluginMetricType([]string{"/psutil/load/load1"}, time.Now().Add(3*time.Second), "linux3", nil, nil, 23.3),
			}
			enc.Encode(metrics)

			err := op.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

		Convey("Publish int metrics to OpenTSDB", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"/psutil/vm/free"}, time.Now().Add(5*time.Second), "linux7", nil, nil, 23),
			}
			enc.Encode(metrics)

			err := op.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})
	})
}
func TestMySQLPublish(t *testing.T) {
	var buf bytes.Buffer
	metrics := []plugin.PluginMetricType{
		*plugin.NewPluginMetricType([]string{"test", "string"}, time.Now(), "127.0.0.1", nil, nil, "example_string"),
		*plugin.NewPluginMetricType([]string{"test", "int"}, time.Now(), "127.0.0.1", nil, nil, 1),
		*plugin.NewPluginMetricType([]string{"test", "string", "slice"}, time.Now(), "localhost", nil, nil, []string{"str1", "str2"}),
		*plugin.NewPluginMetricType([]string{"test", "string", "slice"}, time.Now(), "localhost", nil, nil, []int{1, 2}),
	}
	config := make(map[string]ctypes.ConfigValue)
	enc := gob.NewEncoder(&buf)
	enc.Encode(metrics)
	config["username"] = ctypes.ConfigValueStr{Value: "root"}
	config["password"] = ctypes.ConfigValueStr{Value: ""}
	config["database"] = ctypes.ConfigValueStr{Value: "snap_test"}
	config["tablename"] = ctypes.ConfigValueStr{Value: "info"}
	mp := NewMySQLPublisher()
	cp, _ := mp.GetConfigPolicy()
	cfg, _ := cp.Get([]string{""}).Process(config)
	Convey("Publish metrics to MySQL instance should succeed and not throw an error", t, func() {
		err := mp.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
		So(err, ShouldBeNil)
	})
}
// Collect collects metrics from external binary a returns them in form
// acceptable by Snap, only returns collects that were asked for and return nothing when asked for none
// the order of requested and received metrics isn't guaranted
func (f *Facter) CollectMetrics(metricTypes []plugin.PluginMetricType) ([]plugin.PluginMetricType, error) {

	// parse and check requested names of metrics
	names := []string{}
	for _, metricType := range metricTypes {
		namespace := metricType.Namespace()

		err := validateNamespace(namespace)
		if err != nil {
			return nil, err
		}

		// name of fact - last part of namespace
		name := namespace[2]
		names = append(names, name)
	}

	if len(names) == 0 {
		// nothing request, none returned
		// !because returned by value, it would return nil slice
		return nil, nil
	}

	// facts composed of entries
	facts, err := f.getFacts(names, f.facterTimeout, nil)
	if err != nil {
		return nil, err
	}

	// make sure that recevied len of names equals asked
	if len(facts) != len(names) {
		return nil, errors.New("assertion: getFacts returns more/less than asked!")
	}

	host, _ := os.Hostname()
	// convert facts into PluginMetrics
	metrics := make([]plugin.PluginMetricType, 0, len(facts))
	for name, value := range facts {
		namespace := createNamespace(name)
		metric := *plugin.NewPluginMetricType(namespace, time.Now(), host, nil, nil, value)
		metrics = append(metrics, metric)
	}
	return metrics, nil
}
Ejemplo n.º 8
0
func (m *mockCollectorProxy) CollectMetrics(args []byte, reply *[]byte) error {
	rand.Seed(time.Now().Unix())
	var dargs plugin.CollectMetricsArgs
	err := m.e.Decode(args, &dargs)
	if err != nil {
		return err
	}
	var mts []plugin.PluginMetricType
	for _, i := range dargs.PluginMetricTypes {
		p := plugin.NewPluginMetricType(i.Namespace(), time.Now(), "", nil, nil, rand.Intn(100))
		p.Config_ = i.Config()
		mts = append(mts, *p)
	}
	cmr := &plugin.CollectMetricsReply{PluginMetrics: mts}
	*reply, err = m.e.Encode(cmr)
	if err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 9
0
func TestFilePublish(t *testing.T) {
	var buf bytes.Buffer
	metrics := []plugin.PluginMetricType{
		*plugin.NewPluginMetricType([]string{"foo"}, time.Now(), "", nil, nil, 99),
	}
	config := make(map[string]ctypes.ConfigValue)
	enc := gob.NewEncoder(&buf)
	enc.Encode(metrics)

	Convey("TestFilePublish", t, func() {
		config["file"] = ctypes.ConfigValueStr{Value: "/tmp/pub.out"}
		fp := NewFilePublisher()
		So(fp, ShouldNotBeNil)
		err := fp.Publish("", buf.Bytes(), config)
		So(err, ShouldResemble, errors.New("Unknown content type ''"))
		err = fp.Publish(plugin.SnapGOBContentType, buf.Bytes(), config)
		So(err, ShouldBeNil)
		_, err = os.Stat(config["file"].(ctypes.ConfigValueStr).Value)
		So(err, ShouldBeNil)
		meta := Meta()
		So(meta, ShouldNotBeNil)
	})
}
func TestInfluxPublish(t *testing.T) {
	config := make(map[string]ctypes.ConfigValue)

	Convey("snap plugin InfluxDB integration testing with Influx", t, func() {
		var buf bytes.Buffer

		config["host"] = ctypes.ConfigValueStr{Value: os.Getenv("SNAP_INFLUXDB_HOST")}
		config["port"] = ctypes.ConfigValueInt{Value: 8086}
		config["user"] = ctypes.ConfigValueStr{Value: "root"}
		config["password"] = ctypes.ConfigValueStr{Value: "root"}
		config["database"] = ctypes.ConfigValueStr{Value: "test"}
		config["debug"] = ctypes.ConfigValueBool{Value: false}
		config["log-level"] = ctypes.ConfigValueStr{Value: "debug"}

		ip := NewInfluxPublisher()
		cp, _ := ip.GetConfigPolicy()
		cfg, _ := cp.Get([]string{""}).Process(config)
		tags := map[string]string{"zone": "red"}
		labels := []core.Label{}

		Convey("Publish integer metric", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"foo"}, time.Now(), "127.0.0.1", tags, labels, 99),
			}
			buf.Reset()
			enc := gob.NewEncoder(&buf)
			enc.Encode(metrics)
			err := ip.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

		Convey("Publish float metric", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"bar"}, time.Now(), "127.0.0.1", tags, labels, 3.141),
			}
			buf.Reset()
			enc := gob.NewEncoder(&buf)
			enc.Encode(metrics)
			err := ip.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

		Convey("Publish string metric", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"qux"}, time.Now(), "127.0.0.1", tags, labels, "bar"),
			}
			buf.Reset()
			enc := gob.NewEncoder(&buf)
			enc.Encode(metrics)
			err := ip.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

		Convey("Publish boolean metric", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"baz"}, time.Now(), "127.0.0.1", tags, labels, true),
			}
			buf.Reset()
			enc := gob.NewEncoder(&buf)
			enc.Encode(metrics)
			err := ip.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

		Convey("Publish multiple metrics", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"foo"}, time.Now(), "127.0.0.1", tags, labels, 101),
				*plugin.NewPluginMetricType([]string{"bar"}, time.Now(), "127.0.0.1", tags, labels, 5.789),
			}
			buf.Reset()
			enc := gob.NewEncoder(&buf)
			enc.Encode(metrics)
			err := ip.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

	})
}
Ejemplo n.º 11
0
func TestHTTPJSONRPC(t *testing.T) {
	log.SetLevel(log.DebugLevel)
	addr, session := startHTTPJSONRPC()
	time.Sleep(time.Millisecond * 100)

	Convey("Collector Client", t, func() {
		session.c = true
		c, err := NewCollectorHttpJSONRPCClient(fmt.Sprintf("http://%v", addr), 1*time.Second, &key.PublicKey, true)
		So(err, ShouldBeNil)
		So(c, ShouldNotBeNil)
		cl := c.(*httpJSONRPCClient)
		cl.encrypter.Key = symkey

		Convey("Ping", func() {
			err := c.Ping()
			So(err, ShouldBeNil)
		})

		Convey("Kill", func() {
			err := c.Kill("somereason")
			So(err, ShouldBeNil)
		})

		Convey("GetMetricTypes", func() {
			cfg := plugin.NewPluginConfigType()
			cfg.AddItem("test", ctypes.ConfigValueBool{Value: true})
			mts, err := c.GetMetricTypes(cfg)
			So(err, ShouldBeNil)
			So(mts, ShouldNotBeNil)
			So(mts, ShouldHaveSameTypeAs, []core.Metric{})
			So(len(mts), ShouldBeGreaterThan, 0)
			So(len(mts[0].Config().Table()), ShouldBeGreaterThan, 0)
		})

		Convey("CollectMetrics provided a valid config", func() {
			cdn := cdata.NewNode()
			cdn.AddItem("someInt", ctypes.ConfigValueInt{Value: 1})
			cdn.AddItem("password", ctypes.ConfigValueStr{Value: "secure"})

			time.Sleep(500 * time.Millisecond)
			mts, err := c.CollectMetrics([]core.Metric{
				&plugin.PluginMetricType{
					Namespace_: []string{"foo", "bar"},
					Config_:    cdn,
				},
			})
			So(err, ShouldBeNil)
			So(mts, ShouldNotBeNil)
			So(mts, ShouldHaveSameTypeAs, []core.Metric{})
			So(len(mts), ShouldBeGreaterThan, 0)
			So(mts[0].Config().Table(), ShouldNotBeEmpty)
			So(mts[0].Config().Table()["someInt"].Type(), ShouldResemble, "integer")

			Convey("Get and process the ConfigPolicy", func() {
				cp, err := c.GetConfigPolicy()
				So(err, ShouldBeNil)
				So(cp, ShouldNotBeNil)
				So(cp.Get([]string{"foo", "bar"}), ShouldNotBeNil)
				node := cp.Get([]string{"foo", "bar"})
				So(node, ShouldNotBeNil)
				cpn, cserrs := node.Process(mts[0].Config().Table())
				So(cpn, ShouldNotBeNil)
				So((*cpn)["somefloat"].Type(), ShouldResemble, "float")
				So((*cpn)["somefloat"].(*ctypes.ConfigValueFloat).Value, ShouldResemble, 3.14)
				So(cserrs.Errors(), ShouldBeEmpty)
			})
		})

		Convey("CollectMetrics provided an invalid config", func() {
			cdn := cdata.NewNode()
			cdn.AddItem("someInt", ctypes.ConfigValueInt{Value: 1})

			time.Sleep(500 * time.Millisecond)
			mts, err := c.CollectMetrics([]core.Metric{
				&plugin.PluginMetricType{
					Namespace_: []string{"foo", "bar"},
					Config_:    cdn,
				},
			})
			So(err, ShouldBeNil)
			So(mts, ShouldNotBeNil)
			So(mts, ShouldHaveSameTypeAs, []core.Metric{})
			So(len(mts), ShouldBeGreaterThan, 0)
			So(mts[0].Config().Table(), ShouldNotBeEmpty)
			So(mts[0].Config().Table()["someInt"].Type(), ShouldResemble, "integer")

			Convey("Get and process the ConfigPolicy", func() {
				cp, err := c.GetConfigPolicy()
				So(err, ShouldBeNil)
				So(cp, ShouldNotBeNil)
				node := cp.Get([]string{"foo", "bar"})
				So(node, ShouldNotBeNil)
				So(err, ShouldBeNil)
				_, cserrs := node.Process(mts[0].Config().Table())
				//So(cpn, ShouldBeNil)
				So(cserrs.Errors(), ShouldNotBeEmpty)
				So(len(cserrs.Errors()), ShouldEqual, 1)
				So(cserrs.Errors()[0].Error(), ShouldContainSubstring, "password")
			})
		})
	})

	Convey("Processor Client", t, func() {
		session.c = false
		p, _ := NewProcessorHttpJSONRPCClient(fmt.Sprintf("http://%v", addr), 1*time.Second, &key.PublicKey, true)
		cl := p.(*httpJSONRPCClient)
		cl.encrypter.Key = symkey
		So(p, ShouldNotBeNil)

		Convey("GetConfigPolicy", func() {
			cp, err := p.GetConfigPolicy()
			So(err, ShouldBeNil)
			So(cp, ShouldNotBeNil)
			cp_ := cpolicy.New()
			cpn_ := cpolicy.NewPolicyNode()
			r1, err := cpolicy.NewIntegerRule("SomeRequiredInt", true, 1)
			r2, _ := cpolicy.NewStringRule("password", true)
			r3, _ := cpolicy.NewFloatRule("somefloat", false, 3.14)
			So(err, ShouldBeNil)
			cpn_.Add(r1, r2, r3)
			cp_.Add([]string{""}, cpn_)
			cpjson, _ := cp.MarshalJSON()
			cp_json, _ := cp_.MarshalJSON()
			So(string(cpjson), ShouldResemble, string(cp_json))
		})

		Convey("Process metrics", func() {
			pmt := plugin.NewPluginMetricType([]string{"foo", "bar"}, time.Now(), "", nil, nil, 1)
			b, _ := json.Marshal([]plugin.PluginMetricType{*pmt})
			contentType, content, err := p.Process(plugin.SnapJSONContentType, b, nil)
			So(contentType, ShouldResemble, plugin.SnapJSONContentType)
			So(content, ShouldNotBeNil)
			So(err, ShouldEqual, nil)
			var pmts []plugin.PluginMetricType
			err = json.Unmarshal(content, &pmts)
			So(err, ShouldBeNil)
			So(len(pmts), ShouldEqual, 1)
			So(pmts[0].Data(), ShouldEqual, 1)
			So(pmts[0].Namespace(), ShouldResemble, []string{"foo", "bar"})
		})
	})

	Convey("Publisher Client", t, func() {
		session.c = false
		p, _ := NewPublisherHttpJSONRPCClient(fmt.Sprintf("http://%v", addr), 1*time.Second, &key.PublicKey, true)
		cl := p.(*httpJSONRPCClient)
		cl.encrypter.Key = symkey
		So(p, ShouldNotBeNil)

		Convey("GetConfigPolicy", func() {
			cp, err := p.GetConfigPolicy()
			So(err, ShouldBeNil)
			So(cp, ShouldNotBeNil)
			cp_ := cpolicy.New()
			cpn_ := cpolicy.NewPolicyNode()
			r1, err := cpolicy.NewIntegerRule("SomeRequiredInt", true, 1)
			r2, _ := cpolicy.NewStringRule("password", true)
			r3, _ := cpolicy.NewFloatRule("somefloat", false, 3.14)
			So(err, ShouldBeNil)
			cpn_.Add(r1, r2, r3)
			cp_.Add([]string{""}, cpn_)
			cpjson, _ := cp.MarshalJSON()
			cp_json, _ := cp_.MarshalJSON()
			So(string(cpjson), ShouldResemble, string(cp_json))
		})

		Convey("Publish metrics", func() {
			pmt := plugin.NewPluginMetricType([]string{"foo", "bar"}, time.Now(), "", nil, nil, 1)
			b, _ := json.Marshal([]plugin.PluginMetricType{*pmt})
			err := p.Publish(plugin.SnapJSONContentType, b, nil)
			So(err, ShouldBeNil)
		})

	})
}
Ejemplo n.º 12
0
func TestProcessMetrics(t *testing.T) {
	Convey("Given an available file processor plugin", t, func() {
		// adjust HB timeouts for test
		plugin.PingTimeoutLimit = 1
		plugin.PingTimeoutDurationDefault = time.Second * 1

		// Create controller
		c := New()
		lpe := newListenToPluginEvent()
		c.eventManager.RegisterHandler("TestProcessMetrics", lpe)
		c.pluginRunner.(*runner).monitor.duration = time.Millisecond * 100
		c.Start()
		time.Sleep(1 * time.Second)
		c.Config.Plugins.Processor.Plugins["passthru"] = newPluginConfigItem(optAddPluginConfigItem("test", ctypes.ConfigValueBool{Value: true}))

		// Load plugin
		_, err := load(c, path.Join(SnapPath, "plugin", "snap-processor-passthru"))
		<-lpe.done
		So(err, ShouldBeNil)
		So(len(c.pluginManager.all()), ShouldEqual, 1)
		lp, err2 := c.pluginManager.get("processor:passthru:1")
		So(err2, ShouldBeNil)
		So(lp.Name(), ShouldResemble, "passthru")
		So(lp.ConfigPolicy, ShouldNotBeNil)

		Convey("Subscribe to passthru processor with good config", func() {
			n := cdata.NewNode()
			pool, errp := c.pluginRunner.AvailablePlugins().getOrCreatePool("processor:passthru:1")
			So(errp, ShouldBeNil)
			pool.subscribe("1", unboundSubscriptionType)
			err := c.pluginRunner.runPlugin(lp.Details)
			So(err, ShouldBeNil)
			time.Sleep(2500 * time.Millisecond)

			Convey("process metrics", func() {
				metrics := []plugin.PluginMetricType{
					*plugin.NewPluginMetricType([]string{"foo"}, time.Now(), "", nil, nil, 1),
				}
				var buf bytes.Buffer
				enc := gob.NewEncoder(&buf)
				enc.Encode(metrics)
				contentType := plugin.SnapGOBContentType
				_, ct, errs := c.ProcessMetrics(contentType, buf.Bytes(), "passthru", 1, n.Table())
				So(errs, ShouldBeEmpty)
				mts := []plugin.PluginMetricType{}
				dec := gob.NewDecoder(bytes.NewBuffer(ct))
				err := dec.Decode(&mts)
				So(err, ShouldBeNil)
				So(mts[0].Data_, ShouldEqual, 2)
				So(errs, ShouldBeNil)
			})
		})

		Convey("Count()", func() {
			pmt := &pluginMetricTypes{}
			count := pmt.Count()
			So(count, ShouldResemble, 0)

		})
		c.Stop()
		time.Sleep(100 * time.Millisecond)

	})
}
func TestPostgresPublish(t *testing.T) {
	config := make(map[string]ctypes.ConfigValue)

	Convey("Snap Plugin PostgreSQL integration testing with PostgreSQL", t, func() {
		var buf bytes.Buffer

		config["hostname"] = ctypes.ConfigValueStr{Value: os.Getenv("SNAP_POSTGRESQL_HOST")}
		config["port"] = ctypes.ConfigValueInt{Value: 5432}
		config["username"] = ctypes.ConfigValueStr{Value: "postgres"}
		config["password"] = ctypes.ConfigValueStr{Value: ""}
		config["database"] = ctypes.ConfigValueStr{Value: "snap_test"}
		config["table_name"] = ctypes.ConfigValueStr{Value: "info"}

		ip := NewPostgreSQLPublisher()
		cp, _ := ip.GetConfigPolicy()
		cfg, _ := cp.Get([]string{""}).Process(config)

		Convey("Publish integer metric", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"foo"}, time.Now(), "", nil, nil, 99),
			}
			buf.Reset()
			enc := gob.NewEncoder(&buf)
			enc.Encode(metrics)
			err := ip.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

		Convey("Publish float metric", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"bar"}, time.Now(), "", nil, nil, 3.141),
			}
			buf.Reset()
			enc := gob.NewEncoder(&buf)
			enc.Encode(metrics)
			err := ip.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

		Convey("Publish string metric", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"qux"}, time.Now(), "", nil, nil, "bar"),
			}
			buf.Reset()
			enc := gob.NewEncoder(&buf)
			enc.Encode(metrics)
			err := ip.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

		Convey("Publish boolean metric", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"baz"}, time.Now(), "", nil, nil, true),
			}
			buf.Reset()
			enc := gob.NewEncoder(&buf)
			enc.Encode(metrics)
			err := ip.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

		Convey("Publish multiple metrics", func() {
			metrics := []plugin.PluginMetricType{
				*plugin.NewPluginMetricType([]string{"foo"}, time.Now(), "", nil, nil, 101),
				*plugin.NewPluginMetricType([]string{"bar"}, time.Now(), "", nil, nil, 5.789),
			}
			buf.Reset()
			enc := gob.NewEncoder(&buf)
			enc.Encode(metrics)
			err := ip.Publish(plugin.SnapGOBContentType, buf.Bytes(), *cfg)
			So(err, ShouldBeNil)
		})

	})
}