blob: 06b06e87a0ee0e05e01ab291a1e4ff2bb48b5de3 [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 Lif54f8a62021-05-22 00:10:15 +090022import org.onosproject.kubevirtnode.api.KubevirtApiConfig;
23import org.onosproject.kubevirtnode.api.KubevirtApiConfigService;
Jian Lib230e07c2020-12-21 11:25:12 +090024import org.onosproject.kubevirtnode.api.KubevirtNode;
25import org.onosproject.kubevirtnode.api.KubevirtNodeAdminService;
26import org.onosproject.kubevirtnode.api.KubevirtNodeState;
Jian Lie2a53cb2020-12-19 01:26:57 +090027import org.onosproject.rest.AbstractWebResource;
28import org.slf4j.Logger;
29import org.slf4j.LoggerFactory;
30
31import javax.ws.rs.Consumes;
Jian Lib230e07c2020-12-21 11:25:12 +090032import javax.ws.rs.DELETE;
33import javax.ws.rs.GET;
Jian Lie2a53cb2020-12-19 01:26:57 +090034import javax.ws.rs.POST;
Jian Lib230e07c2020-12-21 11:25:12 +090035import javax.ws.rs.PUT;
Jian Lie2a53cb2020-12-19 01:26:57 +090036import javax.ws.rs.Path;
Jian Lib230e07c2020-12-21 11:25:12 +090037import javax.ws.rs.PathParam;
Jian Lie2a53cb2020-12-19 01:26:57 +090038import javax.ws.rs.Produces;
Jian Lib230e07c2020-12-21 11:25:12 +090039import javax.ws.rs.core.Context;
Jian Lie2a53cb2020-12-19 01:26:57 +090040import javax.ws.rs.core.MediaType;
41import javax.ws.rs.core.Response;
Jian Lib230e07c2020-12-21 11:25:12 +090042import javax.ws.rs.core.UriBuilder;
43import javax.ws.rs.core.UriInfo;
Jian Lie2a53cb2020-12-19 01:26:57 +090044import java.io.InputStream;
Jian Lib230e07c2020-12-21 11:25:12 +090045import java.util.Set;
Jian Lie2a53cb2020-12-19 01:26:57 +090046
Jian Lib230e07c2020-12-21 11:25:12 +090047import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
Jian Libe478b72021-05-14 15:21:08 +090048import static java.lang.Thread.sleep;
Jian Lib230e07c2020-12-21 11:25:12 +090049import static javax.ws.rs.core.Response.created;
50import static org.onlab.util.Tools.nullIsIllegal;
51import static org.onlab.util.Tools.readTreeFromStream;
Jian Libe478b72021-05-14 15:21:08 +090052import static org.onosproject.kubevirtnode.api.KubevirtNode.Type.WORKER;
53import static org.onosproject.kubevirtnode.api.KubevirtNodeState.COMPLETE;
54import static org.onosproject.kubevirtnode.api.KubevirtNodeState.INIT;
Jian Lib230e07c2020-12-21 11:25:12 +090055
56/**
57 * Handles REST API call of KubeVirt node config.
58 */
Jian Lif2483072020-12-25 02:24:16 +090059@Path("node")
Jian Lie2a53cb2020-12-19 01:26:57 +090060public class KubevirtNodeWebResource extends AbstractWebResource {
61
62 private final Logger log = LoggerFactory.getLogger(getClass());
63
Jian Lib230e07c2020-12-21 11:25:12 +090064 private static final String MESSAGE_NODE = "Received node %s request";
65 private static final String NODES = "nodes";
66 private static final String CREATE = "CREATE";
67 private static final String UPDATE = "UPDATE";
68 private static final String NODE_ID = "NODE_ID";
69 private static final String REMOVE = "REMOVE";
70 private static final String QUERY = "QUERY";
Jian Lib230e07c2020-12-21 11:25:12 +090071 private static final String NOT_EXIST = "Not exist";
72 private static final String STATE = "State";
Jian Lif54f8a62021-05-22 00:10:15 +090073 private static final String API_CONFIG = "apiConfig";
74 private static final String OK = "ok";
75 private static final String ERROR = "error";
Jian Lib230e07c2020-12-21 11:25:12 +090076 private static final String RESULT = "Result";
77
Jian Libe478b72021-05-14 15:21:08 +090078 private static final long SLEEP_MS = 5000; // we wait 5s for init each node
79 private static final long TIMEOUT_MS = 10000; // we wait 10s
80
Jian Lib230e07c2020-12-21 11:25:12 +090081 private static final String HOST_NAME = "hostname";
82 private static final String ERROR_MESSAGE = " cannot be null";
83
Jian Lib230e07c2020-12-21 11:25:12 +090084 @Context
85 private UriInfo uriInfo;
86
Jian Lie2a53cb2020-12-19 01:26:57 +090087 /**
88 * Creates a set of KubeVirt nodes' config from the JSON input stream.
89 *
90 * @param input KubeVirt nodes JSON input stream
91 * @return 201 CREATED if the JSON is correct, 400 BAD_REQUEST if the JSON
92 * is malformed
93 * @onos.rsModel KubevirtNode
94 */
95 @POST
Jian Lie2a53cb2020-12-19 01:26:57 +090096 @Consumes(MediaType.APPLICATION_JSON)
97 @Produces(MediaType.APPLICATION_JSON)
Jian Lib230e07c2020-12-21 11:25:12 +090098 public Response createNodes(InputStream input) {
99 log.trace(String.format(MESSAGE_NODE, CREATE));
100
Jian Li35813002021-02-19 10:28:01 +0900101 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
102
Jian Lib230e07c2020-12-21 11:25:12 +0900103 readNodeConfiguration(input).forEach(node -> {
Jian Li35813002021-02-19 10:28:01 +0900104 KubevirtNode existing = service.node(node.hostname());
Jian Lib230e07c2020-12-21 11:25:12 +0900105 if (existing == null) {
Jian Li35813002021-02-19 10:28:01 +0900106 service.createNode(node);
Jian Lib230e07c2020-12-21 11:25:12 +0900107 }
108 });
109
110 UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
111 .path(NODES)
112 .path(NODE_ID);
113
114 return created(locationBuilder.build()).build();
115 }
116
117 /**
118 * Updates a set of KubeVirt nodes' config from the JSON input stream.
119 *
120 * @param input KubeVirt nodes JSON input stream
121 * @return 200 OK with the updated KubeVirt node's config, 400 BAD_REQUEST
122 * if the JSON is malformed, and 304 NOT_MODIFIED without the updated config
123 * @onos.rsModel KubevirtNode
124 */
125 @PUT
Jian Lib230e07c2020-12-21 11:25:12 +0900126 @Consumes(MediaType.APPLICATION_JSON)
127 @Produces(MediaType.APPLICATION_JSON)
128 public Response updateNodes(InputStream input) {
129 log.trace(String.format(MESSAGE_NODE, UPDATE));
130
Jian Li35813002021-02-19 10:28:01 +0900131 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
Jian Lib230e07c2020-12-21 11:25:12 +0900132 Set<KubevirtNode> nodes = readNodeConfiguration(input);
133 for (KubevirtNode node: nodes) {
Jian Li35813002021-02-19 10:28:01 +0900134 KubevirtNode existing = service.node(node.hostname());
Jian Lib230e07c2020-12-21 11:25:12 +0900135 if (existing == null) {
136 log.warn("There is no node configuration to update : {}", node.hostname());
137 return Response.notModified().build();
138 } else if (!existing.equals(node)) {
Jian Li35813002021-02-19 10:28:01 +0900139 service.updateNode(node);
Jian Lib230e07c2020-12-21 11:25:12 +0900140 }
141 }
142
Jian Lie2a53cb2020-12-19 01:26:57 +0900143 return Response.ok().build();
144 }
Jian Lib230e07c2020-12-21 11:25:12 +0900145
146 /**
147 * Removes a set of KubeVirt nodes' config from the JSON input stream.
148 *
149 * @param hostname host name contained in KubeVirt nodes configuration
150 * @return 204 NO_CONTENT, 400 BAD_REQUEST if the JSON is malformed, and
151 * 304 NOT_MODIFIED without the updated config
152 */
153 @DELETE
Jian Lif2483072020-12-25 02:24:16 +0900154 @Path("{hostname}")
Jian Lib230e07c2020-12-21 11:25:12 +0900155 @Consumes(MediaType.APPLICATION_JSON)
156 @Produces(MediaType.APPLICATION_JSON)
157 public Response deleteNode(@PathParam("hostname") String hostname) {
158 log.trace(String.format(MESSAGE_NODE, REMOVE));
159
Jian Li35813002021-02-19 10:28:01 +0900160 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
161 KubevirtNode existing = service.node(
Jian Lib230e07c2020-12-21 11:25:12 +0900162 nullIsIllegal(hostname, HOST_NAME + ERROR_MESSAGE));
163
164 if (existing == null) {
165 log.warn("There is no node configuration to delete : {}", hostname);
166 return Response.notModified().build();
167 } else {
Jian Li35813002021-02-19 10:28:01 +0900168 service.removeNode(hostname);
Jian Lib230e07c2020-12-21 11:25:12 +0900169 }
170
171 return Response.noContent().build();
172 }
173
174 /**
175 * Obtains the state of the KubeVirt node.
176 *
177 * @param hostname hostname of the KubeVirt
178 * @return the state of the KubeVirt node in Json
179 */
180 @GET
181 @Produces(MediaType.APPLICATION_JSON)
182 @Path("state/{hostname}")
183 public Response stateOfNode(@PathParam("hostname") String hostname) {
184 log.trace(String.format(MESSAGE_NODE, QUERY));
185
Jian Li35813002021-02-19 10:28:01 +0900186 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
187 KubevirtNode node = service.node(hostname);
Jian Lib230e07c2020-12-21 11:25:12 +0900188 String nodeState = node != null ? node.state().toString() : NOT_EXIST;
189
190 return ok(mapper().createObjectNode().put(STATE, nodeState)).build();
191 }
192
193 /**
194 * Initializes KubeVirt node.
195 *
196 * @param hostname hostname of KubeVirt node
197 * @return 200 OK with init result, 404 not found, 500 server error
198 */
199 @GET
200 @Produces(MediaType.APPLICATION_JSON)
Jian Lif2483072020-12-25 02:24:16 +0900201 @Path("init/{hostname}")
Jian Lib230e07c2020-12-21 11:25:12 +0900202 public Response initNode(@PathParam("hostname") String hostname) {
203 log.trace(String.format(MESSAGE_NODE, QUERY));
204
Jian Li35813002021-02-19 10:28:01 +0900205 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
206 KubevirtNode node = service.node(hostname);
Jian Lib230e07c2020-12-21 11:25:12 +0900207 if (node == null) {
208 log.error("Given node {} does not exist", hostname);
209 return Response.serverError().build();
210 }
Jian Libe478b72021-05-14 15:21:08 +0900211 KubevirtNode updated = node.updateState(INIT);
Jian Li35813002021-02-19 10:28:01 +0900212 service.updateNode(updated);
Jian Lib230e07c2020-12-21 11:25:12 +0900213 return ok(mapper().createObjectNode()).build();
214 }
215
216 /**
217 * Initializes all KubeVirt nodes.
218 *
219 * @return 200 OK with init result, 500 server error
220 */
221 @GET
222 @Produces(MediaType.APPLICATION_JSON)
223 @Path("init/all")
224 public Response initAllNodes() {
225 log.trace(String.format(MESSAGE_NODE, QUERY));
226
Jian Li35813002021-02-19 10:28:01 +0900227 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
228
229 service.nodes()
Jian Lib230e07c2020-12-21 11:25:12 +0900230 .forEach(n -> {
Jian Libe478b72021-05-14 15:21:08 +0900231 KubevirtNode updated = n.updateState(INIT);
Jian Li35813002021-02-19 10:28:01 +0900232 service.updateNode(updated);
Jian Lib230e07c2020-12-21 11:25:12 +0900233 });
234
235 return ok(mapper().createObjectNode()).build();
236 }
237
238 /**
239 * Initializes KubeVirt nodes which are in the stats other than COMPLETE.
240 *
241 * @return 200 OK with init result, 500 server error
242 */
243 @GET
244 @Produces(MediaType.APPLICATION_JSON)
245 @Path("init/incomplete")
246 public Response initIncompleteNodes() {
247 log.trace(String.format(MESSAGE_NODE, QUERY));
248
Jian Li35813002021-02-19 10:28:01 +0900249 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
250 service.nodes().stream()
Jian Lib230e07c2020-12-21 11:25:12 +0900251 .filter(n -> n.state() != KubevirtNodeState.COMPLETE)
252 .forEach(n -> {
Jian Libe478b72021-05-14 15:21:08 +0900253 KubevirtNode updated = n.updateState(INIT);
Jian Li35813002021-02-19 10:28:01 +0900254 service.updateNode(updated);
Jian Lib230e07c2020-12-21 11:25:12 +0900255 });
256
257 return ok(mapper().createObjectNode()).build();
258 }
259
Jian Libe478b72021-05-14 15:21:08 +0900260 /**
261 * Synchronizes the flow rules.
262 *
263 * @return 200 OK with sync result, 404 not found
264 */
265 @GET
266 @Produces(MediaType.APPLICATION_JSON)
267 @Path("sync/rules")
268 public Response syncRules() {
269
270 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
271
272 service.completeNodes(WORKER).forEach(this::syncRulesBase);
273 return ok(mapper().createObjectNode()).build();
274 }
275
Jian Lif54f8a62021-05-22 00:10:15 +0900276 /**
277 * Returns the health check result.
278 *
279 * @return 200 OK with health check result, 404 not found
280 */
281 @GET
282 @Produces(MediaType.APPLICATION_JSON)
283 @Path("healthz")
284 public Response healthz() {
285 KubevirtApiConfigService configService = get(KubevirtApiConfigService.class);
286 KubevirtApiConfig config = configService.apiConfig();
287
288 // TODO: we need to add more health check items
289 ObjectNode jsonResult = mapper().createObjectNode();
290 String result = config != null ? OK : ERROR;
291 jsonResult.put(API_CONFIG, result);
292 return ok(jsonResult).build();
293 }
294
Jian Libe478b72021-05-14 15:21:08 +0900295 private void syncRulesBase(KubevirtNode node) {
296 KubevirtNode updated = node.updateState(INIT);
297 KubevirtNodeAdminService service = get(KubevirtNodeAdminService.class);
298 service.updateNode(updated);
299
300 boolean result = true;
301 long timeoutExpiredMs = System.currentTimeMillis() + TIMEOUT_MS;
302
303 while (service.node(node.hostname()).state() != COMPLETE) {
304
305 long waitMs = timeoutExpiredMs - System.currentTimeMillis();
306
307 try {
308 sleep(SLEEP_MS);
309 } catch (InterruptedException e) {
310 log.error("Exception caused during node synchronization...");
311 }
312
313 if (service.node(node.hostname()).state() == COMPLETE) {
314 break;
315 } else {
316 service.updateNode(updated);
317 log.info("Failed to synchronize flow rules, retrying...");
318 }
319
320 if (waitMs <= 0) {
321 result = false;
322 break;
323 }
324 }
325
326 if (result) {
327 log.info("Successfully synchronize flow rules for node {}!", node.hostname());
328 } else {
329 log.warn("Failed to synchronize flow rules for node {}.", node.hostname());
330 }
331 }
332
Jian Lib230e07c2020-12-21 11:25:12 +0900333 private Set<KubevirtNode> readNodeConfiguration(InputStream input) {
334 Set<KubevirtNode> nodeSet = Sets.newHashSet();
335 try {
336 JsonNode jsonTree = readTreeFromStream(mapper().enable(INDENT_OUTPUT), input);
337 ArrayNode nodes = (ArrayNode) jsonTree.path(NODES);
338 nodes.forEach(node -> {
339 try {
340 ObjectNode objectNode = node.deepCopy();
341 KubevirtNode kubevirtNode =
342 codec(KubevirtNode.class).decode(objectNode, this);
343 nodeSet.add(kubevirtNode);
344 } catch (Exception e) {
345 log.error("Exception occurred due to {}", e);
346 throw new IllegalArgumentException();
347 }
348 });
349 } catch (Exception e) {
350 throw new IllegalArgumentException(e);
351 }
352
353 return nodeSet;
354 }
Jian Lie2a53cb2020-12-19 01:26:57 +0900355}