blob: 6d7d9f4761ed81aaca0efa06b6c7f7cde2e33f7c [file] [log] [blame]
xuzhangfda00932015-08-11 11:33:45 +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.net.HostId;
47import org.onosproject.rest.AbstractWebResource;
48import org.onosproject.app.vtnrsc.AllowedAddressPair;
49import org.onosproject.app.vtnrsc.DefaultVirtualPort;
50import org.onosproject.app.vtnrsc.FixedIp;
51import org.onosproject.app.vtnrsc.SecurityGroup;
52import org.onosproject.app.vtnrsc.SubnetId;
53import org.onosproject.app.vtnrsc.TenantId;
54import org.onosproject.app.vtnrsc.TenantNetworkId;
55import org.onosproject.app.vtnrsc.VirtualPort;
56import org.onosproject.app.vtnrsc.VirtualPortId;
57import org.onosproject.app.vtnrsc.VirtualPort.State;
58import org.onosproject.app.vtnrsc.virtualport.VirtualPortService;
59import org.onosproject.app.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))) {
97 return ok("the virtualPort does not exists").build();
98 }
99 VirtualPort virtualPort = nullIsNotFound(get(VirtualPortService.class)
100 .getPort(VirtualPortId.portId(id)), VPORT_NOT_FOUND);
101 ObjectNode result = new ObjectMapper().createObjectNode();
102 result.set("ports", new VirtualPortCodec().encode(virtualPort, this));
103 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 fixedIpNode = vPortnode.get("fixed_ips");
220 FixedIp fixedIp = jsonNodeToFixedIps(fixedIpNode);
221 HostId bindingHostId = HostId.hostId(MacAddress.valueOf(vPortnode
222 .get("binding:host_id").asText()));
223 String bindingVnicType = vPortnode.get("binding:vnic_type")
224 .asText();
225 String bindingVifType = vPortnode.get("binding:vif_type").asText();
226 String bindingVifDetails = vPortnode.get("binding:vif_details")
227 .asText();
228 JsonNode allowedAddressPairJsonNode = vPortnode
229 .get("allowed_address_pairs");
230 Collection<AllowedAddressPair> allowedAddressPairs =
231 jsonNodeToAllowedAddressPair(allowedAddressPairJsonNode);
232 JsonNode securityGroupNode = vPortnode.get("security_groups");
233 Collection<SecurityGroup> securityGroups =
234 jsonNodeToSecurityGroup(securityGroupNode);
235 strMap.putIfAbsent("name", name);
236 strMap.putIfAbsent("deviceOwner", deviceOwner);
237 strMap.putIfAbsent("bindingVnicType", bindingVnicType);
238 strMap.putIfAbsent("bindingVifType", bindingVifType);
239 strMap.putIfAbsent("bindingVifDetails", bindingVifDetails);
240 VirtualPort vPort = new DefaultVirtualPort(id, networkId,
241 adminStateUp, strMap,
242 isState(state),
243 macAddress, tenantId,
244 deviceId, fixedIp,
245 bindingHostId,
246 allowedAddressPairs,
247 securityGroups);
248 portMap.put(id, vPort);
249 }
250 return Collections.unmodifiableCollection(portMap.values());
251 }
252
253 /**
254 * Returns a collection of virtualPorts from subnetNodes.
255 *
256 * @param vPortNodes the virtualPort json node
257 * @return virtualPorts a collection of virtualPorts
258 */
259 public Iterable<VirtualPort> changeJsonToPort(JsonNode vPortNodes) {
260 checkNotNull(vPortNodes, JSON_NOT_NULL);
261 Map<VirtualPortId, VirtualPort> vportMap = new HashMap<VirtualPortId, VirtualPort>();
262 Map<String, String> strMap = new HashMap<String, String>();
263 VirtualPortId id = VirtualPortId.portId(vPortNodes.get("id").asText());
264 String name = vPortNodes.get("name").asText();
265 TenantId tenantId = TenantId.tenantId(vPortNodes.get("tenant_id")
266 .asText());
267 TenantNetworkId networkId = TenantNetworkId.networkId(vPortNodes
268 .get("network_id").asText());
269 Boolean adminStateUp = vPortNodes.get("admin_state_up").asBoolean();
270 String state = vPortNodes.get("status").asText();
271 MacAddress macAddress = MacAddress.valueOf(vPortNodes
272 .get("mac_address").asText());
273 DeviceId deviceId = DeviceId.deviceId(vPortNodes.get("device_id")
274 .asText());
275 String deviceOwner = vPortNodes.get("device_owner").asText();
276 JsonNode fixedIpNode = vPortNodes.get("fixed_ips");
277 FixedIp fixedIp = jsonNodeToFixedIps(fixedIpNode);
278 HostId bindingHostId = HostId.hostId(MacAddress.valueOf(vPortNodes
279 .get("binding:host_id").asText()));
280 String bindingVnicType = vPortNodes.get("binding:vnic_type").asText();
281 String bindingVifType = vPortNodes.get("binding:vif_type").asText();
282 String bindingVifDetails = vPortNodes.get("binding:vif_details")
283 .asText();
284 JsonNode allowedAddressPairJsonNode = vPortNodes
285 .get("allowed_address_pairs");
286 Collection<AllowedAddressPair> allowedAddressPairs =
287 jsonNodeToAllowedAddressPair(allowedAddressPairJsonNode);
288 JsonNode securityGroupNode = vPortNodes.get("security_groups");
289 Collection<SecurityGroup> securityGroups =
290 jsonNodeToSecurityGroup(securityGroupNode);
291 strMap.putIfAbsent("name", name);
292 strMap.putIfAbsent("deviceOwner", deviceOwner);
293 strMap.putIfAbsent("bindingVnicType", bindingVnicType);
294 strMap.putIfAbsent("bindingVifType", bindingVifType);
295 strMap.putIfAbsent("bindingVifDetails", bindingVifDetails);
296 VirtualPort vPort = new DefaultVirtualPort(id, networkId, adminStateUp,
297 strMap, isState(state),
298 macAddress, tenantId,
299 deviceId, fixedIp,
300 bindingHostId,
301 allowedAddressPairs,
302 securityGroups);
303 vportMap.put(id, vPort);
304
305 return Collections.unmodifiableCollection(vportMap.values());
306 }
307
308 /**
309 * Returns a Object of the currently known infrastructure virtualPort.
310 *
311 * @param allowedAddressPairs the allowedAddressPairs json node
312 * @return a collection of allowedAddressPair
313 */
314 public Collection<AllowedAddressPair> jsonNodeToAllowedAddressPair(JsonNode allowedAddressPairs) {
315 checkNotNull(allowedAddressPairs, JSON_NOT_NULL);
316 ConcurrentMap<Integer, AllowedAddressPair> allowMaps = Maps
317 .newConcurrentMap();
318 int i = 0;
319 for (JsonNode node : allowedAddressPairs) {
320 IpAddress ip = IpAddress.valueOf(node.get("ip_address").asText());
321 MacAddress mac = MacAddress.valueOf(node.get("mac_address")
322 .asText());
323 AllowedAddressPair allows = AllowedAddressPair
324 .allowedAddressPair(ip, mac);
325 allowMaps.put(i, allows);
326 i++;
327 }
328 log.debug("The jsonNode of allowedAddressPairallow is {}"
329 + allowedAddressPairs.toString());
330 return Collections.unmodifiableCollection(allowMaps.values());
331 }
332
333 /**
334 * Returns a collection of virtualPorts.
335 *
336 * @param securityGroups the virtualPort jsonnode
337 * @return a collection of securityGroups
338 */
339 public Collection<SecurityGroup> jsonNodeToSecurityGroup(JsonNode securityGroups) {
340 checkNotNull(securityGroups, JSON_NOT_NULL);
341 ConcurrentMap<Integer, SecurityGroup> securMaps = Maps
342 .newConcurrentMap();
343 int i = 0;
344 for (JsonNode node : securityGroups) {
345 SecurityGroup securityGroup = SecurityGroup.securityGroup(node
346 .get("security_group").asText());
347 securMaps.put(i, securityGroup);
348 i++;
349 }
350 return Collections.unmodifiableCollection(securMaps.values());
351 }
352
353 /**
354 * Returns a collection of fixedIps.
355 *
356 * @param fixedIpNode the fixedIp jsonnode
357 * @return a collection of SecurityGroup
358 */
359 public FixedIp jsonNodeToFixedIps(JsonNode fixedIpNode) {
360 SubnetId subnetId = SubnetId.subnetId(fixedIpNode.get("subnet_id")
361 .asText());
362 IpAddress ipAddress = IpAddress.valueOf(fixedIpNode.get("ip_address")
363 .asText());
364 FixedIp fixedIps = FixedIp.fixedIp(subnetId, ipAddress);
365 return fixedIps;
366 }
367
368 /**
369 * Returns VirtualPort State.
370 *
371 * @param state the virtualport state
372 * @return the virtualPort state
373 */
374 private State isState(String state) {
375 if (state.equals("ACTIVE")) {
376 return VirtualPort.State.ACTIVE;
377 } else {
378 return VirtualPort.State.DOWN;
379 }
380
381 }
382
383 /**
384 * Returns the specified item if that items is null; otherwise throws not
385 * found exception.
386 *
387 * @param item item to check
388 * @param <T> item type
389 * @param message not found message
390 * @return item if not null
391 * @throws org.onlab.util.ItemNotFoundException if item is null
392 */
393 protected <T> T nullIsNotFound(T item, String message) {
394 if (item == null) {
395 throw new ItemNotFoundException(message);
396 }
397 return item;
398 }
399}