2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.hosttracker.northbound;
11 import java.net.InetAddress;
12 import java.net.UnknownHostException;
13 import java.util.HashSet;
14 import java.util.List;
17 import javax.ws.rs.Consumes;
18 import javax.ws.rs.DELETE;
19 import javax.ws.rs.GET;
20 import javax.ws.rs.PUT;
21 import javax.ws.rs.Path;
22 import javax.ws.rs.PathParam;
23 import javax.ws.rs.Produces;
24 import javax.ws.rs.QueryParam;
25 import javax.ws.rs.core.Context;
26 import javax.ws.rs.core.MediaType;
27 import javax.ws.rs.core.Response;
28 import javax.ws.rs.core.SecurityContext;
29 import javax.ws.rs.core.UriInfo;
30 import javax.ws.rs.ext.ContextResolver;
32 import org.codehaus.enunciate.jaxrs.ResponseCode;
33 import org.codehaus.enunciate.jaxrs.StatusCodes;
34 import org.codehaus.enunciate.jaxrs.TypeHint;
35 import org.opendaylight.controller.containermanager.IContainerManager;
36 import org.opendaylight.controller.hosttracker.IfIptoHost;
37 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
38 import org.opendaylight.controller.northbound.commons.RestMessages;
39 import org.opendaylight.controller.northbound.commons.exception.BadRequestException;
40 import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException;
41 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
42 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
43 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
44 import org.opendaylight.controller.northbound.commons.query.QueryContext;
45 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
46 import org.opendaylight.controller.sal.authorization.Privilege;
47 import org.opendaylight.controller.sal.core.Node;
48 import org.opendaylight.controller.sal.core.NodeConnector;
49 import org.opendaylight.controller.sal.utils.GlobalConstants;
50 import org.opendaylight.controller.sal.utils.ServiceHelper;
51 import org.opendaylight.controller.sal.utils.Status;
52 import org.opendaylight.controller.switchmanager.ISwitchManager;
55 * Host Tracker Northbound REST APIs.<br>
56 * This class provides REST APIs to track host location in a network. Host
57 * Location is represented by Host node connector which is essentially a logical
58 * entity that represents a Switch/Port. A host is represented by it's
59 * IP-address and mac-address.
63 * Authentication scheme : <b>HTTP Basic</b><br>
64 * Authentication realm : <b>opendaylight</b><br>
65 * Transport : <b>HTTP and HTTPS</b><br>
67 * HTTPS Authentication is disabled by default.
72 public class HostTrackerNorthbound {
74 private String username;
75 private QueryContext queryContext;
78 public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
79 if (queryCtxResolver != null) {
80 queryContext = queryCtxResolver.getContext(QueryContext.class);
85 public void setSecurityContext(SecurityContext context) {
86 if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName();
89 protected String getUserName() {
93 private IfIptoHost getIfIpToHostService(String containerName) {
94 IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance(
95 IContainerManager.class, this);
96 if (containerManager == null) {
97 throw new ServiceUnavailableException("Container " + RestMessages.SERVICEUNAVAILABLE.toString());
100 boolean found = false;
101 List<String> containerNames = containerManager.getContainerNames();
102 for (String cName : containerNames) {
103 if (cName.trim().equalsIgnoreCase(containerName.trim())) {
110 throw new ResourceNotFoundException(containerName + " " + RestMessages.NOCONTAINER.toString());
113 IfIptoHost hostTracker = (IfIptoHost) ServiceHelper.getInstance(IfIptoHost.class, containerName, this);
114 if (hostTracker == null) {
115 throw new ServiceUnavailableException("Host Tracker " + RestMessages.SERVICEUNAVAILABLE.toString());
121 private Set<HostConfig> convertHosts(Set<HostNodeConnector> hostNodeConnectors) {
122 if(hostNodeConnectors == null) {
125 Set<HostConfig> hosts = new HashSet<HostConfig>();
126 for(HostNodeConnector hnc : hostNodeConnectors) {
127 hosts.add(HostConfig.convert(hnc));
133 * Returns a list of all Hosts : both configured via PUT API and dynamically
134 * learnt on the network.
136 * @param containerName
137 * Name of the Container. The Container name for the base
138 * controller is "default".
139 * @return List of Active Hosts.
145 * http://localhost:8080/controller/nb/v2/hosttracker/default/hosts/active
147 * Response body in XML
150 *  <hostConfig>
151 *   <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
152 *   <networkAddress>1.1.1.1</networkAddress>
153 *   <nodeType>OF</nodeType>
154 *   <nodeId>00:00:00:00:00:00:00:01</nodeId>
155 *   <nodeConnectorType>OF</nodeConnectorType>
156 *   <nodeConnectorId>9</nodeConnectorId>
157 *   <vlan>0</vlan>
158 *   <staticHost>false</staticHost>
159 *  </hostConfig>
160 *  <hostConfig>
161 *   <dataLayerAddress>00:00:00:00:02:02</dataLayerAddress>
162 *   <networkAddress>2.2.2.2</networkAddress>
163 *   <nodeType>OF</nodeType>
164 *   <nodeId>00:00:00:00:00:00:00:02</nodeId>
165 *   <nodeConnectorType>OF</nodeConnectorType>
166 *   <nodeConnectorId>5</nodeConnectorId>
167 *   <vlan>0</vlan>
168 *   <staticHost>false</staticHost>
169 *  </hostConfig>
172 * Response body in JSON:
175 *  "hostConfig":[
177 *    "dataLayerAddress":"00:00:00:00:01:01",
178 *    "nodeType":"OF",
179 *    "nodeId":"00:00:00:00:00:00:00:01",
180 *    "nodeConnectorType":"OF",
181 *    "nodeConnectorId":"9",
182 *    "vlan":"0",
183 *    "staticHost":"false",
184 *    "networkAddress":"1.1.1.1"
187 *    "dataLayerAddress":"00:00:00:00:02:02",
188 *    "nodeType":"OF",
189 *    "nodeId":"00:00:00:00:00:00:00:02",
190 *    "nodeConnectorType":"OF",
191 *    "nodeConnectorId":"5",
192 *    "vlan":"0",
193 *    "staticHost":"false",
194 *    "networkAddress":"2.2.2.2"
200 @Path("/{containerName}/hosts/active")
202 @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
203 @TypeHint(Hosts.class)
205 @ResponseCode(code = 200, condition = "Operation successful"),
206 @ResponseCode(code = 404, condition = "The containerName is not found"),
207 @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
208 public Hosts getActiveHosts(@PathParam("containerName") String containerName,
209 @QueryParam("_q") String queryString) {
211 if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
212 throw new UnauthorizedException("User is not authorized to perform this operation on container "
215 IfIptoHost hostTracker = getIfIpToHostService(containerName);
216 Hosts hosts = new Hosts(convertHosts(hostTracker.getAllHosts()));
217 if (queryString != null) {
218 queryContext.createQuery(queryString, Hosts.class)
219 .filter(hosts, HostConfig.class);
225 * Returns a list of Hosts that are statically configured and are connected
226 * to a NodeConnector that is down.
228 * @param containerName
229 * Name of the Container. The Container name for the base
230 * controller is "default".
231 * @return List of inactive Hosts.
237 * http://localhost:8080/controller/nb/v2/hosttracker/default/hosts/inactive
239 * Response body in XML
242 *  <hostConfig>
243 *   <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
244 *   <networkAddress>1.1.1.1</networkAddress>
245 *   <nodeType>OF</nodeType>
246 *   <nodeId>00:00:00:00:00:00:00:01</nodeId>
247 *   <nodeConnectorType>OF</nodeConnectorType>
248 *   <nodeConnectorId>9</nodeConnectorId>
249 *   <vlan>0</vlan>
250 *   <staticHost>false</staticHost>
251 *  </hostConfig>
252 *  <hostConfig>
253 *   <dataLayerAddress>00:00:00:00:02:02</dataLayerAddress>
254 *   <networkAddress>2.2.2.2</networkAddress>
255 *   <nodeType>OF</nodeType>
256 *   <nodeId>00:00:00:00:00:00:00:02</nodeId>
257 *   <nodeConnectorType>OF</nodeConnectorType>
258 *   <nodeConnectorId>5</nodeConnectorId>
259 *   <vlan>0</vlan>
260 *   <staticHost>false</staticHost>
261 *  </hostConfig>
264 * Response body in JSON:
267 *  "hostConfig":[
269 *    "dataLayerAddress":"00:00:00:00:01:01",
270 *    "nodeType":"OF",
271 *    "nodeId":"00:00:00:00:00:00:00:01",
272 *    "nodeConnectorType":"OF",
273 *    "nodeConnectorId":"9",
274 *    "vlan":"0",
275 *    "staticHost":"false",
276 *    "networkAddress":"1.1.1.1"
279 *    "dataLayerAddress":"00:00:00:00:02:02",
280 *    "nodeType":"OF",
281 *    "nodeId":"00:00:00:00:00:00:00:02",
282 *    "nodeConnectorType":"OF",
283 *    "nodeConnectorId":"5",
284 *    "vlan":"0",
285 *    "staticHost":"false",
286 *    "networkAddress":"2.2.2.2"
292 @Path("/{containerName}/hosts/inactive")
294 @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
295 @TypeHint(Hosts.class)
297 @ResponseCode(code = 200, condition = "Operation successful"),
298 @ResponseCode(code = 404, condition = "The containerName is not found"),
299 @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
300 public Hosts getInactiveHosts(
301 @PathParam("containerName") String containerName,
302 @QueryParam("_q") String queryString) {
303 if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
304 throw new UnauthorizedException("User is not authorized to perform this operation on container "
307 IfIptoHost hostTracker = getIfIpToHostService(containerName);
308 Hosts hosts = new Hosts(convertHosts(hostTracker.getInactiveStaticHosts()));
309 if (queryString != null) {
310 queryContext.createQuery(queryString, Hosts.class)
311 .filter(hosts, HostConfig.class);
317 * Returns a host that matches the IP Address value passed as parameter.
319 * @param containerName
320 * Name of the Container. The Container name for the base
321 * controller is "default".
322 * @param networkAddress
323 * IP Address being looked up
324 * @return host that matches the IP Address
330 * http://localhost:8080/controller/nb/v2/hosttracker/default/address/1.1.1.1
332 * Response body in XML
335 *  <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
336 *  <networkAddress>1.1.1.1</networkAddress>
337 *  <nodeType>OF</nodeType>
338 *  <nodeId>00:00:00:00:00:00:00:01</nodeId>
339 *  <nodeConnectorType>OF</nodeConnectorType>
340 *  <nodeConnectorId>9</nodeConnectorId>
341 *  <vlan>0</vlan>
342 *  <staticHost>false</staticHost>
343 * </hostConfig>
345 * Response body in JSON:
348 *  "dataLayerAddress":"00:00:00:00:01:01",
349 *  "nodeType":"OF",
350 *  "nodeId":"00:00:00:00:00:00:00:01",
351 *  "nodeConnectorType":"OF",
352 *  "nodeConnectorId":"9",
354 *  "staticHost":"false",
355 *  "networkAddress":"1.1.1.1"
359 @Path("/{containerName}/address/{networkAddress}")
361 @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
362 @TypeHint(HostConfig.class)
364 @ResponseCode(code = 200, condition = "Operation successful"),
365 @ResponseCode(code = 400, condition = "Invalid IP specified in networkAddress parameter"),
366 @ResponseCode(code = 404, condition = "The containerName is not found"),
367 @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
368 public HostConfig getHostDetails(
369 @PathParam("containerName") String containerName,
370 @PathParam("networkAddress") String networkAddress) {
371 if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
372 throw new UnauthorizedException("User is not authorized to perform this operation on container "
375 IfIptoHost hostTracker = getIfIpToHostService(containerName);
379 ip = InetAddress.getByName(networkAddress);
380 } catch (UnknownHostException e) {
381 throw new BadRequestException(RestMessages.INVALIDADDRESS.toString() + " " + networkAddress);
383 for (HostNodeConnector host : hostTracker.getAllHosts()) {
384 if (host.getNetworkAddress().equals(ip)) {
385 return HostConfig.convert(host);
388 throw new ResourceNotFoundException(RestMessages.NOHOST.toString());
392 * Add a Static Host configuration. If a host by the given address already
393 * exists, this method will respond with a non-successful status response.
395 * @param containerName
396 * Name of the Container. The Container name for the base
397 * controller is "default".
398 * @param networkAddress
401 * Host Config Details
402 * @return Response as dictated by the HTTP Response Status code
409 * http://localhost:8080/controller/nb/v2/hosttracker/default/address/1.1.1.1
411 * Request body in XML
414 *  <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
415 *  <networkAddress>1.1.1.1</networkAddress>
416 *  <nodeType>OF</nodeType>
417 *  <nodeId>00:00:00:00:00:00:00:01</nodeId>
418 *  <nodeConnectorType>OF</nodeConnectorType>
419 *  <nodeConnectorId>9</nodeConnectorId>
420 *  <vlan>1</vlan>
421 *  <staticHost>true</staticHost>
422 * </hostConfig>
424 * Request body in JSON:
427 *  "dataLayerAddress":"00:00:00:00:01:01",
428 *  "nodeType":"OF",
429 *  "nodeId":"00:00:00:00:00:00:00:01",
430 *  "nodeConnectorType":"OF",
431 *  "nodeConnectorId":"9",
433 *  "staticHost":"true",
434 *  "networkAddress":"1.1.1.1"
439 @Path("/{containerName}/address/{networkAddress}")
441 @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
443 @ResponseCode(code = 201, condition = "Static host created successfully"),
444 @ResponseCode(code = 400, condition = "Invalid parameters specified, see response body for details"),
445 @ResponseCode(code = 404, condition = "The container or resource is not found"),
446 @ResponseCode(code = 409, condition = "Resource conflict, see response body for details"),
447 @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
448 public Response addHost(@Context UriInfo uriInfo, @PathParam("containerName") String containerName,
449 @PathParam("networkAddress") String networkAddress,
450 @TypeHint(HostConfig.class) HostConfig hostConfig) {
452 if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
453 return Response.status(Response.Status.UNAUTHORIZED)
454 .entity("User is not authorized to perform this operation on container " + containerName)
457 handleDefaultDisabled(containerName);
459 IfIptoHost hostTracker = getIfIpToHostService(containerName);
461 HostConfig hc = hostConfig;
462 if (!networkAddress.equals(hc.getNetworkAddress())) {
463 return Response.status(Response.Status.CONFLICT)
464 .entity("Resource name in config object doesn't match URI")
467 if (!hc.isStaticHost()) {
468 return Response.status(Response.Status.BAD_REQUEST)
469 .entity("Can only add static host.")
472 Node node = handleNodeAvailability(containerName, hc.getNodeType(), hc.getNodeId());
473 NodeConnector nc = NodeConnector.fromStringNoNode(hc.getNodeConnectorType(), hc.getNodeConnectorId(), node);
475 Status status = hostTracker.addStaticHost(networkAddress, hc.getDataLayerAddress(), nc, hc.getVlan());
476 if (status.isSuccess()) {
477 NorthboundUtils.auditlog("Static Host", username, "added", networkAddress, containerName);
478 return Response.created(uriInfo.getRequestUri()).build();
481 return NorthboundUtils.getResponse(status);
485 * Delete a Static Host configuration
487 * @param containerName
488 * Name of the Container. The Container name for the base
489 * controller is "default".
490 * @param networkAddress
492 * @return Response as dictated by the HTTP Response code.
497 * http://localhost:8080/controller/nb/v2/hosttracker/default/address/1.1.1.1
501 @Path("/{containerName}/address/{networkAddress}")
503 @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
505 @ResponseCode(code = 204, condition = "Static host deleted successfully"),
506 @ResponseCode(code = 404, condition = "The container or a specified resource was not found"),
507 @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active"),
508 @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") })
509 public Response deleteHost(
510 @PathParam(value = "containerName") String containerName,
511 @PathParam(value = "networkAddress") String networkAddress) {
513 if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
514 return Response.status(Response.Status.UNAUTHORIZED)
515 .entity("User is not authorized to perform this operation on container " + containerName)
518 handleDefaultDisabled(containerName);
519 IfIptoHost hostTracker = getIfIpToHostService(containerName);
521 Status status = hostTracker.removeStaticHost(networkAddress);
522 if (status.isSuccess()) {
523 NorthboundUtils.auditlog("Static Host", username, "removed", networkAddress, containerName);
524 return Response.noContent().build();
526 return NorthboundUtils.getResponse(status);
530 private void handleDefaultDisabled(String containerName) {
531 IContainerManager containerManager = (IContainerManager) ServiceHelper
532 .getGlobalInstance(IContainerManager.class, this);
533 if (containerManager == null) {
534 throw new ServiceUnavailableException(
535 RestMessages.SERVICEUNAVAILABLE.toString());
537 if (containerName.equals(GlobalConstants.DEFAULT.toString())
538 && containerManager.hasNonDefaultContainer()) {
539 throw new ResourceConflictException(
540 RestMessages.DEFAULTDISABLED.toString());
544 private Node handleNodeAvailability(String containerName, String nodeType, String nodeId) {
546 Node node = Node.fromString(nodeType, nodeId);
548 throw new ResourceNotFoundException(nodeId + " : "
549 + RestMessages.NONODE.toString());
552 ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(
553 ISwitchManager.class, containerName, this);
556 throw new ServiceUnavailableException("Switch Manager "
557 + RestMessages.SERVICEUNAVAILABLE.toString());
560 if (!sm.getNodes().contains(node)) {
561 throw new ResourceNotFoundException(node.toString() + " : "
562 + RestMessages.NONODE.toString());