baa02edf3c355411cd2561a264dd2ba90a940c82
[controller.git] / opendaylight / config / config-manager / src / main / java / org / opendaylight / controller / config / manager / impl / ServiceReferenceRegistryImpl.java
1 /*
2  * Copyright (c) 2013 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.controller.config.manager.impl;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.ImmutableSet;
13 import java.util.AbstractMap.SimpleImmutableEntry;
14 import java.util.Collections;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.Map;
18 import java.util.Map.Entry;
19 import java.util.Set;
20 import javax.management.InstanceAlreadyExistsException;
21 import javax.management.InstanceNotFoundException;
22 import javax.management.ObjectName;
23 import org.opendaylight.controller.config.api.LookupRegistry;
24 import org.opendaylight.controller.config.api.ModuleIdentifier;
25 import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
26 import org.opendaylight.controller.config.api.ServiceReferenceWritableRegistry;
27 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
28 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
29 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
30 import org.opendaylight.controller.config.manager.impl.jmx.ServiceReference;
31 import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceMXBeanImpl;
32 import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceRegistrator;
33 import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceRegistrator.ServiceReferenceJMXRegistration;
34 import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceRegistrator.ServiceReferenceTransactionRegistratorFactory;
35 import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceRegistrator.ServiceReferenceTransactionRegistratorFactoryImpl;
36 import org.opendaylight.controller.config.manager.impl.util.InterfacesHelper;
37 import org.opendaylight.controller.config.spi.ModuleFactory;
38 import org.osgi.framework.BundleContext;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceReadableRegistry, SearchableServiceReferenceWritableRegistry {
43     private static final Logger LOG = LoggerFactory.getLogger(ServiceReferenceRegistryImpl.class);
44
45     private final Map<String, ModuleFactory> factories;
46     private final Map<String, Set<String>> factoryNamesToQNames;
47     // validator of incoming ObjectNames - throws InstanceNotFoundException if not found either in registry or transaction
48     private final LookupRegistry lookupRegistry;
49     private final ServiceReferenceRegistrator serviceReferenceRegistrator;
50     // helper method for getting QName of SI from namespace + local name
51     private final Map<String /* namespace */, Map<String /* local name */, ServiceInterfaceAnnotation>> namespacesToAnnotations;
52     private final Map<String /* service qName */, ServiceInterfaceAnnotation> serviceQNamesToAnnotations;
53     // all Service Interface qNames for sanity checking
54     private final Set<String /* qName */> allQNames;
55     Map<ModuleIdentifier, Map<ServiceInterfaceAnnotation, String /* service ref name */>> modulesToServiceRef = new HashMap<>();
56
57
58     // actual reference database
59     private final Map<ServiceReference, ModuleIdentifier> refNames = new HashMap<>();
60     private final boolean writable;
61     private final Map<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>> mBeans = new HashMap<>();
62
63     private ServiceReferenceRegistryImpl(final Map<String, ModuleFactory> factories, final LookupRegistry lookupRegistry,
64             final ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory, final boolean writable) {
65         this.factories = factories;
66         this.writable = writable;
67         this.lookupRegistry = lookupRegistry;
68
69         this.serviceReferenceRegistrator = serviceReferenceRegistratorFactory.create();
70
71         Map<String, Set<String /* QName */>> modifiableFactoryNamesToQNames = new HashMap<>();
72         Set<ServiceInterfaceAnnotation> allAnnotations = new HashSet<>();
73         Set<String /* qName */> allQNameSet = new HashSet<>();
74
75         for (Entry<String, ModuleFactory> entry : factories.entrySet()) {
76             if (!entry.getKey().equals(entry.getValue().getImplementationName())) {
77                 LOG.error("Possible error in code: Mismatch between supplied and actual name of {}", entry);
78                 throw new IllegalArgumentException("Possible error in code: Mismatch between supplied and actual name of " + entry);
79             }
80             Set<ServiceInterfaceAnnotation> siAnnotations = InterfacesHelper.getServiceInterfaceAnnotations(entry.getValue());
81             Set<String> qNames = InterfacesHelper.getQNames(siAnnotations);
82             allAnnotations.addAll(siAnnotations);
83             allQNameSet.addAll(qNames);
84             modifiableFactoryNamesToQNames.put(entry.getKey(), qNames);
85         }
86         this.factoryNamesToQNames = ImmutableMap.copyOf(modifiableFactoryNamesToQNames);
87         this.allQNames = ImmutableSet.copyOf(allQNameSet);
88         // fill namespacesToAnnotations
89         Map<String /* namespace */, Map<String /* localName */, ServiceInterfaceAnnotation>> modifiableNamespacesToAnnotations = new HashMap<>();
90         Map<String /* service qName*/, ServiceInterfaceAnnotation> modifiableServiceQNamesToAnnotations = new HashMap<>();
91         for (ServiceInterfaceAnnotation sia : allAnnotations) {
92             Map<String, ServiceInterfaceAnnotation> ofNamespace = modifiableNamespacesToAnnotations.get(sia.namespace());
93             if (ofNamespace == null) {
94                 ofNamespace = new HashMap<>();
95                 modifiableNamespacesToAnnotations.put(sia.namespace(), ofNamespace);
96             }
97             if (ofNamespace.containsKey(sia.localName())) {
98                 LOG.error(
99                         "Cannot construct namespacesToAnnotations map, conflict between local names in {}, offending local name: {}, map so far {}",
100                         sia.namespace(), sia.localName(), modifiableNamespacesToAnnotations);
101                 throw new IllegalArgumentException("Conflict between local names in " + sia.namespace() + " : " + sia.localName());
102             }
103             ofNamespace.put(sia.localName(), sia);
104             modifiableServiceQNamesToAnnotations.put(sia.value(), sia);
105         }
106         this.namespacesToAnnotations = ImmutableMap.copyOf(modifiableNamespacesToAnnotations);
107         this.serviceQNamesToAnnotations = ImmutableMap.copyOf(modifiableServiceQNamesToAnnotations);
108         LOG.trace("factoryNamesToQNames:{}", this.factoryNamesToQNames);
109     }
110
111     /**
112      * Static constructor for config registry. Since only transaction can write to this registry, it will
113      * return blank state.
114      */
115     public static CloseableServiceReferenceReadableRegistry createInitialSRLookupRegistry() {
116         // since this is initial state, just throw exception:
117         LookupRegistry lookupRegistry = new LookupRegistry() {
118             @Override
119             public Set<ObjectName> lookupConfigBeans() {
120                 throw new UnsupportedOperationException();
121             }
122
123             @Override
124             public Set<ObjectName> lookupConfigBeans(final String moduleName) {
125                 throw new UnsupportedOperationException();
126             }
127
128             @Override
129             public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
130                 throw new UnsupportedOperationException();
131             }
132
133             @Override
134             public ObjectName lookupConfigBean(final String moduleName, final String instanceName) throws InstanceNotFoundException {
135                 throw new UnsupportedOperationException();
136             }
137
138             @Override
139             public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
140                 throw new InstanceNotFoundException("Cannot find " + objectName + " - Tried to use mocking registry");
141             }
142
143             @Override
144             public Set<String> getAvailableModuleFactoryQNames() {
145                 throw new UnsupportedOperationException();
146             }
147
148             @Override
149             public Set<ObjectName> lookupRuntimeBeans() {
150                 throw new UnsupportedOperationException();
151             }
152
153             @Override
154             public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
155                 throw new UnsupportedOperationException();
156             }
157
158             @Override
159             public String toString() {
160                 return "initial";
161             }
162         };
163         ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory = () -> new ServiceReferenceRegistrator() {
164             @Override
165             public String getNullableTransactionName() {
166                 throw new UnsupportedOperationException();
167             }
168
169             @Override
170             public ServiceReferenceJMXRegistration registerMBean(final ServiceReferenceMXBeanImpl object, final ObjectName on) throws InstanceAlreadyExistsException {
171                 throw new UnsupportedOperationException();
172             }
173
174             @Override
175             public void close() {
176
177             }
178         };
179         return new ServiceReferenceRegistryImpl(Collections.<String, ModuleFactory>emptyMap(), lookupRegistry,
180                 serviceReferenceRegistratorFactory, false);
181     }
182
183     /**
184      * Static constructor for transaction controller. Take current state as seen by config registry, allow writing new data.
185      */
186     public static SearchableServiceReferenceWritableRegistry createSRWritableRegistry(final ServiceReferenceReadableRegistry oldReadableRegistry,
187                                                     final ConfigTransactionLookupRegistry txLookupRegistry,
188                                                     final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
189
190         if (txLookupRegistry == null) {
191             throw new IllegalArgumentException("txLookupRegistry is null");
192         }
193         ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldReadableRegistry;
194         Map<String, ModuleFactory> factories = extractFactoriesMap(currentlyRegisteredFactories);
195         ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory = new ServiceReferenceTransactionRegistratorFactoryImpl(
196                 txLookupRegistry.getTxModuleJMXRegistrator(), txLookupRegistry.getTxModuleJMXRegistrator().getTransactionName());
197         ServiceReferenceRegistryImpl newRegistry = new ServiceReferenceRegistryImpl(factories, txLookupRegistry,
198                 serviceReferenceRegistratorFactory, true);
199         copy(old, newRegistry, txLookupRegistry.getTransactionIdentifier().getName());
200         return newRegistry;
201     }
202
203     /**
204      * Copy back state to config registry after commit.
205      */
206     public static CloseableServiceReferenceReadableRegistry createSRReadableRegistry(final ServiceReferenceWritableRegistry oldWritableRegistry,
207                                                                             final LookupRegistry lookupRegistry, final BaseJMXRegistrator baseJMXRegistrator) {
208         ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldWritableRegistry;
209
210         // even if factories do change, nothing in the mapping can change between transactions
211         ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory = new ServiceReferenceTransactionRegistratorFactoryImpl(baseJMXRegistrator);
212         ServiceReferenceRegistryImpl newRegistry = new ServiceReferenceRegistryImpl(old.factories, lookupRegistry,
213                 serviceReferenceRegistratorFactory, false);
214         copy(old, newRegistry, null);
215         return newRegistry;
216     }
217
218     /**
219      * Fill refNames and mBeans maps from old instance
220      */
221     private static void copy(final ServiceReferenceRegistryImpl old, final ServiceReferenceRegistryImpl newRegistry, final String nullableDstTransactionName) {
222         for (Entry<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>> refNameEntry : old.mBeans.entrySet()) {
223             ObjectName currentImplementation;
224             ObjectName currentImplementationSrc = refNameEntry.getValue().getKey().getCurrentImplementation();
225             if (nullableDstTransactionName != null) {
226                 currentImplementation = ObjectNameUtil.withTransactionName(currentImplementationSrc, nullableDstTransactionName);
227             } else {
228                 currentImplementation = ObjectNameUtil.withoutTransactionName(currentImplementationSrc);
229             }
230             try {
231                 boolean skipChecks = true;
232                 newRegistry.saveServiceReference(refNameEntry.getKey(), currentImplementation, skipChecks);
233             } catch (final InstanceNotFoundException e) {
234                 LOG.error("Cannot save service reference({}, {})", refNameEntry.getKey(), currentImplementation);
235                 throw new IllegalStateException("Possible code error", e);
236             }
237         }
238     }
239
240     private static Map<String, ModuleFactory> extractFactoriesMap(final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
241         Map<String, ModuleFactory> result = new HashMap<>();
242         for (Entry<String, Entry<ModuleFactory, BundleContext>> entry : currentlyRegisteredFactories.entrySet()) {
243             result.put(entry.getKey(), entry.getValue().getKey());
244         }
245         return result;
246     }
247
248     @Override
249     public Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(final ModuleIdentifier moduleIdentifier) {
250         Map<ServiceInterfaceAnnotation, String /* service ref name */> result = modulesToServiceRef.get(moduleIdentifier);
251         if (result == null) {
252             return Collections.emptyMap();
253         }
254         return Collections.unmodifiableMap(result);
255     }
256
257     @Override
258     public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
259         lookupRegistry.checkConfigBeanExists(objectName);
260
261         String factoryName = ObjectNameUtil.getFactoryName(objectName);
262         Set<String> serviceInterfaceAnnotations = factoryNamesToQNames.get(factoryName);
263         if (serviceInterfaceAnnotations == null) {
264             LOG.error("Possible error in code: cannot find factory annotations of '{}' extracted from ON {} in {}",
265                     factoryName, objectName, factoryNamesToQNames);
266             throw new IllegalArgumentException("Cannot find factory with name " + factoryName);
267         }
268         return serviceInterfaceAnnotations;
269     }
270
271     @Override
272     public synchronized String getServiceInterfaceName(final String namespace, final String localName) {
273         Map<String /* localName */, ServiceInterfaceAnnotation> ofNamespace = namespacesToAnnotations.get(namespace);
274         if (ofNamespace == null) {
275             LOG.error("Cannot find namespace {} in {}", namespace, namespacesToAnnotations);
276             throw new IllegalArgumentException("Cannot find namespace " + namespace);
277         }
278         ServiceInterfaceAnnotation sia = ofNamespace.get(localName);
279         if (sia == null) {
280             LOG.error("Cannot find local name {} in namespace {}, found only {}", localName, namespace, ofNamespace);
281             throw new IllegalArgumentException("Cannot find local name " + localName + " in namespace " + namespace);
282         }
283         return sia.value();
284     }
285
286     // reading:
287
288     @Override
289     public synchronized Map<String /* serviceInterfaceName */, Map<String/* refName */, ObjectName>> getServiceMapping() {
290         Map<String /* serviceInterfaceName */, Map<String/* refName */, ObjectName>> result = new HashMap<>();
291         for (Entry<ServiceReference, ModuleIdentifier> entry: refNames.entrySet()) {
292             String qName = entry.getKey().getServiceInterfaceQName();
293             Map<String /* refName */, ObjectName> innerMap = result.get(qName);
294             if (innerMap == null) {
295                 innerMap = new HashMap<>();
296                 result.put(qName, innerMap);
297             }
298             innerMap.put(entry.getKey().getRefName(), getObjectName(entry.getValue()));
299         }
300         return result;
301     }
302
303     private ObjectName getObjectName(final ModuleIdentifier moduleIdentifier) {
304         ObjectName on;
305         try {
306             on = lookupRegistry.lookupConfigBean(moduleIdentifier.getFactoryName(), moduleIdentifier.getInstanceName());
307         } catch (final InstanceNotFoundException e) {
308             LOG.error("Cannot find instance {}", moduleIdentifier);
309             throw new IllegalStateException("Cannot find instance " + moduleIdentifier, e);
310         }
311         return on;
312     }
313
314     @Override
315     public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
316         ServiceReference serviceReference = new ServiceReference(serviceInterfaceQName, refName);
317         ModuleIdentifier moduleIdentifier = refNames.get(serviceReference);
318         if (moduleIdentifier == null) {
319             LOG.error("Cannot find qname {} and refName {} in {}", serviceInterfaceQName, refName, refName);
320             throw new IllegalArgumentException("Cannot find " + serviceReference);
321         }
322         return getObjectName(moduleIdentifier);
323     }
324
325     @Override
326     public synchronized Map<String /* refName */, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
327         Map<String, Map<String, ObjectName>> serviceMapping = getServiceMapping();
328         Map<String, ObjectName> innerMap = serviceMapping.get(serviceInterfaceQName);
329         if (innerMap == null) {
330             LOG.error("Cannot find qname {} in {}", serviceInterfaceQName, refNames);
331             throw new IllegalArgumentException("Cannot find " + serviceInterfaceQName);
332         }
333         return innerMap;
334     }
335
336     @Override
337     public synchronized ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
338         ServiceReference serviceReference = new ServiceReference(serviceInterfaceQName, refName);
339         if (!mBeans.containsKey(serviceReference)) {
340             throw new InstanceNotFoundException("Cannot find " + serviceReference);
341         }
342         return getServiceON(serviceReference);
343     }
344
345     @Override
346     public synchronized void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
347         String actualTransactionName = ObjectNameUtil.getTransactionName(objectName);
348         String expectedTransactionName = serviceReferenceRegistrator.getNullableTransactionName();
349         if (writable && actualTransactionName == null || writable && !actualTransactionName.equals(expectedTransactionName)) {
350             throw new IllegalArgumentException("Mismatched transaction name in " + objectName);
351         }
352         String serviceQName = ObjectNameUtil.getServiceQName(objectName);
353         String referenceName = ObjectNameUtil.getReferenceName(objectName);
354         ServiceReference serviceReference = new ServiceReference(serviceQName, referenceName);
355         if (!refNames.containsKey(serviceReference)) {
356             LOG.warn("Cannot find {} in {}", serviceReference, refNames);
357             throw new InstanceNotFoundException("Service reference not found:" + objectName);
358         }
359     }
360
361     // writing:
362     private void assertWritable() {
363         if (!writable) {
364             throw new IllegalStateException("Cannot write to readable registry");
365         }
366     }
367
368     @Override
369     public synchronized ObjectName saveServiceReference(final String serviceInterfaceName, final String refName, final ObjectName moduleON)  throws InstanceNotFoundException {
370         assertWritable();
371         ServiceReference serviceReference = new ServiceReference(serviceInterfaceName, refName);
372         return saveServiceReference(serviceReference, moduleON);
373     }
374
375     private synchronized ObjectName saveServiceReference(final ServiceReference serviceReference, final ObjectName moduleON)
376             throws InstanceNotFoundException{
377         return saveServiceReference(serviceReference, moduleON, false);
378     }
379
380     private synchronized ObjectName saveServiceReference(final ServiceReference serviceReference, final ObjectName moduleON,
381                                                          final boolean skipChecks) throws InstanceNotFoundException {
382
383         // make sure it is found
384         if (!skipChecks) {
385             lookupRegistry.checkConfigBeanExists(moduleON);
386         }
387         String factoryName = ObjectNameUtil.getFactoryName(moduleON);
388         String instanceName = ObjectNameUtil.getInstanceName(moduleON);
389         ModuleIdentifier moduleIdentifier = new ModuleIdentifier(factoryName, instanceName);
390
391         // check that service interface name exist
392         Set<String> serviceInterfaceQNames = factoryNamesToQNames.get(moduleIdentifier.getFactoryName());
393         if (serviceInterfaceQNames == null) {
394             LOG.error("Possible error in code: cannot find factoryName {} in {}, {}", moduleIdentifier.getFactoryName(),
395                     factoryNamesToQNames, moduleIdentifier);
396             throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory " + moduleIdentifier.getFactoryName());
397         }
398         // supplied serviceInterfaceName must exist in this collection
399         if (!serviceInterfaceQNames.contains(serviceReference.getServiceInterfaceQName())) {
400             LOG.error("Cannot find qName {} with factory name {}, found {}", serviceReference.getServiceInterfaceQName(), moduleIdentifier.getFactoryName(), serviceInterfaceQNames);
401             throw new IllegalArgumentException("Cannot find service interface " + serviceReference.getServiceInterfaceQName() + " within factory " + moduleIdentifier.getFactoryName());
402         }
403
404
405         // create service reference object name, put to mBeans
406         ObjectName result = getServiceON(serviceReference);
407         Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> mxBeanEntry = mBeans.get(serviceReference);
408         if (mxBeanEntry == null) {
409             // create dummy mx bean
410             ServiceReferenceMXBeanImpl dummyMXBean = new ServiceReferenceMXBeanImpl(moduleON);
411             ServiceReferenceJMXRegistration dummyMXBeanRegistration;
412             try {
413                 dummyMXBeanRegistration = serviceReferenceRegistrator.registerMBean(dummyMXBean, result);
414             } catch (final InstanceAlreadyExistsException e) {
415                 throw new IllegalStateException("Possible error in code. Cannot register " + result, e);
416             }
417             mBeans.put(serviceReference, new SimpleImmutableEntry<>(dummyMXBean, dummyMXBeanRegistration));
418         } else {
419             // update
420             mxBeanEntry.getKey().setCurrentImplementation(moduleON);
421         }
422         // save to refNames
423         refNames.put(serviceReference, moduleIdentifier);
424         Map<ServiceInterfaceAnnotation, String /* service ref name */> refNamesToAnnotations = modulesToServiceRef.get(moduleIdentifier);
425         if (refNamesToAnnotations == null){
426             refNamesToAnnotations = new HashMap<>();
427             modulesToServiceRef.put(moduleIdentifier, refNamesToAnnotations);
428         }
429
430         ServiceInterfaceAnnotation annotation = serviceQNamesToAnnotations.get(serviceReference.getServiceInterfaceQName());
431         Preconditions.checkNotNull(annotation, "Possible error in code, cannot find annotation for " + serviceReference);
432         refNamesToAnnotations.put(annotation, serviceReference.getRefName());
433         return result;
434     }
435
436     private ObjectName getServiceON(final ServiceReference serviceReference) {
437         if (writable) {
438             return ObjectNameUtil.createTransactionServiceON(serviceReferenceRegistrator.getNullableTransactionName(),
439                     serviceReference.getServiceInterfaceQName(), serviceReference.getRefName());
440         }
441
442         return ObjectNameUtil.createReadOnlyServiceON(serviceReference.getServiceInterfaceQName(), serviceReference.getRefName());
443     }
444
445     @Override
446     public synchronized void removeServiceReference(final String serviceInterfaceName, final String refName) throws InstanceNotFoundException{
447         ServiceReference serviceReference = new ServiceReference(serviceInterfaceName, refName);
448         removeServiceReference(serviceReference);
449     }
450
451     private synchronized void removeServiceReference(final ServiceReference serviceReference) throws InstanceNotFoundException {
452         LOG.debug("Removing service reference {} from {}", serviceReference, this);
453         assertWritable();
454         // is the qName known?
455         if (!allQNames.contains(serviceReference.getServiceInterfaceQName())) {
456             LOG.error("Cannot find qname {} in {}", serviceReference.getServiceInterfaceQName(), allQNames);
457             throw new IllegalArgumentException("Cannot find service interface " + serviceReference.getServiceInterfaceQName());
458         }
459         ModuleIdentifier removed = refNames.remove(serviceReference);
460         if (removed == null){
461             throw new InstanceNotFoundException("Cannot find " + serviceReference.getServiceInterfaceQName());
462         }
463         Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> entry = mBeans.remove(serviceReference);
464         if (entry == null) {
465             throw new IllegalStateException("Possible code error: cannot remove from mBeans: " + serviceReference);
466         }
467         entry.getValue().close();
468     }
469
470     @Override
471     public synchronized void removeAllServiceReferences() {
472         assertWritable();
473         for (ServiceReference serviceReference: mBeans.keySet()) {
474             try {
475                 removeServiceReference(serviceReference);
476             } catch (final InstanceNotFoundException e) {
477                 throw new IllegalStateException("Possible error in code", e);
478             }
479         }
480     }
481
482     @Override
483     public synchronized boolean removeServiceReferences(final ObjectName moduleObjectName) throws InstanceNotFoundException {
484         lookupRegistry.checkConfigBeanExists(moduleObjectName);
485         String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName);
486         // check that service interface name exist
487         Set<String> serviceInterfaceQNames = factoryNamesToQNames.get(factoryName);
488         return removeServiceReferences(moduleObjectName, serviceInterfaceQNames);
489     }
490
491
492     private boolean removeServiceReferences(final ObjectName moduleObjectName, final Set<String> qNames) throws InstanceNotFoundException {
493         ObjectNameUtil.checkType(moduleObjectName, ObjectNameUtil.TYPE_MODULE);
494         assertWritable();
495         Set<ServiceReference> serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, qNames);
496         for (ServiceReference sr : serviceReferencesLinkingTo) {
497             removeServiceReference(sr);
498         }
499         return !serviceReferencesLinkingTo.isEmpty();
500     }
501
502     private Set<ServiceReference> findServiceReferencesLinkingTo(final ObjectName moduleObjectName, final Set<String> serviceInterfaceQNames) {
503         String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName);
504         if (serviceInterfaceQNames == null) {
505             LOG.warn("Possible error in code: cannot find factoryName {} in {}, object name {}", factoryName, factoryNamesToQNames, moduleObjectName);
506             throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory " + factoryName);
507         }
508         String instanceName = ObjectNameUtil.getInstanceName(moduleObjectName);
509         ModuleIdentifier moduleIdentifier = new ModuleIdentifier(factoryName, instanceName);
510         Set<ServiceReference> result = new HashSet<>();
511         for (Entry<ServiceReference, ModuleIdentifier> entry : refNames.entrySet()) {
512             if (entry.getValue().equals(moduleIdentifier)) {
513                 result.add(entry.getKey());
514             }
515         }
516         return result;
517     }
518
519     @Override
520     public String toString() {
521         return "ServiceReferenceRegistryImpl{" +
522                 "lookupRegistry=" + lookupRegistry +
523                 "refNames=" + refNames +
524                 ", factoryNamesToQNames=" + factoryNamesToQNames +
525                 '}';
526     }
527
528     @Override
529     public void close() {
530         serviceReferenceRegistrator.close();
531     }
532 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.