blob: 35f334c40dfad4e76a37d693cb09b2ed23f07c1e [file] [log] [blame]
Andreas Wundsam27303462013-07-16 12:52:35 -07001# Copyright 2013, Big Switch Networks, Inc.
2#
3# LoxiGen is licensed under the Eclipse Public License, version 1.0 (EPL), with
4# the following special exception:
5#
6# LOXI Exception
7#
8# As a special exception to the terms of the EPL, you may distribute libraries
9# generated by LoxiGen (LoxiGen Libraries) under the terms of your choice, provided
10# that copyright and licensing notices generated by LoxiGen are not altered or removed
11# from the LoxiGen Libraries and the notice provided below is (i) included in
12# the LoxiGen Libraries, if distributed in source code form and (ii) included in any
13# documentation for the LoxiGen Libraries, if distributed in binary form.
14#
15# Notice: "Copyright 2013, Big Switch Networks, Inc. This library was generated by the LoxiGen Compiler."
16#
17# You may not use this file except in compliance with the EPL or LOXI Exception. You may obtain
18# a copy of the EPL at:
19#
20# http://www.eclipse.org/legal/epl-v10.html
21#
22# Unless required by applicable law or agreed to in writing, software
23# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
24# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
25# EPL for the specific language governing permissions and limitations
26# under the EPL.
27
Andreas Wundsam40e14f72013-05-06 14:49:08 -070028# Prototype of an Intermediate Object model for the java code generator
29# A lot of this stuff could/should probably be merged with the python utilities
30
Andreas Wundsam27303462013-07-16 12:52:35 -070031import collections
32from collections import namedtuple, defaultdict
33import logging
Andreas Wundsam40e14f72013-05-06 14:49:08 -070034import os
35import pdb
36import re
37
Andreas Wundsam27303462013-07-16 12:52:35 -070038from generic_utils import find, memoize, OrderedSet
39import of_g
40from loxi_ir import *
Andreas Wundsam40e14f72013-05-06 14:49:08 -070041import loxi_front_end.type_maps as type_maps
42import loxi_utils.loxi_utils as utils
43import py_gen.util as py_utils
44
Andreas Wundsam27303462013-07-16 12:52:35 -070045import java_gen.java_type as java_type
Andreas Wundsam40e14f72013-05-06 14:49:08 -070046
Andreas Wundsam27303462013-07-16 12:52:35 -070047class JavaModel(object):
48 write_blacklist = defaultdict(lambda: set(), OFOxm=set(('typeLen',)))
49 virtual_interfaces = set(['OFOxm' ])
50
51 @property
52 @memoize
53 def versions(self):
54 return OrderedSet( JavaOFVersion(raw_version) for raw_version in of_g.target_version_list )
55
56 @property
57 @memoize
58 def interfaces(self):
59 version_map_per_class = collections.defaultdict(lambda: {})
60
61 for raw_version, of_protocol in of_g.ir.items():
62 jversion = JavaOFVersion(of_protocol.wire_version)
63
64 for of_class in of_protocol.classes:
65 version_map_per_class[of_class.name][jversion] = of_class
66
67 interfaces = []
68 for class_name, version_map in version_map_per_class.items():
69 interfaces.append(JavaOFInterface(class_name, version_map))
70
71 return interfaces
72
73 @property
74 @memoize
75 def enums(self):
76 enum_entry_version_value_map = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.OrderedDict()))
77
78 for version in self.versions:
79 of_protocol = of_g.ir[version.int_version]
80 for enum in of_protocol.enums:
81 for entry_name, entry_value in enum.values:
82 enum_entry_version_value_map[enum.name][entry_name][version] = entry_value
83
84 enums = [ JavaEnum(name, entry_version_value_map) for name, entry_version_value_map
85 in enum_entry_version_value_map.items() ]
86
87 return enums
88
89 @memoize
90 def enum_by_name(self, name):
91 try:
92 return find(self.enums, lambda e: e.name == name)
93 except KeyError:
94 raise KeyError("Could not find enum with name %s" % name)
95
96model = JavaModel()
97
98#######################################################################
99### OFVersion
100#######################################################################
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700101
102class JavaOFVersion(object):
103 """ Models a version of OpenFlow. contains methods to convert the internal
104 Loxi version to a java constant / a string """
105 def __init__(self, int_version):
106 self.int_version = int(int_version)
107
108 @property
109 def of_version(self):
110 return "1" + str(int(self.int_version) - 1)
111
112 @property
113 def constant_version(self):
114 return "OF_" + self.of_version
115
Andreas Wundsam27303462013-07-16 12:52:35 -0700116 def __repr__(self):
117 return "JavaOFVersion(%d)" % self.int_version
118
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700119 def __str__(self):
120 return of_g.param_version_names[self.int_version]
121
Andreas Wundsam27303462013-07-16 12:52:35 -0700122 def __hash__(self):
123 return hash(self.int_version)
124
125 def __eq__(self, other):
126 if other is None or type(self) != type(other):
127 return False
128 return (self.int_version,) == (other.int_version,)
129
130#######################################################################
131### Interface
132#######################################################################
133
134class JavaOFInterface(object):
135 """ Models an OpenFlow Message class for the purpose of the java class.
136 Version agnostic, in contrast to the loxi_ir python model.
137 """
138 def __init__(self, c_name, version_map):
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700139 self.c_name = c_name
Andreas Wundsam27303462013-07-16 12:52:35 -0700140 self.version_map = version_map
141 self.name = java_type.name_c_to_caps_camel(c_name)
142 self.builder_name = self.name + "Builder"
143 self.constant_name = c_name.upper().replace("OF_", "")
144
145 pck_suffix, parent_interface = self.class_info()
146 self.package = "org.openflow.protocol.%s" % pck_suffix if pck_suffix else "org.openflow.protocol"
147 if self.name != parent_interface:
148 self.parent_interface = parent_interface
149 else:
150 self.parent_interface = None
151
152 def class_info(self):
Yotam Harchol161a5d52013-07-25 17:17:48 -0700153 if re.match(r'OFFlow(Add|Modify(Strict)?|Delete(Strict)?)$', self.name):
Andreas Wundsam27303462013-07-16 12:52:35 -0700154 return ("", "OFFlowMod")
155 elif utils.class_is_message(self.c_name):
156 return ("", "OFMessage")
157 elif utils.class_is_action(self.c_name):
158 return ("action", "OFAction")
159 elif utils.class_is_oxm(self.c_name):
160 return ("oxm", "OFOxm")
161 elif utils.class_is_instruction(self.c_name):
162 return ("instruction", "OFInstruction")
163 elif utils.class_is_meter_band(self.c_name):
164 return ("meterband", "OFMeterBand")
165 else:
166 return ("", None)
167
168 @property
169 @memoize
170 def members(self):
171 all_versions = []
172 member_map = collections.OrderedDict()
173
174 for (version, of_class) in self.version_map.items():
175 for of_member in of_class.members:
176 if isinstance(of_member, OFLengthMember) or \
177 isinstance(of_member, OFFieldLengthMember) or \
178 isinstance(of_member, OFPadMember):
179 continue
180 if of_member.name not in member_map:
181 member_map[of_member.name] = JavaMember.for_of_member(self, of_member)
182
183 return member_map.values()
184
185 @property
186 @memoize
187 def is_virtual(self):
188 return self.name in model.virtual_interfaces
189
190 @property
191 @memoize
192 def all_versions(self):
193 return self.version_map.keys()
194
195 def versioned_class(self, version):
196 return JavaOFClass(self, version, self.version_map[version])
197
198 @property
199 @memoize
200 def versioned_classes(self):
201 if self.is_virtual:
202 return []
203 else:
204 return [ self.versioned_class(version) for version in self.all_versions ]
205
206#######################################################################
207### (Versioned) Classes
208#######################################################################
209
210class JavaOFClass(object):
211 """ Models an OpenFlow Message class for the purpose of the java class.
Andreas Wundsamd40ddbf2013-07-25 15:40:47 -0700212 Version specific child of a JavaOFInterface
Andreas Wundsam27303462013-07-16 12:52:35 -0700213 """
214 def __init__(self, interface, version, ir_class):
215 self.interface = interface
216 self.ir_class = ir_class
217 self.c_name = self.ir_class.name
218 self.version = version
219 self.constant_name = self.c_name.upper().replace("OF_", "")
220 self.package = "org.openflow.protocol.ver%s" % version.of_version
221
222 @property
223 def name(self):
224 return "%sVer%s" % (self.interface.name, self.version.of_version)
225
226 @property
227 def length(self):
228 if self.is_fixed_length:
229 return self.min_length
230 else:
231 raise Exception("No fixed length for class %s, version %s" % (self.name, self.version))
232
233 @property
234 def min_length(self):
235 id_tuple = (self.ir_class.name, self.version.int_version)
236 return of_g.base_length[id_tuple] if id_tuple in of_g.base_length else -1
237
238 @property
239 def is_fixed_length(self):
240 return (self.ir_class.name, self.version.int_version) in of_g.is_fixed_length
241
242 def all_properties(self):
243 return self.interface.members
244
245 def get_member(self, name):
246 for m in self.members:
247 if m.name == name:
248 return m
249
250 @property
251 @memoize
252 def data_members(self):
253 return [ prop for prop in self.members if prop.is_data ]
254
255 @property
256 @memoize
257 def fixed_value_members(self):
258 return [ prop for prop in self.members if prop.is_fixed_value ]
259
260 @property
261 @memoize
262 def public_members(self):
263 return [ prop for prop in self.members if prop.is_public ]
264
265 @property
266 @memoize
267 def members(self):
268 members = [ JavaMember.for_of_member(self, of_member) for of_member in self.ir_class.members ]
269 return members
270
271 def all_versions(self):
272 return [ JavaOFVersion(int_version)
273 for int_version in of_g.unified[self.c_name]
274 if int_version != 'union' and int_version != 'object_id' ]
275
276 def version_is_inherited(self, version):
277 return 'use_version' in of_g.unified[self.ir_class.name][version.int_version]
278
279 def inherited_from(self, version):
280 return JavaOFVersion(of_g.unified[self.ir_class.name][version.int_version]['use_version'])
281
282 @property
283 def is_virtual(self):
284 return type_maps.class_is_virtual(self.c_name)
285
286 @property
287 def is_extension(self):
288 return type_maps.message_is_extension(self.c_name, -1)
289
290#######################################################################
291### Member
292#######################################################################
293
294
295class JavaMember(object):
296 """ Models a property (member) of an openflow class. """
297 def __init__(self, msg, name, java_type, member):
298 self.msg = msg
299 self.name = name
300 self.java_type = java_type
301 self.member = member
302 self.c_name = self.member.name if(hasattr(self.member, "name")) else ""
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700303
304 @property
305 def title_name(self):
306 return self.name[0].upper() + self.name[1:]
307
308 @property
309 def constant_name(self):
310 return self.c_name.upper()
311
312 @property
313 def default_name(self):
Andreas Wundsam27303462013-07-16 12:52:35 -0700314 if self.is_fixed_value:
315 return self.constant_name
316 else:
317 return "DEFAULT_"+self.constant_name
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700318
319 @property
320 def default_value(self):
321 java_type = self.java_type.public_type;
322
Andreas Wundsam27303462013-07-16 12:52:35 -0700323 if self.is_fixed_value:
324 return self.enum_value
325 elif re.match(r'List.*', java_type):
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700326 return "Collections.emptyList()"
327 elif java_type == "boolean":
328 return "false";
329 elif java_type in ("byte", "char", "short", "int", "long"):
330 return "({0}) 0".format(java_type);
331 else:
332 return "null";
333
334 @property
Andreas Wundsam27303462013-07-16 12:52:35 -0700335 def enum_value(self):
336 if self.name == "version":
337 return "OFVersion.%s" % self.msg.version.constant_version
338
339 java_type = self.java_type.public_type;
340 try:
341 global model
342 enum = model.enum_by_name(java_type)
343 entry = enum.entry_by_version_value(self.msg.version, self.value)
344 return "%s.%s" % ( enum.name, entry.name)
345 except KeyError, e:
346 print e.message
347 return self.value
348
349 @property
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700350 def is_pad(self):
Andreas Wundsam27303462013-07-16 12:52:35 -0700351 return isinstance(self.member, OFPadMember)
352
353 def is_type_value(self, version=None):
354 if(version==None):
355 return any(self.is_type_value(version) for version in self.msg.all_versions)
356 try:
357 return self.c_name in get_type_values(self.msg.c_name, version.int_version)
358 except:
359 return False
360
361 @property
362 def is_field_length_value(self):
363 return isinstance(self.member, OFFieldLengthMember)
364
365 @property
366 def is_length_value(self):
367 return isinstance(self.member, OFLengthMember)
368
369 @property
370 def is_public(self):
371 return not (self.is_pad or self.is_length_value)
372
373 @property
374 def is_data(self):
375 return isinstance(self.member, OFDataMember) and self.name != "version"
376
377 @property
378 def is_fixed_value(self):
379 return hasattr(self.member, "value") or self.name == "version" \
380 or ( self.name == "length" and self.msg.is_fixed_length) \
381 or ( self.name == "len" and self.msg.is_fixed_length)
382
383 @property
384 def value(self):
385 if self.name == "version":
386 return self.msg.version.int_version
387 elif self.name == "length" or self.name == "len":
388 return self.msg.length
389 elif self.java_type.public_type in ("int", "short", "byte") and self.member.value > 100:
390 return "0x%x" % self.member.value
391 else:
392 return self.member.value
393
394 @property
395 def is_writeable(self):
396 return self.is_data and not self.name in model.write_blacklist[self.msg.name]
397
398 def get_type_value_info(self, version):
399 return get_type_values(msg.c_name, version.int_version)[self.c_name]
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700400
401 @property
402 def length(self):
Andreas Wundsam27303462013-07-16 12:52:35 -0700403 if hasattr(self.member, "length"):
404 return self.member.length
405 else:
406 count, base = utils.type_dec_to_count_base(self.member.type)
407 return of_g.of_base_types[base]['bytes'] * count
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700408
409 @staticmethod
Andreas Wundsam27303462013-07-16 12:52:35 -0700410 def for_of_member(java_class, member):
411 if isinstance(member, OFPadMember):
412 return JavaMember(None, "", None, member)
413 else:
414 if member.name == 'len':
415 name = 'length'
416 else:
417 name = java_type.name_c_to_camel(member.name)
418 j_type = java_type.convert_to_jtype(java_class.c_name, member.name, member.oftype)
419 return JavaMember(java_class, name, j_type, member)
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700420
421 @property
422 def is_universal(self):
Andreas Wundsam27303462013-07-16 12:52:35 -0700423 if not self.msg.c_name in of_g.unified:
424 print("%s not self.unified" % self.msg.c_name)
425 return False
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700426 for version in of_g.unified[self.msg.c_name]:
427 if version == 'union' or version =='object_id':
428 continue
429 if 'use_version' in of_g.unified[self.msg.c_name][version]:
430 continue
431
Andreas Wundsam27303462013-07-16 12:52:35 -0700432 if not self.member.name in (f['name'] for f in of_g.unified[self.msg.c_name][version]['members']):
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700433 return False
434 return True
435
Andreas Wundsam27303462013-07-16 12:52:35 -0700436 def __hash__(self):
437 return hash(self.name)
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700438
Andreas Wundsam27303462013-07-16 12:52:35 -0700439 def __eq__(self, other):
440 if other is None or type(self) != type(other):
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700441 return False
Andreas Wundsam27303462013-07-16 12:52:35 -0700442 return (self.name,) == (other.name,)
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700443
Andreas Wundsam27303462013-07-16 12:52:35 -0700444#######################################################################
445### Enums
446#######################################################################
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700447
Andreas Wundsam27303462013-07-16 12:52:35 -0700448class JavaEnum(object):
449 def __init__(self, c_name, entry_version_value_map):
450 self.c_name = c_name
451 self.name = "OF" + java_type.name_c_to_caps_camel("_".join(c_name.split("_")[1:]))
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700452
Andreas Wundsam27303462013-07-16 12:52:35 -0700453 # Port_features has constants that start with digits
454 self.name_prefix = "PF_" if self.name == "OFPortFeatures" else ""
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700455
Andreas Wundsam27303462013-07-16 12:52:35 -0700456 self.entries = [ JavaEnumEntry(self, name, version_value_map)
457 for (name, version_value_map) in entry_version_value_map.items() ]
458 self.package = "org.openflow.protocol"
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700459
Andreas Wundsam27303462013-07-16 12:52:35 -0700460 @memoize
461 def entry_by_name(self, name):
Andreas Wundsam40e14f72013-05-06 14:49:08 -0700462 try:
Andreas Wundsam27303462013-07-16 12:52:35 -0700463 return find(self.entries, lambda e: e.name == name)
464 except KeyError:
465 raise KeyError("Enum %s: no entry with name %s" % (self.name, name))
466
467 @memoize
468 def entry_by_c_name(self, name):
469 try:
470 return find(self.entries, lambda e: e.c_name == name)
471 except KeyError:
472 raise KeyError("Enum %s: no entry with c_name %s" % (self.name, name))
473
474 @memoize
475 def entry_by_version_value(self, version, value):
476 try:
477 return find(self.entries, lambda e: e.values[version] == value if version in e.values else False )
478 except KeyError:
479 raise KeyError("Enum %s: no entry with version %s, value %s" % (self.name, version, value))
480
481# values: Map JavaVersion->Value
482class JavaEnumEntry(object):
483 def __init__(self, enum, name, values):
484 self.name = enum.name_prefix + "_".join(name.split("_")[1:]).upper()
485 self.values = values
486
487 def value(self, version):
488 res = self.version_value_map[version]
489 return res
490
Andreas Wundsam27303462013-07-16 12:52:35 -0700491 def all_values(self, versions, not_present=None):
492 return [ self.values[version] if version in self.values else not_present for version in versions ]