blob: 28e3302300c1617367499f88211d44f94bd485da [file] [log] [blame]
alshabib10580802015-02-18 18:30:33 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
alshabib10580802015-02-18 18:30:33 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.store.group.impl;
17
Jonathan Hart6ec029a2015-03-24 17:12:35 -070018import com.google.common.collect.FluentIterable;
Charles Chanf4838a72015-12-07 18:13:45 -080019import com.google.common.collect.ImmutableSet;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070020import com.google.common.collect.Iterables;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070021import com.google.common.collect.Sets;
alshabib10580802015-02-18 18:30:33 -080022import org.apache.felix.scr.annotations.Activate;
23import org.apache.felix.scr.annotations.Component;
24import org.apache.felix.scr.annotations.Deactivate;
alshabibb0285992016-03-28 23:30:37 -070025import org.apache.felix.scr.annotations.Modified;
26import org.apache.felix.scr.annotations.Property;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070027import org.apache.felix.scr.annotations.Reference;
28import org.apache.felix.scr.annotations.ReferenceCardinality;
alshabib10580802015-02-18 18:30:33 -080029import org.apache.felix.scr.annotations.Service;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070030import org.onlab.util.KryoNamespace;
alshabibb0285992016-03-28 23:30:37 -070031import org.onosproject.cfg.ComponentConfigService;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070032import org.onosproject.cluster.ClusterService;
Charles Chanf4838a72015-12-07 18:13:45 -080033import org.onosproject.cluster.NodeId;
alshabib10580802015-02-18 18:30:33 -080034import org.onosproject.core.DefaultGroupId;
35import org.onosproject.core.GroupId;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070036import org.onosproject.mastership.MastershipService;
alshabib10580802015-02-18 18:30:33 -080037import org.onosproject.net.DeviceId;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070038import org.onosproject.net.MastershipRole;
alshabib10580802015-02-18 18:30:33 -080039import org.onosproject.net.group.DefaultGroup;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070040import org.onosproject.net.group.DefaultGroupBucket;
alshabib10580802015-02-18 18:30:33 -080041import org.onosproject.net.group.DefaultGroupDescription;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070042import org.onosproject.net.group.DefaultGroupKey;
alshabib10580802015-02-18 18:30:33 -080043import org.onosproject.net.group.Group;
44import org.onosproject.net.group.Group.GroupState;
45import org.onosproject.net.group.GroupBucket;
46import org.onosproject.net.group.GroupBuckets;
47import org.onosproject.net.group.GroupDescription;
48import org.onosproject.net.group.GroupEvent;
49import org.onosproject.net.group.GroupEvent.Type;
50import org.onosproject.net.group.GroupKey;
51import org.onosproject.net.group.GroupOperation;
52import org.onosproject.net.group.GroupStore;
53import org.onosproject.net.group.GroupStoreDelegate;
Srikanth Vavilapalli10e75cd2015-04-13 16:21:24 -070054import org.onosproject.net.group.StoredGroupBucketEntry;
alshabib10580802015-02-18 18:30:33 -080055import org.onosproject.net.group.StoredGroupEntry;
56import org.onosproject.store.AbstractStore;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070057import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070058import org.onosproject.store.serializers.KryoNamespaces;
Madan Jampani0b847532016-03-03 13:44:15 -080059import org.onosproject.store.service.ConsistentMap;
60import org.onosproject.store.service.MapEvent;
61import org.onosproject.store.service.MapEventListener;
alshabibb0285992016-03-28 23:30:37 -070062import org.onosproject.store.service.MultiValuedTimestamp;
Madan Jampani0b847532016-03-03 13:44:15 -080063import org.onosproject.store.service.Serializer;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070064import org.onosproject.store.service.StorageService;
helenyrwua1c41152016-08-18 16:16:14 -070065import org.onosproject.store.service.Topic;
Madan Jampani0b847532016-03-03 13:44:15 -080066import org.onosproject.store.service.Versioned;
alshabibb0285992016-03-28 23:30:37 -070067import org.osgi.service.component.ComponentContext;
alshabib10580802015-02-18 18:30:33 -080068import org.slf4j.Logger;
69
Jonathan Hart6ec029a2015-03-24 17:12:35 -070070import java.util.ArrayList;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070071import java.util.Collection;
Charles Chanf4838a72015-12-07 18:13:45 -080072import java.util.Collections;
alshabibb0285992016-03-28 23:30:37 -070073import java.util.Dictionary;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070074import java.util.HashMap;
Charles Chan0c7c43b2016-01-14 17:39:20 -080075import java.util.HashSet;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070076import java.util.Iterator;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070077import java.util.List;
Madan Jampani0b847532016-03-03 13:44:15 -080078import java.util.Map;
Charles Chan0c7c43b2016-01-14 17:39:20 -080079import java.util.Map.Entry;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070080import java.util.Objects;
Sho SHIMIZU30d639b2015-05-05 09:30:35 -070081import java.util.Optional;
alshabibb0285992016-03-28 23:30:37 -070082import java.util.Properties;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -070083import java.util.Set;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070084import java.util.concurrent.ConcurrentHashMap;
85import java.util.concurrent.ConcurrentMap;
86import java.util.concurrent.ExecutorService;
87import java.util.concurrent.Executors;
88import java.util.concurrent.atomic.AtomicInteger;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070089import java.util.stream.Collectors;
90
alshabibb0285992016-03-28 23:30:37 -070091import static com.google.common.base.Strings.isNullOrEmpty;
alshabibb0285992016-03-28 23:30:37 -070092import static org.onlab.util.Tools.get;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070093import static org.onlab.util.Tools.groupedThreads;
94import static org.slf4j.LoggerFactory.getLogger;
alshabib10580802015-02-18 18:30:33 -080095
96/**
Saurav Das0fd79d92016-03-07 10:58:36 -080097 * Manages inventory of group entries using distributed group stores from the
98 * storage service.
alshabib10580802015-02-18 18:30:33 -080099 */
100@Component(immediate = true)
101@Service
102public class DistributedGroupStore
103 extends AbstractStore<GroupEvent, GroupStoreDelegate>
104 implements GroupStore {
105
106 private final Logger log = getLogger(getClass());
107
alshabibb0285992016-03-28 23:30:37 -0700108 private static final boolean GARBAGE_COLLECT = false;
109 private static final int GC_THRESH = 6;
110
alshabib10580802015-02-18 18:30:33 -0800111 private final int dummyId = 0xffffffff;
112 private final GroupId dummyGroupId = new DefaultGroupId(dummyId);
113
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700114 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
115 protected ClusterCommunicationService clusterCommunicator;
116
117 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
118 protected ClusterService clusterService;
119
120 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700121 protected StorageService storageService;
122
123 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700124 protected MastershipService mastershipService;
125
alshabibb0285992016-03-28 23:30:37 -0700126 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
127 protected ComponentConfigService cfgService;
128
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700129 // Per device group table with (device id + app cookie) as key
Madan Jampani0b847532016-03-03 13:44:15 -0800130 private ConsistentMap<GroupStoreKeyMapKey,
alshabibb0285992016-03-28 23:30:37 -0700131 StoredGroupEntry> groupStoreEntriesByKey = null;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700132 // Per device group table with (device id + group id) as key
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700133 private final ConcurrentMap<DeviceId, ConcurrentMap<GroupId, StoredGroupEntry>>
alshabibb0285992016-03-28 23:30:37 -0700134 groupEntriesById = new ConcurrentHashMap<>();
Madan Jampani0b847532016-03-03 13:44:15 -0800135 private ConsistentMap<GroupStoreKeyMapKey,
alshabibb0285992016-03-28 23:30:37 -0700136 StoredGroupEntry> auditPendingReqQueue = null;
Frank Wange0eb5ce2016-07-01 18:21:25 +0800137 private MapEventListener<GroupStoreKeyMapKey, StoredGroupEntry>
138 mapListener = new GroupStoreKeyMapListener();
alshabib10580802015-02-18 18:30:33 -0800139 private final ConcurrentMap<DeviceId, ConcurrentMap<GroupId, Group>>
140 extraneousGroupEntriesById = new ConcurrentHashMap<>();
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700141 private ExecutorService messageHandlingExecutor;
142 private static final int MESSAGE_HANDLER_THREAD_POOL_SIZE = 1;
Sho SHIMIZU7a4087b2015-09-10 09:23:16 -0700143 private final HashMap<DeviceId, Boolean> deviceAuditStatus = new HashMap<>();
alshabib10580802015-02-18 18:30:33 -0800144
145 private final AtomicInteger groupIdGen = new AtomicInteger();
146
HIGUCHI Yuta180d70f2015-10-01 16:13:56 -0700147 private KryoNamespace clusterMsgSerializer;
148
helenyrwua1c41152016-08-18 16:16:14 -0700149 private static Topic<GroupStoreMessage> groupTopic;
150
alshabibb0285992016-03-28 23:30:37 -0700151 @Property(name = "garbageCollect", boolValue = GARBAGE_COLLECT,
152 label = "Enable group garbage collection")
153 private boolean garbageCollect = GARBAGE_COLLECT;
154
155 @Property(name = "gcThresh", intValue = GC_THRESH,
156 label = "Number of rounds for group garbage collection")
157 private int gcThresh = GC_THRESH;
158
159
alshabib10580802015-02-18 18:30:33 -0800160 @Activate
161 public void activate() {
alshabibb0285992016-03-28 23:30:37 -0700162 cfgService.registerProperties(getClass());
HIGUCHI Yuta3a84b322016-05-18 13:38:07 -0700163 KryoNamespace.Builder kryoBuilder = new KryoNamespace.Builder()
alshabibb0285992016-03-28 23:30:37 -0700164 .register(KryoNamespaces.API)
HIGUCHI Yuta3a84b322016-05-18 13:38:07 -0700165 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
alshabibb0285992016-03-28 23:30:37 -0700166 .register(DefaultGroup.class,
167 DefaultGroupBucket.class,
168 DefaultGroupDescription.class,
169 DefaultGroupKey.class,
170 GroupDescription.Type.class,
171 Group.GroupState.class,
172 GroupBuckets.class,
alshabibb0285992016-03-28 23:30:37 -0700173 GroupStoreMessage.class,
174 GroupStoreMessage.Type.class,
175 UpdateType.class,
176 GroupStoreMessageSubjects.class,
177 MultiValuedTimestamp.class,
178 GroupStoreKeyMapKey.class,
179 GroupStoreIdMapKey.class,
180 GroupStoreMapKey.class
181 );
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700182
HIGUCHI Yuta3a84b322016-05-18 13:38:07 -0700183 clusterMsgSerializer = kryoBuilder.build("GroupStore");
184 Serializer serializer = Serializer.using(clusterMsgSerializer);
HIGUCHI Yuta180d70f2015-10-01 16:13:56 -0700185
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700186 messageHandlingExecutor = Executors.
187 newFixedThreadPool(MESSAGE_HANDLER_THREAD_POOL_SIZE,
188 groupedThreads("onos/store/group",
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700189 "message-handlers",
190 log));
Madan Jampani01e05fb2015-08-13 13:29:36 -0700191
192 clusterCommunicator.addSubscriber(GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST,
alshabibb0285992016-03-28 23:30:37 -0700193 clusterMsgSerializer::deserialize,
194 this::process,
195 messageHandlingExecutor);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700196
Madan Jampani0b847532016-03-03 13:44:15 -0800197 log.debug("Creating Consistent map onos-group-store-keymap");
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700198
Madan Jampani0b847532016-03-03 13:44:15 -0800199 groupStoreEntriesByKey = storageService.<GroupStoreKeyMapKey, StoredGroupEntry>consistentMapBuilder()
200 .withName("onos-group-store-keymap")
HIGUCHI Yuta3a84b322016-05-18 13:38:07 -0700201 .withSerializer(serializer)
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700202 .build();
Frank Wange0eb5ce2016-07-01 18:21:25 +0800203 groupStoreEntriesByKey.addListener(mapListener);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700204 log.debug("Current size of groupstorekeymap:{}",
205 groupStoreEntriesByKey.size());
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700206
Madan Jampani0b847532016-03-03 13:44:15 -0800207 log.debug("Creating Consistent map pendinggroupkeymap");
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700208
Madan Jampani0b847532016-03-03 13:44:15 -0800209 auditPendingReqQueue = storageService.<GroupStoreKeyMapKey, StoredGroupEntry>consistentMapBuilder()
210 .withName("onos-pending-group-keymap")
HIGUCHI Yuta3a84b322016-05-18 13:38:07 -0700211 .withSerializer(serializer)
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700212 .build();
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700213 log.debug("Current size of pendinggroupkeymap:{}",
214 auditPendingReqQueue.size());
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700215
helenyrwua1c41152016-08-18 16:16:14 -0700216 groupTopic = getOrCreateGroupTopic(serializer);
217 groupTopic.subscribe(this::processGroupMessage);
218
alshabib10580802015-02-18 18:30:33 -0800219 log.info("Started");
220 }
221
222 @Deactivate
223 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800224 groupStoreEntriesByKey.removeListener(mapListener);
alshabibb0285992016-03-28 23:30:37 -0700225 cfgService.unregisterProperties(getClass(), false);
HIGUCHI Yuta180d70f2015-10-01 16:13:56 -0700226 clusterCommunicator.removeSubscriber(GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST);
alshabib10580802015-02-18 18:30:33 -0800227 log.info("Stopped");
228 }
229
alshabibb0285992016-03-28 23:30:37 -0700230 @Modified
231 public void modified(ComponentContext context) {
232 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
233
234 try {
235 String s = get(properties, "garbageCollect");
236 garbageCollect = isNullOrEmpty(s) ? GARBAGE_COLLECT : Boolean.parseBoolean(s.trim());
237
238 s = get(properties, "gcThresh");
239 gcThresh = isNullOrEmpty(s) ? GC_THRESH : Integer.parseInt(s.trim());
240 } catch (Exception e) {
241 gcThresh = GC_THRESH;
242 garbageCollect = GARBAGE_COLLECT;
243 }
244 }
245
helenyrwua1c41152016-08-18 16:16:14 -0700246 private Topic<GroupStoreMessage> getOrCreateGroupTopic(Serializer serializer) {
247 if (groupTopic == null) {
248 return storageService.getTopic("group-failover-notif", serializer);
249 } else {
250 return groupTopic;
251 }
Sho SHIMIZUa6285542017-01-12 15:08:24 -0800252 }
helenyrwua1c41152016-08-18 16:16:14 -0700253
alshabib10580802015-02-18 18:30:33 -0800254 /**
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700255 * Returns the group store eventual consistent key map.
alshabib10580802015-02-18 18:30:33 -0800256 *
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700257 * @return Map representing group key table.
alshabib10580802015-02-18 18:30:33 -0800258 */
Madan Jampani0b847532016-03-03 13:44:15 -0800259 private Map<GroupStoreKeyMapKey, StoredGroupEntry>
alshabibb0285992016-03-28 23:30:37 -0700260 getGroupStoreKeyMap() {
Madan Jampani0b847532016-03-03 13:44:15 -0800261 return groupStoreEntriesByKey.asJavaMap();
alshabib10580802015-02-18 18:30:33 -0800262 }
263
264 /**
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700265 * Returns the group id table for specified device.
alshabib10580802015-02-18 18:30:33 -0800266 *
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700267 * @param deviceId identifier of the device
268 * @return Map representing group key table of given device.
alshabib10580802015-02-18 18:30:33 -0800269 */
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700270 private ConcurrentMap<GroupId, StoredGroupEntry> getGroupIdTable(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700271 return groupEntriesById.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
alshabib10580802015-02-18 18:30:33 -0800272 }
273
274 /**
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700275 * Returns the pending group request table.
alshabib10580802015-02-18 18:30:33 -0800276 *
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700277 * @return Map representing group key table.
alshabib10580802015-02-18 18:30:33 -0800278 */
Madan Jampani0b847532016-03-03 13:44:15 -0800279 private Map<GroupStoreKeyMapKey, StoredGroupEntry>
alshabibb0285992016-03-28 23:30:37 -0700280 getPendingGroupKeyTable() {
Madan Jampani0b847532016-03-03 13:44:15 -0800281 return auditPendingReqQueue.asJavaMap();
alshabib10580802015-02-18 18:30:33 -0800282 }
283
284 /**
285 * Returns the extraneous group id table for specified device.
286 *
287 * @param deviceId identifier of the device
288 * @return Map representing group key table of given device.
289 */
290 private ConcurrentMap<GroupId, Group>
291 getExtraneousGroupIdTable(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700292 return extraneousGroupEntriesById.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
alshabib10580802015-02-18 18:30:33 -0800293 }
294
295 /**
296 * Returns the number of groups for the specified device in the store.
297 *
298 * @return number of groups for the specified device
299 */
300 @Override
301 public int getGroupCount(DeviceId deviceId) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700302 return (getGroups(deviceId) != null) ?
alshabibb0285992016-03-28 23:30:37 -0700303 Iterables.size(getGroups(deviceId)) : 0;
alshabib10580802015-02-18 18:30:33 -0800304 }
305
306 /**
307 * Returns the groups associated with a device.
308 *
309 * @param deviceId the device ID
alshabib10580802015-02-18 18:30:33 -0800310 * @return the group entries
311 */
312 @Override
313 public Iterable<Group> getGroups(DeviceId deviceId) {
Charles Chanf4838a72015-12-07 18:13:45 -0800314 // Let ImmutableSet.copyOf do the type conversion
315 return ImmutableSet.copyOf(getStoredGroups(deviceId));
alshabib10580802015-02-18 18:30:33 -0800316 }
317
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700318 private Iterable<StoredGroupEntry> getStoredGroups(DeviceId deviceId) {
Charles Chanf4838a72015-12-07 18:13:45 -0800319 NodeId master = mastershipService.getMasterFor(deviceId);
320 if (master == null) {
321 log.debug("Failed to getGroups: No master for {}", deviceId);
322 return Collections.emptySet();
323 }
324
325 Set<StoredGroupEntry> storedGroups = getGroupStoreKeyMap().values()
326 .stream()
327 .filter(input -> input.deviceId().equals(deviceId))
328 .collect(Collectors.toSet());
329 return ImmutableSet.copyOf(storedGroups);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700330 }
331
alshabib10580802015-02-18 18:30:33 -0800332 /**
333 * Returns the stored group entry.
334 *
alshabibb0285992016-03-28 23:30:37 -0700335 * @param deviceId the device ID
alshabib10580802015-02-18 18:30:33 -0800336 * @param appCookie the group key
alshabib10580802015-02-18 18:30:33 -0800337 * @return a group associated with the key
338 */
339 @Override
340 public Group getGroup(DeviceId deviceId, GroupKey appCookie) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700341 return getStoredGroupEntry(deviceId, appCookie);
342 }
343
344 private StoredGroupEntry getStoredGroupEntry(DeviceId deviceId,
345 GroupKey appCookie) {
346 return getGroupStoreKeyMap().get(new GroupStoreKeyMapKey(deviceId,
347 appCookie));
348 }
349
350 @Override
351 public Group getGroup(DeviceId deviceId, GroupId groupId) {
352 return getStoredGroupEntry(deviceId, groupId);
353 }
354
355 private StoredGroupEntry getStoredGroupEntry(DeviceId deviceId,
356 GroupId groupId) {
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700357 return getGroupIdTable(deviceId).get(groupId);
alshabib10580802015-02-18 18:30:33 -0800358 }
359
360 private int getFreeGroupIdValue(DeviceId deviceId) {
361 int freeId = groupIdGen.incrementAndGet();
362
363 while (true) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700364 Group existing = getGroup(deviceId, new DefaultGroupId(freeId));
alshabib10580802015-02-18 18:30:33 -0800365 if (existing == null) {
366 existing = (
367 extraneousGroupEntriesById.get(deviceId) != null) ?
368 extraneousGroupEntriesById.get(deviceId).
369 get(new DefaultGroupId(freeId)) :
370 null;
371 }
372 if (existing != null) {
373 freeId = groupIdGen.incrementAndGet();
374 } else {
375 break;
376 }
377 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700378 log.debug("getFreeGroupIdValue: Next Free ID is {}", freeId);
alshabib10580802015-02-18 18:30:33 -0800379 return freeId;
380 }
381
382 /**
383 * Stores a new group entry using the information from group description.
384 *
385 * @param groupDesc group description to be used to create group entry
386 */
387 @Override
388 public void storeGroupDescription(GroupDescription groupDesc) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700389 log.debug("In storeGroupDescription");
alshabib10580802015-02-18 18:30:33 -0800390 // Check if a group is existing with the same key
Saurav Das8a0732e2015-11-20 15:27:53 -0800391 Group existingGroup = getGroup(groupDesc.deviceId(), groupDesc.appCookie());
392 if (existingGroup != null) {
Charles Chan216e3c82016-04-23 14:48:16 -0700393 log.info("Group already exists with the same key {} in dev:{} with id:0x{}",
Saurav Das8a0732e2015-11-20 15:27:53 -0800394 groupDesc.appCookie(), groupDesc.deviceId(),
395 Integer.toHexString(existingGroup.id().id()));
alshabib10580802015-02-18 18:30:33 -0800396 return;
397 }
398
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700399 // Check if group to be created by a remote instance
Madan Jampani175e8fd2015-05-20 14:10:45 -0700400 if (mastershipService.getLocalRole(groupDesc.deviceId()) != MastershipRole.MASTER) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700401 log.debug("storeGroupDescription: Device {} local role is not MASTER",
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700402 groupDesc.deviceId());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700403 if (mastershipService.getMasterFor(groupDesc.deviceId()) == null) {
404 log.error("No Master for device {}..."
alshabibb0285992016-03-28 23:30:37 -0700405 + "Can not perform add group operation",
406 groupDesc.deviceId());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700407 //TODO: Send Group operation failure event
408 return;
409 }
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700410 GroupStoreMessage groupOp = GroupStoreMessage.
411 createGroupAddRequestMsg(groupDesc.deviceId(),
412 groupDesc);
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700413
Madan Jampani175e8fd2015-05-20 14:10:45 -0700414 clusterCommunicator.unicast(groupOp,
alshabibb0285992016-03-28 23:30:37 -0700415 GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST,
416 clusterMsgSerializer::serialize,
417 mastershipService.getMasterFor(groupDesc.deviceId()))
418 .whenComplete((result, error) -> {
Madan Jampani175e8fd2015-05-20 14:10:45 -0700419 if (error != null) {
420 log.warn("Failed to send request to master: {} to {}",
alshabibb0285992016-03-28 23:30:37 -0700421 groupOp,
422 mastershipService.getMasterFor(groupDesc.deviceId()));
Madan Jampani175e8fd2015-05-20 14:10:45 -0700423 //TODO: Send Group operation failure event
424 } else {
425 log.debug("Sent Group operation request for device {} "
alshabibb0285992016-03-28 23:30:37 -0700426 + "to remote MASTER {}",
427 groupDesc.deviceId(),
428 mastershipService.getMasterFor(groupDesc.deviceId()));
Madan Jampani175e8fd2015-05-20 14:10:45 -0700429 }
430 });
alshabib10580802015-02-18 18:30:33 -0800431 return;
432 }
433
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700434 log.debug("Store group for device {} is getting handled locally",
435 groupDesc.deviceId());
alshabib10580802015-02-18 18:30:33 -0800436 storeGroupDescriptionInternal(groupDesc);
437 }
438
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700439 private Group getMatchingExtraneousGroupbyId(DeviceId deviceId, Integer groupId) {
440 ConcurrentMap<GroupId, Group> extraneousMap =
441 extraneousGroupEntriesById.get(deviceId);
442 if (extraneousMap == null) {
443 return null;
444 }
445 return extraneousMap.get(new DefaultGroupId(groupId));
446 }
447
448 private Group getMatchingExtraneousGroupbyBuckets(DeviceId deviceId,
449 GroupBuckets buckets) {
450 ConcurrentMap<GroupId, Group> extraneousMap =
451 extraneousGroupEntriesById.get(deviceId);
452 if (extraneousMap == null) {
453 return null;
454 }
455
alshabibb0285992016-03-28 23:30:37 -0700456 for (Group extraneousGroup : extraneousMap.values()) {
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700457 if (extraneousGroup.buckets().equals(buckets)) {
458 return extraneousGroup;
459 }
460 }
461 return null;
462 }
463
alshabib10580802015-02-18 18:30:33 -0800464 private void storeGroupDescriptionInternal(GroupDescription groupDesc) {
465 // Check if a group is existing with the same key
466 if (getGroup(groupDesc.deviceId(), groupDesc.appCookie()) != null) {
467 return;
468 }
469
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700470 if (deviceAuditStatus.get(groupDesc.deviceId()) == null) {
471 // Device group audit has not completed yet
472 // Add this group description to pending group key table
473 // Create a group entry object with Dummy Group ID
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700474 log.debug("storeGroupDescriptionInternal: Device {} AUDIT pending...Queuing Group ADD request",
alshabibb0285992016-03-28 23:30:37 -0700475 groupDesc.deviceId());
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700476 StoredGroupEntry group = new DefaultGroup(dummyGroupId, groupDesc);
477 group.setState(GroupState.WAITING_AUDIT_COMPLETE);
Madan Jampani0b847532016-03-03 13:44:15 -0800478 Map<GroupStoreKeyMapKey, StoredGroupEntry> pendingKeyTable =
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700479 getPendingGroupKeyTable();
480 pendingKeyTable.put(new GroupStoreKeyMapKey(groupDesc.deviceId(),
481 groupDesc.appCookie()),
482 group);
483 return;
484 }
485
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700486 Group matchingExtraneousGroup = null;
487 if (groupDesc.givenGroupId() != null) {
488 //Check if there is a extraneous group existing with the same Id
489 matchingExtraneousGroup = getMatchingExtraneousGroupbyId(
alshabibb0285992016-03-28 23:30:37 -0700490 groupDesc.deviceId(), groupDesc.givenGroupId());
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700491 if (matchingExtraneousGroup != null) {
Saurav Das0fd79d92016-03-07 10:58:36 -0800492 log.debug("storeGroupDescriptionInternal: Matching extraneous group "
alshabibb0285992016-03-28 23:30:37 -0700493 + "found in Device {} for group id 0x{}",
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700494 groupDesc.deviceId(),
Saurav Das0fd79d92016-03-07 10:58:36 -0800495 Integer.toHexString(groupDesc.givenGroupId()));
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700496 //Check if the group buckets matches with user provided buckets
497 if (matchingExtraneousGroup.buckets().equals(groupDesc.buckets())) {
498 //Group is already existing with the same buckets and Id
499 // Create a group entry object
Saurav Das0fd79d92016-03-07 10:58:36 -0800500 log.debug("storeGroupDescriptionInternal: Buckets also matching "
alshabibb0285992016-03-28 23:30:37 -0700501 + "in Device {} for group id 0x{}",
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700502 groupDesc.deviceId(),
Saurav Das0fd79d92016-03-07 10:58:36 -0800503 Integer.toHexString(groupDesc.givenGroupId()));
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700504 StoredGroupEntry group = new DefaultGroup(
alshabibb0285992016-03-28 23:30:37 -0700505 matchingExtraneousGroup.id(), groupDesc);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700506 // Insert the newly created group entry into key and id maps
507 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700508 put(new GroupStoreKeyMapKey(groupDesc.deviceId(),
509 groupDesc.appCookie()), group);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700510 // Ensure it also inserted into group id based table to
511 // avoid any chances of duplication in group id generation
512 getGroupIdTable(groupDesc.deviceId()).
alshabibb0285992016-03-28 23:30:37 -0700513 put(matchingExtraneousGroup.id(), group);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700514 addOrUpdateGroupEntry(matchingExtraneousGroup);
515 removeExtraneousGroupEntry(matchingExtraneousGroup);
516 return;
517 } else {
518 //Group buckets are not matching. Update group
519 //with user provided buckets.
Saurav Das0fd79d92016-03-07 10:58:36 -0800520 log.debug("storeGroupDescriptionInternal: Buckets are not "
alshabibb0285992016-03-28 23:30:37 -0700521 + "matching in Device {} for group id 0x{}",
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700522 groupDesc.deviceId(),
Saurav Das0fd79d92016-03-07 10:58:36 -0800523 Integer.toHexString(groupDesc.givenGroupId()));
524 StoredGroupEntry modifiedGroup = new DefaultGroup(
alshabibb0285992016-03-28 23:30:37 -0700525 matchingExtraneousGroup.id(), groupDesc);
Saurav Das0fd79d92016-03-07 10:58:36 -0800526 modifiedGroup.setState(GroupState.PENDING_UPDATE);
527 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700528 put(new GroupStoreKeyMapKey(groupDesc.deviceId(),
529 groupDesc.appCookie()), modifiedGroup);
Saurav Das0fd79d92016-03-07 10:58:36 -0800530 // Ensure it also inserted into group id based table to
531 // avoid any chances of duplication in group id generation
532 getGroupIdTable(groupDesc.deviceId()).
alshabibb0285992016-03-28 23:30:37 -0700533 put(matchingExtraneousGroup.id(), modifiedGroup);
Saurav Das0fd79d92016-03-07 10:58:36 -0800534 removeExtraneousGroupEntry(matchingExtraneousGroup);
535 log.debug("storeGroupDescriptionInternal: Triggering Group "
alshabibb0285992016-03-28 23:30:37 -0700536 + "UPDATE request for {} in device {}",
Saurav Das0fd79d92016-03-07 10:58:36 -0800537 matchingExtraneousGroup.id(),
538 groupDesc.deviceId());
539 notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_REQUESTED, modifiedGroup));
540 return;
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700541 }
542 }
543 } else {
544 //Check if there is an extraneous group with user provided buckets
545 matchingExtraneousGroup = getMatchingExtraneousGroupbyBuckets(
alshabibb0285992016-03-28 23:30:37 -0700546 groupDesc.deviceId(), groupDesc.buckets());
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700547 if (matchingExtraneousGroup != null) {
548 //Group is already existing with the same buckets.
549 //So reuse this group.
550 log.debug("storeGroupDescriptionInternal: Matching extraneous group found in Device {}",
551 groupDesc.deviceId());
552 //Create a group entry object
553 StoredGroupEntry group = new DefaultGroup(
alshabibb0285992016-03-28 23:30:37 -0700554 matchingExtraneousGroup.id(), groupDesc);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700555 // Insert the newly created group entry into key and id maps
556 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700557 put(new GroupStoreKeyMapKey(groupDesc.deviceId(),
558 groupDesc.appCookie()), group);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700559 // Ensure it also inserted into group id based table to
560 // avoid any chances of duplication in group id generation
561 getGroupIdTable(groupDesc.deviceId()).
alshabibb0285992016-03-28 23:30:37 -0700562 put(matchingExtraneousGroup.id(), group);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700563 addOrUpdateGroupEntry(matchingExtraneousGroup);
564 removeExtraneousGroupEntry(matchingExtraneousGroup);
565 return;
566 } else {
567 //TODO: Check if there are any empty groups that can be used here
568 log.debug("storeGroupDescriptionInternal: No matching extraneous groups found in Device {}",
569 groupDesc.deviceId());
570 }
571 }
572
Saurav Das100e3b82015-04-30 11:12:10 -0700573 GroupId id = null;
574 if (groupDesc.givenGroupId() == null) {
575 // Get a new group identifier
576 id = new DefaultGroupId(getFreeGroupIdValue(groupDesc.deviceId()));
577 } else {
Saurav Das8be4e3a2016-03-11 17:19:07 -0800578 // we need to use the identifier passed in by caller, but check if
579 // already used
580 Group existing = getGroup(groupDesc.deviceId(),
581 new DefaultGroupId(groupDesc.givenGroupId()));
582 if (existing != null) {
583 log.warn("Group already exists with the same id: 0x{} in dev:{} "
alshabibb0285992016-03-28 23:30:37 -0700584 + "but with different key: {} (request gkey: {})",
585 Integer.toHexString(groupDesc.givenGroupId()),
586 groupDesc.deviceId(),
587 existing.appCookie(),
588 groupDesc.appCookie());
Saurav Das8be4e3a2016-03-11 17:19:07 -0800589 return;
590 }
Saurav Das100e3b82015-04-30 11:12:10 -0700591 id = new DefaultGroupId(groupDesc.givenGroupId());
592 }
alshabib10580802015-02-18 18:30:33 -0800593 // Create a group entry object
594 StoredGroupEntry group = new DefaultGroup(id, groupDesc);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700595 // Insert the newly created group entry into key and id maps
596 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700597 put(new GroupStoreKeyMapKey(groupDesc.deviceId(),
598 groupDesc.appCookie()), group);
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700599 // Ensure it also inserted into group id based table to
600 // avoid any chances of duplication in group id generation
601 getGroupIdTable(groupDesc.deviceId()).
alshabibb0285992016-03-28 23:30:37 -0700602 put(id, group);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700603 log.debug("storeGroupDescriptionInternal: Processing Group ADD request for Id {} in device {}",
alshabibb0285992016-03-28 23:30:37 -0700604 id,
605 groupDesc.deviceId());
alshabib10580802015-02-18 18:30:33 -0800606 notifyDelegate(new GroupEvent(GroupEvent.Type.GROUP_ADD_REQUESTED,
607 group));
608 }
609
610 /**
611 * Updates the existing group entry with the information
612 * from group description.
613 *
alshabibb0285992016-03-28 23:30:37 -0700614 * @param deviceId the device ID
alshabib10580802015-02-18 18:30:33 -0800615 * @param oldAppCookie the current group key
alshabibb0285992016-03-28 23:30:37 -0700616 * @param type update type
617 * @param newBuckets group buckets for updates
alshabib10580802015-02-18 18:30:33 -0800618 * @param newAppCookie optional new group key
619 */
620 @Override
621 public void updateGroupDescription(DeviceId deviceId,
622 GroupKey oldAppCookie,
623 UpdateType type,
624 GroupBuckets newBuckets,
625 GroupKey newAppCookie) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700626 // Check if group update to be done by a remote instance
sangho52abe3a2015-05-05 14:13:34 -0700627 if (mastershipService.getMasterFor(deviceId) != null &&
628 mastershipService.getLocalRole(deviceId) != MastershipRole.MASTER) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700629 log.debug("updateGroupDescription: Device {} local role is not MASTER",
630 deviceId);
631 if (mastershipService.getMasterFor(deviceId) == null) {
632 log.error("No Master for device {}..."
alshabibb0285992016-03-28 23:30:37 -0700633 + "Can not perform update group operation",
634 deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700635 //TODO: Send Group operation failure event
636 return;
637 }
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700638 GroupStoreMessage groupOp = GroupStoreMessage.
639 createGroupUpdateRequestMsg(deviceId,
640 oldAppCookie,
641 type,
642 newBuckets,
643 newAppCookie);
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700644
Madan Jampani175e8fd2015-05-20 14:10:45 -0700645 clusterCommunicator.unicast(groupOp,
alshabibb0285992016-03-28 23:30:37 -0700646 GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST,
647 clusterMsgSerializer::serialize,
648 mastershipService.getMasterFor(deviceId)).whenComplete((result, error) -> {
649 if (error != null) {
650 log.warn("Failed to send request to master: {} to {}",
651 groupOp,
652 mastershipService.getMasterFor(deviceId), error);
653 }
654 //TODO: Send Group operation failure event
655 });
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700656 return;
657 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700658 log.debug("updateGroupDescription for device {} is getting handled locally",
659 deviceId);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700660 updateGroupDescriptionInternal(deviceId,
661 oldAppCookie,
662 type,
663 newBuckets,
664 newAppCookie);
665 }
666
667 private void updateGroupDescriptionInternal(DeviceId deviceId,
alshabibb0285992016-03-28 23:30:37 -0700668 GroupKey oldAppCookie,
669 UpdateType type,
670 GroupBuckets newBuckets,
671 GroupKey newAppCookie) {
alshabib10580802015-02-18 18:30:33 -0800672 // Check if a group is existing with the provided key
673 Group oldGroup = getGroup(deviceId, oldAppCookie);
674 if (oldGroup == null) {
Saurav Das8be4e3a2016-03-11 17:19:07 -0800675 log.warn("updateGroupDescriptionInternal: Group not found...strange. "
alshabibb0285992016-03-28 23:30:37 -0700676 + "GroupKey:{} DeviceId:{}", oldAppCookie, deviceId);
alshabib10580802015-02-18 18:30:33 -0800677 return;
678 }
679
680 List<GroupBucket> newBucketList = getUpdatedBucketList(oldGroup,
681 type,
682 newBuckets);
683 if (newBucketList != null) {
684 // Create a new group object from the old group
685 GroupBuckets updatedBuckets = new GroupBuckets(newBucketList);
686 GroupKey newCookie = (newAppCookie != null) ? newAppCookie : oldAppCookie;
687 GroupDescription updatedGroupDesc = new DefaultGroupDescription(
688 oldGroup.deviceId(),
689 oldGroup.type(),
690 updatedBuckets,
691 newCookie,
Saurav Das100e3b82015-04-30 11:12:10 -0700692 oldGroup.givenGroupId(),
alshabib10580802015-02-18 18:30:33 -0800693 oldGroup.appId());
694 StoredGroupEntry newGroup = new DefaultGroup(oldGroup.id(),
695 updatedGroupDesc);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700696 log.debug("updateGroupDescriptionInternal: group entry {} in device {} moving from {} to PENDING_UPDATE",
alshabibb0285992016-03-28 23:30:37 -0700697 oldGroup.id(),
698 oldGroup.deviceId(),
699 oldGroup.state());
alshabib10580802015-02-18 18:30:33 -0800700 newGroup.setState(GroupState.PENDING_UPDATE);
701 newGroup.setLife(oldGroup.life());
702 newGroup.setPackets(oldGroup.packets());
703 newGroup.setBytes(oldGroup.bytes());
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700704 //Update the group entry in groupkey based map.
705 //Update to groupid based map will happen in the
706 //groupkey based map update listener
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700707 log.debug("updateGroupDescriptionInternal with type {}: Group updated with buckets",
708 type);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700709 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700710 put(new GroupStoreKeyMapKey(newGroup.deviceId(),
711 newGroup.appCookie()), newGroup);
alshabib10580802015-02-18 18:30:33 -0800712 notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_REQUESTED, newGroup));
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700713 } else {
714 log.warn("updateGroupDescriptionInternal with type {}: No "
alshabibb0285992016-03-28 23:30:37 -0700715 + "change in the buckets in update", type);
alshabib10580802015-02-18 18:30:33 -0800716 }
717 }
718
719 private List<GroupBucket> getUpdatedBucketList(Group oldGroup,
720 UpdateType type,
721 GroupBuckets buckets) {
Victor Silvadf1eeae2016-08-12 15:28:57 -0300722 List<GroupBucket> oldBuckets = oldGroup.buckets().buckets();
723 List<GroupBucket> updatedBucketList = new ArrayList<>();
alshabib10580802015-02-18 18:30:33 -0800724 boolean groupDescUpdated = false;
725
726 if (type == UpdateType.ADD) {
Victor Silvadf1eeae2016-08-12 15:28:57 -0300727 List<GroupBucket> newBuckets = buckets.buckets();
728
729 // Add old buckets that will not be updated and check if any will be updated.
730 for (GroupBucket oldBucket : oldBuckets) {
731 int newBucketIndex = newBuckets.indexOf(oldBucket);
732
733 if (newBucketIndex != -1) {
734 GroupBucket newBucket = newBuckets.get(newBucketIndex);
735 if (!newBucket.hasSameParameters(oldBucket)) {
736 // Bucket will be updated
737 groupDescUpdated = true;
738 }
739 } else {
740 // Old bucket will remain the same - add it.
741 updatedBucketList.add(oldBucket);
alshabib10580802015-02-18 18:30:33 -0800742 }
743 }
Victor Silvadf1eeae2016-08-12 15:28:57 -0300744
745 // Add all new buckets
746 updatedBucketList.addAll(newBuckets);
747 if (!oldBuckets.containsAll(newBuckets)) {
748 groupDescUpdated = true;
749 }
750
alshabib10580802015-02-18 18:30:33 -0800751 } else if (type == UpdateType.REMOVE) {
Victor Silvadf1eeae2016-08-12 15:28:57 -0300752 List<GroupBucket> bucketsToRemove = buckets.buckets();
753
754 // Check which old buckets should remain
755 for (GroupBucket oldBucket : oldBuckets) {
756 if (!bucketsToRemove.contains(oldBucket)) {
757 updatedBucketList.add(oldBucket);
758 } else {
alshabib10580802015-02-18 18:30:33 -0800759 groupDescUpdated = true;
760 }
761 }
762 }
763
764 if (groupDescUpdated) {
Victor Silvadf1eeae2016-08-12 15:28:57 -0300765 return updatedBucketList;
alshabib10580802015-02-18 18:30:33 -0800766 } else {
767 return null;
768 }
769 }
770
771 /**
772 * Triggers deleting the existing group entry.
773 *
alshabibb0285992016-03-28 23:30:37 -0700774 * @param deviceId the device ID
alshabib10580802015-02-18 18:30:33 -0800775 * @param appCookie the group key
776 */
777 @Override
778 public void deleteGroupDescription(DeviceId deviceId,
779 GroupKey appCookie) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700780 // Check if group to be deleted by a remote instance
781 if (mastershipService.
782 getLocalRole(deviceId) != MastershipRole.MASTER) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700783 log.debug("deleteGroupDescription: Device {} local role is not MASTER",
784 deviceId);
785 if (mastershipService.getMasterFor(deviceId) == null) {
786 log.error("No Master for device {}..."
alshabibb0285992016-03-28 23:30:37 -0700787 + "Can not perform delete group operation",
788 deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700789 //TODO: Send Group operation failure event
790 return;
791 }
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700792 GroupStoreMessage groupOp = GroupStoreMessage.
793 createGroupDeleteRequestMsg(deviceId,
794 appCookie);
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700795
Madan Jampani175e8fd2015-05-20 14:10:45 -0700796 clusterCommunicator.unicast(groupOp,
alshabibb0285992016-03-28 23:30:37 -0700797 GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST,
798 clusterMsgSerializer::serialize,
799 mastershipService.getMasterFor(deviceId)).whenComplete((result, error) -> {
800 if (error != null) {
801 log.warn("Failed to send request to master: {} to {}",
802 groupOp,
803 mastershipService.getMasterFor(deviceId), error);
804 }
805 //TODO: Send Group operation failure event
806 });
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700807 return;
808 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700809 log.debug("deleteGroupDescription in device {} is getting handled locally",
810 deviceId);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700811 deleteGroupDescriptionInternal(deviceId, appCookie);
812 }
813
814 private void deleteGroupDescriptionInternal(DeviceId deviceId,
815 GroupKey appCookie) {
alshabib10580802015-02-18 18:30:33 -0800816 // Check if a group is existing with the provided key
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700817 StoredGroupEntry existing = getStoredGroupEntry(deviceId, appCookie);
alshabib10580802015-02-18 18:30:33 -0800818 if (existing == null) {
819 return;
820 }
821
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700822 log.debug("deleteGroupDescriptionInternal: group entry {} in device {} moving from {} to PENDING_DELETE",
alshabibb0285992016-03-28 23:30:37 -0700823 existing.id(),
824 existing.deviceId(),
825 existing.state());
alshabib10580802015-02-18 18:30:33 -0800826 synchronized (existing) {
827 existing.setState(GroupState.PENDING_DELETE);
Saurav Das80980c72016-03-23 11:22:49 -0700828 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700829 put(new GroupStoreKeyMapKey(existing.deviceId(), existing.appCookie()),
830 existing);
alshabib10580802015-02-18 18:30:33 -0800831 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700832 log.debug("deleteGroupDescriptionInternal: in device {} issuing GROUP_REMOVE_REQUESTED",
833 deviceId);
alshabib10580802015-02-18 18:30:33 -0800834 notifyDelegate(new GroupEvent(Type.GROUP_REMOVE_REQUESTED, existing));
835 }
836
837 /**
838 * Stores a new group entry, or updates an existing entry.
839 *
840 * @param group group entry
841 */
842 @Override
843 public void addOrUpdateGroupEntry(Group group) {
844 // check if this new entry is an update to an existing entry
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700845 StoredGroupEntry existing = getStoredGroupEntry(group.deviceId(),
846 group.id());
alshabib10580802015-02-18 18:30:33 -0800847 GroupEvent event = null;
848
849 if (existing != null) {
Saurav Das0fd79d92016-03-07 10:58:36 -0800850 log.trace("addOrUpdateGroupEntry: updating group entry {} in device {}",
alshabibb0285992016-03-28 23:30:37 -0700851 group.id(),
852 group.deviceId());
alshabib10580802015-02-18 18:30:33 -0800853 synchronized (existing) {
alshabibb0285992016-03-28 23:30:37 -0700854 for (GroupBucket bucket : group.buckets().buckets()) {
Sho SHIMIZU30d639b2015-05-05 09:30:35 -0700855 Optional<GroupBucket> matchingBucket =
Srikanth Vavilapalli10e75cd2015-04-13 16:21:24 -0700856 existing.buckets().buckets()
alshabibb0285992016-03-28 23:30:37 -0700857 .stream()
858 .filter((existingBucket) -> (existingBucket.equals(bucket)))
859 .findFirst();
Srikanth Vavilapalli10e75cd2015-04-13 16:21:24 -0700860 if (matchingBucket.isPresent()) {
861 ((StoredGroupBucketEntry) matchingBucket.
862 get()).setPackets(bucket.packets());
863 ((StoredGroupBucketEntry) matchingBucket.
864 get()).setBytes(bucket.bytes());
865 } else {
866 log.warn("addOrUpdateGroupEntry: No matching "
alshabibb0285992016-03-28 23:30:37 -0700867 + "buckets to update stats");
Srikanth Vavilapalli10e75cd2015-04-13 16:21:24 -0700868 }
869 }
alshabib10580802015-02-18 18:30:33 -0800870 existing.setLife(group.life());
871 existing.setPackets(group.packets());
872 existing.setBytes(group.bytes());
alshabibb0285992016-03-28 23:30:37 -0700873 existing.setReferenceCount(group.referenceCount());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700874 if ((existing.state() == GroupState.PENDING_ADD) ||
alshabibb0285992016-03-28 23:30:37 -0700875 (existing.state() == GroupState.PENDING_ADD_RETRY)) {
Saurav Das0fd79d92016-03-07 10:58:36 -0800876 log.trace("addOrUpdateGroupEntry: group entry {} in device {} moving from {} to ADDED",
alshabibb0285992016-03-28 23:30:37 -0700877 existing.id(),
878 existing.deviceId(),
879 existing.state());
alshabib10580802015-02-18 18:30:33 -0800880 existing.setState(GroupState.ADDED);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700881 existing.setIsGroupStateAddedFirstTime(true);
alshabib10580802015-02-18 18:30:33 -0800882 event = new GroupEvent(Type.GROUP_ADDED, existing);
883 } else {
Saurav Das0fd79d92016-03-07 10:58:36 -0800884 log.trace("addOrUpdateGroupEntry: group entry {} in device {} moving from {} to ADDED",
alshabibb0285992016-03-28 23:30:37 -0700885 existing.id(),
886 existing.deviceId(),
887 GroupState.PENDING_UPDATE);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700888 existing.setState(GroupState.ADDED);
889 existing.setIsGroupStateAddedFirstTime(false);
alshabib10580802015-02-18 18:30:33 -0800890 event = new GroupEvent(Type.GROUP_UPDATED, existing);
891 }
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700892 //Re-PUT map entries to trigger map update events
893 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700894 put(new GroupStoreKeyMapKey(existing.deviceId(),
895 existing.appCookie()), existing);
alshabib10580802015-02-18 18:30:33 -0800896 }
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700897 } else {
898 log.warn("addOrUpdateGroupEntry: Group update "
alshabibb0285992016-03-28 23:30:37 -0700899 + "happening for a non-existing entry in the map");
alshabib10580802015-02-18 18:30:33 -0800900 }
901
902 if (event != null) {
903 notifyDelegate(event);
904 }
905 }
906
907 /**
908 * Removes the group entry from store.
909 *
910 * @param group group entry
911 */
912 @Override
913 public void removeGroupEntry(Group group) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700914 StoredGroupEntry existing = getStoredGroupEntry(group.deviceId(),
915 group.id());
alshabib10580802015-02-18 18:30:33 -0800916
917 if (existing != null) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700918 log.debug("removeGroupEntry: removing group entry {} in device {}",
alshabibb0285992016-03-28 23:30:37 -0700919 group.id(),
920 group.deviceId());
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700921 //Removal from groupid based map will happen in the
922 //map update listener
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700923 getGroupStoreKeyMap().remove(new GroupStoreKeyMapKey(existing.deviceId(),
924 existing.appCookie()));
alshabib10580802015-02-18 18:30:33 -0800925 notifyDelegate(new GroupEvent(Type.GROUP_REMOVED, existing));
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700926 } else {
927 log.warn("removeGroupEntry for {} in device{} is "
alshabibb0285992016-03-28 23:30:37 -0700928 + "not existing in our maps",
929 group.id(),
930 group.deviceId());
alshabib10580802015-02-18 18:30:33 -0800931 }
932 }
933
Victor Silva4e8b7832016-08-17 17:11:19 -0300934 private void purgeGroupEntries(Set<Entry<GroupStoreKeyMapKey, StoredGroupEntry>> entries) {
935 entries.forEach(entry -> {
936 groupStoreEntriesByKey.remove(entry.getKey());
937 });
938 }
939
alshabib10580802015-02-18 18:30:33 -0800940 @Override
Charles Chan0c7c43b2016-01-14 17:39:20 -0800941 public void purgeGroupEntry(DeviceId deviceId) {
Victor Silva4e8b7832016-08-17 17:11:19 -0300942 Set<Entry<GroupStoreKeyMapKey, StoredGroupEntry>> entriesPendingRemove =
Charles Chan0c7c43b2016-01-14 17:39:20 -0800943 new HashSet<>();
944
Madan Jampani0b847532016-03-03 13:44:15 -0800945 getGroupStoreKeyMap().entrySet().stream()
Charles Chan0c7c43b2016-01-14 17:39:20 -0800946 .filter(entry -> entry.getKey().deviceId().equals(deviceId))
Victor Silva4e8b7832016-08-17 17:11:19 -0300947 .forEach(entriesPendingRemove::add);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800948
Victor Silva4e8b7832016-08-17 17:11:19 -0300949 purgeGroupEntries(entriesPendingRemove);
950 }
951
952 @Override
953 public void purgeGroupEntries() {
954 purgeGroupEntries(getGroupStoreKeyMap().entrySet());
Charles Chan0c7c43b2016-01-14 17:39:20 -0800955 }
956
957 @Override
alshabib10580802015-02-18 18:30:33 -0800958 public void deviceInitialAuditCompleted(DeviceId deviceId,
959 boolean completed) {
960 synchronized (deviceAuditStatus) {
961 if (completed) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700962 log.debug("AUDIT completed for device {}",
963 deviceId);
alshabib10580802015-02-18 18:30:33 -0800964 deviceAuditStatus.put(deviceId, true);
965 // Execute all pending group requests
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700966 List<StoredGroupEntry> pendingGroupRequests =
967 getPendingGroupKeyTable().values()
alshabibb0285992016-03-28 23:30:37 -0700968 .stream()
969 .filter(g -> g.deviceId().equals(deviceId))
970 .collect(Collectors.toList());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700971 log.debug("processing pending group add requests for device {} and number of pending requests {}",
alshabibb0285992016-03-28 23:30:37 -0700972 deviceId,
973 pendingGroupRequests.size());
974 for (Group group : pendingGroupRequests) {
alshabib10580802015-02-18 18:30:33 -0800975 GroupDescription tmp = new DefaultGroupDescription(
976 group.deviceId(),
977 group.type(),
978 group.buckets(),
979 group.appCookie(),
Saurav Das100e3b82015-04-30 11:12:10 -0700980 group.givenGroupId(),
alshabib10580802015-02-18 18:30:33 -0800981 group.appId());
982 storeGroupDescriptionInternal(tmp);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700983 getPendingGroupKeyTable().
alshabibb0285992016-03-28 23:30:37 -0700984 remove(new GroupStoreKeyMapKey(deviceId, group.appCookie()));
alshabib10580802015-02-18 18:30:33 -0800985 }
alshabib10580802015-02-18 18:30:33 -0800986 } else {
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700987 Boolean audited = deviceAuditStatus.get(deviceId);
988 if (audited != null && audited) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700989 log.debug("Clearing AUDIT status for device {}", deviceId);
alshabib10580802015-02-18 18:30:33 -0800990 deviceAuditStatus.put(deviceId, false);
991 }
992 }
993 }
994 }
995
996 @Override
997 public boolean deviceInitialAuditStatus(DeviceId deviceId) {
998 synchronized (deviceAuditStatus) {
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700999 Boolean audited = deviceAuditStatus.get(deviceId);
1000 return audited != null && audited;
alshabib10580802015-02-18 18:30:33 -08001001 }
1002 }
1003
1004 @Override
1005 public void groupOperationFailed(DeviceId deviceId, GroupOperation operation) {
1006
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001007 StoredGroupEntry existing = getStoredGroupEntry(deviceId,
1008 operation.groupId());
alshabib10580802015-02-18 18:30:33 -08001009
1010 if (existing == null) {
1011 log.warn("No group entry with ID {} found ", operation.groupId());
1012 return;
1013 }
1014
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001015 log.warn("groupOperationFailed: group operation {} failed"
alshabibb0285992016-03-28 23:30:37 -07001016 + "for group {} in device {} with code {}",
1017 operation.opType(),
1018 existing.id(),
1019 existing.deviceId(),
1020 operation.failureCode());
Saurav Das0fd79d92016-03-07 10:58:36 -08001021 if (operation.failureCode() == GroupOperation.GroupMsgErrorCode.GROUP_EXISTS) {
1022 log.warn("Current extraneous groups in device:{} are: {}",
1023 deviceId,
1024 getExtraneousGroups(deviceId));
Saurav Das8be4e3a2016-03-11 17:19:07 -08001025 if (operation.buckets().equals(existing.buckets())) {
1026 if (existing.state() == GroupState.PENDING_ADD) {
1027 log.info("GROUP_EXISTS: GroupID and Buckets match for group in pending "
alshabibb0285992016-03-28 23:30:37 -07001028 + "add state - moving to ADDED for group {} in device {}",
1029 existing.id(), deviceId);
Saurav Das8be4e3a2016-03-11 17:19:07 -08001030 addOrUpdateGroupEntry(existing);
1031 return;
1032 } else {
1033 log.warn("GROUP EXISTS: Group ID matched but buckets did not. "
alshabibb0285992016-03-28 23:30:37 -07001034 + "Operation: {} Existing: {}", operation.buckets(),
1035 existing.buckets());
Saurav Das8be4e3a2016-03-11 17:19:07 -08001036 }
1037 }
Saurav Das0fd79d92016-03-07 10:58:36 -08001038 }
alshabib10580802015-02-18 18:30:33 -08001039 switch (operation.opType()) {
1040 case ADD:
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001041 if (existing.state() == GroupState.PENDING_ADD) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001042 notifyDelegate(new GroupEvent(Type.GROUP_ADD_FAILED, existing));
1043 log.warn("groupOperationFailed: cleaningup "
alshabibb0285992016-03-28 23:30:37 -07001044 + "group {} from store in device {}....",
1045 existing.id(),
1046 existing.deviceId());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001047 //Removal from groupid based map will happen in the
1048 //map update listener
1049 getGroupStoreKeyMap().remove(new GroupStoreKeyMapKey(existing.deviceId(),
1050 existing.appCookie()));
1051 }
alshabib10580802015-02-18 18:30:33 -08001052 break;
1053 case MODIFY:
1054 notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_FAILED, existing));
1055 break;
1056 case DELETE:
1057 notifyDelegate(new GroupEvent(Type.GROUP_REMOVE_FAILED, existing));
1058 break;
1059 default:
1060 log.warn("Unknown group operation type {}", operation.opType());
1061 }
alshabib10580802015-02-18 18:30:33 -08001062 }
1063
1064 @Override
1065 public void addOrUpdateExtraneousGroupEntry(Group group) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001066 log.debug("add/update extraneous group entry {} in device {}",
alshabibb0285992016-03-28 23:30:37 -07001067 group.id(),
1068 group.deviceId());
alshabib10580802015-02-18 18:30:33 -08001069 ConcurrentMap<GroupId, Group> extraneousIdTable =
1070 getExtraneousGroupIdTable(group.deviceId());
1071 extraneousIdTable.put(group.id(), group);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -07001072 // Don't remove the extraneous groups, instead re-use it when
1073 // a group request comes with the same set of buckets
alshabib10580802015-02-18 18:30:33 -08001074 }
1075
1076 @Override
1077 public void removeExtraneousGroupEntry(Group group) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001078 log.debug("remove extraneous group entry {} of device {} from store",
alshabibb0285992016-03-28 23:30:37 -07001079 group.id(),
1080 group.deviceId());
alshabib10580802015-02-18 18:30:33 -08001081 ConcurrentMap<GroupId, Group> extraneousIdTable =
1082 getExtraneousGroupIdTable(group.deviceId());
1083 extraneousIdTable.remove(group.id());
1084 }
1085
1086 @Override
1087 public Iterable<Group> getExtraneousGroups(DeviceId deviceId) {
1088 // flatten and make iterator unmodifiable
1089 return FluentIterable.from(
1090 getExtraneousGroupIdTable(deviceId).values());
1091 }
1092
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001093 /**
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -07001094 * Map handler to receive any events when the group key map is updated.
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001095 */
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -07001096 private class GroupStoreKeyMapListener implements
Madan Jampani0b847532016-03-03 13:44:15 -08001097 MapEventListener<GroupStoreKeyMapKey, StoredGroupEntry> {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001098
1099 @Override
Madan Jampani0b847532016-03-03 13:44:15 -08001100 public void event(MapEvent<GroupStoreKeyMapKey, StoredGroupEntry> mapEvent) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001101 GroupEvent groupEvent = null;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001102 GroupStoreKeyMapKey key = mapEvent.key();
Madan Jampani0b847532016-03-03 13:44:15 -08001103 StoredGroupEntry group = Versioned.valueOrNull(mapEvent.newValue());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001104 if ((key == null) && (group == null)) {
1105 log.error("GroupStoreKeyMapListener: Received "
alshabibb0285992016-03-28 23:30:37 -07001106 + "event {} with null entry", mapEvent.type());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001107 return;
1108 } else if (group == null) {
1109 group = getGroupIdTable(key.deviceId()).values()
1110 .stream()
1111 .filter((storedGroup) -> (storedGroup.appCookie().equals(key.appCookie)))
Yuta HIGUCHI6e5f4702016-11-21 11:42:11 -08001112 .findFirst().orElse(null);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001113 if (group == null) {
1114 log.error("GroupStoreKeyMapListener: Received "
alshabibb0285992016-03-28 23:30:37 -07001115 + "event {} with null entry... can not process", mapEvent.type());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001116 return;
1117 }
1118 }
1119 log.trace("received groupid map event {} for id {} in device {}",
1120 mapEvent.type(),
1121 group.id(),
jaegonkim68e080c2016-12-01 22:31:01 +09001122 (key != null ? key.deviceId() : null));
Madan Jampani0b847532016-03-03 13:44:15 -08001123 if (mapEvent.type() == MapEvent.Type.INSERT || mapEvent.type() == MapEvent.Type.UPDATE) {
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -07001124 // Update the group ID table
1125 getGroupIdTable(group.deviceId()).put(group.id(), group);
Madan Jampani0b847532016-03-03 13:44:15 -08001126 StoredGroupEntry value = Versioned.valueOrNull(mapEvent.newValue());
1127 if (value.state() == Group.GroupState.ADDED) {
1128 if (value.isGroupStateAddedFirstTime()) {
1129 groupEvent = new GroupEvent(Type.GROUP_ADDED, value);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001130 log.trace("Received first time GROUP_ADDED state update for id {} in device {}",
alshabibb0285992016-03-28 23:30:37 -07001131 group.id(),
1132 group.deviceId());
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001133 } else {
Madan Jampani0b847532016-03-03 13:44:15 -08001134 groupEvent = new GroupEvent(Type.GROUP_UPDATED, value);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001135 log.trace("Received following GROUP_ADDED state update for id {} in device {}",
alshabibb0285992016-03-28 23:30:37 -07001136 group.id(),
1137 group.deviceId());
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001138 }
1139 }
Madan Jampani0b847532016-03-03 13:44:15 -08001140 } else if (mapEvent.type() == MapEvent.Type.REMOVE) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001141 groupEvent = new GroupEvent(Type.GROUP_REMOVED, group);
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -07001142 // Remove the entry from the group ID table
1143 getGroupIdTable(group.deviceId()).remove(group.id(), group);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001144 }
1145
1146 if (groupEvent != null) {
1147 notifyDelegate(groupEvent);
1148 }
1149 }
1150 }
Madan Jampani01e05fb2015-08-13 13:29:36 -07001151
helenyrwua1c41152016-08-18 16:16:14 -07001152 private void processGroupMessage(GroupStoreMessage message) {
1153 if (message.type() == GroupStoreMessage.Type.FAILOVER) {
1154 // FIXME: groupStoreEntriesByKey inaccessible here
1155 getGroupIdTable(message.deviceId()).values()
1156 .stream()
1157 .filter((storedGroup) -> (storedGroup.appCookie().equals(message.appCookie())))
1158 .findFirst().ifPresent(group -> notifyDelegate(new GroupEvent(Type.GROUP_BUCKET_FAILOVER, group)));
1159 }
1160 }
1161
Madan Jampani01e05fb2015-08-13 13:29:36 -07001162 private void process(GroupStoreMessage groupOp) {
1163 log.debug("Received remote group operation {} request for device {}",
alshabibb0285992016-03-28 23:30:37 -07001164 groupOp.type(),
1165 groupOp.deviceId());
1166 if (!mastershipService.isLocalMaster(groupOp.deviceId())) {
1167 log.warn("This node is not MASTER for device {}", groupOp.deviceId());
1168 return;
1169 }
1170 if (groupOp.type() == GroupStoreMessage.Type.ADD) {
1171 storeGroupDescriptionInternal(groupOp.groupDesc());
1172 } else if (groupOp.type() == GroupStoreMessage.Type.UPDATE) {
1173 updateGroupDescriptionInternal(groupOp.deviceId(),
1174 groupOp.appCookie(),
1175 groupOp.updateType(),
1176 groupOp.updateBuckets(),
1177 groupOp.newAppCookie());
1178 } else if (groupOp.type() == GroupStoreMessage.Type.DELETE) {
1179 deleteGroupDescriptionInternal(groupOp.deviceId(),
1180 groupOp.appCookie());
1181 }
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001182 }
1183
1184 /**
1185 * Flattened map key to be used to store group entries.
1186 */
Ray Milkeyb3c5ce22015-08-10 09:07:36 -07001187 protected static class GroupStoreMapKey {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001188 private final DeviceId deviceId;
1189
1190 public GroupStoreMapKey(DeviceId deviceId) {
1191 this.deviceId = deviceId;
1192 }
1193
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001194 public DeviceId deviceId() {
1195 return deviceId;
1196 }
1197
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001198 @Override
1199 public boolean equals(Object o) {
1200 if (this == o) {
1201 return true;
1202 }
1203 if (!(o instanceof GroupStoreMapKey)) {
1204 return false;
1205 }
1206 GroupStoreMapKey that = (GroupStoreMapKey) o;
1207 return this.deviceId.equals(that.deviceId);
1208 }
1209
1210 @Override
1211 public int hashCode() {
1212 int result = 17;
1213
1214 result = 31 * result + Objects.hash(this.deviceId);
1215
1216 return result;
1217 }
1218 }
1219
Ray Milkeyb3c5ce22015-08-10 09:07:36 -07001220 protected static class GroupStoreKeyMapKey extends GroupStoreMapKey {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001221 private final GroupKey appCookie;
alshabibb0285992016-03-28 23:30:37 -07001222
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001223 public GroupStoreKeyMapKey(DeviceId deviceId,
1224 GroupKey appCookie) {
1225 super(deviceId);
1226 this.appCookie = appCookie;
1227 }
1228
1229 @Override
1230 public boolean equals(Object o) {
1231 if (this == o) {
1232 return true;
1233 }
1234 if (!(o instanceof GroupStoreKeyMapKey)) {
1235 return false;
1236 }
1237 GroupStoreKeyMapKey that = (GroupStoreKeyMapKey) o;
1238 return (super.equals(that) &&
1239 this.appCookie.equals(that.appCookie));
1240 }
1241
1242 @Override
1243 public int hashCode() {
1244 int result = 17;
1245
1246 result = 31 * result + super.hashCode() + Objects.hash(this.appCookie);
1247
1248 return result;
1249 }
1250 }
1251
Ray Milkeyb3c5ce22015-08-10 09:07:36 -07001252 protected static class GroupStoreIdMapKey extends GroupStoreMapKey {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001253 private final GroupId groupId;
alshabibb0285992016-03-28 23:30:37 -07001254
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001255 public GroupStoreIdMapKey(DeviceId deviceId,
1256 GroupId groupId) {
1257 super(deviceId);
1258 this.groupId = groupId;
1259 }
1260
1261 @Override
1262 public boolean equals(Object o) {
1263 if (this == o) {
1264 return true;
1265 }
1266 if (!(o instanceof GroupStoreIdMapKey)) {
1267 return false;
1268 }
1269 GroupStoreIdMapKey that = (GroupStoreIdMapKey) o;
1270 return (super.equals(that) &&
1271 this.groupId.equals(that.groupId));
1272 }
1273
1274 @Override
1275 public int hashCode() {
1276 int result = 17;
1277
1278 result = 31 * result + super.hashCode() + Objects.hash(this.groupId);
1279
1280 return result;
1281 }
1282 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001283
1284 @Override
1285 public void pushGroupMetrics(DeviceId deviceId,
1286 Collection<Group> groupEntries) {
1287 boolean deviceInitialAuditStatus =
1288 deviceInitialAuditStatus(deviceId);
1289 Set<Group> southboundGroupEntries =
1290 Sets.newHashSet(groupEntries);
1291 Set<StoredGroupEntry> storedGroupEntries =
1292 Sets.newHashSet(getStoredGroups(deviceId));
1293 Set<Group> extraneousStoredEntries =
1294 Sets.newHashSet(getExtraneousGroups(deviceId));
1295
Sho SHIMIZU695bac62016-08-15 12:41:59 -07001296 if (log.isTraceEnabled()) {
1297 log.trace("pushGroupMetrics: Displaying all ({}) southboundGroupEntries for device {}",
1298 southboundGroupEntries.size(),
1299 deviceId);
1300 for (Group group : southboundGroupEntries) {
1301 log.trace("Group {} in device {}", group, deviceId);
1302 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001303
Sho SHIMIZU695bac62016-08-15 12:41:59 -07001304 log.trace("Displaying all ({}) stored group entries for device {}",
1305 storedGroupEntries.size(),
1306 deviceId);
1307 for (StoredGroupEntry group : storedGroupEntries) {
1308 log.trace("Stored Group {} for device {}", group, deviceId);
1309 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001310 }
1311
alshabibb0285992016-03-28 23:30:37 -07001312 garbageCollect(deviceId, southboundGroupEntries, storedGroupEntries);
1313
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001314 for (Iterator<Group> it2 = southboundGroupEntries.iterator(); it2.hasNext();) {
1315 Group group = it2.next();
1316 if (storedGroupEntries.remove(group)) {
1317 // we both have the group, let's update some info then.
1318 log.trace("Group AUDIT: group {} exists in both planes for device {}",
alshabibb0285992016-03-28 23:30:37 -07001319 group.id(), deviceId);
1320
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001321 groupAdded(group);
1322 it2.remove();
1323 }
1324 }
1325 for (Group group : southboundGroupEntries) {
1326 if (getGroup(group.deviceId(), group.id()) != null) {
1327 // There is a group existing with the same id
1328 // It is possible that group update is
1329 // in progress while we got a stale info from switch
1330 if (!storedGroupEntries.remove(getGroup(
alshabibb0285992016-03-28 23:30:37 -07001331 group.deviceId(), group.id()))) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001332 log.warn("Group AUDIT: Inconsistent state:"
alshabibb0285992016-03-28 23:30:37 -07001333 + "Group exists in ID based table while "
1334 + "not present in key based table");
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001335 }
1336 } else {
1337 // there are groups in the switch that aren't in the store
1338 log.debug("Group AUDIT: extraneous group {} exists in data plane for device {}",
alshabibb0285992016-03-28 23:30:37 -07001339 group.id(), deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001340 extraneousStoredEntries.remove(group);
1341 extraneousGroup(group);
1342 }
1343 }
1344 for (Group group : storedGroupEntries) {
1345 // there are groups in the store that aren't in the switch
1346 log.debug("Group AUDIT: group {} missing in data plane for device {}",
alshabibb0285992016-03-28 23:30:37 -07001347 group.id(), deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001348 groupMissing(group);
1349 }
1350 for (Group group : extraneousStoredEntries) {
1351 // there are groups in the extraneous store that
1352 // aren't in the switch
Saurav Das0fd79d92016-03-07 10:58:36 -08001353 log.debug("Group AUDIT: clearing extraneous group {} from store for device {}",
alshabibb0285992016-03-28 23:30:37 -07001354 group.id(), deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001355 removeExtraneousGroupEntry(group);
1356 }
1357
1358 if (!deviceInitialAuditStatus) {
Saurav Das0fd79d92016-03-07 10:58:36 -08001359 log.info("Group AUDIT: Setting device {} initial AUDIT completed",
alshabibb0285992016-03-28 23:30:37 -07001360 deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001361 deviceInitialAuditCompleted(deviceId, true);
1362 }
1363 }
1364
helenyrwu89470f12016-08-12 13:18:10 -07001365 @Override
1366 public void notifyOfFailovers(Collection<Group> failoverGroups) {
helenyrwu89470f12016-08-12 13:18:10 -07001367 failoverGroups.forEach(group -> {
1368 if (group.type() == Group.Type.FAILOVER) {
helenyrwua1c41152016-08-18 16:16:14 -07001369 groupTopic.publish(GroupStoreMessage.createGroupFailoverMsg(
1370 group.deviceId(), group));
helenyrwu89470f12016-08-12 13:18:10 -07001371 }
1372 });
helenyrwu89470f12016-08-12 13:18:10 -07001373 }
1374
alshabibb0285992016-03-28 23:30:37 -07001375 private void garbageCollect(DeviceId deviceId,
1376 Set<Group> southboundGroupEntries,
1377 Set<StoredGroupEntry> storedGroupEntries) {
1378 if (!garbageCollect) {
1379 return;
1380 }
1381
1382 Iterator<StoredGroupEntry> it = storedGroupEntries.iterator();
1383 while (it.hasNext()) {
1384 StoredGroupEntry group = it.next();
1385 if (group.state() != GroupState.PENDING_DELETE && checkGroupRefCount(group)) {
1386 log.debug("Garbage collecting group {} on {}", group, deviceId);
1387 deleteGroupDescription(deviceId, group.appCookie());
1388 southboundGroupEntries.remove(group);
1389 it.remove();
1390 }
1391 }
1392 }
1393
1394 private boolean checkGroupRefCount(Group group) {
1395 return (group.referenceCount() == 0 && group.age() >= gcThresh);
1396 }
1397
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001398 private void groupMissing(Group group) {
1399 switch (group.state()) {
1400 case PENDING_DELETE:
1401 log.debug("Group {} delete confirmation from device {}",
1402 group, group.deviceId());
1403 removeGroupEntry(group);
1404 break;
1405 case ADDED:
1406 case PENDING_ADD:
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001407 case PENDING_ADD_RETRY:
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001408 case PENDING_UPDATE:
1409 log.debug("Group {} is in store but not on device {}",
1410 group, group.deviceId());
1411 StoredGroupEntry existing =
1412 getStoredGroupEntry(group.deviceId(), group.id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001413 log.debug("groupMissing: group entry {} in device {} moving from {} to PENDING_ADD_RETRY",
alshabibb0285992016-03-28 23:30:37 -07001414 existing.id(),
1415 existing.deviceId(),
1416 existing.state());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001417 existing.setState(Group.GroupState.PENDING_ADD_RETRY);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001418 //Re-PUT map entries to trigger map update events
1419 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -07001420 put(new GroupStoreKeyMapKey(existing.deviceId(),
1421 existing.appCookie()), existing);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001422 notifyDelegate(new GroupEvent(GroupEvent.Type.GROUP_ADD_REQUESTED,
1423 group));
1424 break;
1425 default:
1426 log.debug("Group {} has not been installed.", group);
1427 break;
1428 }
1429 }
1430
1431 private void extraneousGroup(Group group) {
Saurav Das0fd79d92016-03-07 10:58:36 -08001432 log.trace("Group {} is on device {} but not in store.",
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001433 group, group.deviceId());
1434 addOrUpdateExtraneousGroupEntry(group);
1435 }
1436
1437 private void groupAdded(Group group) {
1438 log.trace("Group {} Added or Updated in device {}",
1439 group, group.deviceId());
1440 addOrUpdateGroupEntry(group);
1441 }
alshabib10580802015-02-18 18:30:33 -08001442}