forked from p4lang/tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswitch.py
More file actions
246 lines (212 loc) · 8.67 KB
/
switch.py
File metadata and controls
246 lines (212 loc) · 8.67 KB
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
# SPDX-FileCopyrightText: 2017 Open Networking Foundation
#
# SPDX-License-Identifier: Apache-2.0
from abc import abstractmethod
from datetime import datetime
from queue import Queue
import threading
import grpc
from p4.tmp import p4config_pb2
from p4.v1 import p4runtime_pb2, p4runtime_pb2_grpc
MSG_LOG_MAX_LEN = 1024
# List of all active connections
connections = []
def ShutdownAllSwitchConnections():
for c in connections:
c.shutdown()
class StreamDispatcher:
def __init__(self, stream):
self.stream = stream
self.running = True
# Queues for each message type
self.arbitration_queue = Queue()
self.packet_in_queue = Queue()
self.timeout_queue = Queue()
self.error_queue = Queue()
self.thread = threading.Thread(target=self._dispatch_loop, daemon=True)
self.thread.start()
def _dispatch_loop(self):
for msg in self.stream:
if not self.running:
break
if msg.HasField("arbitration"):
self.arbitration_queue.put(msg.arbitration)
elif msg.HasField("packet"):
self.packet_in_queue.put(msg.packet)
elif msg.HasField("idle_timeout_notification"):
self.timeout_queue.put(msg.idle_timeout_notification)
elif msg.HasField("error"):
self.error_queue.put(msg.error)
else:
print("Unknown StreamMessageResponse:", msg)
def stop(self):
self.running = False
class SwitchConnection(object):
def __init__(self, name=None, address='127.0.0.1:50051', device_id=0,
proto_dump_file=None):
self.name = name
self.address = address
self.device_id = device_id
self.p4info = None
self.channel = grpc.insecure_channel(self.address)
if proto_dump_file is not None:
interceptor = GrpcRequestLogger(proto_dump_file)
self.channel = grpc.intercept_channel(self.channel, interceptor)
self.client_stub = p4runtime_pb2_grpc.P4RuntimeStub(self.channel)
self.requests_stream = IterableQueue()
self.stream_msg_resp = self.client_stub.StreamChannel(iter(self.requests_stream))
self.dispatcher = StreamDispatcher(self.stream_msg_resp)
self.proto_dump_file = proto_dump_file
connections.append(self)
@abstractmethod
def buildDeviceConfig(self, **kwargs):
return p4config_pb2.P4DeviceConfig()
def shutdown(self):
self.requests_stream.close()
self.dispatcher.stop()
def MasterArbitrationUpdate(self, dry_run=False, **kwargs):
request = p4runtime_pb2.StreamMessageRequest()
request.arbitration.device_id = self.device_id
request.arbitration.election_id.high = 0
request.arbitration.election_id.low = 1
if dry_run:
print("P4Runtime MasterArbitrationUpdate: ", request)
else:
self.requests_stream.put(request)
return self.dispatcher.arbitration_queue.get()
def SetForwardingPipelineConfig(self, p4info, dry_run=False, **kwargs):
device_config = self.buildDeviceConfig(**kwargs)
request = p4runtime_pb2.SetForwardingPipelineConfigRequest()
request.election_id.low = 1
request.device_id = self.device_id
config = request.config
config.p4info.CopyFrom(p4info)
config.p4_device_config = device_config.SerializeToString()
request.action = p4runtime_pb2.SetForwardingPipelineConfigRequest.VERIFY_AND_COMMIT
if dry_run:
print("P4Runtime SetForwardingPipelineConfig:", request)
else:
self.client_stub.SetForwardingPipelineConfig(request)
def WriteTableEntry(self, table_entry, dry_run=False):
request = p4runtime_pb2.WriteRequest()
request.device_id = self.device_id
request.election_id.low = 1
update = request.updates.add()
if table_entry.is_default_action:
update.type = p4runtime_pb2.Update.MODIFY
else:
update.type = p4runtime_pb2.Update.INSERT
update.entity.table_entry.CopyFrom(table_entry)
if dry_run:
print("P4Runtime Write:", request)
else:
self.client_stub.Write(request)
def DeleteTableEntry(self, table_entry, dry_run=False):
request = p4runtime_pb2.WriteRequest()
request.device_id = self.device_id
request.election_id.low = 1
update = request.updates.add()
update.type = p4runtime_pb2.Update.DELETE
update.entity.table_entry.CopyFrom(table_entry)
if dry_run:
print("P4Runtime Write:", request)
else:
self.client_stub.Write(request)
def ReadTableEntries(self, table_id=None, dry_run=False):
request = p4runtime_pb2.ReadRequest()
request.device_id = self.device_id
entity = request.entities.add()
table_entry = entity.table_entry
if table_id is not None:
table_entry.table_id = table_id
else:
table_entry.table_id = 0
if dry_run:
print("P4Runtime Read:", request)
else:
for response in self.client_stub.Read(request):
yield response
def ReadCounters(self, counter_id=None, index=None, dry_run=False):
request = p4runtime_pb2.ReadRequest()
request.device_id = self.device_id
entity = request.entities.add()
counter_entry = entity.counter_entry
if counter_id is not None:
counter_entry.counter_id = counter_id
else:
counter_entry.counter_id = 0
if index is not None:
counter_entry.index.index = index
if dry_run:
print("P4Runtime Read:", request)
else:
for response in self.client_stub.Read(request):
yield response
def WritePREEntry(self, pre_entry, dry_run=False):
request = p4runtime_pb2.WriteRequest()
request.device_id = self.device_id
request.election_id.low = 1
update = request.updates.add()
update.type = p4runtime_pb2.Update.INSERT
update.entity.packet_replication_engine_entry.CopyFrom(pre_entry)
if dry_run:
print("P4Runtime Write:", request)
else:
self.client_stub.Write(request)
def PacketIn(self, dry_run=False):
request = self.dispatcher.packet_in_queue.get()
if dry_run:
print("P4 Runtime PacketIn: ", request)
else:
return request
def PacketOut(self, payload, metadatas):
packet_out = p4runtime_pb2.PacketOut()
packet_out.payload = payload
metadata_list = []
i = 1
for meta in metadatas:
item = p4runtime_pb2.PacketMetadata()
item.metadata_id = i
item.value = meta["value"].to_bytes(meta["bitwidth"], 'big')
metadata_list.append(item)
i +=1
packet_out.metadata.extend(metadata_list)
request = p4runtime_pb2.StreamMessageRequest()
request.packet.CopyFrom(packet_out)
self.requests_stream.put(request)
def IdleTimeoutNotification(self, dry_run=False):
msg = self.dispatcher.timeout_queue.get()
if dry_run:
print("P4 Runtime PacketIn: ", msg)
else:
return msg
class GrpcRequestLogger(grpc.UnaryUnaryClientInterceptor,
grpc.UnaryStreamClientInterceptor):
"""Implementation of a gRPC interceptor that logs request to a file"""
def __init__(self, log_file):
self.log_file = log_file
with open(self.log_file, 'w') as f:
# Clear content if it exists.
f.write("")
def log_message(self, method_name, body):
with open(self.log_file, 'a') as f:
ts = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
msg = str(body)
f.write("\n[%s] %s\n---\n" % (ts, method_name))
if len(msg) < MSG_LOG_MAX_LEN:
f.write(str(body))
else:
f.write("Message too long (%d bytes)! Skipping log...\n" % len(msg))
f.write('---\n')
def intercept_unary_unary(self, continuation, client_call_details, request):
self.log_message(client_call_details.method, request)
return continuation(client_call_details, request)
def intercept_unary_stream(self, continuation, client_call_details, request):
self.log_message(client_call_details.method, request)
return continuation(client_call_details, request)
class IterableQueue(Queue):
_sentinel = object()
def __iter__(self):
return iter(self.get, self._sentinel)
def close(self):
self.put(self._sentinel)