Modernize test-common's use of NotificationService
[openflowplugin.git] / test-common / src / main / java / org / opendaylight / openflowplugin / testcommon / AbstractDropTest.java
1 /*
2  * Copyright (c) 2014, 2015 Cisco Systems, Inc. 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 package org.opendaylight.openflowplugin.testcommon;
9
10 import com.google.common.util.concurrent.ThreadFactoryBuilder;
11 import java.util.Arrays;
12 import java.util.Collections;
13 import java.util.concurrent.ArrayBlockingQueue;
14 import java.util.concurrent.ExecutorService;
15 import java.util.concurrent.RejectedExecutionException;
16 import java.util.concurrent.ThreadPoolExecutor;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
19 import org.opendaylight.mdsal.binding.api.NotificationService.Listener;
20 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.IetfYangUtil;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.DropActionCase;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.DropActionCaseBuilder;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.drop.action._case.DropActionBuilder;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Instructions;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCaseBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActions;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActionsBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetSourceBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
41 import org.opendaylight.yangtools.yang.common.Uint16;
42 import org.opendaylight.yangtools.yang.common.Uint32;
43 import org.opendaylight.yangtools.yang.common.Uint8;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 abstract class AbstractDropTest implements Listener<PacketReceived>, AutoCloseable {
48     private static final Logger LOG = LoggerFactory.getLogger(AbstractDropTest.class);
49
50     protected static final Uint16 PRIORITY = Uint16.valueOf(4);
51     protected static final Uint32 BUFFER_ID = Uint32.ZERO;
52     protected static final Uint16 HARD_TIMEOUT = Uint16.valueOf(300);
53     protected static final Uint16 IDLE_TIMEOUT = Uint16.valueOf(240);
54     protected static final Uint8 TABLE_ID = Uint8.ZERO;
55
56     static final long STARTUP_LOOP_TICK = 500L;
57     static final int STARTUP_LOOP_MAX_RETRIES = 8;
58     private static final int PROCESSING_POOL_SIZE = 10000;
59
60     private static final int POOL_THREAD_AMOUNT = 8;
61     private final ExecutorService executorService;
62
63
64     private static final AtomicIntegerFieldUpdater<AbstractDropTest> SENT_UPDATER = AtomicIntegerFieldUpdater
65             .newUpdater(AbstractDropTest.class, "sent");
66     private volatile int sent;
67
68     private static final AtomicIntegerFieldUpdater<AbstractDropTest> RCVD_UPDATER = AtomicIntegerFieldUpdater
69             .newUpdater(AbstractDropTest.class, "rcvd");
70     private volatile int rcvd;
71
72     private static final AtomicIntegerFieldUpdater<AbstractDropTest> EXCS_UPDATER = AtomicIntegerFieldUpdater
73             .newUpdater(AbstractDropTest.class, "excs");
74     private volatile int excs;
75
76     protected static final AtomicIntegerFieldUpdater<AbstractDropTest> RPC_FUTURE_SUCCESS_UPDATER =
77             AtomicIntegerFieldUpdater.newUpdater(AbstractDropTest.class, "ftrSuccess");
78     protected volatile int ftrSuccess;
79
80     protected static final AtomicIntegerFieldUpdater<AbstractDropTest> RPC_FUTURE_FAIL_UPDATER =
81             AtomicIntegerFieldUpdater.newUpdater(AbstractDropTest.class, "ftrFailed");
82     protected volatile int ftrFailed;
83
84     protected static final AtomicIntegerFieldUpdater<AbstractDropTest> RUNABLES_EXECUTED = AtomicIntegerFieldUpdater
85             .newUpdater(AbstractDropTest.class, "runablesExecuted");
86     protected volatile int runablesExecuted;
87
88     protected static final AtomicIntegerFieldUpdater<AbstractDropTest> RUNABLES_REJECTED = AtomicIntegerFieldUpdater
89             .newUpdater(AbstractDropTest.class, "runablesRejected");
90     protected volatile int runablesRejected;
91
92     public final DropTestStats getStats() {
93         return new DropTestStats(sent, rcvd, excs, ftrFailed, ftrSuccess, runablesExecuted, runablesRejected);
94     }
95
96     AbstractDropTest() {
97         final ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(PROCESSING_POOL_SIZE);
98         final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(POOL_THREAD_AMOUNT, POOL_THREAD_AMOUNT, 0,
99                 TimeUnit.MILLISECONDS,
100                 workQueue);
101         threadPool.setThreadFactory(new ThreadFactoryBuilder().setNameFormat("dropTest-%d").build());
102         threadPool.setRejectedExecutionHandler((rejected, executor) -> {
103             try {
104                 workQueue.put(rejected);
105             } catch (final InterruptedException e) {
106                 throw new RejectedExecutionException("Interrupted while waiting on queue", e);
107             }
108         });
109
110         executorService = threadPool;
111     }
112
113     public final void clearStats() {
114         sent = 0;
115         rcvd = 0;
116         excs = 0;
117         ftrSuccess = 0;
118         ftrFailed = 0;
119         runablesExecuted = 0;
120         runablesRejected = 0;
121     }
122
123     private void incrementRunableExecuted() {
124         RUNABLES_EXECUTED.incrementAndGet(this);
125     }
126
127     private void incrementRunableRejected() {
128         RUNABLES_REJECTED.incrementAndGet(this);
129     }
130
131     @Override
132     public final void onNotification(final PacketReceived notification) {
133         LOG.debug("onPacketReceived - Entering - {}", notification);
134
135         RCVD_UPDATER.incrementAndGet(this);
136
137         try {
138             executorService.execute(() -> {
139                 incrementRunableExecuted();
140                 processPacket(notification);
141             });
142         } catch (RejectedExecutionException e) {
143             incrementRunableRejected();
144         }
145         LOG.debug("onPacketReceived - {} Leaving", notification);
146     }
147
148     private static final Instructions DROP_INSTRUCTIONS = makeStaticDropActionInstructions();
149
150     private static Instructions makeStaticDropActionInstructions() {
151         // Create an DropAction
152         final DropActionCase dropAction = new DropActionCaseBuilder().setDropAction(
153                 new DropActionBuilder().build()).build();
154         // Create an Action
155         final Action ab = new ActionBuilder().setOrder(0).setAction(dropAction).build();
156         // Create an Apply Action
157         final ApplyActions aab = new ApplyActionsBuilder().setAction(Collections.singletonMap(ab.key(), ab)).build();
158         // Wrap our Apply Action in an Instruction
159         final Instruction ib = new InstructionBuilder()
160                 .setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab).build()).setOrder(0).build();
161         // Put our Instruction in a list of Instructions
162         return new InstructionsBuilder().setInstruction(Collections.singletonMap(ib.key(), ib)).build();
163     }
164
165     @SuppressWarnings("checkstyle:IllegalCatch")
166     private void processPacket(final PacketReceived notification) {
167         try {
168             final byte[] rawPacket = notification.getPayload();
169             final byte[] srcMac = Arrays.copyOfRange(rawPacket, 6, 12);
170
171             final MatchBuilder match = new MatchBuilder();
172             final EthernetMatchBuilder ethernetMatch = new EthernetMatchBuilder();
173             final EthernetSourceBuilder ethSourceBuilder = new EthernetSourceBuilder();
174
175             //TODO: use HEX, use binary form
176             //Hex.decodeHex("000000000001".toCharArray());
177
178             ethSourceBuilder.setAddress(IetfYangUtil.INSTANCE.macAddressFor(srcMac));
179             ethernetMatch.setEthernetSource(ethSourceBuilder.build());
180             match.setEthernetMatch(ethernetMatch.build());
181
182             // Get the Ingress nodeConnectorRef
183             final NodeConnectorRef ncr = notification.getIngress();
184
185             // Get the instance identifier for the nodeConnectorRef
186             final InstanceIdentifier<?> ncri = ncr.getValue();
187
188             processPacket(ncri.firstIdentifierOf(Node.class), match.build(), DROP_INSTRUCTIONS);
189
190             SENT_UPDATER.incrementAndGet(this);
191         } catch (RuntimeException e) {
192             LOG.warn("Failed to process packet: {}", e.getMessage());
193             LOG.debug("Failed to process packet.. ", e);
194             EXCS_UPDATER.incrementAndGet(this);
195         }
196     }
197
198     protected abstract void processPacket(InstanceIdentifier<Node> node, Match match, Instructions instructions);
199
200
201     @Override
202     public void close() {
203         executorService.shutdown();
204     }
205
206     public void countFutureSuccess() {
207         RPC_FUTURE_SUCCESS_UPDATER.incrementAndGet(this);
208     }
209
210     public void countFutureError() {
211         RPC_FUTURE_FAIL_UPDATER.incrementAndGet(this);
212     }
213 }