forked from voldemort/voldemort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CoordinatorService.java
239 lines (204 loc) · 10.3 KB
/
CoordinatorService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/*
* Copyright 2008-2013 LinkedIn, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package voldemort.coordinator;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.net.InetSocketAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.io.JsonDecoder;
import org.apache.avro.util.Utf8;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import voldemort.client.ClientConfig;
import voldemort.client.SocketStoreClientFactory;
import voldemort.client.SystemStoreRepository;
import voldemort.client.scheduler.AsyncMetadataVersionManager;
import voldemort.common.service.SchedulerService;
import voldemort.store.StoreDefinition;
import voldemort.store.metadata.MetadataStore;
import voldemort.utils.SystemTime;
import voldemort.xml.StoreDefinitionsMapper;
import com.google.common.base.Joiner;
/**
* A Netty based HTTP service that accepts REST requests from the Voldemort thin
* clients and invokes the corresponding Fat client API.
*
*/
public class CoordinatorService {
private static boolean noop = false;
private static SocketStoreClientFactory storeClientFactory = null;
private static String[] bootstrapURLs;
private static AsyncMetadataVersionManager asyncMetadataManager = null;
private static SchedulerService schedulerService = null;
private static final Logger logger = Logger.getLogger(CoordinatorService.class);
private static Map<String, FatClientWrapper> fatClientMap = null;
private static long asyncMetadataCheckIntervalInMs = 5000;
public final static Schema CLIENT_CONFIGS_AVRO_SCHEMA = Schema.parse("{ \"name\": \"clientConfigs\", \"type\":\"array\","
+ "\"items\": { \"name\": \"clientConfig\", \"type\": \"map\", \"values\":\"string\" }}}");
private static final String STORE_NAME_KEY = "store_name";
private static String CLIENT_CONFIG_AVRO_FILE_PATH = "";
/**
* Initializes all the Fat clients (1 per store) for the cluster that this
* Coordinator talks to. This is invoked once during startup and then every
* time the Metadata manager detects changes to the cluster and stores
* metadata.
*/
private static void initializeFatClients() {
StoreDefinitionsMapper storeMapper = new StoreDefinitionsMapper();
// Fetch the state once and use this to initialize all the Fat clients
String storesXml = storeClientFactory.bootstrapMetadataWithRetries(MetadataStore.STORES_KEY);
String clusterXml = storeClientFactory.bootstrapMetadataWithRetries(MetadataStore.CLUSTER_KEY);
List<StoreDefinition> storeDefList = storeMapper.readStoreList(new StringReader(storesXml),
false);
Map<String, ClientConfig> fatClientConfigMap = readClientConfig(CLIENT_CONFIG_AVRO_FILE_PATH,
bootstrapURLs);
// For now Simply create the map of store definition to
// FatClientWrappers
// TODO: After the fat client improvements is done, modify this to
// - Fetch cluster.xml and stores.xml
// - Pass these on to each FatClientWrapper
// - Set up AsyncMetadataVersionManager
fatClientMap = new HashMap<String, FatClientWrapper>();
for(StoreDefinition storeDef: storeDefList) {
String storeName = storeDef.getName();
logger.info("Creating a Fat client wrapper for store: " + storeName);
logger.info("Using config: " + fatClientConfigMap.get(storeName));
fatClientMap.put(storeName, new FatClientWrapper(storeName,
bootstrapURLs,
fatClientConfigMap.get(storeName),
storesXml,
clusterXml));
}
}
public static void main(String[] args) {
if(args.length < 2) {
System.err.println("Missing argument: <Bootstrap URL> <fat client config file path>");
System.exit(-1);
}
if(args.length == 3) {
if(args[2].equals("noop")) {
noop = true;
}
}
// Initialize Config
bootstrapURLs = new String[1];
bootstrapURLs[0] = args[0];
CLIENT_CONFIG_AVRO_FILE_PATH = args[1];
// Initialize the Voldemort Metadata
ClientConfig clientConfig = new ClientConfig();
clientConfig.setBootstrapUrls(bootstrapURLs);
storeClientFactory = new SocketStoreClientFactory(clientConfig);
initializeFatClients();
// Setup the Async Metadata checker
SystemStoreRepository sysRepository = new SystemStoreRepository();
String clusterXml = storeClientFactory.bootstrapMetadataWithRetries(MetadataStore.CLUSTER_KEY);
sysRepository.createSystemStores(clientConfig,
clusterXml,
storeClientFactory.getFailureDetector());
// Create a callback for re-bootstrapping the client
Callable<Void> rebootstrapCallback = new Callable<Void>() {
@Override
public Void call() throws Exception {
initializeFatClients();
return null;
}
};
asyncMetadataManager = new AsyncMetadataVersionManager(sysRepository,
rebootstrapCallback,
null);
schedulerService = new SchedulerService(1, SystemTime.INSTANCE, true);
schedulerService.schedule(asyncMetadataManager.getClass().getName(),
asyncMetadataManager,
new Date(),
asyncMetadataCheckIntervalInMs);
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setOption("backlog", 1000);
// Set up the event pipeline factory.
bootstrap.setPipelineFactory(new CoordinatorPipelineFactory(fatClientMap, noop));
// Bind and start to accept incoming connections.
bootstrap.bind(new InetSocketAddress(8080));
}
/**
* A function to parse the specified Avro file in order to obtain the config
* for each fat client managed by this coordinator.
*
* @param configFilePath Path of the Avro file containing fat client configs
* @param bootstrapURLs The server URLs used during bootstrap
* @return Map of store name to the corresponding fat client config
*/
@SuppressWarnings("unchecked")
private static Map<String, ClientConfig> readClientConfig(String configFilePath,
String[] bootstrapURLs) {
String line;
Map<String, ClientConfig> storeNameConfigMap = new HashMap<String, ClientConfig>();
try {
line = Joiner.on(" ")
.join(IOUtils.readLines(new FileReader(new File(configFilePath))))
.trim();
JsonDecoder decoder = new JsonDecoder(CLIENT_CONFIGS_AVRO_SCHEMA, line);
GenericDatumReader<Object> datumReader = new GenericDatumReader<Object>(CLIENT_CONFIGS_AVRO_SCHEMA);
GenericData.Array<Map<Utf8, Utf8>> flowMaps = (GenericData.Array<Map<Utf8, Utf8>>) datumReader.read(null,
decoder);
// Flows to return back
if(flowMaps != null && flowMaps.size() > 0) {
for(Map<Utf8, Utf8> flowMap: flowMaps) {
Properties props = new Properties();
for(Utf8 key: flowMap.keySet()) {
props.put(key.toString(), flowMap.get(key).toString());
}
String storeName = flowMap.get(new Utf8(STORE_NAME_KEY)).toString();
storeName = props.getProperty(STORE_NAME_KEY);
if(storeName == null || storeName.length() == 0) {
throw new Exception("Illegal Store Name !!!");
}
ClientConfig config = new ClientConfig(props);
config.setBootstrapUrls(bootstrapURLs)
.setEnableCompressionLayer(false)
.setEnableSerializationLayer(false)
.enableDefaultClient(true)
.setEnableLazy(false);
storeNameConfigMap.put(storeName, config);
}
}
} catch(FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return storeNameConfigMap;
}
}