Merge "Move utility function to common place."
[groupbasedpolicy.git] / groupbasedpolicy / src / main / java / org / opendaylight / groupbasedpolicy / endpoint / EndpointRpcRegistry.java
1 /*
2  * Copyright (c) 2014 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
9 package org.opendaylight.groupbasedpolicy.endpoint;
10
11 import java.util.Map.Entry;
12 import java.util.concurrent.ConcurrentHashMap;
13 import java.util.concurrent.ConcurrentMap;
14 import java.util.concurrent.Future;
15 import java.util.concurrent.ScheduledExecutorService;
16
17 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
18 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
19 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
20 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
21 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
22 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.Endpoints;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointsBuilder;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.SetEndpointGroupConditionsInput;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInput;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnsetEndpointGroupConditionsInput;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3Address;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.ConditionMapping;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.ConditionMappingKey;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointKey;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Builder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Key;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.has.endpoint.group.conditions.EndpointGroupCondition;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.has.endpoint.group.conditions.EndpointGroupConditionKey;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L2;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
44 import org.opendaylight.yangtools.yang.common.RpcResult;
45 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 import com.google.common.base.Function;
50 import com.google.common.util.concurrent.CheckedFuture;
51 import com.google.common.util.concurrent.FutureCallback;
52 import com.google.common.util.concurrent.Futures;
53 import com.google.common.util.concurrent.ListenableFuture;
54
55 /**
56  * Endpoint registry provides a scalable store for accessing and 
57  * updating information about endpoints.
58  * @author readamsO
59  */
60 public class EndpointRpcRegistry implements EndpointService {
61     private static final Logger LOG = 
62             LoggerFactory.getLogger(EndpointRpcRegistry.class);
63
64     private final DataBroker dataProvider;
65     private final ScheduledExecutorService executor;
66     private final RpcProviderRegistry rpcRegistry;
67     private static EndpointRpcRegistry endpointRpcRegistry;
68
69     final BindingAwareBroker.RpcRegistration<EndpointService> rpcRegistration;
70
71     private final static ConcurrentMap<String, EpRendererAugmentation> registeredRenderers = new ConcurrentHashMap<String, EpRendererAugmentation>();
72
73
74     /**
75      * This method registers a renderer for endpoint RPC API. This method
76      * ensures single RPC registration for all renderers since a single RPC
77      * registration is only allowed.
78      *
79      * @param dataProvider
80      *            - the dataProvider
81      * @param rpcRegistry
82      *            - the rpcRegistry
83      * @param executor
84      *            - thread pool executor
85      * @param epRendererAugmentation
86      *            - specific implementation RPC augmentation, if any. Otherwise NULL
87      */
88     public static void register(DataBroker dataProvider,
89             RpcProviderRegistry rpcRegistry, ScheduledExecutorService executor,
90             EpRendererAugmentation epRendererAugmentation) {
91         if (dataProvider == null || rpcRegistry == null || executor == null) {
92             if (epRendererAugmentation != null) {
93                 LOG.warn("Couldn't register class {} for endpoint RPC because of missing required info");
94             }
95             return;
96         }
97         if (endpointRpcRegistry == null) {
98             synchronized (EndpointRpcRegistry.class) {
99                 if (endpointRpcRegistry == null) {
100                     endpointRpcRegistry = new EndpointRpcRegistry(dataProvider,
101                             rpcRegistry, executor);
102                 }
103             }
104         }
105         if (epRendererAugmentation != null) {
106             registeredRenderers.putIfAbsent(epRendererAugmentation.getClass()
107                     .getName(), epRendererAugmentation);
108         }
109     }
110
111     /**
112      *
113      * @param regImp
114      * @throws Exception
115      */
116     public static void unregister(EpRendererAugmentation regImp)
117             throws Exception {
118         if (regImp == null
119                 || !registeredRenderers
120                         .containsKey(regImp.getClass().getName())) {
121             return;
122         }
123         registeredRenderers.remove(regImp.getClass().getName());
124         LOG.info("Unregistered {}", regImp.getClass().getName());
125         if (registeredRenderers.isEmpty() && endpointRpcRegistry != null) {
126             synchronized (EndpointRpcRegistry.class) {
127                 if (registeredRenderers.isEmpty()
128                         && endpointRpcRegistry != null) {
129                     endpointRpcRegistry.rpcRegistration.close();
130                     endpointRpcRegistry = null;
131                 }
132             }
133         }
134     }
135
136     /**
137      * Constructor
138      *
139      * @param dataProvider
140      * @param rpcRegistry
141      * @param executor
142      */
143     private EndpointRpcRegistry(DataBroker dataProvider,
144                                     RpcProviderRegistry rpcRegistry,
145                                     ScheduledExecutorService executor) {
146         this.dataProvider = dataProvider;
147         this.executor = executor;
148         this.rpcRegistry = rpcRegistry;
149
150         if (this.rpcRegistry != null) {
151             rpcRegistration =
152                     this.rpcRegistry.addRpcImplementation(EndpointService.class, this);
153             LOG.debug("Added RPC Implementation Correctly");
154         } else
155             rpcRegistration = null;
156         
157         if (dataProvider != null) {
158             InstanceIdentifier<Endpoints> iid = 
159                     InstanceIdentifier.builder(Endpoints.class).build();
160             WriteTransaction t = this.dataProvider.newWriteOnlyTransaction();
161             t.put(LogicalDatastoreType.OPERATIONAL, 
162                   iid, new EndpointsBuilder().build());
163             CheckedFuture<Void, TransactionCommitFailedException> f = t.submit();
164             Futures.addCallback(f, new FutureCallback<Void>() {
165                 @Override
166                 public void onFailure(Throwable t) {
167                     LOG.error("Could not write endpoint base container", t);
168                 }
169
170                 @Override
171                 public void onSuccess(Void result) {
172                     
173                 }
174             });
175         }
176
177         // XXX TODO - age out endpoint data and remove 
178         // endpoint group/condition mappings with no conditions
179     }
180   
181     /**
182      * Construct an endpoint with the appropriate augmentations from the 
183      * endpoint input.  Each concrete implementation can provides its specifics earlier.
184      * @param input the input object
185      */
186     private EndpointBuilder buildEndpoint(RegisterEndpointInput input) {
187         EndpointBuilder eb = new EndpointBuilder(input);
188         for (Entry<String, EpRendererAugmentation> entry : registeredRenderers
189                 .entrySet()) {
190             try {
191                 entry.getValue().buildEndpointAugmentation(eb, input);
192             } catch (Throwable t) {
193                 LOG.warn("Endpoint Augmentation error while processing "
194                         + entry.getKey() + ". Reason: ", t);
195             }
196         }
197         return eb;
198     }
199
200     /**
201      * Construct an L3 endpoint with the appropriate augmentations from the 
202      * endpoint input.  Each concrete implementation can provides its specifics earlier.
203      * @param input the input object
204      */
205     private EndpointL3Builder buildEndpointL3(RegisterEndpointInput input) {
206         EndpointL3Builder eb = new EndpointL3Builder(input);
207         for (Entry<String, EpRendererAugmentation> entry : registeredRenderers
208                 .entrySet()) {
209             try {
210                 entry.getValue().buildEndpointL3Augmentation(eb, input);
211             } catch (Throwable t) {
212                 LOG.warn("L3 endpoint Augmentation error while processing "
213                         + entry.getKey() + ". Reason: ", t);
214             }
215         }
216         return eb;
217     }
218
219     @Override
220     public Future<RpcResult<Void>>
221         registerEndpoint(RegisterEndpointInput input) {
222         long timestamp = System.currentTimeMillis();
223         
224         WriteTransaction t = dataProvider.newWriteOnlyTransaction();
225
226         if (input.getL2Context() != null &&
227             input.getMacAddress() != null) {
228             Endpoint ep = buildEndpoint(input)
229                     .setTimestamp(timestamp)
230                     .build();
231
232             EndpointKey key = 
233                     new EndpointKey(ep.getL2Context(), ep.getMacAddress());
234             InstanceIdentifier<Endpoint> iid = 
235                     InstanceIdentifier.builder(Endpoints.class)
236                     .child(Endpoint.class, key)
237                     .build();
238             t.put(LogicalDatastoreType.OPERATIONAL, iid, ep);
239         }
240         if (input.getL3Address() != null) {
241             for (L3Address l3addr : input.getL3Address()) {
242                 EndpointL3Key key3 = new EndpointL3Key(l3addr.getIpAddress(), 
243                                                        l3addr.getL3Context());
244                 EndpointL3 ep3 = buildEndpointL3(input)
245                     .setIpAddress(key3.getIpAddress())
246                     .setL3Context(key3.getL3Context())
247                     .setTimestamp(timestamp)
248                     .build();
249                 InstanceIdentifier<EndpointL3> iid_l3 = 
250                         InstanceIdentifier.builder(Endpoints.class)
251                             .child(EndpointL3.class, key3)
252                             .build();
253                 t.put(LogicalDatastoreType.OPERATIONAL, iid_l3, ep3);
254             }
255         }
256         ListenableFuture<Void> r = t.submit();
257         return Futures.transform(r, futureTrans, executor);
258     }
259
260     @Override
261     public Future<RpcResult<Void>>
262         unregisterEndpoint(UnregisterEndpointInput input) {
263         WriteTransaction t = dataProvider.newWriteOnlyTransaction();
264         if (input.getL2() != null) {
265             for (L2 l2a : input.getL2()) {
266                 EndpointKey key = 
267                         new EndpointKey(l2a.getL2Context(), 
268                                         l2a.getMacAddress());
269                 InstanceIdentifier<Endpoint> iid = 
270                         InstanceIdentifier.builder(Endpoints.class)
271                         .child(Endpoint.class, key).build();
272                 t.delete(LogicalDatastoreType.OPERATIONAL, iid);
273             }
274         }
275         if (input.getL3() != null) {
276             for (L3 l3addr : input.getL3()) {
277                 EndpointL3Key key3 = 
278                         new EndpointL3Key(l3addr.getIpAddress(), 
279                                           l3addr.getL3Context());
280                 InstanceIdentifier<EndpointL3> iid_l3 = 
281                         InstanceIdentifier.builder(Endpoints.class)
282                         .child(EndpointL3.class, key3)
283                         .build();
284                 t.delete(LogicalDatastoreType.OPERATIONAL, iid_l3);
285             }
286         }
287
288         ListenableFuture<Void> r = t.submit();
289         return Futures.transform(r, futureTrans, executor);
290     }
291
292     @Override
293     public Future<RpcResult<Void>> 
294         setEndpointGroupConditions(SetEndpointGroupConditionsInput input) {
295         WriteTransaction t = dataProvider.newWriteOnlyTransaction();
296
297         ConditionMappingKey key = 
298                 new ConditionMappingKey(input.getEndpointGroup());
299         
300         for (EndpointGroupCondition condition: input.getEndpointGroupCondition()) {
301             EndpointGroupConditionKey ckey = 
302                     new EndpointGroupConditionKey(condition.getCondition());
303             InstanceIdentifier<EndpointGroupCondition> iid = 
304                     InstanceIdentifier.builder(Endpoints.class)
305                         .child(ConditionMapping.class, key)
306                         .child(EndpointGroupCondition.class, ckey)
307                         .build();
308             t.put(LogicalDatastoreType.OPERATIONAL, iid, condition);
309         }
310
311         ListenableFuture<Void> r = t.submit();
312         return Futures.transform(r, futureTrans, executor);
313     }
314
315     @Override
316     public Future<RpcResult<Void>> 
317         unsetEndpointGroupConditions(UnsetEndpointGroupConditionsInput input) {
318         WriteTransaction t = dataProvider.newWriteOnlyTransaction();
319
320         ConditionMappingKey key = 
321                 new ConditionMappingKey(input.getEndpointGroup());
322         
323         for (EndpointGroupCondition condition: input.getEndpointGroupCondition()) {
324             EndpointGroupConditionKey ckey = 
325                     new EndpointGroupConditionKey(condition.getCondition());
326             InstanceIdentifier<EndpointGroupCondition> iid = 
327                     InstanceIdentifier.builder(Endpoints.class)
328                         .child(ConditionMapping.class, key)
329                         .child(EndpointGroupCondition.class, ckey)
330                         .build();
331
332             t.delete(LogicalDatastoreType.OPERATIONAL, iid);
333         }
334
335         ListenableFuture<Void> r = t.submit();
336         return Futures.transform(r, futureTrans, executor);
337     }
338
339     Function<Void, RpcResult<Void>> futureTrans =
340             new Function<Void,RpcResult<Void>>() {
341         @Override
342         public RpcResult<Void> apply(Void input) {
343             return RpcResultBuilder.<Void>success().build();
344         }
345     };
346 }