blob: de7a3e143c94a5a26157358051bff1109581ca42 [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
Jordan Halterman00e92da2018-05-22 23:05:52 -070018import java.io.File;
19import java.io.FileInputStream;
20import java.io.IOException;
21import java.net.HttpURLConnection;
22import java.net.URL;
23import java.util.Set;
24import java.util.UUID;
25import java.util.concurrent.ScheduledExecutorService;
26import java.util.concurrent.TimeUnit;
27import java.util.concurrent.atomic.AtomicReference;
28import java.util.stream.Collectors;
29
Ray Milkey6a51cb92018-03-06 09:03:03 -080030import com.fasterxml.jackson.databind.ObjectMapper;
Jordan Halterman19c123a2018-07-30 13:57:19 -070031import com.google.common.collect.Sets;
Ray Milkey6a51cb92018-03-06 09:03:03 -080032import com.google.common.io.Files;
Madan Jampaniad3c5262016-01-20 00:50:17 -080033import org.apache.felix.scr.annotations.Activate;
34import org.apache.felix.scr.annotations.Component;
35import org.apache.felix.scr.annotations.Deactivate;
36import org.apache.felix.scr.annotations.Reference;
37import org.apache.felix.scr.annotations.ReferenceCardinality;
Madan Jampaniad3c5262016-01-20 00:50:17 -080038import org.onosproject.cluster.ClusterMetadata;
39import org.onosproject.cluster.ClusterMetadataProvider;
40import org.onosproject.cluster.ClusterMetadataProviderRegistry;
41import org.onosproject.cluster.ClusterMetadataProviderService;
Madan Jampaniad3c5262016-01-20 00:50:17 -080042import org.onosproject.cluster.DefaultControllerNode;
Jordan Halterman00e92da2018-05-22 23:05:52 -070043import org.onosproject.cluster.Node;
Madan Jampaniad3c5262016-01-20 00:50:17 -080044import org.onosproject.cluster.NodeId;
Madan Jampaniad3c5262016-01-20 00:50:17 -080045import org.onosproject.cluster.PartitionId;
46import org.onosproject.net.provider.ProviderId;
47import org.onosproject.store.service.Versioned;
48import org.slf4j.Logger;
49
Madan Jampaniad3c5262016-01-20 00:50:17 -080050import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070051import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Ray Milkey6a51cb92018-03-06 09:03:03 -080052import static org.onlab.util.Tools.groupedThreads;
53import static org.slf4j.LoggerFactory.getLogger;
Madan Jampaniad3c5262016-01-20 00:50:17 -080054
55/**
56 * Provider of {@link ClusterMetadata cluster metadata} sourced from a local config file.
57 */
58@Component(immediate = true)
59public class ConfigFileBasedClusterMetadataProvider implements ClusterMetadataProvider {
60
61 private final Logger log = getLogger(getClass());
62
Madan Jampani898fcca2016-02-26 12:42:08 -080063 private static final String CONFIG_DIR = "../config";
64 private static final String CONFIG_FILE_NAME = "cluster.json";
65 private static final File CONFIG_FILE = new File(CONFIG_DIR, CONFIG_FILE_NAME);
Madan Jampaniad3c5262016-01-20 00:50:17 -080066
67 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
68 protected ClusterMetadataProviderRegistry providerRegistry;
69
Madan Jampanif172d402016-03-04 00:56:38 -080070 private static final ProviderId PROVIDER_ID = new ProviderId("file", "none");
Madan Jampani898fcca2016-02-26 12:42:08 -080071 private final AtomicReference<Versioned<ClusterMetadata>> cachedMetadata = new AtomicReference<>();
Madan Jampanif172d402016-03-04 00:56:38 -080072 private final ScheduledExecutorService configFileChangeDetector =
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070073 newSingleThreadScheduledExecutor(groupedThreads("onos/cluster/metadata/config-watcher", "", log));
Madan Jampaniad3c5262016-01-20 00:50:17 -080074
Madan Jampanif172d402016-03-04 00:56:38 -080075 private String metadataUrl;
Madan Jampaniad3c5262016-01-20 00:50:17 -080076 private ObjectMapper mapper;
77 private ClusterMetadataProviderService providerService;
78
79 @Activate
80 public void activate() {
81 mapper = new ObjectMapper();
Madan Jampaniad3c5262016-01-20 00:50:17 -080082 providerService = providerRegistry.register(this);
Madan Jampanif172d402016-03-04 00:56:38 -080083 metadataUrl = System.getProperty("onos.cluster.metadata.uri", "file://" + CONFIG_DIR + "/" + CONFIG_FILE);
84 configFileChangeDetector.scheduleWithFixedDelay(() -> watchUrl(metadataUrl), 100, 500, TimeUnit.MILLISECONDS);
Madan Jampaniad3c5262016-01-20 00:50:17 -080085 log.info("Started");
86 }
87
88 @Deactivate
89 public void deactivate() {
Madan Jampani898fcca2016-02-26 12:42:08 -080090 configFileChangeDetector.shutdown();
Madan Jampaniad3c5262016-01-20 00:50:17 -080091 providerRegistry.unregister(this);
92 log.info("Stopped");
93 }
94
95 @Override
96 public ProviderId id() {
97 return PROVIDER_ID;
98 }
99
100 @Override
101 public Versioned<ClusterMetadata> getClusterMetadata() {
102 checkState(isAvailable());
103 synchronized (this) {
104 if (cachedMetadata.get() == null) {
Jordan Haltermandbfff062017-06-19 10:31:32 -0700105 cachedMetadata.set(blockForMetadata(metadataUrl));
Madan Jampaniad3c5262016-01-20 00:50:17 -0800106 }
107 return cachedMetadata.get();
108 }
109 }
110
Jordan Halterman00e92da2018-05-22 23:05:52 -0700111 private ClusterMetadataPrototype toPrototype(ClusterMetadata metadata) {
112 ClusterMetadataPrototype prototype = new ClusterMetadataPrototype();
113 prototype.setName(metadata.getName());
Jordan Halterman19c123a2018-07-30 13:57:19 -0700114 prototype.setController(metadata.getNodes()
115 .stream()
116 .map(this::toPrototype)
117 .collect(Collectors.toSet()));
118 prototype.setStorage(metadata.getStorageNodes()
119 .stream()
120 .map(this::toPrototype)
121 .collect(Collectors.toSet()));
Samuel Jero31e16f52018-09-21 10:34:28 -0400122 prototype.setClusterSecret(metadata.getClusterSecret());
Jordan Halterman00e92da2018-05-22 23:05:52 -0700123 return prototype;
124 }
125
126 private NodePrototype toPrototype(Node node) {
127 NodePrototype prototype = new NodePrototype();
128 prototype.setId(node.id().id());
Jordan Haltermane458f002018-09-18 17:42:05 -0700129 prototype.setHost(node.host());
Jordan Halterman00e92da2018-05-22 23:05:52 -0700130 prototype.setPort(node.tcpPort());
131 return prototype;
132 }
133
Madan Jampaniad3c5262016-01-20 00:50:17 -0800134 @Override
135 public void setClusterMetadata(ClusterMetadata metadata) {
136 try {
Ray Milkey83200882017-11-13 19:18:21 -0800137 File configFile = new File(metadataUrl.replaceFirst("file://", ""));
138 Files.createParentDirs(configFile);
Jordan Halterman00e92da2018-05-22 23:05:52 -0700139 ClusterMetadataPrototype metadataPrototype = toPrototype(metadata);
140 mapper.writeValue(configFile, metadataPrototype);
Ray Milkey83200882017-11-13 19:18:21 -0800141 cachedMetadata.set(fetchMetadata(metadataUrl));
142 providerService.clusterMetadataChanged(new Versioned<>(metadata, configFile.lastModified()));
Madan Jampaniad3c5262016-01-20 00:50:17 -0800143 } catch (IOException e) {
Ray Milkey6a51cb92018-03-06 09:03:03 -0800144 throw new IllegalArgumentException(e);
Madan Jampaniad3c5262016-01-20 00:50:17 -0800145 }
146 }
147
148 @Override
149 public void addActivePartitionMember(PartitionId partitionId, NodeId nodeId) {
150 throw new UnsupportedOperationException();
151 }
152
153 @Override
154 public void removeActivePartitionMember(PartitionId partitionId, NodeId nodeId) {
155 throw new UnsupportedOperationException();
156 }
157
158 @Override
159 public Set<NodeId> getActivePartitionMembers(PartitionId partitionId) {
160 throw new UnsupportedOperationException();
161 }
162
163 @Override
164 public boolean isAvailable() {
Madan Jampanif172d402016-03-04 00:56:38 -0800165 try {
166 URL url = new URL(metadataUrl);
Jon Halla3fcf672017-03-28 16:53:22 -0700167 if ("file".equals(url.getProtocol())) {
Madan Jampanif172d402016-03-04 00:56:38 -0800168 File file = new File(metadataUrl.replaceFirst("file://", ""));
169 return file.exists();
Madan Jampanif172d402016-03-04 00:56:38 -0800170 } else {
Jordan Halterman46c76902017-08-24 14:55:25 -0700171 // Return true for HTTP URLs since we allow blocking until HTTP servers come up
172 return "http".equals(url.getProtocol());
Madan Jampanif172d402016-03-04 00:56:38 -0800173 }
174 } catch (Exception e) {
Jon Halldb2cf752016-06-28 16:24:45 -0700175 log.warn("Exception accessing metadata file at {}:", metadataUrl, e);
Madan Jampanif172d402016-03-04 00:56:38 -0800176 return false;
177 }
Madan Jampaniad3c5262016-01-20 00:50:17 -0800178 }
179
Jordan Haltermandbfff062017-06-19 10:31:32 -0700180 private Versioned<ClusterMetadata> blockForMetadata(String metadataUrl) {
Ray Milkey3717e602018-02-01 13:49:47 -0800181 long iterations = 0;
Jordan Haltermandbfff062017-06-19 10:31:32 -0700182 for (;;) {
Jordan Halterman9ada34a2017-10-23 16:31:50 -0700183 try {
184 Versioned<ClusterMetadata> metadata = fetchMetadata(metadataUrl);
185 if (metadata != null) {
186 return metadata;
187 }
188 } catch (Exception e) {
189 log.warn("Exception attempting to access metadata file at {}: {}", metadataUrl, e);
Jordan Haltermandbfff062017-06-19 10:31:32 -0700190 }
191
192 try {
Ray Milkey961b19f2018-02-05 13:47:55 -0800193 Thread.sleep((int) Math.pow(2, iterations < 7 ? ++iterations : iterations) * 10L);
Jordan Haltermandbfff062017-06-19 10:31:32 -0700194 } catch (InterruptedException e) {
Ray Milkey5c7d4882018-02-05 14:50:39 -0800195 Thread.currentThread().interrupt();
Ray Milkey6a51cb92018-03-06 09:03:03 -0800196 throw new IllegalStateException(e);
Jordan Haltermandbfff062017-06-19 10:31:32 -0700197 }
198 }
199 }
200
Jordan Haltermane458f002018-09-18 17:42:05 -0700201 private static NodeId getNodeId(NodePrototype node) {
202 if (node.getId() != null) {
203 return NodeId.nodeId(node.getId());
204 } else if (node.getHost() != null) {
205 return NodeId.nodeId(node.getHost());
206 } else if (node.getIp() != null) {
207 return NodeId.nodeId(node.getIp());
208 } else {
209 return NodeId.nodeId(UUID.randomUUID().toString());
210 }
211 }
212
213 private static String getNodeHost(NodePrototype node) {
214 if (node.getHost() != null) {
215 return node.getHost();
216 } else if (node.getIp() != null) {
217 return node.getIp();
218 } else {
219 throw new IllegalArgumentException(
220 "Malformed cluster configuration: No host specified for node " + node.getId());
221 }
222 }
223
224 private static int getNodePort(NodePrototype node) {
225 if (node.getPort() != null) {
226 return node.getPort();
227 }
228 return DefaultControllerNode.DEFAULT_PORT;
229 }
230
Madan Jampanif172d402016-03-04 00:56:38 -0800231 private Versioned<ClusterMetadata> fetchMetadata(String metadataUrl) {
Madan Jampaniad3c5262016-01-20 00:50:17 -0800232 try {
Madan Jampanif172d402016-03-04 00:56:38 -0800233 URL url = new URL(metadataUrl);
Jordan Halterman00e92da2018-05-22 23:05:52 -0700234 ClusterMetadataPrototype metadata = null;
Madan Jampanif172d402016-03-04 00:56:38 -0800235 long version = 0;
Jon Halla3fcf672017-03-28 16:53:22 -0700236 if ("file".equals(url.getProtocol())) {
Madan Jampanif172d402016-03-04 00:56:38 -0800237 File file = new File(metadataUrl.replaceFirst("file://", ""));
238 version = file.lastModified();
Jordan Halterman00e92da2018-05-22 23:05:52 -0700239 metadata = mapper.readValue(new FileInputStream(file), ClusterMetadataPrototype.class);
Jon Halla3fcf672017-03-28 16:53:22 -0700240 } else if ("http".equals(url.getProtocol())) {
Jordan Haltermanda268372017-09-19 11:18:08 -0700241 try {
242 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
243 if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
244 log.warn("Could not reach metadata URL {}. Retrying...", url);
245 return null;
246 }
247 if (conn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
248 return null;
249 }
250 version = conn.getLastModified();
Jordan Halterman00e92da2018-05-22 23:05:52 -0700251 metadata = mapper.readValue(conn.getInputStream(), ClusterMetadataPrototype.class);
Jordan Haltermanda268372017-09-19 11:18:08 -0700252 } catch (IOException e) {
Jordan Halterman46c76902017-08-24 14:55:25 -0700253 log.warn("Could not reach metadata URL {}. Retrying...", url);
254 return null;
255 }
Madan Jampanif172d402016-03-04 00:56:38 -0800256 }
Jordan Haltermandbfff062017-06-19 10:31:32 -0700257
zhiyong ke60e40002017-04-13 13:50:47 +0800258 if (null == metadata) {
259 log.warn("Metadata is null in the function fetchMetadata");
260 throw new NullPointerException();
261 }
Jordan Haltermandbfff062017-06-19 10:31:32 -0700262
Jordan Halterman00e92da2018-05-22 23:05:52 -0700263 return new Versioned<>(new ClusterMetadata(
264 PROVIDER_ID,
265 metadata.getName(),
266 metadata.getNode() != null ?
267 new DefaultControllerNode(
Jordan Haltermane458f002018-09-18 17:42:05 -0700268 getNodeId(metadata.getNode()),
269 getNodeHost(metadata.getNode()),
270 getNodePort(metadata.getNode())) : null,
Jordan Halterman19c123a2018-07-30 13:57:19 -0700271 metadata.getController()
272 .stream()
Jordan Haltermane458f002018-09-18 17:42:05 -0700273 .map(node -> new DefaultControllerNode(getNodeId(node), getNodeHost(node), getNodePort(node)))
Jordan Halterman19c123a2018-07-30 13:57:19 -0700274 .collect(Collectors.toSet()),
275 metadata.getStorage()
276 .stream()
Jordan Haltermane458f002018-09-18 17:42:05 -0700277 .map(node -> new DefaultControllerNode(getNodeId(node), getNodeHost(node), getNodePort(node)))
Samuel Jero31e16f52018-09-21 10:34:28 -0400278 .collect(Collectors.toSet()),
279 metadata.getClusterSecret()),
Jordan Halterman00e92da2018-05-22 23:05:52 -0700280 version);
Madan Jampaniad3c5262016-01-20 00:50:17 -0800281 } catch (IOException e) {
Ray Milkey6a51cb92018-03-06 09:03:03 -0800282 throw new IllegalArgumentException(e);
Madan Jampaniad3c5262016-01-20 00:50:17 -0800283 }
Madan Jampaniad3c5262016-01-20 00:50:17 -0800284 }
285
Madan Jampani898fcca2016-02-26 12:42:08 -0800286 /**
Madan Jampanif172d402016-03-04 00:56:38 -0800287 * Monitors the metadata url for any updates and notifies providerService accordingly.
Madan Jampani898fcca2016-02-26 12:42:08 -0800288 */
Madan Jampanif172d402016-03-04 00:56:38 -0800289 private void watchUrl(String metadataUrl) {
Ray Milkeye3708c72017-11-13 13:10:46 -0800290 if (!isAvailable()) {
291 return;
292 }
Madan Jampanif172d402016-03-04 00:56:38 -0800293 // TODO: We are merely polling the url.
294 // This can be easily addressed for files. For http urls we need to move to a push style protocol.
dvaddire49add802017-08-23 09:45:49 +0530295 try {
296 Versioned<ClusterMetadata> latestMetadata = fetchMetadata(metadataUrl);
297 if (cachedMetadata.get() != null && latestMetadata != null
298 && cachedMetadata.get().version() < latestMetadata.version()) {
299 cachedMetadata.set(latestMetadata);
300 providerService.clusterMetadataChanged(latestMetadata);
301 }
302 } catch (Exception e) {
303 log.error("Unable to parse metadata : ", e);
Madan Jampani898fcca2016-02-26 12:42:08 -0800304 }
305 }
Jordan Halterman00e92da2018-05-22 23:05:52 -0700306
307 private static class ClusterMetadataPrototype {
308 private String name;
309 private NodePrototype node;
Jordan Halterman19c123a2018-07-30 13:57:19 -0700310 private Set<NodePrototype> controller = Sets.newHashSet();
311 private Set<NodePrototype> storage = Sets.newHashSet();
Samuel Jero31e16f52018-09-21 10:34:28 -0400312 private String clusterSecret;
Jordan Halterman00e92da2018-05-22 23:05:52 -0700313
314 public String getName() {
315 return name;
316 }
317
318 public void setName(String name) {
319 this.name = name;
320 }
321
322 public NodePrototype getNode() {
323 return node;
324 }
325
326 public void setNode(NodePrototype node) {
327 this.node = node;
328 }
329
Jordan Halterman19c123a2018-07-30 13:57:19 -0700330 public Set<NodePrototype> getController() {
331 return controller;
Jordan Halterman00e92da2018-05-22 23:05:52 -0700332 }
333
Jordan Halterman19c123a2018-07-30 13:57:19 -0700334 public void setController(Set<NodePrototype> controller) {
335 this.controller = controller;
336 }
337
338 public Set<NodePrototype> getStorage() {
339 return storage;
340 }
341
342 public void setStorage(Set<NodePrototype> storage) {
343 this.storage = storage;
Jordan Halterman00e92da2018-05-22 23:05:52 -0700344 }
Samuel Jero31e16f52018-09-21 10:34:28 -0400345
346 public void setClusterSecret(String clusterSecret) {
347 this.clusterSecret = clusterSecret;
348 }
349
350 public String getClusterSecret() {
351 return clusterSecret;
352 }
Jordan Halterman00e92da2018-05-22 23:05:52 -0700353 }
354
355 private static class NodePrototype {
356 private String id;
357 private String ip;
Jordan Haltermane458f002018-09-18 17:42:05 -0700358 private String host;
Jordan Halterman00e92da2018-05-22 23:05:52 -0700359 private Integer port;
360
361 public String getId() {
362 return id;
363 }
364
365 public void setId(String id) {
366 this.id = id;
367 }
368
369 public String getIp() {
370 return ip;
371 }
372
373 public void setIp(String ip) {
374 this.ip = ip;
375 }
376
Jordan Haltermane458f002018-09-18 17:42:05 -0700377 public String getHost() {
378 return host;
379 }
380
381 public void setHost(String host) {
382 this.host = host;
383 }
384
Jordan Halterman00e92da2018-05-22 23:05:52 -0700385 public Integer getPort() {
386 return port;
387 }
388
389 public void setPort(Integer port) {
390 this.port = port;
391 }
392 }
Samuel Jero31e16f52018-09-21 10:34:28 -0400393}