packetforge: add packetforge for generic flow to extras
[vpp.git] / extras / packetforge / Edge.py
1 # Copyright (c) 2022 Intel and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 from EdgeAction import *
15 import json
16
17
18 class Edge:
19     def __init__(self):
20         self.JSON = None
21         self.Start = None
22         self.End = None
23         self.actionList = []
24
25     def Create(jsonfile):
26         f = open(jsonfile, "r", encoding="utf-8")
27         token = json.load(f)
28
29         if token == None:
30             return None
31
32         if token["type"] != "edge":
33             return None
34
35         edgeList = []
36
37         startNodes = token["start"]
38         endNodes = token["end"]
39
40         if startNodes == None or endNodes == None:
41             return None
42
43         startTokens = startNodes.split(",")
44         endTokens = endNodes.split(",")
45
46         for start in startTokens:
47             for end in endTokens:
48
49                 edge = Edge()
50
51                 edge.Start = start
52                 edge.End = end
53
54                 if "actions" in token:
55                     for at in token["actions"]:
56                         action = EdgeAction.Create(at)
57                         if not action:
58                             return None
59
60                         edge.actionList.append(action)
61
62                 edge.JSON = jsonfile
63                 edgeList.append(edge)
64
65         return edgeList
66
67     def Apply(self, first, second):
68         exp = []
69
70         for i in range(len(self.actionList)):
71             act = self.actionList[i]
72
73             if act.FromStartObject == True:
74                 exp.append(first.GetValue(act.FromExpression))
75             elif act.FromStartObject == False:
76                 exp.append(second.GetValue(act.FromExpression))
77             else:
78                 exp.append(act.FromExpression)
79
80         for i in range(len(exp)):
81             act = self.actionList[i]
82
83             if act.ToStartObject:
84                 first.SetFieldAuto(act.ToExpression, exp[i])
85             else:
86                 second.SetFieldAuto(act.ToExpression, exp[i])
87
88     def Actions(self):
89         return self.actionList
90
91     def Name(self):
92         return self.Start + "_" + self.End