-
Notifications
You must be signed in to change notification settings - Fork 24
/
circuit-graph.go
308 lines (289 loc) · 11.1 KB
/
circuit-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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package controlplane
import (
"fmt"
"strings"
"github.com/emicklei/dot"
"google.golang.org/protobuf/types/known/structpb"
policymonitoringv1 "github.com/fluxninja/aperture/api/gen/proto/go/aperture/policy/monitoring/v1"
"github.com/fluxninja/aperture/pkg/log"
"github.com/fluxninja/aperture/pkg/policies/controlplane/runtime"
)
// ComponentDTO takes a CompiledCircuit and returns its graph representation.
func ComponentDTO(circuit CompiledCircuit) ([]*policymonitoringv1.ComponentView, []*policymonitoringv1.Link) {
var componentsDTO []*policymonitoringv1.ComponentView
var links []*policymonitoringv1.Link
type componentData struct {
componentID string
portName string
}
outSignalsIndex := make(map[string][]componentData)
inSignalsIndex := make(map[string][]componentData)
for _, c := range circuit {
var inPorts, outPorts []*policymonitoringv1.PortView
for name, signals := range c.InPortToSignalsMap {
for _, signal := range signals {
if signal.SignalType == runtime.SignalTypeNamed {
signalName := signal.Name
inPorts = append(inPorts, &policymonitoringv1.PortView{
PortName: name,
Value: &policymonitoringv1.PortView_SignalName{SignalName: signalName},
Looped: signal.Looped,
})
inSignalsIndex[signalName] = append(inSignalsIndex[signalName], componentData{
componentID: c.ComponentID,
portName: name,
})
} else if signal.SignalType == runtime.SignalTypeConstant {
inPorts = append(inPorts, &policymonitoringv1.PortView{
PortName: name,
Value: &policymonitoringv1.PortView_ConstantValue{ConstantValue: signal.Value},
})
}
}
}
for name, signals := range c.OutPortToSignalsMap {
for _, signal := range signals {
signalName := signal.Name
outPorts = append(outPorts, &policymonitoringv1.PortView{
PortName: name,
Value: &policymonitoringv1.PortView_SignalName{SignalName: signalName},
Looped: signal.Looped,
})
outSignalsIndex[signalName] = append(outSignalsIndex[signalName], componentData{
componentID: c.ComponentID,
portName: name,
})
}
}
componentMap, err := structpb.NewStruct(c.CompiledComponent.MapStruct)
if err != nil {
log.Error().Err(err).Msg("converting component map")
}
getServiceSelector := func(selector interface{}) string {
selectorMap, ok := selector.(map[string]interface{})
if !ok {
return ""
}
serviceSelectorInterface, ok := selectorMap["service_selector"]
if !ok {
return ""
}
serviceSelector, ok := serviceSelectorInterface.(map[string]interface{})
if !ok {
return ""
}
agentGroup, ok := serviceSelector["agent_group"]
if !ok {
return ""
}
service, ok := serviceSelector["service"]
if !ok {
return ""
}
if agentGroup == "default" {
return service.(string)
}
return fmt.Sprintf("%s/%s", agentGroup, service)
}
componentName := c.CompiledComponent.Name
mapStruct := c.CompiledComponent.MapStruct
componentDescription := ""
switch componentName {
case "Constant":
componentDescription = fmt.Sprintf("%0.2f", mapStruct["value"])
case "ArithmeticCombinator":
componentDescription = fmt.Sprintf("%s", mapStruct["operator"])
case "Decider":
componentDescription = fmt.Sprintf("%s for %s", mapStruct["operator"], mapStruct["true_for"])
case "EMA":
componentDescription = fmt.Sprintf("win: %s", mapStruct["ema_window"])
case "GradientController":
componentDescription = fmt.Sprintf("slope: %0.2f", mapStruct["slope"])
case "Extrapolator":
componentDescription = fmt.Sprintf("for: %s", mapStruct["max_extrapolation_interval"])
case "ConcurrencyLimiter":
componentDescription = getServiceSelector(mapStruct["selector"])
case "RateLimiter":
componentDescription = getServiceSelector(mapStruct["selector"])
}
componentsDTO = append(componentsDTO, &policymonitoringv1.ComponentView{
ComponentId: c.ComponentID,
ComponentName: componentName,
ComponentDescription: componentDescription,
ComponentType: string(c.CompiledComponent.ComponentType),
Component: componentMap,
InPorts: convertPortViews(inPorts),
OutPorts: convertPortViews(outPorts),
ParentComponentId: c.ParentComponentID,
})
}
// compute links
for signalName := range outSignalsIndex {
for _, outComponent := range outSignalsIndex[signalName] {
for _, inComponent := range inSignalsIndex[signalName] {
links = append(links, &policymonitoringv1.Link{
Source: &policymonitoringv1.SourceTarget{
ComponentId: outComponent.componentID,
PortName: outComponent.portName,
},
Target: &policymonitoringv1.SourceTarget{
ComponentId: inComponent.componentID,
PortName: inComponent.portName,
},
SignalName: signalName,
})
}
}
}
return componentsDTO, links
}
func convertPortViews(ports []*policymonitoringv1.PortView) []*policymonitoringv1.PortView {
var converted []*policymonitoringv1.PortView
for i := range ports {
converted = append(converted, ports[i])
}
return converted
}
// Mermaid returns Components and Links as a mermaid graph.
func Mermaid(components []*policymonitoringv1.ComponentView, links []*policymonitoringv1.Link) string {
var sb strings.Builder
sb.WriteString("flowchart LR\n")
parentComponents := make(map[string][]*policymonitoringv1.ComponentView)
for i, c := range components {
if c.ParentComponentId == "" {
continue
}
parentComponents[c.ParentComponentId] = append(parentComponents[c.ParentComponentId], c)
// remove this element from the slice
components[i] = components[len(components)-1]
components = components[:len(components)-1]
}
renderComponentSubGraph := func(component *policymonitoringv1.ComponentView) string {
var s strings.Builder
if component.ComponentName == "Constant" {
// lookup value in component.Component struct
value := component.Component.Fields["value"].GetNumberValue()
outPort := component.OutPorts[0].PortName
// render constant as a circle with value
s.WriteString(fmt.Sprintf("%s((%0.2f))\n", component.ComponentId+outPort, value))
return s.String()
}
name := component.ComponentName
// only show component description
if component.ComponentDescription != "" {
description := component.ComponentDescription
// truncate description if too long (mermaid limitation)
if len(description) > 16 {
description = description[:16] + "..."
}
name = fmt.Sprintf("<center>%s<br/>%s</center>", name, description)
}
s.WriteString(fmt.Sprintf("subgraph %s[%s]\n", component.ComponentId, name))
if len(component.InPorts) > 0 {
// add subgraph for inports
s.WriteString(fmt.Sprintf("subgraph %s_inports[ ]\n", component.ComponentId))
// style to make inports invisible
s.WriteString(fmt.Sprintf("style %s_inports fill:none,stroke:none\n", component.ComponentId))
// InPorts and OutPorts are nodes in the subgraph
for _, inputPort := range component.InPorts {
s.WriteString(fmt.Sprintf("%s[%s]\n", component.ComponentId+inputPort.PortName, inputPort.PortName))
}
s.WriteString("end\n")
}
if len(component.OutPorts) > 0 {
// add subgraph for outports
s.WriteString(fmt.Sprintf("subgraph %s_outports[ ]\n", component.ComponentId))
// style to make outports invisible
s.WriteString(fmt.Sprintf("style %s_outports fill:none,stroke:none\n", component.ComponentId))
for _, outputPort := range component.OutPorts {
s.WriteString(fmt.Sprintf("%s[%s]\n", component.ComponentId+outputPort.PortName, outputPort.PortName))
}
s.WriteString("end\n")
}
s.WriteString("end\n")
return s.String()
}
// prefix for fake constant components
fakeConstantPrefix := "FakeConstant"
// constantID for fake constant components
var constantID int
// subgraph for each component
for _, c := range components {
// if it's a parent component then render the subgraph for each component
if _, ok := parentComponents[c.ComponentId]; ok {
for _, childComponent := range parentComponents[c.ComponentId] {
childComponent.ComponentName = c.ComponentName + "/" + childComponent.ComponentName
if c.ComponentDescription != "" {
if childComponent.ComponentDescription != "" {
childComponent.ComponentDescription = "<center>" + c.ComponentDescription + "<br/>" + childComponent.ComponentDescription + "</center>"
} else {
childComponent.ComponentDescription = c.ComponentDescription
}
}
sb.WriteString(renderComponentSubGraph(childComponent))
}
} else {
sb.WriteString(renderComponentSubGraph(c))
}
// fake nodes for constant value ports
for _, inPort := range c.InPorts {
if constValue, ok := inPort.GetValue().(*policymonitoringv1.PortView_ConstantValue); ok {
// Concatenate fakeConstant prefix to constantComponentID to avoid collision with real component IDs
constantComponentID := fmt.Sprintf("%s%d", fakeConstantPrefix, constantID)
constantID++
sb.WriteString(fmt.Sprintf("%s((%0.2f))\n", constantComponentID, constValue.ConstantValue))
// link constant to component
sb.WriteString(fmt.Sprintf("%s --> %s\n", constantComponentID, c.ComponentId+inPort.PortName))
}
}
}
// links
for _, link := range links {
sb.WriteString(fmt.Sprintf("%s --> |%s| %s\n", link.Source.ComponentId+link.Source.PortName, link.SignalName, link.Target.ComponentId+link.Target.PortName))
}
return sb.String()
}
// DOT returns Components and Links as a DOT graph description.
func DOT(components []*policymonitoringv1.ComponentView, links []*policymonitoringv1.Link) string {
g := dot.NewGraph(dot.Directed)
g.AttributesMap.Attr("splines", "ortho")
g.AttributesMap.Attr("rankdir", "LR")
// indexed by component id
clusters := make(map[string]*dot.Graph)
for i := range components {
var sg *dot.Graph
if components[i].ParentComponentId == "" {
sg = g
} else {
sg = clusters[components[i].ParentComponentId]
}
name := fmt.Sprintf("%s[%s]", components[i].ComponentName, strings.SplitN(components[i].ComponentId, ".", 1)[0])
cluster := sg.Subgraph(name, dot.ClusterOption{})
cluster.AttributesMap.Attr("margin", "50.0")
clusters[components[i].ComponentId] = cluster
var anyIn, anyOut dot.Node
for _, inPort := range components[i].InPorts {
anyIn = cluster.Node(inPort.PortName)
cluster.AddToSameRank("input", anyIn)
// fake nodes for constant value ports
if constValue, ok := inPort.GetValue().(*policymonitoringv1.PortView_ConstantValue); ok {
// Concatenate fakeConstant prefix to constantComponentID to avoid collision with real component IDs
fromNode := cluster.Node(fmt.Sprintf("%0.2f", constValue.ConstantValue))
// link constant to component
cluster.Edge(fromNode, anyIn)
}
}
for j := range components[i].OutPorts {
anyOut = cluster.Node(components[i].OutPorts[j].PortName)
cluster.AddToSameRank("output", anyOut)
}
if len(components[i].InPorts) > 0 && len(components[i].OutPorts) > 0 {
cluster.Edge(anyIn, anyOut).Attr("style", "invis")
}
}
for i := range links {
g.Edge(clusters[links[i].Source.ComponentId].Node(links[i].Source.PortName),
clusters[links[i].Target.ComponentId].Node(links[i].Target.PortName)).Attr("label", links[i].SignalName)
}
return g.String()
}