Migrate to odlparent 2.0.0
[groupbasedpolicy.git] / sxp-integration / sxp-ep-provider / src / main / java / org / opendaylight / groupbasedpolicy / sxp / ep / provider / impl / listen / EPForwardingTemplateListenerImpl.java
1 /*
2  * Copyright (c) 2016 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.groupbasedpolicy.sxp.ep.provider.impl.listen;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.AsyncFunction;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.util.Collection;
17 import javax.annotation.Nonnull;
18 import org.apache.commons.lang3.tuple.Pair;
19 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
20 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
21 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.groupbasedpolicy.sxp.ep.provider.impl.DSAsyncDao;
24 import org.opendaylight.groupbasedpolicy.sxp.ep.provider.impl.EPTemplateListener;
25 import org.opendaylight.groupbasedpolicy.sxp.ep.provider.impl.SimpleCachedDao;
26 import org.opendaylight.groupbasedpolicy.sxp.ep.provider.impl.SxpMapperReactor;
27 import org.opendaylight.groupbasedpolicy.sxp.ep.provider.impl.util.EPTemplateUtil;
28 import org.opendaylight.groupbasedpolicy.sxp.ep.provider.impl.util.L3EPServiceUtil;
29 import org.opendaylight.groupbasedpolicy.sxp.ep.provider.impl.util.SxpListenerUtil;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.sxp.integration.sxp.ep.provider.model.rev160302.sxp.ep.mapper.EndpointForwardingTemplateBySubnet;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.sxp.integration.sxp.ep.provider.model.rev160302.sxp.ep.mapper.EndpointPolicyTemplateBySgt;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.sxp.database.rev160308.Sgt;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.sxp.database.rev160308.master.database.fields.MasterDatabaseBinding;
35 import org.opendaylight.yangtools.concepts.ListenerRegistration;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.common.RpcError;
38 import org.opendaylight.yangtools.yang.common.RpcResult;
39 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Purpose: listens to EP forwarding template and propagates change events for further processing
45  */
46 public class EPForwardingTemplateListenerImpl implements EPTemplateListener<EndpointForwardingTemplateBySubnet> {
47
48     private static final Logger LOG = LoggerFactory.getLogger(EPForwardingTemplateListenerImpl.class);
49
50     public static final FutureCallback<RpcResult<Void>> ANY_RPC_FUTURE_CALLBACK =
51             L3EPServiceUtil.createFailureLoggingCallback("failed to read epForwardingTemplate");
52
53     private final SxpMapperReactor sxpMapperReactor;
54     private final SimpleCachedDao<IpPrefix, EndpointForwardingTemplateBySubnet> templateCachedDao;
55     private final DSAsyncDao<IpPrefix, MasterDatabaseBinding> masterDBBindingDao;
56     private final ListenerRegistration<? extends EPTemplateListener> listenerRegistration;
57     private final InstanceIdentifier<EndpointForwardingTemplateBySubnet> templatePath;
58     private final DSAsyncDao<Sgt, EndpointPolicyTemplateBySgt> epPolicyTemplateDao;
59
60     public EPForwardingTemplateListenerImpl(final DataBroker dataBroker,
61                                             final SxpMapperReactor sxpMapperReactor,
62                                             final SimpleCachedDao<IpPrefix, EndpointForwardingTemplateBySubnet> templateCachedDao,
63                                             final DSAsyncDao<IpPrefix, MasterDatabaseBinding> masterDBBindingDao,
64                                             final DSAsyncDao<Sgt, EndpointPolicyTemplateBySgt> epPolicyTemplateDao) {
65         this.sxpMapperReactor = Preconditions.checkNotNull(sxpMapperReactor);
66         this.templateCachedDao = Preconditions.checkNotNull(templateCachedDao);
67         this.masterDBBindingDao = Preconditions.checkNotNull(masterDBBindingDao);
68         this.epPolicyTemplateDao = Preconditions.checkNotNull(epPolicyTemplateDao);
69         templatePath = EPTemplateListener.SXP_MAPPER_TEMPLATE_PARENT_PATH.child(EndpointForwardingTemplateBySubnet.class);
70
71         final DataTreeIdentifier<EndpointForwardingTemplateBySubnet> dataTreeIdentifier = new DataTreeIdentifier<>(
72                 LogicalDatastoreType.CONFIGURATION, templatePath);
73         listenerRegistration = dataBroker.registerDataTreeChangeListener(dataTreeIdentifier, this);
74         LOG.debug("started listening to {}", templatePath);
75     }
76
77     @Override
78     public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<EndpointForwardingTemplateBySubnet>> collection) {
79         for (DataTreeModification<EndpointForwardingTemplateBySubnet> change : collection) {
80             LOG.trace("received modification: {} -> {}", change.getRootPath(), change.getRootNode().getModificationType());
81             // update cached dao
82             final InstanceIdentifier<EndpointForwardingTemplateBySubnet> changePath = change.getRootPath().getRootIdentifier();
83             final IpPrefix changeKey = changePath.firstKeyOf(EndpointForwardingTemplateBySubnet.class).getIpPrefix();
84             SxpListenerUtil.updateCachedDao(templateCachedDao, changeKey, change);
85
86             final EndpointForwardingTemplateBySubnet epForwardingTemplate = change.getRootNode().getDataAfter();
87             if (epForwardingTemplate == null) {
88                 LOG.debug("EPForwarding template removed - NOOP {}", change.getRootNode().getDataBefore());
89                 //TODO: handle removal (update cache)
90             } else {
91                 processWithEPTemplates(epForwardingTemplate);
92             }
93         }
94     }
95
96     private void processWithEPTemplates(final EndpointForwardingTemplateBySubnet epForwardingTemplate) {
97         final ListenableFuture<Optional<MasterDatabaseBinding>> sxpMasterDbItemRead =
98                 masterDBBindingDao.read(epForwardingTemplate.getIpPrefix());
99
100         // find all available epForwardingTemplates and pair those to sxpMasterDBBinding
101         final ListenableFuture<Optional<Pair<MasterDatabaseBinding, EndpointPolicyTemplateBySgt>>> searchResult =
102                 Futures.transformAsync(sxpMasterDbItemRead, createReadAndPairTemplateToBindingFunction(epForwardingTemplate));
103
104         // invoke sxpMapperReactor.process for every valid combination of sxpMasterDBBinding, epPolicyTemplate, epForwardingTemplate
105         final ListenableFuture<RpcResult<Void>> rpcResult =
106                 Futures.transformAsync(searchResult, createProcessAllFunction(epForwardingTemplate));
107
108         Futures.addCallback(rpcResult, ANY_RPC_FUTURE_CALLBACK);
109     }
110
111     private AsyncFunction<Optional<Pair<MasterDatabaseBinding, EndpointPolicyTemplateBySgt>>, RpcResult<Void>>
112     createProcessAllFunction(final EndpointForwardingTemplateBySubnet epForwardingTemplate) {
113         return new AsyncFunction<Optional<Pair<MasterDatabaseBinding, EndpointPolicyTemplateBySgt>>, RpcResult<Void>>() {
114             @Override
115             public ListenableFuture<RpcResult<Void>>
116             apply(final Optional<Pair<MasterDatabaseBinding, EndpointPolicyTemplateBySgt>> input) throws Exception {
117                 final ListenableFuture<RpcResult<Void>> result;
118                 if (! input.isPresent()) {
119                     LOG.debug("no pair [epPolicyTemplate, ip-sgt-binding] available for ip-prefix: {}", epForwardingTemplate.getIpPrefix());
120                     result = Futures.immediateFuture(
121                             RpcResultBuilder.<Void>failed()
122                                     .withError(RpcError.ErrorType.APPLICATION,
123                                             "no pair [epPolicyTemplate, ip-sgt-binding] available for ip-prefix " + epForwardingTemplate.getIpPrefix())
124                                     .build());
125                 } else {
126                     LOG.trace("processing epForwardingTemplate event for ip-prefix: {}", epForwardingTemplate.getIpPrefix());
127                     final Pair<MasterDatabaseBinding, EndpointPolicyTemplateBySgt> pair = input.get();
128                     final MasterDatabaseBinding sxpMasterDBBinding = pair.getLeft();
129                     final EndpointPolicyTemplateBySgt epPolicyTemplate = pair.getRight();
130                     if (epPolicyTemplate != null && sxpMasterDBBinding != null) {
131                         LOG.trace("processing epForwardingTemplate event with resolved sxpMasterDb entry and " +
132                                         "epPolicyTemplate for sgt/ip-prefix: {}/{}",
133                                 sxpMasterDBBinding.getSecurityGroupTag(), sxpMasterDBBinding.getImplementedInterface());
134                         result = sxpMapperReactor.processTemplatesAndSxpMasterDB(epPolicyTemplate, epForwardingTemplate, sxpMasterDBBinding);
135                     } else {
136                         LOG.debug("Skipped ep-forwarding-template processing");
137                         result = Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
138                     }
139                 }
140
141                 return result;
142             }
143         };
144     }
145
146     private AsyncFunction<Optional<MasterDatabaseBinding>, Optional<Pair<MasterDatabaseBinding, EndpointPolicyTemplateBySgt>>>
147     createReadAndPairTemplateToBindingFunction(final EndpointForwardingTemplateBySubnet epFowardingTemplate) {
148         return new AsyncFunction<Optional<MasterDatabaseBinding>, Optional<Pair<MasterDatabaseBinding, EndpointPolicyTemplateBySgt>>>() {
149             @Override
150             public ListenableFuture<Optional<Pair<MasterDatabaseBinding, EndpointPolicyTemplateBySgt>>>
151             apply(final Optional<MasterDatabaseBinding> input) throws Exception {
152                 final ListenableFuture<Pair<MasterDatabaseBinding, EndpointPolicyTemplateBySgt>> result;
153                 if (! input.isPresent()) {
154                     LOG.debug("no sxpMasterDB entry available for ip-prefix: {}", epFowardingTemplate.getIpPrefix());
155                     result = Futures.immediateFuture(null);
156                 } else {
157                     LOG.trace("processing sxpMasterDB entry for ip-prefix: {}", epFowardingTemplate.getIpPrefix());
158                     final MasterDatabaseBinding masterDBItem = input.get();
159                     final ListenableFuture<Optional<EndpointPolicyTemplateBySgt>> epPolicyTemplateRead =
160                             epPolicyTemplateDao.read(masterDBItem.getSecurityGroupTag());
161                     result = EPTemplateUtil.wrapToPair(masterDBItem, epPolicyTemplateRead);
162                 }
163
164                 return EPTemplateUtil.wrapToOptional(result);
165             }
166         };
167     }
168
169
170     @Override
171     public void close() throws Exception {
172         LOG.debug("closing listener registration to {}", templatePath);
173         listenerRegistration.close();
174     }
175 }