blob: e07cb259eb9d92e42ab5855da9b5ee642e246f53 [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;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070033
34import org.osgi.service.component.annotations.Activate;
35import org.osgi.service.component.annotations.Component;
36import org.osgi.service.component.annotations.Deactivate;
37import org.osgi.service.component.annotations.Reference;
38import org.osgi.service.component.annotations.ReferenceCardinality;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070039
Madan Jampaniad3c5262016-01-20 00:50:17 -080040import org.onosproject.cluster.ClusterMetadata;
41import org.onosproject.cluster.ClusterMetadataProvider;
42import org.onosproject.cluster.ClusterMetadataProviderRegistry;
43import org.onosproject.cluster.ClusterMetadataProviderService;
Madan Jampaniad3c5262016-01-20 00:50:17 -080044import org.onosproject.cluster.DefaultControllerNode;
Jordan Halterman00e92da2018-05-22 23:05:52 -070045import org.onosproject.cluster.Node;
Madan Jampaniad3c5262016-01-20 00:50:17 -080046import org.onosproject.cluster.NodeId;
Madan Jampaniad3c5262016-01-20 00:50:17 -080047import org.onosproject.cluster.PartitionId;
48import org.onosproject.net.provider.ProviderId;
49import org.onosproject.store.service.Versioned;
50import org.slf4j.Logger;
51
Madan Jampaniad3c5262016-01-20 00:50:17 -080052import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070053import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Ray Milkey6a51cb92018-03-06 09:03:03 -080054import static org.onlab.util.Tools.groupedThreads;
55import static org.slf4j.LoggerFactory.getLogger;
Madan Jampaniad3c5262016-01-20 00:50:17 -080056
57/**
58 * Provider of {@link ClusterMetadata cluster metadata} sourced from a local config file.
59 */
60@Component(immediate = true)
61public class ConfigFileBasedClusterMetadataProvider implements ClusterMetadataProvider {
62
63 private final Logger log = getLogger(getClass());
64
Madan Jampani898fcca2016-02-26 12:42:08 -080065 private static final String CONFIG_DIR = "../config";
66 private static final String CONFIG_FILE_NAME = "cluster.json";
67 private static final File CONFIG_FILE = new File(CONFIG_DIR, CONFIG_FILE_NAME);
Madan Jampaniad3c5262016-01-20 00:50:17 -080068
Ray Milkeyd84f89b2018-08-17 14:54:17 -070069 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Madan Jampaniad3c5262016-01-20 00:50:17 -080070 protected ClusterMetadataProviderRegistry providerRegistry;
71
Madan Jampanif172d402016-03-04 00:56:38 -080072 private static final ProviderId PROVIDER_ID = new ProviderId("file", "none");
Madan Jampani898fcca2016-02-26 12:42:08 -080073 private final AtomicReference<Versioned<ClusterMetadata>> cachedMetadata = new AtomicReference<>();
Madan Jampanif172d402016-03-04 00:56:38 -080074 private final ScheduledExecutorService configFileChangeDetector =
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070075 newSingleThreadScheduledExecutor(groupedThreads("onos/cluster/metadata/config-watcher", "", log));
Madan Jampaniad3c5262016-01-20 00:50:17 -080076
Madan Jampanif172d402016-03-04 00:56:38 -080077 private String metadataUrl;
Madan Jampaniad3c5262016-01-20 00:50:17 -080078 private ObjectMapper mapper;
79 private ClusterMetadataProviderService providerService;
80
81 @Activate
82 public void activate() {
83 mapper = new ObjectMapper();
Madan Jampaniad3c5262016-01-20 00:50:17 -080084 providerService = providerRegistry.register(this);
Madan Jampanif172d402016-03-04 00:56:38 -080085 metadataUrl = System.getProperty("onos.cluster.metadata.uri", "file://" + CONFIG_DIR + "/" + CONFIG_FILE);
86 configFileChangeDetector.scheduleWithFixedDelay(() -> watchUrl(metadataUrl), 100, 500, TimeUnit.MILLISECONDS);
Madan Jampaniad3c5262016-01-20 00:50:17 -080087 log.info("Started");
88 }
89
90 @Deactivate
91 public void deactivate() {
Madan Jampani898fcca2016-02-26 12:42:08 -080092 configFileChangeDetector.shutdown();
Madan Jampaniad3c5262016-01-20 00:50:17 -080093 providerRegistry.unregister(this);
94 log.info("Stopped");
95 }
96
97 @Override
98 public ProviderId id() {
99 return PROVIDER_ID;
100 }
101
102 @Override
103 public Versioned<ClusterMetadata> getClusterMetadata() {
104 checkState(isAvailable());
105 synchronized (this) {
106 if (cachedMetadata.get() == null) {
Jordan Haltermandbfff062017-06-19 10:31:32 -0700107 cachedMetadata.set(blockForMetadata(metadataUrl));
Madan Jampaniad3c5262016-01-20 00:50:17 -0800108 }
109 return cachedMetadata.get();
110 }
111 }
112
Jordan Halterman00e92da2018-05-22 23:05:52 -0700113 private ClusterMetadataPrototype toPrototype(ClusterMetadata metadata) {
114 ClusterMetadataPrototype prototype = new ClusterMetadataPrototype();
115 prototype.setName(metadata.getName());
Jordan Halterman19c123a2018-07-30 13:57:19 -0700116 prototype.setController(metadata.getNodes()
117 .stream()
118 .map(this::toPrototype)
119 .collect(Collectors.toSet()));
120 prototype.setStorage(metadata.getStorageNodes()
121 .stream()
122 .map(this::toPrototype)
123 .collect(Collectors.toSet()));
Jordan Halterman00e92da2018-05-22 23:05:52 -0700124 return prototype;
125 }
126
127 private NodePrototype toPrototype(Node node) {
128 NodePrototype prototype = new NodePrototype();
129 prototype.setId(node.id().id());
Jordan Haltermane458f002018-09-18 17:42:05 -0700130 prototype.setHost(node.host());
Jordan Halterman00e92da2018-05-22 23:05:52 -0700131 prototype.setPort(node.tcpPort());
132 return prototype;
133 }
134
Madan Jampaniad3c5262016-01-20 00:50:17 -0800135 @Override
136 public void setClusterMetadata(ClusterMetadata metadata) {
137 try {
Ray Milkey83200882017-11-13 19:18:21 -0800138 File configFile = new File(metadataUrl.replaceFirst("file://", ""));
139 Files.createParentDirs(configFile);
Jordan Halterman00e92da2018-05-22 23:05:52 -0700140 ClusterMetadataPrototype metadataPrototype = toPrototype(metadata);
141 mapper.writeValue(configFile, metadataPrototype);
Ray Milkey83200882017-11-13 19:18:21 -0800142 cachedMetadata.set(fetchMetadata(metadataUrl));
143 providerService.clusterMetadataChanged(new Versioned<>(metadata, configFile.lastModified()));
Madan Jampaniad3c5262016-01-20 00:50:17 -0800144 } catch (IOException e) {
Ray Milkey6a51cb92018-03-06 09:03:03 -0800145 throw new IllegalArgumentException(e);
Madan Jampaniad3c5262016-01-20 00:50:17 -0800146 }
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) {
Ray Milkey3717e602018-02-01 13:49:47 -0800182 long iterations = 0;
Jordan Haltermandbfff062017-06-19 10:31:32 -0700183 for (;;) {
Jordan Halterman9ada34a2017-10-23 16:31:50 -0700184 try {
185 Versioned<ClusterMetadata> metadata = fetchMetadata(metadataUrl);
186 if (metadata != null) {
187 return metadata;
188 }
189 } catch (Exception e) {
190 log.warn("Exception attempting to access metadata file at {}: {}", metadataUrl, e);
Jordan Haltermandbfff062017-06-19 10:31:32 -0700191 }
192
193 try {
Ray Milkey961b19f2018-02-05 13:47:55 -0800194 Thread.sleep((int) Math.pow(2, iterations < 7 ? ++iterations : iterations) * 10L);
Jordan Haltermandbfff062017-06-19 10:31:32 -0700195 } catch (InterruptedException e) {
Ray Milkey5c7d4882018-02-05 14:50:39 -0800196 Thread.currentThread().interrupt();
Ray Milkey6a51cb92018-03-06 09:03:03 -0800197 throw new IllegalStateException(e);
Jordan Haltermandbfff062017-06-19 10:31:32 -0700198 }
199 }
200 }
201
Jordan Haltermane458f002018-09-18 17:42:05 -0700202 private static NodeId getNodeId(NodePrototype node) {
203 if (node.getId() != null) {
204 return NodeId.nodeId(node.getId());
205 } else if (node.getHost() != null) {
206 return NodeId.nodeId(node.getHost());
207 } else if (node.getIp() != null) {
208 return NodeId.nodeId(node.getIp());
209 } else {
210 return NodeId.nodeId(UUID.randomUUID().toString());
211 }
212 }
213
214 private static String getNodeHost(NodePrototype node) {
215 if (node.getHost() != null) {
216 return node.getHost();
217 } else if (node.getIp() != null) {
218 return node.getIp();
219 } else {
220 throw new IllegalArgumentException(
221 "Malformed cluster configuration: No host specified for node " + node.getId());
222 }
223 }
224
225 private static int getNodePort(NodePrototype node) {
226 if (node.getPort() != null) {
227 return node.getPort();
228 }
229 return DefaultControllerNode.DEFAULT_PORT;
230 }
231
Madan Jampanif172d402016-03-04 00:56:38 -0800232 private Versioned<ClusterMetadata> fetchMetadata(String metadataUrl) {
Madan Jampaniad3c5262016-01-20 00:50:17 -0800233 try {
Madan Jampanif172d402016-03-04 00:56:38 -0800234 URL url = new URL(metadataUrl);
Jordan Halterman00e92da2018-05-22 23:05:52 -0700235 ClusterMetadataPrototype metadata = null;
Madan Jampanif172d402016-03-04 00:56:38 -0800236 long version = 0;
Jon Halla3fcf672017-03-28 16:53:22 -0700237 if ("file".equals(url.getProtocol())) {
Madan Jampanif172d402016-03-04 00:56:38 -0800238 File file = new File(metadataUrl.replaceFirst("file://", ""));
239 version = file.lastModified();
Jordan Halterman00e92da2018-05-22 23:05:52 -0700240 metadata = mapper.readValue(new FileInputStream(file), ClusterMetadataPrototype.class);
Jon Halla3fcf672017-03-28 16:53:22 -0700241 } else if ("http".equals(url.getProtocol())) {
Jordan Haltermanda268372017-09-19 11:18:08 -0700242 try {
243 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
244 if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
245 log.warn("Could not reach metadata URL {}. Retrying...", url);
246 return null;
247 }
248 if (conn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
249 return null;
250 }
251 version = conn.getLastModified();
Jordan Halterman00e92da2018-05-22 23:05:52 -0700252 metadata = mapper.readValue(conn.getInputStream(), ClusterMetadataPrototype.class);
Jordan Haltermanda268372017-09-19 11:18:08 -0700253 } catch (IOException e) {
Jordan Halterman46c76902017-08-24 14:55:25 -0700254 log.warn("Could not reach metadata URL {}. Retrying...", url);
255 return null;
256 }
Madan Jampanif172d402016-03-04 00:56:38 -0800257 }
Jordan Haltermandbfff062017-06-19 10:31:32 -0700258
zhiyong ke60e40002017-04-13 13:50:47 +0800259 if (null == metadata) {
260 log.warn("Metadata is null in the function fetchMetadata");
261 throw new NullPointerException();
262 }
Jordan Haltermandbfff062017-06-19 10:31:32 -0700263
Jordan Halterman00e92da2018-05-22 23:05:52 -0700264 return new Versioned<>(new ClusterMetadata(
265 PROVIDER_ID,
266 metadata.getName(),
267 metadata.getNode() != null ?
268 new DefaultControllerNode(
Jordan Haltermane458f002018-09-18 17:42:05 -0700269 getNodeId(metadata.getNode()),
270 getNodeHost(metadata.getNode()),
271 getNodePort(metadata.getNode())) : null,
Jordan Halterman19c123a2018-07-30 13:57:19 -0700272 metadata.getController()
273 .stream()
Jordan Haltermane458f002018-09-18 17:42:05 -0700274 .map(node -> new DefaultControllerNode(getNodeId(node), getNodeHost(node), getNodePort(node)))
Jordan Halterman19c123a2018-07-30 13:57:19 -0700275 .collect(Collectors.toSet()),
276 metadata.getStorage()
277 .stream()
Jordan Haltermane458f002018-09-18 17:42:05 -0700278 .map(node -> new DefaultControllerNode(getNodeId(node), getNodeHost(node), getNodePort(node)))
Jordan Halterman19c123a2018-07-30 13:57:19 -0700279 .collect(Collectors.toSet())),
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();
Jordan Halterman00e92da2018-05-22 23:05:52 -0700312
313 public String getName() {
314 return name;
315 }
316
317 public void setName(String name) {
318 this.name = name;
319 }
320
321 public NodePrototype getNode() {
322 return node;
323 }
324
325 public void setNode(NodePrototype node) {
326 this.node = node;
327 }
328
Jordan Halterman19c123a2018-07-30 13:57:19 -0700329 public Set<NodePrototype> getController() {
330 return controller;
Jordan Halterman00e92da2018-05-22 23:05:52 -0700331 }
332
Jordan Halterman19c123a2018-07-30 13:57:19 -0700333 public void setController(Set<NodePrototype> controller) {
334 this.controller = controller;
335 }
336
337 public Set<NodePrototype> getStorage() {
338 return storage;
339 }
340
341 public void setStorage(Set<NodePrototype> storage) {
342 this.storage = storage;
Jordan Halterman00e92da2018-05-22 23:05:52 -0700343 }
344 }
345
346 private static class NodePrototype {
347 private String id;
348 private String ip;
Jordan Haltermane458f002018-09-18 17:42:05 -0700349 private String host;
Jordan Halterman00e92da2018-05-22 23:05:52 -0700350 private Integer port;
351
352 public String getId() {
353 return id;
354 }
355
356 public void setId(String id) {
357 this.id = id;
358 }
359
360 public String getIp() {
361 return ip;
362 }
363
364 public void setIp(String ip) {
365 this.ip = ip;
366 }
367
Jordan Haltermane458f002018-09-18 17:42:05 -0700368 public String getHost() {
369 return host;
370 }
371
372 public void setHost(String host) {
373 this.host = host;
374 }
375
Jordan Halterman00e92da2018-05-22 23:05:52 -0700376 public Integer getPort() {
377 return port;
378 }
379
380 public void setPort(Integer port) {
381 this.port = port;
382 }
383 }
Madan Jampaniad3c5262016-01-20 00:50:17 -0800384}