blob: 61b9be01f56b5d3189cc8ca3dd426ee0809183c5 [file] [log] [blame]
Jian Lib6dc08f2021-03-24 15:24:18 +09001/*
2 * Copyright 2021-present Open Networking Foundation
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 */
16package org.onosproject.kubevirtnetworking.impl;
17
18import com.fasterxml.jackson.databind.JsonNode;
19import com.fasterxml.jackson.databind.ObjectMapper;
20import com.fasterxml.jackson.databind.node.ArrayNode;
21import com.fasterxml.jackson.databind.node.ObjectNode;
22import io.fabric8.kubernetes.api.model.Pod;
23import io.fabric8.kubernetes.client.KubernetesClient;
24import io.fabric8.kubernetes.client.KubernetesClientException;
25import io.fabric8.kubernetes.client.Watcher;
26import io.fabric8.kubernetes.client.WatcherException;
27import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext;
28import org.apache.commons.lang3.StringUtils;
29import org.onlab.packet.IpAddress;
30import org.onlab.packet.MacAddress;
31import org.onosproject.cluster.ClusterService;
32import org.onosproject.cluster.LeadershipService;
33import org.onosproject.cluster.NodeId;
34import org.onosproject.core.ApplicationId;
35import org.onosproject.core.CoreService;
36import org.onosproject.kubevirtnetworking.api.DefaultKubevirtPort;
37import org.onosproject.kubevirtnetworking.api.KubevirtNetwork;
38import org.onosproject.kubevirtnetworking.api.KubevirtNetworkAdminService;
39import org.onosproject.kubevirtnetworking.api.KubevirtPodService;
40import org.onosproject.kubevirtnetworking.api.KubevirtPort;
41import org.onosproject.kubevirtnetworking.api.KubevirtPortAdminService;
42import org.onosproject.kubevirtnode.api.KubevirtApiConfigEvent;
43import org.onosproject.kubevirtnode.api.KubevirtApiConfigListener;
44import org.onosproject.kubevirtnode.api.KubevirtApiConfigService;
45import org.onosproject.kubevirtnode.api.KubevirtNodeService;
46import org.onosproject.mastership.MastershipService;
47import org.onosproject.net.DeviceId;
48import org.osgi.service.component.annotations.Activate;
49import org.osgi.service.component.annotations.Component;
50import org.osgi.service.component.annotations.Deactivate;
51import org.osgi.service.component.annotations.Reference;
52import org.osgi.service.component.annotations.ReferenceCardinality;
53import org.slf4j.Logger;
54
55import java.io.IOException;
56import java.util.HashMap;
57import java.util.HashSet;
58import java.util.Map;
59import java.util.Objects;
60import java.util.Set;
61import java.util.concurrent.ExecutorService;
62import java.util.stream.Collectors;
63
64import static java.lang.Thread.sleep;
65import static java.util.concurrent.Executors.newSingleThreadExecutor;
66import static org.onlab.util.Tools.groupedThreads;
67import static org.onosproject.kubevirtnetworking.api.Constants.KUBEVIRT_NETWORKING_APP_ID;
68import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.getPorts;
69import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.k8sClient;
70import static org.onosproject.kubevirtnetworking.util.KubevirtNetworkingUtil.parseResourceName;
71import static org.slf4j.LoggerFactory.getLogger;
72
73/**
74 * Kubernetes VM watcher used for feeding VM information.
75 */
76@Component(immediate = true)
77public class KubevirtVmWatcher {
78
79 private final Logger log = getLogger(getClass());
80
81 private static final long SLEEP_MS = 3000; // we wait 3s
82
83 private static final String SPEC = "spec";
84 private static final String TEMPLATE = "template";
85 private static final String METADATA = "metadata";
86 private static final String ANNOTATIONS = "annotations";
87 private static final String DOMAIN = "domain";
88 private static final String DEVICES = "devices";
89 private static final String INTERFACES = "interfaces";
90 private static final String NAME = "name";
91 private static final String NETWORK = "network";
92 private static final String MAC = "macAddress";
93 private static final String IP = "ipAddress";
94 private static final String DEFAULT = "default";
95 private static final String NETWORK_SUFFIX = "-net";
96
97 @Reference(cardinality = ReferenceCardinality.MANDATORY)
98 protected CoreService coreService;
99
100 @Reference(cardinality = ReferenceCardinality.MANDATORY)
101 protected MastershipService mastershipService;
102
103 @Reference(cardinality = ReferenceCardinality.MANDATORY)
104 protected ClusterService clusterService;
105
106 @Reference(cardinality = ReferenceCardinality.MANDATORY)
107 protected LeadershipService leadershipService;
108
109 @Reference(cardinality = ReferenceCardinality.MANDATORY)
110 protected KubevirtNodeService nodeService;
111
112 @Reference(cardinality = ReferenceCardinality.MANDATORY)
113 protected KubevirtNetworkAdminService networkAdminService;
114
115 @Reference(cardinality = ReferenceCardinality.MANDATORY)
116 protected KubevirtPortAdminService portAdminService;
117
118 @Reference(cardinality = ReferenceCardinality.MANDATORY)
119 protected KubevirtPodService podService;
120
121 @Reference(cardinality = ReferenceCardinality.MANDATORY)
122 protected KubevirtApiConfigService configService;
123
124 private final ExecutorService eventExecutor = newSingleThreadExecutor(
125 groupedThreads(this.getClass().getSimpleName(), "event-handler"));
126
127 private final InternalKubevirtVmWatcher watcher = new InternalKubevirtVmWatcher();
128 private final InternalKubevirtApiConfigListener
129 configListener = new InternalKubevirtApiConfigListener();
130
131 CustomResourceDefinitionContext vmCrdCxt = new CustomResourceDefinitionContext
132 .Builder()
133 .withGroup("kubevirt.io")
134 .withScope("Namespaced")
135 .withVersion("v1")
136 .withPlural("virtualmachines")
137 .build();
138
139 private ApplicationId appId;
140 private NodeId localNodeId;
141
142 @Activate
143 protected void activate() {
144 appId = coreService.registerApplication(KUBEVIRT_NETWORKING_APP_ID);
145 localNodeId = clusterService.getLocalNode().id();
146 leadershipService.runForLeadership(appId.name());
147 configService.addListener(configListener);
148
149 log.info("Started");
150 }
151
152 @Deactivate
153 protected void deactivate() {
154 configService.removeListener(configListener);
155 leadershipService.withdraw(appId.name());
156 eventExecutor.shutdown();
157
158 log.info("Stopped");
159 }
160
161 private void instantiateWatcher() {
162 KubernetesClient client = k8sClient(configService);
163
164 if (client != null) {
165 try {
166 client.customResource(vmCrdCxt).watch(watcher);
167 } catch (IOException e) {
168 e.printStackTrace();
169 }
170 }
171 }
172
173 private class InternalKubevirtApiConfigListener implements KubevirtApiConfigListener {
174
175 private boolean isRelevantHelper() {
176 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
177 }
178
179 @Override
180 public void event(KubevirtApiConfigEvent event) {
181
182 switch (event.type()) {
183 case KUBEVIRT_API_CONFIG_UPDATED:
184 eventExecutor.execute(this::processConfigUpdate);
185 break;
186 case KUBEVIRT_API_CONFIG_CREATED:
187 case KUBEVIRT_API_CONFIG_REMOVED:
188 default:
189 // do nothing
190 break;
191 }
192 }
193
194 private void processConfigUpdate() {
195 if (!isRelevantHelper()) {
196 return;
197 }
198
199 instantiateWatcher();
200 }
201 }
202
203 private class InternalKubevirtVmWatcher implements Watcher<String> {
204
205 @Override
206 public void eventReceived(Action action, String resource) {
207 switch (action) {
208 case ADDED:
209 eventExecutor.execute(() -> processAddition(resource));
210 break;
211 case DELETED:
212 eventExecutor.execute(() -> processDeletion(resource));
213 break;
214 case ERROR:
215 log.warn("Failures processing VM manipulation.");
216 break;
217 default:
218 break;
219 }
220 }
221
222 @Override
223 public void onClose(WatcherException e) {
224 log.warn("VM watcher OnClose, re-instantiate the VM watcher...");
225 instantiateWatcher();
226 }
227
228 private void processAddition(String resource) {
229 if (!isMaster()) {
230 return;
231 }
232
233 parseMacAddresses(resource).forEach((mac, net) -> {
234 KubevirtPort port = DefaultKubevirtPort.builder()
235 .macAddress(mac)
236 .networkId(net)
237 .build();
238
239 String name = parseResourceName(resource);
240
241 Map<String, IpAddress> ips = parseIpAddresses(resource);
242 IpAddress ip;
243 IpAddress existingIp = ips.get(port.networkId());
244
245 KubevirtNetwork network = networkAdminService.network(port.networkId());
246 if (network == null) {
247 try {
248 sleep(SLEEP_MS);
249 } catch (InterruptedException e) {
250 e.printStackTrace();
251 }
252 }
253
254 KubevirtPort existingPort = portAdminService.port(port.macAddress());
255
256 if (existingIp == null) {
257
258 KubernetesClient client = k8sClient(configService);
259
260 if (client == null) {
261 return;
262 }
263
264 ip = networkAdminService.allocateIp(port.networkId());
265 log.info("IP address {} is allocated from network {}", ip, port.networkId());
266
267 try {
268 // we wait a while to avoid potentially referring to old version resource
269 // FIXME: we may need to find a better solution to avoid this
270 sleep(SLEEP_MS);
271 ObjectMapper mapper = new ObjectMapper();
272 Map<String, Object> newResource = client.customResource(vmCrdCxt).get(DEFAULT, name);
273 String newResourceStr = mapper.writeValueAsString(newResource);
274 String updatedResource = updateIpAddress(newResourceStr, port.networkId(), ip);
275 client.customResource(vmCrdCxt).edit(DEFAULT, name, updatedResource);
276 } catch (IOException | InterruptedException e) {
277 log.error("Failed to annotate IP addresses", e);
278 } catch (KubernetesClientException kce) {
279 log.error("Failed to update VM resource", kce);
280 }
281
282 } else {
283 if (existingPort != null) {
284 return;
285 }
286
287 ip = existingIp;
288 networkAdminService.reserveIp(port.networkId(), ip);
289 log.info("IP address {} is reserved from network {}", ip, port.networkId());
290 }
291
292 if (existingPort == null) {
293 KubevirtPort updated = port.updateIpAddress(ip);
294
295 DeviceId deviceId = getDeviceId(podService.pods(), port);
296
297 if (deviceId != null) {
298 updated = updated.updateDeviceId(deviceId);
299 }
300
301 portAdminService.createPort(updated);
302 }
303 });
304 }
305
306 private void processDeletion(String resource) {
307 if (!isMaster()) {
308 return;
309 }
310
311 parseMacAddresses(resource).forEach((mac, net) -> {
312 KubevirtPort port = portAdminService.port(mac);
313 if (port != null) {
314 networkAdminService.releaseIp(port.networkId(), port.ipAddress());
315 log.info("IP address {} is released from network {}",
316 port.ipAddress(), port.networkId());
317
318 portAdminService.removePort(mac);
319 }
320 });
321 }
322
323 private boolean isMaster() {
324 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
325 }
326
327 // FIXME: to obtains the device ID, we have to search through
328 // existing POD inventory, need to find a better wat to obtain device ID
329 private DeviceId getDeviceId(Set<Pod> pods, KubevirtPort port) {
330 Set<Pod> defaultPods = pods.stream()
331 .filter(pod -> pod.getMetadata().getNamespace().equals(DEFAULT))
332 .collect(Collectors.toSet());
333
334 Set<KubevirtPort> allPorts = new HashSet<>();
335 for (Pod pod : defaultPods) {
336 allPorts.addAll(getPorts(nodeService, networkAdminService.networks(), pod));
337 }
338
339 return allPorts.stream().filter(p -> p.macAddress().equals(port.macAddress()))
340 .map(KubevirtPort::deviceId).findFirst().orElse(null);
341 }
342
343 private Map<String, IpAddress> parseIpAddresses(String resource) {
344 try {
345 ObjectMapper mapper = new ObjectMapper();
346 JsonNode json = mapper.readTree(resource);
347 JsonNode metadata = json.get(SPEC).get(TEMPLATE).get(METADATA);
348
349 JsonNode annots = metadata.get(ANNOTATIONS);
350 if (annots == null) {
351 return new HashMap<>();
352 }
353
354 JsonNode interfacesJson = annots.get(INTERFACES);
355 if (interfacesJson == null) {
356 return new HashMap<>();
357 }
358
359 Map<String, IpAddress> result = new HashMap<>();
360
361 String interfacesString = interfacesJson.asText();
362 ArrayNode interfaces = (ArrayNode) mapper.readTree(interfacesString);
363 for (JsonNode intf : interfaces) {
364 String network = intf.get(NETWORK).asText();
365 String ip = intf.get(IP).asText();
366 result.put(network, IpAddress.valueOf(ip));
367 }
368
369 return result;
370 } catch (IOException e) {
371 log.error("Failed to parse kubevirt VM IP addresses");
372 }
373
374 return new HashMap<>();
375 }
376
377 private String updateIpAddress(String resource, String network, IpAddress ip) {
378 try {
379 ObjectMapper mapper = new ObjectMapper();
380 ObjectNode json = (ObjectNode) mapper.readTree(resource);
381 ObjectNode spec = (ObjectNode) json.get(SPEC);
382 ObjectNode template = (ObjectNode) spec.get(TEMPLATE);
383 ObjectNode metadata = (ObjectNode) template.get(METADATA);
384 ObjectNode annots = (ObjectNode) metadata.get(ANNOTATIONS);
385
386 if (!annots.has(INTERFACES)) {
387 annots.put(INTERFACES, "[]");
388 }
389
390 String intfs = annots.get(INTERFACES).asText();
391 ArrayNode intfsJson = (ArrayNode) mapper.readTree(intfs);
392
393 ObjectNode intf = mapper.createObjectNode();
394 intf.put(NETWORK, network);
395 intf.put(IP, ip.toString());
396
397 intfsJson.add(intf);
398
399 annots.put(INTERFACES, intfsJson.toString());
400 metadata.set(ANNOTATIONS, annots);
401 template.set(METADATA, metadata);
402 spec.set(TEMPLATE, template);
403 json.set(SPEC, spec);
404
405 return json.toString();
406
407 } catch (IOException e) {
408 log.error("Failed to update kubevirt VM IP addresses");
409 }
410 return null;
411 }
412
413 private Map<MacAddress, String> parseMacAddresses(String resource) {
414 try {
415 ObjectMapper mapper = new ObjectMapper();
416 JsonNode json = mapper.readTree(resource);
417 JsonNode spec = json.get(SPEC).get(TEMPLATE).get(SPEC);
418 ArrayNode interfaces = (ArrayNode) spec.get(DOMAIN).get(DEVICES).get(INTERFACES);
419
420 Map<MacAddress, String> result = new HashMap<>();
421 for (JsonNode intf : interfaces) {
422 String network = intf.get(NAME).asText();
423 JsonNode macJson = intf.get(MAC);
424
425 if (!DEFAULT.equals(network) && macJson != null) {
426 String compact = StringUtils.substringBeforeLast(network, NETWORK_SUFFIX);
427 MacAddress mac = MacAddress.valueOf(macJson.asText());
428 result.put(mac, compact);
429 }
430 }
431
432 return result;
433 } catch (IOException e) {
434 log.error("Failed to parse kubevirt VM MAC addresses");
435 }
436
437 return new HashMap<>();
438 }
439 }
440}