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