27683a853f2c98b428d4f511ff6f17d8ce5d9000
[ovsdb.git] / hwvtepsouthbound / hwvtepsouthbound-impl / src / main / java / org / opendaylight / ovsdb / hwvtepsouthbound / transact / PhysicalSwitchUpdateCommand.java
1 /*
2  * Copyright © 2015, 2017 China Telecom Beijing Research Institute 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.ovsdb.hwvtepsouthbound.transact;
10
11 import static org.opendaylight.ovsdb.hwvtepsouthbound.HwvtepSouthboundUtil.schemaMismatchLog;
12 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
13
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Map.Entry;
21 import java.util.Set;
22
23 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
24 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
25 import org.opendaylight.ovsdb.hwvtepsouthbound.HwvtepSouthboundMapper;
26 import org.opendaylight.ovsdb.lib.error.SchemaVersionMismatchException;
27 import org.opendaylight.ovsdb.lib.notation.Mutator;
28 import org.opendaylight.ovsdb.lib.notation.UUID;
29 import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
30 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
31 import org.opendaylight.ovsdb.schema.hardwarevtep.Global;
32 import org.opendaylight.ovsdb.schema.hardwarevtep.PhysicalSwitch;
33 import org.opendaylight.ovsdb.schema.hardwarevtep.Tunnel;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalLocatorAugmentation;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.PhysicalSwitchAugmentation;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical._switch.attributes.ManagementIps;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical._switch.attributes.TunnelIps;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical._switch.attributes.Tunnels;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.tunnel.attributes.BfdLocalConfigs;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.tunnel.attributes.BfdParams;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.tunnel.attributes.BfdRemoteConfigs;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import com.google.common.base.Optional;
49 import com.google.common.collect.ImmutableMap;
50 import com.google.common.collect.Sets;
51
52 public class PhysicalSwitchUpdateCommand extends AbstractTransactCommand {
53     private static final Logger LOG = LoggerFactory.getLogger(PhysicalSwitchUpdateCommand.class);
54
55     public PhysicalSwitchUpdateCommand(HwvtepOperationalState state,
56             Collection<DataTreeModification<Node>> changes) {
57         super(state, changes);
58     }
59
60     @Override
61     public void execute(TransactionBuilder transaction) {
62         Map<InstanceIdentifier<Node>, PhysicalSwitchAugmentation> created =
63                 extractCreated(getChanges(),PhysicalSwitchAugmentation.class);
64         if (!created.isEmpty()) {
65             for (Entry<InstanceIdentifier<Node>, PhysicalSwitchAugmentation> physicalSwitchEntry:
66                 created.entrySet()) {
67                 updatePhysicalSwitch(transaction,  physicalSwitchEntry.getKey(), physicalSwitchEntry.getValue());
68             }
69         }
70         Map<InstanceIdentifier<Node>, PhysicalSwitchAugmentation> updated =
71                 extractUpdatedSwitches(getChanges(),PhysicalSwitchAugmentation.class);
72         if (!updated.isEmpty()) {
73             for (Entry<InstanceIdentifier<Node>, PhysicalSwitchAugmentation> physicalSwitchEntry:
74                 updated.entrySet()) {
75                 updatePhysicalSwitch(transaction,  physicalSwitchEntry.getKey(), physicalSwitchEntry.getValue());
76             }
77         }
78     }
79
80
81     private void updatePhysicalSwitch(TransactionBuilder transaction,
82             InstanceIdentifier<Node> iid, PhysicalSwitchAugmentation physicalSwitchAugmentation) {
83         LOG.debug("Creating a physical switch named: {}", physicalSwitchAugmentation.getHwvtepNodeName());
84         Optional<PhysicalSwitchAugmentation> operationalPhysicalSwitchOptional =
85                 getOperationalState().getPhysicalSwitchAugmentation(iid);
86         PhysicalSwitch physicalSwitch = TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), PhysicalSwitch.class);
87         setDescription(physicalSwitch, physicalSwitchAugmentation);
88         setManagementIps(physicalSwitch, physicalSwitchAugmentation);
89         setTunnuleIps(physicalSwitch, operationalPhysicalSwitchOptional.get());
90         try {
91             setTunnels(transaction, iid, physicalSwitch, physicalSwitchAugmentation,
92                             operationalPhysicalSwitchOptional.isPresent());
93         } catch (SchemaVersionMismatchException e) {
94             schemaMismatchLog("tunnels", "Physical_Switch", e);
95         }
96         if (!operationalPhysicalSwitchOptional.isPresent()) {
97             //create a physical switch
98             setName(physicalSwitch, physicalSwitchAugmentation, operationalPhysicalSwitchOptional);
99             String pswitchUuid = "PhysicalSwitch_" + HwvtepSouthboundMapper.getRandomUUID();
100             transaction.add(op.insert(physicalSwitch).withId(pswitchUuid));
101             transaction.add(op.comment("Physical Switch: Creating " +
102                             physicalSwitchAugmentation.getHwvtepNodeName().getValue()));
103             //update global table
104             Global global = TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), Global.class);
105             global.setSwitches(Collections.singleton(new UUID(pswitchUuid)));
106
107             LOG.trace("execute: create physical switch: {}", physicalSwitch);
108             transaction.add(op.mutate(global)
109                     .addMutation(global.getSwitchesColumn().getSchema(), Mutator.INSERT,
110                             global.getSwitchesColumn().getData()));
111             transaction.add(op.comment("Global: Mutating " +
112                             physicalSwitchAugmentation.getHwvtepNodeName().getValue() + " " + pswitchUuid));
113         } else {
114             PhysicalSwitchAugmentation updatedPhysicalSwitch = operationalPhysicalSwitchOptional.get();
115             String existingPhysicalSwitchName = updatedPhysicalSwitch.getHwvtepNodeName().getValue();
116             /* In case TOR devices don't allow creation of PhysicalSwitch name might be null
117              * as user is only adding configurable parameters to MDSAL like BFD params
118              * 
119              * TODO Note: Consider handling tunnel udpate/remove in separate command
120              */
121             if(existingPhysicalSwitchName == null) {
122                 existingPhysicalSwitchName = operationalPhysicalSwitchOptional.get().getHwvtepNodeName().getValue();
123             }
124             // Name is immutable, and so we *can't* update it.  So we use extraPhysicalSwitch for the schema stuff
125             PhysicalSwitch extraPhysicalSwitch = TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), PhysicalSwitch.class);
126             extraPhysicalSwitch.setName("");
127             LOG.trace("execute: updating physical switch: {}", physicalSwitch);
128             transaction.add(op.update(physicalSwitch)
129                     .where(extraPhysicalSwitch.getNameColumn().getSchema().opEqual(existingPhysicalSwitchName))
130                     .build());
131             transaction.add(op.comment("Physical Switch: Updating " + existingPhysicalSwitchName));
132         }
133     }
134
135     private void setName(PhysicalSwitch physicalSwitch, PhysicalSwitchAugmentation physicalSwitchAugmentation,
136             Optional<PhysicalSwitchAugmentation> operationalPhysicalSwitchOptional) {
137         if (physicalSwitchAugmentation.getHwvtepNodeName() != null) {
138             physicalSwitch.setName(physicalSwitchAugmentation.getHwvtepNodeName().getValue());
139         } else if (operationalPhysicalSwitchOptional.isPresent() && operationalPhysicalSwitchOptional.get().getHwvtepNodeName() != null) {
140             physicalSwitch.setName(operationalPhysicalSwitchOptional.get().getHwvtepNodeName().getValue());
141         }
142     }
143
144     private void setDescription(PhysicalSwitch physicalSwitch, PhysicalSwitchAugmentation physicalSwitchAugmentation) {
145         if (physicalSwitchAugmentation.getHwvtepNodeDescription() != null) {
146             physicalSwitch.setDescription(physicalSwitchAugmentation.getHwvtepNodeDescription());
147         }
148     }
149
150     private void setManagementIps(PhysicalSwitch physicalSwitch, PhysicalSwitchAugmentation physicalSwitchAugmentation) {
151         Set<String> ipSet = new HashSet<>();
152         if (physicalSwitchAugmentation.getManagementIps() != null) {
153             for (ManagementIps ip: physicalSwitchAugmentation.getManagementIps()) {
154                 ipSet.add(ip.getManagementIpsKey().getIpv4Address().getValue());
155             }
156             physicalSwitch.setManagementIps(ipSet);
157         }
158     }
159
160     private void setTunnuleIps(PhysicalSwitch physicalSwitch, PhysicalSwitchAugmentation physicalSwitchAugmentation) {
161         Set<String> ipSet = new HashSet<>();
162         if (physicalSwitchAugmentation.getTunnelIps() != null) {
163             for (TunnelIps ip: physicalSwitchAugmentation.getTunnelIps()) {
164                 ipSet.add(ip.getTunnelIpsKey().getIpv4Address().getValue());
165             }
166             physicalSwitch.setTunnelIps(ipSet);
167         }
168     }
169
170     @SuppressWarnings("unchecked")
171     private void setTunnels(TransactionBuilder transaction, InstanceIdentifier<Node> iid,
172                     PhysicalSwitch physicalSwitch, PhysicalSwitchAugmentation physicalSwitchAugmentation,
173                     boolean pSwitchExists) {
174         //TODO: revisit this code for optimizations
175         //TODO: needs more testing
176         if(physicalSwitchAugmentation.getTunnels() != null) {
177             for(Tunnels tunnel: physicalSwitchAugmentation.getTunnels()) {
178                 Optional<Tunnels> opTunnelOpt = getOperationalState().getTunnels(iid, tunnel.getKey());
179                 Tunnel newTunnel = TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), Tunnel.class);
180
181                 UUID localUUID = getLocatorUUID(transaction,
182                                 (InstanceIdentifier<TerminationPoint>) tunnel.getLocalLocatorRef().getValue());
183                 UUID remoteUUID = getLocatorUUID(transaction,
184                                 (InstanceIdentifier<TerminationPoint>) tunnel.getRemoteLocatorRef().getValue());
185                 if(localUUID != null && remoteUUID != null) {
186                     UUID uuid;
187                     // local and remote must exist
188                     newTunnel.setLocal(localUUID);
189                     newTunnel.setRemote(remoteUUID);
190                     setBfdParams(newTunnel, tunnel);
191                     setBfdLocalConfigs(newTunnel, tunnel);
192                     setBfdRemoteConfigs(newTunnel, tunnel);
193                     if(!opTunnelOpt.isPresent()) {
194                         String tunnelUuid = "Tunnel_" + HwvtepSouthboundMapper.getRandomUUID();
195                         transaction.add(op.insert(newTunnel).withId(tunnelUuid));
196                         transaction.add(op.comment("Tunnel: Creating " + tunnelUuid));
197                         if(!pSwitchExists) {
198                             //TODO: Figure out a way to handle this
199                             LOG.warn("Tunnel configuration requires pre-existing physicalSwitch");
200                         } else {
201                             // TODO: Can we reuse physicalSwitch instead?
202                             PhysicalSwitch pSwitch =
203                                             TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(),
204                                                             PhysicalSwitch.class);
205                             pSwitch.setTunnels(Collections.singleton(new UUID(tunnelUuid)));
206                             pSwitch.setName(physicalSwitchAugmentation.getHwvtepNodeName().getValue());
207                             transaction.add(op.mutate(pSwitch)
208                                             .addMutation(pSwitch.getTunnels().getSchema(), Mutator.INSERT,
209                                                     pSwitch.getTunnels().getData())
210                                             .where(pSwitch.getNameColumn().getSchema().
211                                                             opEqual(pSwitch.getNameColumn().getData()))
212                                             .build());
213                             transaction.add(op.comment("PhysicalSwitch: Mutating " + tunnelUuid));
214                         }
215                         uuid = new UUID(tunnelUuid);
216                     } else {
217                         uuid = new UUID (opTunnelOpt.get().getTunnelUuid().getValue());
218                         Tunnel extraTunnel =
219                                 TyperUtils.getTypedRowWrapper(transaction.getDatabaseSchema(), Tunnel.class, null);
220                         extraTunnel.getUuidColumn().setData(uuid);
221                         transaction.add(op.update(newTunnel)
222                                         .where(extraTunnel.getUuidColumn().getSchema().opEqual(uuid))
223                                         .build());
224                         transaction.add(op.comment("Tunnel: Updating " + uuid));
225                     }
226                 }
227             }
228         }
229     }
230
231     private void setBfdParams(Tunnel tunnel, Tunnels psAugTunnel) {
232         List<BfdParams> bfdParams = psAugTunnel.getBfdParams();
233         if(bfdParams != null) {
234             Map<String, String> bfdParamMap = new HashMap<>();
235             for(BfdParams bfdParam : bfdParams) {
236                 bfdParamMap.put(bfdParam.getBfdParamKey(), bfdParam.getBfdParamValue());
237             }
238             try {
239                 tunnel.setBfdParams(ImmutableMap.copyOf(bfdParamMap));
240             } catch (NullPointerException e) {
241                 LOG.warn("Incomplete BFD Params for tunnel", e);
242             }
243         }
244     }
245
246     private void setBfdLocalConfigs(Tunnel tunnel, Tunnels psAugTunnel) {
247         List<BfdLocalConfigs> bfdLocalConfigs = psAugTunnel.getBfdLocalConfigs();
248         if(bfdLocalConfigs != null) {
249             Map<String, String> configLocalMap = new HashMap<>();
250             for(BfdLocalConfigs localConfig : bfdLocalConfigs) {
251                 configLocalMap.put(localConfig.getBfdLocalConfigKey(), localConfig.getBfdLocalConfigValue());
252             }
253             try {
254                 tunnel.setBfdConfigLocal(ImmutableMap.copyOf(configLocalMap));
255             } catch (NullPointerException e) {
256                 LOG.warn("Incomplete BFD LocalConfig for tunnel", e);
257             }
258         }
259     }
260
261     private void setBfdRemoteConfigs(Tunnel tunnel, Tunnels psAugTunnel) {
262         List<BfdRemoteConfigs> bfdRemoteConfigs = psAugTunnel.getBfdRemoteConfigs();
263         if(bfdRemoteConfigs != null) {
264             Map<String, String> configRemoteMap = new HashMap<>();
265             for(BfdRemoteConfigs remoteConfig : bfdRemoteConfigs) {
266                 configRemoteMap.put(remoteConfig.getBfdRemoteConfigKey(), remoteConfig.getBfdRemoteConfigValue());
267             }
268             try {
269                 tunnel.setBfdConfigRemote(ImmutableMap.copyOf(configRemoteMap));
270             } catch (NullPointerException e) {
271                 LOG.warn("Incomplete BFD RemoteConfig for tunnel", e);
272             }
273         }
274     }
275
276     private UUID getLocatorUUID(TransactionBuilder transaction, InstanceIdentifier<TerminationPoint> iid) {
277         UUID locatorUUID = null;
278         Optional<HwvtepPhysicalLocatorAugmentation> opLocOptional =
279                         getOperationalState().getPhysicalLocatorAugmentation(iid);
280         if (opLocOptional.isPresent()) {
281             // Get Locator UUID from operational
282             HwvtepPhysicalLocatorAugmentation locatorAug = opLocOptional.get();
283             locatorUUID = new UUID(locatorAug.getPhysicalLocatorUuid().getValue());
284         } else {
285             // TODO/FIXME: Not in operational, do we create a new one?
286             LOG.warn("Trying to create tunnel without creating physical locators first");
287             Optional<TerminationPoint> confLocOptional =
288                             TransactUtils.readNodeFromConfig(getOperationalState().getReadWriteTransaction(), iid);
289             if (confLocOptional.isPresent()) {
290                 HwvtepPhysicalLocatorAugmentation locatorAugmentation =
291                                 confLocOptional.get().getAugmentation(HwvtepPhysicalLocatorAugmentation.class);
292                 locatorUUID = TransactUtils.createPhysicalLocator(transaction, locatorAugmentation);
293             } else {
294                 LOG.warn("Unable to find endpoint for tunnel. Endpoint indentifier is {}", iid);
295             }
296         }
297         return locatorUUID;
298     }
299
300     private Map<InstanceIdentifier<Node>, PhysicalSwitchAugmentation> extractCreated(
301             Collection<DataTreeModification<Node>> changes, Class<PhysicalSwitchAugmentation> class1) {
302         Map<InstanceIdentifier<Node>, PhysicalSwitchAugmentation> result = new HashMap<>();
303         if (changes != null && !changes.isEmpty()) {
304             for (DataTreeModification<Node> change : changes) {
305                 final InstanceIdentifier<Node> key = change.getRootPath().getRootIdentifier();
306                 final DataObjectModification<Node> mod = change.getRootNode();
307                 Node created = TransactUtils.getCreated(mod);
308                 if (created != null) {
309                     PhysicalSwitchAugmentation physicalSwitch = created.getAugmentation(PhysicalSwitchAugmentation.class);
310                     if (physicalSwitch != null) {
311                         result.put(key, physicalSwitch);
312                     }
313                 }
314             }
315         }
316         return result;
317     }
318
319     private Map<InstanceIdentifier<Node>, PhysicalSwitchAugmentation> extractUpdatedSwitches(
320             Collection<DataTreeModification<Node>> changes, Class<PhysicalSwitchAugmentation> class1) {
321         Map<InstanceIdentifier<Node>, PhysicalSwitchAugmentation> result = new HashMap<>();
322         if (changes != null && !changes.isEmpty()) {
323             for (DataTreeModification<Node> change : changes) {
324                 final InstanceIdentifier<Node> key = change.getRootPath().getRootIdentifier();
325                 final DataObjectModification<Node> mod = change.getRootNode();
326                 Node updated = TransactUtils.getUpdated(mod);
327                 if (updated != null) {
328                     PhysicalSwitchAugmentation physicalSwitch = updated.getAugmentation(PhysicalSwitchAugmentation.class);
329                     if (physicalSwitch != null) {
330                         result.put(key, physicalSwitch);
331                     }
332                 }
333             }
334         }
335         return result;
336     }
337
338 }