Merge "Fix checkstyle warnings for impl/protocol package"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / protocol / serialization / messages / FlowMessageSerializer.java
1 /*
2  * Copyright (c) 2016 Pantheon Technologies s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.openflowplugin.impl.protocol.serialization.messages;
10
11 import com.google.common.base.MoreObjects;
12 import io.netty.buffer.ByteBuf;
13 import java.math.BigInteger;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.List;
17 import java.util.Objects;
18 import java.util.Optional;
19 import java.util.stream.Collectors;
20 import org.opendaylight.openflowjava.protocol.api.extensibility.OFSerializer;
21 import org.opendaylight.openflowjava.protocol.api.extensibility.SerializerRegistry;
22 import org.opendaylight.openflowjava.protocol.api.extensibility.SerializerRegistryInjector;
23 import org.opendaylight.openflowjava.protocol.api.keys.MessageTypeKey;
24 import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;
25 import org.opendaylight.openflowjava.util.ByteBufUtils;
26 import org.opendaylight.openflowplugin.api.OFConstants;
27 import org.opendaylight.openflowplugin.impl.protocol.serialization.util.InstructionUtil;
28 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.common.OrderComparator;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.ActionList;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.VlanCfi;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.PushVlanActionCaseBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetTpDstActionCase;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetTpDstActionCaseBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetTpSrcActionCase;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetTpSrcActionCaseBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetVlanIdActionCase;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.push.vlan.action._case.PushVlanActionBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.tp.dst.action._case.SetTpDstActionBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.tp.src.action._case.SetTpSrcActionBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.Flow;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowMessage;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowMessageBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowModFlags;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.Instruction;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCase;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCaseBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActionsBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.Match;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatch;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatchBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.vlan.match.fields.VlanIdBuilder;
59
60 /**
61  * Translates FlowMod messages.
62  * OF protocol versions: 1.3
63  */
64 public class FlowMessageSerializer extends AbstractMessageSerializer<FlowMessage> implements
65         SerializerRegistryInjector {
66     private static final FlowCookie DEFAULT_COOKIE = new FlowCookie(OFConstants.DEFAULT_COOKIE);
67     private static final FlowCookie DEFAULT_COOKIE_MASK = new FlowCookie(OFConstants.DEFAULT_COOKIE_MASK);
68     private static final Short DEFAULT_TABLE_ID = (short) 0;
69     private static final Integer DEFAULT_IDLE_TIMEOUT = 0;
70     private static final Integer DEFAULT_HARD_TIMEOUT = 0;
71     private static final Integer DEFAULT_PRIORITY = OFConstants.DEFAULT_FLOW_PRIORITY;
72     private static final Long DEFAULT_BUFFER_ID = OFConstants.OFP_NO_BUFFER;
73     private static final BigInteger DEFAULT_OUT_PORT = BigInteger.valueOf(OFConstants.OFPP_ANY);
74     private static final Long DEFAULT_OUT_GROUP = OFConstants.OFPG_ANY;
75     private static final byte PADDING_IN_FLOW_MOD_MESSAGE = 2;
76     private static final FlowModFlags DEFAULT_FLAGS = new FlowModFlags(false, false, false, false, false);
77     private static final Integer PUSH_VLAN = 0x8100;
78
79     private static final VlanMatch VLAN_MATCH_FALSE = new VlanMatchBuilder()
80             .setVlanId(new VlanIdBuilder()
81                     .setVlanIdPresent(false)
82                     .setVlanId(new VlanId(0))
83                     .build())
84             .build();
85
86     private static final VlanMatch VLAN_MATCH_TRUE = new VlanMatchBuilder()
87             .setVlanId(new VlanIdBuilder()
88                     .setVlanIdPresent(true)
89                     .setVlanId(new VlanId(0))
90                     .build())
91             .build();
92
93     private SerializerRegistry registry;
94
95     @Override
96     public void serialize(FlowMessage message, ByteBuf outBuffer) {
97         if (!isVlanMatchPresent(message) && isSetVlanIdActionCasePresent(message)) {
98             writeVlanFlow(message, outBuffer);
99         } else {
100             writeFlow(message, outBuffer);
101         }
102     }
103
104     /**
105      * Serialize flow message. Needs to be separated from main serialize method to prevent recursion
106      * when serializing SetVlanId flows.
107      *
108      * @param message   flow message
109      * @param outBuffer output buffer
110      */
111     private void writeFlow(final FlowMessage message, final ByteBuf outBuffer) {
112         final int index = outBuffer.writerIndex();
113         super.serialize(message, outBuffer);
114         outBuffer.writeLong(MoreObjects.firstNonNull(message.getCookie(), DEFAULT_COOKIE).getValue().longValue());
115         outBuffer.writeLong(MoreObjects.firstNonNull(message.getCookieMask(), DEFAULT_COOKIE_MASK).getValue()
116                 .longValue());
117         outBuffer.writeByte(MoreObjects.firstNonNull(message.getTableId(), DEFAULT_TABLE_ID));
118         outBuffer.writeByte(message.getCommand().getIntValue());
119         outBuffer.writeShort(MoreObjects.firstNonNull(message.getIdleTimeout(), DEFAULT_IDLE_TIMEOUT));
120         outBuffer.writeShort(MoreObjects.firstNonNull(message.getHardTimeout(), DEFAULT_HARD_TIMEOUT));
121         outBuffer.writeShort(MoreObjects.firstNonNull(message.getPriority(), DEFAULT_PRIORITY));
122         outBuffer.writeInt(MoreObjects.firstNonNull(message.getBufferId(), DEFAULT_BUFFER_ID).intValue());
123         outBuffer.writeInt(MoreObjects.firstNonNull(message.getOutPort(), DEFAULT_OUT_PORT).intValue());
124         outBuffer.writeInt(MoreObjects.firstNonNull(message.getOutGroup(), DEFAULT_OUT_GROUP).intValue());
125         outBuffer.writeShort(createFlowModFlagsBitmask(MoreObjects.firstNonNull(message.getFlags(), DEFAULT_FLAGS)));
126         outBuffer.writeZero(PADDING_IN_FLOW_MOD_MESSAGE);
127         writeMatch(message, outBuffer);
128         writeInstructions(message, outBuffer);
129         outBuffer.setShort(index + 2, outBuffer.writerIndex() - index);
130     }
131
132     /**
133      * Instead of serializing this flow normally, we need to split it to two parts if flow contains
134      * #{@link org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetVlanIdActionCase}.
135      *
136      * @param message   flow mod message
137      * @param outBuffer output buffer
138      */
139     private void writeVlanFlow(final FlowMessage message, final ByteBuf outBuffer) {
140         writeFlow(
141                 new FlowMessageBuilder(message)
142                         .setMatch(new MatchBuilder(message.getMatch())
143                                 .setVlanMatch(VLAN_MATCH_FALSE)
144                                 .build())
145                         .setInstructions(new InstructionsBuilder()
146                                 .setInstruction(updateSetVlanIdAction(message))
147                                 .build())
148                         .build(),
149                 outBuffer);
150
151         writeFlow(
152                 new FlowMessageBuilder(message)
153                         .setMatch(new MatchBuilder(message.getMatch())
154                                 .setVlanMatch(VLAN_MATCH_TRUE)
155                                 .build())
156                         .build(),
157                 outBuffer);
158     }
159
160     /**
161      * Serialize OpenFlowPlugin match to raw bytes.
162      *
163      * @param message   OpenFlow flow mod message
164      * @param outBuffer output buffer
165      */
166     private void writeMatch(final FlowMessage message, final ByteBuf outBuffer) {
167         registry.<Match, OFSerializer<Match>>getSerializer(new MessageTypeKey<>(message.getVersion(), Match.class))
168                 .serialize(message.getMatch(), outBuffer);
169
170     }
171
172     /**
173      * Serialize OpenFlowPlugin instructions and set ip protocol of set-tp-src and set-tp-dst actions of need.
174      *
175      * @param message   OpenFlow flow mod message
176      * @param outBuffer output buffer
177      */
178     @SuppressWarnings("unchecked")
179     private void writeInstructions(final FlowMessage message, final ByteBuf outBuffer) {
180         // Try to get IP protocol from IP match
181         final Optional<Short> protocol = Optional
182                 .ofNullable(message.getMatch())
183                 .flatMap(m -> Optional.ofNullable(m.getIpMatch()))
184                 .flatMap(ipm -> Optional.ofNullable(ipm.getIpProtocol()));
185
186         // Update instructions if needed and then serialize all instructions
187         Optional.ofNullable(message.getInstructions())
188                 .flatMap(is -> Optional.ofNullable(is.getInstruction()))
189                 .ifPresent(is -> is
190                         .stream()
191                         .filter(Objects::nonNull)
192                         .sorted(OrderComparator.build())
193                         .map(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types
194                                 .rev131026.Instruction::getInstruction)
195                         .filter(Objects::nonNull)
196                         .map(i -> protocol.flatMap(p -> updateInstruction(i, p)).orElse(i))
197                         .forEach(i -> InstructionUtil.writeInstruction(i, EncodeConstants.OF13_VERSION_ID, registry,
198                                 outBuffer)));
199     }
200
201     /**
202      * Determine type of instruction and update it's actions if it is apply-actions instruction.
203      *
204      * @param instruction instruction
205      * @param protocol    protocol
206      * @return updated instruction or empty
207      */
208     private static Optional<Instruction> updateInstruction(final Instruction instruction, final Short protocol) {
209         if (ApplyActionsCase.class.isInstance(instruction)) {
210             return Optional
211                     .ofNullable(ApplyActionsCase.class.cast(instruction).getApplyActions())
212                     .flatMap(aa -> Optional.ofNullable(aa.getAction()))
213                     .map(as -> new ApplyActionsCaseBuilder()
214                             .setApplyActions(new ApplyActionsBuilder()
215                                     .setAction(as
216                                             .stream()
217                                             .filter(Objects::nonNull)
218                                             .map(a -> updateSetTpActions(a, protocol))
219                                             .collect(Collectors.toList()))
220                                     .build())
221                             .build());
222         }
223
224         return Optional.empty();
225     }
226
227     /**
228      * If action is set-tp-src or set-tp-dst, inject IP protocol into it, otherwise return original action.
229      *
230      * @param action   OpenFlow action
231      * @param protocol IP protocol
232      * @return updated OpenFlow action
233      */
234     private static Action updateSetTpActions(Action action, Short protocol) {
235         if (SetTpSrcActionCase.class.isInstance(action.getAction())) {
236             final SetTpSrcActionCase actionCase = SetTpSrcActionCase.class.cast(action.getAction());
237
238             return new ActionBuilder(action)
239                     .setAction(new SetTpSrcActionCaseBuilder(actionCase)
240                             .setSetTpSrcAction(new SetTpSrcActionBuilder(
241                                     actionCase.getSetTpSrcAction())
242                                     .setIpProtocol(protocol)
243                                     .build())
244                             .build())
245                     .build();
246         } else if (SetTpDstActionCase.class.isInstance(action.getAction())) {
247             final SetTpDstActionCase actionCase = SetTpDstActionCase.class.cast(action.getAction());
248
249             return new ActionBuilder(action)
250                     .setAction(new SetTpDstActionCaseBuilder(actionCase)
251                             .setSetTpDstAction(new SetTpDstActionBuilder(
252                                     actionCase.getSetTpDstAction())
253                                     .setIpProtocol(protocol)
254                                     .build())
255                             .build())
256                     .build();
257         }
258
259         // Return original action if no modifications are needed
260         return action;
261     }
262
263     /**
264      * Create copy of instructions of original flow but insert
265      * #{@link org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.PushVlanActionCase}
266      * before each
267      * #{@link org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetVlanIdActionCase}.
268      *
269      * @param message OpenFlowPlugin flow mod message
270      * @return list of instructions
271      */
272     private static List<org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list
273             .Instruction> updateSetVlanIdAction(final FlowMessage message) {
274         return message.getInstructions().getInstruction()
275                 .stream()
276                 .map(i -> {
277                     final int[] offset = {0};
278
279                     return ApplyActionsCase.class.isInstance(i.getInstruction())
280                             ? Optional
281                             .ofNullable(ApplyActionsCase.class.cast(i.getInstruction()).getApplyActions())
282                             .flatMap(as -> Optional.ofNullable(as.getAction()))
283                             .map(a -> a.stream()
284                                     .sorted(OrderComparator.build())
285                                     .flatMap(action -> {
286                                         final List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112
287                                                 .action.list.Action> actions = new ArrayList<>();
288
289                                         // If current action is SetVlanId, insert PushVlan action before it and
290                                         // update order
291                                         if (SetVlanIdActionCase.class.isInstance(action.getAction())) {
292                                             actions.add(new ActionBuilder()
293                                                     .setAction(new PushVlanActionCaseBuilder()
294                                                             .setPushVlanAction(new PushVlanActionBuilder()
295                                                                     .setCfi(new VlanCfi(1))
296                                                                     .setVlanId(SetVlanIdActionCase.class.cast(action
297                                                                             .getAction()).getSetVlanIdAction()
298                                                                             .getVlanId())
299                                                                     .setEthernetType(PUSH_VLAN)
300                                                                     .setTag(PUSH_VLAN)
301                                                                     .build())
302                                                             .build())
303                                                     .setKey(action.getKey())
304                                                     .setOrder(action.getOrder() + offset[0])
305                                                     .build());
306
307                                             offset[0]++;
308                                         }
309
310                                         // Update offset of action if there is any inserted PushVlan actions
311                                         actions.add(offset[0] > 0
312                                                 ? new ActionBuilder(action).setOrder(action.getOrder() + offset[0])
313                                                 .build()
314                                                 : action);
315
316                                         return actions.stream();
317                                     }))
318                             .map(as -> new InstructionBuilder(i)
319                                     .setInstruction(new ApplyActionsCaseBuilder()
320                                             .setApplyActions(new ApplyActionsBuilder()
321                                                     .setAction(as.collect(Collectors.toList()))
322                                                     .build())
323                                             .build())
324                                     .build())
325                             .orElse(i)
326                             : i;
327                 }).collect(Collectors.toList());
328     }
329
330     /**
331      * Create integer bit mask from
332      * #{@link org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowModFlags}.
333      *
334      * @param flags flow mod flags
335      * @return bit mask
336      */
337     private static int createFlowModFlagsBitmask(final FlowModFlags flags) {
338         return ByteBufUtils.fillBitMask(0,
339                 flags.isSENDFLOWREM(),
340                 flags.isCHECKOVERLAP(),
341                 flags.isRESETCOUNTS(),
342                 flags.isNOPKTCOUNTS(),
343                 flags.isNOBYTCOUNTS());
344     }
345
346     /**
347      * Determine if flow contains vlan match.
348      *
349      * @param flow flow
350      * @return true if flow contains vlan match
351      */
352     private static boolean isVlanMatchPresent(final Flow flow) {
353         return Optional
354                 .ofNullable(flow.getMatch())
355                 .flatMap(m -> Optional.ofNullable(m.getVlanMatch()))
356                 .isPresent();
357     }
358
359     /**
360      * Determine if flow contains
361      * #{@link org.opendaylight.yang.gen.v1.urn.opendaylight
362      * .flow.types.rev131026.instruction.instruction.ApplyActionsCase} instruction with
363      * #{@link org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetVlanIdActionCase}
364      * action.
365      *
366      * @param flow OpenFlowPlugin flow
367      * @return true if flow contains SetVlanIdAction
368      */
369     private static boolean isSetVlanIdActionCasePresent(final Flow flow) {
370         return Optional
371                 .ofNullable(flow.getInstructions())
372                 .flatMap(is -> Optional.ofNullable(is.getInstruction()))
373                 .flatMap(is -> is
374                         .stream()
375                         .map(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types
376                                 .rev131026.Instruction::getInstruction)
377                         .filter(ApplyActionsCase.class::isInstance)
378                         .map(i -> ApplyActionsCase.class.cast(i).getApplyActions())
379                         .filter(Objects::nonNull)
380                         .map(ActionList::getAction)
381                         .filter(Objects::nonNull)
382                         .flatMap(Collection::stream)
383                         .map(Action::getAction)
384                         .filter(SetVlanIdActionCase.class::isInstance)
385                         .findFirst())
386                 .isPresent();
387     }
388
389     @Override
390     protected byte getMessageType() {
391         return 14;
392     }
393
394     @Override
395     public void injectSerializerRegistry(SerializerRegistry serializerRegistry) {
396         registry = serializerRegistry;
397     }
398 }