blob: 308707eb7328dcf1e9f4cb99a79229ce19a4f463 [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";
Jian Li8f944d42021-03-23 00:43:29 +090090 private static final String NETWORK_POLICIES = "networkPolicies";
91 private static final String SECURITY_GROUPS = "securityGroups";
Jian Lib6dc08f2021-03-24 15:24:18 +090092 private static final String NAME = "name";
93 private static final String NETWORK = "network";
94 private static final String MAC = "macAddress";
95 private static final String IP = "ipAddress";
96 private static final String DEFAULT = "default";
97 private static final String NETWORK_SUFFIX = "-net";
98
99 @Reference(cardinality = ReferenceCardinality.MANDATORY)
100 protected CoreService coreService;
101
102 @Reference(cardinality = ReferenceCardinality.MANDATORY)
103 protected MastershipService mastershipService;
104
105 @Reference(cardinality = ReferenceCardinality.MANDATORY)
106 protected ClusterService clusterService;
107
108 @Reference(cardinality = ReferenceCardinality.MANDATORY)
109 protected LeadershipService leadershipService;
110
111 @Reference(cardinality = ReferenceCardinality.MANDATORY)
112 protected KubevirtNodeService nodeService;
113
114 @Reference(cardinality = ReferenceCardinality.MANDATORY)
115 protected KubevirtNetworkAdminService networkAdminService;
116
117 @Reference(cardinality = ReferenceCardinality.MANDATORY)
118 protected KubevirtPortAdminService portAdminService;
119
120 @Reference(cardinality = ReferenceCardinality.MANDATORY)
121 protected KubevirtPodService podService;
122
123 @Reference(cardinality = ReferenceCardinality.MANDATORY)
124 protected KubevirtApiConfigService configService;
125
126 private final ExecutorService eventExecutor = newSingleThreadExecutor(
127 groupedThreads(this.getClass().getSimpleName(), "event-handler"));
128
129 private final InternalKubevirtVmWatcher watcher = new InternalKubevirtVmWatcher();
130 private final InternalKubevirtApiConfigListener
131 configListener = new InternalKubevirtApiConfigListener();
132
133 CustomResourceDefinitionContext vmCrdCxt = new CustomResourceDefinitionContext
134 .Builder()
135 .withGroup("kubevirt.io")
136 .withScope("Namespaced")
137 .withVersion("v1")
138 .withPlural("virtualmachines")
139 .build();
140
141 private ApplicationId appId;
142 private NodeId localNodeId;
143
144 @Activate
145 protected void activate() {
146 appId = coreService.registerApplication(KUBEVIRT_NETWORKING_APP_ID);
147 localNodeId = clusterService.getLocalNode().id();
148 leadershipService.runForLeadership(appId.name());
149 configService.addListener(configListener);
150
151 log.info("Started");
152 }
153
154 @Deactivate
155 protected void deactivate() {
156 configService.removeListener(configListener);
157 leadershipService.withdraw(appId.name());
158 eventExecutor.shutdown();
159
160 log.info("Stopped");
161 }
162
163 private void instantiateWatcher() {
164 KubernetesClient client = k8sClient(configService);
165
166 if (client != null) {
167 try {
168 client.customResource(vmCrdCxt).watch(watcher);
169 } catch (IOException e) {
170 e.printStackTrace();
171 }
172 }
173 }
174
175 private class InternalKubevirtApiConfigListener implements KubevirtApiConfigListener {
176
177 private boolean isRelevantHelper() {
178 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
179 }
180
181 @Override
182 public void event(KubevirtApiConfigEvent event) {
183
184 switch (event.type()) {
185 case KUBEVIRT_API_CONFIG_UPDATED:
186 eventExecutor.execute(this::processConfigUpdate);
187 break;
188 case KUBEVIRT_API_CONFIG_CREATED:
189 case KUBEVIRT_API_CONFIG_REMOVED:
190 default:
191 // do nothing
192 break;
193 }
194 }
195
196 private void processConfigUpdate() {
197 if (!isRelevantHelper()) {
198 return;
199 }
200
201 instantiateWatcher();
202 }
203 }
204
205 private class InternalKubevirtVmWatcher implements Watcher<String> {
206
207 @Override
208 public void eventReceived(Action action, String resource) {
209 switch (action) {
210 case ADDED:
211 eventExecutor.execute(() -> processAddition(resource));
212 break;
213 case DELETED:
214 eventExecutor.execute(() -> processDeletion(resource));
215 break;
Jian Li8f944d42021-03-23 00:43:29 +0900216 case MODIFIED:
217 eventExecutor.execute(() -> processModification(resource));
218 break;
Jian Lib6dc08f2021-03-24 15:24:18 +0900219 case ERROR:
220 log.warn("Failures processing VM manipulation.");
221 break;
222 default:
223 break;
224 }
225 }
226
227 @Override
228 public void onClose(WatcherException e) {
229 log.warn("VM watcher OnClose, re-instantiate the VM watcher...");
230 instantiateWatcher();
231 }
232
233 private void processAddition(String resource) {
234 if (!isMaster()) {
235 return;
236 }
237
238 parseMacAddresses(resource).forEach((mac, net) -> {
239 KubevirtPort port = DefaultKubevirtPort.builder()
240 .macAddress(mac)
241 .networkId(net)
242 .build();
243
244 String name = parseResourceName(resource);
245
Jian Li8f944d42021-03-23 00:43:29 +0900246 Set<String> sgs = parseSecurityGroups(resource);
247 port = port.updateSecurityGroups(sgs);
248
Jian Lib6dc08f2021-03-24 15:24:18 +0900249 Map<String, IpAddress> ips = parseIpAddresses(resource);
250 IpAddress ip;
251 IpAddress existingIp = ips.get(port.networkId());
252
253 KubevirtNetwork network = networkAdminService.network(port.networkId());
254 if (network == null) {
255 try {
256 sleep(SLEEP_MS);
257 } catch (InterruptedException e) {
258 e.printStackTrace();
259 }
260 }
261
262 KubevirtPort existingPort = portAdminService.port(port.macAddress());
263
264 if (existingIp == null) {
265
266 KubernetesClient client = k8sClient(configService);
267
268 if (client == null) {
269 return;
270 }
271
272 ip = networkAdminService.allocateIp(port.networkId());
273 log.info("IP address {} is allocated from network {}", ip, port.networkId());
274
275 try {
276 // we wait a while to avoid potentially referring to old version resource
277 // FIXME: we may need to find a better solution to avoid this
278 sleep(SLEEP_MS);
279 ObjectMapper mapper = new ObjectMapper();
280 Map<String, Object> newResource = client.customResource(vmCrdCxt).get(DEFAULT, name);
281 String newResourceStr = mapper.writeValueAsString(newResource);
282 String updatedResource = updateIpAddress(newResourceStr, port.networkId(), ip);
283 client.customResource(vmCrdCxt).edit(DEFAULT, name, updatedResource);
284 } catch (IOException | InterruptedException e) {
285 log.error("Failed to annotate IP addresses", e);
286 } catch (KubernetesClientException kce) {
287 log.error("Failed to update VM resource", kce);
288 }
289
290 } else {
291 if (existingPort != null) {
292 return;
293 }
294
295 ip = existingIp;
296 networkAdminService.reserveIp(port.networkId(), ip);
297 log.info("IP address {} is reserved from network {}", ip, port.networkId());
298 }
299
300 if (existingPort == null) {
301 KubevirtPort updated = port.updateIpAddress(ip);
302
303 DeviceId deviceId = getDeviceId(podService.pods(), port);
304
305 if (deviceId != null) {
306 updated = updated.updateDeviceId(deviceId);
307 }
308
309 portAdminService.createPort(updated);
310 }
311 });
312 }
313
Jian Li8f944d42021-03-23 00:43:29 +0900314 private void processModification(String resource) {
315 if (!isMaster()) {
316 return;
317 }
318
319 parseMacAddresses(resource).forEach((mac, net) -> {
320 KubevirtPort port = DefaultKubevirtPort.builder()
321 .macAddress(mac)
322 .networkId(net)
323 .build();
324
325 KubevirtPort existing = portAdminService.port(port.macAddress());
326
327 if (existing == null) {
328 return;
329 }
330
331 Set<String> sgs = parseSecurityGroups(resource);
332 portAdminService.updatePort(existing.updateSecurityGroups(sgs));
333 });
334 }
335
Jian Lib6dc08f2021-03-24 15:24:18 +0900336 private void processDeletion(String resource) {
337 if (!isMaster()) {
338 return;
339 }
340
341 parseMacAddresses(resource).forEach((mac, net) -> {
342 KubevirtPort port = portAdminService.port(mac);
343 if (port != null) {
344 networkAdminService.releaseIp(port.networkId(), port.ipAddress());
345 log.info("IP address {} is released from network {}",
346 port.ipAddress(), port.networkId());
347
348 portAdminService.removePort(mac);
349 }
350 });
351 }
352
353 private boolean isMaster() {
354 return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
355 }
356
357 // FIXME: to obtains the device ID, we have to search through
358 // existing POD inventory, need to find a better wat to obtain device ID
359 private DeviceId getDeviceId(Set<Pod> pods, KubevirtPort port) {
360 Set<Pod> defaultPods = pods.stream()
361 .filter(pod -> pod.getMetadata().getNamespace().equals(DEFAULT))
362 .collect(Collectors.toSet());
363
364 Set<KubevirtPort> allPorts = new HashSet<>();
365 for (Pod pod : defaultPods) {
366 allPorts.addAll(getPorts(nodeService, networkAdminService.networks(), pod));
367 }
368
369 return allPorts.stream().filter(p -> p.macAddress().equals(port.macAddress()))
370 .map(KubevirtPort::deviceId).findFirst().orElse(null);
371 }
372
373 private Map<String, IpAddress> parseIpAddresses(String resource) {
374 try {
375 ObjectMapper mapper = new ObjectMapper();
376 JsonNode json = mapper.readTree(resource);
377 JsonNode metadata = json.get(SPEC).get(TEMPLATE).get(METADATA);
378
379 JsonNode annots = metadata.get(ANNOTATIONS);
380 if (annots == null) {
381 return new HashMap<>();
382 }
383
384 JsonNode interfacesJson = annots.get(INTERFACES);
385 if (interfacesJson == null) {
386 return new HashMap<>();
387 }
388
389 Map<String, IpAddress> result = new HashMap<>();
390
391 String interfacesString = interfacesJson.asText();
392 ArrayNode interfaces = (ArrayNode) mapper.readTree(interfacesString);
393 for (JsonNode intf : interfaces) {
394 String network = intf.get(NETWORK).asText();
395 String ip = intf.get(IP).asText();
396 result.put(network, IpAddress.valueOf(ip));
397 }
398
399 return result;
400 } catch (IOException e) {
401 log.error("Failed to parse kubevirt VM IP addresses");
402 }
403
404 return new HashMap<>();
405 }
406
407 private String updateIpAddress(String resource, String network, IpAddress ip) {
408 try {
409 ObjectMapper mapper = new ObjectMapper();
410 ObjectNode json = (ObjectNode) mapper.readTree(resource);
411 ObjectNode spec = (ObjectNode) json.get(SPEC);
412 ObjectNode template = (ObjectNode) spec.get(TEMPLATE);
413 ObjectNode metadata = (ObjectNode) template.get(METADATA);
414 ObjectNode annots = (ObjectNode) metadata.get(ANNOTATIONS);
415
416 if (!annots.has(INTERFACES)) {
417 annots.put(INTERFACES, "[]");
418 }
419
420 String intfs = annots.get(INTERFACES).asText();
421 ArrayNode intfsJson = (ArrayNode) mapper.readTree(intfs);
422
423 ObjectNode intf = mapper.createObjectNode();
424 intf.put(NETWORK, network);
425 intf.put(IP, ip.toString());
426
427 intfsJson.add(intf);
428
429 annots.put(INTERFACES, intfsJson.toString());
430 metadata.set(ANNOTATIONS, annots);
431 template.set(METADATA, metadata);
432 spec.set(TEMPLATE, template);
433 json.set(SPEC, spec);
434
435 return json.toString();
436
437 } catch (IOException e) {
438 log.error("Failed to update kubevirt VM IP addresses");
439 }
440 return null;
441 }
442
Jian Li8f944d42021-03-23 00:43:29 +0900443 private Set<String> parseSecurityGroups(String resource) {
444 try {
445 ObjectMapper mapper = new ObjectMapper();
446 JsonNode json = mapper.readTree(resource);
447 JsonNode metadata = json.get(SPEC).get(TEMPLATE).get(METADATA);
448
449 JsonNode annots = metadata.get(ANNOTATIONS);
450 if (annots == null) {
451 return new HashSet<>();
452 }
453
454 JsonNode sgsJson = annots.get(SECURITY_GROUPS);
455 if (sgsJson == null) {
456 return new HashSet<>();
457 }
458
459 Set<String> result = new HashSet<>();
460 ArrayNode sgs = (ArrayNode) mapper.readTree(sgsJson.asText());
461 for (JsonNode sg : sgs) {
462 result.add(sg.asText());
463 }
464
465 return result;
466
467 } catch (IOException e) {
468 log.error("Failed to parse kubevirt security group IDs.");
469 }
470
471 return new HashSet<>();
472 }
473
Jian Lib6dc08f2021-03-24 15:24:18 +0900474 private Map<MacAddress, String> parseMacAddresses(String resource) {
475 try {
476 ObjectMapper mapper = new ObjectMapper();
477 JsonNode json = mapper.readTree(resource);
478 JsonNode spec = json.get(SPEC).get(TEMPLATE).get(SPEC);
479 ArrayNode interfaces = (ArrayNode) spec.get(DOMAIN).get(DEVICES).get(INTERFACES);
480
481 Map<MacAddress, String> result = new HashMap<>();
482 for (JsonNode intf : interfaces) {
483 String network = intf.get(NAME).asText();
484 JsonNode macJson = intf.get(MAC);
485
486 if (!DEFAULT.equals(network) && macJson != null) {
487 String compact = StringUtils.substringBeforeLast(network, NETWORK_SUFFIX);
488 MacAddress mac = MacAddress.valueOf(macJson.asText());
489 result.put(mac, compact);
490 }
491 }
492
493 return result;
494 } catch (IOException e) {
495 log.error("Failed to parse kubevirt VM MAC addresses");
496 }
497
498 return new HashMap<>();
499 }
500 }
501}