blob: cb5b7d632653349776e4df44d87c1a5fedf17436 [file] [log] [blame]
Madan Jampani38a88212015-09-15 11:21:27 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Madan Jampani38a88212015-09-15 11:21:27 -07003 *
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
Jian Lic2a542b2016-05-10 11:48:19 -070018import com.fasterxml.jackson.databind.JsonNode;
19import com.fasterxml.jackson.databind.ObjectMapper;
20import com.fasterxml.jackson.databind.node.ObjectNode;
21import com.google.common.collect.Maps;
22import com.google.common.collect.Sets;
Madan Jampani38a88212015-09-15 11:21:27 -070023import org.onlab.packet.IpAddress;
24import org.onlab.packet.MacAddress;
25import org.onlab.util.ItemNotFoundException;
26import org.onosproject.net.DeviceId;
27import org.onosproject.rest.AbstractWebResource;
28import org.onosproject.vtnrsc.AllowedAddressPair;
29import org.onosproject.vtnrsc.BindingHostId;
30import org.onosproject.vtnrsc.DefaultVirtualPort;
31import org.onosproject.vtnrsc.FixedIp;
32import org.onosproject.vtnrsc.SecurityGroup;
33import org.onosproject.vtnrsc.SubnetId;
34import org.onosproject.vtnrsc.TenantId;
35import org.onosproject.vtnrsc.TenantNetworkId;
36import org.onosproject.vtnrsc.VirtualPort;
37import org.onosproject.vtnrsc.VirtualPort.State;
38import org.onosproject.vtnrsc.VirtualPortId;
39import org.onosproject.vtnrsc.virtualport.VirtualPortService;
onosjcc36e04a82015-10-27 16:46:37 +080040import org.onosproject.vtnweb.web.VirtualPortCodec;
Madan Jampani38a88212015-09-15 11:21:27 -070041import org.slf4j.Logger;
42import org.slf4j.LoggerFactory;
43
Jian Lic2a542b2016-05-10 11:48:19 -070044import javax.ws.rs.Consumes;
45import javax.ws.rs.DELETE;
46import javax.ws.rs.GET;
47import javax.ws.rs.POST;
48import javax.ws.rs.PUT;
49import javax.ws.rs.Path;
50import javax.ws.rs.PathParam;
51import javax.ws.rs.Produces;
52import javax.ws.rs.core.MediaType;
53import javax.ws.rs.core.Response;
54import java.io.InputStream;
55import java.util.Collection;
56import java.util.Collections;
57import java.util.HashMap;
58import java.util.HashSet;
59import java.util.Map;
60import java.util.Set;
61import java.util.concurrent.ConcurrentMap;
62
63import static com.google.common.base.Preconditions.checkArgument;
64import static com.google.common.base.Preconditions.checkNotNull;
65import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
66import static javax.ws.rs.core.Response.Status.NOT_FOUND;
67import static javax.ws.rs.core.Response.Status.OK;
Madan Jampani38a88212015-09-15 11:21:27 -070068
69/**
70 * REST resource for interacting with the inventory of infrastructure
71 * virtualPort.
72 */
73@Path("ports")
74public class VirtualPortWebResource extends AbstractWebResource {
75 public static final String VPORT_NOT_FOUND = "VirtualPort is not found";
76 public static final String VPORT_ID_EXIST = "VirtualPort id is exist";
77 public static final String VPORT_ID_NOT_EXIST = "VirtualPort id is not exist";
78 public static final String JSON_NOT_NULL = "JsonNode can not be null";
79 protected static final Logger log = LoggerFactory
80 .getLogger(VirtualPortService.class);
81
82 @GET
Wu wenbind0b119f2016-05-11 18:03:41 +080083 @Produces(MediaType.APPLICATION_JSON)
84 @Consumes(MediaType.APPLICATION_JSON)
Madan Jampani38a88212015-09-15 11:21:27 -070085 public Response getPorts() {
86 Iterable<VirtualPort> virtualPorts = get(VirtualPortService.class)
87 .getPorts();
88 ObjectNode result = new ObjectMapper().createObjectNode();
89 result.set("ports", new VirtualPortCodec().encode(virtualPorts, this));
90 return ok(result.toString()).build();
91 }
92
93 @GET
94 @Path("{id}")
Wu wenbind0b119f2016-05-11 18:03:41 +080095 @Produces(MediaType.APPLICATION_JSON)
96 @Consumes(MediaType.APPLICATION_JSON)
Madan Jampani38a88212015-09-15 11:21:27 -070097 public Response getportsById(@PathParam("id") String id) {
98
99 if (!get(VirtualPortService.class).exists(VirtualPortId.portId(id))) {
lishuai0f47f342015-09-16 11:38:48 +0800100 return Response.status(NOT_FOUND)
101 .entity(VPORT_NOT_FOUND).build();
Madan Jampani38a88212015-09-15 11:21:27 -0700102 }
103 VirtualPort virtualPort = nullIsNotFound(get(VirtualPortService.class)
104 .getPort(VirtualPortId.portId(id)), VPORT_NOT_FOUND);
105 ObjectNode result = new ObjectMapper().createObjectNode();
106 result.set("port", new VirtualPortCodec().encode(virtualPort, this));
107 return ok(result.toString()).build();
108 }
109
110 @POST
111 @Consumes(MediaType.APPLICATION_JSON)
112 @Produces(MediaType.APPLICATION_JSON)
113 public Response createPorts(InputStream input) {
114 try {
115 ObjectMapper mapper = new ObjectMapper();
116 JsonNode cfg = mapper.readTree(input);
117 Iterable<VirtualPort> vPorts = createOrUpdateByInputStream(cfg);
118 Boolean issuccess = nullIsNotFound(get(VirtualPortService.class)
119 .createPorts(vPorts), VPORT_NOT_FOUND);
120 if (!issuccess) {
121 return Response.status(INTERNAL_SERVER_ERROR)
122 .entity(VPORT_ID_NOT_EXIST).build();
123 }
124 return Response.status(OK).entity(issuccess.toString()).build();
125 } catch (Exception e) {
126 log.error("Creates VirtualPort failed because of exception {}",
127 e.toString());
128 return Response.status(INTERNAL_SERVER_ERROR).entity(e.toString())
129 .build();
130 }
131 }
132
Madan Jampani38a88212015-09-15 11:21:27 -0700133 @DELETE
Wu wenbinb0bd6132016-05-10 19:20:23 +0800134 @Path("{portUUID}")
135 @Consumes(MediaType.APPLICATION_JSON)
136 @Produces(MediaType.APPLICATION_JSON)
Madan Jampani38a88212015-09-15 11:21:27 -0700137 public Response deletePorts(@PathParam("portUUID") String id) {
138 Set<VirtualPortId> vPortIds = new HashSet<>();
139 try {
140 if (id != null) {
141 vPortIds.add(VirtualPortId.portId(id));
142 }
143 Boolean issuccess = nullIsNotFound(get(VirtualPortService.class)
144 .removePorts(vPortIds), VPORT_NOT_FOUND);
145 if (!issuccess) {
146 return Response.status(INTERNAL_SERVER_ERROR)
147 .entity(VPORT_ID_NOT_EXIST).build();
148 }
Jian Lic2a542b2016-05-10 11:48:19 -0700149 return ok(issuccess.toString()).build();
Madan Jampani38a88212015-09-15 11:21:27 -0700150 } catch (Exception e) {
151 log.error("Deletes VirtualPort failed because of exception {}",
152 e.toString());
153 return Response.status(INTERNAL_SERVER_ERROR).entity(e.toString())
154 .build();
155 }
156 }
157
158 @PUT
159 @Path("{id}")
160 @Consumes(MediaType.APPLICATION_JSON)
161 @Produces(MediaType.APPLICATION_JSON)
162 public Response updatePorts(@PathParam("id") String id, InputStream input) {
163 try {
164 ObjectMapper mapper = new ObjectMapper();
165 JsonNode cfg = mapper.readTree(input);
166 Iterable<VirtualPort> vPorts = createOrUpdateByInputStream(cfg);
167 Boolean issuccess = nullIsNotFound(get(VirtualPortService.class)
168 .updatePorts(vPorts), VPORT_NOT_FOUND);
169 if (!issuccess) {
170 return Response.status(INTERNAL_SERVER_ERROR)
171 .entity(VPORT_ID_NOT_EXIST).build();
172 }
173 return Response.status(OK).entity(issuccess.toString()).build();
174 } catch (Exception e) {
175 log.error("Updates failed because of exception {}", e.toString());
176 return Response.status(INTERNAL_SERVER_ERROR).entity(e.toString())
177 .build();
178 }
179 }
180
181 /**
182 * Returns a Object of the currently known infrastructure virtualPort.
183 *
184 * @param vPortNode the virtualPort json node
185 * @return a collection of virtualPorts
186 */
187 public Iterable<VirtualPort> createOrUpdateByInputStream(JsonNode vPortNode) {
188 checkNotNull(vPortNode, JSON_NOT_NULL);
189 JsonNode vPortNodes = vPortNode.get("ports");
190 if (vPortNodes == null) {
191 vPortNodes = vPortNode.get("port");
192 }
193 if (vPortNodes.isArray()) {
194 return changeJsonToPorts(vPortNodes);
195 } else {
196 return changeJsonToPort(vPortNodes);
197 }
198 }
199
200 /**
201 * Returns the iterable collection of virtualports from subnetNodes.
202 *
203 * @param vPortNodes the virtualPort json node
204 * @return virtualPorts a collection of virtualPorts
205 */
206 public Iterable<VirtualPort> changeJsonToPorts(JsonNode vPortNodes) {
207 checkNotNull(vPortNodes, JSON_NOT_NULL);
208 Map<VirtualPortId, VirtualPort> portMap = new HashMap<>();
209 Map<String, String> strMap = new HashMap<>();
210 for (JsonNode vPortnode : vPortNodes) {
211 VirtualPortId id = VirtualPortId.portId(vPortnode.get("id")
212 .asText());
213 String name = vPortnode.get("name").asText();
214 TenantId tenantId = TenantId.tenantId(vPortnode.get("tenant_id")
215 .asText());
216 TenantNetworkId networkId = TenantNetworkId.networkId(vPortnode
217 .get("network_id").asText());
218 checkArgument(vPortnode.get("admin_state_up").isBoolean(), "admin_state_up should be boolean");
219 Boolean adminStateUp = vPortnode.get("admin_state_up").asBoolean();
220 String state = vPortnode.get("status").asText();
221 MacAddress macAddress = MacAddress.valueOf(vPortnode
222 .get("mac_address").asText());
223 DeviceId deviceId = DeviceId.deviceId(vPortnode.get("device_id")
224 .asText());
225 String deviceOwner = vPortnode.get("device_owner").asText();
226 JsonNode fixedIpNodes = vPortNodes.get("fixed_ips");
227 Set<FixedIp> fixedIps = new HashSet<>();
228 for (JsonNode fixedIpNode : fixedIpNodes) {
229 FixedIp fixedIp = jsonNodeToFixedIps(fixedIpNode);
230 fixedIps.add(fixedIp);
231 }
232
233 BindingHostId bindingHostId = BindingHostId
234 .bindingHostId(vPortnode.get("binding:host_id").asText());
235 String bindingVnicType = vPortnode.get("binding:vnic_type")
236 .asText();
237 String bindingVifType = vPortnode.get("binding:vif_type").asText();
238 String bindingVifDetails = vPortnode.get("binding:vif_details")
239 .asText();
240 JsonNode allowedAddressPairJsonNode = vPortnode
241 .get("allowed_address_pairs");
242 Collection<AllowedAddressPair> allowedAddressPairs =
243 jsonNodeToAllowedAddressPair(allowedAddressPairJsonNode);
244 JsonNode securityGroupNode = vPortnode.get("security_groups");
245 Collection<SecurityGroup> securityGroups = jsonNodeToSecurityGroup(securityGroupNode);
246 strMap.put("name", name);
247 strMap.put("deviceOwner", deviceOwner);
248 strMap.put("bindingVnicType", bindingVnicType);
249 strMap.put("bindingVifType", bindingVifType);
250 strMap.put("bindingVifDetails", bindingVifDetails);
251 VirtualPort vPort = new DefaultVirtualPort(id, networkId,
252 adminStateUp, strMap,
253 isState(state),
254 macAddress, tenantId,
255 deviceId, fixedIps,
256 bindingHostId,
257 Sets.newHashSet(allowedAddressPairs),
258 Sets.newHashSet(securityGroups));
259 portMap.put(id, vPort);
260 }
261 return Collections.unmodifiableCollection(portMap.values());
262 }
263
264 /**
265 * Returns a collection of virtualPorts from subnetNodes.
266 *
267 * @param vPortNodes the virtualPort json node
268 * @return virtualPorts a collection of virtualPorts
269 */
270 public Iterable<VirtualPort> changeJsonToPort(JsonNode vPortNodes) {
271 checkNotNull(vPortNodes, JSON_NOT_NULL);
272 Map<VirtualPortId, VirtualPort> vportMap = new HashMap<>();
273 Map<String, String> strMap = new HashMap<>();
274 VirtualPortId id = VirtualPortId.portId(vPortNodes.get("id").asText());
275 String name = vPortNodes.get("name").asText();
276 TenantId tenantId = TenantId.tenantId(vPortNodes.get("tenant_id")
277 .asText());
278 TenantNetworkId networkId = TenantNetworkId.networkId(vPortNodes
279 .get("network_id").asText());
280 Boolean adminStateUp = vPortNodes.get("admin_state_up").asBoolean();
281 String state = vPortNodes.get("status").asText();
282 MacAddress macAddress = MacAddress.valueOf(vPortNodes
283 .get("mac_address").asText());
284 DeviceId deviceId = DeviceId.deviceId(vPortNodes.get("device_id")
285 .asText());
286 String deviceOwner = vPortNodes.get("device_owner").asText();
287 JsonNode fixedIpNodes = vPortNodes.get("fixed_ips");
288 Set<FixedIp> fixedIps = new HashSet<>();
289 for (JsonNode fixedIpNode : fixedIpNodes) {
290 FixedIp fixedIp = jsonNodeToFixedIps(fixedIpNode);
291 fixedIps.add(fixedIp);
292 }
293
294 BindingHostId bindingHostId = BindingHostId
295 .bindingHostId(vPortNodes.get("binding:host_id").asText());
296 String bindingVnicType = vPortNodes.get("binding:vnic_type").asText();
297 String bindingVifType = vPortNodes.get("binding:vif_type").asText();
298 String bindingVifDetails = vPortNodes.get("binding:vif_details")
299 .asText();
300 JsonNode allowedAddressPairJsonNode = vPortNodes
301 .get("allowed_address_pairs");
302 Collection<AllowedAddressPair> allowedAddressPairs =
303 jsonNodeToAllowedAddressPair(allowedAddressPairJsonNode);
304 JsonNode securityGroupNode = vPortNodes.get("security_groups");
305 Collection<SecurityGroup> securityGroups = jsonNodeToSecurityGroup(securityGroupNode);
306 strMap.put("name", name);
307 strMap.put("deviceOwner", deviceOwner);
308 strMap.put("bindingVnicType", bindingVnicType);
309 strMap.put("bindingVifType", bindingVifType);
310 strMap.put("bindingVifDetails", bindingVifDetails);
311 VirtualPort vPort = new DefaultVirtualPort(id, networkId, adminStateUp,
312 strMap, isState(state),
313 macAddress, tenantId,
314 deviceId, fixedIps,
315 bindingHostId,
316 Sets.newHashSet(allowedAddressPairs),
317 Sets.newHashSet(securityGroups));
318 vportMap.put(id, vPort);
319
320 return Collections.unmodifiableCollection(vportMap.values());
321 }
322
323 /**
324 * Returns a Object of the currently known infrastructure virtualPort.
325 *
326 * @param allowedAddressPairs the allowedAddressPairs json node
327 * @return a collection of allowedAddressPair
328 */
329 public Collection<AllowedAddressPair> jsonNodeToAllowedAddressPair(JsonNode allowedAddressPairs) {
330 checkNotNull(allowedAddressPairs, JSON_NOT_NULL);
331 ConcurrentMap<Integer, AllowedAddressPair> allowMaps = Maps
332 .newConcurrentMap();
333 int i = 0;
334 for (JsonNode node : allowedAddressPairs) {
335 IpAddress ip = IpAddress.valueOf(node.get("ip_address").asText());
336 MacAddress mac = MacAddress.valueOf(node.get("mac_address")
337 .asText());
338 AllowedAddressPair allows = AllowedAddressPair
339 .allowedAddressPair(ip, mac);
340 allowMaps.put(i, allows);
341 i++;
342 }
343 log.debug("The jsonNode of allowedAddressPairallow is {}"
344 + allowedAddressPairs.toString());
345 return Collections.unmodifiableCollection(allowMaps.values());
346 }
347
348 /**
349 * Returns a collection of virtualPorts.
350 *
351 * @param securityGroups the virtualPort jsonnode
352 * @return a collection of securityGroups
353 */
354 public Collection<SecurityGroup> jsonNodeToSecurityGroup(JsonNode securityGroups) {
355 checkNotNull(securityGroups, JSON_NOT_NULL);
356 ConcurrentMap<Integer, SecurityGroup> securMaps = Maps
357 .newConcurrentMap();
358 int i = 0;
359 for (JsonNode node : securityGroups) {
360 SecurityGroup securityGroup = SecurityGroup
361 .securityGroup(node.asText());
362 securMaps.put(i, securityGroup);
363 i++;
364 }
365 return Collections.unmodifiableCollection(securMaps.values());
366 }
367
368 /**
369 * Returns a collection of fixedIps.
370 *
371 * @param fixedIpNode the fixedIp jsonnode
372 * @return a collection of SecurityGroup
373 */
374 public FixedIp jsonNodeToFixedIps(JsonNode fixedIpNode) {
375 SubnetId subnetId = SubnetId.subnetId(fixedIpNode.get("subnet_id")
376 .asText());
377 IpAddress ipAddress = IpAddress.valueOf(fixedIpNode.get("ip_address")
378 .asText());
379 FixedIp fixedIps = FixedIp.fixedIp(subnetId, ipAddress);
380 return fixedIps;
381 }
382
383 /**
384 * Returns VirtualPort State.
385 *
386 * @param state the virtualport state
387 * @return the virtualPort state
388 */
389 private State isState(String state) {
Jon Halla3fcf672017-03-28 16:53:22 -0700390 if ("ACTIVE".equals(state)) {
Madan Jampani38a88212015-09-15 11:21:27 -0700391 return VirtualPort.State.ACTIVE;
392 } else {
393 return VirtualPort.State.DOWN;
394 }
395
396 }
397
398 /**
399 * Returns the specified item if that items is null; otherwise throws not
400 * found exception.
401 *
402 * @param item item to check
403 * @param <T> item type
404 * @param message not found message
405 * @return item if not null
406 * @throws org.onlab.util.ItemNotFoundException if item is null
407 */
408 protected <T> T nullIsNotFound(T item, String message) {
409 if (item == null) {
410 throw new ItemNotFoundException(message);
411 }
412 return item;
413 }
414}