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