Use simple Registration in ClusterSingletonServiceProvider
[mdsal.git] / singleton-service / mdsal-singleton-dom-impl / src / main / java / org / opendaylight / mdsal / singleton / dom / impl / EOSClusterSingletonServiceProvider.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.mdsal.singleton.dom.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Strings;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.ExecutionException;
25 import javax.annotation.PreDestroy;
26 import javax.inject.Inject;
27 import javax.inject.Singleton;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
30 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipStateChange;
31 import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
32 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListener;
33 import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipService;
34 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
35 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
36 import org.opendaylight.yangtools.concepts.Registration;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
38 import org.osgi.service.component.annotations.Activate;
39 import org.osgi.service.component.annotations.Component;
40 import org.osgi.service.component.annotations.Deactivate;
41 import org.osgi.service.component.annotations.Reference;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * Implementation of {@link ClusterSingletonServiceProvider} working on top a {@link DOMEntityOwnershipService}.
47  */
48 @Singleton
49 @Component(service = ClusterSingletonServiceProvider.class)
50 public final class EOSClusterSingletonServiceProvider
51         implements ClusterSingletonServiceProvider, DOMEntityOwnershipListener, AutoCloseable {
52     private static final Logger LOG = LoggerFactory.getLogger(EOSClusterSingletonServiceProvider.class);
53
54     @VisibleForTesting
55     static final @NonNull String SERVICE_ENTITY_TYPE = "org.opendaylight.mdsal.ServiceEntityType";
56     @VisibleForTesting
57     static final @NonNull String CLOSE_SERVICE_ENTITY_TYPE = "org.opendaylight.mdsal.AsyncServiceCloseEntityType";
58
59     private final ConcurrentMap<String, ClusterSingletonServiceGroup> serviceGroupMap = new ConcurrentHashMap<>();
60     private final DOMEntityOwnershipService entityOwnershipService;
61
62     /* EOS Entity Listeners Registration */
63     private Registration serviceEntityListenerReg;
64     private Registration asyncCloseEntityListenerReg;
65
66     @Inject
67     @Activate
68     public EOSClusterSingletonServiceProvider(@Reference final DOMEntityOwnershipService entityOwnershipService) {
69         this.entityOwnershipService = requireNonNull(entityOwnershipService);
70         serviceEntityListenerReg = entityOwnershipService.registerListener(SERVICE_ENTITY_TYPE, this);
71         asyncCloseEntityListenerReg = entityOwnershipService.registerListener(CLOSE_SERVICE_ENTITY_TYPE, this);
72         LOG.info("Cluster Singleton Service started");
73     }
74
75     @PreDestroy
76     @Deactivate
77     @Override
78     public synchronized void close() throws ExecutionException, InterruptedException {
79         if (serviceEntityListenerReg == null) {
80             // Idempotent
81             return;
82         }
83
84         LOG.info("Cluster Singleton Service stopping");
85         serviceEntityListenerReg.close();
86         serviceEntityListenerReg = null;
87
88         final var future = Futures.allAsList(serviceGroupMap.values().stream()
89             .map(ClusterSingletonServiceGroup::closeClusterSingletonGroup)
90             .toList());
91         try {
92             LOG.debug("Waiting for service groups to stop");
93             future.get();
94         } finally {
95             asyncCloseEntityListenerReg.close();
96             asyncCloseEntityListenerReg = null;
97             serviceGroupMap.clear();
98         }
99
100         LOG.info("Cluster Singleton Service stopped");
101     }
102
103     @Override
104     public synchronized Registration registerClusterSingletonService(final ClusterSingletonService service) {
105         LOG.debug("Call registrationService {} method for ClusterSingletonService Provider {}", service, this);
106
107         final String serviceIdentifier = service.getIdentifier().getName();
108         checkArgument(!Strings.isNullOrEmpty(serviceIdentifier),
109             "ClusterSingletonService identifier may not be null nor empty");
110
111         final ClusterSingletonServiceGroup serviceGroup;
112         final var existing = serviceGroupMap.get(serviceIdentifier);
113         if (existing == null) {
114             serviceGroup = createGroup(serviceIdentifier, new ArrayList<>(1));
115             serviceGroupMap.put(serviceIdentifier, serviceGroup);
116
117             try {
118                 initializeOrRemoveGroup(serviceGroup);
119             } catch (CandidateAlreadyRegisteredException e) {
120                 throw new IllegalArgumentException("Service group already registered", e);
121             }
122         } else {
123             serviceGroup = existing;
124         }
125
126         final var reg = new ServiceRegistration(service) {
127             @Override
128             protected void removeRegistration() {
129                 // We need to bounce the unregistration through a ordered lock in order not to deal with asynchronous
130                 // shutdown of the group and user registering it again.
131                 EOSClusterSingletonServiceProvider.this.removeRegistration(serviceIdentifier, this);
132             }
133         };
134
135         serviceGroup.registerService(reg);
136         return reg;
137     }
138
139     private ClusterSingletonServiceGroup createGroup(final String serviceIdentifier,
140             final List<ServiceRegistration> services) {
141         return new ClusterSingletonServiceGroupImpl(serviceIdentifier, entityOwnershipService,
142             createEntity(SERVICE_ENTITY_TYPE, serviceIdentifier),
143             createEntity(CLOSE_SERVICE_ENTITY_TYPE, serviceIdentifier), services);
144     }
145
146     private void initializeOrRemoveGroup(final ClusterSingletonServiceGroup group)
147             throws CandidateAlreadyRegisteredException {
148         try {
149             group.initialize();
150         } catch (CandidateAlreadyRegisteredException e) {
151             serviceGroupMap.remove(group.getIdentifier(), group);
152             throw e;
153         }
154     }
155
156     private void removeRegistration(final String serviceIdentifier, final ServiceRegistration reg) {
157         final PlaceholderGroup placeHolder;
158         final ListenableFuture<?> future;
159         synchronized (this) {
160             final var lookup = verifyNotNull(serviceGroupMap.get(serviceIdentifier));
161             future = lookup.unregisterService(reg);
162             if (future == null) {
163                 return;
164             }
165
166             // Close the group and replace it with a placeholder
167             LOG.debug("Closing service group {}", serviceIdentifier);
168             placeHolder = new PlaceholderGroup(lookup, future);
169
170             final String identifier = reg.getInstance().getIdentifier().getName();
171             verify(serviceGroupMap.replace(identifier, lookup, placeHolder));
172             LOG.debug("Replaced group {} with {}", serviceIdentifier, placeHolder);
173
174             lookup.closeClusterSingletonGroup();
175         }
176
177         future.addListener(() -> finishShutdown(placeHolder), MoreExecutors.directExecutor());
178     }
179
180     private synchronized void finishShutdown(final PlaceholderGroup placeHolder) {
181         final var identifier = placeHolder.getIdentifier();
182         LOG.debug("Service group {} closed", identifier);
183
184         final var services = placeHolder.getServices();
185         if (services.isEmpty()) {
186             // No services, we are all done
187             if (serviceGroupMap.remove(identifier, placeHolder)) {
188                 LOG.debug("Service group {} removed", placeHolder);
189             } else {
190                 LOG.debug("Service group {} superseded by {}", placeHolder, serviceGroupMap.get(identifier));
191             }
192             return;
193         }
194
195         // Placeholder is being retired, we are reusing its services as the seed for the group.
196         final var group = createGroup(identifier, services);
197         verify(serviceGroupMap.replace(identifier, placeHolder, group));
198         placeHolder.setSuccessor(group);
199         LOG.debug("Service group upgraded from {} to {}", placeHolder, group);
200
201         try {
202             initializeOrRemoveGroup(group);
203         } catch (CandidateAlreadyRegisteredException e) {
204             LOG.error("Failed to register delayed group {}, it will remain inoperational", identifier, e);
205         }
206     }
207
208     @Override
209     public void ownershipChanged(final DOMEntity entity, final EntityOwnershipStateChange change,
210             final boolean inJeopardy) {
211         LOG.debug("Ownership change for ClusterSingletonService Provider on {} {} inJeopardy={}", entity, change,
212             inJeopardy);
213
214         final var serviceIdentifier = getServiceIdentifierFromEntity(entity);
215         final var serviceHolder = serviceGroupMap.get(serviceIdentifier);
216         if (serviceHolder != null) {
217             serviceHolder.ownershipChanged(entity, change, inJeopardy);
218         } else {
219             LOG.debug("ClusterSingletonServiceGroup was not found for serviceIdentifier {}", serviceIdentifier);
220         }
221     }
222
223     @VisibleForTesting
224     static String getServiceIdentifierFromEntity(final DOMEntity entity) {
225         final var yii = entity.getIdentifier();
226         final var niiwp = (NodeIdentifierWithPredicates) yii.getLastPathArgument();
227         return niiwp.values().iterator().next().toString();
228     }
229
230     /**
231      * Creates an extended {@link DOMEntity} instance.
232      *
233      * @param entityType the type of the entity
234      * @param entityIdentifier the identifier of the entity
235      * @return instance of Entity extended GenericEntity type
236      */
237     @VisibleForTesting
238     static DOMEntity createEntity(final String entityType, final String entityIdentifier) {
239         return new DOMEntity(entityType, entityIdentifier);
240     }
241 }