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) {
87 username = context.getUserPrincipal().getName();
91 protected String getUserName() {
95 private IfIptoHost getIfIpToHostService(String containerName) {
96 IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance(
97 IContainerManager.class, this);
98 if (containerManager == null) {
99 throw new ServiceUnavailableException("Container " + RestMessages.SERVICEUNAVAILABLE.toString());
102 boolean found = false;
103 List<String> containerNames = containerManager.getContainerNames();
104 for (String cName : containerNames) {
105 if (cName.trim().equalsIgnoreCase(containerName.trim())) {
112 throw new ResourceNotFoundException(containerName + " " + RestMessages.NOCONTAINER.toString());
115 IfIptoHost hostTracker = (IfIptoHost) ServiceHelper.getInstance(IfIptoHost.class, containerName, this);
116 if (hostTracker == null) {
117 throw new ServiceUnavailableException("Host Tracker " + RestMessages.SERVICEUNAVAILABLE.toString());
123 private Set<HostConfig> convertHosts(Set<HostNodeConnector> hostNodeConnectors) {
124 if(hostNodeConnectors == null) {
127 Set<HostConfig> hosts = new HashSet<HostConfig>();
128 for(HostNodeConnector hnc : hostNodeConnectors) {
129 hosts.add(HostConfig.convert(hnc));
135 * Returns a list of all Hosts : both configured via PUT API and dynamically
136 * learnt on the network.
138 * @param containerName
139 * Name of the Container. The Container name for the base
140 * controller is "default".
141 * @return List of Active Hosts.
147 * http://localhost:8080/controller/nb/v2/hosttracker/default/hosts/active
149 * Response body in XML
152 *  <hostConfig>
153 *   <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
154 *   <networkAddress>1.1.1.1</networkAddress>
155 *   <nodeType>OF</nodeType>
156 *   <nodeId>00:00:00:00:00:00:00:01</nodeId>
157 *   <nodeConnectorType>OF</nodeConnectorType>
158 *   <nodeConnectorId>9</nodeConnectorId>
159 *   <vlan>0</vlan>
160 *   <staticHost>false</staticHost>
161 *  </hostConfig>
162 *  <hostConfig>
163 *   <dataLayerAddress>00:00:00:00:02:02</dataLayerAddress>
164 *   <networkAddress>2.2.2.2</networkAddress>
165 *   <nodeType>OF</nodeType>
166 *   <nodeId>00:00:00:00:00:00:00:02</nodeId>
167 *   <nodeConnectorType>OF</nodeConnectorType>
168 *   <nodeConnectorId>5</nodeConnectorId>
169 *   <vlan>0</vlan>
170 *   <staticHost>false</staticHost>
171 *  </hostConfig>
174 * Response body in JSON:
177 *  "hostConfig":[
179 *    "dataLayerAddress":"00:00:00:00:01:01",
180 *    "nodeType":"OF",
181 *    "nodeId":"00:00:00:00:00:00:00:01",
182 *    "nodeConnectorType":"OF",
183 *    "nodeConnectorId":"9",
184 *    "vlan":"0",
185 *    "staticHost":"false",
186 *    "networkAddress":"1.1.1.1"
189 *    "dataLayerAddress":"00:00:00:00:02:02",
190 *    "nodeType":"OF",
191 *    "nodeId":"00:00:00:00:00:00:00:02",
192 *    "nodeConnectorType":"OF",
193 *    "nodeConnectorId":"5",
194 *    "vlan":"0",
195 *    "staticHost":"false",
196 *    "networkAddress":"2.2.2.2"
202 @Path("/{containerName}/hosts/active")
204 @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
205 @TypeHint(Hosts.class)
207 @ResponseCode(code = 200, condition = "Operation successful"),
208 @ResponseCode(code = 404, condition = "The containerName is not found"),
209 @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
210 public Hosts getActiveHosts(@PathParam("containerName") String containerName,
211 @QueryParam("_q") String queryString) {
213 if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
214 throw new UnauthorizedException("User is not authorized to perform this operation on container "
217 IfIptoHost hostTracker = getIfIpToHostService(containerName);
218 Hosts hosts = new Hosts(convertHosts(hostTracker.getAllHosts()));
219 if (queryString != null) {
220 queryContext.createQuery(queryString, Hosts.class)
221 .filter(hosts, HostConfig.class);
227 * Returns a list of Hosts that are statically configured and are connected
228 * to a NodeConnector that is down.
230 * @param containerName
231 * Name of the Container. The Container name for the base
232 * controller is "default".
233 * @return List of inactive Hosts.
239 * http://localhost:8080/controller/nb/v2/hosttracker/default/hosts/inactive
241 * Response body in XML
244 *  <hostConfig>
245 *   <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
246 *   <networkAddress>1.1.1.1</networkAddress>
247 *   <nodeType>OF</nodeType>
248 *   <nodeId>00:00:00:00:00:00:00:01</nodeId>
249 *   <nodeConnectorType>OF</nodeConnectorType>
250 *   <nodeConnectorId>9</nodeConnectorId>
251 *   <vlan>0</vlan>
252 *   <staticHost>false</staticHost>
253 *  </hostConfig>
254 *  <hostConfig>
255 *   <dataLayerAddress>00:00:00:00:02:02</dataLayerAddress>
256 *   <networkAddress>2.2.2.2</networkAddress>
257 *   <nodeType>OF</nodeType>
258 *   <nodeId>00:00:00:00:00:00:00:02</nodeId>
259 *   <nodeConnectorType>OF</nodeConnectorType>
260 *   <nodeConnectorId>5</nodeConnectorId>
261 *   <vlan>0</vlan>
262 *   <staticHost>false</staticHost>
263 *  </hostConfig>
266 * Response body in JSON:
269 *  "hostConfig":[
271 *    "dataLayerAddress":"00:00:00:00:01:01",
272 *    "nodeType":"OF",
273 *    "nodeId":"00:00:00:00:00:00:00:01",
274 *    "nodeConnectorType":"OF",
275 *    "nodeConnectorId":"9",
276 *    "vlan":"0",
277 *    "staticHost":"false",
278 *    "networkAddress":"1.1.1.1"
281 *    "dataLayerAddress":"00:00:00:00:02:02",
282 *    "nodeType":"OF",
283 *    "nodeId":"00:00:00:00:00:00:00:02",
284 *    "nodeConnectorType":"OF",
285 *    "nodeConnectorId":"5",
286 *    "vlan":"0",
287 *    "staticHost":"false",
288 *    "networkAddress":"2.2.2.2"
294 @Path("/{containerName}/hosts/inactive")
296 @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
297 @TypeHint(Hosts.class)
299 @ResponseCode(code = 200, condition = "Operation successful"),
300 @ResponseCode(code = 404, condition = "The containerName is not found"),
301 @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
302 public Hosts getInactiveHosts(
303 @PathParam("containerName") String containerName,
304 @QueryParam("_q") String queryString) {
305 if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
306 throw new UnauthorizedException("User is not authorized to perform this operation on container "
309 IfIptoHost hostTracker = getIfIpToHostService(containerName);
310 Hosts hosts = new Hosts(convertHosts(hostTracker.getInactiveStaticHosts()));
311 if (queryString != null) {
312 queryContext.createQuery(queryString, Hosts.class)
313 .filter(hosts, HostConfig.class);
319 * Returns a host that matches the IP Address value passed as parameter.
321 * @param containerName
322 * Name of the Container. The Container name for the base
323 * controller is "default".
324 * @param networkAddress
325 * IP Address being looked up
326 * @return host that matches the IP Address
332 * http://localhost:8080/controller/nb/v2/hosttracker/default/address/1.1.1.1
334 * Response body in XML
337 *  <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
338 *  <networkAddress>1.1.1.1</networkAddress>
339 *  <nodeType>OF</nodeType>
340 *  <nodeId>00:00:00:00:00:00:00:01</nodeId>
341 *  <nodeConnectorType>OF</nodeConnectorType>
342 *  <nodeConnectorId>9</nodeConnectorId>
343 *  <vlan>0</vlan>
344 *  <staticHost>false</staticHost>
345 * </hostConfig>
347 * Response body in JSON:
350 *  "dataLayerAddress":"00:00:00:00:01:01",
351 *  "nodeType":"OF",
352 *  "nodeId":"00:00:00:00:00:00:00:01",
353 *  "nodeConnectorType":"OF",
354 *  "nodeConnectorId":"9",
356 *  "staticHost":"false",
357 *  "networkAddress":"1.1.1.1"
361 @Path("/{containerName}/address/{networkAddress}")
363 @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
364 @TypeHint(HostConfig.class)
366 @ResponseCode(code = 200, condition = "Operation successful"),
367 @ResponseCode(code = 400, condition = "Invalid IP specified in networkAddress parameter"),
368 @ResponseCode(code = 404, condition = "The containerName is not found"),
369 @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
370 public HostConfig getHostDetails(
371 @PathParam("containerName") String containerName,
372 @PathParam("networkAddress") String networkAddress) {
373 if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
374 throw new UnauthorizedException("User is not authorized to perform this operation on container "
377 IfIptoHost hostTracker = getIfIpToHostService(containerName);
381 ip = InetAddress.getByName(networkAddress);
382 } catch (UnknownHostException e) {
383 throw new BadRequestException(RestMessages.INVALIDADDRESS.toString() + " " + networkAddress);
385 for (HostNodeConnector host : hostTracker.getAllHosts()) {
386 if (host.getNetworkAddress().equals(ip)) {
387 return HostConfig.convert(host);
390 throw new ResourceNotFoundException(RestMessages.NOHOST.toString());
394 * Add a Static Host configuration. If a host by the given address already
395 * exists, this method will respond with a non-successful status response.
397 * @param containerName
398 * Name of the Container. The Container name for the base
399 * controller is "default".
400 * @param networkAddress
403 * Host Config Details
404 * @return Response as dictated by the HTTP Response Status code
411 * http://localhost:8080/controller/nb/v2/hosttracker/default/address/1.1.1.1
413 * Request body in XML
416 *  <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
417 *  <networkAddress>1.1.1.1</networkAddress>
418 *  <nodeType>OF</nodeType>
419 *  <nodeId>00:00:00:00:00:00:00:01</nodeId>
420 *  <nodeConnectorType>OF</nodeConnectorType>
421 *  <nodeConnectorId>9</nodeConnectorId>
422 *  <vlan>1</vlan>
423 *  <staticHost>true</staticHost>
424 * </hostConfig>
426 * Request body in JSON:
429 *  "dataLayerAddress":"00:00:00:00:01:01",
430 *  "nodeType":"OF",
431 *  "nodeId":"00:00:00:00:00:00:00:01",
432 *  "nodeConnectorType":"OF",
433 *  "nodeConnectorId":"9",
435 *  "staticHost":"true",
436 *  "networkAddress":"1.1.1.1"
441 @Path("/{containerName}/address/{networkAddress}")
443 @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
445 @ResponseCode(code = 201, condition = "Static host created successfully"),
446 @ResponseCode(code = 400, condition = "Invalid parameters specified, see response body for details"),
447 @ResponseCode(code = 404, condition = "The container or resource is not found"),
448 @ResponseCode(code = 409, condition = "Resource conflict, see response body for details"),
449 @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
450 public Response addHost(@Context UriInfo uriInfo, @PathParam("containerName") String containerName,
451 @PathParam("networkAddress") String networkAddress,
452 @TypeHint(HostConfig.class) HostConfig hostConfig) {
454 if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
455 return Response.status(Response.Status.UNAUTHORIZED)
456 .entity("User is not authorized to perform this operation on container " + containerName)
459 handleDefaultDisabled(containerName);
461 IfIptoHost hostTracker = getIfIpToHostService(containerName);
463 HostConfig hc = hostConfig;
464 if (!networkAddress.equals(hc.getNetworkAddress())) {
465 return Response.status(Response.Status.CONFLICT)
466 .entity("Resource name in config object doesn't match URI")
469 if (!hc.isStaticHost()) {
470 return Response.status(Response.Status.BAD_REQUEST)
471 .entity("Can only add static host.")
474 Node node = handleNodeAvailability(containerName, hc.getNodeType(), hc.getNodeId());
475 NodeConnector nc = NodeConnector.fromStringNoNode(hc.getNodeConnectorType(), hc.getNodeConnectorId(), node);
477 Status status = hostTracker.addStaticHost(networkAddress, hc.getDataLayerAddress(), nc, hc.getVlan());
478 if (status.isSuccess()) {
479 NorthboundUtils.auditlog("Static Host", username, "added", networkAddress, containerName);
480 return Response.created(uriInfo.getRequestUri()).build();
483 return NorthboundUtils.getResponse(status);
487 * Delete a Static Host configuration
489 * @param containerName
490 * Name of the Container. The Container name for the base
491 * controller is "default".
492 * @param networkAddress
494 * @return Response as dictated by the HTTP Response code.
499 * http://localhost:8080/controller/nb/v2/hosttracker/default/address/1.1.1.1
503 @Path("/{containerName}/address/{networkAddress}")
505 @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
507 @ResponseCode(code = 204, condition = "Static host deleted successfully"),
508 @ResponseCode(code = 404, condition = "The container or a specified resource was not found"),
509 @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active"),
510 @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") })
511 public Response deleteHost(
512 @PathParam(value = "containerName") String containerName,
513 @PathParam(value = "networkAddress") String networkAddress) {
515 if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
516 return Response.status(Response.Status.UNAUTHORIZED)
517 .entity("User is not authorized to perform this operation on container " + containerName)
520 handleDefaultDisabled(containerName);
521 IfIptoHost hostTracker = getIfIpToHostService(containerName);
523 Status status = hostTracker.removeStaticHost(networkAddress);
524 if (status.isSuccess()) {
525 NorthboundUtils.auditlog("Static Host", username, "removed", networkAddress, containerName);
526 return Response.noContent().build();
528 return NorthboundUtils.getResponse(status);
532 private void handleDefaultDisabled(String containerName) {
533 IContainerManager containerManager = (IContainerManager) ServiceHelper
534 .getGlobalInstance(IContainerManager.class, this);
535 if (containerManager == null) {
536 throw new ServiceUnavailableException(
537 RestMessages.SERVICEUNAVAILABLE.toString());
539 if (containerName.equals(GlobalConstants.DEFAULT.toString())
540 && containerManager.hasNonDefaultContainer()) {
541 throw new ResourceConflictException(
542 RestMessages.DEFAULTDISABLED.toString());
546 private Node handleNodeAvailability(String containerName, String nodeType, String nodeId) {
548 Node node = Node.fromString(nodeType, nodeId);
550 throw new ResourceNotFoundException(nodeId + " : "
551 + RestMessages.NONODE.toString());
554 ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(
555 ISwitchManager.class, containerName, this);
558 throw new ServiceUnavailableException("Switch Manager "
559 + RestMessages.SERVICEUNAVAILABLE.toString());
562 if (!sm.getNodes().contains(node)) {
563 throw new ResourceNotFoundException(node.toString() + " : "
564 + RestMessages.NONODE.toString());