Exemplo n.º 1
1
func main() {
	var t toscalib.ServiceTemplateDefinition
	err := t.Parse(os.Stdin)
	if err != nil {
		log.Fatal(err)
	}
	// Creates a new graph
	g := gographviz.NewGraph()
	g.AddAttr("", "rankdir", "LR")
	g.SetName("G")
	g.SetDir(true)
	e := toscaexec.GeneratePlaybook(t)
	for i, p := range e.Index {
		g.AddNode("G", fmt.Sprintf("%v", i),
			map[string]string{
				"id":    fmt.Sprintf("\"%v\"", i),
				"label": fmt.Sprintf("\"%v|%v\"", p.NodeTemplate.Name, p.OperationName),
				"shape": "\"record\"",
			})
	}
	l := e.AdjacencyMatrix.Dim()
	for r := 0; r < l; r++ {
		for c := 0; c < l; c++ {
			if e.AdjacencyMatrix.At(r, c) == 1 {
				g.AddEdge(fmt.Sprintf("%v", r), fmt.Sprintf("%v", c), true, nil)

			}

		}

	}
	log.Println("here")
	s := g.String()
	fmt.Println(s)
	/*
		d, _ := yaml.Marshal(e)
		fmt.Println(string(d))
	*/
	/*
		for i, n := range e.Index {
			log.Printf("[%v] %v:%v -> %v %v",
				i,
				n.NodeTemplate.Name,
				n.OperationName,
				n.NodeTemplate.Interfaces[n.InterfaceName].Operations[n.OperationName].Implementation,
				n.NodeTemplate.Interfaces[n.InterfaceName].Operations[n.OperationName].Inputs,
			)
		}
	*/
}
Exemplo n.º 2
0
func DotTrie(name string, json bool) (string, error) {
	var err error
	Zk = datamodel.Zk.Conn
	ZC := zCfg{map[string]Pool{}, map[string]Rule{}, map[string]Trie{}}
	Edges := Edges{map[string]bool{}, map[string]bool{}, map[string]bool{}}
	graph := ggv.NewGraph()
	graph.SetName(graphName)
	graph.SetDir(true)
	result := zkGraph{graph, &ZC, &Edges}
	if name == "all" {
		err = ZC.ParseAllTrie()
	} else {
		err = ZC.ParseWholeTrie(name)
	}
	if err != nil {
		return "{}", err
	}
	str, err := ZC.ToJSON()
	if err != nil {
		return "{}", err
	}
	if json {
		return str, nil
	}
	str = result.JSONtoDot(str)
	return str, nil
}
Exemplo n.º 3
0
func (nn NeuralNetwork) CreateGraph() string {
	graph := graphviz.NewGraph()
	graph.SetDir(true)
	graph.SetName("NeuralNetwork")

	for layerIndex, layer := range nn.layers {
		for i, neuron := range layer.neurons {
			name := nodeName(layerIndex, i)
			attrs := make(map[string]string)
			if neuron.bias != 0.0 {
				attrs["label"] = label(name, neuron.bias)
			}
			graph.AddNode(name, name, attrs)
		}

		for b, neuron := range layer.neurons {
			for a, weight := range neuron.weights {
				if weight != 0.0 {
					attrs := make(map[string]string)
					attrs["label"] = fmt.Sprintf("%v", weight)
					aLabel := nodeName(layerIndex-1, a)
					bLabel := nodeName(layerIndex, b)
					graph.AddEdge(aLabel, bLabel, true, attrs)
				}
			}
		}
	}
	return graph.String()
}
Exemplo n.º 4
0
func TestDFSAlmostEmptyGraph(t *testing.T) {
	g := ggv.NewGraph()
	g.SetName("G")
	g.AddNode("G", "N1", nil)
	g.SetDir(true)

	nodeToOutEdges := map[string][]*ggv.Edge{}
	buffer := new(bytes.Buffer)

	mockPathStringer := new(mockPathStringer)
	anythingType := mock.AnythingOfType("map[string]*gographviz.Node")

	mockPathStringer.On("pathAsString", []ggv.Edge{}, anythingType).Return("").Once()

	searcherWithTestStringer := &defaultSearcher{
		pathStringer: mockPathStringer,
	}
	searcherWithTestStringer.dfs(searchArgs{
		root:           "N1",
		path:           []ggv.Edge{},
		nodeToOutEdges: nodeToOutEdges,
		nameToNodes:    g.Nodes.Lookup,
		buffer:         buffer,
		statusMap:      make(map[string]discoveryStatus),
	})

	correctOutput := ""
	actualOutput := buffer.String()

	assert.Equal(t, correctOutput, actualOutput)
	mockPathStringer.AssertExpectations(t)
}
Exemplo n.º 5
0
// GraphAsText is the standard implementation of Grapher
func (g *defaultGrapher) GraphAsText(dotText []byte) (string, error) {
	graphAst, err := parser.ParseBytes(dotText)
	if err != nil {
		return "", err
	}
	dag := ggv.NewGraph() // A directed acyclic graph
	ggv.Analyse(graphAst, dag)

	if len(dag.Edges.Edges) == 0 {
		return "", errNoActivity
	}
	nodeToOutEdges := g.collectionGetter.generateNodeToOutEdges(dag)
	inDegreeZeroNodes := g.collectionGetter.getInDegreeZeroNodes(dag)
	nameToNodes := dag.Nodes.Lookup

	buffer := new(bytes.Buffer)
	statusMap := make(map[string]discoveryStatus)

	for _, root := range inDegreeZeroNodes {
		g.searcher.dfs(searchArgs{
			root:           root,
			path:           nil,
			nodeToOutEdges: nodeToOutEdges,
			nameToNodes:    nameToNodes,
			buffer:         buffer,
			statusMap:      statusMap,
		})
	}

	return buffer.String(), nil
}
Exemplo n.º 6
0
func (this *DotSerializer) Deserialize(data []byte) (*DAG, error) {
	ast, err := dotparser.ParseBytes(data)
	if err != nil {
		return nil, err
	}
	graph := dot.NewGraph()
	dot.Analyse(ast, graph)

	p := NewDAG(graph.Name)

	for src, dests := range graph.Edges.SrcToDsts {
		for dest, _ := range dests {

			if orig, ok := p.Jobs[src]; !ok {
				n := dotNameToDAGJob(graph, src)
				n.Post = append(n.Post, dest)
				p.Jobs[src] = n
			} else {
				orig.Post = append(orig.Post, dest)
			}
			if orig, ok := p.Jobs[dest]; !ok {
				n := dotNameToDAGJob(graph, dest)
				n.Prev = append(n.Prev, src)
				p.Jobs[dest] = n
			} else {
				orig.Prev = append(orig.Prev, src)
			}

			if _, ok := p.InDegrees[src]; !ok {
				p.InDegrees[src] = 0
			}
			if orig, ok := p.InDegrees[dest]; !ok {
				p.InDegrees[dest] = 1
			} else {
				p.InDegrees[dest] = orig + 1
			}
		}
	}

	for _, edge := range graph.Edges.Edges {
		if v, ok := edge.Attrs["nonstrict"]; ok {
			nonstrict, err := util.StringToBool(strings.Trim(v, "\""))
			if err != nil {
				log.Error(err)
				return nil, err
			}
			if len(edge.Src) != 0 && len(edge.Dst) != 0 {
				r := NewRelation()
				r.NonStrict = nonstrict
				if _, ok := p.Relations[edge.Src]; !ok {
					p.Relations[edge.Src] = make(map[string]*Relation)
				}
				p.Relations[edge.Src][edge.Dst] = r
			}
		}
	}

	return p, nil
}
Exemplo n.º 7
0
Arquivo: synthdef.go Projeto: go-on/sc
func newGraph(name string) *gographviz.Graph {
	g := gographviz.NewGraph()
	g.SetName(name)
	g.SetDir(true)
	g.AddAttr(name, "rankdir", "BT")
	// g.AddAttr(name, "ordering", "in")
	return g
}
Exemplo n.º 8
0
func printDotGraph(functions []uint16) {

	brAttr1 := make(map[string]string)
	//brAttr1["label"] = "T"
	brAttr1["color"] = "green"
	brAttr2 := make(map[string]string)
	brAttr2["color"] = "red"
	//brAttr2["label"] = "F"

	for _, addr := range functions {
		b := blockMap[addr]
		fn := gographviz.NewGraph()
		//fname := "\""+b.fnString()+"\""
		fname := b.fnString()
		fn.SetName(fname)
		fn.SetDir(true)
		fn.SetStrict(true)

		// DFS
		visited := make(map[uint16]bool)
		var s stack
		s.Put(addr)
		for !s.Empty() {
			a := s.Pop()
			if !visited[a] {
				visited[a] = true
				fn.AddNode(fname, blockMap[a].addrString(), blockMap[a].getAttributes())
				if len(blockMap[a].branches) == 1 {
					if blockMap[blockMap[a].branches[0]] != nil {
						fn.AddEdge(blockMap[a].addrString(), blockMap[blockMap[a].branches[0]].addrString(), true, nil)
						if !visited[blockMap[a].branches[0]] {
							s.Put(blockMap[a].branches[0])
						}
					}
				}
				if len(blockMap[a].branches) == 2 {

					if blockMap[blockMap[a].branches[1]] != nil {
						fn.AddEdge(blockMap[a].addrString(), blockMap[blockMap[a].branches[1]].addrString(), true, brAttr2)
						if !visited[blockMap[a].branches[1]] {
							s.Put(blockMap[a].branches[1])
						}
					}
					if blockMap[blockMap[a].branches[0]] != nil {
						fn.AddEdge(blockMap[a].addrString(), blockMap[blockMap[a].branches[0]].addrString(), true, brAttr1)
						if !visited[blockMap[a].branches[0]] {
							s.Put(blockMap[a].branches[0])
						}

					}
				}
			}
		}

		saveGraph(fn)
	}

}
Exemplo n.º 9
0
func TestGetInDegreeZeroNodesEmptyGraph(t *testing.T) {
	g := ggv.NewGraph()
	g.SetName("G")
	g.SetDir(true)

	var correctInDegreeZeroNodes []string
	actualInDegreeZeroNodes := new(defaultCollectionGetter).getInDegreeZeroNodes(g)
	assert.Equal(t, correctInDegreeZeroNodes, actualInDegreeZeroNodes)
}
Exemplo n.º 10
0
func TestGenerateNodeToOutEdgesEmptyGraph(t *testing.T) {
	g := ggv.NewGraph()
	g.SetName("G")
	g.SetDir(true)

	correctNodeToOutEdges := make(map[string][]*ggv.Edge)
	actualNodeToOutEdges := new(defaultCollectionGetter).generateNodeToOutEdges(g)
	assert.Equal(t, correctNodeToOutEdges, actualNodeToOutEdges)
}
Exemplo n.º 11
0
func GenerateDotString(res []struct {
	ANAME   string
	BNAME   string
	AID     int
	BID     int
	RELKIND string
	RELID   int
	URLS    []string
}, attrs url.Values) string {
	attrs.Del("url")
	attrs.Del("r")

	// split our slice in a slice with only nodes and a slice with only rels
	var splitAt int
	for index, row := range res {
		if row.BNAME != "" {
			splitAt = index
			break
		}
	}

	graphName := "nodes"
	g := gographviz.NewGraph()
	g.SetName(graphName)
	g.SetDir(true)
	g.AddAttr(graphName, "size", "\"15,1000\"")
	g.AddAttr(graphName, "ratio", "compress")
	for k := range attrs {
		g.AddAttr(graphName, k, attrs.Get(k))
	}

	// add nodes
	for _, row := range res[:splitAt] {
		g.AddNode(graphName, strconv.Itoa(row.AID), map[string]string{
			"id":       strconv.Itoa(row.AID),
			"label":    nodeTable(row.ANAME, row.URLS),
			"shape":    "box",
			"fontname": "Verdana",
			"fontsize": "9",
		})
	}

	// add edges
	for _, row := range res[splitAt:] {
		g.AddEdge(strconv.Itoa(row.AID), strconv.Itoa(row.BID), true, map[string]string{
			"id":       strconv.Itoa(row.RELID),
			"label":    row.RELKIND,
			"dir":      relationshipDir(row.RELKIND),
			"tooltip":  row.RELKIND,
			"fontname": "Verdana",
			"fontsize": "9",
		})
	}

	return g.String()
}
Exemplo n.º 12
0
func (n *Node) Graph() string {
	g := gographviz.NewGraph()
	g.SetName("Tree")
	g.SetDir(true)

	g.AddNode("Tree", "root", nil)

	n.addToGraph(g, "root")
	return g.String()
}
Exemplo n.º 13
0
func (n *Node) ToGraphViz() string {
	graphAst, _ := parser.ParseString(`digraph NestedSet {}`)
	graph := gographviz.NewGraph()
	gographviz.Analyse(graphAst, graph)

	n.addToGraphViz(graph, "NestedSet", "")

	output := graph.String()

	return output
}
Exemplo n.º 14
0
// The returned graph, represented in ascii:
//	           +----------+
//	           | Ignoreme |
//	           +----------+
//	+----+     +----------+
//	| N2 | <-- |    N1    |
//	+----+     +----------+
//	             |
//	             |
//	             v
//	           +----------+
//	           |    N3    |
//  	       +----------+
func testGraphWithClusterNodes() *ggv.Graph {
	g := ggv.NewGraph()
	g.SetName("G")
	g.SetDir(true)
	g.AddNode("G", "N1", nil)
	g.AddNode("G", "N2", nil)
	g.AddNode("G", "N3", nil)
	g.AddNode("G", "Ignore me!", nil)
	g.AddEdge("N1", "N2", true, nil)
	g.AddEdge("N1", "N3", true, nil)
	return g
}
Exemplo n.º 15
0
// The returned graph, represented in ascii:
//	+----+
//	| N1 | -+
//	+----+  |
//	  |     |
//	  |     |
//	  v     |
//	+----+  |
//	| N2 |  |
//	+----+  |
//	  |     |
//	  |     |
//	  v     |
//	+----+  |
//	| N3 |  |
//	+----+  |
//	  |     |
//	  |     |
//	  v     |
//	+----+  |
//	| N4 | <+
//	+----+
func testGraphWithTooltip() *ggv.Graph {
	g := ggv.NewGraph()
	g.SetName("G")
	g.SetDir(true)
	g.AddNode("G", "N1", map[string]string{"tooltip": "function1"})
	g.AddNode("G", "N2", map[string]string{"tooltip": "function2"})
	g.AddNode("G", "N3", map[string]string{"tooltip": "function3"})
	g.AddNode("G", "N4", map[string]string{"tooltip": "function4"})
	g.AddEdge("N1", "N2", true, nil)
	g.AddEdge("N2", "N3", true, nil)
	g.AddEdge("N3", "N4", true, nil)
	g.AddEdge("N1", "N4", true, nil)
	return g
}
Exemplo n.º 16
0
// The returned graph, represented in ascii:
//	+----+     +----+
//	| N4 | <-- | N1 | -+
//	+----+     +----+  |
//	  |          |     |
//	  |          |     |
//	  |          v     |
//	  |        +----+  |
//	  |        | N2 |  |
//	  |        +----+  |
//	  |          |     |
//	  |          |     |
//	  |          v     |
//	  |        +----+  |
//	  +------> | N3 | <+
//	           +----+
func testSingleRootGraph() *ggv.Graph {
	g := ggv.NewGraph()
	g.SetName("G")
	g.SetDir(true)
	g.AddNode("G", "N1", nil)
	g.AddNode("G", "N2", nil)
	g.AddNode("G", "N3", nil)
	g.AddNode("G", "N4", nil)
	g.AddEdge("N1", "N2", true, nil)
	g.AddEdge("N2", "N3", true, nil)
	g.AddEdge("N4", "N3", true, nil)
	g.AddEdge("N1", "N4", true, nil)
	g.AddEdge("N1", "N3", true, nil)
	return g
}
Exemplo n.º 17
0
func visualize(data *Data) {
	graphAst, _ := parser.ParseString(`digraph G {}`)
	g := gographviz.NewGraph()

	gographviz.Analyse(graphAst, g)

	// step1 : add nodes
	for node := range data.NodeMap {
		g.AddNode("G", node.ID, nil)
	}

	// step2 : make edge from source node  to target node
	for _, edge := range data.GetEdges() {
		g.AddEdge(edge.Src.ID, edge.Dst.ID, true, nil)
	}
	output := g.String()
	fmt.Println(output)
}
Exemplo n.º 18
0
// The returned graph, represented in ascii:
//    +----+     +----+
// +> | N4 | <-- | N1 |
// |  +----+     +----+
// |    ^          |
// |    |          |
// |    |          v
// |    |        +----+
// |    +------- | N2 | <+
// |             +----+  |
// |               |     |
// |               |     |
// |               v     |
// |             +----+  |
// +------------ | N3 |  |
//               +----+  |
//                 |     |
//                 |     |
//                 v     |
//               +----+  |
//               | N5 | -+
//               +----+
func testGraphWithCycles() *ggv.Graph {
	g := ggv.NewGraph()
	g.SetName("G")
	g.SetDir(true)
	g.AddNode("G", "N1", nil)
	g.AddNode("G", "N2", nil)
	g.AddNode("G", "N3", nil)
	g.AddNode("G", "N4", nil)
	g.AddNode("G", "N5", nil)
	g.AddEdge("N1", "N2", true, nil)
	g.AddEdge("N1", "N4", true, nil)
	g.AddEdge("N2", "N3", true, nil)
	g.AddEdge("N2", "N4", true, nil)
	g.AddEdge("N3", "N4", true, nil)
	g.AddEdge("N3", "N5", true, nil)
	g.AddEdge("N5", "N2", true, nil)
	return g
}
Exemplo n.º 19
0
func printFunctionGraph(fgraph map[uint16]map[uint16]bool) {

	fn := gographviz.NewGraph()
	fname := "Functions"
	fn.SetName(fname)
	fn.SetDir(true)
	fn.SetStrict(true)

	for fnaddr := range fgraph {
		fn.AddNode(fname, f(fnaddr), nil) //TODO
		for calledfn := range fgraph[fnaddr] {
			fn.AddEdge(f(fnaddr), f(calledfn), true, nil)
		}

	}

	saveGraph(fn)

}
Exemplo n.º 20
0
func main() {
	// Creates a new graph
	g := gographviz.NewGraph()
	g.AddAttr("", "rankdir", "LR")
	// Now read the json input
	var v orchestrator.Graph
	dec := json.NewDecoder(os.Stdin)
	if err := dec.Decode(&v); err != nil {
		panic(err)

	}

	// Now for each node, create a node
	g.SetName(v.Name)
	g.SetDir(true)
	m := make(map[int]string)
	// Now add every node
	for i, _ := range v.Nodes {
		v.Nodes[i].Name = strings.Replace(v.Nodes[i].Name, "-", "_", -1)
		v.Nodes[i].Name = strings.Replace(v.Nodes[i].Name, ":", "_Method", -1)
		g.AddNode("G", v.Nodes[i].Name,
			map[string]string{
				"id":    fmt.Sprintf("\"%v\"", strconv.Itoa(v.Nodes[i].ID)),
				"label": fmt.Sprintf("\"%v|%v|%v|%v\"", v.Nodes[i].Name, v.Nodes[i].Engine, v.Nodes[i].Artifact, v.Nodes[i].Args),
				"shape": "\"record\"",
			})
		m[v.Nodes[i].ID] = v.Nodes[i].Name
	}
	l := v.Digraph.Dim()
	for r := 0; r < l; r++ {
		for c := 0; c < l; c++ {
			if v.Digraph.At(r, c) == 1 {
				g.AddEdge(m[r], m[c], true, nil)
			}
		}
	}
	// Now add the edges
	//g.AddEdge("Hello", "World", true, nil)
	s := g.String()
	fmt.Println(s)
}
func main() {
	var (
		bytes   []byte
		data    map[string]service
		err     error
		graph   *gographviz.Graph
		project string
	)
	logger = stdlog.GetFromFlags()
	project = ""

	// Load docker-compose.yml
	bytes, err = ioutil.ReadFile("docker-compose.yml")
	if err != nil {
		abort(err.Error())
	}

	// Parse it as YML
	data = make(map[string]service, 5)
	yaml.Unmarshal(bytes, &data)
	if err != nil {
		abort(err.Error())
	}

	// Create directed graph
	graph = gographviz.NewGraph()
	graph.SetName(project)
	graph.SetDir(true)

	// Add legend
	graph.AddSubGraph(project, "cluster_legend", map[string]string{"label": "Legend"})
	graph.AddNode("cluster_legend", "legend_service", map[string]string{"label": "service"})
	graph.AddNode("cluster_legend", "legend_service_with_ports",
		map[string]string{
			"label": "\"service with exposed ports\\n80:80 443:443\\n--volume1[:host_dir1]\\n--volume2[:host_dir2]\"",
			"shape": "box"})
	graph.AddEdge("legend_service", "legend_service_with_ports", true, map[string]string{"label": "links"})
	graph.AddEdge("legend_service_with_ports", "legend_service", true, map[string]string{"label": "volumes_from", "style": "dashed"})

	// Round one: populate nodes
	for name, service := range data {
		var attrs = map[string]string{"label": name}
		if service.Ports != nil {
			attrs["label"] += "\\n" + strings.Join(service.Ports, " ")
			attrs["shape"] = "box"
		}
		if service.Volumes != nil {
			attrs["label"] += "\\n--" + strings.Join(service.Volumes, "\\n--")
		}
		attrs["label"] = fmt.Sprintf("\"%s\"", attrs["label"])
		graph.AddNode(project, name, attrs)
	}

	// Round two: populate connections
	for name, service := range data {
		// links
		if service.Links != nil {
			for _, linkTo := range service.Links {
				if strings.Contains(linkTo, ":") {
					linkTo = strings.Split(linkTo, ":")[0]
				}
				graph.AddEdge(name, linkTo, true, nil)
			}
		}
		// volumes_from
		if service.VolumesFrom != nil {
			for _, linkTo := range service.VolumesFrom {
				graph.AddEdge(name, linkTo, true, map[string]string{"style": "dotted"})
			}
		}
	}

	fmt.Print(graph)
}
Exemplo n.º 22
0
func generateSvg(id string) ([]byte, error) {

	template, err := template.New("node").Parse(`{{define "NODE"}}<<table border="0" cellspacing="0">
		<tr ><td colspan="2" port="port1" border="1" bgcolor="lightblue">{{.Name}}</td></tr>
		<tr ><td colspan="2" port="port2" border="1">{{.Target}}</td></tr>
		<tr>
			<td port="port2" border="1">{{.Engine}}</td>
			<td port="port8" border="1">{{.Artifact}}</td>
		</tr>
		{{range .Args}}
		<tr ><td colspan="2" port="port2" border="1">{{.}}</td></tr>
		{{end}}
		<tr ><td colspan="2" port="port2" border="1">{{.Outputs}}</td></tr>
		</table>>{{end}}`)

	// Creates a new graph
	g := gographviz.NewGraph()
	//g.AddAttr("", "rankdir", "LR")
	// Now read the json input
	var v orchestrator.Graph

	resp, err := http.Get(fmt.Sprintf("%v/%v", OrchestratorUrl, id))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	//body, err := ioutil.ReadAll(resp.Body)

	dec := json.NewDecoder(resp.Body)
	if err := dec.Decode(&v); err != nil {
		return nil, err
	}

	// Now for each node, create a node
	g.SetName("Execution")
	g.SetDir(true)
	m := make(map[int]string)
	// Now add every node
	// Hack: If node has no Engine and no Artiface, and if sum(row)=sum(col)=0, skip it
	for i, _ := range v.Nodes {
		sumr := int64(0)
		sumc := int64(0)
		for r := 0; r < v.Digraph.Dim(); r++ {
			sumr = sumr + v.Digraph.At(v.Nodes[i].ID, r)
			sumc = sumc + v.Digraph.At(r, v.Nodes[i].ID)
		}
		if v.Nodes[i].Artifact == "" && sumr == 0 && sumc == 0 {
			continue
		}
		tmp := make([]string, 2)
		v.Nodes[i].Name = strings.Replace(v.Nodes[i].Name, "-", "_", -1)
		tmp = strings.SplitAfter(v.Nodes[i].Name, ":")
		v.Nodes[i].Name = strings.Replace(v.Nodes[i].Name, ":", "_", -1)
		if len(tmp) != 2 {
			tmp[0] = v.Nodes[i].Name
			tmp = append(tmp, "")
		}
		var out bytes.Buffer
		err = template.ExecuteTemplate(&out, "NODE", v.Nodes[i])
		g.AddNode("G", v.Nodes[i].Name,
			map[string]string{
				"id": fmt.Sprintf("\"%v\"", strconv.Itoa(v.Nodes[i].ID)),
				//"label": fmt.Sprintf("\"%v|%v\"", tmp[0], tmp[1]),
				"label": out.String(),
				//"label": fmt.Sprintf("\"%v|%v|%v|%v|%v\"", tmp[0], tmp[1], v.Nodes[i].Engine, v.Nodes[i].Artifact, v.Nodes[i].Args[:]),
				"shape": "\"record\"",
				"style": "\"rounded\"",
			})
		m[v.Nodes[i].ID] = v.Nodes[i].Name
	}
	for r := 0; r < v.Digraph.Dim(); r++ {
		for c := 0; c < v.Digraph.Dim(); c++ {
			if v.Digraph.At(r, c) != 0 {
				//g.AddEdge(fmt.Sprintf("%v:%v", m[r], r), fmt.Sprintf("%v:%v", m[c], c), true, nil)
				g.AddEdge(m[r], m[c], true, nil)
			}
		}
	}
	// Now add the edges
	s := g.String()
	d := exec.Command("dot", "-Tsvg")

	// Set the stdin stdout and stderr of the dot subprocess
	stdinOfDotProcess, err := d.StdinPipe()
	if err != nil {
		return nil, err

	}
	defer stdinOfDotProcess.Close() // the doc says subProcess.Wait will close it, but I'm not sure, so I kept this line
	readCloser, err := d.StdoutPipe()
	if err != nil {
		return nil, err

	}
	d.Stderr = os.Stderr

	// Actually run the dot subprocess
	if err = d.Start(); err != nil { //Use start, not run
		fmt.Println("An error occured: ", err) //replace with logger, or anything you want
	}
	fmt.Fprintf(stdinOfDotProcess, s)
	stdinOfDotProcess.Close()

	// Read from stdout and store it in the correct structure
	var buf bytes.Buffer
	buf.ReadFrom(readCloser)

	err = d.Wait()
	if err != nil {
		fmt.Println(s)
	}

	return buf.Bytes(), nil
}
Exemplo n.º 23
0
// RunBuildChain contains all the necessary functionality for the OpenShift
// experimental build-chain command
func RunBuildChain(f *clientcmd.Factory, cmd *cobra.Command, args []string) error {
	all := cmdutil.GetFlagBool(cmd, "all")
	allTags := cmdutil.GetFlagBool(cmd, "all-tags")
	if len(args) > 1 ||
		(len(args) == 1 && all) ||
		(len(args) == 0 && allTags) ||
		(all && allTags) {
		return cmdutil.UsageError(cmd, "Must pass nothing, an ImageStream name:tag combination, or specify the --all flag")
	}

	oc, _, err := f.Clients()
	if err != nil {
		return err
	}

	// Retrieve namespace(s)
	namespace := cmdutil.GetFlagString(cmd, "namespace")
	if len(namespace) == 0 {
		namespace, err = f.DefaultNamespace()
		if err != nil {
			return err
		}
	}
	namespaces := make([]string, 0)
	if all {
		projectList, err := oc.Projects().List(labels.Everything(), fields.Everything())
		if err != nil {
			return err
		}
		for _, project := range projectList.Items {
			glog.V(4).Infof("Found namespace %s", project.Name)
			namespaces = append(namespaces, project.Name)
		}
	}
	if len(namespaces) == 0 {
		namespaces = append(namespaces, namespace)
	}

	// Get all build configurations
	buildConfigList := make([]buildapi.BuildConfig, 0)
	for _, namespace := range namespaces {
		cfgList, err := oc.BuildConfigs(namespace).List(labels.Everything(), fields.Everything())
		if err != nil {
			return err
		}
		buildConfigList = append(buildConfigList, cfgList.Items...)
	}

	// Parse user input and validate specified image stream
	streams := make(map[string][]string)
	if !all && len(args) != 0 {
		name, specifiedTag, err := parseTag(args[0])
		if err != nil {
			return err
		}

		// Validate the specified image stream
		is, err := oc.ImageStreams(namespace).Get(name)
		if err != nil {
			return err
		}
		stream := join(namespace, name)

		// Validate specified tag
		tags := make([]string, 0)
		exists := false
		for tag := range is.Status.Tags {
			tags = append(tags, tag)
			if specifiedTag == tag {
				exists = true
			}
		}
		if !exists && !allTags {
			// The specified tag isn't a part of our image stream
			return fmt.Errorf("no tag %s exists in %s", specifiedTag, stream)
		} else if !allTags {
			// Use only the specified tag
			tags = []string{specifiedTag}
		}

		// Set the specified stream as the only one to output dependencies for
		streams[stream] = tags
	} else {
		streams = getStreams(buildConfigList)
	}

	if len(streams) == 0 {
		return fmt.Errorf("no ImageStream available for building its dependency tree")
	}

	output := cmdutil.GetFlagString(cmd, "output")
	for stream, tags := range streams {
		for _, tag := range tags {
			glog.V(4).Infof("Checking dependencies of stream %s tag %s", stream, tag)
			root, err := findStreamDeps(stream, tag, buildConfigList)
			if err != nil {
				return err
			}

			// Check if the given image stream doesn't have any dependencies
			if treeSize(root) < 2 {
				glog.Infof("%s:%s has no dependencies\n", root.FullName, tag)
				continue
			}

			switch output {
			case "json":
				jsonDump, err := json.MarshalIndent(root, "", "\t")
				if err != nil {
					return err
				}
				fmt.Println(string(jsonDump))
			case "dot":
				g := dot.NewGraph()
				_, name, err := split(stream)
				if err != nil {
					return err
				}
				graphName := validDOT(name)
				g.SetName(graphName)
				// Directed graph since we illustrate dependencies
				g.SetDir(true)
				// Explicitly allow multiple pairs of edges between
				// the same pair of nodes
				g.SetStrict(false)
				out, err := dotDump(root, g, graphName)
				if err != nil {
					return err
				}
				fmt.Println(out)
			case "ast":
				fmt.Println(root)
			default:
				return cmdutil.UsageError(cmd, "Wrong output format specified: %s", output)
			}
		}
	}
	return nil
}
Exemplo n.º 24
0
func main() {
	pDoGame := flag.Bool("game", false, "start the game")
	flag.Parse()

	rcsv("data/neurons.csv", func(records []string) {
		newEmptyNeuron(records[0], records, 5, BODY)
	})

	rcsv("data/connectome.csv", func(records []string) {
		weight, err := strconv.ParseInt(records[3], 10, 32)
		if err != nil {
			log.Fatal(err)
		}

		ID_TO_NEURON[records[0]].connect(ID_TO_NEURON[records[1]], int32(weight))
	})

	rcsv("data/fake_motor.csv", func(records []string) {
		weight, err := strconv.ParseInt(records[3], 10, 32)
		if err != nil {
			log.Fatal(err)
		}

		if records[1] == "LEFT" {
			ID_TO_NEURON[records[0]].connect(BODY.left, int32(weight))
		} else if records[1] == "RIGHT" {
			ID_TO_NEURON[records[0]].connect(BODY.right, int32(weight))
		}
	})

	for _, v := range ID_TO_NEURON {
		v.ticker()
	}

	http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.RawQuery
		if n, ok := ID_TO_NEURON[r.URL.RawQuery]; ok {
			n.ping(30)
			fmt.Fprintf(w, "nReceived: %d", n.nReceived)
		} else {
			http.Error(w, fmt.Sprintf("missing neuron: %s", q), 404)
		}
	})

	http.HandleFunc("/debug", func(w http.ResponseWriter, r *http.Request) {
		DEBUG = !DEBUG
		fmt.Fprintf(w, "current: %#v", DEBUG)
	})

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		graphAst, _ := parser.ParseString(`digraph G {}`)
		graph := gv.NewGraph()
		graph.SetDir(true)
		for _, v := range ID_TO_NEURON {

			if v.activity() > 0 {
				graph.AddNode("G", v.id(), nil)
				for _, c := range v.connections {
					graph.AddNode("G", c.to.id(), nil)
					graph.AddEdge(v.id(), c.to.id(), true, nil)
				}
			}
		}
		gv.Analyse(graphAst, graph)
		output := graph.String()
		fmt.Fprintf(w, output)
	})

	go func() {
		log.Fatal(http.ListenAndServe(":8080", nil))
	}()
	if *pDoGame {
		world()
	} else {
		BODY.ticker()
		for {
			time.Sleep(1 * time.Second)
		}
	}
}
Exemplo n.º 25
0
func lbpkr_run_cmd_dep_graph(cmd *commander.Command, args []string) error {
	var err error

	siteroot := cmd.Flag.Lookup("siteroot").Value.Get().(string)
	debug := cmd.Flag.Lookup("v").Value.Get().(bool)
	dotfname := cmd.Flag.Lookup("o").Value.Get().(string)
	dmax := cmd.Flag.Lookup("maxdepth").Value.Get().(int)

	name := ""
	vers := ""
	release := ""

	switch len(args) {
	case 0:
		name = ""
	case 1:
		name = args[0]
	case 2:
		name = args[0]
		vers = args[1]
	case 3:
		name = args[0]
		vers = args[1]
		release = args[2]
	default:
		cmd.Usage()
		return fmt.Errorf("lbpkr: invalid number of arguments. expected n=0|1|2|3. got=%d (%v)",
			len(args),
			args,
		)
	}

	cfg := NewConfig(siteroot)
	ctx, err := New(cfg, Debug(debug))
	if err != nil {
		return err
	}
	defer ctx.Close()

	g := graph.NewGraph()
	g.SetName("rpms")
	g.SetDir(true)

	decorate := func(pkg yum.RPM) map[string]string {
		return map[string]string{
			"name":    strconv.Quote(pkg.Name()),
			"version": strconv.Quote(pkg.Version()),
			"release": strconv.Quote(pkg.Release()),
			"epoch":   strconv.Quote(pkg.Epoch()),
		}
	}

	pkgs, err := ctx.ListInstalledPackages(name, vers, release)
	if err != nil {
		return err
	}

	str_in_slice := func(str string, slice []string) bool {
		for _, v := range slice {
			if str == v {
				return true
			}
		}
		return false
	}

	var process func(pkg *yum.Package, lvl int) error

	process = func(pkg *yum.Package, lvl int) error {
		var err error
		root := strconv.Quote(pkg.ID())
		g.AddNode("rpms", root, decorate(pkg))
		reqs := pkg.Requires()
		for _, req := range reqs {
			if str_in_slice(req.Name(), yum.IGNORED_PACKAGES) {
				continue
			}
			dep, err := ctx.Client().FindLatestMatchingRequire(req)
			if err != nil {
				ctx.msg.Infof("no package providing name=%q version=%q release=%q\n",
					req.Name(),
					req.Version(),
					req.Release(),
				)
				continue
			}
			g.AddNode("rpms", strconv.Quote(dep.ID()), decorate(dep))
			g.AddEdge(root, strconv.Quote(dep.ID()), true, nil)
			if lvl < dmax || dmax < 0 {
				err = process(dep, lvl+1)
				if err != nil {
					return err
				}
			}
		}
		return err
	}

	for _, pkg := range pkgs {
		err = process(pkg, 1)
		if err != nil {
			return err
		}
	}

	err = ioutil.WriteFile(dotfname, []byte(g.String()), 0644)
	if err != nil {
		return err
	}

	return err
}