blob: 157d3a601016b5629f1b553d7559d05f9bc64470 [file] [log] [blame]
Madan Jampani9b37d572014-11-12 11:53:24 -08001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
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 */
16
17package org.onlab.onos.store.service.impl;
18
19import java.io.IOException;
20import java.util.HashMap;
21import java.util.Map;
22import java.util.Objects;
23import java.util.concurrent.TimeUnit;
24import java.util.concurrent.atomic.AtomicBoolean;
25
26import net.jodah.expiringmap.ExpiringMap;
27import net.jodah.expiringmap.ExpiringMap.ExpirationListener;
28import net.jodah.expiringmap.ExpiringMap.ExpirationPolicy;
29import net.kuujo.copycat.cluster.Member;
30import net.kuujo.copycat.event.EventHandler;
31import net.kuujo.copycat.event.LeaderElectEvent;
32
Madan Jampanidef2c652014-11-12 13:50:10 -080033import org.onlab.onos.cluster.ControllerNode;
Madan Jampani9b37d572014-11-12 11:53:24 -080034import org.onlab.onos.store.cluster.messaging.ClusterCommunicationService;
35import org.onlab.onos.store.cluster.messaging.ClusterMessage;
36import org.onlab.onos.store.cluster.messaging.MessageSubject;
37import org.onlab.onos.store.service.DatabaseService;
38import org.onlab.onos.store.service.VersionedValue;
Madan Jampanidef2c652014-11-12 13:50:10 -080039import org.onlab.onos.store.service.impl.DatabaseStateMachine.State;
40import org.onlab.onos.store.service.impl.DatabaseStateMachine.TableMetadata;
Madan Jampani9b37d572014-11-12 11:53:24 -080041import org.slf4j.Logger;
42import org.slf4j.LoggerFactory;
43
44/**
45 * Plugs into the database update stream and track the TTL of entries added to
46 * the database. For tables with pre-configured finite TTL, this class has
47 * mechanisms for expiring (deleting) old, expired entries from the database.
48 */
49public class DatabaseEntryExpirationTracker implements
50 DatabaseUpdateEventListener, EventHandler<LeaderElectEvent> {
51
52 private final Logger log = LoggerFactory.getLogger(getClass());
53
54 public static final MessageSubject DATABASE_UPDATES = new MessageSubject(
55 "database-update-event");
56
Madan Jampanidef2c652014-11-12 13:50:10 -080057 private final DatabaseService databaseService;
58 private final ClusterCommunicationService clusterCommunicator;
Madan Jampani9b37d572014-11-12 11:53:24 -080059
60 private final Member localMember;
Madan Jampanidef2c652014-11-12 13:50:10 -080061 private final ControllerNode localNode;
Madan Jampani9b37d572014-11-12 11:53:24 -080062 private final AtomicBoolean isLocalMemberLeader = new AtomicBoolean(false);
63
64 private final Map<String, Map<DatabaseRow, VersionedValue>> tableEntryExpirationMap = new HashMap<>();
65
66 private final ExpirationListener<DatabaseRow, VersionedValue> expirationObserver = new ExpirationObserver();
67
Madan Jampanidef2c652014-11-12 13:50:10 -080068 DatabaseEntryExpirationTracker(
69 Member localMember,
70 ControllerNode localNode,
71 ClusterCommunicationService clusterCommunicator,
72 DatabaseService databaseService) {
Madan Jampani9b37d572014-11-12 11:53:24 -080073 this.localMember = localMember;
Madan Jampanidef2c652014-11-12 13:50:10 -080074 this.localNode = localNode;
75 this.clusterCommunicator = clusterCommunicator;
76 this.databaseService = databaseService;
Madan Jampani9b37d572014-11-12 11:53:24 -080077 }
78
79 @Override
80 public void tableModified(TableModificationEvent event) {
Madan Jampanidef2c652014-11-12 13:50:10 -080081 if (!tableEntryExpirationMap.containsKey(event.tableName())) {
82 return;
83 }
84
Madan Jampani9b37d572014-11-12 11:53:24 -080085 DatabaseRow row = new DatabaseRow(event.tableName(), event.key());
86 Map<DatabaseRow, VersionedValue> map = tableEntryExpirationMap
87 .get(event.tableName());
88
89 switch (event.type()) {
90 case ROW_DELETED:
91 if (isLocalMemberLeader.get()) {
92 try {
Madan Jampanidef2c652014-11-12 13:50:10 -080093 clusterCommunicator.broadcast(new ClusterMessage(
94 localNode.id(), DATABASE_UPDATES,
Madan Jampani9b37d572014-11-12 11:53:24 -080095 DatabaseStateMachine.SERIALIZER.encode(event)));
96 } catch (IOException e) {
97 log.error(
98 "Failed to broadcast a database table modification event.",
99 e);
100 }
101 }
102 break;
103 case ROW_ADDED:
104 case ROW_UPDATED:
105 map.put(row, null);
106 break;
107 default:
108 break;
109 }
110 }
111
112 @Override
Madan Jampanidef2c652014-11-12 13:50:10 -0800113 public void tableCreated(TableMetadata metadata) {
114 if (metadata.expireOldEntries()) {
115 tableEntryExpirationMap.put(metadata.tableName(), ExpiringMap.builder()
116 .expiration(metadata.ttlMillis(), TimeUnit.SECONDS)
Madan Jampani9b37d572014-11-12 11:53:24 -0800117 .expirationListener(expirationObserver)
118 // FIXME: make the expiration policy configurable.
119 .expirationPolicy(ExpirationPolicy.CREATED).build());
120 }
121 }
122
123 @Override
124 public void tableDeleted(String tableName) {
125 tableEntryExpirationMap.remove(tableName);
126 }
127
128 private class ExpirationObserver implements
129 ExpirationListener<DatabaseRow, VersionedValue> {
130 @Override
131 public void expired(DatabaseRow key, VersionedValue value) {
132 try {
133 if (isLocalMemberLeader.get()) {
134 if (!databaseService.removeIfVersionMatches(key.tableName,
135 key.key, value.version())) {
136 log.info("Entry in the database changed before right its TTL expiration.");
137 }
138 } else {
139 // If this node is not the current leader, we should never
140 // let the expiring entries drop off
141 // Under stable conditions (i.e no leadership switch) the
142 // current leader will initiate
143 // a database remove and this instance will get notified
144 // of a tableModification event causing it to remove from
145 // the map.
146 Map<DatabaseRow, VersionedValue> map = tableEntryExpirationMap
147 .get(key.tableName);
148 if (map != null) {
149 map.put(key, value);
150 }
151 }
152
153 } catch (Exception e) {
154 log.warn(
155 "Failed to delete entry from the database after ttl expiration. Will retry eviction",
156 e);
157 tableEntryExpirationMap.get(key.tableName).put(
158 new DatabaseRow(key.tableName, key.key), value);
159 }
160 }
161 }
162
163 @Override
164 public void handle(LeaderElectEvent event) {
165 if (localMember.equals(event.leader())) {
166 isLocalMemberLeader.set(true);
167 }
168 }
169
170 /**
171 * Wrapper class for a database row identifier.
172 */
173 private class DatabaseRow {
174
175 String tableName;
176 String key;
177
178 public DatabaseRow(String tableName, String key) {
179 this.tableName = tableName;
180 this.key = key;
181 }
182
183 @Override
184 public boolean equals(Object obj) {
185 if (this == obj) {
186 return true;
187 }
188 if (!(obj instanceof DatabaseRow)) {
189 return false;
190 }
191 DatabaseRow that = (DatabaseRow) obj;
192
193 return Objects.equals(this.tableName, that.tableName)
194 && Objects.equals(this.key, that.key);
195 }
196
197 @Override
198 public int hashCode() {
199 return Objects.hash(tableName, key);
200 }
201 }
Madan Jampanidef2c652014-11-12 13:50:10 -0800202
203 @Override
204 public void snapshotInstalled(State state) {
205 if (!tableEntryExpirationMap.isEmpty()) {
206 return;
207 }
208 for (String tableName : state.getTableNames()) {
209
210 TableMetadata metadata = state.getTableMetadata(tableName);
211 if (!metadata.expireOldEntries()) {
212 continue;
213 }
214
215 Map<DatabaseRow, VersionedValue> tableExpirationMap = ExpiringMap.builder()
216 .expiration(metadata.ttlMillis(), TimeUnit.MILLISECONDS)
217 .expirationListener(expirationObserver)
218 .expirationPolicy(ExpirationPolicy.CREATED).build();
219 for (Map.Entry<String, VersionedValue> entry : state.getTable(tableName).entrySet()) {
220 tableExpirationMap.put(new DatabaseRow(tableName, entry.getKey()), entry.getValue());
221 }
222
223 tableEntryExpirationMap.put(tableName, tableExpirationMap);
224 }
225 }
Madan Jampani9b37d572014-11-12 11:53:24 -0800226}