blob: 6d5abf1088b4805edf3dfda7883f06f11f8d4b5c [file] [log] [blame]
Madan Jampaniad3c5262016-01-20 00:50:17 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2016-present Open Networking Foundation
Madan Jampaniad3c5262016-01-20 00:50:17 -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.cluster.impl;
17
Madan Jampani898fcca2016-02-26 12:42:08 -080018import static org.onlab.util.Tools.groupedThreads;
Madan Jampaniad3c5262016-01-20 00:50:17 -080019import static org.slf4j.LoggerFactory.getLogger;
20
21import java.io.File;
Madan Jampanif172d402016-03-04 00:56:38 -080022import java.io.FileInputStream;
Madan Jampaniad3c5262016-01-20 00:50:17 -080023import java.io.IOException;
Jordan Haltermandbfff062017-06-19 10:31:32 -070024import java.net.HttpURLConnection;
Madan Jampanif172d402016-03-04 00:56:38 -080025import java.net.URL;
Madan Jampaniad3c5262016-01-20 00:50:17 -080026import java.util.Set;
Madan Jampanif172d402016-03-04 00:56:38 -080027import java.util.concurrent.ScheduledExecutorService;
28import java.util.concurrent.TimeUnit;
Madan Jampaniad3c5262016-01-20 00:50:17 -080029import java.util.concurrent.atomic.AtomicReference;
30
31import org.apache.felix.scr.annotations.Activate;
32import org.apache.felix.scr.annotations.Component;
33import org.apache.felix.scr.annotations.Deactivate;
34import org.apache.felix.scr.annotations.Reference;
35import org.apache.felix.scr.annotations.ReferenceCardinality;
36import org.onlab.packet.IpAddress;
37import org.onosproject.cluster.ClusterMetadata;
38import org.onosproject.cluster.ClusterMetadataProvider;
39import org.onosproject.cluster.ClusterMetadataProviderRegistry;
40import org.onosproject.cluster.ClusterMetadataProviderService;
41import org.onosproject.cluster.ControllerNode;
42import org.onosproject.cluster.DefaultControllerNode;
43import org.onosproject.cluster.DefaultPartition;
44import org.onosproject.cluster.NodeId;
45import org.onosproject.cluster.Partition;
46import org.onosproject.cluster.PartitionId;
47import org.onosproject.net.provider.ProviderId;
48import org.onosproject.store.service.Versioned;
49import org.slf4j.Logger;
50
51import com.fasterxml.jackson.core.JsonGenerator;
52import com.fasterxml.jackson.core.JsonParser;
53import com.fasterxml.jackson.core.JsonProcessingException;
54import com.fasterxml.jackson.databind.DeserializationContext;
55import com.fasterxml.jackson.databind.JsonDeserializer;
56import com.fasterxml.jackson.databind.JsonNode;
57import com.fasterxml.jackson.databind.JsonSerializer;
58import com.fasterxml.jackson.databind.ObjectMapper;
59import com.fasterxml.jackson.databind.SerializerProvider;
60import com.fasterxml.jackson.databind.module.SimpleModule;
61import com.google.common.base.Throwables;
62import com.google.common.collect.Sets;
63import com.google.common.io.Files;
64
65import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070066import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Madan Jampaniad3c5262016-01-20 00:50:17 -080067
68/**
69 * Provider of {@link ClusterMetadata cluster metadata} sourced from a local config file.
70 */
71@Component(immediate = true)
72public class ConfigFileBasedClusterMetadataProvider implements ClusterMetadataProvider {
73
74 private final Logger log = getLogger(getClass());
75
76 // constants for filed names (used in serialization)
77 private static final String ID = "id";
78 private static final String PORT = "port";
79 private static final String IP = "ip";
80
Madan Jampani898fcca2016-02-26 12:42:08 -080081 private static final String CONFIG_DIR = "../config";
82 private static final String CONFIG_FILE_NAME = "cluster.json";
83 private static final File CONFIG_FILE = new File(CONFIG_DIR, CONFIG_FILE_NAME);
Madan Jampaniad3c5262016-01-20 00:50:17 -080084
85 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
86 protected ClusterMetadataProviderRegistry providerRegistry;
87
Madan Jampanif172d402016-03-04 00:56:38 -080088 private static final ProviderId PROVIDER_ID = new ProviderId("file", "none");
Madan Jampani898fcca2016-02-26 12:42:08 -080089 private final AtomicReference<Versioned<ClusterMetadata>> cachedMetadata = new AtomicReference<>();
Madan Jampanif172d402016-03-04 00:56:38 -080090 private final ScheduledExecutorService configFileChangeDetector =
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070091 newSingleThreadScheduledExecutor(groupedThreads("onos/cluster/metadata/config-watcher", "", log));
Madan Jampaniad3c5262016-01-20 00:50:17 -080092
Madan Jampanif172d402016-03-04 00:56:38 -080093 private String metadataUrl;
Madan Jampaniad3c5262016-01-20 00:50:17 -080094 private ObjectMapper mapper;
95 private ClusterMetadataProviderService providerService;
96
97 @Activate
98 public void activate() {
99 mapper = new ObjectMapper();
100 SimpleModule module = new SimpleModule();
101 module.addSerializer(NodeId.class, new NodeIdSerializer());
102 module.addDeserializer(NodeId.class, new NodeIdDeserializer());
103 module.addSerializer(ControllerNode.class, new ControllerNodeSerializer());
104 module.addDeserializer(ControllerNode.class, new ControllerNodeDeserializer());
105 module.addDeserializer(Partition.class, new PartitionDeserializer());
106 module.addSerializer(PartitionId.class, new PartitionIdSerializer());
107 module.addDeserializer(PartitionId.class, new PartitionIdDeserializer());
108 mapper.registerModule(module);
109 providerService = providerRegistry.register(this);
Madan Jampanif172d402016-03-04 00:56:38 -0800110 metadataUrl = System.getProperty("onos.cluster.metadata.uri", "file://" + CONFIG_DIR + "/" + CONFIG_FILE);
111 configFileChangeDetector.scheduleWithFixedDelay(() -> watchUrl(metadataUrl), 100, 500, TimeUnit.MILLISECONDS);
Madan Jampaniad3c5262016-01-20 00:50:17 -0800112 log.info("Started");
113 }
114
115 @Deactivate
116 public void deactivate() {
Madan Jampani898fcca2016-02-26 12:42:08 -0800117 configFileChangeDetector.shutdown();
Madan Jampaniad3c5262016-01-20 00:50:17 -0800118 providerRegistry.unregister(this);
119 log.info("Stopped");
120 }
121
122 @Override
123 public ProviderId id() {
124 return PROVIDER_ID;
125 }
126
127 @Override
128 public Versioned<ClusterMetadata> getClusterMetadata() {
129 checkState(isAvailable());
130 synchronized (this) {
131 if (cachedMetadata.get() == null) {
Jordan Haltermandbfff062017-06-19 10:31:32 -0700132 cachedMetadata.set(blockForMetadata(metadataUrl));
Madan Jampaniad3c5262016-01-20 00:50:17 -0800133 }
134 return cachedMetadata.get();
135 }
136 }
137
138 @Override
139 public void setClusterMetadata(ClusterMetadata metadata) {
140 try {
141 Files.createParentDirs(CONFIG_FILE);
142 mapper.writeValue(CONFIG_FILE, metadata);
143 providerService.clusterMetadataChanged(new Versioned<>(metadata, CONFIG_FILE.lastModified()));
144 } catch (IOException e) {
145 Throwables.propagate(e);
146 }
147 }
148
149 @Override
150 public void addActivePartitionMember(PartitionId partitionId, NodeId nodeId) {
151 throw new UnsupportedOperationException();
152 }
153
154 @Override
155 public void removeActivePartitionMember(PartitionId partitionId, NodeId nodeId) {
156 throw new UnsupportedOperationException();
157 }
158
159 @Override
160 public Set<NodeId> getActivePartitionMembers(PartitionId partitionId) {
161 throw new UnsupportedOperationException();
162 }
163
164 @Override
165 public boolean isAvailable() {
Madan Jampanif172d402016-03-04 00:56:38 -0800166 try {
167 URL url = new URL(metadataUrl);
Jon Halla3fcf672017-03-28 16:53:22 -0700168 if ("file".equals(url.getProtocol())) {
Madan Jampanif172d402016-03-04 00:56:38 -0800169 File file = new File(metadataUrl.replaceFirst("file://", ""));
170 return file.exists();
Madan Jampanif172d402016-03-04 00:56:38 -0800171 } else {
Jordan Halterman46c76902017-08-24 14:55:25 -0700172 // Return true for HTTP URLs since we allow blocking until HTTP servers come up
173 return "http".equals(url.getProtocol());
Madan Jampanif172d402016-03-04 00:56:38 -0800174 }
175 } catch (Exception e) {
Jon Halldb2cf752016-06-28 16:24:45 -0700176 log.warn("Exception accessing metadata file at {}:", metadataUrl, e);
Madan Jampanif172d402016-03-04 00:56:38 -0800177 return false;
178 }
Madan Jampaniad3c5262016-01-20 00:50:17 -0800179 }
180
Jordan Haltermandbfff062017-06-19 10:31:32 -0700181 private Versioned<ClusterMetadata> blockForMetadata(String metadataUrl) {
Jordan Halterman46c76902017-08-24 14:55:25 -0700182 int iterations = 0;
Jordan Haltermandbfff062017-06-19 10:31:32 -0700183 for (;;) {
184 Versioned<ClusterMetadata> metadata = fetchMetadata(metadataUrl);
185 if (metadata != null) {
186 return metadata;
187 }
188
189 try {
Jordan Halterman46c76902017-08-24 14:55:25 -0700190 Thread.sleep(Math.min((int) Math.pow(2, ++iterations) * 10, 1000));
Jordan Haltermandbfff062017-06-19 10:31:32 -0700191 } catch (InterruptedException e) {
192 throw Throwables.propagate(e);
193 }
194 }
195 }
196
Madan Jampanif172d402016-03-04 00:56:38 -0800197 private Versioned<ClusterMetadata> fetchMetadata(String metadataUrl) {
Madan Jampaniad3c5262016-01-20 00:50:17 -0800198 try {
Madan Jampanif172d402016-03-04 00:56:38 -0800199 URL url = new URL(metadataUrl);
200 ClusterMetadata metadata = null;
201 long version = 0;
Jon Halla3fcf672017-03-28 16:53:22 -0700202 if ("file".equals(url.getProtocol())) {
Madan Jampanif172d402016-03-04 00:56:38 -0800203 File file = new File(metadataUrl.replaceFirst("file://", ""));
204 version = file.lastModified();
205 metadata = mapper.readValue(new FileInputStream(file), ClusterMetadata.class);
Jon Halla3fcf672017-03-28 16:53:22 -0700206 } else if ("http".equals(url.getProtocol())) {
Jordan Haltermanda268372017-09-19 11:18:08 -0700207 try {
208 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
209 if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
210 log.warn("Could not reach metadata URL {}. Retrying...", url);
211 return null;
212 }
213 if (conn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
214 return null;
215 }
216 version = conn.getLastModified();
217 metadata = mapper.readValue(conn.getInputStream(), ClusterMetadata.class);
218 } catch (IOException e) {
Jordan Halterman46c76902017-08-24 14:55:25 -0700219 log.warn("Could not reach metadata URL {}. Retrying...", url);
220 return null;
221 }
Madan Jampanif172d402016-03-04 00:56:38 -0800222 }
Jordan Haltermandbfff062017-06-19 10:31:32 -0700223
zhiyong ke60e40002017-04-13 13:50:47 +0800224 if (null == metadata) {
225 log.warn("Metadata is null in the function fetchMetadata");
226 throw new NullPointerException();
227 }
Jordan Haltermandbfff062017-06-19 10:31:32 -0700228
229 // If the configured partitions are empty then return a null metadata to indicate that the configuration
230 // needs to be polled until the partitions are populated.
231 if (metadata.getPartitions().isEmpty() || metadata.getPartitions().stream()
232 .map(partition -> partition.getMembers().size())
233 .reduce(Math::min)
234 .orElse(0) == 0) {
235 return null;
236 }
Madan Jampanif172d402016-03-04 00:56:38 -0800237 return new Versioned<>(new ClusterMetadata(PROVIDER_ID,
238 metadata.getName(),
239 Sets.newHashSet(metadata.getNodes()),
240 Sets.newHashSet(metadata.getPartitions())),
241 version);
Madan Jampaniad3c5262016-01-20 00:50:17 -0800242 } catch (IOException e) {
Madan Jampanif172d402016-03-04 00:56:38 -0800243 throw Throwables.propagate(e);
Madan Jampaniad3c5262016-01-20 00:50:17 -0800244 }
Madan Jampaniad3c5262016-01-20 00:50:17 -0800245 }
246
247 private static class PartitionDeserializer extends JsonDeserializer<Partition> {
248 @Override
249 public Partition deserialize(JsonParser jp, DeserializationContext ctxt)
250 throws IOException, JsonProcessingException {
251 return jp.readValueAs(DefaultPartition.class);
252 }
253 }
254
255 private static class PartitionIdSerializer extends JsonSerializer<PartitionId> {
256 @Override
257 public void serialize(PartitionId partitionId, JsonGenerator jgen, SerializerProvider provider)
258 throws IOException, JsonProcessingException {
259 jgen.writeNumber(partitionId.asInt());
260 }
261 }
262
263 private class PartitionIdDeserializer extends JsonDeserializer<PartitionId> {
264 @Override
265 public PartitionId deserialize(JsonParser jp, DeserializationContext ctxt)
266 throws IOException, JsonProcessingException {
267 JsonNode node = jp.getCodec().readTree(jp);
268 return new PartitionId(node.asInt());
269 }
270 }
271
272 private static class ControllerNodeSerializer extends JsonSerializer<ControllerNode> {
273 @Override
274 public void serialize(ControllerNode node, JsonGenerator jgen, SerializerProvider provider)
275 throws IOException, JsonProcessingException {
276 jgen.writeStartObject();
277 jgen.writeStringField(ID, node.id().toString());
278 jgen.writeStringField(IP, node.ip().toString());
279 jgen.writeNumberField(PORT, node.tcpPort());
280 jgen.writeEndObject();
281 }
282 }
283
284 private static class ControllerNodeDeserializer extends JsonDeserializer<ControllerNode> {
285 @Override
286 public ControllerNode deserialize(JsonParser jp, DeserializationContext ctxt)
287 throws IOException, JsonProcessingException {
288 JsonNode node = jp.getCodec().readTree(jp);
289 NodeId nodeId = new NodeId(node.get(ID).textValue());
290 IpAddress ip = IpAddress.valueOf(node.get(IP).textValue());
291 int port = node.get(PORT).asInt();
292 return new DefaultControllerNode(nodeId, ip, port);
293 }
294 }
295
296 private static class NodeIdSerializer extends JsonSerializer<NodeId> {
297 @Override
298 public void serialize(NodeId nodeId, JsonGenerator jgen, SerializerProvider provider)
299 throws IOException, JsonProcessingException {
300 jgen.writeString(nodeId.toString());
301 }
302 }
303
304 private class NodeIdDeserializer extends JsonDeserializer<NodeId> {
305 @Override
306 public NodeId deserialize(JsonParser jp, DeserializationContext ctxt)
307 throws IOException, JsonProcessingException {
308 JsonNode node = jp.getCodec().readTree(jp);
309 return new NodeId(node.asText());
310 }
311 }
Madan Jampani898fcca2016-02-26 12:42:08 -0800312
313 /**
Madan Jampanif172d402016-03-04 00:56:38 -0800314 * Monitors the metadata url for any updates and notifies providerService accordingly.
Madan Jampani898fcca2016-02-26 12:42:08 -0800315 */
Madan Jampanif172d402016-03-04 00:56:38 -0800316 private void watchUrl(String metadataUrl) {
317 // TODO: We are merely polling the url.
318 // This can be easily addressed for files. For http urls we need to move to a push style protocol.
319 Versioned<ClusterMetadata> latestMetadata = fetchMetadata(metadataUrl);
Jordan Haltermandbfff062017-06-19 10:31:32 -0700320 if (cachedMetadata.get() != null && latestMetadata != null
321 && cachedMetadata.get().version() < latestMetadata.version()) {
Madan Jampanif172d402016-03-04 00:56:38 -0800322 cachedMetadata.set(latestMetadata);
323 providerService.clusterMetadataChanged(latestMetadata);
Madan Jampani898fcca2016-02-26 12:42:08 -0800324 }
325 }
Madan Jampaniad3c5262016-01-20 00:50:17 -0800326}