blob: df8a99c6ecaae5dbd841b1503a04dd5ef44291d0 [file] [log] [blame]
alshabib10580802015-02-18 18:30:33 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
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.GroupId;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070035import org.onosproject.mastership.MastershipService;
alshabib10580802015-02-18 18:30:33 -080036import org.onosproject.net.DeviceId;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070037import org.onosproject.net.MastershipRole;
alshabib10580802015-02-18 18:30:33 -080038import org.onosproject.net.group.DefaultGroup;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070039import org.onosproject.net.group.DefaultGroupBucket;
alshabib10580802015-02-18 18:30:33 -080040import org.onosproject.net.group.DefaultGroupDescription;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070041import org.onosproject.net.group.DefaultGroupKey;
alshabib10580802015-02-18 18:30:33 -080042import org.onosproject.net.group.Group;
43import org.onosproject.net.group.Group.GroupState;
44import org.onosproject.net.group.GroupBucket;
45import org.onosproject.net.group.GroupBuckets;
46import org.onosproject.net.group.GroupDescription;
47import org.onosproject.net.group.GroupEvent;
48import org.onosproject.net.group.GroupEvent.Type;
49import org.onosproject.net.group.GroupKey;
50import org.onosproject.net.group.GroupOperation;
51import org.onosproject.net.group.GroupStore;
52import org.onosproject.net.group.GroupStoreDelegate;
Srikanth Vavilapalli10e75cd2015-04-13 16:21:24 -070053import org.onosproject.net.group.StoredGroupBucketEntry;
alshabib10580802015-02-18 18:30:33 -080054import org.onosproject.net.group.StoredGroupEntry;
55import org.onosproject.store.AbstractStore;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070056import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -070057import org.onosproject.store.serializers.KryoNamespaces;
Madan Jampani0b847532016-03-03 13:44:15 -080058import org.onosproject.store.service.ConsistentMap;
59import org.onosproject.store.service.MapEvent;
60import org.onosproject.store.service.MapEventListener;
alshabibb0285992016-03-28 23:30:37 -070061import org.onosproject.store.service.MultiValuedTimestamp;
Madan Jampani0b847532016-03-03 13:44:15 -080062import org.onosproject.store.service.Serializer;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070063import org.onosproject.store.service.StorageService;
helenyrwua1c41152016-08-18 16:16:14 -070064import org.onosproject.store.service.Topic;
Madan Jampani0b847532016-03-03 13:44:15 -080065import org.onosproject.store.service.Versioned;
Kavitha Alagesanc884c3ef2017-01-19 12:32:26 +053066import org.onosproject.store.service.DistributedPrimitive.Status;
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;
Kavitha Alagesanc884c3ef2017-01-19 12:32:26 +053088import java.util.concurrent.ScheduledExecutorService;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070089import java.util.concurrent.atomic.AtomicInteger;
Kavitha Alagesanc884c3ef2017-01-19 12:32:26 +053090import java.util.function.Consumer;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070091import java.util.stream.Collectors;
92
alshabibb0285992016-03-28 23:30:37 -070093import static com.google.common.base.Strings.isNullOrEmpty;
Kavitha Alagesanc884c3ef2017-01-19 12:32:26 +053094import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
alshabibb0285992016-03-28 23:30:37 -070095import static org.onlab.util.Tools.get;
Jonathan Hart6ec029a2015-03-24 17:12:35 -070096import static org.onlab.util.Tools.groupedThreads;
97import static org.slf4j.LoggerFactory.getLogger;
alshabib10580802015-02-18 18:30:33 -080098
99/**
Saurav Das0fd79d92016-03-07 10:58:36 -0800100 * Manages inventory of group entries using distributed group stores from the
101 * storage service.
alshabib10580802015-02-18 18:30:33 -0800102 */
103@Component(immediate = true)
104@Service
105public class DistributedGroupStore
106 extends AbstractStore<GroupEvent, GroupStoreDelegate>
107 implements GroupStore {
108
109 private final Logger log = getLogger(getClass());
110
alshabibb0285992016-03-28 23:30:37 -0700111 private static final boolean GARBAGE_COLLECT = false;
112 private static final int GC_THRESH = 6;
Kavitha Alagesanc56cded2017-01-13 10:48:18 +0530113 private static final boolean ALLOW_EXTRANEOUS_GROUPS = true;
alshabibb0285992016-03-28 23:30:37 -0700114
alshabib10580802015-02-18 18:30:33 -0800115 private final int dummyId = 0xffffffff;
Yi Tsengfa394de2017-02-01 11:26:40 -0800116 private final GroupId dummyGroupId = new GroupId(dummyId);
alshabib10580802015-02-18 18:30:33 -0800117
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700118 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
119 protected ClusterCommunicationService clusterCommunicator;
120
121 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
122 protected ClusterService clusterService;
123
124 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700125 protected StorageService storageService;
126
127 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700128 protected MastershipService mastershipService;
129
alshabibb0285992016-03-28 23:30:37 -0700130 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
131 protected ComponentConfigService cfgService;
132
Kavitha Alagesanc884c3ef2017-01-19 12:32:26 +0530133 private ScheduledExecutorService executor;
134 private Consumer<Status> statusChangeListener;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700135 // Per device group table with (device id + app cookie) as key
Madan Jampani0b847532016-03-03 13:44:15 -0800136 private ConsistentMap<GroupStoreKeyMapKey,
alshabibb0285992016-03-28 23:30:37 -0700137 StoredGroupEntry> groupStoreEntriesByKey = null;
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700138 // Per device group table with (device id + group id) as key
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700139 private final ConcurrentMap<DeviceId, ConcurrentMap<GroupId, StoredGroupEntry>>
alshabibb0285992016-03-28 23:30:37 -0700140 groupEntriesById = new ConcurrentHashMap<>();
Madan Jampani0b847532016-03-03 13:44:15 -0800141 private ConsistentMap<GroupStoreKeyMapKey,
alshabibb0285992016-03-28 23:30:37 -0700142 StoredGroupEntry> auditPendingReqQueue = null;
Frank Wange0eb5ce2016-07-01 18:21:25 +0800143 private MapEventListener<GroupStoreKeyMapKey, StoredGroupEntry>
144 mapListener = new GroupStoreKeyMapListener();
alshabib10580802015-02-18 18:30:33 -0800145 private final ConcurrentMap<DeviceId, ConcurrentMap<GroupId, Group>>
146 extraneousGroupEntriesById = new ConcurrentHashMap<>();
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700147 private ExecutorService messageHandlingExecutor;
148 private static final int MESSAGE_HANDLER_THREAD_POOL_SIZE = 1;
Sho SHIMIZU7a4087b2015-09-10 09:23:16 -0700149 private final HashMap<DeviceId, Boolean> deviceAuditStatus = new HashMap<>();
alshabib10580802015-02-18 18:30:33 -0800150
151 private final AtomicInteger groupIdGen = new AtomicInteger();
152
HIGUCHI Yuta180d70f2015-10-01 16:13:56 -0700153 private KryoNamespace clusterMsgSerializer;
154
helenyrwua1c41152016-08-18 16:16:14 -0700155 private static Topic<GroupStoreMessage> groupTopic;
156
alshabibb0285992016-03-28 23:30:37 -0700157 @Property(name = "garbageCollect", boolValue = GARBAGE_COLLECT,
158 label = "Enable group garbage collection")
159 private boolean garbageCollect = GARBAGE_COLLECT;
160
161 @Property(name = "gcThresh", intValue = GC_THRESH,
162 label = "Number of rounds for group garbage collection")
163 private int gcThresh = GC_THRESH;
164
Kavitha Alagesanc56cded2017-01-13 10:48:18 +0530165 @Property(name = "allowExtraneousGroups", boolValue = ALLOW_EXTRANEOUS_GROUPS,
166 label = "Allow groups in switches not installed by ONOS")
167 private boolean allowExtraneousGroups = ALLOW_EXTRANEOUS_GROUPS;
alshabibb0285992016-03-28 23:30:37 -0700168
alshabib10580802015-02-18 18:30:33 -0800169 @Activate
sisubram4beea652017-08-09 10:38:14 +0000170 public void activate(ComponentContext context) {
alshabibb0285992016-03-28 23:30:37 -0700171 cfgService.registerProperties(getClass());
sisubram4beea652017-08-09 10:38:14 +0000172 modified(context);
HIGUCHI Yuta3a84b322016-05-18 13:38:07 -0700173 KryoNamespace.Builder kryoBuilder = new KryoNamespace.Builder()
alshabibb0285992016-03-28 23:30:37 -0700174 .register(KryoNamespaces.API)
HIGUCHI Yuta3a84b322016-05-18 13:38:07 -0700175 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
alshabibb0285992016-03-28 23:30:37 -0700176 .register(DefaultGroup.class,
177 DefaultGroupBucket.class,
178 DefaultGroupDescription.class,
179 DefaultGroupKey.class,
180 GroupDescription.Type.class,
181 Group.GroupState.class,
182 GroupBuckets.class,
alshabibb0285992016-03-28 23:30:37 -0700183 GroupStoreMessage.class,
184 GroupStoreMessage.Type.class,
185 UpdateType.class,
186 GroupStoreMessageSubjects.class,
187 MultiValuedTimestamp.class,
188 GroupStoreKeyMapKey.class,
189 GroupStoreIdMapKey.class,
190 GroupStoreMapKey.class
191 );
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700192
HIGUCHI Yuta3a84b322016-05-18 13:38:07 -0700193 clusterMsgSerializer = kryoBuilder.build("GroupStore");
194 Serializer serializer = Serializer.using(clusterMsgSerializer);
HIGUCHI Yuta180d70f2015-10-01 16:13:56 -0700195
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700196 messageHandlingExecutor = Executors.
197 newFixedThreadPool(MESSAGE_HANDLER_THREAD_POOL_SIZE,
198 groupedThreads("onos/store/group",
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700199 "message-handlers",
200 log));
Madan Jampani01e05fb2015-08-13 13:29:36 -0700201
202 clusterCommunicator.addSubscriber(GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST,
alshabibb0285992016-03-28 23:30:37 -0700203 clusterMsgSerializer::deserialize,
204 this::process,
205 messageHandlingExecutor);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700206
Madan Jampani0b847532016-03-03 13:44:15 -0800207 log.debug("Creating Consistent map onos-group-store-keymap");
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700208
Madan Jampani0b847532016-03-03 13:44:15 -0800209 groupStoreEntriesByKey = storageService.<GroupStoreKeyMapKey, StoredGroupEntry>consistentMapBuilder()
210 .withName("onos-group-store-keymap")
HIGUCHI Yuta3a84b322016-05-18 13:38:07 -0700211 .withSerializer(serializer)
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700212 .build();
Frank Wange0eb5ce2016-07-01 18:21:25 +0800213 groupStoreEntriesByKey.addListener(mapListener);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700214 log.debug("Current size of groupstorekeymap:{}",
215 groupStoreEntriesByKey.size());
Thiago Santosfb73c502016-08-18 18:15:13 -0300216 synchronizeGroupStoreEntries();
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700217
Kavitha Alagesanc884c3ef2017-01-19 12:32:26 +0530218 log.debug("Creating GroupStoreId Map From GroupStoreKey Map");
219 matchGroupEntries();
220 executor = newSingleThreadScheduledExecutor(groupedThreads("onos/group", "store", log));
221 statusChangeListener = status -> {
222 if (status == Status.ACTIVE) {
223 executor.execute(this::matchGroupEntries);
224 }
225 };
226 groupStoreEntriesByKey.addStatusChangeListener(statusChangeListener);
227
Madan Jampani0b847532016-03-03 13:44:15 -0800228 log.debug("Creating Consistent map pendinggroupkeymap");
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700229
Madan Jampani0b847532016-03-03 13:44:15 -0800230 auditPendingReqQueue = storageService.<GroupStoreKeyMapKey, StoredGroupEntry>consistentMapBuilder()
231 .withName("onos-pending-group-keymap")
HIGUCHI Yuta3a84b322016-05-18 13:38:07 -0700232 .withSerializer(serializer)
Jonathan Hart6ec029a2015-03-24 17:12:35 -0700233 .build();
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700234 log.debug("Current size of pendinggroupkeymap:{}",
235 auditPendingReqQueue.size());
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700236
helenyrwua1c41152016-08-18 16:16:14 -0700237 groupTopic = getOrCreateGroupTopic(serializer);
238 groupTopic.subscribe(this::processGroupMessage);
239
alshabib10580802015-02-18 18:30:33 -0800240 log.info("Started");
241 }
242
243 @Deactivate
244 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800245 groupStoreEntriesByKey.removeListener(mapListener);
alshabibb0285992016-03-28 23:30:37 -0700246 cfgService.unregisterProperties(getClass(), false);
HIGUCHI Yuta180d70f2015-10-01 16:13:56 -0700247 clusterCommunicator.removeSubscriber(GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST);
alshabib10580802015-02-18 18:30:33 -0800248 log.info("Stopped");
249 }
250
alshabibb0285992016-03-28 23:30:37 -0700251 @Modified
252 public void modified(ComponentContext context) {
253 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
254
255 try {
256 String s = get(properties, "garbageCollect");
257 garbageCollect = isNullOrEmpty(s) ? GARBAGE_COLLECT : Boolean.parseBoolean(s.trim());
258
259 s = get(properties, "gcThresh");
260 gcThresh = isNullOrEmpty(s) ? GC_THRESH : Integer.parseInt(s.trim());
Kavitha Alagesanc56cded2017-01-13 10:48:18 +0530261
262 s = get(properties, "allowExtraneousGroups");
263 allowExtraneousGroups = isNullOrEmpty(s) ? ALLOW_EXTRANEOUS_GROUPS : Boolean.parseBoolean(s.trim());
alshabibb0285992016-03-28 23:30:37 -0700264 } catch (Exception e) {
265 gcThresh = GC_THRESH;
266 garbageCollect = GARBAGE_COLLECT;
Kavitha Alagesanc56cded2017-01-13 10:48:18 +0530267 allowExtraneousGroups = ALLOW_EXTRANEOUS_GROUPS;
alshabibb0285992016-03-28 23:30:37 -0700268 }
269 }
270
helenyrwua1c41152016-08-18 16:16:14 -0700271 private Topic<GroupStoreMessage> getOrCreateGroupTopic(Serializer serializer) {
272 if (groupTopic == null) {
273 return storageService.getTopic("group-failover-notif", serializer);
274 } else {
275 return groupTopic;
276 }
Sho SHIMIZUa6285542017-01-12 15:08:24 -0800277 }
helenyrwua1c41152016-08-18 16:16:14 -0700278
alshabib10580802015-02-18 18:30:33 -0800279 /**
Kavitha Alagesanc884c3ef2017-01-19 12:32:26 +0530280 * Updating values of groupEntriesById.
281 */
282 private void matchGroupEntries() {
283 for (Entry<GroupStoreKeyMapKey, StoredGroupEntry> entry : groupStoreEntriesByKey.asJavaMap().entrySet()) {
284 StoredGroupEntry group = entry.getValue();
285 getGroupIdTable(entry.getKey().deviceId()).put(group.id(), group);
286 }
287 }
288
Thiago Santosfb73c502016-08-18 18:15:13 -0300289
290 private void synchronizeGroupStoreEntries() {
291 Map<GroupStoreKeyMapKey, StoredGroupEntry> groupEntryMap = groupStoreEntriesByKey.asJavaMap();
292 for (Entry<GroupStoreKeyMapKey, StoredGroupEntry> entry : groupEntryMap.entrySet()) {
Thiago Santosfb73c502016-08-18 18:15:13 -0300293 StoredGroupEntry value = entry.getValue();
Thiago Santosfb73c502016-08-18 18:15:13 -0300294 ConcurrentMap<GroupId, StoredGroupEntry> groupIdTable = getGroupIdTable(value.deviceId());
295 groupIdTable.put(value.id(), value);
296 }
297 }
298
Kavitha Alagesanc884c3ef2017-01-19 12:32:26 +0530299 /**
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700300 * Returns the group store eventual consistent key map.
alshabib10580802015-02-18 18:30:33 -0800301 *
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700302 * @return Map representing group key table.
alshabib10580802015-02-18 18:30:33 -0800303 */
Madan Jampani0b847532016-03-03 13:44:15 -0800304 private Map<GroupStoreKeyMapKey, StoredGroupEntry>
alshabibb0285992016-03-28 23:30:37 -0700305 getGroupStoreKeyMap() {
Madan Jampani0b847532016-03-03 13:44:15 -0800306 return groupStoreEntriesByKey.asJavaMap();
alshabib10580802015-02-18 18:30:33 -0800307 }
308
309 /**
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700310 * Returns the group id table for specified device.
alshabib10580802015-02-18 18:30:33 -0800311 *
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700312 * @param deviceId identifier of the device
313 * @return Map representing group key table of given device.
alshabib10580802015-02-18 18:30:33 -0800314 */
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700315 private ConcurrentMap<GroupId, StoredGroupEntry> getGroupIdTable(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700316 return groupEntriesById.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
alshabib10580802015-02-18 18:30:33 -0800317 }
318
319 /**
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700320 * Returns the pending group request table.
alshabib10580802015-02-18 18:30:33 -0800321 *
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700322 * @return Map representing group key table.
alshabib10580802015-02-18 18:30:33 -0800323 */
Madan Jampani0b847532016-03-03 13:44:15 -0800324 private Map<GroupStoreKeyMapKey, StoredGroupEntry>
alshabibb0285992016-03-28 23:30:37 -0700325 getPendingGroupKeyTable() {
Madan Jampani0b847532016-03-03 13:44:15 -0800326 return auditPendingReqQueue.asJavaMap();
alshabib10580802015-02-18 18:30:33 -0800327 }
328
329 /**
330 * Returns the extraneous group id table for specified device.
331 *
332 * @param deviceId identifier of the device
333 * @return Map representing group key table of given device.
334 */
335 private ConcurrentMap<GroupId, Group>
336 getExtraneousGroupIdTable(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700337 return extraneousGroupEntriesById.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
alshabib10580802015-02-18 18:30:33 -0800338 }
339
340 /**
341 * Returns the number of groups for the specified device in the store.
342 *
343 * @return number of groups for the specified device
344 */
345 @Override
346 public int getGroupCount(DeviceId deviceId) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700347 return (getGroups(deviceId) != null) ?
alshabibb0285992016-03-28 23:30:37 -0700348 Iterables.size(getGroups(deviceId)) : 0;
alshabib10580802015-02-18 18:30:33 -0800349 }
350
351 /**
352 * Returns the groups associated with a device.
353 *
354 * @param deviceId the device ID
alshabib10580802015-02-18 18:30:33 -0800355 * @return the group entries
356 */
357 @Override
358 public Iterable<Group> getGroups(DeviceId deviceId) {
Charles Chanf4838a72015-12-07 18:13:45 -0800359 // Let ImmutableSet.copyOf do the type conversion
360 return ImmutableSet.copyOf(getStoredGroups(deviceId));
alshabib10580802015-02-18 18:30:33 -0800361 }
362
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700363 private Iterable<StoredGroupEntry> getStoredGroups(DeviceId deviceId) {
Charles Chanf4838a72015-12-07 18:13:45 -0800364 NodeId master = mastershipService.getMasterFor(deviceId);
365 if (master == null) {
366 log.debug("Failed to getGroups: No master for {}", deviceId);
367 return Collections.emptySet();
368 }
369
370 Set<StoredGroupEntry> storedGroups = getGroupStoreKeyMap().values()
371 .stream()
372 .filter(input -> input.deviceId().equals(deviceId))
373 .collect(Collectors.toSet());
374 return ImmutableSet.copyOf(storedGroups);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700375 }
376
alshabib10580802015-02-18 18:30:33 -0800377 /**
378 * Returns the stored group entry.
379 *
alshabibb0285992016-03-28 23:30:37 -0700380 * @param deviceId the device ID
alshabib10580802015-02-18 18:30:33 -0800381 * @param appCookie the group key
alshabib10580802015-02-18 18:30:33 -0800382 * @return a group associated with the key
383 */
384 @Override
385 public Group getGroup(DeviceId deviceId, GroupKey appCookie) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700386 return getStoredGroupEntry(deviceId, appCookie);
387 }
388
389 private StoredGroupEntry getStoredGroupEntry(DeviceId deviceId,
390 GroupKey appCookie) {
391 return getGroupStoreKeyMap().get(new GroupStoreKeyMapKey(deviceId,
392 appCookie));
393 }
394
395 @Override
396 public Group getGroup(DeviceId deviceId, GroupId groupId) {
397 return getStoredGroupEntry(deviceId, groupId);
398 }
399
400 private StoredGroupEntry getStoredGroupEntry(DeviceId deviceId,
401 GroupId groupId) {
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700402 return getGroupIdTable(deviceId).get(groupId);
alshabib10580802015-02-18 18:30:33 -0800403 }
404
405 private int getFreeGroupIdValue(DeviceId deviceId) {
406 int freeId = groupIdGen.incrementAndGet();
407
408 while (true) {
Yi Tsengfa394de2017-02-01 11:26:40 -0800409 Group existing = getGroup(deviceId, new GroupId(freeId));
alshabib10580802015-02-18 18:30:33 -0800410 if (existing == null) {
411 existing = (
412 extraneousGroupEntriesById.get(deviceId) != null) ?
413 extraneousGroupEntriesById.get(deviceId).
Yi Tsengfa394de2017-02-01 11:26:40 -0800414 get(new GroupId(freeId)) :
alshabib10580802015-02-18 18:30:33 -0800415 null;
416 }
417 if (existing != null) {
418 freeId = groupIdGen.incrementAndGet();
419 } else {
420 break;
421 }
422 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700423 log.debug("getFreeGroupIdValue: Next Free ID is {}", freeId);
alshabib10580802015-02-18 18:30:33 -0800424 return freeId;
425 }
426
427 /**
428 * Stores a new group entry using the information from group description.
429 *
430 * @param groupDesc group description to be used to create group entry
431 */
432 @Override
433 public void storeGroupDescription(GroupDescription groupDesc) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700434 log.debug("In storeGroupDescription");
alshabib10580802015-02-18 18:30:33 -0800435 // Check if a group is existing with the same key
Saurav Das8a0732e2015-11-20 15:27:53 -0800436 Group existingGroup = getGroup(groupDesc.deviceId(), groupDesc.appCookie());
437 if (existingGroup != null) {
Charles Chan216e3c82016-04-23 14:48:16 -0700438 log.info("Group already exists with the same key {} in dev:{} with id:0x{}",
Saurav Das8a0732e2015-11-20 15:27:53 -0800439 groupDesc.appCookie(), groupDesc.deviceId(),
440 Integer.toHexString(existingGroup.id().id()));
alshabib10580802015-02-18 18:30:33 -0800441 return;
442 }
443
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700444 // Check if group to be created by a remote instance
Madan Jampani175e8fd2015-05-20 14:10:45 -0700445 if (mastershipService.getLocalRole(groupDesc.deviceId()) != MastershipRole.MASTER) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700446 log.debug("storeGroupDescription: Device {} local role is not MASTER",
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700447 groupDesc.deviceId());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700448 if (mastershipService.getMasterFor(groupDesc.deviceId()) == null) {
449 log.error("No Master for device {}..."
alshabibb0285992016-03-28 23:30:37 -0700450 + "Can not perform add group operation",
451 groupDesc.deviceId());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700452 //TODO: Send Group operation failure event
453 return;
454 }
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700455 GroupStoreMessage groupOp = GroupStoreMessage.
456 createGroupAddRequestMsg(groupDesc.deviceId(),
457 groupDesc);
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700458
Madan Jampani175e8fd2015-05-20 14:10:45 -0700459 clusterCommunicator.unicast(groupOp,
alshabibb0285992016-03-28 23:30:37 -0700460 GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST,
461 clusterMsgSerializer::serialize,
462 mastershipService.getMasterFor(groupDesc.deviceId()))
463 .whenComplete((result, error) -> {
Madan Jampani175e8fd2015-05-20 14:10:45 -0700464 if (error != null) {
465 log.warn("Failed to send request to master: {} to {}",
alshabibb0285992016-03-28 23:30:37 -0700466 groupOp,
467 mastershipService.getMasterFor(groupDesc.deviceId()));
Madan Jampani175e8fd2015-05-20 14:10:45 -0700468 //TODO: Send Group operation failure event
469 } else {
470 log.debug("Sent Group operation request for device {} "
alshabibb0285992016-03-28 23:30:37 -0700471 + "to remote MASTER {}",
472 groupDesc.deviceId(),
473 mastershipService.getMasterFor(groupDesc.deviceId()));
Madan Jampani175e8fd2015-05-20 14:10:45 -0700474 }
475 });
alshabib10580802015-02-18 18:30:33 -0800476 return;
477 }
478
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700479 log.debug("Store group for device {} is getting handled locally",
480 groupDesc.deviceId());
alshabib10580802015-02-18 18:30:33 -0800481 storeGroupDescriptionInternal(groupDesc);
482 }
483
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700484 private Group getMatchingExtraneousGroupbyId(DeviceId deviceId, Integer groupId) {
485 ConcurrentMap<GroupId, Group> extraneousMap =
486 extraneousGroupEntriesById.get(deviceId);
487 if (extraneousMap == null) {
488 return null;
489 }
Yi Tsengfa394de2017-02-01 11:26:40 -0800490 return extraneousMap.get(new GroupId(groupId));
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700491 }
492
493 private Group getMatchingExtraneousGroupbyBuckets(DeviceId deviceId,
494 GroupBuckets buckets) {
495 ConcurrentMap<GroupId, Group> extraneousMap =
496 extraneousGroupEntriesById.get(deviceId);
497 if (extraneousMap == null) {
498 return null;
499 }
500
alshabibb0285992016-03-28 23:30:37 -0700501 for (Group extraneousGroup : extraneousMap.values()) {
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700502 if (extraneousGroup.buckets().equals(buckets)) {
503 return extraneousGroup;
504 }
505 }
506 return null;
507 }
508
alshabib10580802015-02-18 18:30:33 -0800509 private void storeGroupDescriptionInternal(GroupDescription groupDesc) {
510 // Check if a group is existing with the same key
511 if (getGroup(groupDesc.deviceId(), groupDesc.appCookie()) != null) {
512 return;
513 }
514
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700515 if (deviceAuditStatus.get(groupDesc.deviceId()) == null) {
516 // Device group audit has not completed yet
517 // Add this group description to pending group key table
518 // Create a group entry object with Dummy Group ID
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700519 log.debug("storeGroupDescriptionInternal: Device {} AUDIT pending...Queuing Group ADD request",
alshabibb0285992016-03-28 23:30:37 -0700520 groupDesc.deviceId());
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700521 StoredGroupEntry group = new DefaultGroup(dummyGroupId, groupDesc);
522 group.setState(GroupState.WAITING_AUDIT_COMPLETE);
Madan Jampani0b847532016-03-03 13:44:15 -0800523 Map<GroupStoreKeyMapKey, StoredGroupEntry> pendingKeyTable =
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700524 getPendingGroupKeyTable();
525 pendingKeyTable.put(new GroupStoreKeyMapKey(groupDesc.deviceId(),
526 groupDesc.appCookie()),
527 group);
528 return;
529 }
530
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700531 Group matchingExtraneousGroup = null;
532 if (groupDesc.givenGroupId() != null) {
533 //Check if there is a extraneous group existing with the same Id
534 matchingExtraneousGroup = getMatchingExtraneousGroupbyId(
alshabibb0285992016-03-28 23:30:37 -0700535 groupDesc.deviceId(), groupDesc.givenGroupId());
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700536 if (matchingExtraneousGroup != null) {
Saurav Das0fd79d92016-03-07 10:58:36 -0800537 log.debug("storeGroupDescriptionInternal: Matching extraneous group "
alshabibb0285992016-03-28 23:30:37 -0700538 + "found in Device {} for group id 0x{}",
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700539 groupDesc.deviceId(),
Saurav Das0fd79d92016-03-07 10:58:36 -0800540 Integer.toHexString(groupDesc.givenGroupId()));
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700541 //Check if the group buckets matches with user provided buckets
542 if (matchingExtraneousGroup.buckets().equals(groupDesc.buckets())) {
543 //Group is already existing with the same buckets and Id
544 // Create a group entry object
Saurav Das0fd79d92016-03-07 10:58:36 -0800545 log.debug("storeGroupDescriptionInternal: Buckets also matching "
alshabibb0285992016-03-28 23:30:37 -0700546 + "in Device {} for group id 0x{}",
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700547 groupDesc.deviceId(),
Saurav Das0fd79d92016-03-07 10:58:36 -0800548 Integer.toHexString(groupDesc.givenGroupId()));
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700549 StoredGroupEntry group = new DefaultGroup(
alshabibb0285992016-03-28 23:30:37 -0700550 matchingExtraneousGroup.id(), groupDesc);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700551 // Insert the newly created group entry into key and id maps
552 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700553 put(new GroupStoreKeyMapKey(groupDesc.deviceId(),
554 groupDesc.appCookie()), group);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700555 // Ensure it also inserted into group id based table to
556 // avoid any chances of duplication in group id generation
557 getGroupIdTable(groupDesc.deviceId()).
alshabibb0285992016-03-28 23:30:37 -0700558 put(matchingExtraneousGroup.id(), group);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700559 addOrUpdateGroupEntry(matchingExtraneousGroup);
560 removeExtraneousGroupEntry(matchingExtraneousGroup);
561 return;
562 } else {
563 //Group buckets are not matching. Update group
564 //with user provided buckets.
Saurav Das0fd79d92016-03-07 10:58:36 -0800565 log.debug("storeGroupDescriptionInternal: Buckets are not "
alshabibb0285992016-03-28 23:30:37 -0700566 + "matching in Device {} for group id 0x{}",
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700567 groupDesc.deviceId(),
Saurav Das0fd79d92016-03-07 10:58:36 -0800568 Integer.toHexString(groupDesc.givenGroupId()));
569 StoredGroupEntry modifiedGroup = new DefaultGroup(
alshabibb0285992016-03-28 23:30:37 -0700570 matchingExtraneousGroup.id(), groupDesc);
Saurav Das0fd79d92016-03-07 10:58:36 -0800571 modifiedGroup.setState(GroupState.PENDING_UPDATE);
572 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700573 put(new GroupStoreKeyMapKey(groupDesc.deviceId(),
574 groupDesc.appCookie()), modifiedGroup);
Saurav Das0fd79d92016-03-07 10:58:36 -0800575 // Ensure it also inserted into group id based table to
576 // avoid any chances of duplication in group id generation
577 getGroupIdTable(groupDesc.deviceId()).
alshabibb0285992016-03-28 23:30:37 -0700578 put(matchingExtraneousGroup.id(), modifiedGroup);
Saurav Das0fd79d92016-03-07 10:58:36 -0800579 removeExtraneousGroupEntry(matchingExtraneousGroup);
580 log.debug("storeGroupDescriptionInternal: Triggering Group "
alshabibb0285992016-03-28 23:30:37 -0700581 + "UPDATE request for {} in device {}",
Saurav Das0fd79d92016-03-07 10:58:36 -0800582 matchingExtraneousGroup.id(),
583 groupDesc.deviceId());
584 notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_REQUESTED, modifiedGroup));
585 return;
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700586 }
587 }
588 } else {
589 //Check if there is an extraneous group with user provided buckets
590 matchingExtraneousGroup = getMatchingExtraneousGroupbyBuckets(
alshabibb0285992016-03-28 23:30:37 -0700591 groupDesc.deviceId(), groupDesc.buckets());
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700592 if (matchingExtraneousGroup != null) {
593 //Group is already existing with the same buckets.
594 //So reuse this group.
595 log.debug("storeGroupDescriptionInternal: Matching extraneous group found in Device {}",
596 groupDesc.deviceId());
597 //Create a group entry object
598 StoredGroupEntry group = new DefaultGroup(
alshabibb0285992016-03-28 23:30:37 -0700599 matchingExtraneousGroup.id(), groupDesc);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700600 // Insert the newly created group entry into key and id maps
601 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700602 put(new GroupStoreKeyMapKey(groupDesc.deviceId(),
603 groupDesc.appCookie()), group);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700604 // Ensure it also inserted into group id based table to
605 // avoid any chances of duplication in group id generation
606 getGroupIdTable(groupDesc.deviceId()).
alshabibb0285992016-03-28 23:30:37 -0700607 put(matchingExtraneousGroup.id(), group);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -0700608 addOrUpdateGroupEntry(matchingExtraneousGroup);
609 removeExtraneousGroupEntry(matchingExtraneousGroup);
610 return;
611 } else {
612 //TODO: Check if there are any empty groups that can be used here
613 log.debug("storeGroupDescriptionInternal: No matching extraneous groups found in Device {}",
614 groupDesc.deviceId());
615 }
616 }
617
Saurav Das100e3b82015-04-30 11:12:10 -0700618 GroupId id = null;
619 if (groupDesc.givenGroupId() == null) {
620 // Get a new group identifier
Yi Tsengfa394de2017-02-01 11:26:40 -0800621 id = new GroupId(getFreeGroupIdValue(groupDesc.deviceId()));
Saurav Das100e3b82015-04-30 11:12:10 -0700622 } else {
Saurav Das8be4e3a2016-03-11 17:19:07 -0800623 // we need to use the identifier passed in by caller, but check if
624 // already used
625 Group existing = getGroup(groupDesc.deviceId(),
Yi Tsengfa394de2017-02-01 11:26:40 -0800626 new GroupId(groupDesc.givenGroupId()));
Saurav Das8be4e3a2016-03-11 17:19:07 -0800627 if (existing != null) {
628 log.warn("Group already exists with the same id: 0x{} in dev:{} "
alshabibb0285992016-03-28 23:30:37 -0700629 + "but with different key: {} (request gkey: {})",
630 Integer.toHexString(groupDesc.givenGroupId()),
631 groupDesc.deviceId(),
632 existing.appCookie(),
633 groupDesc.appCookie());
Saurav Das8be4e3a2016-03-11 17:19:07 -0800634 return;
635 }
Yi Tsengfa394de2017-02-01 11:26:40 -0800636 id = new GroupId(groupDesc.givenGroupId());
Saurav Das100e3b82015-04-30 11:12:10 -0700637 }
alshabib10580802015-02-18 18:30:33 -0800638 // Create a group entry object
639 StoredGroupEntry group = new DefaultGroup(id, groupDesc);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700640 // Insert the newly created group entry into key and id maps
641 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700642 put(new GroupStoreKeyMapKey(groupDesc.deviceId(),
643 groupDesc.appCookie()), group);
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700644 // Ensure it also inserted into group id based table to
645 // avoid any chances of duplication in group id generation
646 getGroupIdTable(groupDesc.deviceId()).
alshabibb0285992016-03-28 23:30:37 -0700647 put(id, group);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700648 log.debug("storeGroupDescriptionInternal: Processing Group ADD request for Id {} in device {}",
alshabibb0285992016-03-28 23:30:37 -0700649 id,
650 groupDesc.deviceId());
alshabib10580802015-02-18 18:30:33 -0800651 notifyDelegate(new GroupEvent(GroupEvent.Type.GROUP_ADD_REQUESTED,
652 group));
653 }
654
655 /**
656 * Updates the existing group entry with the information
657 * from group description.
658 *
alshabibb0285992016-03-28 23:30:37 -0700659 * @param deviceId the device ID
alshabib10580802015-02-18 18:30:33 -0800660 * @param oldAppCookie the current group key
alshabibb0285992016-03-28 23:30:37 -0700661 * @param type update type
662 * @param newBuckets group buckets for updates
alshabib10580802015-02-18 18:30:33 -0800663 * @param newAppCookie optional new group key
664 */
665 @Override
666 public void updateGroupDescription(DeviceId deviceId,
667 GroupKey oldAppCookie,
668 UpdateType type,
669 GroupBuckets newBuckets,
670 GroupKey newAppCookie) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700671 // Check if group update to be done by a remote instance
sangho52abe3a2015-05-05 14:13:34 -0700672 if (mastershipService.getMasterFor(deviceId) != null &&
673 mastershipService.getLocalRole(deviceId) != MastershipRole.MASTER) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700674 log.debug("updateGroupDescription: Device {} local role is not MASTER",
675 deviceId);
676 if (mastershipService.getMasterFor(deviceId) == null) {
677 log.error("No Master for device {}..."
alshabibb0285992016-03-28 23:30:37 -0700678 + "Can not perform update group operation",
679 deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700680 //TODO: Send Group operation failure event
681 return;
682 }
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700683 GroupStoreMessage groupOp = GroupStoreMessage.
684 createGroupUpdateRequestMsg(deviceId,
685 oldAppCookie,
686 type,
687 newBuckets,
688 newAppCookie);
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700689
Madan Jampani175e8fd2015-05-20 14:10:45 -0700690 clusterCommunicator.unicast(groupOp,
alshabibb0285992016-03-28 23:30:37 -0700691 GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST,
692 clusterMsgSerializer::serialize,
693 mastershipService.getMasterFor(deviceId)).whenComplete((result, error) -> {
694 if (error != null) {
695 log.warn("Failed to send request to master: {} to {}",
696 groupOp,
697 mastershipService.getMasterFor(deviceId), error);
698 }
699 //TODO: Send Group operation failure event
700 });
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700701 return;
702 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700703 log.debug("updateGroupDescription for device {} is getting handled locally",
704 deviceId);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700705 updateGroupDescriptionInternal(deviceId,
706 oldAppCookie,
707 type,
708 newBuckets,
709 newAppCookie);
710 }
711
712 private void updateGroupDescriptionInternal(DeviceId deviceId,
alshabibb0285992016-03-28 23:30:37 -0700713 GroupKey oldAppCookie,
714 UpdateType type,
715 GroupBuckets newBuckets,
716 GroupKey newAppCookie) {
alshabib10580802015-02-18 18:30:33 -0800717 // Check if a group is existing with the provided key
718 Group oldGroup = getGroup(deviceId, oldAppCookie);
719 if (oldGroup == null) {
Saurav Das8be4e3a2016-03-11 17:19:07 -0800720 log.warn("updateGroupDescriptionInternal: Group not found...strange. "
alshabibb0285992016-03-28 23:30:37 -0700721 + "GroupKey:{} DeviceId:{}", oldAppCookie, deviceId);
alshabib10580802015-02-18 18:30:33 -0800722 return;
723 }
724
725 List<GroupBucket> newBucketList = getUpdatedBucketList(oldGroup,
726 type,
727 newBuckets);
728 if (newBucketList != null) {
729 // Create a new group object from the old group
730 GroupBuckets updatedBuckets = new GroupBuckets(newBucketList);
731 GroupKey newCookie = (newAppCookie != null) ? newAppCookie : oldAppCookie;
732 GroupDescription updatedGroupDesc = new DefaultGroupDescription(
733 oldGroup.deviceId(),
734 oldGroup.type(),
735 updatedBuckets,
736 newCookie,
Saurav Das100e3b82015-04-30 11:12:10 -0700737 oldGroup.givenGroupId(),
alshabib10580802015-02-18 18:30:33 -0800738 oldGroup.appId());
739 StoredGroupEntry newGroup = new DefaultGroup(oldGroup.id(),
740 updatedGroupDesc);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700741 log.debug("updateGroupDescriptionInternal: group entry {} in device {} moving from {} to PENDING_UPDATE",
alshabibb0285992016-03-28 23:30:37 -0700742 oldGroup.id(),
743 oldGroup.deviceId(),
744 oldGroup.state());
alshabib10580802015-02-18 18:30:33 -0800745 newGroup.setState(GroupState.PENDING_UPDATE);
746 newGroup.setLife(oldGroup.life());
747 newGroup.setPackets(oldGroup.packets());
748 newGroup.setBytes(oldGroup.bytes());
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700749 //Update the group entry in groupkey based map.
750 //Update to groupid based map will happen in the
751 //groupkey based map update listener
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700752 log.debug("updateGroupDescriptionInternal with type {}: Group updated with buckets",
753 type);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700754 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700755 put(new GroupStoreKeyMapKey(newGroup.deviceId(),
756 newGroup.appCookie()), newGroup);
alshabib10580802015-02-18 18:30:33 -0800757 notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_REQUESTED, newGroup));
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700758 } else {
759 log.warn("updateGroupDescriptionInternal with type {}: No "
alshabibb0285992016-03-28 23:30:37 -0700760 + "change in the buckets in update", type);
alshabib10580802015-02-18 18:30:33 -0800761 }
762 }
763
764 private List<GroupBucket> getUpdatedBucketList(Group oldGroup,
765 UpdateType type,
766 GroupBuckets buckets) {
Victor Silva0282ab82016-11-15 16:30:27 -0300767 if (type == UpdateType.SET) {
768 return buckets.buckets();
769 }
770
Victor Silvadf1eeae2016-08-12 15:28:57 -0300771 List<GroupBucket> oldBuckets = oldGroup.buckets().buckets();
772 List<GroupBucket> updatedBucketList = new ArrayList<>();
alshabib10580802015-02-18 18:30:33 -0800773 boolean groupDescUpdated = false;
774
775 if (type == UpdateType.ADD) {
Victor Silvadf1eeae2016-08-12 15:28:57 -0300776 List<GroupBucket> newBuckets = buckets.buckets();
777
778 // Add old buckets that will not be updated and check if any will be updated.
779 for (GroupBucket oldBucket : oldBuckets) {
780 int newBucketIndex = newBuckets.indexOf(oldBucket);
781
782 if (newBucketIndex != -1) {
783 GroupBucket newBucket = newBuckets.get(newBucketIndex);
784 if (!newBucket.hasSameParameters(oldBucket)) {
785 // Bucket will be updated
786 groupDescUpdated = true;
787 }
788 } else {
789 // Old bucket will remain the same - add it.
790 updatedBucketList.add(oldBucket);
alshabib10580802015-02-18 18:30:33 -0800791 }
792 }
Victor Silvadf1eeae2016-08-12 15:28:57 -0300793
794 // Add all new buckets
795 updatedBucketList.addAll(newBuckets);
796 if (!oldBuckets.containsAll(newBuckets)) {
797 groupDescUpdated = true;
798 }
799
alshabib10580802015-02-18 18:30:33 -0800800 } else if (type == UpdateType.REMOVE) {
Victor Silvadf1eeae2016-08-12 15:28:57 -0300801 List<GroupBucket> bucketsToRemove = buckets.buckets();
802
803 // Check which old buckets should remain
804 for (GroupBucket oldBucket : oldBuckets) {
805 if (!bucketsToRemove.contains(oldBucket)) {
806 updatedBucketList.add(oldBucket);
807 } else {
alshabib10580802015-02-18 18:30:33 -0800808 groupDescUpdated = true;
809 }
810 }
811 }
812
813 if (groupDescUpdated) {
Victor Silvadf1eeae2016-08-12 15:28:57 -0300814 return updatedBucketList;
alshabib10580802015-02-18 18:30:33 -0800815 } else {
816 return null;
817 }
818 }
819
820 /**
821 * Triggers deleting the existing group entry.
822 *
alshabibb0285992016-03-28 23:30:37 -0700823 * @param deviceId the device ID
alshabib10580802015-02-18 18:30:33 -0800824 * @param appCookie the group key
825 */
826 @Override
827 public void deleteGroupDescription(DeviceId deviceId,
828 GroupKey appCookie) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700829 // Check if group to be deleted by a remote instance
830 if (mastershipService.
831 getLocalRole(deviceId) != MastershipRole.MASTER) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700832 log.debug("deleteGroupDescription: Device {} local role is not MASTER",
833 deviceId);
834 if (mastershipService.getMasterFor(deviceId) == null) {
835 log.error("No Master for device {}..."
alshabibb0285992016-03-28 23:30:37 -0700836 + "Can not perform delete group operation",
837 deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700838 //TODO: Send Group operation failure event
839 return;
840 }
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700841 GroupStoreMessage groupOp = GroupStoreMessage.
842 createGroupDeleteRequestMsg(deviceId,
843 appCookie);
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700844
Madan Jampani175e8fd2015-05-20 14:10:45 -0700845 clusterCommunicator.unicast(groupOp,
alshabibb0285992016-03-28 23:30:37 -0700846 GroupStoreMessageSubjects.REMOTE_GROUP_OP_REQUEST,
847 clusterMsgSerializer::serialize,
848 mastershipService.getMasterFor(deviceId)).whenComplete((result, error) -> {
849 if (error != null) {
850 log.warn("Failed to send request to master: {} to {}",
851 groupOp,
852 mastershipService.getMasterFor(deviceId), error);
853 }
854 //TODO: Send Group operation failure event
855 });
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700856 return;
857 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700858 log.debug("deleteGroupDescription in device {} is getting handled locally",
859 deviceId);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700860 deleteGroupDescriptionInternal(deviceId, appCookie);
861 }
862
863 private void deleteGroupDescriptionInternal(DeviceId deviceId,
864 GroupKey appCookie) {
alshabib10580802015-02-18 18:30:33 -0800865 // Check if a group is existing with the provided key
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700866 StoredGroupEntry existing = getStoredGroupEntry(deviceId, appCookie);
alshabib10580802015-02-18 18:30:33 -0800867 if (existing == null) {
868 return;
869 }
870
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700871 log.debug("deleteGroupDescriptionInternal: group entry {} in device {} moving from {} to PENDING_DELETE",
alshabibb0285992016-03-28 23:30:37 -0700872 existing.id(),
873 existing.deviceId(),
874 existing.state());
alshabib10580802015-02-18 18:30:33 -0800875 synchronized (existing) {
876 existing.setState(GroupState.PENDING_DELETE);
Saurav Das80980c72016-03-23 11:22:49 -0700877 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700878 put(new GroupStoreKeyMapKey(existing.deviceId(), existing.appCookie()),
879 existing);
alshabib10580802015-02-18 18:30:33 -0800880 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700881 log.debug("deleteGroupDescriptionInternal: in device {} issuing GROUP_REMOVE_REQUESTED",
882 deviceId);
alshabib10580802015-02-18 18:30:33 -0800883 notifyDelegate(new GroupEvent(Type.GROUP_REMOVE_REQUESTED, existing));
884 }
885
886 /**
887 * Stores a new group entry, or updates an existing entry.
888 *
889 * @param group group entry
890 */
891 @Override
892 public void addOrUpdateGroupEntry(Group group) {
893 // check if this new entry is an update to an existing entry
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700894 StoredGroupEntry existing = getStoredGroupEntry(group.deviceId(),
895 group.id());
alshabib10580802015-02-18 18:30:33 -0800896 GroupEvent event = null;
897
898 if (existing != null) {
Saurav Das0fd79d92016-03-07 10:58:36 -0800899 log.trace("addOrUpdateGroupEntry: updating group entry {} in device {}",
alshabibb0285992016-03-28 23:30:37 -0700900 group.id(),
901 group.deviceId());
alshabib10580802015-02-18 18:30:33 -0800902 synchronized (existing) {
alshabibb0285992016-03-28 23:30:37 -0700903 for (GroupBucket bucket : group.buckets().buckets()) {
Sho SHIMIZU30d639b2015-05-05 09:30:35 -0700904 Optional<GroupBucket> matchingBucket =
Srikanth Vavilapalli10e75cd2015-04-13 16:21:24 -0700905 existing.buckets().buckets()
alshabibb0285992016-03-28 23:30:37 -0700906 .stream()
907 .filter((existingBucket) -> (existingBucket.equals(bucket)))
908 .findFirst();
Srikanth Vavilapalli10e75cd2015-04-13 16:21:24 -0700909 if (matchingBucket.isPresent()) {
910 ((StoredGroupBucketEntry) matchingBucket.
911 get()).setPackets(bucket.packets());
912 ((StoredGroupBucketEntry) matchingBucket.
913 get()).setBytes(bucket.bytes());
914 } else {
915 log.warn("addOrUpdateGroupEntry: No matching "
alshabibb0285992016-03-28 23:30:37 -0700916 + "buckets to update stats");
Srikanth Vavilapalli10e75cd2015-04-13 16:21:24 -0700917 }
918 }
alshabib10580802015-02-18 18:30:33 -0800919 existing.setLife(group.life());
920 existing.setPackets(group.packets());
921 existing.setBytes(group.bytes());
alshabibb0285992016-03-28 23:30:37 -0700922 existing.setReferenceCount(group.referenceCount());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -0700923 if ((existing.state() == GroupState.PENDING_ADD) ||
alshabibb0285992016-03-28 23:30:37 -0700924 (existing.state() == GroupState.PENDING_ADD_RETRY)) {
Saurav Das0fd79d92016-03-07 10:58:36 -0800925 log.trace("addOrUpdateGroupEntry: group entry {} in device {} moving from {} to ADDED",
alshabibb0285992016-03-28 23:30:37 -0700926 existing.id(),
927 existing.deviceId(),
928 existing.state());
alshabib10580802015-02-18 18:30:33 -0800929 existing.setState(GroupState.ADDED);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700930 existing.setIsGroupStateAddedFirstTime(true);
alshabib10580802015-02-18 18:30:33 -0800931 event = new GroupEvent(Type.GROUP_ADDED, existing);
932 } else {
Saurav Das0fd79d92016-03-07 10:58:36 -0800933 log.trace("addOrUpdateGroupEntry: group entry {} in device {} moving from {} to ADDED",
alshabibb0285992016-03-28 23:30:37 -0700934 existing.id(),
935 existing.deviceId(),
936 GroupState.PENDING_UPDATE);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700937 existing.setState(GroupState.ADDED);
938 existing.setIsGroupStateAddedFirstTime(false);
alshabib10580802015-02-18 18:30:33 -0800939 event = new GroupEvent(Type.GROUP_UPDATED, existing);
940 }
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700941 //Re-PUT map entries to trigger map update events
942 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -0700943 put(new GroupStoreKeyMapKey(existing.deviceId(),
944 existing.appCookie()), existing);
alshabib10580802015-02-18 18:30:33 -0800945 }
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700946 } else {
947 log.warn("addOrUpdateGroupEntry: Group update "
alshabibb0285992016-03-28 23:30:37 -0700948 + "happening for a non-existing entry in the map");
alshabib10580802015-02-18 18:30:33 -0800949 }
950
951 if (event != null) {
952 notifyDelegate(event);
953 }
954 }
955
956 /**
957 * Removes the group entry from store.
958 *
959 * @param group group entry
960 */
961 @Override
962 public void removeGroupEntry(Group group) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700963 StoredGroupEntry existing = getStoredGroupEntry(group.deviceId(),
964 group.id());
alshabib10580802015-02-18 18:30:33 -0800965
966 if (existing != null) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700967 log.debug("removeGroupEntry: removing group entry {} in device {}",
alshabibb0285992016-03-28 23:30:37 -0700968 group.id(),
969 group.deviceId());
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -0700970 //Removal from groupid based map will happen in the
971 //map update listener
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -0700972 getGroupStoreKeyMap().remove(new GroupStoreKeyMapKey(existing.deviceId(),
973 existing.appCookie()));
alshabib10580802015-02-18 18:30:33 -0800974 notifyDelegate(new GroupEvent(Type.GROUP_REMOVED, existing));
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700975 } else {
976 log.warn("removeGroupEntry for {} in device{} is "
alshabibb0285992016-03-28 23:30:37 -0700977 + "not existing in our maps",
978 group.id(),
979 group.deviceId());
alshabib10580802015-02-18 18:30:33 -0800980 }
981 }
982
Victor Silva4e8b7832016-08-17 17:11:19 -0300983 private void purgeGroupEntries(Set<Entry<GroupStoreKeyMapKey, StoredGroupEntry>> entries) {
984 entries.forEach(entry -> {
985 groupStoreEntriesByKey.remove(entry.getKey());
986 });
987 }
988
alshabib10580802015-02-18 18:30:33 -0800989 @Override
Charles Chan0c7c43b2016-01-14 17:39:20 -0800990 public void purgeGroupEntry(DeviceId deviceId) {
Victor Silva4e8b7832016-08-17 17:11:19 -0300991 Set<Entry<GroupStoreKeyMapKey, StoredGroupEntry>> entriesPendingRemove =
Charles Chan0c7c43b2016-01-14 17:39:20 -0800992 new HashSet<>();
993
Madan Jampani0b847532016-03-03 13:44:15 -0800994 getGroupStoreKeyMap().entrySet().stream()
Charles Chan0c7c43b2016-01-14 17:39:20 -0800995 .filter(entry -> entry.getKey().deviceId().equals(deviceId))
Victor Silva4e8b7832016-08-17 17:11:19 -0300996 .forEach(entriesPendingRemove::add);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800997
Victor Silva4e8b7832016-08-17 17:11:19 -0300998 purgeGroupEntries(entriesPendingRemove);
999 }
1000
1001 @Override
1002 public void purgeGroupEntries() {
1003 purgeGroupEntries(getGroupStoreKeyMap().entrySet());
Charles Chan0c7c43b2016-01-14 17:39:20 -08001004 }
1005
1006 @Override
alshabib10580802015-02-18 18:30:33 -08001007 public void deviceInitialAuditCompleted(DeviceId deviceId,
1008 boolean completed) {
1009 synchronized (deviceAuditStatus) {
1010 if (completed) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001011 log.debug("AUDIT completed for device {}",
1012 deviceId);
alshabib10580802015-02-18 18:30:33 -08001013 deviceAuditStatus.put(deviceId, true);
1014 // Execute all pending group requests
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001015 List<StoredGroupEntry> pendingGroupRequests =
1016 getPendingGroupKeyTable().values()
alshabibb0285992016-03-28 23:30:37 -07001017 .stream()
1018 .filter(g -> g.deviceId().equals(deviceId))
1019 .collect(Collectors.toList());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001020 log.debug("processing pending group add requests for device {} and number of pending requests {}",
alshabibb0285992016-03-28 23:30:37 -07001021 deviceId,
1022 pendingGroupRequests.size());
1023 for (Group group : pendingGroupRequests) {
alshabib10580802015-02-18 18:30:33 -08001024 GroupDescription tmp = new DefaultGroupDescription(
1025 group.deviceId(),
1026 group.type(),
1027 group.buckets(),
1028 group.appCookie(),
Saurav Das100e3b82015-04-30 11:12:10 -07001029 group.givenGroupId(),
alshabib10580802015-02-18 18:30:33 -08001030 group.appId());
1031 storeGroupDescriptionInternal(tmp);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001032 getPendingGroupKeyTable().
alshabibb0285992016-03-28 23:30:37 -07001033 remove(new GroupStoreKeyMapKey(deviceId, group.appCookie()));
alshabib10580802015-02-18 18:30:33 -08001034 }
alshabib10580802015-02-18 18:30:33 -08001035 } else {
Thomas Vachuskac40d4632015-04-09 16:55:03 -07001036 Boolean audited = deviceAuditStatus.get(deviceId);
1037 if (audited != null && audited) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001038 log.debug("Clearing AUDIT status for device {}", deviceId);
alshabib10580802015-02-18 18:30:33 -08001039 deviceAuditStatus.put(deviceId, false);
1040 }
1041 }
1042 }
1043 }
1044
1045 @Override
1046 public boolean deviceInitialAuditStatus(DeviceId deviceId) {
1047 synchronized (deviceAuditStatus) {
Thomas Vachuskac40d4632015-04-09 16:55:03 -07001048 Boolean audited = deviceAuditStatus.get(deviceId);
1049 return audited != null && audited;
alshabib10580802015-02-18 18:30:33 -08001050 }
1051 }
1052
1053 @Override
1054 public void groupOperationFailed(DeviceId deviceId, GroupOperation operation) {
1055
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001056 StoredGroupEntry existing = getStoredGroupEntry(deviceId,
1057 operation.groupId());
alshabib10580802015-02-18 18:30:33 -08001058
1059 if (existing == null) {
1060 log.warn("No group entry with ID {} found ", operation.groupId());
1061 return;
1062 }
1063
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001064 log.warn("groupOperationFailed: group operation {} failed"
alshabibb0285992016-03-28 23:30:37 -07001065 + "for group {} in device {} with code {}",
1066 operation.opType(),
1067 existing.id(),
1068 existing.deviceId(),
1069 operation.failureCode());
Saurav Das0fd79d92016-03-07 10:58:36 -08001070 if (operation.failureCode() == GroupOperation.GroupMsgErrorCode.GROUP_EXISTS) {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001071 if (operation.buckets().equals(existing.buckets())) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001072 if (existing.state() == GroupState.PENDING_ADD ||
1073 existing.state() == GroupState.PENDING_ADD_RETRY) {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001074 log.info("GROUP_EXISTS: GroupID and Buckets match for group in pending "
alshabibb0285992016-03-28 23:30:37 -07001075 + "add state - moving to ADDED for group {} in device {}",
1076 existing.id(), deviceId);
Saurav Das8be4e3a2016-03-11 17:19:07 -08001077 addOrUpdateGroupEntry(existing);
1078 return;
1079 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -07001080 log.warn("GROUP_EXISTS: GroupId and Buckets match but existing"
1081 + "group in state: {}", existing.state());
Saurav Das8be4e3a2016-03-11 17:19:07 -08001082 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001083 } else {
1084 log.warn("GROUP EXISTS: Group ID matched but buckets did not. "
1085 + "Operation: {} Existing: {}", operation.buckets(),
1086 existing.buckets());
Saurav Das8be4e3a2016-03-11 17:19:07 -08001087 }
Saurav Das0fd79d92016-03-07 10:58:36 -08001088 }
alshabib10580802015-02-18 18:30:33 -08001089 switch (operation.opType()) {
1090 case ADD:
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001091 if (existing.state() == GroupState.PENDING_ADD) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001092 notifyDelegate(new GroupEvent(Type.GROUP_ADD_FAILED, existing));
1093 log.warn("groupOperationFailed: cleaningup "
alshabibb0285992016-03-28 23:30:37 -07001094 + "group {} from store in device {}....",
1095 existing.id(),
1096 existing.deviceId());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001097 //Removal from groupid based map will happen in the
1098 //map update listener
1099 getGroupStoreKeyMap().remove(new GroupStoreKeyMapKey(existing.deviceId(),
1100 existing.appCookie()));
1101 }
alshabib10580802015-02-18 18:30:33 -08001102 break;
1103 case MODIFY:
1104 notifyDelegate(new GroupEvent(Type.GROUP_UPDATE_FAILED, existing));
1105 break;
1106 case DELETE:
1107 notifyDelegate(new GroupEvent(Type.GROUP_REMOVE_FAILED, existing));
1108 break;
1109 default:
1110 log.warn("Unknown group operation type {}", operation.opType());
1111 }
alshabib10580802015-02-18 18:30:33 -08001112 }
1113
1114 @Override
1115 public void addOrUpdateExtraneousGroupEntry(Group group) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001116 log.debug("add/update extraneous group entry {} in device {}",
alshabibb0285992016-03-28 23:30:37 -07001117 group.id(),
1118 group.deviceId());
alshabib10580802015-02-18 18:30:33 -08001119 ConcurrentMap<GroupId, Group> extraneousIdTable =
1120 getExtraneousGroupIdTable(group.deviceId());
1121 extraneousIdTable.put(group.id(), group);
Srikanth Vavilapallie48b3cf2015-07-06 11:43:07 -07001122 // Don't remove the extraneous groups, instead re-use it when
1123 // a group request comes with the same set of buckets
alshabib10580802015-02-18 18:30:33 -08001124 }
1125
1126 @Override
1127 public void removeExtraneousGroupEntry(Group group) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001128 log.debug("remove extraneous group entry {} of device {} from store",
alshabibb0285992016-03-28 23:30:37 -07001129 group.id(),
1130 group.deviceId());
alshabib10580802015-02-18 18:30:33 -08001131 ConcurrentMap<GroupId, Group> extraneousIdTable =
1132 getExtraneousGroupIdTable(group.deviceId());
1133 extraneousIdTable.remove(group.id());
1134 }
1135
1136 @Override
1137 public Iterable<Group> getExtraneousGroups(DeviceId deviceId) {
1138 // flatten and make iterator unmodifiable
1139 return FluentIterable.from(
1140 getExtraneousGroupIdTable(deviceId).values());
1141 }
1142
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001143 /**
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -07001144 * Map handler to receive any events when the group key map is updated.
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001145 */
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -07001146 private class GroupStoreKeyMapListener implements
Madan Jampani0b847532016-03-03 13:44:15 -08001147 MapEventListener<GroupStoreKeyMapKey, StoredGroupEntry> {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001148
1149 @Override
Madan Jampani0b847532016-03-03 13:44:15 -08001150 public void event(MapEvent<GroupStoreKeyMapKey, StoredGroupEntry> mapEvent) {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001151 GroupEvent groupEvent = null;
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001152 GroupStoreKeyMapKey key = mapEvent.key();
Madan Jampani0b847532016-03-03 13:44:15 -08001153 StoredGroupEntry group = Versioned.valueOrNull(mapEvent.newValue());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001154 if ((key == null) && (group == null)) {
1155 log.error("GroupStoreKeyMapListener: Received "
alshabibb0285992016-03-28 23:30:37 -07001156 + "event {} with null entry", mapEvent.type());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001157 return;
1158 } else if (group == null) {
1159 group = getGroupIdTable(key.deviceId()).values()
1160 .stream()
1161 .filter((storedGroup) -> (storedGroup.appCookie().equals(key.appCookie)))
Yuta HIGUCHI6e5f4702016-11-21 11:42:11 -08001162 .findFirst().orElse(null);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001163 if (group == null) {
1164 log.error("GroupStoreKeyMapListener: Received "
alshabibb0285992016-03-28 23:30:37 -07001165 + "event {} with null entry... can not process", mapEvent.type());
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001166 return;
1167 }
1168 }
1169 log.trace("received groupid map event {} for id {} in device {}",
1170 mapEvent.type(),
1171 group.id(),
jaegonkim68e080c2016-12-01 22:31:01 +09001172 (key != null ? key.deviceId() : null));
Madan Jampani0b847532016-03-03 13:44:15 -08001173 if (mapEvent.type() == MapEvent.Type.INSERT || mapEvent.type() == MapEvent.Type.UPDATE) {
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -07001174 // Update the group ID table
1175 getGroupIdTable(group.deviceId()).put(group.id(), group);
Madan Jampani0b847532016-03-03 13:44:15 -08001176 StoredGroupEntry value = Versioned.valueOrNull(mapEvent.newValue());
1177 if (value.state() == Group.GroupState.ADDED) {
1178 if (value.isGroupStateAddedFirstTime()) {
1179 groupEvent = new GroupEvent(Type.GROUP_ADDED, value);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001180 log.trace("Received first time GROUP_ADDED state update for id {} in device {}",
alshabibb0285992016-03-28 23:30:37 -07001181 group.id(),
1182 group.deviceId());
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001183 } else {
Madan Jampani0b847532016-03-03 13:44:15 -08001184 groupEvent = new GroupEvent(Type.GROUP_UPDATED, value);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001185 log.trace("Received following GROUP_ADDED state update for id {} in device {}",
alshabibb0285992016-03-28 23:30:37 -07001186 group.id(),
1187 group.deviceId());
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001188 }
1189 }
Madan Jampani0b847532016-03-03 13:44:15 -08001190 } else if (mapEvent.type() == MapEvent.Type.REMOVE) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001191 groupEvent = new GroupEvent(Type.GROUP_REMOVED, group);
Srikanth Vavilapalli6a9d4e42015-03-30 19:41:56 -07001192 // Remove the entry from the group ID table
1193 getGroupIdTable(group.deviceId()).remove(group.id(), group);
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001194 }
1195
1196 if (groupEvent != null) {
1197 notifyDelegate(groupEvent);
1198 }
1199 }
1200 }
Madan Jampani01e05fb2015-08-13 13:29:36 -07001201
helenyrwua1c41152016-08-18 16:16:14 -07001202 private void processGroupMessage(GroupStoreMessage message) {
1203 if (message.type() == GroupStoreMessage.Type.FAILOVER) {
1204 // FIXME: groupStoreEntriesByKey inaccessible here
1205 getGroupIdTable(message.deviceId()).values()
1206 .stream()
1207 .filter((storedGroup) -> (storedGroup.appCookie().equals(message.appCookie())))
1208 .findFirst().ifPresent(group -> notifyDelegate(new GroupEvent(Type.GROUP_BUCKET_FAILOVER, group)));
1209 }
1210 }
1211
Madan Jampani01e05fb2015-08-13 13:29:36 -07001212 private void process(GroupStoreMessage groupOp) {
1213 log.debug("Received remote group operation {} request for device {}",
alshabibb0285992016-03-28 23:30:37 -07001214 groupOp.type(),
1215 groupOp.deviceId());
1216 if (!mastershipService.isLocalMaster(groupOp.deviceId())) {
1217 log.warn("This node is not MASTER for device {}", groupOp.deviceId());
1218 return;
1219 }
1220 if (groupOp.type() == GroupStoreMessage.Type.ADD) {
1221 storeGroupDescriptionInternal(groupOp.groupDesc());
1222 } else if (groupOp.type() == GroupStoreMessage.Type.UPDATE) {
1223 updateGroupDescriptionInternal(groupOp.deviceId(),
1224 groupOp.appCookie(),
1225 groupOp.updateType(),
1226 groupOp.updateBuckets(),
1227 groupOp.newAppCookie());
1228 } else if (groupOp.type() == GroupStoreMessage.Type.DELETE) {
1229 deleteGroupDescriptionInternal(groupOp.deviceId(),
1230 groupOp.appCookie());
1231 }
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001232 }
1233
1234 /**
1235 * Flattened map key to be used to store group entries.
1236 */
Ray Milkeyb3c5ce22015-08-10 09:07:36 -07001237 protected static class GroupStoreMapKey {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001238 private final DeviceId deviceId;
1239
1240 public GroupStoreMapKey(DeviceId deviceId) {
1241 this.deviceId = deviceId;
1242 }
1243
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001244 public DeviceId deviceId() {
1245 return deviceId;
1246 }
1247
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001248 @Override
1249 public boolean equals(Object o) {
1250 if (this == o) {
1251 return true;
1252 }
1253 if (!(o instanceof GroupStoreMapKey)) {
1254 return false;
1255 }
1256 GroupStoreMapKey that = (GroupStoreMapKey) o;
1257 return this.deviceId.equals(that.deviceId);
1258 }
1259
1260 @Override
1261 public int hashCode() {
1262 int result = 17;
1263
1264 result = 31 * result + Objects.hash(this.deviceId);
1265
1266 return result;
1267 }
1268 }
1269
Ray Milkeyb3c5ce22015-08-10 09:07:36 -07001270 protected static class GroupStoreKeyMapKey extends GroupStoreMapKey {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001271 private final GroupKey appCookie;
alshabibb0285992016-03-28 23:30:37 -07001272
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001273 public GroupStoreKeyMapKey(DeviceId deviceId,
1274 GroupKey appCookie) {
1275 super(deviceId);
1276 this.appCookie = appCookie;
1277 }
1278
1279 @Override
1280 public boolean equals(Object o) {
1281 if (this == o) {
1282 return true;
1283 }
1284 if (!(o instanceof GroupStoreKeyMapKey)) {
1285 return false;
1286 }
1287 GroupStoreKeyMapKey that = (GroupStoreKeyMapKey) o;
1288 return (super.equals(that) &&
1289 this.appCookie.equals(that.appCookie));
1290 }
1291
1292 @Override
1293 public int hashCode() {
1294 int result = 17;
1295
1296 result = 31 * result + super.hashCode() + Objects.hash(this.appCookie);
1297
1298 return result;
1299 }
1300 }
1301
Ray Milkeyb3c5ce22015-08-10 09:07:36 -07001302 protected static class GroupStoreIdMapKey extends GroupStoreMapKey {
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001303 private final GroupId groupId;
alshabibb0285992016-03-28 23:30:37 -07001304
Srikanth Vavilapalli717361f2015-03-16 12:06:04 -07001305 public GroupStoreIdMapKey(DeviceId deviceId,
1306 GroupId groupId) {
1307 super(deviceId);
1308 this.groupId = groupId;
1309 }
1310
1311 @Override
1312 public boolean equals(Object o) {
1313 if (this == o) {
1314 return true;
1315 }
1316 if (!(o instanceof GroupStoreIdMapKey)) {
1317 return false;
1318 }
1319 GroupStoreIdMapKey that = (GroupStoreIdMapKey) o;
1320 return (super.equals(that) &&
1321 this.groupId.equals(that.groupId));
1322 }
1323
1324 @Override
1325 public int hashCode() {
1326 int result = 17;
1327
1328 result = 31 * result + super.hashCode() + Objects.hash(this.groupId);
1329
1330 return result;
1331 }
1332 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001333
1334 @Override
1335 public void pushGroupMetrics(DeviceId deviceId,
1336 Collection<Group> groupEntries) {
1337 boolean deviceInitialAuditStatus =
1338 deviceInitialAuditStatus(deviceId);
1339 Set<Group> southboundGroupEntries =
1340 Sets.newHashSet(groupEntries);
1341 Set<StoredGroupEntry> storedGroupEntries =
1342 Sets.newHashSet(getStoredGroups(deviceId));
1343 Set<Group> extraneousStoredEntries =
1344 Sets.newHashSet(getExtraneousGroups(deviceId));
1345
Sho SHIMIZU695bac62016-08-15 12:41:59 -07001346 if (log.isTraceEnabled()) {
1347 log.trace("pushGroupMetrics: Displaying all ({}) southboundGroupEntries for device {}",
1348 southboundGroupEntries.size(),
1349 deviceId);
1350 for (Group group : southboundGroupEntries) {
1351 log.trace("Group {} in device {}", group, deviceId);
1352 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001353
Sho SHIMIZU695bac62016-08-15 12:41:59 -07001354 log.trace("Displaying all ({}) stored group entries for device {}",
1355 storedGroupEntries.size(),
1356 deviceId);
1357 for (StoredGroupEntry group : storedGroupEntries) {
1358 log.trace("Stored Group {} for device {}", group, deviceId);
1359 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001360 }
1361
alshabibb0285992016-03-28 23:30:37 -07001362 garbageCollect(deviceId, southboundGroupEntries, storedGroupEntries);
1363
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001364 for (Iterator<Group> it2 = southboundGroupEntries.iterator(); it2.hasNext();) {
1365 Group group = it2.next();
1366 if (storedGroupEntries.remove(group)) {
1367 // we both have the group, let's update some info then.
1368 log.trace("Group AUDIT: group {} exists in both planes for device {}",
alshabibb0285992016-03-28 23:30:37 -07001369 group.id(), deviceId);
1370
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001371 groupAdded(group);
1372 it2.remove();
1373 }
1374 }
1375 for (Group group : southboundGroupEntries) {
1376 if (getGroup(group.deviceId(), group.id()) != null) {
1377 // There is a group existing with the same id
1378 // It is possible that group update is
1379 // in progress while we got a stale info from switch
1380 if (!storedGroupEntries.remove(getGroup(
alshabibb0285992016-03-28 23:30:37 -07001381 group.deviceId(), group.id()))) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001382 log.warn("Group AUDIT: Inconsistent state:"
alshabibb0285992016-03-28 23:30:37 -07001383 + "Group exists in ID based table while "
1384 + "not present in key based table");
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001385 }
1386 } else {
1387 // there are groups in the switch that aren't in the store
1388 log.debug("Group AUDIT: extraneous group {} exists in data plane for device {}",
alshabibb0285992016-03-28 23:30:37 -07001389 group.id(), deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001390 extraneousStoredEntries.remove(group);
Kavitha Alagesanc56cded2017-01-13 10:48:18 +05301391 if (allowExtraneousGroups) {
1392 extraneousGroup(group);
1393 } else {
1394 notifyDelegate(new GroupEvent(Type.GROUP_REMOVE_REQUESTED, group));
1395 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001396 }
1397 }
1398 for (Group group : storedGroupEntries) {
1399 // there are groups in the store that aren't in the switch
1400 log.debug("Group AUDIT: group {} missing in data plane for device {}",
alshabibb0285992016-03-28 23:30:37 -07001401 group.id(), deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001402 groupMissing(group);
1403 }
1404 for (Group group : extraneousStoredEntries) {
1405 // there are groups in the extraneous store that
1406 // aren't in the switch
Saurav Das0fd79d92016-03-07 10:58:36 -08001407 log.debug("Group AUDIT: clearing extraneous group {} from store for device {}",
alshabibb0285992016-03-28 23:30:37 -07001408 group.id(), deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001409 removeExtraneousGroupEntry(group);
1410 }
1411
1412 if (!deviceInitialAuditStatus) {
Saurav Das0fd79d92016-03-07 10:58:36 -08001413 log.info("Group AUDIT: Setting device {} initial AUDIT completed",
alshabibb0285992016-03-28 23:30:37 -07001414 deviceId);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001415 deviceInitialAuditCompleted(deviceId, true);
1416 }
1417 }
1418
helenyrwu89470f12016-08-12 13:18:10 -07001419 @Override
1420 public void notifyOfFailovers(Collection<Group> failoverGroups) {
helenyrwu89470f12016-08-12 13:18:10 -07001421 failoverGroups.forEach(group -> {
1422 if (group.type() == Group.Type.FAILOVER) {
helenyrwua1c41152016-08-18 16:16:14 -07001423 groupTopic.publish(GroupStoreMessage.createGroupFailoverMsg(
1424 group.deviceId(), group));
helenyrwu89470f12016-08-12 13:18:10 -07001425 }
1426 });
helenyrwu89470f12016-08-12 13:18:10 -07001427 }
1428
alshabibb0285992016-03-28 23:30:37 -07001429 private void garbageCollect(DeviceId deviceId,
1430 Set<Group> southboundGroupEntries,
1431 Set<StoredGroupEntry> storedGroupEntries) {
1432 if (!garbageCollect) {
1433 return;
1434 }
1435
1436 Iterator<StoredGroupEntry> it = storedGroupEntries.iterator();
1437 while (it.hasNext()) {
1438 StoredGroupEntry group = it.next();
1439 if (group.state() != GroupState.PENDING_DELETE && checkGroupRefCount(group)) {
1440 log.debug("Garbage collecting group {} on {}", group, deviceId);
1441 deleteGroupDescription(deviceId, group.appCookie());
1442 southboundGroupEntries.remove(group);
1443 it.remove();
1444 }
1445 }
1446 }
1447
1448 private boolean checkGroupRefCount(Group group) {
1449 return (group.referenceCount() == 0 && group.age() >= gcThresh);
1450 }
1451
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001452 private void groupMissing(Group group) {
1453 switch (group.state()) {
1454 case PENDING_DELETE:
1455 log.debug("Group {} delete confirmation from device {}",
1456 group, group.deviceId());
1457 removeGroupEntry(group);
1458 break;
1459 case ADDED:
1460 case PENDING_ADD:
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001461 case PENDING_ADD_RETRY:
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001462 case PENDING_UPDATE:
1463 log.debug("Group {} is in store but not on device {}",
1464 group, group.deviceId());
1465 StoredGroupEntry existing =
1466 getStoredGroupEntry(group.deviceId(), group.id());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001467 log.debug("groupMissing: group entry {} in device {} moving from {} to PENDING_ADD_RETRY",
alshabibb0285992016-03-28 23:30:37 -07001468 existing.id(),
1469 existing.deviceId(),
1470 existing.state());
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001471 existing.setState(Group.GroupState.PENDING_ADD_RETRY);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001472 //Re-PUT map entries to trigger map update events
1473 getGroupStoreKeyMap().
alshabibb0285992016-03-28 23:30:37 -07001474 put(new GroupStoreKeyMapKey(existing.deviceId(),
1475 existing.appCookie()), existing);
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001476 notifyDelegate(new GroupEvent(GroupEvent.Type.GROUP_ADD_REQUESTED,
1477 group));
1478 break;
1479 default:
1480 log.debug("Group {} has not been installed.", group);
1481 break;
1482 }
1483 }
1484
1485 private void extraneousGroup(Group group) {
Saurav Das0fd79d92016-03-07 10:58:36 -08001486 log.trace("Group {} is on device {} but not in store.",
Srikanth Vavilapalli23181912015-05-04 09:48:09 -07001487 group, group.deviceId());
1488 addOrUpdateExtraneousGroupEntry(group);
1489 }
1490
1491 private void groupAdded(Group group) {
1492 log.trace("Group {} Added or Updated in device {}",
1493 group, group.deviceId());
1494 addOrUpdateGroupEntry(group);
1495 }
alshabib10580802015-02-18 18:30:33 -08001496}