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