Search in sources :

Example 56 with ExecutionException

use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.

the class PaloAltoResource method request.

/*
     * XML API commands
     */
/* Function to make calls to the Palo Alto API. */
/* All API calls will end up going through this function. */
protected String request(PaloAltoMethod method, Map<String, String> params) throws ExecutionException {
    if (method != PaloAltoMethod.GET && method != PaloAltoMethod.POST) {
        throw new ExecutionException("Invalid http method used to access the Palo Alto API.");
    }
    String responseBody = "";
    String debug_msg = "Palo Alto Request\n";
    // a GET method...
    if (method == PaloAltoMethod.GET) {
        String queryString = "?";
        for (String key : params.keySet()) {
            if (!queryString.equals("?")) {
                queryString = queryString + "&";
            }
            try {
                queryString = queryString + key + "=" + URLEncoder.encode(params.get(key), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new ExecutionException(e.getMessage());
            }
        }
        if (_key != null) {
            queryString = queryString + "&key=" + _key;
        }
        try {
            debug_msg = debug_msg + "GET request: https://" + _ip + s_apiUri + URLDecoder.decode(queryString, "UTF-8") + "\n";
        } catch (UnsupportedEncodingException e) {
            debug_msg = debug_msg + "GET request: https://" + _ip + s_apiUri + queryString + "\n";
        }
        HttpGet get_request = new HttpGet("https://" + _ip + s_apiUri + queryString);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            responseBody = s_httpclient.execute(get_request, responseHandler);
        } catch (IOException e) {
            throw new ExecutionException(e.getMessage());
        }
    }
    // a POST method...
    if (method == PaloAltoMethod.POST) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }
        if (_key != null) {
            nvps.add(new BasicNameValuePair("key", _key));
        }
        debug_msg = debug_msg + "POST request: https://" + _ip + s_apiUri + "\n";
        for (NameValuePair nvp : nvps) {
            debug_msg = debug_msg + "param: " + nvp.getName() + ", " + nvp.getValue() + "\n";
        }
        HttpPost post_request = new HttpPost("https://" + _ip + s_apiUri);
        try {
            post_request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            throw new ExecutionException(e.getMessage());
        }
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            responseBody = s_httpclient.execute(post_request, responseHandler);
        } catch (IOException e) {
            throw new ExecutionException(e.getMessage());
        }
    }
    debug_msg = debug_msg + prettyFormat(responseBody);
    // test cases
    debug_msg = debug_msg + "\n" + responseBody.replace("\"", "\\\"") + "\n\n";
    return responseBody;
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) HttpGet(org.apache.http.client.methods.HttpGet) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 57 with ExecutionException

use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.

the class PaloAltoResource method execute.

private Answer execute(SetPortForwardingRulesCommand cmd, int numRetries) {
    PortForwardingRuleTO[] rules = cmd.getRules();
    try {
        ArrayList<IPaloAltoCommand> commandList = new ArrayList<IPaloAltoCommand>();
        for (PortForwardingRuleTO rule : rules) {
            if (!rule.revoked()) {
                manageDstNatRule(commandList, PaloAltoPrimative.ADD, rule);
            } else {
                manageDstNatRule(commandList, PaloAltoPrimative.DELETE, rule);
            }
        }
        boolean status = requestWithCommit(commandList);
        return new Answer(cmd);
    } catch (ExecutionException e) {
        s_logger.error(e);
        if (numRetries > 0 && refreshPaloAltoConnection()) {
            int numRetriesRemaining = numRetries - 1;
            s_logger.debug("Retrying SetPortForwardingRulesCommand. Number of retries remaining: " + numRetriesRemaining);
            return execute(cmd, numRetriesRemaining);
        } else {
            return new Answer(cmd, e);
        }
    }
}
Also used : Answer(com.cloud.agent.api.Answer) MaintainAnswer(com.cloud.agent.api.MaintainAnswer) IpAssocAnswer(com.cloud.agent.api.routing.IpAssocAnswer) ReadyAnswer(com.cloud.agent.api.ReadyAnswer) ExternalNetworkResourceUsageAnswer(com.cloud.agent.api.ExternalNetworkResourceUsageAnswer) PortForwardingRuleTO(com.cloud.agent.api.to.PortForwardingRuleTO) ArrayList(java.util.ArrayList) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 58 with ExecutionException

use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.

the class PaloAltoResource method manageFirewallRule.

public boolean manageFirewallRule(ArrayList<IPaloAltoCommand> cmdList, PaloAltoPrimative prim, FirewallRuleTO rule) throws ExecutionException {
    String ruleName;
    if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
        ruleName = genFirewallRuleName(rule.getId(), rule.getSrcVlanTag());
    } else {
        ruleName = genFirewallRuleName(rule.getId());
    }
    switch(prim) {
        case CHECK_IF_EXISTS:
            // check if one exists already
            Map<String, String> params = new HashMap<String, String>();
            params.put("type", "config");
            params.put("action", "get");
            params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='" + ruleName + "']");
            String response = request(PaloAltoMethod.GET, params);
            boolean result = (validResponse(response) && responseNotEmpty(response));
            s_logger.debug("Firewall policy exists: " + ruleName + ", " + result);
            return result;
        case ADD:
            if (manageFirewallRule(cmdList, PaloAltoPrimative.CHECK_IF_EXISTS, rule)) {
                return true;
            }
            String srcZone;
            String dstZone;
            String dstAddressXML;
            String appXML;
            String serviceXML;
            String protocol = rule.getProtocol();
            String action = "allow";
            // Only ICMP will use an Application, so others will be any.
            if (protocol.equals(Protocol.ICMP.toString())) {
                // use the default icmp applications...
                appXML = "<member>icmp</member><member>ping</member><member>traceroute</member>";
            } else {
                appXML = "<member>any</member>";
            }
            // Only TCP and UDP will use a Service, others will use any.
            if (protocol.equals(Protocol.TCP.toString()) || protocol.equals(Protocol.UDP.toString())) {
                String portRange;
                if (rule.getSrcPortRange() != null) {
                    int startPort = rule.getSrcPortRange()[0];
                    int endPort = rule.getSrcPortRange()[1];
                    if (startPort == endPort) {
                        portRange = String.valueOf(startPort);
                    } else {
                        portRange = String.valueOf(startPort) + "-" + String.valueOf(endPort);
                    }
                    manageService(cmdList, PaloAltoPrimative.ADD, protocol, portRange, null);
                    serviceXML = "<member>" + genServiceName(protocol, portRange, null) + "</member>";
                } else {
                    // no equivalent config in PA, so allow all traffic...
                    serviceXML = "<member>any</member>";
                }
            } else {
                serviceXML = "<member>any</member>";
            }
            // handle different types of fire wall rules (egress | ingress)
            if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                // Egress Rule
                srcZone = _privateZone;
                dstZone = _publicZone;
                dstAddressXML = "<member>any</member>";
                // defaults to 'allow', the deny rules are as follows
                if (rule.getType() == FirewallRule.FirewallRuleType.System) {
                    if (!rule.isDefaultEgressPolicy()) {
                        // default of deny && system rule, so deny
                        action = "deny";
                    }
                } else {
                    if (rule.isDefaultEgressPolicy()) {
                        // default is allow && user rule, so deny
                        action = "deny";
                    }
                }
            } else {
                // Ingress Rule
                srcZone = _publicZone;
                dstZone = _privateZone;
                dstAddressXML = "<member>" + rule.getSrcIp() + "</member>";
            }
            // build the source cidr xml
            String srcCidrXML = "";
            List<String> ruleSrcCidrList = rule.getSourceCidrList();
            if (ruleSrcCidrList.size() > 0) {
                // a cidr was entered, modify as needed...
                for (int i = 0; i < ruleSrcCidrList.size(); i++) {
                    if (ruleSrcCidrList.get(i).trim().equals("0.0.0.0/0")) {
                        // allow any
                        if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                            srcCidrXML += "<member>" + getPrivateSubnet(rule.getSrcVlanTag()) + "</member>";
                        } else {
                            srcCidrXML += "<member>any</member>";
                        }
                    } else {
                        srcCidrXML += "<member>" + ruleSrcCidrList.get(i).trim() + "</member>";
                    }
                }
            } else {
                // no cidr was entered, so allow ALL according to firewall rule type
                if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                    srcCidrXML = "<member>" + getPrivateSubnet(rule.getSrcVlanTag()) + "</member>";
                } else {
                    srcCidrXML = "<member>any</member>";
                }
            }
            // build new rule xml
            String xml = "";
            xml += "<from><member>" + srcZone + "</member></from>";
            xml += "<to><member>" + dstZone + "</member></to>";
            xml += "<source>" + srcCidrXML + "</source>";
            xml += "<destination>" + dstAddressXML + "</destination>";
            xml += "<application>" + appXML + "</application>";
            xml += "<service>" + serviceXML + "</service>";
            xml += "<action>" + action + "</action>";
            xml += "<negate-source>no</negate-source>";
            xml += "<negate-destination>no</negate-destination>";
            if (_threatProfile != null && action.equals("allow")) {
                // add the threat profile if it exists
                xml += "<profile-setting><group><member>" + _threatProfile + "</member></group></profile-setting>";
            }
            if (_logProfile != null && action.equals("allow")) {
                // add the log profile if it exists
                xml += "<log-setting>" + _logProfile + "</log-setting>";
            }
            boolean has_default = false;
            String defaultEgressRule = "";
            if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                // check if a default egress rule exists because it always has to be after the other rules.
                Map<String, String> e_params = new HashMap<String, String>();
                e_params.put("type", "config");
                e_params.put("action", "get");
                e_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_" + rule.getSrcVlanTag() + "']");
                String e_response = request(PaloAltoMethod.GET, e_params);
                has_default = (validResponse(e_response) && responseNotEmpty(e_response));
                // there is an existing default rule, so we need to remove it and add it back after the new rule is added.
                if (has_default) {
                    s_logger.debug("Moving the default egress rule after the new rule: " + ruleName);
                    NodeList response_body;
                    Document doc = getDocument(e_response);
                    XPath xpath = XPathFactory.newInstance().newXPath();
                    try {
                        XPathExpression expr = xpath.compile("/response[@status='success']/result/entry/node()");
                        response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                    } catch (XPathExpressionException e) {
                        throw new ExecutionException(e.getCause().getMessage());
                    }
                    for (int i = 0; i < response_body.getLength(); i++) {
                        Node n = response_body.item(i);
                        defaultEgressRule += nodeToString(n);
                    }
                    Map<String, String> dd_params = new HashMap<String, String>();
                    dd_params.put("type", "config");
                    dd_params.put("action", "delete");
                    dd_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_" + rule.getSrcVlanTag() + "']");
                    cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, dd_params));
                }
            }
            // add the new rule...
            Map<String, String> a_params = new HashMap<String, String>();
            a_params.put("type", "config");
            a_params.put("action", "set");
            a_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='" + ruleName + "']");
            a_params.put("element", xml);
            cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, a_params));
            // add back the default rule
            if (rule.getTrafficType() == FirewallRule.TrafficType.Egress && has_default) {
                Map<String, String> da_params = new HashMap<String, String>();
                da_params.put("type", "config");
                da_params.put("action", "set");
                da_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='policy_0_" + rule.getSrcVlanTag() + "']");
                da_params.put("element", defaultEgressRule);
                cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, da_params));
                s_logger.debug("Completed move of the default egress rule after rule: " + ruleName);
            }
            return true;
        case DELETE:
            if (!manageFirewallRule(cmdList, PaloAltoPrimative.CHECK_IF_EXISTS, rule)) {
                return true;
            }
            Map<String, String> d_params = new HashMap<String, String>();
            d_params.put("type", "config");
            d_params.put("action", "delete");
            d_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/rulebase/security/rules/entry[@name='" + ruleName + "']");
            cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.POST, d_params));
            return true;
        default:
            s_logger.debug("Unrecognized command.");
            return false;
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) HashMap(java.util.HashMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 59 with ExecutionException

use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.

the class PaloAltoResource method validResponse.

/* A default response handler to validate that the request was successful. */
public boolean validResponse(String response) throws ExecutionException {
    NodeList response_body;
    Document doc = getDocument(response);
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        XPathExpression expr = xpath.compile("/response[@status='success']");
        response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new ExecutionException(e.getCause().getMessage());
    }
    if (response_body.getLength() > 0) {
        return true;
    } else {
        NodeList error_details;
        try {
            XPathExpression expr = xpath.compile("/response/msg/line/line");
            error_details = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            throw new ExecutionException(e.getCause().getMessage());
        }
        if (error_details.getLength() == 0) {
            try {
                XPathExpression expr = xpath.compile("/response/msg/line");
                error_details = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            } catch (XPathExpressionException e) {
                throw new ExecutionException(e.getCause().getMessage());
            }
            if (error_details.getLength() == 0) {
                try {
                    XPathExpression expr = xpath.compile("/response/result/msg");
                    error_details = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                } catch (XPathExpressionException e) {
                    throw new ExecutionException(e.getCause().getMessage());
                }
            }
        }
        String error = "";
        for (int i = 0; i < error_details.getLength(); i++) {
            error = error + error_details.item(i).getTextContent() + "\n";
        }
        throw new ExecutionException(error);
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 60 with ExecutionException

use of com.cloud.utils.exception.ExecutionException in project cloudstack by apache.

the class F5BigIpResource method addVirtualServer.

// Virtual server methods
private void addVirtualServer(String virtualServerName, LbProtocol protocol, String srcIp, int srcPort, StickinessPolicyTO[] stickyPolicies) throws ExecutionException {
    try {
        if (!virtualServerExists(virtualServerName)) {
            s_logger.debug("Adding virtual server " + virtualServerName);
            _virtualServerApi.create(genVirtualServerDefinition(virtualServerName, protocol, srcIp, srcPort), new String[] { "255.255.255.255" }, genVirtualServerResource(virtualServerName), genVirtualServerProfile(protocol));
            _virtualServerApi.set_snat_automap(genStringArray(virtualServerName));
            if (!virtualServerExists(virtualServerName)) {
                throw new ExecutionException("Failed to add virtual server " + virtualServerName);
            }
        }
        if ((stickyPolicies != null) && (stickyPolicies.length > 0) && (stickyPolicies[0] != null)) {
            StickinessPolicyTO stickinessPolicy = stickyPolicies[0];
            if (StickinessMethodType.LBCookieBased.getName().equalsIgnoreCase(stickinessPolicy.getMethodName())) {
                String[] profileNames = genStringArray("Cookie-profile-" + virtualServerName);
                if (!persistenceProfileExists(profileNames[0])) {
                    LocalLBPersistenceMode[] lbPersistenceMode = new iControl.LocalLBPersistenceMode[1];
                    lbPersistenceMode[0] = iControl.LocalLBPersistenceMode.PERSISTENCE_MODE_COOKIE;
                    _persistenceProfileApi.create(profileNames, lbPersistenceMode);
                    _virtualServerApi.add_persistence_profile(genStringArray(virtualServerName), genPersistenceProfile(profileNames[0]));
                }
                List<Pair<String, String>> paramsList = stickinessPolicy.getParams();
                for (Pair<String, String> param : paramsList) {
                    if ("holdtime".equalsIgnoreCase(param.first())) {
                        //F5 default
                        long timeout = 180;
                        if (param.second() != null) {
                            timeout = Long.parseLong(param.second());
                        }
                        LocalLBProfileULong[] cookieTimeout = new LocalLBProfileULong[1];
                        cookieTimeout[0] = new LocalLBProfileULong();
                        cookieTimeout[0].setValue(timeout);
                        _persistenceProfileApi.set_cookie_expiration(profileNames, cookieTimeout);
                    }
                }
            }
        } else {
            _virtualServerApi.remove_all_persistence_profiles(genStringArray(virtualServerName));
        }
    } catch (RemoteException e) {
        throw new ExecutionException(e.getMessage());
    }
}
Also used : LocalLBPersistenceMode(iControl.LocalLBPersistenceMode) LocalLBProfileULong(iControl.LocalLBProfileULong) ExecutionException(com.cloud.utils.exception.ExecutionException) RemoteException(java.rmi.RemoteException) StickinessPolicyTO(com.cloud.agent.api.to.LoadBalancerTO.StickinessPolicyTO) Pair(com.cloud.utils.Pair)

Aggregations

ExecutionException (com.cloud.utils.exception.ExecutionException)83 ConfigurationException (javax.naming.ConfigurationException)31 IOException (java.io.IOException)30 ArrayList (java.util.ArrayList)23 IpAssocAnswer (com.cloud.agent.api.routing.IpAssocAnswer)20 RemoteException (java.rmi.RemoteException)20 ExternalNetworkResourceUsageAnswer (com.cloud.agent.api.ExternalNetworkResourceUsageAnswer)19 Answer (com.cloud.agent.api.Answer)17 MaintainAnswer (com.cloud.agent.api.MaintainAnswer)16 ReadyAnswer (com.cloud.agent.api.ReadyAnswer)16 com.citrix.netscaler.nitro.exception.nitro_exception (com.citrix.netscaler.nitro.exception.nitro_exception)13 Document (org.w3c.dom.Document)12 XPathExpressionException (javax.xml.xpath.XPathExpressionException)11 HashMap (java.util.HashMap)10 XPath (javax.xml.xpath.XPath)8 XPathExpression (javax.xml.xpath.XPathExpression)8 NodeList (org.w3c.dom.NodeList)7 com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver (com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver)5 com.citrix.netscaler.nitro.resource.config.lb.lbvserver (com.citrix.netscaler.nitro.resource.config.lb.lbvserver)5 com.citrix.netscaler.nitro.resource.config.ns.nsconfig (com.citrix.netscaler.nitro.resource.config.ns.nsconfig)5