blob: 09cc645f205d89043930fbc3f44057300b4f5edf [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;
34import org.onosproject.cluster.ControllerNode;
35import org.onosproject.cluster.DefaultControllerNode;
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
69 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
70 protected ClusterService clusterService;
71
72 protected String nodeToUri(ControllerNode node) {
Madan Jampani393e0f02015-02-12 07:35:39 +053073 return String.format("tcp://%s:%d", node.ip(), COPYCAT_TCP_PORT);
Madan Jampani09342702015-02-05 23:32:40 -080074 }
75
76 @Activate
77 public void activate() {
78
79 final String logDir = System.getProperty("karaf.data", "./data");
80
81 // load database configuration
82 File file = new File(CONFIG_DIR, PARTITION_DEFINITION_FILE);
83 log.info("Loading database definition: {}", file.getAbsolutePath());
84
85 DatabaseDefinitionStore databaseDef = new DatabaseDefinitionStore(file);
86 Map<String, Set<DefaultControllerNode>> partitionMap;
87 try {
88 partitionMap = databaseDef.read();
89 } catch (IOException e) {
90 log.error("Failed to load database config {}", file);
91 throw new IllegalStateException("Failed to load database config", e);
92 }
93
94 String[] activeNodeUris = partitionMap.values()
95 .stream()
96 .reduce((s1, s2) -> Sets.union(s1, s2))
97 .get()
98 .stream()
99 .map(this::nodeToUri)
100 .toArray(String[]::new);
101
102 String localNodeUri = nodeToUri(clusterService.getLocalNode());
103
104 ClusterConfig clusterConfig = new ClusterConfig()
Madan Jampani393e0f02015-02-12 07:35:39 +0530105 .withProtocol(new NettyTcpProtocol()
106 .withSsl(false)
107 .withConnectTimeout(60000)
108 .withAcceptBacklog(1024)
109 .withTrafficClass(-1)
110 .withSoLinger(-1)
111 .withReceiveBufferSize(32768)
112 .withSendBufferSize(8192)
113 .withThreads(1))
Thomas Vachuska0249b532015-02-20 16:46:18 -0800114 .withElectionTimeout(3000)
115 .withHeartbeatInterval(1500)
Madan Jampani09342702015-02-05 23:32:40 -0800116 .withMembers(activeNodeUris)
117 .withLocalMember(localNodeUri);
118
119 PartitionedDatabaseConfig databaseConfig = new PartitionedDatabaseConfig();
120
121 partitionMap.forEach((name, nodes) -> {
122 Set<String> replicas = nodes.stream().map(this::nodeToUri).collect(Collectors.toSet());
123 DatabaseConfig partitionConfig = new DatabaseConfig()
Thomas Vachuska0249b532015-02-20 16:46:18 -0800124 .withElectionTimeout(3000)
125 .withHeartbeatInterval(1500)
Madan Jampani09342702015-02-05 23:32:40 -0800126 .withConsistency(Consistency.STRONG)
Madan Jampani393e0f02015-02-12 07:35:39 +0530127 .withLog(new FileLog()
128 .withDirectory(logDir)
129 .withSegmentSize(1073741824) // 1GB
130 .withFlushOnWrite(true)
131 .withSegmentInterval(Long.MAX_VALUE))
132 .withDefaultSerializer(new DatabaseSerializer())
Madan Jampani09342702015-02-05 23:32:40 -0800133 .withReplicas(replicas);
134 databaseConfig.addPartition(name, partitionConfig);
135 });
136
137 partitionedDatabase = PartitionedDatabaseManager.create("onos-store", clusterConfig, databaseConfig);
138
Madan Jampanid14166a2015-02-24 17:37:51 -0800139 CountDownLatch latch = new CountDownLatch(1);
Madan Jampani09342702015-02-05 23:32:40 -0800140 partitionedDatabase.open().whenComplete((db, error) -> {
141 if (error != null) {
142 log.warn("Failed to open database.", error);
143 } else {
Madan Jampanid14166a2015-02-24 17:37:51 -0800144 latch.countDown();
Madan Jampani09342702015-02-05 23:32:40 -0800145 log.info("Successfully opened database.");
146 }
147 });
Madan Jampanid14166a2015-02-24 17:37:51 -0800148 try {
149 if (!latch.await(DATABASE_STARTUP_TIMEOUT_SEC, TimeUnit.SECONDS)) {
150 log.warn("Timeed out watiing for database to initialize.");
151 }
152 } catch (InterruptedException e) {
153 Thread.currentThread().interrupt();
154 log.warn("Failed to complete database initialization.");
155 }
Madan Jampani09342702015-02-05 23:32:40 -0800156 log.info("Started");
157 }
158
159 @Deactivate
160 public void deactivate() {
161 partitionedDatabase.close().whenComplete((result, error) -> {
162 if (error != null) {
163 log.warn("Failed to cleanly close database.", error);
164 } else {
165 log.info("Successfully closed database.");
166 }
167 });
168 log.info("Stopped");
169 }
170
171 @Override
Madan Jampani393e0f02015-02-12 07:35:39 +0530172 public <K, V> ConsistentMap<K , V> createConsistentMap(String name, Serializer serializer) {
Madan Jampani09342702015-02-05 23:32:40 -0800173 return new ConsistentMapImpl<K, V>(name, partitionedDatabase, serializer);
174 }
Madan Jampani64689552015-02-17 10:00:27 -0800175
176 @Override
177 public TransactionContext createTransactionContext() {
178 return new DefaultTransactionContext(partitionedDatabase);
179 }
Jonathan Hart054da972015-02-18 17:30:28 -0800180
181 @Override
182 public List<PartitionInfo> getPartitionInfo() {
183 return partitionedDatabase.getRegisteredPartitions()
184 .values()
185 .stream()
186 .map(DatabaseManager::toPartitionInfo)
187 .collect(Collectors.toList());
188 }
189
190 /**
191 * Maps a Raft Database object to a PartitionInfo object.
192 *
193 * @param database database containing input data
194 * @return PartitionInfo object
195 */
196 private static PartitionInfo toPartitionInfo(Database database) {
197 return new PartitionInfo(database.name(),
198 database.cluster().term(),
199 database.cluster().members().stream()
200 .map(Member::uri)
201 .collect(Collectors.toList()),
202 database.cluster().leader() != null ?
203 database.cluster().leader().uri() : null);
204 }
205}