-
Notifications
You must be signed in to change notification settings - Fork 243
/
graph.go
191 lines (169 loc) · 5.03 KB
/
graph.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright 2020 Nokia
// Licensed under the BSD 3-Clause License.
// SPDX-License-Identifier: BSD-3-Clause
package cmd
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"html/template"
"net/http"
"sort"
"strings"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/srl-labs/containerlab/clab"
"github.com/srl-labs/containerlab/runtime"
"github.com/srl-labs/containerlab/types"
)
var (
srv string
tmpl string
offline bool
dot bool
//go:embed graph-template.html
graphTemplate string
)
type graphTopo struct {
Nodes []containerDetails `json:"nodes,omitempty"`
Links []link `json:"links,omitempty"`
}
type link struct {
Source string `json:"source,omitempty"`
SourceEndpoint string `json:"source_endpoint,omitempty"`
Target string `json:"target,omitempty"`
TargetEndpoint string `json:"target_endpoint,omitempty"`
}
type topoData struct {
Name string
Data template.JS
}
// graphCmd represents the graph command
var graphCmd = &cobra.Command{
Use: "graph",
Short: "generate a topology graph",
Long: "generate topology graph based on the topology definition file and running containers\nreference: https://containerlab.srlinux.dev/cmd/graph/",
RunE: func(cmd *cobra.Command, args []string) error {
var err error
opts := []clab.ClabOption{
clab.WithTimeout(timeout),
clab.WithTopoFile(topo),
clab.WithRuntime(rt,
&runtime.RuntimeConfig{
Debug: debug,
Timeout: timeout,
GracefulShutdown: graceful,
},
),
}
c, err := clab.NewContainerLab(opts...)
if err != nil {
return err
}
if dot {
if err := c.GenerateGraph(topo); err != nil {
return err
}
return nil
}
gtopo := graphTopo{
Nodes: make([]containerDetails, 0, len(c.Nodes)),
Links: make([]link, 0, len(c.Links)),
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var containers []types.GenericContainer
// if offline mode is not enforced, list containers matching lab name
if !offline {
labels := []*types.GenericFilter{{FilterType: "label", Match: c.Config.Name, Field: "containerlab", Operator: "="}}
containers, err = c.ListContainers(ctx, labels)
if err != nil {
return err
}
log.Debugf("found %d containers", len(containers))
}
switch {
case len(containers) == 0:
buildGraphFromTopo(>opo, c)
case len(containers) > 0:
buildGraphFromDeployedLab(>opo, c, containers)
}
sort.Slice(gtopo.Nodes, func(i, j int) bool {
return gtopo.Nodes[i].Name < gtopo.Nodes[j].Name
})
for _, l := range c.Links {
gtopo.Links = append(gtopo.Links, link{
Source: l.A.Node.ShortName,
SourceEndpoint: l.A.EndpointName,
Target: l.B.Node.ShortName,
TargetEndpoint: l.B.EndpointName,
})
}
b, err := json.Marshal(gtopo)
if err != nil {
return err
}
log.Debugf("generating graph using data: %s", string(b))
topoD := topoData{
Name: c.Config.Name,
Data: template.JS(string(b)),
}
var t *template.Template
if tmpl != "" {
t = template.Must(template.ParseFiles(tmpl))
} else {
t = template.Must(template.New("graph").Parse(graphTemplate))
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_ = t.Execute(w, topoD)
})
log.Infof("Listening on %s...", srv)
err = http.ListenAndServe(srv, nil)
if err != nil {
return err
}
return nil
},
}
func buildGraphFromTopo(g *graphTopo, c *clab.CLab) {
log.Info("building graph from topology file")
for _, node := range c.Nodes {
g.Nodes = append(g.Nodes, containerDetails{
Name: node.Config().ShortName,
Kind: node.Config().Kind,
Image: node.Config().Image,
Group: node.Config().Group,
State: "N/A",
IPv4Address: node.Config().MgmtIPv4Address,
IPv6Address: node.Config().MgmtIPv6Address,
})
}
}
func buildGraphFromDeployedLab(g *graphTopo, c *clab.CLab, containers []types.GenericContainer) {
for _, cont := range containers {
var name string
if len(cont.Names) > 0 {
name = strings.TrimPrefix(cont.Names[0], fmt.Sprintf("/clab-%s-", c.Config.Name))
}
log.Debugf("looking for node name %s", name)
if node, ok := c.Nodes[name]; ok {
g.Nodes = append(g.Nodes, containerDetails{
Name: name,
Kind: node.Config().Kind,
Image: cont.Image,
Group: node.Config().Group,
State: fmt.Sprintf("%s/%s", cont.State, cont.Status),
IPv4Address: getContainerIPv4(cont, c.Config.Mgmt.Network),
IPv6Address: getContainerIPv6(cont, c.Config.Mgmt.Network),
})
}
}
}
func init() {
rootCmd.AddCommand(graphCmd)
graphCmd.Flags().StringVarP(&srv, "srv", "s", ":50080", "HTTP server address to view, customize and export your topology")
graphCmd.Flags().BoolVarP(&offline, "offline", "o", false, "use only information from topo file when building graph")
graphCmd.Flags().BoolVarP(&dot, "dot", "", false, "generate dot file instead of launching the web server")
graphCmd.Flags().StringVarP(&tmpl, "template", "", "", "Go html template used to generate the graph")
}