Bug 500: Updated data APIs with new concepts.
[controller.git] / opendaylight / web / devices / src / main / java / org / opendaylight / controller / devices / web / Devices.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.devices.web;
10
11 import java.lang.reflect.Type;
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.Iterator;
15 import java.util.LinkedList;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Map.Entry;
19 import java.util.Set;
20 import java.util.TreeMap;
21 import java.util.concurrent.ConcurrentMap;
22
23 import javax.servlet.http.HttpServletRequest;
24 import javax.servlet.http.HttpServletResponse;
25
26 import org.opendaylight.controller.connectionmanager.IConnectionManager;
27 import org.opendaylight.controller.forwarding.staticrouting.IForwardingStaticRouting;
28 import org.opendaylight.controller.forwarding.staticrouting.StaticRouteConfig;
29 import org.opendaylight.controller.sal.authorization.Privilege;
30 import org.opendaylight.controller.sal.authorization.UserLevel;
31 import org.opendaylight.controller.sal.connection.ConnectionConstants;
32 import org.opendaylight.controller.sal.core.Config;
33 import org.opendaylight.controller.sal.core.Description;
34 import org.opendaylight.controller.sal.core.ForwardingMode;
35 import org.opendaylight.controller.sal.core.Name;
36 import org.opendaylight.controller.sal.core.Node;
37 import org.opendaylight.controller.sal.core.NodeConnector;
38 import org.opendaylight.controller.sal.core.Property;
39 import org.opendaylight.controller.sal.core.State;
40 import org.opendaylight.controller.sal.core.Tier;
41 import org.opendaylight.controller.sal.utils.GlobalConstants;
42 import org.opendaylight.controller.sal.utils.HexEncode;
43 import org.opendaylight.controller.sal.utils.NetUtils;
44 import org.opendaylight.controller.sal.utils.ServiceHelper;
45 import org.opendaylight.controller.sal.utils.Status;
46 import org.opendaylight.controller.sal.utils.StatusCode;
47 import org.opendaylight.controller.sal.utils.TierHelper;
48 import org.opendaylight.controller.switchmanager.ISwitchManager;
49 import org.opendaylight.controller.switchmanager.SpanConfig;
50 import org.opendaylight.controller.switchmanager.SubnetConfig;
51 import org.opendaylight.controller.switchmanager.Switch;
52 import org.opendaylight.controller.switchmanager.SwitchConfig;
53 import org.opendaylight.controller.web.DaylightWebUtil;
54 import org.opendaylight.controller.web.IDaylightWeb;
55 import org.springframework.stereotype.Controller;
56 import org.springframework.web.bind.annotation.PathVariable;
57 import org.springframework.web.bind.annotation.RequestMapping;
58 import org.springframework.web.bind.annotation.RequestMethod;
59 import org.springframework.web.bind.annotation.RequestParam;
60 import org.springframework.web.bind.annotation.ResponseBody;
61
62 import com.fasterxml.jackson.databind.ObjectMapper;
63 import com.google.gson.Gson;
64 import com.google.gson.reflect.TypeToken;
65
66 @Controller
67 @RequestMapping("/")
68 public class Devices implements IDaylightWeb {
69     private static final UserLevel AUTH_LEVEL = UserLevel.CONTAINERUSER;
70     private static final String WEB_NAME = "Devices";
71     private static final String WEB_ID = "devices";
72     private static final short WEB_ORDER = 1;
73
74     public Devices() {
75         ServiceHelper.registerGlobalService(IDaylightWeb.class, this, null);
76     }
77
78     @Override
79     public String getWebName() {
80         return WEB_NAME;
81     }
82
83     @Override
84     public String getWebId() {
85         return WEB_ID;
86     }
87
88     @Override
89     public short getWebOrder() {
90         return WEB_ORDER;
91     }
92
93     @Override
94     public boolean isAuthorized(UserLevel userLevel) {
95         return userLevel.ordinal() <= AUTH_LEVEL.ordinal();
96     }
97
98     @RequestMapping(value = "/nodesLearnt", method = RequestMethod.GET)
99     @ResponseBody
100     public DevicesJsonBean getNodesLearnt(HttpServletRequest request, @RequestParam(required = false) String container) {
101         Gson gson = new Gson();
102         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
103
104         // Derive the privilege this user has on the current container
105         String userName = request.getUserPrincipal().getName();
106         Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
107
108         ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
109                 this);
110         List<Map<String, String>> nodeData = new ArrayList<Map<String, String>>();
111         if (switchManager != null && privilege != Privilege.NONE) {
112             for (Switch device : switchManager.getNetworkDevices()) {
113                 HashMap<String, String> nodeDatum = new HashMap<String, String>();
114                 Node node = device.getNode();
115                 Tier tier = (Tier) switchManager.getNodeProp(node, Tier.TierPropName);
116                 nodeDatum.put("containerName", containerName);
117                 Description description = (Description) switchManager.getNodeProp(node, Description.propertyName);
118                 String desc = (description == null) ? "" : description.getValue();
119                 nodeDatum.put("nodeName", desc);
120                 nodeDatum.put("nodeId", node.toString());
121                 int tierNumber = (tier == null) ? TierHelper.unknownTierNumber : tier.getValue();
122                 nodeDatum.put("tierName", TierHelper.getTierName(tierNumber) + " (Tier-" + tierNumber + ")");
123                 nodeDatum.put("tier", tierNumber + "");
124                 String modeStr = "0";
125                 ForwardingMode mode = null;
126                 if (!containerName.equals(GlobalConstants.DEFAULT.toString())) {
127                     ISwitchManager switchManagerDefault = (ISwitchManager) ServiceHelper.getInstance(
128                             ISwitchManager.class, GlobalConstants.DEFAULT.toString(), this);
129                     mode = (ForwardingMode) switchManagerDefault.getNodeProp(node, ForwardingMode.name);
130                 } else {
131                     mode = (ForwardingMode) switchManager.getNodeProp(node, ForwardingMode.name);
132                 }
133                 if (mode != null) {
134                     modeStr = String.valueOf(mode.getValue());
135                 }
136                 nodeDatum.put("mode", modeStr);
137
138                 nodeDatum.put("json", gson.toJson(nodeDatum));
139                 nodeDatum.put("mac", HexEncode.bytesToHexStringFormat(device.getDataLayerAddress()));
140                 StringBuffer sb1 = new StringBuffer();
141                 Set<NodeConnector> nodeConnectorSet = device.getNodeConnectors();
142                 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
143                     Map<Short, String> portList = new HashMap<Short, String>();
144                     List<String> intfList = new ArrayList<String>();
145                     for (NodeConnector nodeConnector : nodeConnectorSet) {
146                         String nodeConnectorNumberToStr = nodeConnector.getID().toString();
147                         Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector, Name.NamePropName));
148                         Config portConfig = ((Config) switchManager.getNodeConnectorProp(nodeConnector,
149                                 Config.ConfigPropName));
150                         State portState = ((State) switchManager.getNodeConnectorProp(nodeConnector,
151                                 State.StatePropName));
152                         String nodeConnectorName = (ncName != null) ? ncName.getValue() : "";
153                         nodeConnectorName += " (" + nodeConnector.getID() + ")";
154
155                         if (portConfig != null) {
156                             if (portConfig.getValue() == Config.ADMIN_UP) {
157                                 if (portState != null && portState.getValue() == State.EDGE_UP) {
158                                     nodeConnectorName = "<span class='admin-up'>" + nodeConnectorName + "</span>";
159                                 } else if (portState == null || portState.getValue() == State.EDGE_DOWN) {
160                                     nodeConnectorName = "<span class='edge-down'>" + nodeConnectorName + "</span>";
161                                 }
162                             } else if (portConfig.getValue() == Config.ADMIN_DOWN) {
163                                 nodeConnectorName = "<span class='admin-down'>" + nodeConnectorName + "</span>";
164                             }
165                         }
166
167                         Class<?> idClass = nodeConnector.getID().getClass();
168                         if (idClass.equals(Short.class)) {
169                             portList.put(Short.parseShort(nodeConnectorNumberToStr), nodeConnectorName);
170                         } else {
171                             intfList.add(nodeConnectorName);
172                         }
173                     }
174
175                     if (portList.size() > 0) {
176                         Map<Short, String> sortedPortList = new TreeMap<Short, String>(portList);
177
178                         for (Entry<Short, String> e : sortedPortList.entrySet()) {
179                             sb1.append(e.getValue());
180                             sb1.append("<br>");
181                         }
182                     } else if (intfList.size() > 0) {
183                         for (String intf : intfList) {
184                             sb1.append(intf);
185                             sb1.append("<br>");
186                         }
187                     }
188                 }
189                 nodeDatum.put("ports", sb1.toString());
190                 nodeData.add(nodeDatum);
191             }
192         }
193
194         DevicesJsonBean result = new DevicesJsonBean();
195         result.setNodeData(nodeData);
196         result.setPrivilege(privilege);
197         List<String> columnNames = new ArrayList<String>();
198         columnNames.add("Node ID");
199         columnNames.add("Node Name");
200         columnNames.add("Tier");
201         columnNames.add("Mac Address");
202         columnNames.add("Ports");
203         columnNames.add("Port Status");
204
205         result.setColumnNames(columnNames);
206         return result;
207     }
208
209     @RequestMapping(value = "/tiers", method = RequestMethod.GET)
210     @ResponseBody
211     public List<String> getTiers() {
212         return TierHelper.getTiers();
213     }
214
215     @RequestMapping(value = "/nodesLearnt/update", method = RequestMethod.GET)
216     @ResponseBody
217     public StatusJsonBean updateLearntNode(@RequestParam("nodeName") String nodeName,
218             @RequestParam("nodeId") String nodeId, @RequestParam("tier") String tier,
219             @RequestParam("operationMode") String operationMode, HttpServletRequest request,
220             @RequestParam(required = false) String container) {
221         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
222
223         // Authorization check
224         String userName = request.getUserPrincipal().getName();
225         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
226             return unauthorizedMessage();
227         }
228
229         StatusJsonBean resultBean = new StatusJsonBean();
230         try {
231             ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
232                     containerName, this);
233             Map<String, Property> nodeProperties = new HashMap<String, Property>();
234             Property desc = new Description(nodeName);
235             nodeProperties.put(desc.getName(), desc);
236             Property nodeTier = new Tier(Integer.parseInt(tier));
237             nodeProperties.put(nodeTier.getName(), nodeTier);
238             if (containerName.equals(GlobalConstants.DEFAULT.toString())) {
239                 Property mode = new ForwardingMode(Integer.parseInt(operationMode));
240                 nodeProperties.put(mode.getName(), mode);
241             }
242             SwitchConfig cfg = new SwitchConfig(nodeId, nodeProperties);
243             Status result = switchManager.updateNodeConfig(cfg);
244             if (!result.isSuccess()) {
245                 resultBean.setStatus(false);
246                 resultBean.setMessage(result.getDescription());
247             } else {
248                 resultBean.setStatus(true);
249                 resultBean.setMessage("Updated node information successfully");
250                 DaylightWebUtil.auditlog("Property", userName, "updated",
251                         "of Node " + DaylightWebUtil.getNodeDesc(Node.fromString(nodeId), switchManager));
252             }
253         } catch (Exception e) {
254             resultBean.setStatus(false);
255             resultBean.setMessage("Error updating node information. " + e.getMessage());
256         }
257         return resultBean;
258     }
259
260     @RequestMapping(value = "/staticRoutes", method = RequestMethod.GET)
261     @ResponseBody
262     public DevicesJsonBean getStaticRoutes(HttpServletRequest request, @RequestParam(required = false) String container) {
263         Gson gson = new Gson();
264         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
265
266         // Derive the privilege this user has on the current container
267         String userName = request.getUserPrincipal().getName();
268         Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
269
270         IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper.getInstance(
271                 IForwardingStaticRouting.class, containerName, this);
272         if (staticRouting == null) {
273             return null;
274         }
275         List<Map<String, String>> staticRoutes = new ArrayList<Map<String, String>>();
276         ConcurrentMap<String, StaticRouteConfig> routeConfigs = staticRouting.getStaticRouteConfigs();
277         if (routeConfigs == null) {
278             return null;
279         }
280         if (privilege != Privilege.NONE) {
281             for (StaticRouteConfig conf : routeConfigs.values()) {
282                 Map<String, String> staticRoute = new HashMap<String, String>();
283                 staticRoute.put("name", conf.getName());
284                 staticRoute.put("staticRoute", conf.getStaticRoute());
285                 staticRoute.put("nextHopType", conf.getNextHopType());
286                 staticRoute.put("nextHop", conf.getNextHop());
287                 staticRoute.put("json", gson.toJson(conf));
288                 staticRoutes.add(staticRoute);
289             }
290         }
291         DevicesJsonBean result = new DevicesJsonBean();
292         result.setPrivilege(privilege);
293         result.setColumnNames(StaticRouteConfig.getGuiFieldsNames());
294         result.setNodeData(staticRoutes);
295         return result;
296     }
297
298     @RequestMapping(value = "/staticRoute/add", method = RequestMethod.GET)
299     @ResponseBody
300     public StatusJsonBean addStaticRoute(@RequestParam("routeName") String routeName,
301             @RequestParam("staticRoute") String staticRoute, @RequestParam("nextHop") String nextHop,
302             HttpServletRequest request, @RequestParam(required = false) String container) {
303         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
304
305         // Authorization check
306         String userName = request.getUserPrincipal().getName();
307         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
308             return unauthorizedMessage();
309         }
310
311         StatusJsonBean result = new StatusJsonBean();
312         try {
313             IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper.getInstance(
314                     IForwardingStaticRouting.class, containerName, this);
315             StaticRouteConfig config = new StaticRouteConfig();
316             config.setName(routeName);
317             config.setStaticRoute(staticRoute);
318             config.setNextHop(nextHop);
319             Status addStaticRouteResult = staticRouting.addStaticRoute(config);
320             if (addStaticRouteResult.isSuccess()) {
321                 result.setStatus(true);
322                 result.setMessage("Static Route saved successfully");
323                 DaylightWebUtil.auditlog("Static Route", userName, "added", routeName, containerName);
324             } else {
325                 result.setStatus(false);
326                 result.setMessage(addStaticRouteResult.getDescription());
327             }
328         } catch (Exception e) {
329             result.setStatus(false);
330             result.setMessage("Error - " + e.getMessage());
331         }
332         return result;
333     }
334
335     @RequestMapping(value = "/staticRoute/delete", method = RequestMethod.GET)
336     @ResponseBody
337     public StatusJsonBean deleteStaticRoute(@RequestParam("routesToDelete") String routesToDelete,
338             HttpServletRequest request, @RequestParam(required = false) String container) {
339         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
340
341         // Authorization check
342         String userName = request.getUserPrincipal().getName();
343         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
344             return unauthorizedMessage();
345         }
346
347         StatusJsonBean resultBean = new StatusJsonBean();
348         try {
349             IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper.getInstance(
350                     IForwardingStaticRouting.class, containerName, this);
351             String[] routes = routesToDelete.split(",");
352             Status result;
353             resultBean.setStatus(true);
354             resultBean.setMessage("Successfully deleted selected static routes");
355             for (String route : routes) {
356                 result = staticRouting.removeStaticRoute(route);
357                 if (!result.isSuccess()) {
358                     resultBean.setStatus(false);
359                     resultBean.setMessage(result.getDescription());
360                     break;
361                 }
362                 DaylightWebUtil.auditlog("Static Route", userName, "removed", route, containerName);
363             }
364         } catch (Exception e) {
365             resultBean.setStatus(false);
366             resultBean.setMessage("Error occurred while deleting static routes. " + e.getMessage());
367         }
368         return resultBean;
369     }
370
371     @RequestMapping(value = "/subnets", method = RequestMethod.GET)
372     @ResponseBody
373     public DevicesJsonBean getSubnetGateways(HttpServletRequest request,
374             @RequestParam(required = false) String container) {
375         Gson gson = new Gson();
376         List<Map<String, String>> subnets = new ArrayList<Map<String, String>>();
377         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
378
379         // Derive the privilege this user has on the current container
380         String userName = request.getUserPrincipal().getName();
381         Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
382
383         if (privilege != Privilege.NONE) {
384             ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
385                     containerName, this);
386             if (switchManager != null) {
387                 for (SubnetConfig conf : switchManager.getSubnetsConfigList()) {
388                     Map<String, String> subnet = new HashMap<String, String>();
389                     subnet.put("name", conf.getName());
390                     subnet.put("subnet", conf.getSubnet());
391                     List<SubnetGatewayPortBean> portsList = new ArrayList<SubnetGatewayPortBean>();
392                     Iterator<NodeConnector> itor = conf.getNodeConnectors().iterator();
393                     while (itor.hasNext()) {
394                         SubnetGatewayPortBean bean = new SubnetGatewayPortBean();
395                         NodeConnector nodeConnector = itor.next();
396                         String nodeName = getNodeDesc(nodeConnector.getNode().toString(), containerName);
397                         Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector, Name.NamePropName));
398                         String nodeConnectorName = (ncName != null) ? ncName.getValue() : "";
399                         bean.setNodeName(nodeName);
400                         bean.setNodePortName(nodeConnectorName);
401                         bean.setNodeId(nodeConnector.getNode().toString());
402                         bean.setNodePortId(nodeConnector.toString());
403                         portsList.add(bean);
404                     }
405                     subnet.put("nodePorts", gson.toJson(portsList));
406                     subnets.add(subnet);
407                 }
408             }
409         }
410         DevicesJsonBean result = new DevicesJsonBean();
411         result.setPrivilege(privilege);
412         result.setColumnNames(SubnetConfig.getGuiFieldsNames());
413         result.setNodeData(subnets);
414         return result;
415     }
416
417     @RequestMapping(value = "/subnetGateway/add", method = RequestMethod.GET)
418     @ResponseBody
419     public StatusJsonBean addSubnetGateways(@RequestParam("gatewayName") String gatewayName,
420             @RequestParam("gatewayIPAddress") String gatewayIPAddress, HttpServletRequest request,
421             @RequestParam(required = false) String container) {
422         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
423
424         // Authorization check
425         String userName = request.getUserPrincipal().getName();
426         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
427             return unauthorizedMessage();
428         }
429
430         StatusJsonBean resultBean = new StatusJsonBean();
431         try {
432             ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
433                     containerName, this);
434             SubnetConfig cfgObject = new SubnetConfig(gatewayName, gatewayIPAddress, new ArrayList<String>());
435             Status result = switchManager.addSubnet(cfgObject);
436             if (result.isSuccess()) {
437                 resultBean.setStatus(true);
438                 resultBean.setMessage("Added gateway address successfully");
439                 DaylightWebUtil.auditlog("Subnet Gateway", userName, "added", gatewayName, containerName);
440             } else {
441                 resultBean.setStatus(false);
442                 resultBean.setMessage(result.getDescription());
443             }
444         } catch (Exception e) {
445             resultBean.setStatus(false);
446             resultBean.setMessage(e.getMessage());
447         }
448         return resultBean;
449     }
450
451     @RequestMapping(value = "/subnetGateway/delete", method = RequestMethod.GET)
452     @ResponseBody
453     public StatusJsonBean deleteSubnetGateways(@RequestParam("gatewaysToDelete") String gatewaysToDelete,
454             HttpServletRequest request, @RequestParam(required = false) String container) {
455         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
456
457         // Authorization check
458         String userName = request.getUserPrincipal().getName();
459         if (DaylightWebUtil.getContainerPrivilege(userName, container, this) != Privilege.WRITE) {
460             return unauthorizedMessage();
461         }
462
463         StatusJsonBean resultBean = new StatusJsonBean();
464         try {
465             ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
466                     containerName, this);
467             String[] subnets = gatewaysToDelete.split(",");
468             resultBean.setStatus(true);
469             resultBean.setMessage("Added gateway address successfully");
470             for (String subnet : subnets) {
471                 Status result = switchManager.removeSubnet(subnet);
472                 if (!result.isSuccess()) {
473                     resultBean.setStatus(false);
474                     resultBean.setMessage(result.getDescription());
475                     break;
476                 }
477                 DaylightWebUtil.auditlog("Subnet Gateway", userName, "removed", subnet, containerName);
478             }
479         } catch (Exception e) {
480             resultBean.setStatus(false);
481             resultBean.setMessage(e.getMessage());
482         }
483         return resultBean;
484     }
485
486     @RequestMapping(value = "/subnetGateway/ports/add", method = RequestMethod.GET)
487     @ResponseBody
488     public StatusJsonBean addSubnetGatewayPort(@RequestParam("portsName") String portsName,
489             @RequestParam("ports") String ports, @RequestParam("nodeId") String nodeId, HttpServletRequest request,
490             @RequestParam(required = false) String container) {
491         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
492
493         // Authorization check
494         String userName = request.getUserPrincipal().getName();
495         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
496             return unauthorizedMessage();
497         }
498
499         StatusJsonBean resultBean = new StatusJsonBean();
500         try {
501             ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
502                     containerName, this);
503             List<String> toAdd = new ArrayList<String>();
504             for (String port : ports.split(",")) {
505                 toAdd.add(port);
506             }
507             Status result = switchManager.addPortsToSubnet(portsName, toAdd);
508
509             if (result.isSuccess()) {
510                 resultBean.setStatus(true);
511                 resultBean.setMessage("Added ports to subnet gateway address successfully");
512                 for (String port : toAdd) {
513                     DaylightWebUtil.auditlog("Port", userName, "added",
514                             DaylightWebUtil.getPortName(NodeConnector.fromString(port), switchManager)
515                             + " to Subnet Gateway " + portsName, containerName);
516                 }
517             } else {
518                 resultBean.setStatus(false);
519                 resultBean.setMessage(result.getDescription());
520             }
521         } catch (Exception e) {
522             resultBean.setStatus(false);
523             resultBean.setMessage(e.getMessage());
524         }
525         return resultBean;
526     }
527
528     @RequestMapping(value = "/subnetGateway/ports/delete", method = RequestMethod.GET)
529     @ResponseBody
530     public StatusJsonBean deleteSubnetGatewayPort(@RequestParam("gatewayName") String gatewayName,
531             @RequestParam("nodePort") String nodePort, HttpServletRequest request,
532             @RequestParam(required = false) String container) {
533         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
534
535         // Authorization check
536         String userName = request.getUserPrincipal().getName();
537         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
538             return unauthorizedMessage();
539         }
540
541         StatusJsonBean resultBean = new StatusJsonBean();
542         try {
543             ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
544                     containerName, this);
545             List<String> toRemove = new ArrayList<String>();
546             for (String port : nodePort.split(",")) {
547                 toRemove.add(port);
548             }
549             Status result = switchManager.removePortsFromSubnet(gatewayName, toRemove);
550
551             if (result.isSuccess()) {
552                 resultBean.setStatus(true);
553                 resultBean.setMessage("Deleted port from subnet gateway address successfully");
554                 for (String port : toRemove) {
555                     DaylightWebUtil.auditlog("Port", userName, "removed",
556                             DaylightWebUtil.getPortName(NodeConnector.fromString(port), switchManager)
557                             + " from Subnet Gateway " + gatewayName, containerName);
558                 }
559             } else {
560                 resultBean.setStatus(false);
561                 resultBean.setMessage(result.getDescription());
562             }
563         } catch (Exception e) {
564             resultBean.setStatus(false);
565             resultBean.setMessage(e.getMessage());
566         }
567         return resultBean;
568     }
569
570     @RequestMapping(value = "/spanPorts", method = RequestMethod.GET)
571     @ResponseBody
572     public DevicesJsonBean getSpanPorts(HttpServletRequest request, @RequestParam(required = false) String container) {
573         Gson gson = new Gson();
574         List<Map<String, String>> spanConfigs = new ArrayList<Map<String, String>>();
575         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
576
577         // Derive the privilege this user has on the current container
578         String userName = request.getUserPrincipal().getName();
579         Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
580
581         if (privilege != Privilege.NONE) {
582             List<String> spanConfigs_json = new ArrayList<String>();
583             ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
584                     containerName, this);
585             if (switchManager != null) {
586                 for (SpanConfig conf : switchManager.getSpanConfigList()) {
587                     spanConfigs_json.add(gson.toJson(conf));
588                 }
589             }
590             ObjectMapper mapper = new ObjectMapper();
591
592             for (String config_json : spanConfigs_json) {
593                 try {
594                     @SuppressWarnings("unchecked")
595                     Map<String, String> config_data = mapper.readValue(config_json, HashMap.class);
596                     Map<String, String> config = new HashMap<String, String>();
597                     for (String name : config_data.keySet()) {
598                         config.put(name, config_data.get(name));
599                         // Add switch portName value (non-configuration field)
600                         config.put("nodeName", getNodeDesc(config_data.get("nodeId"), containerName));
601                         NodeConnector spanPortNodeConnector = NodeConnector.fromString(config_data.get("spanPort"));
602                         Name ncName = ((Name) switchManager.getNodeConnectorProp(spanPortNodeConnector,
603                                 Name.NamePropName));
604                         String spanPortName = (ncName != null) ? ncName.getValue() : "";
605                         config.put("spanPortName", spanPortName);
606                     }
607                     config.put("json", config_json);
608                     spanConfigs.add(config);
609                 } catch (Exception e) {
610                     // TODO: Handle the exception.
611                 }
612             }
613         }
614
615         DevicesJsonBean result = new DevicesJsonBean();
616         result.setPrivilege(privilege);
617         result.setColumnNames(SpanConfig.getGuiFieldsNames());
618         result.setNodeData(spanConfigs);
619         return result;
620     }
621
622     @RequestMapping(value = "/nodeports")
623     @ResponseBody
624     public String getNodePorts(HttpServletRequest request, @RequestParam(required = false) String container) {
625         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
626
627         // Derive the privilege this user has on the current container
628         String userName = request.getUserPrincipal().getName();
629         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
630             return null;
631         }
632
633         ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
634                 this);
635         if (switchManager == null) {
636             return null;
637         }
638         List<NodeJsonBean> nodeJsonBeans = new ArrayList<NodeJsonBean>();
639
640         for (Switch node : switchManager.getNetworkDevices()) {
641             NodeJsonBean nodeJsonBean = new NodeJsonBean();
642             List<PortJsonBean> port = new ArrayList<PortJsonBean>();
643             Set<NodeConnector> nodeConnectorSet = node.getNodeConnectors();
644             if (nodeConnectorSet != null) {
645                 for (NodeConnector nodeConnector : nodeConnectorSet) {
646                     String nodeConnectorName = ((Name) switchManager.getNodeConnectorProp(nodeConnector,
647                             Name.NamePropName)).getValue();
648                     port.add(new PortJsonBean(nodeConnector.getID().toString(), nodeConnectorName, nodeConnector
649                             .toString()));
650                 }
651             }
652             nodeJsonBean.setNodeId(node.getNode().toString());
653             nodeJsonBean.setNodeName(getNodeDesc(node.getNode().toString(), containerName));
654             nodeJsonBean.setNodePorts(port);
655             nodeJsonBeans.add(nodeJsonBean);
656         }
657
658         return new Gson().toJson(nodeJsonBeans);
659     }
660
661     @RequestMapping(value = "/spanPorts/add", method = RequestMethod.GET)
662     @ResponseBody
663     public StatusJsonBean addSpanPort(@RequestParam("jsonData") String jsonData, HttpServletRequest request,
664             @RequestParam(required = false) String container) {
665         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
666
667         // Authorization check
668         String userName = request.getUserPrincipal().getName();
669         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
670             return unauthorizedMessage();
671         }
672
673         StatusJsonBean resultBean = new StatusJsonBean();
674         try {
675             Gson gson = new Gson();
676             ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
677                     containerName, this);
678             SpanConfig cfgObject = gson.fromJson(jsonData, SpanConfig.class);
679             Status result = switchManager.addSpanConfig(cfgObject);
680             if (result.isSuccess()) {
681                 resultBean.setStatus(true);
682                 resultBean.setMessage("SPAN Port added successfully");
683                 DaylightWebUtil.auditlog("SPAN Port", userName, "added",
684                         DaylightWebUtil.getPortName(NodeConnector.fromString(cfgObject.getSpanPort()), switchManager),
685                         containerName);
686             } else {
687                 resultBean.setStatus(false);
688                 resultBean.setMessage(result.getDescription());
689             }
690         } catch (Exception e) {
691             resultBean.setStatus(false);
692             resultBean.setMessage("Error occurred while adding span port. " + e.getMessage());
693         }
694         return resultBean;
695     }
696
697     @RequestMapping(value = "/spanPorts/delete", method = RequestMethod.GET)
698     @ResponseBody
699     public StatusJsonBean deleteSpanPorts(@RequestParam("spanPortsToDelete") String spanPortsToDelete,
700             HttpServletRequest request, @RequestParam(required = false) String container) {
701         String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
702
703         // Authorization check
704         String userName = request.getUserPrincipal().getName();
705         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
706             return unauthorizedMessage();
707         }
708
709         StatusJsonBean resultBean = new StatusJsonBean();
710         try {
711             Gson gson = new Gson();
712             ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
713                     containerName, this);
714             Type collectionType = new TypeToken<List<SpanPortJsonBean>>() {
715             }.getType();
716             List<SpanPortJsonBean> jsonBeanList = gson.fromJson(spanPortsToDelete, collectionType);
717             for (SpanPortJsonBean jsonBean : jsonBeanList) {
718                 SpanConfig cfgObject = gson.fromJson(gson.toJson(jsonBean), SpanConfig.class);
719                 Status result = switchManager.removeSpanConfig(cfgObject);
720                 if (!result.isSuccess()) {
721                     resultBean.setStatus(false);
722                     resultBean.setMessage(result.getDescription());
723                     break;
724                 }
725                 DaylightWebUtil.auditlog("SPAN Port", userName, "removed",
726                         DaylightWebUtil.getPortName(NodeConnector.fromString(cfgObject.getSpanPort()), switchManager),
727                         containerName);
728             }
729             resultBean.setStatus(true);
730             resultBean.setMessage("SPAN Port(s) deleted successfully");
731         } catch (Exception e) {
732             resultBean.setStatus(false);
733             resultBean.setMessage("Error occurred while deleting span port. " + e.getMessage());
734         }
735         return resultBean;
736     }
737
738     @RequestMapping(value = "/connect/nodes", method = RequestMethod.GET)
739     @ResponseBody
740     public List<NodeJsonBean> getNodes(HttpServletRequest request) {
741         IConnectionManager connectionManager = (IConnectionManager) ServiceHelper.getGlobalInstance(
742                 IConnectionManager.class, this);
743         if (connectionManager == null) {
744             return null;
745         }
746         ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
747                 GlobalConstants.DEFAULT.toString(), this);
748         if (switchManager == null) {
749             return null;
750         }
751
752         Set<Node> nodes = connectionManager.getLocalNodes();
753         List<NodeJsonBean> result = new LinkedList<NodeJsonBean>();
754         if (nodes == null) {
755             return result;
756         }
757         for (Node node : nodes) {
758             Description descriptionProperty = (Description) switchManager.getNodeProp(node, "description");
759             String description = node.toString();
760             if (descriptionProperty != null) {
761                 description = descriptionProperty.getValue();
762             }
763             NodeJsonBean nodeBean = new NodeJsonBean();
764             nodeBean.setNodeId(node.getNodeIDString());
765             nodeBean.setNodeType(node.getType());
766             if (description.equals("None")) {
767                 nodeBean.setNodeName(node.toString());
768             } else {
769                 nodeBean.setNodeName(description);
770             }
771             result.add(nodeBean);
772         }
773
774         return result;
775     }
776
777     @RequestMapping(value = "/connect/{nodeId}", method = RequestMethod.POST)
778     @ResponseBody
779     public Status addNode(HttpServletRequest request, @PathVariable("nodeId") String nodeId,
780             @RequestParam(required = true) String ipAddress, @RequestParam(required = true) String port,
781             @RequestParam(required = false) String nodeType) {
782         IConnectionManager connectionManager = (IConnectionManager) ServiceHelper.getGlobalInstance(
783                 IConnectionManager.class, this);
784         if (connectionManager == null) {
785             return new Status(StatusCode.NOTFOUND, "Service not found");
786         }
787
788         if (!NetUtils.isIPv4AddressValid(ipAddress)) {
789             return new Status(StatusCode.NOTACCEPTABLE, "Invalid IP Address: " + ipAddress);
790         }
791
792         try {
793             Integer.parseInt(port);
794         } catch (Exception e) {
795             return new Status(StatusCode.NOTACCEPTABLE, "Invalid Layer 4 Port: " + port);
796         }
797
798         Map<ConnectionConstants, String> params = new HashMap<ConnectionConstants, String>();
799         params.put(ConnectionConstants.ADDRESS, ipAddress);
800         params.put(ConnectionConstants.PORT, port);
801
802         Node node = null;
803         if (nodeType != null) {
804             node = connectionManager.connect(nodeType, nodeId, params);
805         } else {
806             node = connectionManager.connect(nodeId, params);
807         }
808         if (node == null) {
809             return new Status(StatusCode.NOTFOUND, "Failed to connect to Node at " + ipAddress + ":" + port);
810         }
811         return new Status(StatusCode.SUCCESS);
812     }
813
814     @RequestMapping(value = "/disconnect/{nodeId}", method = RequestMethod.POST)
815     @ResponseBody
816     public Status removeNode(HttpServletRequest request, @PathVariable("nodeId") String nodeId,
817             @RequestParam(required = true) String nodeType) {
818         IConnectionManager connectionManager = (IConnectionManager) ServiceHelper.getGlobalInstance(
819                 IConnectionManager.class, this);
820         if (connectionManager == null) {
821             return new Status(StatusCode.NOTFOUND, "Service not found");
822         }
823
824         try {
825             Node node = new Node(nodeType, nodeId);
826             return connectionManager.disconnect(node);
827         } catch (Exception e) {
828             return new Status(StatusCode.NOTFOUND, "Resource not found");
829         }
830     }
831
832     private String getNodeDesc(String nodeId, String containerName) {
833         ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
834                 this);
835         String description = "";
836         if (switchManager != null) {
837             Description desc = (Description) switchManager.getNodeProp(Node.fromString(nodeId),
838                     Description.propertyName);
839             if (desc != null) {
840                 description = desc.getValue();
841             }
842         }
843         return (description.isEmpty() || description.equalsIgnoreCase("none")) ? nodeId : description;
844     }
845
846     private StatusJsonBean unauthorizedMessage() {
847         StatusJsonBean message = new StatusJsonBean();
848         message.setStatus(false);
849         message.setMessage("Operation not authorized");
850         return message;
851     }
852
853     @RequestMapping(value = "login")
854     public String login(final HttpServletRequest request, final HttpServletResponse response) {
855         /*
856          * IUserManager userManager = (IUserManager) ServiceHelper
857          * .getGlobalInstance(IUserManager.class, this); if (userManager ==
858          * null) { return "User Manager is not available"; }
859          *
860          * String username = request.getUserPrincipal().getName();
861          *
862          *
863          * model.addAttribute("username", username); model.addAttribute("role",
864          * userManager.getUserLevel(username).toNumber());
865          */
866         return "forward:" + "/";
867     }
868
869 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.