Beispiel #1
0
func TestReporter(t *testing.T) {
	want := report.MakeReport()
	want.Container = report.Topology{
		Adjacency:     report.Adjacency{},
		EdgeMetadatas: report.EdgeMetadatas{},
		NodeMetadatas: report.NodeMetadatas{
			report.MakeContainerNodeID("", "ping"): report.NewNodeMetadata(map[string]string{
				docker.ContainerID:   "ping",
				docker.ContainerName: "pong",
				docker.ImageID:       "baz",
			}),
		},
	}
	want.ContainerImage = report.Topology{
		Adjacency:     report.Adjacency{},
		EdgeMetadatas: report.EdgeMetadatas{},
		NodeMetadatas: report.NodeMetadatas{
			report.MakeContainerNodeID("", "baz"): report.NewNodeMetadata(map[string]string{
				docker.ImageID:   "baz",
				docker.ImageName: "bang",
			}),
		},
	}

	reporter := docker.NewReporter(mockRegistryInstance, "")
	have, _ := reporter.Report()
	if !reflect.DeepEqual(want, have) {
		t.Errorf("%s", test.Diff(want, have))
	}
}
Beispiel #2
0
func TestApply(t *testing.T) {
	var (
		endpointNodeID       = "c"
		addressNodeID        = "d"
		endpointNodeMetadata = report.NewNodeMetadata(map[string]string{"5": "6"})
		addressNodeMetadata  = report.NewNodeMetadata(map[string]string{"7": "8"})
	)

	r := report.MakeReport()
	r.Endpoint.NodeMetadatas[endpointNodeID] = endpointNodeMetadata
	r.Address.NodeMetadatas[addressNodeID] = addressNodeMetadata
	r = Apply(r, []Tagger{newTopologyTagger()})

	for _, tuple := range []struct {
		want report.NodeMetadata
		from report.Topology
		via  string
	}{
		{endpointNodeMetadata.Copy().Merge(report.NewNodeMetadata(map[string]string{"topology": "endpoint"})), r.Endpoint, endpointNodeID},
		{addressNodeMetadata.Copy().Merge(report.NewNodeMetadata(map[string]string{"topology": "address"})), r.Address, addressNodeID},
	} {
		if want, have := tuple.want, tuple.from.NodeMetadatas[tuple.via]; !reflect.DeepEqual(want, have) {
			t.Errorf("want %+v, have %+v", want, have)
		}
	}
}
Beispiel #3
0
func TestTagger(t *testing.T) {
	oldProcessTree := docker.NewProcessTreeStub
	defer func() { docker.NewProcessTreeStub = oldProcessTree }()

	docker.NewProcessTreeStub = func(_ process.Walker) (process.Tree, error) {
		return &mockProcessTree{map[int]int{2: 1}}, nil
	}

	var (
		pid1NodeID       = report.MakeProcessNodeID("somehost.com", "1")
		pid2NodeID       = report.MakeProcessNodeID("somehost.com", "2")
		wantNodeMetadata = report.NewNodeMetadata(map[string]string{docker.ContainerID: "ping"})
	)

	input := report.MakeReport()
	input.Process.NodeMetadatas[pid1NodeID] = report.NewNodeMetadata(map[string]string{"pid": "1"})
	input.Process.NodeMetadatas[pid2NodeID] = report.NewNodeMetadata(map[string]string{"pid": "2"})

	want := report.MakeReport()
	want.Process.NodeMetadatas[pid1NodeID] = report.NewNodeMetadata(map[string]string{"pid": "1"}).Merge(wantNodeMetadata)
	want.Process.NodeMetadatas[pid2NodeID] = report.NewNodeMetadata(map[string]string{"pid": "2"}).Merge(wantNodeMetadata)

	tagger := docker.NewTagger(mockRegistryInstance, nil)
	have, err := tagger.Tag(input)
	if err != nil {
		t.Errorf("%v", err)
	}
	if !reflect.DeepEqual(want, have) {
		t.Errorf("%s", test.Diff(want, have))
	}
}
Beispiel #4
0
func TestMerge(t *testing.T) {
	log.SetOutput(ioutil.Discard)

	var (
		p1Addr = "localhost:7888"
		p2Addr = "localhost:7889"
	)

	p1, err := xfer.NewTCPPublisher(p1Addr)
	if err != nil {
		t.Fatal(err)
	}
	defer p1.Close()

	p2, err := xfer.NewTCPPublisher(p2Addr)
	if err != nil {
		t.Fatal(err)
	}
	defer p2.Close()

	batchTime := 100 * time.Millisecond
	c := xfer.NewCollector(batchTime, "id")
	c.Add(p1Addr)
	c.Add(p2Addr)
	defer c.Stop()
	time.Sleep(batchTime / 10) // connect

	k1, k2 := report.MakeHostNodeID("p1"), report.MakeHostNodeID("p2")

	{
		r := report.MakeReport()
		r.Host.NodeMetadatas[k1] = report.NewNodeMetadata(map[string]string{"host_name": "test1"})
		p1.Publish(r)
	}
	{
		r := report.MakeReport()
		r.Host.NodeMetadatas[k2] = report.NewNodeMetadata(map[string]string{"host_name": "test2"})
		p2.Publish(r)
	}

	success := make(chan struct{})
	go func() {
		defer close(success)
		for r := range c.Reports() {
			if r.Host.NodeMetadatas[k1].Metadata["host_name"] != "test1" {
				continue
			}
			if r.Host.NodeMetadatas[k2].Metadata["host_name"] != "test2" {
				continue
			}
			return
		}
	}()

	select {
	case <-success:
	case <-time.After(2 * batchTime):
		t.Errorf("collector didn't capture both reports")
	}
}
Beispiel #5
0
func TestReporter(t *testing.T) {
	walker := &mockWalker{
		processes: []process.Process{
			{PID: 1, PPID: 0, Comm: "init"},
			{PID: 2, PPID: 1, Comm: "bash"},
			{PID: 3, PPID: 1, Comm: "apache", Threads: 2},
			{PID: 4, PPID: 2, Comm: "ping", Cmdline: "ping foo.bar.local"},
		},
	}

	reporter := process.NewReporter(walker, "")
	want := report.MakeReport()
	want.Process = report.Topology{
		Adjacency:     report.Adjacency{},
		EdgeMetadatas: report.EdgeMetadatas{},
		NodeMetadatas: report.NodeMetadatas{
			report.MakeProcessNodeID("", "1"): report.NewNodeMetadata(map[string]string{
				process.PID:     "1",
				process.Comm:    "init",
				process.Cmdline: "",
				process.Threads: "0",
			}),
			report.MakeProcessNodeID("", "2"): report.NewNodeMetadata(map[string]string{
				process.PID:     "2",
				process.Comm:    "bash",
				process.PPID:    "1",
				process.Cmdline: "",
				process.Threads: "0",
			}),
			report.MakeProcessNodeID("", "3"): report.NewNodeMetadata(map[string]string{
				process.PID:     "3",
				process.Comm:    "apache",
				process.PPID:    "1",
				process.Cmdline: "",
				process.Threads: "2",
			}),
			report.MakeProcessNodeID("", "4"): report.NewNodeMetadata(map[string]string{
				process.PID:     "4",
				process.Comm:    "ping",
				process.PPID:    "2",
				process.Cmdline: "ping foo.bar.local",
				process.Threads: "0",
			}),
		},
	}

	have, err := reporter.Report()
	if err != nil || !reflect.DeepEqual(want, have) {
		t.Errorf("%s (%v)", test.Diff(want, have), err)
	}
}
Beispiel #6
0
func TestReportLocalNetworks(t *testing.T) {
	r := report.MakeReport()
	r.Merge(report.Report{Host: report.Topology{NodeMetadatas: report.NodeMetadatas{
		"nonets": report.NewNodeMetadata(map[string]string{}),
		"foo":    report.NewNodeMetadata(map[string]string{host.LocalNetworks: "10.0.0.1/8 192.168.1.1/24 10.0.0.1/8 badnet/33"}),
	}}})
	want := report.Networks([]*net.IPNet{
		mustParseCIDR("10.0.0.1/8"),
		mustParseCIDR("192.168.1.1/24"),
	})
	have := render.LocalNetworks(r)
	if !reflect.DeepEqual(want, have) {
		t.Errorf("%s", test.Diff(want, have))
	}
}
Beispiel #7
0
func (c *mockContainer) GetNodeMetadata() report.NodeMetadata {
	return report.NewNodeMetadata(map[string]string{
		docker.ContainerID:   c.c.ID,
		docker.ContainerName: c.c.Name,
		docker.ImageID:       c.c.Image,
	})
}
Beispiel #8
0
func TestWeaveTaggerOverlayTopology(t *testing.T) {
	s := httptest.NewServer(http.HandlerFunc(mockWeaveRouter))
	defer s.Close()

	w, err := overlay.NewWeave(s.URL)
	if err != nil {
		t.Fatal(err)
	}

	have, err := w.Report()
	if err != nil {
		t.Fatal(err)
	}
	if want, have := (report.Topology{
		Adjacency:     report.Adjacency{},
		EdgeMetadatas: report.EdgeMetadatas{},
		NodeMetadatas: report.NodeMetadatas{
			report.MakeOverlayNodeID(mockWeavePeerName): report.NewNodeMetadata(map[string]string{
				overlay.WeavePeerName:     mockWeavePeerName,
				overlay.WeavePeerNickName: mockWeavePeerNickName,
			}),
		},
	}), have.Overlay; !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}
Beispiel #9
0
// Report implements Reporter.
func (w Weave) Report() (report.Report, error) {
	r := report.MakeReport()

	resp, err := http.Get(w.url)
	if err != nil {
		log.Printf("Weave Tagger: %v", err)
		return r, err
	}
	defer resp.Body.Close()

	var status struct {
		Peers []struct {
			Name     string `json:"Name"`
			NickName string `json:"NickName"`
		} `json:"Peers"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&status); err != nil {
		log.Printf("Weave Tagger: %v", err)
		return r, err
	}

	for _, peer := range status.Peers {
		r.Overlay.NodeMetadatas[report.MakeOverlayNodeID(peer.Name)] = report.NewNodeMetadata(map[string]string{
			WeavePeerName:     peer.Name,
			WeavePeerNickName: peer.NickName,
		})
	}
	return r, nil
}
Beispiel #10
0
func TestTagger(t *testing.T) {
	var (
		hostID         = "foo"
		endpointNodeID = report.MakeEndpointNodeID(hostID, "1.2.3.4", "56789") // hostID ignored
		nodeMetadata   = report.NewNodeMetadata(map[string]string{"foo": "bar"})
	)

	r := report.MakeReport()
	r.Endpoint.NodeMetadatas[endpointNodeID] = nodeMetadata
	want := nodeMetadata.Merge(report.NewNodeMetadata(map[string]string{
		report.HostNodeID: report.MakeHostNodeID(hostID),
	}))
	rpt, _ := host.NewTagger(hostID).Tag(r)
	have := rpt.Endpoint.NodeMetadatas[endpointNodeID].Copy()
	if !reflect.DeepEqual(want, have) {
		t.Error(test.Diff(want, have))
	}
}
Beispiel #11
0
// Tag implements Tagger.
func (t Tagger) Tag(r report.Report) (report.Report, error) {
	md := report.NewNodeMetadata(map[string]string{report.HostNodeID: t.hostNodeID})
	for _, topology := range r.Topologies() {
		for nodeID := range topology.NodeMetadatas {
			topology.NodeMetadatas[nodeID].Merge(md)
		}
	}
	return r, nil
}
Beispiel #12
0
func (r *Reporter) addConnection(rpt *report.Report, c *procspy.Connection) {
	var (
		scopedLocal  = report.MakeAddressNodeID(r.hostID, c.LocalAddress.String())
		scopedRemote = report.MakeAddressNodeID(r.hostID, c.RemoteAddress.String())
		key          = report.MakeAdjacencyID(scopedLocal)
		edgeKey      = report.MakeEdgeID(scopedLocal, scopedRemote)
	)

	rpt.Address.Adjacency[key] = rpt.Address.Adjacency[key].Add(scopedRemote)

	if _, ok := rpt.Address.NodeMetadatas[scopedLocal]; !ok {
		rpt.Address.NodeMetadatas[scopedLocal] = report.NewNodeMetadata(map[string]string{
			docker.Name: r.hostName,
			docker.Addr: c.LocalAddress.String(),
		})
	}

	countTCPConnection(rpt.Address.EdgeMetadatas, edgeKey)

	if c.Proc.PID > 0 {
		var (
			scopedLocal  = report.MakeEndpointNodeID(r.hostID, c.LocalAddress.String(), strconv.Itoa(int(c.LocalPort)))
			scopedRemote = report.MakeEndpointNodeID(r.hostID, c.RemoteAddress.String(), strconv.Itoa(int(c.RemotePort)))
			key          = report.MakeAdjacencyID(scopedLocal)
			edgeKey      = report.MakeEdgeID(scopedLocal, scopedRemote)
		)

		rpt.Endpoint.Adjacency[key] = rpt.Endpoint.Adjacency[key].Add(scopedRemote)

		if _, ok := rpt.Endpoint.NodeMetadatas[scopedLocal]; !ok {
			// First hit establishes NodeMetadata for scoped local address + port
			md := report.NewNodeMetadata(map[string]string{
				"addr": c.LocalAddress.String(),
				"port": strconv.Itoa(int(c.LocalPort)),
				"pid":  fmt.Sprintf("%d", c.Proc.PID),
			})

			rpt.Endpoint.NodeMetadatas[scopedLocal] = md
		}

		countTCPConnection(rpt.Endpoint.EdgeMetadatas, edgeKey)
	}
}
Beispiel #13
0
func TestTagMissingID(t *testing.T) {
	const nodeID = "not-found"
	r := report.MakeReport()
	want := report.NewNodeMetadata(map[string]string{})
	rpt, _ := newTopologyTagger().Tag(r)
	have := rpt.Endpoint.NodeMetadatas[nodeID].Copy()
	if !reflect.DeepEqual(want, have) {
		t.Error("TopologyTagger erroneously tagged a missing node ID")
	}
}
Beispiel #14
0
func TestMapEdge(t *testing.T) {
	selector := func(_ report.Report) report.Topology {
		return report.Topology{
			NodeMetadatas: report.NodeMetadatas{
				"foo": report.NewNodeMetadata(map[string]string{"id": "foo"}),
				"bar": report.NewNodeMetadata(map[string]string{"id": "bar"}),
			},
			Adjacency: report.Adjacency{
				">foo": report.MakeIDList("bar"),
				">bar": report.MakeIDList("foo"),
			},
			EdgeMetadatas: report.EdgeMetadatas{
				"foo|bar": report.EdgeMetadata{WithBytes: true, BytesIngress: 1, BytesEgress: 2},
				"bar|foo": report.EdgeMetadata{WithBytes: true, BytesIngress: 3, BytesEgress: 4},
			},
		}
	}

	identity := func(nmd report.NodeMetadata) (render.RenderableNode, bool) {
		return render.NewRenderableNode(nmd.Metadata["id"], "", "", "", nmd), true
	}

	mapper := render.Map{
		MapFunc: func(nodes render.RenderableNode) (render.RenderableNode, bool) {
			return render.RenderableNode{ID: "_" + nodes.ID}, true
		},
		Renderer: render.LeafMap{
			Selector: selector,
			Mapper:   identity,
			Pseudo:   nil,
		},
	}

	want := render.AggregateMetadata{
		render.KeyBytesIngress: 1,
		render.KeyBytesEgress:  2,
	}
	have := mapper.AggregateMetadata(report.MakeReport(), "_foo", "_bar")
	if !reflect.DeepEqual(want, have) {
		t.Errorf("want %+v, have %+v", want, have)
	}
}
Beispiel #15
0
func newPseudoNode(id, major, minor string) RenderableNode {
	return RenderableNode{
		ID:                id,
		LabelMajor:        major,
		LabelMinor:        minor,
		Rank:              "",
		Pseudo:            true,
		AggregateMetadata: AggregateMetadata{},
		NodeMetadata:      report.NewNodeMetadata(map[string]string{}),
	}
}
Beispiel #16
0
func newDerivedNode(id string, node RenderableNode) RenderableNode {
	return RenderableNode{
		ID:                id,
		LabelMajor:        "",
		LabelMinor:        "",
		Rank:              "",
		Pseudo:            node.Pseudo,
		AggregateMetadata: node.AggregateMetadata,
		Origins:           node.Origins,
		NodeMetadata:      report.NewNodeMetadata(map[string]string{}),
	}
}
Beispiel #17
0
func (c *container) GetNodeMetadata() report.NodeMetadata {
	c.RLock()
	defer c.RUnlock()

	result := report.NewNodeMetadata(map[string]string{
		ContainerID:      c.ID(),
		ContainerName:    strings.TrimPrefix(c.container.Name, "/"),
		ContainerPorts:   c.ports(),
		ContainerCreated: c.container.Created.Format(time.RFC822),
		ContainerCommand: c.container.Path + " " + strings.Join(c.container.Args, " "),
		ImageID:          c.container.Image,
	})

	if c.latestStats == nil {
		return result
	}

	result.Merge(report.NewNodeMetadata(map[string]string{
		NetworkRxDropped: strconv.FormatUint(c.latestStats.Network.RxDropped, 10),
		NetworkRxBytes:   strconv.FormatUint(c.latestStats.Network.RxBytes, 10),
		NetworkRxErrors:  strconv.FormatUint(c.latestStats.Network.RxErrors, 10),
		NetworkTxPackets: strconv.FormatUint(c.latestStats.Network.TxPackets, 10),
		NetworkTxDropped: strconv.FormatUint(c.latestStats.Network.TxDropped, 10),
		NetworkRxPackets: strconv.FormatUint(c.latestStats.Network.RxPackets, 10),
		NetworkTxErrors:  strconv.FormatUint(c.latestStats.Network.TxErrors, 10),
		NetworkTxBytes:   strconv.FormatUint(c.latestStats.Network.TxBytes, 10),

		MemoryMaxUsage: strconv.FormatUint(c.latestStats.MemoryStats.MaxUsage, 10),
		MemoryUsage:    strconv.FormatUint(c.latestStats.MemoryStats.Usage, 10),
		MemoryFailcnt:  strconv.FormatUint(c.latestStats.MemoryStats.Failcnt, 10),
		MemoryLimit:    strconv.FormatUint(c.latestStats.MemoryStats.Limit, 10),

		//		CPUPercpuUsage:       strconv.FormatUint(stats.CPUStats.CPUUsage.PercpuUsage, 10),
		CPUUsageInUsermode:   strconv.FormatUint(c.latestStats.CPUStats.CPUUsage.UsageInUsermode, 10),
		CPUTotalUsage:        strconv.FormatUint(c.latestStats.CPUStats.CPUUsage.TotalUsage, 10),
		CPUUsageInKernelmode: strconv.FormatUint(c.latestStats.CPUStats.CPUUsage.UsageInKernelmode, 10),
		CPUSystemCPUUsage:    strconv.FormatUint(c.latestStats.CPUStats.SystemCPUUsage, 10),
	}))
	return result
}
Beispiel #18
0
// Tag implements Tagger
func (topologyTagger) Tag(r report.Report) (report.Report, error) {
	for val, topology := range map[string]*report.Topology{
		"endpoint":        &(r.Endpoint),
		"address":         &(r.Address),
		"process":         &(r.Process),
		"container":       &(r.Container),
		"container_image": &(r.ContainerImage),
		"host":            &(r.Host),
		"overlay":         &(r.Overlay),
	} {
		md := report.NewNodeMetadata(map[string]string{Topology: val})
		for nodeID := range topology.NodeMetadatas {
			(*topology).NodeMetadatas[nodeID].Merge(md)
		}
	}
	return r, nil
}
Beispiel #19
0
func (r *Reporter) containerImageTopology() report.Topology {
	result := report.NewTopology()

	r.registry.WalkImages(func(image *docker_client.APIImages) {
		nmd := report.NewNodeMetadata(map[string]string{
			ImageID: image.ID,
		})

		if len(image.RepoTags) > 0 {
			nmd.Metadata[ImageName] = image.RepoTags[0]
		}

		nodeID := report.MakeContainerNodeID(r.scope, image.ID)
		result.NodeMetadatas[nodeID] = nmd
	})

	return result
}
Beispiel #20
0
func (r *Reporter) processTopology() (report.Topology, error) {
	t := report.NewTopology()
	err := r.walker.Walk(func(p Process) {
		pidstr := strconv.Itoa(p.PID)
		nodeID := report.MakeProcessNodeID(r.scope, pidstr)
		t.NodeMetadatas[nodeID] = report.NewNodeMetadata(map[string]string{
			PID:     pidstr,
			Comm:    p.Comm,
			Cmdline: p.Cmdline,
			Threads: strconv.Itoa(p.Threads),
		})
		if p.PPID > 0 {
			t.NodeMetadatas[nodeID].Metadata[PPID] = strconv.Itoa(p.PPID)
		}
	})

	return t, err
}
Beispiel #21
0
func (t *Tagger) tag(tree process.Tree, topology *report.Topology) {
	for nodeID, nodeMetadata := range topology.NodeMetadatas {
		pidStr, ok := nodeMetadata.Metadata["pid"]
		if !ok {
			continue
		}

		pid, err := strconv.ParseUint(pidStr, 10, 64)
		if err != nil {
			continue
		}

		var (
			c         Container
			candidate = int(pid)
		)

		t.registry.LockedPIDLookup(func(lookup func(int) Container) {
			for {
				c = lookup(candidate)
				if c != nil {
					break
				}

				candidate, err = tree.GetParent(candidate)
				if err != nil {
					break
				}
			}
		})

		if c == nil {
			continue
		}

		md := report.NewNodeMetadata(map[string]string{
			ContainerID: c.ID(),
		})

		topology.NodeMetadatas[nodeID].Merge(md)
	}
}
Beispiel #22
0
// Report implements Reporter.
func (r *Reporter) Report() (report.Report, error) {
	var (
		rep        = report.MakeReport()
		localCIDRs []string
	)

	localNets, err := InterfaceAddrs()
	if err != nil {
		return rep, err
	}
	for _, localNet := range localNets {
		// Not all networks are IP networks.
		if ipNet, ok := localNet.(*net.IPNet); ok {
			localCIDRs = append(localCIDRs, ipNet.String())
		}
	}

	uptime, err := GetUptime()
	if err != nil {
		return rep, err
	}

	kernel, err := GetKernelVersion()
	if err != nil {
		return rep, err
	}

	rep.Host.NodeMetadatas[report.MakeHostNodeID(r.hostID)] = report.NewNodeMetadata(map[string]string{
		Timestamp:     Now(),
		HostName:      r.hostName,
		LocalNetworks: strings.Join(localCIDRs, " "),
		OS:            runtime.GOOS,
		Load:          GetLoad(),
		KernelVersion: kernel,
		Uptime:        uptime.String(),
	})

	return rep, nil
}
Beispiel #23
0
func TestReporter(t *testing.T) {
	var (
		oldGetKernelVersion = host.GetKernelVersion
		oldGetLoad          = host.GetLoad
		oldGetUptime        = host.GetUptime
		oldInterfaceAddrs   = host.InterfaceAddrs
		oldNow              = host.Now
	)
	defer func() {
		host.GetKernelVersion = oldGetKernelVersion
		host.GetLoad = oldGetLoad
		host.GetUptime = oldGetUptime
		host.InterfaceAddrs = oldInterfaceAddrs
		host.Now = oldNow
	}()
	host.GetKernelVersion = func() (string, error) { return release + " " + version, nil }
	host.GetLoad = func() string { return load }
	host.GetUptime = func() (time.Duration, error) { return time.ParseDuration(uptime) }
	host.Now = func() string { return now }
	host.InterfaceAddrs = func() ([]net.Addr, error) { _, ipnet, _ := net.ParseCIDR(network); return []net.Addr{ipnet}, nil }

	want := report.MakeReport()
	want.Host.NodeMetadatas[report.MakeHostNodeID(hostID)] = report.NewNodeMetadata(map[string]string{
		host.Timestamp:     now,
		host.HostName:      hostname,
		host.LocalNetworks: network,
		host.OS:            runtime.GOOS,
		host.Load:          load,
		host.Uptime:        uptime,
		host.KernelVersion: kernel,
	})
	r := host.NewReporter(hostID, hostname)
	have, _ := r.Report()
	if !reflect.DeepEqual(want, have) {
		t.Errorf("%s", test.Diff(want, have))
	}
}
Beispiel #24
0
	Report = report.Report{
		Endpoint: report.Topology{
			Adjacency: report.Adjacency{
				report.MakeAdjacencyID(Client54001NodeID): report.MakeIDList(Server80NodeID),
				report.MakeAdjacencyID(Client54002NodeID): report.MakeIDList(Server80NodeID),
				report.MakeAdjacencyID(Server80NodeID): report.MakeIDList(
					Client54001NodeID, Client54002NodeID, UnknownClient1NodeID, UnknownClient2NodeID,
					UnknownClient3NodeID, RandomClientNodeID),
			},
			NodeMetadatas: report.NodeMetadatas{
				// NodeMetadata is arbitrary. We're free to put only precisely what we
				// care to test into the fixture. Just be sure to include the bits
				// that the mapping funcs extract :)
				Client54001NodeID: report.NewNodeMetadata(map[string]string{
					"addr":            ClientIP,
					"port":            ClientPort54001,
					"pid":             Client1PID,
					report.HostNodeID: ClientHostNodeID,
				}),
				Client54002NodeID: report.NewNodeMetadata(map[string]string{
					"addr":            ClientIP,
					"port":            ClientPort54002,
					"pid":             Client2PID,
					report.HostNodeID: ClientHostNodeID,
				}),
				Server80NodeID: report.NewNodeMetadata(map[string]string{
					"addr":            ServerIP,
					"port":            ServerPort,
					"pid":             ServerPID,
					report.HostNodeID: ServerHostNodeID,
				}),
			},
Beispiel #25
0
// DemoReport makes up a report.
func DemoReport(nodeCount int) report.Report {
	r := report.MakeReport()

	// Make up some plausible IPv4 numbers
	hosts := []string{}
	ip := [4]int{192, 168, 1, 1}
	for range make([]struct{}, nodeCount) {
		hosts = append(hosts, fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]))
		ip[3]++
		if ip[3] > 200 {
			ip[2]++
			ip[3] = 1
		}
	}
	// Some non-local ones.
	hosts = append(hosts, []string{"1.2.3.4", "2.3.4.5"}...)

	_, localNet, err := net.ParseCIDR("192.168.0.0/16")
	if err != nil {
		panic(err)
	}

	type conn struct {
		srcProc, dstProc string
		dstPort          int
	}
	procPool := []conn{
		{srcProc: "curl", dstPort: 80, dstProc: "apache"},
		{srcProc: "wget", dstPort: 80, dstProc: "apache"},
		{srcProc: "curl", dstPort: 80, dstProc: "nginx"},
		{srcProc: "curl", dstPort: 8080, dstProc: "app1"},
		{srcProc: "nginx", dstPort: 8080, dstProc: "app1"},
		{srcProc: "nginx", dstPort: 8080, dstProc: "app2"},
		{srcProc: "nginx", dstPort: 8080, dstProc: "app3"},
	}
	connectionCount := nodeCount * 2
	for i := 0; i < connectionCount; i++ {
		var (
			c                = procPool[rand.Intn(len(procPool))]
			src              = hosts[rand.Intn(len(hosts))]
			dst              = hosts[rand.Intn(len(hosts))]
			srcPort          = rand.Intn(50000) + 10000
			srcPortID        = report.MakeEndpointNodeID("", src, strconv.Itoa(srcPort))
			dstPortID        = report.MakeEndpointNodeID("", dst, strconv.Itoa(c.dstPort))
			srcID            = report.MakeAdjacencyID(srcPortID)
			dstID            = report.MakeAdjacencyID(dstPortID)
			srcAddressID     = report.MakeAddressNodeID("", src)
			dstAddressID     = report.MakeAddressNodeID("", dst)
			nodeSrcAddressID = report.MakeAdjacencyID(srcAddressID)
			nodeDstAddressID = report.MakeAdjacencyID(dstAddressID)
		)

		// Endpoint topology
		if _, ok := r.Endpoint.NodeMetadatas[srcPortID]; !ok {
			r.Endpoint.NodeMetadatas[srcPortID] = report.NewNodeMetadata(map[string]string{
				docker.PID:    "4000",
				docker.Name:   c.srcProc,
				docker.Domain: "node-" + src,
			})
		}
		r.Endpoint.Adjacency[srcID] = r.Endpoint.Adjacency[srcID].Add(dstPortID)
		if _, ok := r.Endpoint.NodeMetadatas[dstPortID]; !ok {
			r.Endpoint.NodeMetadatas[dstPortID] = report.NewNodeMetadata(map[string]string{
				docker.PID:    "4000",
				docker.Name:   c.dstProc,
				docker.Domain: "node-" + dst,
			})
		}
		r.Endpoint.Adjacency[dstID] = r.Endpoint.Adjacency[dstID].Add(srcPortID)
		var (
			edgeKeyEgress  = report.MakeEdgeID(srcPortID, dstPortID)
			edgeKeyIngress = report.MakeEdgeID(dstPortID, srcPortID)
		)
		r.Endpoint.EdgeMetadatas[edgeKeyEgress] = report.EdgeMetadata{
			WithConnCountTCP: true,
			MaxConnCountTCP:  uint(rand.Intn(100) + 10),
		}
		r.Endpoint.EdgeMetadatas[edgeKeyIngress] = report.EdgeMetadata{
			WithConnCountTCP: true,
			MaxConnCountTCP:  uint(rand.Intn(100) + 10),
		}

		// Address topology
		if _, ok := r.Address.NodeMetadatas[srcAddressID]; !ok {
			r.Address.NodeMetadatas[srcAddressID] = report.NewNodeMetadata(map[string]string{
				docker.Name: src,
			})
		}
		r.Address.Adjacency[nodeSrcAddressID] = r.Address.Adjacency[nodeSrcAddressID].Add(dstAddressID)
		if _, ok := r.Address.NodeMetadatas[dstAddressID]; !ok {
			r.Address.NodeMetadatas[dstAddressID] = report.NewNodeMetadata(map[string]string{
				docker.Name: dst,
			})
		}
		r.Address.Adjacency[nodeDstAddressID] = r.Address.Adjacency[nodeDstAddressID].Add(srcAddressID)

		// Host data
		r.Host.NodeMetadatas["hostX"] = report.NewNodeMetadata(map[string]string{
			"ts":             time.Now().UTC().Format(time.RFC3339Nano),
			"host_name":      "host-x",
			"local_networks": localNet.String(),
			"os":             "linux",
		})
	}

	return r
}