blob: 6ddeea9ace94f1e3945793c866309d6eaf6a5abe [file] [log] [blame]
Madan Jampani25461112015-02-17 14:17:29 -08001/*
2 * Copyright 2015 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
Madan Jampani09342702015-02-05 23:32:40 -080017package org.onosproject.store.consistent.impl;
18
Jonathan Hart054da972015-02-18 17:30:28 -080019import com.google.common.collect.Sets;
Madan Jampanid14166a2015-02-24 17:37:51 -080020
Madan Jampani09342702015-02-05 23:32:40 -080021import net.kuujo.copycat.cluster.ClusterConfig;
Jonathan Hart054da972015-02-18 17:30:28 -080022import net.kuujo.copycat.cluster.Member;
Madan Jampani09342702015-02-05 23:32:40 -080023import net.kuujo.copycat.log.FileLog;
24import net.kuujo.copycat.netty.NettyTcpProtocol;
25import net.kuujo.copycat.protocol.Consistency;
Madan Jampanid14166a2015-02-24 17:37:51 -080026
Madan Jampani09342702015-02-05 23:32:40 -080027import org.apache.felix.scr.annotations.Activate;
28import org.apache.felix.scr.annotations.Component;
29import org.apache.felix.scr.annotations.Deactivate;
30import org.apache.felix.scr.annotations.Reference;
31import org.apache.felix.scr.annotations.ReferenceCardinality;
32import org.apache.felix.scr.annotations.Service;
33import org.onosproject.cluster.ClusterService;
Madan Jampani0cb00672015-02-27 00:27:22 -080034import org.onosproject.store.cluster.impl.NodeInfo;
Madan Jampani7c521002015-03-23 12:23:01 -070035import org.onosproject.store.service.AsyncConsistentMap;
Madan Jampani393e0f02015-02-12 07:35:39 +053036import org.onosproject.store.service.ConsistentMap;
Jonathan Hart054da972015-02-18 17:30:28 -080037import org.onosproject.store.service.PartitionInfo;
Madan Jampani393e0f02015-02-12 07:35:39 +053038import org.onosproject.store.service.Serializer;
Jonathan Hart054da972015-02-18 17:30:28 -080039import org.onosproject.store.service.StorageAdminService;
Madan Jampani393e0f02015-02-12 07:35:39 +053040import org.onosproject.store.service.StorageService;
Madan Jampani64689552015-02-17 10:00:27 -080041import org.onosproject.store.service.TransactionContext;
Madan Jampani09342702015-02-05 23:32:40 -080042import org.slf4j.Logger;
43
Jonathan Hart054da972015-02-18 17:30:28 -080044import java.io.File;
45import java.io.IOException;
46import java.util.List;
47import java.util.Map;
48import java.util.Set;
Madan Jampanid14166a2015-02-24 17:37:51 -080049import java.util.concurrent.CountDownLatch;
50import java.util.concurrent.TimeUnit;
Jonathan Hart054da972015-02-18 17:30:28 -080051import java.util.stream.Collectors;
52
53import static org.slf4j.LoggerFactory.getLogger;
Madan Jampani09342702015-02-05 23:32:40 -080054
55/**
56 * Database manager.
57 */
58@Component(immediate = true, enabled = true)
59@Service
Jonathan Hart054da972015-02-18 17:30:28 -080060public class DatabaseManager implements StorageService, StorageAdminService {
Madan Jampani09342702015-02-05 23:32:40 -080061
62 private final Logger log = getLogger(getClass());
63 private PartitionedDatabase partitionedDatabase;
64 public static final int COPYCAT_TCP_PORT = 7238; // 7238 = RAFT
65 private static final String CONFIG_DIR = "../config";
66 private static final String PARTITION_DEFINITION_FILE = "tablets.json";
Madan Jampanid14166a2015-02-24 17:37:51 -080067 private static final int DATABASE_STARTUP_TIMEOUT_SEC = 60;
Madan Jampani09342702015-02-05 23:32:40 -080068
Madan Jampanife3a9a72015-03-13 16:32:26 -070069 private final PartitionedDatabaseConfig databaseConfig = new PartitionedDatabaseConfig();
70
Madan Jampani09342702015-02-05 23:32:40 -080071 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
72 protected ClusterService clusterService;
73
Madan Jampani0cb00672015-02-27 00:27:22 -080074 protected String nodeToUri(NodeInfo node) {
75 return String.format("tcp://%s:%d", node.getIp(), COPYCAT_TCP_PORT);
Madan Jampani09342702015-02-05 23:32:40 -080076 }
77
78 @Activate
79 public void activate() {
80
81 final String logDir = System.getProperty("karaf.data", "./data");
82
83 // load database configuration
84 File file = new File(CONFIG_DIR, PARTITION_DEFINITION_FILE);
85 log.info("Loading database definition: {}", file.getAbsolutePath());
86
Madan Jampani0cb00672015-02-27 00:27:22 -080087 Map<String, Set<NodeInfo>> partitionMap;
Madan Jampani09342702015-02-05 23:32:40 -080088 try {
Madan Jampani0cb00672015-02-27 00:27:22 -080089 DatabaseDefinitionStore databaseDef = new DatabaseDefinitionStore(file);
90 partitionMap = databaseDef.read().getPartitions();
Madan Jampani09342702015-02-05 23:32:40 -080091 } catch (IOException e) {
Madan Jampani09342702015-02-05 23:32:40 -080092 throw new IllegalStateException("Failed to load database config", e);
93 }
94
95 String[] activeNodeUris = partitionMap.values()
96 .stream()
97 .reduce((s1, s2) -> Sets.union(s1, s2))
98 .get()
99 .stream()
100 .map(this::nodeToUri)
101 .toArray(String[]::new);
102
Madan Jampani0cb00672015-02-27 00:27:22 -0800103 String localNodeUri = nodeToUri(NodeInfo.of(clusterService.getLocalNode()));
Madan Jampani09342702015-02-05 23:32:40 -0800104
105 ClusterConfig clusterConfig = new ClusterConfig()
Madan Jampani393e0f02015-02-12 07:35:39 +0530106 .withProtocol(new NettyTcpProtocol()
107 .withSsl(false)
108 .withConnectTimeout(60000)
109 .withAcceptBacklog(1024)
110 .withTrafficClass(-1)
111 .withSoLinger(-1)
112 .withReceiveBufferSize(32768)
113 .withSendBufferSize(8192)
114 .withThreads(1))
Thomas Vachuska0249b532015-02-20 16:46:18 -0800115 .withElectionTimeout(3000)
116 .withHeartbeatInterval(1500)
Madan Jampani09342702015-02-05 23:32:40 -0800117 .withMembers(activeNodeUris)
118 .withLocalMember(localNodeUri);
119
Madan Jampani09342702015-02-05 23:32:40 -0800120 partitionMap.forEach((name, nodes) -> {
121 Set<String> replicas = nodes.stream().map(this::nodeToUri).collect(Collectors.toSet());
122 DatabaseConfig partitionConfig = new DatabaseConfig()
Thomas Vachuska0249b532015-02-20 16:46:18 -0800123 .withElectionTimeout(3000)
124 .withHeartbeatInterval(1500)
Madan Jampani09342702015-02-05 23:32:40 -0800125 .withConsistency(Consistency.STRONG)
Madan Jampani393e0f02015-02-12 07:35:39 +0530126 .withLog(new FileLog()
127 .withDirectory(logDir)
128 .withSegmentSize(1073741824) // 1GB
129 .withFlushOnWrite(true)
130 .withSegmentInterval(Long.MAX_VALUE))
131 .withDefaultSerializer(new DatabaseSerializer())
Madan Jampani09342702015-02-05 23:32:40 -0800132 .withReplicas(replicas);
133 databaseConfig.addPartition(name, partitionConfig);
134 });
135
136 partitionedDatabase = PartitionedDatabaseManager.create("onos-store", clusterConfig, databaseConfig);
137
Madan Jampanid14166a2015-02-24 17:37:51 -0800138 CountDownLatch latch = new CountDownLatch(1);
Madan Jampani09342702015-02-05 23:32:40 -0800139 partitionedDatabase.open().whenComplete((db, error) -> {
140 if (error != null) {
141 log.warn("Failed to open database.", error);
142 } else {
Madan Jampanid14166a2015-02-24 17:37:51 -0800143 latch.countDown();
Madan Jampani09342702015-02-05 23:32:40 -0800144 log.info("Successfully opened database.");
145 }
146 });
Madan Jampanid14166a2015-02-24 17:37:51 -0800147 try {
148 if (!latch.await(DATABASE_STARTUP_TIMEOUT_SEC, TimeUnit.SECONDS)) {
Madan Jampani7f72c3f2015-03-01 17:34:59 -0800149 log.warn("Timed out waiting for database to initialize.");
Madan Jampanid14166a2015-02-24 17:37:51 -0800150 }
151 } catch (InterruptedException e) {
152 Thread.currentThread().interrupt();
153 log.warn("Failed to complete database initialization.");
154 }
Madan Jampani09342702015-02-05 23:32:40 -0800155 log.info("Started");
156 }
157
158 @Deactivate
159 public void deactivate() {
160 partitionedDatabase.close().whenComplete((result, error) -> {
161 if (error != null) {
162 log.warn("Failed to cleanly close database.", error);
163 } else {
164 log.info("Successfully closed database.");
165 }
166 });
167 log.info("Stopped");
168 }
169
170 @Override
Madan Jampani393e0f02015-02-12 07:35:39 +0530171 public <K, V> ConsistentMap<K , V> createConsistentMap(String name, Serializer serializer) {
Madan Jampani7c521002015-03-23 12:23:01 -0700172 return new DefaultConsistentMap<K, V>(name, partitionedDatabase, serializer);
173 }
174
175 @Override
176 public <K, V> AsyncConsistentMap<K , V> createAsyncConsistentMap(String name, Serializer serializer) {
177 return new DefaultAsyncConsistentMap<K, V>(name, partitionedDatabase, serializer);
Madan Jampani09342702015-02-05 23:32:40 -0800178 }
Madan Jampani64689552015-02-17 10:00:27 -0800179
180 @Override
181 public TransactionContext createTransactionContext() {
182 return new DefaultTransactionContext(partitionedDatabase);
183 }
Jonathan Hart054da972015-02-18 17:30:28 -0800184
185 @Override
186 public List<PartitionInfo> getPartitionInfo() {
187 return partitionedDatabase.getRegisteredPartitions()
188 .values()
189 .stream()
Madan Jampanife3a9a72015-03-13 16:32:26 -0700190 .map(db -> toPartitionInfo(db, databaseConfig.partitions().get(db.name())))
Jonathan Hart054da972015-02-18 17:30:28 -0800191 .collect(Collectors.toList());
192 }
193
194 /**
195 * Maps a Raft Database object to a PartitionInfo object.
196 *
197 * @param database database containing input data
198 * @return PartitionInfo object
199 */
Madan Jampanife3a9a72015-03-13 16:32:26 -0700200 private static PartitionInfo toPartitionInfo(Database database, DatabaseConfig dbConfig) {
Jonathan Hart054da972015-02-18 17:30:28 -0800201 return new PartitionInfo(database.name(),
202 database.cluster().term(),
203 database.cluster().members().stream()
204 .map(Member::uri)
Madan Jampanife3a9a72015-03-13 16:32:26 -0700205 .filter(uri -> dbConfig.getReplicas().contains(uri))
Jonathan Hart054da972015-02-18 17:30:28 -0800206 .collect(Collectors.toList()),
207 database.cluster().leader() != null ?
208 database.cluster().leader().uri() : null);
209 }
210}