blob: d7389b749c06adb2476a04917e4af5597b5be704 [file] [log] [blame]
jiangrui330b0c92015-11-28 14:09:50 +08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
jiangrui330b0c92015-11-28 14:09:50 +08003 *
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.vtnweb.resources;
17
18import static com.google.common.base.Preconditions.checkArgument;
19import static com.google.common.base.Preconditions.checkNotNull;
20import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
21import static javax.ws.rs.core.Response.Status.CONFLICT;
22import static javax.ws.rs.core.Response.Status.CREATED;
23import static javax.ws.rs.core.Response.Status.NOT_FOUND;
24import static javax.ws.rs.core.Response.Status.NO_CONTENT;
25
26import java.io.IOException;
27import java.io.InputStream;
28import java.util.ArrayList;
29import java.util.Collection;
30import java.util.Collections;
31import java.util.HashMap;
32import java.util.List;
33import java.util.Map;
34import java.util.Set;
35import java.util.concurrent.ConcurrentMap;
36
37import javax.ws.rs.Consumes;
38import javax.ws.rs.DELETE;
39import javax.ws.rs.GET;
40import javax.ws.rs.POST;
41import javax.ws.rs.PUT;
42import javax.ws.rs.Path;
43import javax.ws.rs.PathParam;
44import javax.ws.rs.Produces;
45import javax.ws.rs.QueryParam;
46import javax.ws.rs.core.MediaType;
47import javax.ws.rs.core.Response;
48
49import org.onlab.packet.IpAddress;
50import org.onlab.util.ItemNotFoundException;
51import org.onosproject.rest.AbstractWebResource;
52import org.onosproject.vtnrsc.DefaultRouter;
53import org.onosproject.vtnrsc.FixedIp;
54import org.onosproject.vtnrsc.Router;
55import org.onosproject.vtnrsc.Router.Status;
56import org.onosproject.vtnrsc.RouterGateway;
57import org.onosproject.vtnrsc.RouterId;
58import org.onosproject.vtnrsc.RouterInterface;
59import org.onosproject.vtnrsc.SubnetId;
60import org.onosproject.vtnrsc.TenantId;
61import org.onosproject.vtnrsc.TenantNetworkId;
62import org.onosproject.vtnrsc.VirtualPortId;
63import org.onosproject.vtnrsc.router.RouterService;
64import org.onosproject.vtnrsc.routerinterface.RouterInterfaceService;
65import org.onosproject.vtnweb.web.RouterCodec;
66import org.slf4j.Logger;
67import org.slf4j.LoggerFactory;
68
69import com.fasterxml.jackson.databind.JsonNode;
70import com.fasterxml.jackson.databind.ObjectMapper;
71import com.fasterxml.jackson.databind.node.ObjectNode;
72import com.google.common.collect.Maps;
73import com.google.common.collect.Sets;
74
75@Path("routers")
76public class RouterWebResource extends AbstractWebResource {
77 private final Logger log = LoggerFactory.getLogger(RouterWebResource.class);
78 public static final String CREATE_FAIL = "Router is failed to create!";
79 public static final String UPDATE_FAIL = "Router is failed to update!";
80 public static final String GET_FAIL = "Router is failed to get!";
81 public static final String NOT_EXIST = "Router does not exist!";
82 public static final String DELETE_SUCCESS = "Router delete success!";
83 public static final String JSON_NOT_NULL = "JsonNode can not be null";
84 public static final String INTFACR_ADD_SUCCESS = "Interface add success";
85 public static final String INTFACR_DEL_SUCCESS = "Interface delete success";
86
87 @GET
88 @Produces(MediaType.APPLICATION_JSON)
89 public Response listRouters() {
90 Collection<Router> routers = get(RouterService.class).getRouters();
91 ObjectNode result = new ObjectMapper().createObjectNode();
92 result.set("routers", new RouterCodec().encode(routers, this));
93 return ok(result.toString()).build();
94 }
95
96 @GET
97 @Path("{routerUUID}")
98 @Produces(MediaType.APPLICATION_JSON)
99 public Response getRouter(@PathParam("routerUUID") String id,
100 @QueryParam("fields") List<String> fields) {
101
102 if (!get(RouterService.class).exists(RouterId.valueOf(id))) {
103 return Response.status(NOT_FOUND)
104 .entity("The Router does not exists").build();
105 }
106 Router sub = nullIsNotFound(get(RouterService.class)
lishuaid6f0c9e2015-12-16 11:40:01 +0800107 .getRouter(RouterId.valueOf(id)), NOT_EXIST);
jiangrui330b0c92015-11-28 14:09:50 +0800108
109 ObjectNode result = new ObjectMapper().createObjectNode();
110 if (fields.size() > 0) {
111 result.set("router",
112 new RouterCodec().extracFields(sub, this, fields));
113 } else {
114 result.set("router", new RouterCodec().encode(sub, this));
115 }
116 return ok(result.toString()).build();
117 }
118
119 @POST
120 @Produces(MediaType.APPLICATION_JSON)
121 @Consumes(MediaType.APPLICATION_JSON)
122 public Response createRouter(final InputStream input) {
123 try {
124 ObjectMapper mapper = new ObjectMapper();
125 JsonNode subnode = mapper.readTree(input);
126 Collection<Router> routers = createOrUpdateByInputStream(subnode);
127
128 Boolean result = nullIsNotFound((get(RouterService.class)
lishuaid6f0c9e2015-12-16 11:40:01 +0800129 .createRouters(routers)), CREATE_FAIL);
jiangrui330b0c92015-11-28 14:09:50 +0800130 if (!result) {
131 return Response.status(CONFLICT).entity(CREATE_FAIL).build();
132 }
133 return Response.status(CREATED).entity(result.toString()).build();
134
135 } catch (Exception e) {
136 return Response.status(BAD_REQUEST).entity(e.getMessage()).build();
137 }
138 }
139
140 @PUT
141 @Path("{routerUUID}")
142 @Produces(MediaType.APPLICATION_JSON)
143 @Consumes(MediaType.APPLICATION_JSON)
144 public Response updateRouter(@PathParam("routerUUID") String id,
145 final InputStream input) {
146 try {
147 ObjectMapper mapper = new ObjectMapper();
148 JsonNode subnode = mapper.readTree(input);
lishuaid6f0c9e2015-12-16 11:40:01 +0800149 Collection<Router> routers = changeUpdateJsonToSub(subnode, id);
jiangrui330b0c92015-11-28 14:09:50 +0800150 Boolean result = nullIsNotFound(get(RouterService.class)
151 .updateRouters(routers), UPDATE_FAIL);
152 if (!result) {
153 return Response.status(CONFLICT).entity(UPDATE_FAIL).build();
154 }
155 return ok(result.toString()).build();
156 } catch (Exception e) {
157 return Response.status(BAD_REQUEST).entity(e.getMessage()).build();
158 }
159 }
160
jiangrui330b0c92015-11-28 14:09:50 +0800161 @DELETE
Wu wenbinb0bd6132016-05-10 19:20:23 +0800162 @Path("{routerUUID}")
163 @Consumes(MediaType.APPLICATION_JSON)
164 @Produces(MediaType.APPLICATION_JSON)
jiangrui330b0c92015-11-28 14:09:50 +0800165 public Response deleteSingleRouter(@PathParam("routerUUID") String id)
166 throws IOException {
167 try {
168 RouterId routerId = RouterId.valueOf(id);
169 Set<RouterId> routerIds = Sets.newHashSet(routerId);
170 get(RouterService.class).removeRouters(routerIds);
171 return Response.status(NO_CONTENT).entity(DELETE_SUCCESS).build();
172 } catch (Exception e) {
173 return Response.status(BAD_REQUEST).entity(e.getMessage()).build();
174 }
175 }
176
177 @PUT
178 @Path("{routerUUID}/add_router_interface")
179 @Produces(MediaType.APPLICATION_JSON)
180 @Consumes(MediaType.APPLICATION_JSON)
181 public Response addRouterInterface(@PathParam("routerUUID") String id,
182 final InputStream input) {
183 if (!get(RouterService.class).exists(RouterId.valueOf(id))) {
184 return Response.status(NOT_FOUND).entity(NOT_EXIST).build();
185 }
186 try {
187 ObjectMapper mapper = new ObjectMapper();
188 JsonNode subnode = mapper.readTree(input);
189 if (!subnode.hasNonNull("id")) {
190 throw new IllegalArgumentException("id should not be null");
191 } else if (subnode.get("id").asText().isEmpty()) {
192 throw new IllegalArgumentException("id should not be empty");
193 }
194 RouterId routerId = RouterId.valueOf(id);
195 if (!subnode.hasNonNull("subnet_id")) {
196 throw new IllegalArgumentException("subnet_id should not be null");
197 } else if (subnode.get("subnet_id").asText().isEmpty()) {
198 throw new IllegalArgumentException("subnet_id should not be empty");
199 }
lishuaid6f0c9e2015-12-16 11:40:01 +0800200 SubnetId subnetId = SubnetId
201 .subnetId(subnode.get("subnet_id").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800202 if (!subnode.hasNonNull("tenant_id")) {
203 throw new IllegalArgumentException("tenant_id should not be null");
204 } else if (subnode.get("tenant_id").asText().isEmpty()) {
205 throw new IllegalArgumentException("tenant_id should not be empty");
206 }
lishuaid6f0c9e2015-12-16 11:40:01 +0800207 TenantId tenentId = TenantId
208 .tenantId(subnode.get("tenant_id").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800209 if (!subnode.hasNonNull("port_id")) {
210 throw new IllegalArgumentException("port_id should not be null");
211 } else if (subnode.get("port_id").asText().isEmpty()) {
212 throw new IllegalArgumentException("port_id should not be empty");
213 }
lishuaid6f0c9e2015-12-16 11:40:01 +0800214 VirtualPortId portId = VirtualPortId
215 .portId(subnode.get("port_id").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800216 RouterInterface routerInterface = RouterInterface
217 .routerInterface(subnetId, portId, routerId, tenentId);
218 get(RouterInterfaceService.class)
219 .addRouterInterface(routerInterface);
220 return ok(INTFACR_ADD_SUCCESS).build();
221 } catch (Exception e) {
222 return Response.status(BAD_REQUEST).entity(e.getMessage()).build();
223 }
224 }
225
226 @PUT
227 @Path("{routerUUID}/remove_router_interface")
228 @Produces(MediaType.APPLICATION_JSON)
229 @Consumes(MediaType.APPLICATION_JSON)
230 public Response removeRouterInterface(@PathParam("routerUUID") String id,
231 final InputStream input) {
232 if (!get(RouterService.class).exists(RouterId.valueOf(id))) {
233 return Response.status(NOT_FOUND).entity(NOT_EXIST).build();
234 }
235 try {
236 ObjectMapper mapper = new ObjectMapper();
237 JsonNode subnode = mapper.readTree(input);
238 if (!subnode.hasNonNull("id")) {
239 throw new IllegalArgumentException("id should not be null");
240 } else if (subnode.get("id").asText().isEmpty()) {
241 throw new IllegalArgumentException("id should not be empty");
242 }
243 RouterId routerId = RouterId.valueOf(id);
244 if (!subnode.hasNonNull("subnet_id")) {
245 throw new IllegalArgumentException("subnet_id should not be null");
246 } else if (subnode.get("subnet_id").asText().isEmpty()) {
247 throw new IllegalArgumentException("subnet_id should not be empty");
248 }
lishuaid6f0c9e2015-12-16 11:40:01 +0800249 SubnetId subnetId = SubnetId
250 .subnetId(subnode.get("subnet_id").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800251 if (!subnode.hasNonNull("port_id")) {
252 throw new IllegalArgumentException("port_id should not be null");
253 } else if (subnode.get("port_id").asText().isEmpty()) {
254 throw new IllegalArgumentException("port_id should not be empty");
255 }
lishuaid6f0c9e2015-12-16 11:40:01 +0800256 VirtualPortId portId = VirtualPortId
257 .portId(subnode.get("port_id").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800258 if (!subnode.hasNonNull("tenant_id")) {
259 throw new IllegalArgumentException("tenant_id should not be null");
260 } else if (subnode.get("tenant_id").asText().isEmpty()) {
261 throw new IllegalArgumentException("tenant_id should not be empty");
262 }
lishuaid6f0c9e2015-12-16 11:40:01 +0800263 TenantId tenentId = TenantId
264 .tenantId(subnode.get("tenant_id").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800265 RouterInterface routerInterface = RouterInterface
266 .routerInterface(subnetId, portId, routerId, tenentId);
267 get(RouterInterfaceService.class)
268 .removeRouterInterface(routerInterface);
269 return ok(INTFACR_DEL_SUCCESS).build();
270 } catch (Exception e) {
271 return Response.status(BAD_REQUEST).entity(e.getMessage()).build();
272 }
273 }
274
275 private Collection<Router> createOrUpdateByInputStream(JsonNode subnode)
276 throws Exception {
277 checkNotNull(subnode, JSON_NOT_NULL);
278 JsonNode routerNode = subnode.get("routers");
279 if (routerNode == null) {
280 routerNode = subnode.get("router");
281 }
282 log.debug("routerNode is {}", routerNode.toString());
283
284 if (routerNode.isArray()) {
285 throw new Exception("only singleton requests allowed");
286 } else {
287 return changeJsonToSub(routerNode);
288 }
289 }
290
291 /**
292 * Returns a collection of floatingIps from floatingIpNodes.
293 *
294 * @param routerNode the router json node
295 * @return routers a collection of router
Bharat saraswald270b182015-12-01 01:53:06 +0530296 * @throws Exception when any argument is illegal
jiangrui330b0c92015-11-28 14:09:50 +0800297 */
298 public Collection<Router> changeJsonToSub(JsonNode routerNode)
299 throws Exception {
300 checkNotNull(routerNode, JSON_NOT_NULL);
301 Map<RouterId, Router> subMap = new HashMap<RouterId, Router>();
302 if (!routerNode.hasNonNull("id")) {
303 new IllegalArgumentException("id should not be null");
304 } else if (routerNode.get("id").asText().isEmpty()) {
305 throw new IllegalArgumentException("id should not be empty");
306 }
307 RouterId id = RouterId.valueOf(routerNode.get("id").asText());
308
309 if (!routerNode.hasNonNull("tenant_id")) {
310 throw new IllegalArgumentException("tenant_id should not be null");
311 } else if (routerNode.get("tenant_id").asText().isEmpty()) {
312 throw new IllegalArgumentException("tenant_id should not be empty");
313 }
lishuaid6f0c9e2015-12-16 11:40:01 +0800314 TenantId tenantId = TenantId
315 .tenantId(routerNode.get("tenant_id").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800316
317 VirtualPortId gwPortId = null;
318 if (routerNode.hasNonNull("gw_port_id")) {
lishuaid6f0c9e2015-12-16 11:40:01 +0800319 gwPortId = VirtualPortId
320 .portId(routerNode.get("gw_port_id").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800321 }
322
323 if (!routerNode.hasNonNull("status")) {
324 throw new IllegalArgumentException("status should not be null");
325 } else if (routerNode.get("status").asText().isEmpty()) {
326 throw new IllegalArgumentException("status should not be empty");
327 }
328 Status status = Status.valueOf(routerNode.get("status").asText());
329
330 String routerName = null;
331 if (routerNode.hasNonNull("name")) {
332 routerName = routerNode.get("name").asText();
333 }
334
335 boolean adminStateUp = true;
336 checkArgument(routerNode.get("admin_state_up").isBoolean(),
337 "admin_state_up should be boolean");
338 if (routerNode.hasNonNull("admin_state_up")) {
339 adminStateUp = routerNode.get("admin_state_up").asBoolean();
340 }
341 boolean distributed = false;
342 if (routerNode.hasNonNull("distributed")) {
343 distributed = routerNode.get("distributed").asBoolean();
344 }
345 RouterGateway gateway = null;
346 if (routerNode.hasNonNull("external_gateway_info")) {
lishuaid6f0c9e2015-12-16 11:40:01 +0800347 gateway = jsonNodeToGateway(routerNode
348 .get("external_gateway_info"));
349 }
350 List<String> routes = new ArrayList<String>();
351 DefaultRouter routerObj = new DefaultRouter(id, routerName,
352 adminStateUp, status,
353 distributed, gateway,
354 gwPortId, tenantId, routes);
355 subMap.put(id, routerObj);
356 return Collections.unmodifiableCollection(subMap.values());
357 }
358
359 /**
360 * Returns a collection of floatingIps from floatingIpNodes.
361 *
362 * @param subnode the router json node
363 * @param routerId the router identify
364 * @return routers a collection of router
365 * @throws Exception when any argument is illegal
366 */
367 public Collection<Router> changeUpdateJsonToSub(JsonNode subnode,
368 String routerId)
369 throws Exception {
370 checkNotNull(subnode, JSON_NOT_NULL);
371 checkNotNull(routerId, "routerId should not be null");
372 Map<RouterId, Router> subMap = new HashMap<RouterId, Router>();
373 JsonNode routerNode = subnode.get("router");
374 RouterId id = RouterId.valueOf(routerId);
375 Router sub = nullIsNotFound(get(RouterService.class).getRouter(id),
376 NOT_EXIST);
377 TenantId tenantId = sub.tenantId();
378
379 VirtualPortId gwPortId = null;
380 if (routerNode.hasNonNull("gw_port_id")) {
381 gwPortId = VirtualPortId
382 .portId(routerNode.get("gw_port_id").asText());
383 }
384 Status status = sub.status();
385
386 String routerName = routerNode.get("name").asText();
387
388 checkArgument(routerNode.get("admin_state_up").isBoolean(),
389 "admin_state_up should be boolean");
390 boolean adminStateUp = routerNode.get("admin_state_up").asBoolean();
391
392 boolean distributed = sub.distributed();
393 if (routerNode.hasNonNull("distributed")) {
394 distributed = routerNode.get("distributed").asBoolean();
395 }
396 RouterGateway gateway = sub.externalGatewayInfo();
397 if (routerNode.hasNonNull("external_gateway_info")) {
398 gateway = jsonNodeToGateway(routerNode
399 .get("external_gateway_info"));
jiangrui330b0c92015-11-28 14:09:50 +0800400 }
401 List<String> routes = new ArrayList<String>();
402 DefaultRouter routerObj = new DefaultRouter(id, routerName,
403 adminStateUp, status,
404 distributed, gateway,
405 gwPortId, tenantId, routes);
406 subMap.put(id, routerObj);
407 return Collections.unmodifiableCollection(subMap.values());
408 }
409
410 /**
411 * Changes JsonNode Gateway to the Gateway.
412 *
413 * @param gateway the gateway JsonNode
414 * @return gateway
415 */
416 private RouterGateway jsonNodeToGateway(JsonNode gateway) {
417 checkNotNull(gateway, JSON_NOT_NULL);
418 if (!gateway.hasNonNull("network_id")) {
419 throw new IllegalArgumentException("network_id should not be null");
420 } else if (gateway.get("network_id").asText().isEmpty()) {
421 throw new IllegalArgumentException("network_id should not be empty");
422 }
lishuaid6f0c9e2015-12-16 11:40:01 +0800423 TenantNetworkId networkId = TenantNetworkId
424 .networkId(gateway.get("network_id").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800425
426 if (!gateway.hasNonNull("enable_snat")) {
427 throw new IllegalArgumentException("enable_snat should not be null");
428 } else if (gateway.get("enable_snat").asText().isEmpty()) {
429 throw new IllegalArgumentException("enable_snat should not be empty");
430 }
431 checkArgument(gateway.get("enable_snat").isBoolean(),
432 "enable_snat should be boolean");
433 boolean enableSnat = gateway.get("enable_snat").asBoolean();
434
435 if (!gateway.hasNonNull("external_fixed_ips")) {
lishuaid6f0c9e2015-12-16 11:40:01 +0800436 throw new IllegalArgumentException("external_fixed_ips should not be null");
jiangrui330b0c92015-11-28 14:09:50 +0800437 } else if (gateway.get("external_fixed_ips").isNull()) {
lishuaid6f0c9e2015-12-16 11:40:01 +0800438 throw new IllegalArgumentException("external_fixed_ips should not be empty");
jiangrui330b0c92015-11-28 14:09:50 +0800439 }
yuanyoue2ed3862016-05-06 13:18:08 +0800440 Iterable<FixedIp> fixedIpList = jsonNodeToFixedIp(gateway
jiangrui330b0c92015-11-28 14:09:50 +0800441 .get("external_fixed_ips"));
lishuaid6f0c9e2015-12-16 11:40:01 +0800442 RouterGateway gatewayObj = RouterGateway
yuanyoue2ed3862016-05-06 13:18:08 +0800443 .routerGateway(networkId, enableSnat, Sets.newHashSet(fixedIpList));
jiangrui330b0c92015-11-28 14:09:50 +0800444 return gatewayObj;
445 }
446
447 /**
448 * Changes JsonNode fixedIp to a collection of the fixedIp.
449 *
450 * @param fixedIp the allocationPools JsonNode
451 * @return a collection of fixedIp
452 */
yuanyoue2ed3862016-05-06 13:18:08 +0800453 private Iterable<FixedIp> jsonNodeToFixedIp(JsonNode fixedIp) {
jiangrui330b0c92015-11-28 14:09:50 +0800454 checkNotNull(fixedIp, JSON_NOT_NULL);
455 ConcurrentMap<Integer, FixedIp> fixedIpMaps = Maps.newConcurrentMap();
456 Integer i = 0;
457 for (JsonNode node : fixedIp) {
458 if (!node.hasNonNull("subnet_id")) {
459 throw new IllegalArgumentException("subnet_id should not be null");
460 } else if (node.get("subnet_id").asText().isEmpty()) {
461 throw new IllegalArgumentException("subnet_id should not be empty");
462 }
lishuaid6f0c9e2015-12-16 11:40:01 +0800463 SubnetId subnetId = SubnetId
464 .subnetId(node.get("subnet_id").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800465 if (!node.hasNonNull("ip_address")) {
466 throw new IllegalArgumentException("ip_address should not be null");
467 } else if (node.get("ip_address").asText().isEmpty()) {
468 throw new IllegalArgumentException("ip_address should not be empty");
469 }
lishuaid6f0c9e2015-12-16 11:40:01 +0800470 IpAddress ipAddress = IpAddress
471 .valueOf(node.get("ip_address").asText());
jiangrui330b0c92015-11-28 14:09:50 +0800472 FixedIp fixedIpObj = FixedIp.fixedIp(subnetId, ipAddress);
473
474 fixedIpMaps.putIfAbsent(i, fixedIpObj);
475 i++;
476 }
477 return Collections.unmodifiableCollection(fixedIpMaps.values());
478 }
479
480 /**
481 * Returns the specified item if that items is null; otherwise throws not
482 * found exception.
483 *
484 * @param item item to check
485 * @param <T> item type
486 * @param message not found message
487 * @return item if not null
488 * @throws org.onlab.util.ItemNotFoundException if item is null
489 */
490 protected <T> T nullIsNotFound(T item, String message) {
491 if (item == null) {
492 throw new ItemNotFoundException(message);
493 }
494 return item;
495 }
496}