2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay;
11 import java.util.ArrayList;
12 import java.util.List;
13 import java.util.Map.Entry;
15 import java.util.concurrent.Callable;
16 import java.util.concurrent.CompletionService;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.ExecutorCompletionService;
19 import java.util.concurrent.ScheduledExecutorService;
20 import java.util.concurrent.TimeUnit;
22 import com.google.common.base.Function;
23 import com.google.common.base.Optional;
24 import com.google.common.collect.ImmutableList;
25 import com.google.common.util.concurrent.AsyncFunction;
26 import com.google.common.util.concurrent.Futures;
27 import com.google.common.util.concurrent.ListenableFuture;
28 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
29 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
30 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
31 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
32 import org.opendaylight.groupbasedpolicy.endpoint.EpKey;
33 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.endpoint.EndpointManager;
34 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.DestinationMapper;
35 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.EgressNatMapper;
36 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.ExternalMapper;
37 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils;
38 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.GroupTable;
39 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.IngressNatMapper;
40 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.OfTable;
41 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.PolicyEnforcer;
42 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.PortSecurity;
43 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.SourceMapper;
44 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.node.SwitchListener;
45 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.node.SwitchManager;
46 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf.Action;
47 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf.SubjectFeatures;
48 import org.opendaylight.groupbasedpolicy.resolver.EgKey;
49 import org.opendaylight.groupbasedpolicy.resolver.PolicyInfo;
50 import org.opendaylight.groupbasedpolicy.resolver.PolicyListener;
51 import org.opendaylight.groupbasedpolicy.resolver.PolicyResolver;
52 import org.opendaylight.groupbasedpolicy.resolver.PolicyScope;
53 import org.opendaylight.groupbasedpolicy.util.SingletonTask;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ActionDefinitionId;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayConfig.LearningMode;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId;
59 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
64 * Manage policies on switches by subscribing to updates from the
65 * policy resolver and information about endpoints from the endpoint
68 public class PolicyManager
69 implements SwitchListener, PolicyListener, EndpointListener {
70 private static final Logger LOG =
71 LoggerFactory.getLogger(PolicyManager.class);
73 private short tableOffset;
74 private static final short TABLEID_PORTSECURITY = 0;
75 private static final short TABLEID_INGRESS_NAT = 1;
76 private static final short TABLEID_SOURCE_MAPPER = 2;
77 private static final short TABLEID_DESTINATION_MAPPER = 3;
78 private static final short TABLEID_POLICY_ENFORCER = 4;
79 private static final short TABLEID_EGRESS_NAT = 5;
80 private static final short TABLEID_EXTERNAL_MAPPER = 6;
82 private final SwitchManager switchManager;
83 private final PolicyResolver policyResolver;
85 private final PolicyScope policyScope;
87 private final ScheduledExecutorService executor;
88 private final SingletonTask flowUpdateTask;
89 private final DataBroker dataBroker;
90 private final OfContext ofCtx;
92 * The flow tables that make up the processing pipeline
94 private List<? extends OfTable> flowPipeline;
97 * The delay before triggering the flow update task in response to an
98 * event in milliseconds.
100 private final static int FLOW_UPDATE_DELAY = 250;
102 public PolicyManager(DataBroker dataBroker,
103 PolicyResolver policyResolver,
104 SwitchManager switchManager,
105 EndpointManager endpointManager,
106 RpcProviderRegistry rpcRegistry,
107 ScheduledExecutorService executor,
110 this.switchManager = switchManager;
111 this.executor = executor;
112 this.policyResolver = policyResolver;
113 this.dataBroker = dataBroker;
114 this.tableOffset = tableOffset;
116 // to validate against model
117 verifyMaxTableId(tableOffset);
118 } catch (IllegalArgumentException e) {
119 throw new IllegalArgumentException("Failed to start OF-Overlay renderer\n."
120 + "Max. table ID would be out of range. Check config-subsystem.\n{}", e);
123 for(Entry<ActionDefinitionId, Action> entry : SubjectFeatures.getActions().entrySet()) {
124 policyResolver.registerActionDefinitions(entry.getKey(), entry.getValue());
127 ofCtx = new OfContext(dataBroker, rpcRegistry,
128 this, policyResolver, switchManager,
129 endpointManager, executor);
131 flowPipeline = createFlowPipeline();
133 policyScope = policyResolver.registerListener(this);
134 if (switchManager != null)
135 switchManager.registerListener(this);
136 endpointManager.registerListener(this);
138 flowUpdateTask = new SingletonTask(executor, new FlowUpdateTask());
141 LOG.debug("Initialized OFOverlay policy manager");
144 private List<? extends OfTable> createFlowPipeline() {
145 // TODO - PORTSECURITY is kept in table 0.
146 // According to openflow spec,processing on vSwitch always starts from table 0.
147 // Packets will be droped if table 0 is empty.
148 // Alternative workaround - table-miss flow entries in table 0.
149 return ImmutableList.of(new PortSecurity(ofCtx, (short) 0),
150 new GroupTable(ofCtx),
151 new IngressNatMapper(ofCtx, getTABLEID_INGRESS_NAT()),
152 new SourceMapper(ofCtx, getTABLEID_SOURCE_MAPPER()),
153 new DestinationMapper(ofCtx, getTABLEID_DESTINATION_MAPPER()),
154 new PolicyEnforcer(ofCtx, getTABLEID_POLICY_ENFORCER()),
155 new EgressNatMapper(ofCtx, getTABLEID_EGRESS_NAT()),
156 new ExternalMapper(ofCtx, getTABLEID_EXTERNAL_MAPPER())
161 * @param tableOffset the new offset value
162 * @return {@link ListenableFuture} to indicate that tables have been synced
164 public ListenableFuture<Void> changeOpenFlowTableOffset(final short tableOffset) {
166 verifyMaxTableId(tableOffset);
167 } catch (IllegalArgumentException e) {
168 LOG.error("Cannot update table offset. Max. table ID would be out of range.\n{}", e);
169 // TODO - invalid offset value remains in conf DS
170 // It's not possible to validate offset value by using constrains in model,
171 // because number of tables in pipeline varies.
172 return Futures.immediateFuture(null);
174 List<Short> tableIDs = getTableIDs();
175 this.tableOffset = tableOffset;
176 return Futures.transform(removeUnusedTables(tableIDs), new Function<Void, Void>() {
179 public Void apply(Void tablesRemoved) {
180 flowPipeline = createFlowPipeline();
188 * @param tableIDs - IDs of tables to delete
189 * @return ListenableFuture<Void> - which will be filled when clearing is done
191 private ListenableFuture<Void> removeUnusedTables(final List<Short> tableIDs) {
192 List<ListenableFuture<Void>> checkList = new ArrayList<>();
193 final ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
194 for (Short tableId : tableIDs) {
195 for (NodeId nodeId : switchManager.getReadySwitches()) {
196 final InstanceIdentifier<Table> tablePath = FlowUtils.createTablePath(nodeId, tableId);
197 checkList.add(deteleTableIfExists(rwTx, tablePath));
200 ListenableFuture<List<Void>> allAsListFuture = Futures.allAsList(checkList);
201 return Futures.transform(allAsListFuture, new AsyncFunction<List<Void>, Void>() {
204 public ListenableFuture<Void> apply(List<Void> readyToSubmit) {
205 return rwTx.submit();
210 private List<Short> getTableIDs() {
211 List<Short> tableIds = new ArrayList<>();
212 tableIds.add(getTABLEID_PORTSECURITY());
213 tableIds.add(getTABLEID_INGRESS_NAT());
214 tableIds.add(getTABLEID_SOURCE_MAPPER());
215 tableIds.add(getTABLEID_DESTINATION_MAPPER());
216 tableIds.add(getTABLEID_POLICY_ENFORCER());
217 tableIds.add(getTABLEID_EGRESS_NAT());
218 tableIds.add(getTABLEID_EXTERNAL_MAPPER());
222 private ListenableFuture<Void> deteleTableIfExists(final ReadWriteTransaction rwTx, final InstanceIdentifier<Table> tablePath){
223 return Futures.transform(rwTx.read(LogicalDatastoreType.CONFIGURATION, tablePath), new Function<Optional<Table>, Void>() {
226 public Void apply(Optional<Table> optTable) {
227 if(optTable.isPresent()){
228 rwTx.delete(LogicalDatastoreType.CONFIGURATION, tablePath);
238 public short getTABLEID_PORTSECURITY() {
239 return (short)(tableOffset+TABLEID_PORTSECURITY);
243 public short getTABLEID_INGRESS_NAT() {
244 return (short)(tableOffset+TABLEID_INGRESS_NAT);
248 public short getTABLEID_SOURCE_MAPPER() {
249 return (short)(tableOffset+TABLEID_SOURCE_MAPPER);
253 public short getTABLEID_DESTINATION_MAPPER() {
254 return (short)(tableOffset+TABLEID_DESTINATION_MAPPER);
258 public short getTABLEID_POLICY_ENFORCER() {
259 return (short)(tableOffset+TABLEID_POLICY_ENFORCER);
263 public short getTABLEID_EGRESS_NAT() {
264 return (short)(tableOffset+TABLEID_EGRESS_NAT);
268 public short getTABLEID_EXTERNAL_MAPPER() {
269 return (short)(tableOffset+TABLEID_EXTERNAL_MAPPER);
273 public TableId verifyMaxTableId(short tableOffset) {
274 return new TableId((short)(tableOffset+TABLEID_EXTERNAL_MAPPER));
278 public void switchReady(final NodeId nodeId) {
283 public void switchRemoved(NodeId sw) {
284 // XXX TODO purge switch flows
289 public void switchUpdated(NodeId sw) {
298 public void endpointUpdated(EpKey epKey) {
303 public void nodeEndpointUpdated(NodeId nodeId, EpKey epKey){
308 public void groupEndpointUpdated(EgKey egKey, EpKey epKey) {
309 policyScope.addToScope(egKey.getTenantId(), egKey.getEgId());
318 public void policyUpdated(Set<EgKey> updatedConsumers) {
327 * Set the learning mode to the specified value
328 * @param learningMode the learning mode to set
330 public void setLearningMode(LearningMode learningMode) {
338 private void scheduleUpdate() {
339 if (switchManager != null) {
340 LOG.trace("Scheduling flow update task");
341 flowUpdateTask.reschedule(FLOW_UPDATE_DELAY, TimeUnit.MILLISECONDS);
346 * Update the flows on a particular switch
348 private class SwitchFlowUpdateTask implements Callable<Void> {
349 private OfWriter ofWriter;
351 public SwitchFlowUpdateTask(OfWriter ofWriter) {
353 this.ofWriter = ofWriter;
357 public Void call() throws Exception {
358 for (NodeId node : switchManager.getReadySwitches()) {
359 PolicyInfo info = policyResolver.getCurrentPolicy();
362 for (OfTable table : flowPipeline) {
364 table.update(node, info, ofWriter);
365 } catch (Exception e) {
366 LOG.error("Failed to write Openflow table {}",
367 table.getClass().getSimpleName(), e);
376 * Update all flows on all switches as needed. Note that this will block
377 * one of the threads on the executor.
379 private class FlowUpdateTask implements Runnable {
382 LOG.debug("Beginning flow update task");
384 CompletionService<Void> ecs
385 = new ExecutorCompletionService<>(executor);
388 OfWriter ofWriter = new OfWriter();
390 SwitchFlowUpdateTask swut = new SwitchFlowUpdateTask(ofWriter);
394 for (int i = 0; i < n; i++) {
397 ofWriter.commitToDataStore(dataBroker);
398 } catch (InterruptedException | ExecutionException e) {
399 LOG.error("Failed to update flow tables", e);
402 LOG.debug("Flow update completed");