blob: 5a9ce5cc5dca87e0b7837abaaca825076ed2100c [file] [log] [blame]
Jian Lie2a53cb2020-12-19 01:26:57 +09001/*
2 * Copyright 2020-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.kubevirtnode.web;
17
Jian Lib230e07c2020-12-21 11:25:12 +090018import com.fasterxml.jackson.databind.JsonNode;
19import com.fasterxml.jackson.databind.node.ArrayNode;
20import com.fasterxml.jackson.databind.node.ObjectNode;
21import com.google.common.collect.Sets;
Jian Lidd5172e2022-03-05 00:03:35 +090022import io.fabric8.kubernetes.client.KubernetesClient;
Jian Lif54f8a62021-05-22 00:10:15 +090023import org.onosproject.kubevirtnode.api.KubevirtApiConfig;
24import org.onosproject.kubevirtnode.api.KubevirtApiConfigService;
Jian Lib230e07c2020-12-21 11:25:12 +090025import org.onosproject.kubevirtnode.api.KubevirtNode;
26import org.onosproject.kubevirtnode.api.KubevirtNodeAdminService;
Jian Lie0eaf5c2021-09-06 10:02:13 +090027import org.onosproject.kubevirtnode.api.KubevirtNodeService;
Jian Lib230e07c2020-12-21 11:25:12 +090028import org.onosproject.kubevirtnode.api.KubevirtNodeState;
Jian Lie2a53cb2020-12-19 01:26:57 +090029import org.onosproject.rest.AbstractWebResource;
30import org.slf4j.Logger;
31import org.slf4j.LoggerFactory;
32
33import javax.ws.rs.Consumes;
Jian Lib230e07c2020-12-21 11:25:12 +090034import javax.ws.rs.DELETE;
35import javax.ws.rs.GET;
Jian Lie2a53cb2020-12-19 01:26:57 +090036import javax.ws.rs.POST;
Jian Lib230e07c2020-12-21 11:25:12 +090037import javax.ws.rs.PUT;
Jian Lie2a53cb2020-12-19 01:26:57 +090038import javax.ws.rs.Path;
Jian Lib230e07c2020-12-21 11:25:12 +090039import javax.ws.rs.PathParam;
Jian Lie2a53cb2020-12-19 01:26:57 +090040import javax.ws.rs.Produces;
Jian Lib230e07c2020-12-21 11:25:12 +090041import javax.ws.rs.core.Context;
Jian Lie2a53cb2020-12-19 01:26:57 +090042import javax.ws.rs.core.MediaType;
43import javax.ws.rs.core.Response;
Jian Lib230e07c2020-12-21 11:25:12 +090044import javax.ws.rs.core.UriBuilder;
45import javax.ws.rs.core.UriInfo;
Jian Lie2a53cb2020-12-19 01:26:57 +090046import java.io.InputStream;
Jian Lidd5172e2022-03-05 00:03:35 +090047import java.util.HashSet;
Jian Lib230e07c2020-12-21 11:25:12 +090048import java.util.Set;
Jian Lidd5172e2022-03-05 00:03:35 +090049import java.util.stream.Collectors;
Jian Lie2a53cb2020-12-19 01:26:57 +090050
Jian Lib230e07c2020-12-21 11:25:12 +090051import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
52import static javax.ws.rs.core.Response.created;
53import static org.onlab.util.Tools.nullIsIllegal;
54import static org.onlab.util.Tools.readTreeFromStream;
Jian Lidd5172e2022-03-05 00:03:35 +090055import static org.onosproject.kubevirtnode.api.KubevirtNode.Type.WORKER;
Jian Libe478b72021-05-14 15:21:08 +090056import static org.onosproject.kubevirtnode.api.KubevirtNodeState.COMPLETE;
57import static org.onosproject.kubevirtnode.api.KubevirtNodeState.INIT;
Jian Lidd5172e2022-03-05 00:03:35 +090058import static org.onosproject.kubevirtnode.util.KubevirtNodeUtil.getNodeType;
59import static org.onosproject.kubevirtnode.util.KubevirtNodeUtil.k8sClient;
Jian Li528335e2021-07-08 20:52:50 +090060import static org.onosproject.kubevirtnode.util.KubevirtNodeUtil.waitFor;
Jian Lib230e07c2020-12-21 11:25:12 +090061
62/**
63 * Handles REST API call of KubeVirt node config.
64 */
Jian Lif2483072020-12-25 02:24:16 +090065@Path("node")
Jian Lie2a53cb2020-12-19 01:26:57 +090066public class KubevirtNodeWebResource extends AbstractWebResource {
67
68 private final Logger log = LoggerFactory.getLogger(getClass());
69
Jian Lib230e07c2020-12-21 11:25:12 +090070 private static final String MESSAGE_NODE = "Received node %s request";
71 private static final String NODES = "nodes";
72 private static final String CREATE = "CREATE";
73 private static final String UPDATE = "UPDATE";
74 private static final String NODE_ID = "NODE_ID";
75 private static final String REMOVE = "REMOVE";
76 private static final String QUERY = "QUERY";
Jian Lib230e07c2020-12-21 11:25:12 +090077 private static final String NOT_EXIST = "Not exist";
78 private static final String STATE = "State";
Jian Lif54f8a62021-05-22 00:10:15 +090079 private static final String API_CONFIG = "apiConfig";
80 private static final String OK = "ok";
81 private static final String ERROR = "error";
Jian Lib230e07c2020-12-21 11:25:12 +090082
Jian Li528335e2021-07-08 20:52:50 +090083 private static final int SLEEP_S = 1; // we re-check the status on every 1s
84 private static final long TIMEOUT_MS = 15000;
Jian Libe478b72021-05-14 15:21:08 +090085
Jian Lib230e07c2020-12-21 11:25:12 +090086 private static final String HOST_NAME = "hostname";
87 private static final String ERROR_MESSAGE = " cannot be null";
88
Jian Lib230e07c2020-12-21 11:25:12 +090089 @Context
90 private UriInfo uriInfo;
91
Jian Lie2a53cb2020-12-19 01:26:57 +090092 /**
93 * Creates a set of KubeVirt nodes' config from the JSON input stream.
94 *
95 * @param input KubeVirt nodes JSON input stream
96 * @return 201 CREATED if the JSON is correct, 400 BAD_REQUEST if the JSON
97 * is malformed
98 * @onos.rsModel KubevirtNode
99 */
100 @POST
Jian Lie2a53cb2020-12-19 01:26:57 +0900101 @Consumes(MediaType.APPLICATION_JSON)
102 @Produces(MediaType.APPLICATION_JSON)
Jian Lib230e07c2020-12-21 11:25:12 +0900103 public Response createNodes(InputStream input) {
104 log.trace(String.format(MESSAGE_NODE, CREATE));
105
Jian Li35813002021-02-19 10:28:01 +0900106 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
107
Jian Lib230e07c2020-12-21 11:25:12 +0900108 readNodeConfiguration(input).forEach(node -> {
Jian Li35813002021-02-19 10:28:01 +0900109 KubevirtNode existing = service.node(node.hostname());
Jian Lib230e07c2020-12-21 11:25:12 +0900110 if (existing == null) {
Jian Li35813002021-02-19 10:28:01 +0900111 service.createNode(node);
Jian Lib230e07c2020-12-21 11:25:12 +0900112 }
113 });
114
115 UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
116 .path(NODES)
117 .path(NODE_ID);
118
119 return created(locationBuilder.build()).build();
120 }
121
122 /**
123 * Updates a set of KubeVirt nodes' config from the JSON input stream.
124 *
125 * @param input KubeVirt nodes JSON input stream
126 * @return 200 OK with the updated KubeVirt node's config, 400 BAD_REQUEST
127 * if the JSON is malformed, and 304 NOT_MODIFIED without the updated config
128 * @onos.rsModel KubevirtNode
129 */
130 @PUT
Jian Lib230e07c2020-12-21 11:25:12 +0900131 @Consumes(MediaType.APPLICATION_JSON)
132 @Produces(MediaType.APPLICATION_JSON)
133 public Response updateNodes(InputStream input) {
134 log.trace(String.format(MESSAGE_NODE, UPDATE));
135
Jian Li35813002021-02-19 10:28:01 +0900136 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
Jian Lib230e07c2020-12-21 11:25:12 +0900137 Set<KubevirtNode> nodes = readNodeConfiguration(input);
138 for (KubevirtNode node: nodes) {
Jian Li35813002021-02-19 10:28:01 +0900139 KubevirtNode existing = service.node(node.hostname());
Jian Lib230e07c2020-12-21 11:25:12 +0900140 if (existing == null) {
141 log.warn("There is no node configuration to update : {}", node.hostname());
142 return Response.notModified().build();
143 } else if (!existing.equals(node)) {
Jian Li35813002021-02-19 10:28:01 +0900144 service.updateNode(node);
Jian Lib230e07c2020-12-21 11:25:12 +0900145 }
146 }
147
Jian Lie2a53cb2020-12-19 01:26:57 +0900148 return Response.ok().build();
149 }
Jian Lib230e07c2020-12-21 11:25:12 +0900150
151 /**
152 * Removes a set of KubeVirt nodes' config from the JSON input stream.
153 *
154 * @param hostname host name contained in KubeVirt nodes configuration
155 * @return 204 NO_CONTENT, 400 BAD_REQUEST if the JSON is malformed, and
156 * 304 NOT_MODIFIED without the updated config
157 */
158 @DELETE
Jian Lif2483072020-12-25 02:24:16 +0900159 @Path("{hostname}")
Jian Lib230e07c2020-12-21 11:25:12 +0900160 @Consumes(MediaType.APPLICATION_JSON)
161 @Produces(MediaType.APPLICATION_JSON)
162 public Response deleteNode(@PathParam("hostname") String hostname) {
163 log.trace(String.format(MESSAGE_NODE, REMOVE));
164
Jian Li35813002021-02-19 10:28:01 +0900165 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
166 KubevirtNode existing = service.node(
Jian Lib230e07c2020-12-21 11:25:12 +0900167 nullIsIllegal(hostname, HOST_NAME + ERROR_MESSAGE));
168
169 if (existing == null) {
170 log.warn("There is no node configuration to delete : {}", hostname);
171 return Response.notModified().build();
172 } else {
Jian Li35813002021-02-19 10:28:01 +0900173 service.removeNode(hostname);
Jian Lib230e07c2020-12-21 11:25:12 +0900174 }
175
176 return Response.noContent().build();
177 }
178
179 /**
180 * Obtains the state of the KubeVirt node.
181 *
182 * @param hostname hostname of the KubeVirt
183 * @return the state of the KubeVirt node in Json
184 */
185 @GET
186 @Produces(MediaType.APPLICATION_JSON)
187 @Path("state/{hostname}")
188 public Response stateOfNode(@PathParam("hostname") String hostname) {
189 log.trace(String.format(MESSAGE_NODE, QUERY));
190
Jian Li35813002021-02-19 10:28:01 +0900191 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
192 KubevirtNode node = service.node(hostname);
Jian Lib230e07c2020-12-21 11:25:12 +0900193 String nodeState = node != null ? node.state().toString() : NOT_EXIST;
194
195 return ok(mapper().createObjectNode().put(STATE, nodeState)).build();
196 }
197
198 /**
199 * Initializes KubeVirt node.
200 *
201 * @param hostname hostname of KubeVirt node
202 * @return 200 OK with init result, 404 not found, 500 server error
203 */
204 @GET
205 @Produces(MediaType.APPLICATION_JSON)
Jian Lif2483072020-12-25 02:24:16 +0900206 @Path("init/{hostname}")
Jian Lib230e07c2020-12-21 11:25:12 +0900207 public Response initNode(@PathParam("hostname") String hostname) {
208 log.trace(String.format(MESSAGE_NODE, QUERY));
209
Jian Li35813002021-02-19 10:28:01 +0900210 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
211 KubevirtNode node = service.node(hostname);
Jian Lib230e07c2020-12-21 11:25:12 +0900212 if (node == null) {
213 log.error("Given node {} does not exist", hostname);
214 return Response.serverError().build();
215 }
Jian Libe478b72021-05-14 15:21:08 +0900216 KubevirtNode updated = node.updateState(INIT);
Jian Li35813002021-02-19 10:28:01 +0900217 service.updateNode(updated);
Jian Lib230e07c2020-12-21 11:25:12 +0900218 return ok(mapper().createObjectNode()).build();
219 }
220
221 /**
222 * Initializes all KubeVirt nodes.
223 *
224 * @return 200 OK with init result, 500 server error
225 */
226 @GET
227 @Produces(MediaType.APPLICATION_JSON)
228 @Path("init/all")
229 public Response initAllNodes() {
230 log.trace(String.format(MESSAGE_NODE, QUERY));
231
Jian Li35813002021-02-19 10:28:01 +0900232 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
233
234 service.nodes()
Jian Lib230e07c2020-12-21 11:25:12 +0900235 .forEach(n -> {
Jian Libe478b72021-05-14 15:21:08 +0900236 KubevirtNode updated = n.updateState(INIT);
Jian Li35813002021-02-19 10:28:01 +0900237 service.updateNode(updated);
Jian Lib230e07c2020-12-21 11:25:12 +0900238 });
239
240 return ok(mapper().createObjectNode()).build();
241 }
242
243 /**
244 * Initializes KubeVirt nodes which are in the stats other than COMPLETE.
245 *
246 * @return 200 OK with init result, 500 server error
247 */
248 @GET
249 @Produces(MediaType.APPLICATION_JSON)
250 @Path("init/incomplete")
251 public Response initIncompleteNodes() {
252 log.trace(String.format(MESSAGE_NODE, QUERY));
253
Jian Li35813002021-02-19 10:28:01 +0900254 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
255 service.nodes().stream()
Jian Lib230e07c2020-12-21 11:25:12 +0900256 .filter(n -> n.state() != KubevirtNodeState.COMPLETE)
257 .forEach(n -> {
Jian Libe478b72021-05-14 15:21:08 +0900258 KubevirtNode updated = n.updateState(INIT);
Jian Li35813002021-02-19 10:28:01 +0900259 service.updateNode(updated);
Jian Lib230e07c2020-12-21 11:25:12 +0900260 });
261
262 return ok(mapper().createObjectNode()).build();
263 }
264
Jian Libe478b72021-05-14 15:21:08 +0900265 /**
266 * Synchronizes the flow rules.
267 *
268 * @return 200 OK with sync result, 404 not found
269 */
270 @GET
271 @Produces(MediaType.APPLICATION_JSON)
272 @Path("sync/rules")
273 public Response syncRules() {
274
275 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
276
Jian Li528335e2021-07-08 20:52:50 +0900277 service.completeNodes().forEach(node -> syncRulesBase(service, node));
Jian Libe478b72021-05-14 15:21:08 +0900278 return ok(mapper().createObjectNode()).build();
279 }
280
Jian Lif54f8a62021-05-22 00:10:15 +0900281 /**
282 * Returns the health check result.
283 *
284 * @return 200 OK with health check result, 404 not found
285 */
286 @GET
287 @Produces(MediaType.APPLICATION_JSON)
288 @Path("healthz")
289 public Response healthz() {
290 KubevirtApiConfigService configService = get(KubevirtApiConfigService.class);
Jian Lie0eaf5c2021-09-06 10:02:13 +0900291 KubevirtNodeService nodeService = get(KubevirtNodeService.class);
Jian Lif54f8a62021-05-22 00:10:15 +0900292
293 // TODO: we need to add more health check items
Jian Lie0eaf5c2021-09-06 10:02:13 +0900294 boolean allInit = true;
295 KubevirtApiConfig config = configService.apiConfig();
296
297 if (nodeService.nodes().size() == 0) {
298 allInit = false;
299 } else {
300 for (KubevirtNode node : nodeService.nodes()) {
301 if (node.state() != INIT) {
302 allInit = false;
303 }
304 }
305 }
306
307 String result = ERROR;
308 if (config != null && !allInit) {
309 result = OK;
310 }
311
Jian Lidd5172e2022-03-05 00:03:35 +0900312 KubernetesClient client = k8sClient(config);
313 if (client != null) {
314 Set<String> k8sNodeNames = new HashSet<>();
315 client.nodes().list().getItems().forEach(n -> {
316 if (getNodeType(n) == WORKER) {
317 k8sNodeNames.add(n.getMetadata().getName());
318 }
319 });
320 Set<String> nodeNames = nodeService.nodes(WORKER).stream()
321 .map(KubevirtNode::hostname).collect(Collectors.toSet());
322 if (!k8sNodeNames.containsAll(nodeNames)) {
323 result = ERROR;
324 }
325 if (!nodeNames.containsAll(k8sNodeNames)) {
326 result = ERROR;
327 }
328 }
329
Jian Lif54f8a62021-05-22 00:10:15 +0900330 ObjectNode jsonResult = mapper().createObjectNode();
Jian Lif54f8a62021-05-22 00:10:15 +0900331 jsonResult.put(API_CONFIG, result);
332 return ok(jsonResult).build();
333 }
334
Jian Li528335e2021-07-08 20:52:50 +0900335 private void syncRulesBase(KubevirtNodeAdminService service, KubevirtNode node) {
Jian Libe478b72021-05-14 15:21:08 +0900336 KubevirtNode updated = node.updateState(INIT);
Jian Libe478b72021-05-14 15:21:08 +0900337 service.updateNode(updated);
338
339 boolean result = true;
340 long timeoutExpiredMs = System.currentTimeMillis() + TIMEOUT_MS;
341
342 while (service.node(node.hostname()).state() != COMPLETE) {
Jian Libe478b72021-05-14 15:21:08 +0900343 long waitMs = timeoutExpiredMs - System.currentTimeMillis();
344
Jian Li528335e2021-07-08 20:52:50 +0900345 waitFor(SLEEP_S);
Jian Libe478b72021-05-14 15:21:08 +0900346
347 if (waitMs <= 0) {
348 result = false;
349 break;
350 }
351 }
352
353 if (result) {
354 log.info("Successfully synchronize flow rules for node {}!", node.hostname());
355 } else {
356 log.warn("Failed to synchronize flow rules for node {}.", node.hostname());
357 }
358 }
359
Jian Lib230e07c2020-12-21 11:25:12 +0900360 private Set<KubevirtNode> readNodeConfiguration(InputStream input) {
361 Set<KubevirtNode> nodeSet = Sets.newHashSet();
362 try {
363 JsonNode jsonTree = readTreeFromStream(mapper().enable(INDENT_OUTPUT), input);
364 ArrayNode nodes = (ArrayNode) jsonTree.path(NODES);
365 nodes.forEach(node -> {
366 try {
367 ObjectNode objectNode = node.deepCopy();
368 KubevirtNode kubevirtNode =
369 codec(KubevirtNode.class).decode(objectNode, this);
370 nodeSet.add(kubevirtNode);
371 } catch (Exception e) {
372 log.error("Exception occurred due to {}", e);
373 throw new IllegalArgumentException();
374 }
375 });
376 } catch (Exception e) {
377 throw new IllegalArgumentException(e);
378 }
379
380 return nodeSet;
381 }
Jian Lie2a53cb2020-12-19 01:26:57 +0900382}