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