From df96af3de4756666d984fe2b6b9dc898bd2f874c Mon Sep 17 00:00:00 2001 From: dahn Date: Wed, 11 Jan 2023 03:07:44 -0800 Subject: [PATCH] delete F5 and SRX plugins (#7023) --- client/pom.xml | 15 - plugins/network-elements/f5/pom.xml | 41 - .../commands/AddExternalLoadBalancerCmd.java | 118 - .../api/commands/AddF5LoadBalancerCmd.java | 143 - .../commands/ConfigureF5LoadBalancerCmd.java | 124 - .../DeleteExternalLoadBalancerCmd.java | 96 - .../api/commands/DeleteF5LoadBalancerCmd.java | 112 - .../ListExternalLoadBalancersCmd.java | 90 - .../ListF5LoadBalancerNetworksCmd.java | 108 - .../api/commands/ListF5LoadBalancersCmd.java | 112 - .../api/response/F5LoadBalancerResponse.java | 109 - .../F5ExternalLoadBalancerElement.java | 538 --- .../F5ExternalLoadBalancerElementService.java | 97 - .../network/resource/F5BigIpResource.java | 1176 ----- .../META-INF/cloudstack/f5/module.properties | 18 - .../cloudstack/f5/spring-f5-context.xml | 34 - plugins/network-elements/juniper-srx/pom.xml | 37 - .../api/commands/AddExternalFirewallCmd.java | 110 - .../cloud/api/commands/AddSrxFirewallCmd.java | 135 - .../api/commands/ConfigureSrxFirewallCmd.java | 117 - .../commands/DeleteExternalFirewallCmd.java | 84 - .../api/commands/DeleteSrxFirewallCmd.java | 105 - .../commands/ListExternalFirewallsCmd.java | 83 - .../commands/ListSrxFirewallNetworksCmd.java | 102 - .../api/commands/ListSrxFirewallsCmd.java | 109 - .../api/response/SrxFirewallResponse.java | 159 - .../JuniperSRXExternalFirewallElement.java | 551 --- .../JuniperSRXFirewallElementService.java | 95 - .../network/resource/JuniperSrxResource.java | 3795 ----------------- .../META-INF/cloudstack/srx/module.properties | 18 - .../cloudstack/srx/spring-srx-context.xml | 35 - plugins/pom.xml | 11 - .../java/com/cloud/api/ApiResponseHelper.java | 2 +- .../ConfigurationManagerImpl.java | 2 +- .../ExternalFirewallDeviceManager.java | 2 +- test/metadata/func/srxstresswithportfwd.xml | 595 --- tools/marvin/marvin/configGenerator.py | 33 +- .../infra/network/ServiceProvidersTab.vue | 59 - .../network/providers/AddSrxFirewall.vue | 381 -- .../network/providers/ProviderListView.vue | 9 - 40 files changed, 4 insertions(+), 9556 deletions(-) delete mode 100644 plugins/network-elements/f5/pom.xml delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/api/commands/AddExternalLoadBalancerCmd.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/api/commands/AddF5LoadBalancerCmd.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListExternalLoadBalancersCmd.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListF5LoadBalancersCmd.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/api/response/F5LoadBalancerResponse.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/network/element/F5ExternalLoadBalancerElement.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/network/element/F5ExternalLoadBalancerElementService.java delete mode 100644 plugins/network-elements/f5/src/main/java/com/cloud/network/resource/F5BigIpResource.java delete mode 100644 plugins/network-elements/f5/src/main/resources/META-INF/cloudstack/f5/module.properties delete mode 100644 plugins/network-elements/f5/src/main/resources/META-INF/cloudstack/f5/spring-f5-context.xml delete mode 100644 plugins/network-elements/juniper-srx/pom.xml delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/AddExternalFirewallCmd.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/AddSrxFirewallCmd.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ConfigureSrxFirewallCmd.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/DeleteExternalFirewallCmd.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/DeleteSrxFirewallCmd.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListExternalFirewallsCmd.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListSrxFirewallsCmd.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/response/SrxFirewallResponse.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/element/JuniperSRXExternalFirewallElement.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/element/JuniperSRXFirewallElementService.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/resource/JuniperSrxResource.java delete mode 100644 plugins/network-elements/juniper-srx/src/main/resources/META-INF/cloudstack/srx/module.properties delete mode 100644 plugins/network-elements/juniper-srx/src/main/resources/META-INF/cloudstack/srx/spring-srx-context.xml delete mode 100644 test/metadata/func/srxstresswithportfwd.xml delete mode 100644 ui/src/views/infra/network/providers/AddSrxFirewall.vue diff --git a/client/pom.xml b/client/pom.xml index 9157894ba40..37b9c39b904 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -929,21 +929,6 @@ - - srx - - - noredist - - - - - org.apache.cloudstack - cloud-plugin-network-srx - ${project.version} - - - vmware diff --git a/plugins/network-elements/f5/pom.xml b/plugins/network-elements/f5/pom.xml deleted file mode 100644 index 7f4ef07b713..00000000000 --- a/plugins/network-elements/f5/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - 4.0.0 - cloud-plugin-network-f5 - Apache CloudStack Plugin - F5 - - org.apache.cloudstack - cloudstack-plugins - 4.18.0.0-SNAPSHOT - ../../pom.xml - - - - com.cloud.com.f5 - icontrol - 12.1 - - - commons-discovery - commons-discovery - - - diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/AddExternalLoadBalancerCmd.java b/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/AddExternalLoadBalancerCmd.java deleted file mode 100644 index 6deea1063d5..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/AddExternalLoadBalancerCmd.java +++ /dev/null @@ -1,118 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.api.commands; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; -import org.apache.cloudstack.api.response.ZoneResponse; - -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.Host; -import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.user.Account; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "addExternalLoadBalancer", description = "Adds F5 external load balancer appliance.", responseObject = ExternalLoadBalancerResponse.class, - requestHasSensitiveInfo = true, responseHasSensitiveInfo = false) -@Deprecated -// API supported only for backward compatibility. -public class AddExternalLoadBalancerCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddExternalLoadBalancerCmd.class.getName()); - private static final String s_name = "addexternalloadbalancerresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.ZONE_ID, - type = CommandType.UUID, - entityType = ZoneResponse.class, - required = true, - description = "Zone in which to add the external load balancer appliance.") - private Long zoneId; - - @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = true, description = "URL of the external load balancer appliance.") - private String url; - - @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Username of the external load balancer appliance.") - private String username; - - @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Password of the external load balancer appliance.") - private String password; - - /////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getZoneId() { - return zoneId; - } - - public String getUrl() { - return url; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - @Inject - F5ExternalLoadBalancerElementService _f5DeviceManagerService; - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - - @Override - public void execute() { - try { - Host externalLoadBalancer = _f5DeviceManagerService.addExternalLoadBalancer(this); - ExternalLoadBalancerResponse response = _f5DeviceManagerService.createExternalLoadBalancerResponse(externalLoadBalancer); - response.setObjectName("externalloadbalancer"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage()); - } catch (CloudRuntimeException cre) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage()); - } - } -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/AddF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/AddF5LoadBalancerCmd.java deleted file mode 100644 index 951439ddb65..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/AddF5LoadBalancerCmd.java +++ /dev/null @@ -1,143 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.api.commands; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.F5LoadBalancerResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.dao.ExternalLoadBalancerDeviceVO; -import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "addF5LoadBalancer", responseObject = F5LoadBalancerResponse.class, description = "Adds a F5 BigIP load balancer device", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class AddF5LoadBalancerCmd extends BaseAsyncCmd { - - public static final Logger s_logger = Logger.getLogger(AddF5LoadBalancerCmd.class.getName()); - private static final String s_name = "addf5bigiploadbalancerresponse"; - @Inject - F5ExternalLoadBalancerElementService _f5DeviceManagerService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, - type = CommandType.UUID, - entityType = PhysicalNetworkResponse.class, - required = true, - description = "the Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = true, description = "URL of the F5 load balancer appliance.") - private String url; - - @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Credentials to reach F5 BigIP load balancer device") - private String username; - - @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Credentials to reach F5 BigIP load balancer device") - private String password; - - @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, required = true, description = "supports only F5BigIpLoadBalancer") - private String deviceType; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public String getUrl() { - return url; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public String getDeviceType() { - return deviceType; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - ExternalLoadBalancerDeviceVO lbDeviceVO = _f5DeviceManagerService.addF5LoadBalancer(this); - if (lbDeviceVO != null) { - F5LoadBalancerResponse response = _f5DeviceManagerService.createF5LoadBalancerResponse(lbDeviceVO); - response.setObjectName("f5loadbalancer"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add F5 Big IP load balancer due to internal error."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getEventDescription() { - return "Adding a F5 Big Ip load balancer device"; - } - - @Override - public String getEventType() { - return EventTypes.EVENT_EXTERNAL_LB_DEVICE_ADD; - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java deleted file mode 100644 index dc520ff7100..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java +++ /dev/null @@ -1,124 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.api.commands; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.F5LoadBalancerResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.dao.ExternalLoadBalancerDeviceVO; -import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "configureF5LoadBalancer", responseObject = F5LoadBalancerResponse.class, description = "configures a F5 load balancer device", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ConfigureF5LoadBalancerCmd extends BaseAsyncCmd { - - public static final Logger s_logger = Logger.getLogger(ConfigureF5LoadBalancerCmd.class.getName()); - private static final String s_name = "configuref5Rloadbalancerresponse"; - @Inject - F5ExternalLoadBalancerElementService _f5DeviceManagerService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.LOAD_BALANCER_DEVICE_ID, - type = CommandType.UUID, - entityType = F5LoadBalancerResponse.class, - required = true, - description = "F5 load balancer device ID") - private Long lbDeviceId; - - @Parameter(name = ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY, - type = CommandType.LONG, - required = false, - description = "capacity of the device, Capacity will be interpreted as number of networks device can handle") - private Long capacity; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getLoadBalancerDeviceId() { - return lbDeviceId; - } - - public Long getLoadBalancerCapacity() { - return capacity; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - ExternalLoadBalancerDeviceVO lbDeviceVO = _f5DeviceManagerService.configureF5LoadBalancer(this); - if (lbDeviceVO != null) { - F5LoadBalancerResponse response = _f5DeviceManagerService.createF5LoadBalancerResponse(lbDeviceVO); - response.setObjectName("f5loadbalancer"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to configure F5 load balancer due to internal error."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getEventDescription() { - return "Configuring a F5 load balancer device"; - } - - @Override - public String getEventType() { - return EventTypes.EVENT_EXTERNAL_LB_DEVICE_CONFIGURE; - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java b/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java deleted file mode 100644 index b695ce4256d..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java +++ /dev/null @@ -1,96 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.api.commands; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.HostResponse; -import org.apache.cloudstack.api.response.SuccessResponse; - -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.user.Account; - -@APICommand(name = "deleteExternalLoadBalancer", description = "Deletes a F5 external load balancer appliance added in a zone.", responseObject = SuccessResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -@Deprecated -// API supported for backward compatibility. -public class DeleteExternalLoadBalancerCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteExternalLoadBalancerCmd.class.getName()); - private static final String s_name = "deleteexternalloadbalancerresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.ID, - type = CommandType.UUID, - entityType = HostResponse.class, - required = true, - description = "Id of the external loadbalancer appliance.") - private Long id; - - /////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getId() { - return id; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Inject - F5ExternalLoadBalancerElementService _f5DeviceManagerService; - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - - @Override - public void execute() { - try { - boolean result = _f5DeviceManagerService.deleteExternalLoadBalancer(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete external load balancer."); - } - } catch (InvalidParameterValueException e) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Failed to delete external load balancer."); - } - } -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java deleted file mode 100644 index cd60c61e3b8..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java +++ /dev/null @@ -1,112 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.api.commands; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.F5LoadBalancerResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "deleteF5LoadBalancer", responseObject = SuccessResponse.class, description = " delete a F5 load balancer device", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class DeleteF5LoadBalancerCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteF5LoadBalancerCmd.class.getName()); - private static final String s_name = "deletef5loadbalancerresponse"; - @Inject - F5ExternalLoadBalancerElementService _f5DeviceManagerService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.LOAD_BALANCER_DEVICE_ID, - type = CommandType.UUID, - entityType = F5LoadBalancerResponse.class, - required = true, - description = "netscaler load balancer device ID") - private Long lbDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getLoadBalancerDeviceId() { - return lbDeviceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - boolean result = _f5DeviceManagerService.deleteF5LoadBalancer(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete F5 load balancer."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getEventDescription() { - return "Deleting a F5 load balancer device"; - } - - @Override - public String getEventType() { - return EventTypes.EVENT_LOAD_BALANCER_DELETE; - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListExternalLoadBalancersCmd.java b/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListExternalLoadBalancersCmd.java deleted file mode 100644 index 4ffe85f5537..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListExternalLoadBalancersCmd.java +++ /dev/null @@ -1,90 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; -import org.apache.cloudstack.api.response.HostResponse; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.ZoneResponse; - -import com.cloud.host.Host; -import com.cloud.network.element.F5ExternalLoadBalancerElementService; - -@APICommand(name = "listExternalLoadBalancers", description = "Lists F5 external load balancer appliances added in a zone.", responseObject = HostResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -@Deprecated -// API supported for backward compatibility. -public class ListExternalLoadBalancersCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListExternalLoadBalancersCmd.class.getName()); - private static final String s_name = "listexternalloadbalancersresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, description = "zone Id") - private long zoneId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public long getZoneId() { - return zoneId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Inject - F5ExternalLoadBalancerElementService _f5DeviceManagerService; - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public void execute() { - List externalLoadBalancers = _f5DeviceManagerService.listExternalLoadBalancers(this); - ListResponse listResponse = new ListResponse(); - List responses = new ArrayList(); - for (Host externalLoadBalancer : externalLoadBalancers) { - ExternalLoadBalancerResponse response = _f5DeviceManagerService.createExternalLoadBalancerResponse(externalLoadBalancer); - response.setObjectName("externalloadbalancer"); - response.setResponseName(getCommandName()); - responses.add(response); - } - - listResponse.setResponses(responses); - listResponse.setResponseName(getCommandName()); - this.setResponseObject(listResponse); - } -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java b/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java deleted file mode 100644 index 1b7e1ec84a4..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java +++ /dev/null @@ -1,108 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ResponseObject.ResponseView; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.NetworkResponse; - -import com.cloud.api.response.F5LoadBalancerResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Network; -import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listF5LoadBalancerNetworks", responseObject = NetworkResponse.class, description = "lists network that are using a F5 load balancer device", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListF5LoadBalancerNetworksCmd extends BaseListCmd { - - public static final Logger s_logger = Logger.getLogger(ListF5LoadBalancerNetworksCmd.class.getName()); - private static final String s_name = "listf5loadbalancernetworksresponse"; - @Inject - F5ExternalLoadBalancerElementService _f5DeviceManagerService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.LOAD_BALANCER_DEVICE_ID, - type = CommandType.UUID, - entityType = F5LoadBalancerResponse.class, - required = true, - description = "f5 load balancer device ID") - private Long lbDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getLoadBalancerDeviceId() { - return lbDeviceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - List networks = _f5DeviceManagerService.listNetworks(this); - ListResponse response = new ListResponse(); - List networkResponses = new ArrayList(); - - if (networks != null && !networks.isEmpty()) { - for (Network network : networks) { - NetworkResponse networkResponse = _responseGenerator.createNetworkResponse(ResponseView.Full, network); - networkResponses.add(networkResponse); - } - } - - response.setResponses(networkResponses); - response.setResponseName(getCommandName()); - setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListF5LoadBalancersCmd.java b/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListF5LoadBalancersCmd.java deleted file mode 100644 index 283a1502da6..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/api/commands/ListF5LoadBalancersCmd.java +++ /dev/null @@ -1,112 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; - -import com.cloud.api.response.F5LoadBalancerResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.dao.ExternalLoadBalancerDeviceVO; -import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listF5LoadBalancers", responseObject = F5LoadBalancerResponse.class, description = "lists F5 load balancer devices", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListF5LoadBalancersCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListF5LoadBalancersCmd.class.getName()); - private static final String s_name = "listf5loadbalancerresponse"; - @Inject - F5ExternalLoadBalancerElementService _f5DeviceManagerService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "the Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.LOAD_BALANCER_DEVICE_ID, - type = CommandType.UUID, - entityType = F5LoadBalancerResponse.class, - description = "f5 load balancer device ID") - private Long lbDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getLoadBalancerDeviceId() { - return lbDeviceId; - } - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - List lbDevices = _f5DeviceManagerService.listF5LoadBalancers(this); - ListResponse response = new ListResponse(); - List lbDevicesResponse = new ArrayList(); - - if (lbDevices != null && !lbDevices.isEmpty()) { - for (ExternalLoadBalancerDeviceVO lbDeviceVO : lbDevices) { - F5LoadBalancerResponse lbdeviceResponse = _f5DeviceManagerService.createF5LoadBalancerResponse(lbDeviceVO); - lbDevicesResponse.add(lbdeviceResponse); - } - } - - response.setResponses(lbDevicesResponse); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/api/response/F5LoadBalancerResponse.java b/plugins/network-elements/f5/src/main/java/com/cloud/api/response/F5LoadBalancerResponse.java deleted file mode 100644 index a378fd39c25..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/api/response/F5LoadBalancerResponse.java +++ /dev/null @@ -1,109 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.network.dao.ExternalLoadBalancerDeviceVO; -import com.cloud.serializer.Param; - -@EntityReference(value = ExternalLoadBalancerDeviceVO.class) -public class F5LoadBalancerResponse extends BaseResponse { - @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_ID) - @Param(description = "device id of the F5 load balancer") - private String id; - - @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) - @Param(description = "the physical network to which this F5 device belongs to") - private String physicalNetworkId; - - @SerializedName(ApiConstants.PROVIDER) - @Param(description = "name of the provider") - private String providerName; - - @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_NAME) - @Param(description = "device name") - private String deviceName; - - @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_STATE) - @Param(description = "device state") - private String deviceState; - - @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY) - @Param(description = "device capacity") - private Long deviceCapacity; - - @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) - @Param(description = "true if device is dedicated for an account") - private Boolean dedicatedLoadBalancer; - - @SerializedName(ApiConstants.PUBLIC_INTERFACE) - @Param(description = "the public interface of the load balancer") - private String publicInterface; - - @SerializedName(ApiConstants.PRIVATE_INTERFACE) - @Param(description = "the private interface of the load balancer") - private String privateInterface; - - @SerializedName(ApiConstants.IP_ADDRESS) - @Param(description = "the management IP address of the external load balancer") - private String ipAddress; - - public void setId(String lbDeviceId) { - this.id = lbDeviceId; - } - - public void setPhysicalNetworkId(String physicalNetworkId) { - this.physicalNetworkId = physicalNetworkId; - } - - public void setProvider(String provider) { - this.providerName = provider; - } - - public void setDeviceName(String deviceName) { - this.deviceName = deviceName; - } - - public void setDeviceCapacity(long deviceCapacity) { - this.deviceCapacity = deviceCapacity; - } - - public void setDeviceState(String deviceState) { - this.deviceState = deviceState; - } - - public void setDedicatedLoadBalancer(boolean isDedicated) { - this.dedicatedLoadBalancer = isDedicated; - } - - public void setPublicInterface(String publicInterface) { - this.publicInterface = publicInterface; - } - - public void setPrivateInterface(String privateInterface) { - this.privateInterface = privateInterface; - } - - public void setIpAddress(String ipAddress) { - this.ipAddress = ipAddress; - } -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/plugins/network-elements/f5/src/main/java/com/cloud/network/element/F5ExternalLoadBalancerElement.java deleted file mode 100644 index bd54d954b8d..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ /dev/null @@ -1,538 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.element; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import com.google.gson.Gson; - -import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; - -import com.cloud.agent.api.to.LoadBalancerTO; -import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.AddExternalLoadBalancerCmd; -import com.cloud.api.commands.AddF5LoadBalancerCmd; -import com.cloud.api.commands.ConfigureF5LoadBalancerCmd; -import com.cloud.api.commands.DeleteExternalLoadBalancerCmd; -import com.cloud.api.commands.DeleteF5LoadBalancerCmd; -import com.cloud.api.commands.ListExternalLoadBalancersCmd; -import com.cloud.api.commands.ListF5LoadBalancerNetworksCmd; -import com.cloud.api.commands.ListF5LoadBalancersCmd; -import com.cloud.api.response.F5LoadBalancerResponse; -import com.cloud.configuration.Config; -import com.cloud.configuration.ConfigurationManager; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientNetworkCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.ExternalLoadBalancerDeviceManager; -import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl; -import com.cloud.network.Network; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.dao.ExternalLoadBalancerDeviceDao; -import com.cloud.network.dao.ExternalLoadBalancerDeviceVO; -import com.cloud.network.dao.ExternalLoadBalancerDeviceVO.LBDeviceState; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkExternalLoadBalancerDao; -import com.cloud.network.dao.NetworkExternalLoadBalancerVO; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.network.lb.LoadBalancingRule; -import com.cloud.network.resource.F5BigIpResource; -import com.cloud.network.rules.LbStickinessMethod; -import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; -import com.cloud.network.rules.LoadBalancerContainer; -import com.cloud.offering.NetworkOffering; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; - -public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, IpDeployer, - F5ExternalLoadBalancerElementService, ExternalLoadBalancerDeviceManager { - - private static final Logger s_logger = Logger.getLogger(F5ExternalLoadBalancerElement.class); - - @Inject - NetworkModel _networkManager; - @Inject - ConfigurationManager _configMgr; - @Inject - NetworkServiceMapDao _ntwkSrvcDao; - @Inject - DataCenterDao _dcDao; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - HostDao _hostDao; - @Inject - ExternalLoadBalancerDeviceDao _lbDeviceDao; - @Inject - NetworkExternalLoadBalancerDao _networkLBDao; - @Inject - NetworkDao _networkDao; - @Inject - HostDetailsDao _detailsDao; - @Inject - ConfigurationDao _configDao; - - private boolean canHandle(Network config, List rules) { - if ((config.getGuestType() != Network.GuestType.Isolated && config.getGuestType() != Network.GuestType.Shared) || config.getTrafficType() != TrafficType.Guest) { - - s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType()); - return false; - } - - Map lbCaps = this.getCapabilities().get(Service.Lb); - if (!lbCaps.isEmpty()) { - String schemeCaps = lbCaps.get(Capability.LbSchemes); - if (schemeCaps != null && rules != null && !rules.isEmpty()) { - for (LoadBalancingRule rule : rules) { - if (!schemeCaps.contains(rule.getScheme().toString())) { - s_logger.debug("Scheme " + rules.get(0).getScheme() + " is not supported by the provider " + this.getName()); - return false; - } - } - } - } - - return (_networkManager.isProviderForNetwork(getProvider(), config.getId()) && _ntwkSrvcDao.canProviderSupportServiceInNetwork(config.getId(), Service.Lb, - Network.Provider.F5BigIp)); - } - - @Override - public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, - ConcurrentOperationException, InsufficientNetworkCapacityException { - - if (!canHandle(guestConfig, null)) { - return false; - } - - try { - return manageGuestNetworkWithExternalLoadBalancer(true, guestConfig); - } catch (InsufficientCapacityException capacityException) { - throw new ResourceUnavailableException("There are no F5 load balancer devices with the free capacity for implementing this network", DataCenter.class, - guestConfig.getDataCenterId()); - } - } - - @Override - public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { - return true; - } - - @Override - public boolean release(Network config, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) { - return true; - } - - @Override - public boolean shutdown(Network guestConfig, ReservationContext context, boolean cleanup) throws ResourceUnavailableException, ConcurrentOperationException { - if (!canHandle(guestConfig, null)) { - return false; - } - - try { - return manageGuestNetworkWithExternalLoadBalancer(false, guestConfig); - } catch (InsufficientCapacityException capacityException) { - // TODO: handle out of capacity exception - return false; - } - } - - @Override - public boolean destroy(Network config, ReservationContext context) { - return true; - } - - @Override - public boolean validateLBRule(Network network, LoadBalancingRule rule) { - if (canHandle(network, new ArrayList(Arrays.asList(rule)))) { - String algo = rule.getAlgorithm(); - return (algo.equals("roundrobin") || algo.equals("leastconn")); - } - return true; - } - - @Override - public boolean applyLBRules(Network config, List rules) throws ResourceUnavailableException { - if (!canHandle(config, rules)) { - return false; - } - - return applyLoadBalancerRules(config, rules); - } - - @Override - public Map> getCapabilities() { - Map> capabilities = new HashMap>(); - - // Set capabilities for LB service - Map lbCapabilities = new HashMap(); - - // Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules - lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn"); - - // specifies that F5 BIG IP network element can provide shared mode only - lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated, shared"); - - // Specifies that load balancing rules can be made for either TCP or UDP traffic - lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp"); - - // Specifies that this element can measure network usage on a per public IP basis - lbCapabilities.put(Capability.TrafficStatistics, "per public ip"); - - // Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs - lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional"); - - // Support inline mode with firewall - lbCapabilities.put(Capability.InlineMode, "true"); - - //support only for public lb - lbCapabilities.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Public.toString()); - - LbStickinessMethod method; - List methodList = new ArrayList(); - method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is cookie based sticky method, can be used only for http"); - methodList.add(method); - method.addParam("holdtime", false, "time period (in seconds) for which persistence is in effect.", false); - - Gson gson = new Gson(); - String stickyMethodList = gson.toJson(methodList); - lbCapabilities.put(Capability.SupportedStickinessMethods, stickyMethodList); - - capabilities.put(Service.Lb, lbCapabilities); - - return capabilities; - } - - @Override - public Provider getProvider() { - return Provider.F5BigIp; - } - - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - List lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.F5BigIp.getName()); - - // true if at-least one F5 device is added in to physical network and is in configured (in enabled state) state - if (lbDevices != null && !lbDevices.isEmpty()) { - for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { - if (lbDevice.getState() == LBDeviceState.Enabled) { - return true; - } - } - } - return false; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - // TODO Auto-generated method stub - return true; - } - - @Override - public boolean canEnableIndividualServices() { - return false; - } - - @Override - public List> getCommands() { - List> cmdList = new ArrayList>(); - cmdList.add(AddExternalLoadBalancerCmd.class); - cmdList.add(AddF5LoadBalancerCmd.class); - cmdList.add(ConfigureF5LoadBalancerCmd.class); - cmdList.add(DeleteExternalLoadBalancerCmd.class); - cmdList.add(DeleteF5LoadBalancerCmd.class); - cmdList.add(ListExternalLoadBalancersCmd.class); - cmdList.add(ListF5LoadBalancerNetworksCmd.class); - cmdList.add(ListF5LoadBalancersCmd.class); - return cmdList; - } - - @Override - @Deprecated - public Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd) { - Long zoneId = cmd.getZoneId(); - DataCenterVO zone = null; - PhysicalNetworkVO pNetwork = null; - ExternalLoadBalancerDeviceVO lbDeviceVO = null; - HostVO lbHost = null; - - zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); - } - - List physicalNetworks = _physicalNetworkDao.listByZone(zoneId); - if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) { - throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: " + zoneId + - " to add this device."); - } - pNetwork = physicalNetworks.get(0); - - String deviceType = NetworkDevice.F5BigIpLoadBalancer.getName(); - lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), - deviceType, new F5BigIpResource(), false, false, null, null); - - if (lbDeviceVO != null) { - lbHost = _hostDao.findById(lbDeviceVO.getHostId()); - } - - return lbHost; - } - - @Override - @Deprecated - public boolean deleteExternalLoadBalancer(DeleteExternalLoadBalancerCmd cmd) { - return deleteExternalLoadBalancer(cmd.getId()); - } - - @Override - @Deprecated - public List listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd) { - Long zoneId = cmd.getZoneId(); - DataCenterVO zone = null; - PhysicalNetworkVO pNetwork = null; - - if (zoneId != null) { - zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); - } - - List physicalNetworks = _physicalNetworkDao.listByZone(zoneId); - if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) { - throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: " + zoneId + - " to add this device."); - } - pNetwork = physicalNetworks.get(0); - return listExternalLoadBalancers(pNetwork.getId(), NetworkDevice.F5BigIpLoadBalancer.getName()); - } else { - throw new InvalidParameterValueException("Zone Id must be specified to list the external load balancers"); - } - } - - @Override - @Deprecated - public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLb) { - return super.createExternalLoadBalancerResponse(externalLb); - } - - @Override - public ExternalLoadBalancerDeviceVO addF5LoadBalancer(AddF5LoadBalancerCmd cmd) { - String deviceName = cmd.getDeviceType(); - if (!deviceName.equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { - throw new InvalidParameterValueException("Invalid F5 load balancer device type"); - } - - return addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), - deviceName, new F5BigIpResource(), false, false, null, - null); - - } - - @Override - public boolean deleteF5LoadBalancer(DeleteF5LoadBalancerCmd cmd) { - Long lbDeviceId = cmd.getLoadBalancerDeviceId(); - - ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId); - if ((lbDeviceVo == null) || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { - throw new InvalidParameterValueException("No F5 load balancer device found with ID: " + lbDeviceId); - } - - return deleteExternalLoadBalancer(lbDeviceVo.getHostId()); - } - - @Override - public ExternalLoadBalancerDeviceVO configureF5LoadBalancer(ConfigureF5LoadBalancerCmd cmd) { - Long lbDeviceId = cmd.getLoadBalancerDeviceId(); - Long capacity = cmd.getLoadBalancerCapacity(); - - ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId); - if ((lbDeviceVo == null) || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { - throw new InvalidParameterValueException("No F5 load balancer device found with ID: " + lbDeviceId); - } - - if (capacity != null) { - // check if any networks are using this F5 device - List networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); - if ((networks != null) && !networks.isEmpty()) { - if (capacity < networks.size()) { - throw new CloudRuntimeException("There are more number of networks already using this F5 device than configured capacity"); - } - } - if (capacity != null) { - lbDeviceVo.setCapacity(capacity); - } - } - - lbDeviceVo.setState(LBDeviceState.Enabled); - _lbDeviceDao.update(lbDeviceId, lbDeviceVo); - return lbDeviceVo; - } - - @Override - public List listF5LoadBalancers(ListF5LoadBalancersCmd cmd) { - Long physcialNetworkId = cmd.getPhysicalNetworkId(); - Long lbDeviceId = cmd.getLoadBalancerDeviceId(); - PhysicalNetworkVO pNetwork = null; - List lbDevices = new ArrayList(); - - if (physcialNetworkId == null && lbDeviceId == null) { - throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified"); - } - - if (lbDeviceId != null) { - ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId); - if (lbDeviceVo == null || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { - throw new InvalidParameterValueException("Could not find F5 load balancer device with ID: " + lbDeviceId); - } - lbDevices.add(lbDeviceVo); - return lbDevices; - } - - if (physcialNetworkId != null) { - pNetwork = _physicalNetworkDao.findById(physcialNetworkId); - if (pNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physcialNetworkId); - } - lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(physcialNetworkId, Provider.F5BigIp.getName()); - return lbDevices; - } - - return null; - } - - @Override - public List listNetworks(ListF5LoadBalancerNetworksCmd cmd) { - Long lbDeviceId = cmd.getLoadBalancerDeviceId(); - List networks = new ArrayList(); - - ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId); - if (lbDeviceVo == null || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) { - throw new InvalidParameterValueException("Could not find F5 load balancer device with ID " + lbDeviceId); - } - - List networkLbMaps = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId); - if (networkLbMaps != null && !networkLbMaps.isEmpty()) { - for (NetworkExternalLoadBalancerVO networkLbMap : networkLbMaps) { - NetworkVO network = _networkDao.findById(networkLbMap.getNetworkId()); - networks.add(network); - } - } - - return networks; - } - - @Override - public F5LoadBalancerResponse createF5LoadBalancerResponse(ExternalLoadBalancerDeviceVO lbDeviceVO) { - F5LoadBalancerResponse response = new F5LoadBalancerResponse(); - Host lbHost = _hostDao.findById(lbDeviceVO.getHostId()); - Map lbDetails = _detailsDao.findDetails(lbDeviceVO.getHostId()); - - response.setId(lbDeviceVO.getUuid()); - response.setIpAddress(lbHost.getPrivateIpAddress()); - PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(lbDeviceVO.getPhysicalNetworkId()); - if (pnw != null) { - response.setPhysicalNetworkId(pnw.getUuid()); - } - response.setPublicInterface(lbDetails.get("publicInterface")); - response.setPrivateInterface(lbDetails.get("privateInterface")); - response.setDeviceName(lbDeviceVO.getDeviceName()); - if (lbDeviceVO.getCapacity() == 0) { - long defaultLbCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalLoadBalancerCapacity.key()), 50); - response.setDeviceCapacity(defaultLbCapacity); - } else { - response.setDeviceCapacity(lbDeviceVO.getCapacity()); - } - response.setDedicatedLoadBalancer(lbDeviceVO.getIsDedicatedDevice()); - response.setProvider(lbDeviceVO.getProviderName()); - response.setDeviceState(lbDeviceVO.getState().name()); - response.setObjectName("f5loadbalancer"); - return response; - } - - @Override - public boolean verifyServicesCombination(Set services) { - return true; - } - - @Override - public boolean applyIps(Network network, List ipAddress, Set service) throws ResourceUnavailableException { - // return true, as IP will be associated as part of LB rule configuration - return true; - } - - @Override - public IpDeployer getIpDeployer(Network network) { - ExternalLoadBalancerDeviceVO lbDevice = getExternalLoadBalancerForNetwork(network); - if (lbDevice == null) { - s_logger.error("Cannot find external load balanacer for network " + network.getName()); - s_logger.error("Make F5 as dummy ip deployer, since we likely met this when clean up resource after shutdown network"); - return this; - } - if (_networkManager.isNetworkInlineMode(network)) { - return getIpDeployerForInlineMode(network); - } - return this; - } - - @Override - public List updateHealthChecks(Network network, List lbrules) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean handlesOnlyRulesInTransitionState() { - return true; - } -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/network/element/F5ExternalLoadBalancerElementService.java b/plugins/network-elements/f5/src/main/java/com/cloud/network/element/F5ExternalLoadBalancerElementService.java deleted file mode 100644 index eacb7cffded..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/network/element/F5ExternalLoadBalancerElementService.java +++ /dev/null @@ -1,97 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.element; - -import java.util.List; - -import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; - -import com.cloud.api.commands.AddExternalLoadBalancerCmd; -import com.cloud.api.commands.AddF5LoadBalancerCmd; -import com.cloud.api.commands.ConfigureF5LoadBalancerCmd; -import com.cloud.api.commands.DeleteExternalLoadBalancerCmd; -import com.cloud.api.commands.DeleteF5LoadBalancerCmd; -import com.cloud.api.commands.ListExternalLoadBalancersCmd; -import com.cloud.api.commands.ListF5LoadBalancerNetworksCmd; -import com.cloud.api.commands.ListF5LoadBalancersCmd; -import com.cloud.api.response.F5LoadBalancerResponse; -import com.cloud.host.Host; -import com.cloud.network.Network; -import com.cloud.network.dao.ExternalLoadBalancerDeviceVO; -import com.cloud.utils.component.PluggableService; - -@SuppressWarnings("deprecation") -public interface F5ExternalLoadBalancerElementService extends PluggableService { - - /** - * adds a F5 load balancer device in to a physical network - * @param AddF5LoadBalancerCmd - * @return ExternalLoadBalancerDeviceVO object for the device added - */ - public ExternalLoadBalancerDeviceVO addF5LoadBalancer(AddF5LoadBalancerCmd cmd); - - /** - * removes a F5 load balancer device from a physical network - * @param DeleteF5LoadBalancerCmd - * @return true if F5 load balancer device is successfully deleted - */ - public boolean deleteF5LoadBalancer(DeleteF5LoadBalancerCmd cmd); - - /** - * configures a F5 load balancer device added in a physical network - * @param ConfigureF5LoadBalancerCmd - * @return ExternalLoadBalancerDeviceVO for the device configured - */ - public ExternalLoadBalancerDeviceVO configureF5LoadBalancer(ConfigureF5LoadBalancerCmd cmd); - - /** - * lists all the load balancer devices added in to a physical network - * @param ListF5LoadBalancersCmd - * @return list of ExternalLoadBalancerDeviceVO for the devices in the physical network. - */ - public List listF5LoadBalancers(ListF5LoadBalancersCmd cmd); - - /** - * lists all the guest networks using a F5 load balancer device - * @param ListF5LoadBalancerNetworksCmd - * @return list of the guest networks that are using this F5 load balancer - */ - public List listNetworks(ListF5LoadBalancerNetworksCmd cmd); - - public F5LoadBalancerResponse createF5LoadBalancerResponse(ExternalLoadBalancerDeviceVO lbDeviceVO); - - /* Deprecated API helper function */ - @Deprecated - // API helper function supported for backward compatibility - public - Host addExternalLoadBalancer(AddExternalLoadBalancerCmd cmd); - - @Deprecated - // API helper function supported for backward compatibility - public - boolean deleteExternalLoadBalancer(DeleteExternalLoadBalancerCmd cmd); - - @Deprecated - // API helper function supported for backward compatibility - public - List listExternalLoadBalancers(ListExternalLoadBalancersCmd cmd); - - @Deprecated - // API helper function supported for backward compatibility - public - ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLb); -} diff --git a/plugins/network-elements/f5/src/main/java/com/cloud/network/resource/F5BigIpResource.java b/plugins/network-elements/f5/src/main/java/com/cloud/network/resource/F5BigIpResource.java deleted file mode 100644 index c4e0fdfb4c1..00000000000 --- a/plugins/network-elements/f5/src/main/java/com/cloud/network/resource/F5BigIpResource.java +++ /dev/null @@ -1,1176 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.resource; - -import iControl.CommonEnabledState; -import iControl.CommonIPPortDefinition; -import iControl.CommonStatistic; -import iControl.CommonStatisticType; -import iControl.CommonVirtualServerDefinition; -import iControl.Interfaces; -import iControl.LocalLBLBMethod; -import iControl.LocalLBNodeAddressBindingStub; -import iControl.LocalLBPersistenceMode; -import iControl.LocalLBPoolBindingStub; -import iControl.LocalLBProfileContextType; -import iControl.LocalLBProfilePersistenceBindingStub; -import iControl.LocalLBProfileULong; -import iControl.LocalLBVirtualServerBindingStub; -import iControl.LocalLBVirtualServerVirtualServerPersistence; -import iControl.LocalLBVirtualServerVirtualServerProfile; -import iControl.LocalLBVirtualServerVirtualServerResource; -import iControl.LocalLBVirtualServerVirtualServerStatisticEntry; -import iControl.LocalLBVirtualServerVirtualServerStatistics; -import iControl.LocalLBVirtualServerVirtualServerType; -import iControl.NetworkingMemberTagType; -import iControl.NetworkingMemberType; -import iControl.NetworkingRouteDomainBindingStub; -import iControl.NetworkingSelfIPBindingStub; -import iControl.NetworkingVLANBindingStub; -import iControl.NetworkingVLANMemberEntry; -import iControl.SystemConfigSyncBindingStub; -import iControl.SystemConfigSyncSaveMode; - -import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; - -import com.cloud.agent.IAgentControl; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.ExternalNetworkResourceUsageAnswer; -import com.cloud.agent.api.ExternalNetworkResourceUsageCommand; -import com.cloud.agent.api.MaintainAnswer; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.ReadyAnswer; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupExternalLoadBalancerCommand; -import com.cloud.agent.api.routing.IpAssocAnswer; -import com.cloud.agent.api.routing.IpAssocCommand; -import com.cloud.agent.api.routing.LoadBalancerConfigCommand; -import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.to.IpAddressTO; -import com.cloud.agent.api.to.LoadBalancerTO; -import com.cloud.agent.api.to.LoadBalancerTO.DestinationTO; -import com.cloud.agent.api.to.LoadBalancerTO.StickinessPolicyTO; -import com.cloud.host.Host; -import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; -import com.cloud.resource.ServerResource; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.Pair; -import com.cloud.utils.exception.ExecutionException; -import com.cloud.utils.net.NetUtils; - -public class F5BigIpResource implements ServerResource { - - private enum LbAlgorithm { - RoundRobin(null, LocalLBLBMethod.LB_METHOD_ROUND_ROBIN), LeastConn(null, LocalLBLBMethod.LB_METHOD_LEAST_CONNECTION_MEMBER); - - String persistenceProfileName; - LocalLBLBMethod method; - - LbAlgorithm(String persistenceProfileName, LocalLBLBMethod method) { - this.persistenceProfileName = persistenceProfileName; - this.method = method; - } - - public String getPersistenceProfileName() { - return persistenceProfileName; - } - - public LocalLBLBMethod getMethod() { - return method; - } - } - - private enum LbProtocol { - tcp, udp; - } - - private String _name; - private String _zoneId; - private String _ip; - private String _username; - private String _password; - private String _publicInterface; - private String _privateInterface; - private Integer _numRetries; - private String _guid; - - private Interfaces _interfaces; - private LocalLBVirtualServerBindingStub _virtualServerApi; - private LocalLBPoolBindingStub _loadbalancerApi; - private LocalLBNodeAddressBindingStub _nodeApi; - private NetworkingVLANBindingStub _vlanApi; - private NetworkingSelfIPBindingStub _selfIpApi; - private NetworkingRouteDomainBindingStub _routeDomainApi; - private SystemConfigSyncBindingStub _configSyncApi; - private LocalLBProfilePersistenceBindingStub _persistenceProfileApi; - private String _objectNamePathSep = "-"; - private String _routeDomainIdentifier = "%"; - - private static final Logger s_logger = Logger.getLogger(F5BigIpResource.class); - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - try { - _name = (String)params.get("name"); - if (_name == null) { - throw new ConfigurationException("Unable to find name"); - } - - _zoneId = (String)params.get("zoneId"); - if (_zoneId == null) { - throw new ConfigurationException("Unable to find zone"); - } - - _ip = (String)params.get("ip"); - if (_ip == null) { - throw new ConfigurationException("Unable to find IP"); - } - - _username = (String)params.get("username"); - if (_username == null) { - throw new ConfigurationException("Unable to find username"); - } - - _password = (String)params.get("password"); - if (_password == null) { - throw new ConfigurationException("Unable to find password"); - } - - _publicInterface = (String)params.get("publicinterface"); - if (_publicInterface == null) { - throw new ConfigurationException("Unable to find public interface"); - } - - _privateInterface = (String)params.get("privateinterface"); - if (_privateInterface == null) { - throw new ConfigurationException("Unable to find private interface"); - } - - _numRetries = NumbersUtil.parseInt((String)params.get("numretries"), 1); - - _guid = (String)params.get("guid"); - if (_guid == null) { - throw new ConfigurationException("Unable to find the guid"); - } - - login(); - - return true; - } catch (Exception e) { - throw new ConfigurationException(e.getMessage()); - } - - } - - @Override - public StartupCommand[] initialize() { - StartupExternalLoadBalancerCommand cmd = new StartupExternalLoadBalancerCommand(); - cmd.setName(_name); - cmd.setDataCenter(_zoneId); - cmd.setPod(""); - cmd.setPrivateIpAddress(_ip); - cmd.setStorageIpAddress(""); - cmd.setVersion(F5BigIpResource.class.getPackage().getImplementationVersion()); - cmd.setGuid(_guid); - return new StartupCommand[] {cmd}; - } - - @Override - public Host.Type getType() { - return Host.Type.ExternalLoadBalancer; - } - - @Override - public String getName() { - return _name; - } - - @Override - public PingCommand getCurrentStatus(final long id) { - return new PingCommand(Host.Type.ExternalLoadBalancer, id); - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public void disconnected() { - return; - } - - @Override - public IAgentControl getAgentControl() { - return null; - } - - @Override - public void setAgentControl(IAgentControl agentControl) { - return; - } - - @Override - public Answer executeRequest(Command cmd) { - return executeRequest(cmd, _numRetries); - } - - private Answer executeRequest(Command cmd, int numRetries) { - if (cmd instanceof ReadyCommand) { - return execute((ReadyCommand)cmd); - } else if (cmd instanceof MaintainCommand) { - return execute((MaintainCommand)cmd); - } else if (cmd instanceof IpAssocCommand) { - return execute((IpAssocCommand)cmd, numRetries); - } else if (cmd instanceof LoadBalancerConfigCommand) { - return execute((LoadBalancerConfigCommand)cmd, numRetries); - } else if (cmd instanceof ExternalNetworkResourceUsageCommand) { - return execute((ExternalNetworkResourceUsageCommand)cmd); - } else { - return Answer.createUnsupportedCommandAnswer(cmd); - } - } - - private Answer retry(Command cmd, int numRetries) { - int numRetriesRemaining = numRetries - 1; - s_logger.error("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetriesRemaining); - return executeRequest(cmd, numRetriesRemaining); - } - - private boolean shouldRetry(int numRetries) { - try { - if (numRetries > 0) { - login(); - return true; - } - } catch (Exception e) { - s_logger.error("Failed to log in to F5 device at " + _ip + " due to " + e.getMessage()); - } - return false; - } - - private Answer execute(ReadyCommand cmd) { - return new ReadyAnswer(cmd); - } - - private Answer execute(MaintainCommand cmd) { - return new MaintainAnswer(cmd); - } - - private synchronized Answer execute(IpAssocCommand cmd, int numRetries) { - String[] results = new String[cmd.getIpAddresses().length]; - int i = 0; - try { - IpAddressTO[] ips = cmd.getIpAddresses(); - for (IpAddressTO ip : ips) { - // is it saver to use Long.valueOf(BroadcastDomain.getValue(ip.getBroadcastUri())) ??? - // i.o.w. can this contain vlan:// then change !!! - long guestVlanTag = Long.parseLong(ip.getBroadcastUri()); - // It's a hack, using isOneToOneNat field for indicate if it's inline or not - boolean inline = ip.isOneToOneNat(); - String vlanSelfIp = inline ? tagAddressWithRouteDomain(ip.getVlanGateway(), guestVlanTag) : ip.getVlanGateway(); - String vlanNetmask = ip.getVlanNetmask(); - - // Delete any existing guest VLAN with this tag, self IP, and netmask - deleteGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask, inline); - - if (ip.isAdd()) { - // Add a new guest VLAN - addGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask, inline); - } - - saveConfiguration(); - results[i++] = ip.getPublicIp() + " - success"; - } - - } catch (ExecutionException e) { - s_logger.error("Failed to execute IPAssocCommand due to " + e); - - if (shouldRetry(numRetries)) { - return retry(cmd, numRetries); - } else { - results[i++] = IpAssocAnswer.errorResult; - } - } - - return new IpAssocAnswer(cmd, results); - } - - private synchronized Answer execute(LoadBalancerConfigCommand cmd, int numRetries) { - try { - long guestVlanTag = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG)); - LoadBalancerTO[] loadBalancers = cmd.getLoadBalancers(); - for (LoadBalancerTO loadBalancer : loadBalancers) { - boolean inline = loadBalancer.isInline(); - LbProtocol lbProtocol; - try { - if (loadBalancer.getProtocol() == null) { - lbProtocol = LbProtocol.tcp; - } else { - lbProtocol = LbProtocol.valueOf(loadBalancer.getProtocol()); - } - } catch (IllegalArgumentException e) { - throw new ExecutionException("Got invalid protocol: " + loadBalancer.getProtocol()); - } - - LbAlgorithm lbAlgorithm; - if (loadBalancer.getAlgorithm().equals("roundrobin")) { - lbAlgorithm = LbAlgorithm.RoundRobin; - } else if (loadBalancer.getAlgorithm().equals("leastconn")) { - lbAlgorithm = LbAlgorithm.LeastConn; - } else { - throw new ExecutionException("Got invalid algorithm: " + loadBalancer.getAlgorithm()); - } - - String srcIp = inline ? tagAddressWithRouteDomain(loadBalancer.getSrcIp(), guestVlanTag) : loadBalancer.getSrcIp(); - int srcPort = loadBalancer.getSrcPort(); - String virtualServerName = genVirtualServerName(lbProtocol, srcIp, srcPort); - - boolean destinationsToAdd = false; - for (DestinationTO destination : loadBalancer.getDestinations()) { - if (!destination.isRevoked()) { - destinationsToAdd = true; - break; - } - } - - // Delete the virtual server with this protocol, source IP, and source port, along with its default pool and all pool members - deleteVirtualServerAndDefaultPool(virtualServerName); - if (!loadBalancer.isRevoked() && destinationsToAdd) { - // Add the pool - addPool(virtualServerName, lbAlgorithm); - - // Add pool members - List activePoolMembers = new ArrayList(); - for (DestinationTO destination : loadBalancer.getDestinations()) { - if (!destination.isRevoked()) { - String destIp = inline ? tagAddressWithRouteDomain(destination.getDestIp(), guestVlanTag) : destination.getDestIp(); - addPoolMember(virtualServerName, destIp, destination.getDestPort()); - activePoolMembers.add(destIp + "-" + destination.getDestPort()); - } - } - - // Add the virtual server - addVirtualServer(virtualServerName, lbProtocol, srcIp, srcPort, loadBalancer.getStickinessPolicies()); - } - } - - saveConfiguration(); - return new Answer(cmd); - } catch (ExecutionException e) { - s_logger.error("Failed to execute LoadBalancerConfigCommand due to " + e); - - if (shouldRetry(numRetries)) { - return retry(cmd, numRetries); - } else { - return new Answer(cmd, e); - } - - } - } - - private synchronized ExternalNetworkResourceUsageAnswer execute(ExternalNetworkResourceUsageCommand cmd) { - try { - return getIpBytesSentAndReceived(cmd); - } catch (ExecutionException e) { - return new ExternalNetworkResourceUsageAnswer(cmd, e); - } - } - - private void saveConfiguration() throws ExecutionException { - try { - _configSyncApi.save_configuration("", SystemConfigSyncSaveMode.SAVE_BASE_LEVEL_CONFIG); - _configSyncApi.save_configuration("", SystemConfigSyncSaveMode.SAVE_HIGH_LEVEL_CONFIG); - s_logger.debug("Successfully saved F5 BigIp configuration."); - } catch (RemoteException e) { - s_logger.error("Failed to save F5 BigIp configuration due to: " + e); - throw new ExecutionException(e.getMessage()); - } - } - - private void addGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask, boolean inline) throws ExecutionException { - try { - String vlanName = genVlanName(vlanTag); - List allVlans = getStrippedVlans(); - if (!allVlans.contains(vlanName)) { - String[] vlanNames = genStringArray(vlanName); - long[] vlanTags = genLongArray(vlanTag); - CommonEnabledState[] commonEnabledState = {CommonEnabledState.STATE_DISABLED}; - - // Create the interface name - NetworkingVLANMemberEntry[][] vlanMemberEntries = {{new NetworkingVLANMemberEntry()}}; - vlanMemberEntries[0][0].setMember_type(NetworkingMemberType.MEMBER_INTERFACE); - vlanMemberEntries[0][0].setTag_state(NetworkingMemberTagType.MEMBER_TAGGED); - vlanMemberEntries[0][0].setMember_name(_privateInterface); - - s_logger.debug("Creating a guest VLAN with tag " + vlanTag); - _vlanApi.create(vlanNames, vlanTags, vlanMemberEntries, commonEnabledState, new long[] {10L}, new String[] {"00:00:00:00:00:00"}); - s_logger.debug("vlanName " + vlanName); - s_logger.debug("getStrippedVlans " + getStrippedVlans()); - - if (!getStrippedVlans().contains(vlanName)) { - throw new ExecutionException("Failed to create vlan with tag " + vlanTag); - } - } - - if (inline) { - List allRouteDomains = getRouteDomains(); - if (!allRouteDomains.contains(vlanTag)) { - long[] routeDomainIds = genLongArray(vlanTag); - String[][] vlanNames = new String[][] {genStringArray(genVlanName(vlanTag))}; - - s_logger.debug("Creating route domain " + vlanTag); - _routeDomainApi.create(routeDomainIds, vlanNames); - - if (!getRouteDomains().contains(vlanTag)) { - throw new ExecutionException("Failed to create route domain " + vlanTag); - } - } - } - - List allSelfIps = getSelfIps(); - if (!allSelfIps.contains(vlanSelfIp)) { - String[] selfIpsToCreate = genStringArray(vlanSelfIp); - String[] vlans = genStringArray(vlanName); - String[] netmasks = genStringArray(vlanNetmask); - long[] unitIds = genLongArray(0L); - CommonEnabledState[] enabledStates = new CommonEnabledState[] {CommonEnabledState.STATE_DISABLED}; - - s_logger.debug("Creating self IP " + vlanSelfIp); - _selfIpApi.create(selfIpsToCreate, vlans, netmasks, unitIds, enabledStates); - - if (!getSelfIps().contains(vlanSelfIp)) { - throw new ExecutionException("Failed to create self IP " + vlanSelfIp); - } - } - } catch (RemoteException e) { - s_logger.error(e); - throw new ExecutionException(e.getMessage()); - } - - } - - private void deleteGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask, boolean inline) throws ExecutionException { - try { - // Delete all virtual servers and pools that use this guest VLAN - deleteVirtualServersInGuestVlan(vlanSelfIp, vlanNetmask); - - List allSelfIps = getSelfIps(); - if (allSelfIps.contains(vlanSelfIp)) { - s_logger.debug("Deleting self IP " + vlanSelfIp); - _selfIpApi.delete_self_ip(genStringArray(vlanSelfIp)); - - if (getSelfIps().contains(vlanSelfIp)) { - throw new ExecutionException("Failed to delete self IP " + vlanSelfIp); - } - } - - if (inline) { - List allRouteDomains = getRouteDomains(); - if (allRouteDomains.contains(vlanTag)) { - s_logger.debug("Deleting route domain " + vlanTag); - _routeDomainApi.delete_route_domain(genLongArray(vlanTag)); - - if (getRouteDomains().contains(vlanTag)) { - throw new ExecutionException("Failed to delete route domain " + vlanTag); - } - } - } - - String vlanName = genVlanName(vlanTag); - List allVlans = getStrippedVlans(); - if (allVlans.contains(vlanName)) { - _vlanApi.delete_vlan(genStringArray(vlanName)); - - if (getVlans().contains(vlanName)) { - throw new ExecutionException("Failed to delete VLAN with tag: " + vlanTag); - } - } - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private void deleteVirtualServersInGuestVlan(String vlanSelfIp, String vlanNetmask) throws ExecutionException { - vlanSelfIp = stripRouteDomainFromAddress(vlanSelfIp); - List virtualServersToDelete = new ArrayList(); - - List allVirtualServers = getStrippedVirtualServers(); - for (String virtualServerName : allVirtualServers) { - // Check if the virtual server's default pool has members in this guest VLAN - List poolMembers = getMembers(virtualServerName); - for (String poolMemberName : poolMembers) { - String poolMemberIp = stripRouteDomainFromAddress(getIpAndPort(poolMemberName)[0]); - if (NetUtils.sameSubnet(vlanSelfIp, poolMemberIp, vlanNetmask)) { - virtualServersToDelete.add(virtualServerName); - break; - } - } - } - - for (String virtualServerName : virtualServersToDelete) { - s_logger.debug("Found a virtual server (" + virtualServerName + ") for guest network with self IP " + vlanSelfIp + - " that is active when the guest network is being destroyed."); - deleteVirtualServerAndDefaultPool(virtualServerName); - } - } - - private String genVlanName(long vlanTag) { - return "vlan-" + String.valueOf(vlanTag); - } - - private List getRouteDomains() throws ExecutionException { - try { - List routeDomains = new ArrayList(); - long[] routeDomainsArray = _routeDomainApi.get_list(); - - for (long routeDomainName : routeDomainsArray) { - routeDomains.add(routeDomainName); - } - - return routeDomains; - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private List getSelfIps() throws ExecutionException { - try { - List selfIps = new ArrayList(); - String[] selfIpsArray = _selfIpApi.get_list(); - - for (String selfIp : selfIpsArray) { - selfIps.add(selfIp); - } - - return selfIps; - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - //This was working with Big IP 10.x - //getVlans retuns vlans with user partition information - //ex: if vlanname is vlan-100 then the get_list() will return /Common/vlan-100 - private List getVlans() throws ExecutionException { - try { - List vlans = new ArrayList(); - String[] vlansArray = _vlanApi.get_list(); - - for (String vlan : vlansArray) { - vlans.add(vlan); - } - - return vlans; - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - //getVlans retuns vlan names without user partition information - //ex: if vlanname is vlan-100 then the get_list() will return /Common/vlan-100 - // This method will strip the partition information and only returns a list with vlan name (vlan-100) - private List getStrippedVlans() throws ExecutionException { - try { - List vlans = new ArrayList(); - String[] vlansArray = _vlanApi.get_list(); - - for (String vlan : vlansArray) { - if(vlan.contains("/")){ - vlans.add(vlan.substring(vlan.lastIndexOf("/") + 1)); - }else{ - vlans.add(vlan); - } - } - - return vlans; - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - // Login - - private void login() throws ExecutionException { - try { - _interfaces = new Interfaces(); - - if (!_interfaces.initialize(_ip, _username, _password)) { - throw new ExecutionException("Failed to log in to BigIp appliance"); - } - - // iControl.Interfaces.initialize always return true so make a call to force connect to F5 to validate credentials - _interfaces.getSystemSystemInfo().get_system_information(); - - _virtualServerApi = _interfaces.getLocalLBVirtualServer(); - _loadbalancerApi = _interfaces.getLocalLBPool(); - _nodeApi = _interfaces.getLocalLBNodeAddress(); - _vlanApi = _interfaces.getNetworkingVLAN(); - _selfIpApi = _interfaces.getNetworkingSelfIP(); - _routeDomainApi = _interfaces.getNetworkingRouteDomain(); - _configSyncApi = _interfaces.getSystemConfigSync(); - _persistenceProfileApi = _interfaces.getLocalLBProfilePersistence(); - } catch (Exception e) { - throw new ExecutionException("Failed to log in to BigIp appliance due to " + e.getMessage()); - } - } - - // 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> paramsList = stickinessPolicy.getParams(); - for (Pair param : paramsList) { - if ("holdtime".equalsIgnoreCase(param.first())) { - long timeout = 180; //F5 default - 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()); - } - } - - private void deleteVirtualServerAndDefaultPool(String virtualServerName) throws ExecutionException { - try { - if (virtualServerExists(virtualServerName)) { - // Delete the default pool's members - List poolMembers = getMembers(virtualServerName); - for (String poolMember : poolMembers) { - String[] destIpAndPort = getIpAndPort(poolMember); - deletePoolMember(virtualServerName, destIpAndPort[0], Integer.parseInt(destIpAndPort[1])); - } - - // Delete the virtual server - s_logger.debug("Deleting virtual server " + virtualServerName); - _virtualServerApi.delete_virtual_server(genStringArray(virtualServerName)); - - if (getStrippedVirtualServers().contains(virtualServerName)) { - throw new ExecutionException("Failed to delete virtual server " + virtualServerName); - } - - // Delete the default pool - deletePool(virtualServerName); - } - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private String genVirtualServerName(LbProtocol protocol, String srcIp, long srcPort) { - srcIp = stripRouteDomainFromAddress(srcIp); - return genObjectName("vs", protocol, srcIp, srcPort); - } - - private boolean virtualServerExists(String virtualServerName) throws ExecutionException { - return getStrippedVirtualServers().contains(virtualServerName); - } - - //This was working with Big IP 10.x - //getVirtualServers retuns VirtualServers with user partition information - //ex: if VirtualServers is vs-tcp-10.147.44.8-22 then the get_list() will return /Common/vs-tcp-10.147.44.8-22 - private List getVirtualServers() throws ExecutionException { - try { - List virtualServers = new ArrayList(); - String[] virtualServersArray = _virtualServerApi.get_list(); - - for (String virtualServer : virtualServersArray) { - virtualServers.add(virtualServer); - } - - return virtualServers; - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - -/* getStrippedVirtualServers retuns VirtualServers without user partition information - ex: if VirtualServers is vs-tcp-10.147.44.8-22 then the get_list() will return /Common/vs-tcp-10.147.44.8-22 - This method will strip the partition information and only returns a list with VirtualServers (vs-tcp-10.147.44.8-22)*/ - private List getStrippedVirtualServers() throws ExecutionException { - try { - List virtualServers = new ArrayList(); - String[] virtualServersArray = _virtualServerApi.get_list(); - - for (String virtualServer : virtualServersArray) { - if(virtualServer.contains("/")){ - virtualServers.add(virtualServer.substring(virtualServer.lastIndexOf("/") + 1)); - }else{ - virtualServers.add(virtualServer); - } - } - - return virtualServers; - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private boolean persistenceProfileExists(String profileName) throws ExecutionException { - try { - String[] persistenceProfileArray = _persistenceProfileApi.get_list(); - if (persistenceProfileArray == null) { - return false; - } - for (String profile : persistenceProfileArray) { - if (profile.equalsIgnoreCase(profileName)) { - return true; - } - } - return false; - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private iControl.CommonVirtualServerDefinition[] genVirtualServerDefinition(String name, LbProtocol protocol, String srcIp, long srcPort) { - CommonVirtualServerDefinition vsDefs[] = {new CommonVirtualServerDefinition()}; - vsDefs[0].setName(name); - vsDefs[0].setAddress(srcIp); - vsDefs[0].setPort(srcPort); - - if (protocol.equals(LbProtocol.tcp)) { - vsDefs[0].setProtocol(iControl.CommonProtocolType.PROTOCOL_TCP); - } else if (protocol.equals(LbProtocol.udp)) { - vsDefs[0].setProtocol(iControl.CommonProtocolType.PROTOCOL_UDP); - } - - return vsDefs; - } - - private iControl.LocalLBVirtualServerVirtualServerResource[] genVirtualServerResource(String poolName) { - LocalLBVirtualServerVirtualServerResource vsRes[] = {new LocalLBVirtualServerVirtualServerResource()}; - vsRes[0].setType(LocalLBVirtualServerVirtualServerType.RESOURCE_TYPE_POOL); - vsRes[0].setDefault_pool_name(poolName); - return vsRes; - } - - private LocalLBVirtualServerVirtualServerProfile[][] genVirtualServerProfile(LbProtocol protocol) { - LocalLBVirtualServerVirtualServerProfile vsProfs[][] = {{new LocalLBVirtualServerVirtualServerProfile()}}; - vsProfs[0][0].setProfile_context(LocalLBProfileContextType.PROFILE_CONTEXT_TYPE_ALL); - - if (protocol.equals(LbProtocol.tcp)) { - vsProfs[0][0].setProfile_name("http"); - } else if (protocol.equals(LbProtocol.udp)) { - vsProfs[0][0].setProfile_name("udp"); - } - - return vsProfs; - } - - private LocalLBVirtualServerVirtualServerPersistence[][] genPersistenceProfile(String persistenceProfileName) { - LocalLBVirtualServerVirtualServerPersistence[][] persistenceProfs = {{new LocalLBVirtualServerVirtualServerPersistence()}}; - persistenceProfs[0][0].setDefault_profile(true); - persistenceProfs[0][0].setProfile_name(persistenceProfileName); - return persistenceProfs; - } - - // Load balancing pool methods - - private void addPool(String virtualServerName, LbAlgorithm algorithm) throws ExecutionException { - try { - if (!poolExists(virtualServerName)) { - if (algorithm.getPersistenceProfileName() != null) { - algorithm = LbAlgorithm.RoundRobin; - } - - s_logger.debug("Adding pool for virtual server " + virtualServerName + " with algorithm " + algorithm); - _loadbalancerApi.create(genStringArray(virtualServerName), genLbMethod(algorithm), genEmptyMembersArray()); - - if (!poolExists(virtualServerName)) { - throw new ExecutionException("Failed to create new pool for virtual server " + virtualServerName); - } - } - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private void deletePool(String virtualServerName) throws ExecutionException { - try { - if (poolExists(virtualServerName) && getMembers(virtualServerName).size() == 0) { - s_logger.debug("Deleting pool for virtual server " + virtualServerName); - _loadbalancerApi.delete_pool(genStringArray(virtualServerName)); - - if (poolExists(virtualServerName)) { - throw new ExecutionException("Failed to delete pool for virtual server " + virtualServerName); - } - } - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private void addPoolMember(String virtualServerName, String destIp, int destPort) throws ExecutionException { - try { - String memberIdentifier = destIp + "-" + destPort; - - if (poolExists(virtualServerName) && !memberExists(virtualServerName, memberIdentifier)) { - s_logger.debug("Adding member " + memberIdentifier + " into pool for virtual server " + virtualServerName); - _loadbalancerApi.add_member(genStringArray(virtualServerName), genMembers(destIp, destPort)); - - if (!memberExists(virtualServerName, memberIdentifier)) { - throw new ExecutionException("Failed to add new member " + memberIdentifier + " into pool for virtual server " + virtualServerName); - } - } - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private void deleteInactivePoolMembers(String virtualServerName, List activePoolMembers) throws ExecutionException { - List allPoolMembers = getMembers(virtualServerName); - - for (String member : allPoolMembers) { - if (!activePoolMembers.contains(member)) { - String[] ipAndPort = member.split("-"); - deletePoolMember(virtualServerName, ipAndPort[0], Integer.parseInt(ipAndPort[1])); - } - } - } - - private void deletePoolMember(String virtualServerName, String destIp, int destPort) throws ExecutionException { - try { - String memberIdentifier = destIp + "-" + destPort; - List lbPools = getAllStrippedLbPools(); - - if (lbPools.contains(virtualServerName) && memberExists(virtualServerName, memberIdentifier)) { - s_logger.debug("Deleting member " + memberIdentifier + " from pool for virtual server " + virtualServerName); - _loadbalancerApi.remove_member(genStringArray(virtualServerName), genMembers(destIp, destPort)); - - if (memberExists(virtualServerName, memberIdentifier)) { - throw new ExecutionException("Failed to delete member " + memberIdentifier + " from pool for virtual server " + virtualServerName); - } - - if (nodeExists(destIp)) { - boolean nodeNeeded = false; - done: for (String poolToCheck : lbPools) { - for (String memberInPool : getMembers(poolToCheck)) { - if (getIpAndPort(memberInPool)[0].equals(destIp)) { - nodeNeeded = true; - break done; - } - } - } - - if (!nodeNeeded) { - s_logger.debug("Deleting node " + destIp); - _nodeApi.delete_node_address(genStringArray(destIp)); - - if (nodeExists(destIp)) { - throw new ExecutionException("Failed to delete node " + destIp); - } - } - } - } - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private boolean poolExists(String poolName) throws ExecutionException { - return getAllStrippedLbPools().contains(poolName); - } - - private boolean memberExists(String poolName, String memberIdentifier) throws ExecutionException { - return getMembers(poolName).contains(memberIdentifier); - } - - private boolean nodeExists(String destIp) throws RemoteException { - return getNodes().contains(destIp); - } - - private String[] getIpAndPort(String memberIdentifier) { - return memberIdentifier.split("-"); - } - - //This was working with Big IP 10.x - //getAllLbPools retuns LbPools with user partition information - //ex: if LbPools is vs-tcp-10.147.44.8-22 then the get_list() will return /Common/vs-tcp-10.147.44.8-22 - public List getAllLbPools() throws ExecutionException { - try { - List lbPools = new ArrayList(); - String[] pools = _loadbalancerApi.get_list(); - - for (String pool : pools) { - lbPools.add(pool); - } - - return lbPools; - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - //Big IP 11.x - //getAllLbPools retuns LbPools without user partition information - //ex: if LbPools is vs-tcp-10.147.44.8-22 then the get_list() will return /Common/vs-tcp-10.147.44.8-22 - //This method will strip the partition information and only returns a list with LbPools (vs-tcp-10.147.44.8-22) - public List getAllStrippedLbPools() throws ExecutionException { - try { - List lbPools = new ArrayList(); - String[] pools = _loadbalancerApi.get_list(); - - for (String pool : pools) { - if(pool.contains("/")){ - lbPools.add(pool.substring(pool.lastIndexOf("/") + 1)); - }else{ - lbPools.add(pool); - } - } - return lbPools; - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private List getMembers(String virtualServerName) throws ExecutionException { - try { - List members = new ArrayList(); - String[] virtualServerNames = genStringArray(virtualServerName); - CommonIPPortDefinition[] membersArray = _loadbalancerApi.get_member(virtualServerNames)[0]; - - for (CommonIPPortDefinition member : membersArray) { - members.add(member.getAddress() + "-" + member.getPort()); - } - - return members; - } catch (RemoteException e) { - throw new ExecutionException(e.getMessage()); - } - } - - private List getNodes() throws RemoteException { - List nodes = new ArrayList(); - String[] nodesArray = _nodeApi.get_list(); - - for (String node : nodesArray) { - nodes.add(node); - } - - return nodes; - } - - private iControl.CommonIPPortDefinition[][] genMembers(String destIp, long destPort) { - iControl.CommonIPPortDefinition[] membersInnerArray = new iControl.CommonIPPortDefinition[1]; - membersInnerArray[0] = new iControl.CommonIPPortDefinition(destIp, destPort); - return new iControl.CommonIPPortDefinition[][] {membersInnerArray}; - } - - private iControl.CommonIPPortDefinition[][] genEmptyMembersArray() { - iControl.CommonIPPortDefinition[] membersInnerArray = new iControl.CommonIPPortDefinition[0]; - return new iControl.CommonIPPortDefinition[][] {membersInnerArray}; - } - - private LocalLBLBMethod[] genLbMethod(LbAlgorithm algorithm) { - if (algorithm.getMethod() != null) { - return new LocalLBLBMethod[] {algorithm.getMethod()}; - } else { - return new LocalLBLBMethod[] {LbAlgorithm.RoundRobin.getMethod()}; - } - } - - // Stats methods - - private ExternalNetworkResourceUsageAnswer getIpBytesSentAndReceived(ExternalNetworkResourceUsageCommand cmd) throws ExecutionException { - ExternalNetworkResourceUsageAnswer answer = new ExternalNetworkResourceUsageAnswer(cmd); - - try { - - LocalLBVirtualServerVirtualServerStatistics stats = _virtualServerApi.get_all_statistics(); - for (LocalLBVirtualServerVirtualServerStatisticEntry entry : stats.getStatistics()) { - String virtualServerIp = entry.getVirtual_server().getAddress(); - - virtualServerIp = stripRouteDomainFromAddress(virtualServerIp); - - long[] bytesSentAndReceived = answer.ipBytes.get(virtualServerIp); - - if (bytesSentAndReceived == null) { - bytesSentAndReceived = new long[] {0, 0}; - } - - for (CommonStatistic stat : entry.getStatistics()) { - int index; - if (stat.getType().equals(CommonStatisticType.STATISTIC_CLIENT_SIDE_BYTES_OUT)) { - // Add to the outgoing bytes - index = 0; - } else if (stat.getType().equals(CommonStatisticType.STATISTIC_CLIENT_SIDE_BYTES_IN)) { - // Add to the incoming bytes - index = 1; - } else { - continue; - } - - long high = stat.getValue().getHigh(); - long low = stat.getValue().getLow(); - long full = getFullUsage(high, low); - - bytesSentAndReceived[index] += full; - } - - if (bytesSentAndReceived[0] >= 0 && bytesSentAndReceived[1] >= 0) { - answer.ipBytes.put(virtualServerIp, bytesSentAndReceived); - } - } - } catch (Exception e) { - s_logger.error(e); - throw new ExecutionException(e.getMessage()); - } - - return answer; - } - - private long getFullUsage(long high, long low) { - Double full; - Double rollOver = new Double(0x7fffffff); - rollOver = new Double(rollOver.doubleValue() + 1.0); - - if (high >= 0) { - // shift left 32 bits and mask off new bits to 0's - full = new Double((high << 32 & 0xffff0000)); - } else { - // mask off sign bits + shift left by 32 bits then add the sign bit back - full = new Double(((high & 0x7fffffff) << 32) + (0x80000000 << 32)); - } - - if (low >= 0) { - // add low to full and we're good - full = new Double(full.doubleValue() + low); - } else { - // add full to low after masking off sign bits and adding 1 to the masked off low order value - full = new Double(full.doubleValue() + ((low & 0x7fffffff)) + rollOver.doubleValue()); - } - - return full.longValue(); - } - - // Misc methods - - private String tagAddressWithRouteDomain(String address, long vlanTag) { - return address + _routeDomainIdentifier + vlanTag; - } - - private String stripRouteDomainFromAddress(String address) { - int i = address.indexOf(_routeDomainIdentifier); - - if (i > 0) { - address = address.substring(0, i); - } - - return address; - } - - private String genObjectName(Object... args) { - String objectName = ""; - - for (int i = 0; i < args.length; i++) { - objectName += args[i]; - if (i != args.length - 1) { - objectName += _objectNamePathSep; - } - } - - return objectName; - } - - private long[] genLongArray(long l) { - return new long[] {l}; - } - - private static String[] genStringArray(String s) { - return new String[] {s}; - } - - @Override - public void setName(String name) { - // TODO Auto-generated method stub - - } - - @Override - public void setConfigParams(Map params) { - // TODO Auto-generated method stub - - } - - @Override - public Map getConfigParams() { - // TODO Auto-generated method stub - return null; - } - - @Override - public int getRunLevel() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void setRunLevel(int level) { - // TODO Auto-generated method stub - - } - -} diff --git a/plugins/network-elements/f5/src/main/resources/META-INF/cloudstack/f5/module.properties b/plugins/network-elements/f5/src/main/resources/META-INF/cloudstack/f5/module.properties deleted file mode 100644 index efdb64a89e7..00000000000 --- a/plugins/network-elements/f5/src/main/resources/META-INF/cloudstack/f5/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -name=f5 -parent=network \ No newline at end of file diff --git a/plugins/network-elements/f5/src/main/resources/META-INF/cloudstack/f5/spring-f5-context.xml b/plugins/network-elements/f5/src/main/resources/META-INF/cloudstack/f5/spring-f5-context.xml deleted file mode 100644 index 10af4625593..00000000000 --- a/plugins/network-elements/f5/src/main/resources/META-INF/cloudstack/f5/spring-f5-context.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/juniper-srx/pom.xml b/plugins/network-elements/juniper-srx/pom.xml deleted file mode 100644 index a167bb7bb2d..00000000000 --- a/plugins/network-elements/juniper-srx/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - 4.0.0 - cloud-plugin-network-srx - Apache CloudStack Plugin - Juniper SRX - - org.apache.cloudstack - cloudstack-plugins - 4.18.0.0-SNAPSHOT - ../../pom.xml - - - - com.cloud.com.f5 - icontrol - 1.0 - - - diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/AddExternalFirewallCmd.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/AddExternalFirewallCmd.java deleted file mode 100644 index 36d542afbe4..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/AddExternalFirewallCmd.java +++ /dev/null @@ -1,110 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ExternalFirewallResponse; -import org.apache.cloudstack.api.response.ZoneResponse; - -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.Host; -import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.user.Account; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "addExternalFirewall", description = "Adds an external firewall appliance", responseObject = ExternalFirewallResponse.class, - requestHasSensitiveInfo = true, responseHasSensitiveInfo = false) -public class AddExternalFirewallCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddExternalFirewallCmd.class.getName()); - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.ZONE_ID, - type = CommandType.UUID, - entityType = ZoneResponse.class, - required = true, - description = "Zone in which to add the external firewall appliance.") - private Long zoneId; - - @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = true, description = "URL of the external firewall appliance.") - private String url; - - @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Username of the external firewall appliance.") - private String username; - - @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Password of the external firewall appliance.") - private String password; - - /////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getZoneId() { - return zoneId; - } - - public String getUrl() { - return url; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Inject - JuniperSRXFirewallElementService _srxElementService; - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - - @SuppressWarnings("deprecation") - @Override - public void execute() { - try { - Host externalFirewall = _srxElementService.addExternalFirewall(this); - ExternalFirewallResponse response = _srxElementService.createExternalFirewallResponse(externalFirewall); - response.setObjectName("externalfirewall"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage()); - } catch (CloudRuntimeException cre) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage()); - } - } -} diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/AddSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/AddSrxFirewallCmd.java deleted file mode 100644 index db3fbf7fa45..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/AddSrxFirewallCmd.java +++ /dev/null @@ -1,135 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.SrxFirewallResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.dao.ExternalFirewallDeviceVO; -import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "addSrxFirewall", responseObject = SrxFirewallResponse.class, description = "Adds a SRX firewall device", - requestHasSensitiveInfo = true, responseHasSensitiveInfo = false) -public class AddSrxFirewallCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(AddSrxFirewallCmd.class.getName()); - @Inject - JuniperSRXFirewallElementService _srxFwService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, - type = CommandType.UUID, - entityType = PhysicalNetworkResponse.class, - required = true, - description = "the Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = true, description = "URL of the SRX appliance.") - private String url; - - @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Credentials to reach SRX firewall device") - private String username; - - @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Credentials to reach SRX firewall device") - private String password; - - @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, required = true, description = "supports only JuniperSRXFirewall") - private String deviceType; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public String getUrl() { - return url; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public String getDeviceType() { - return deviceType; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - ExternalFirewallDeviceVO fwDeviceVO = _srxFwService.addSrxFirewall(this); - if (fwDeviceVO != null) { - SrxFirewallResponse response = _srxFwService.createSrxFirewallResponse(fwDeviceVO); - response.setObjectName("srxfirewall"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add SRX firewall due to internal error."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getEventDescription() { - return "Adding a SRX firewall device"; - } - - @Override - public String getEventType() { - return EventTypes.EVENT_EXTERNAL_FIREWALL_DEVICE_ADD; - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } -} diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ConfigureSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ConfigureSrxFirewallCmd.java deleted file mode 100644 index fcf1a2b3fa7..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ConfigureSrxFirewallCmd.java +++ /dev/null @@ -1,117 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.SrxFirewallResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.dao.ExternalFirewallDeviceVO; -import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "configureSrxFirewall", responseObject = SrxFirewallResponse.class, description = "Configures a SRX firewall device", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ConfigureSrxFirewallCmd extends BaseAsyncCmd { - - public static final Logger s_logger = Logger.getLogger(ConfigureSrxFirewallCmd.class.getName()); - @Inject - JuniperSRXFirewallElementService _srxFwService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.FIREWALL_DEVICE_ID, - type = CommandType.UUID, - entityType = SrxFirewallResponse.class, - required = true, - description = "SRX firewall device ID") - private Long fwDeviceId; - - @Parameter(name = ApiConstants.FIREWALL_DEVICE_CAPACITY, - type = CommandType.LONG, - required = false, - description = "capacity of the firewall device, Capacity will be interpreted as number of networks device can handle") - private Long capacity; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getFirewallDeviceId() { - return fwDeviceId; - } - - public Long getFirewallCapacity() { - return capacity; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - ExternalFirewallDeviceVO fwDeviceVO = _srxFwService.configureSrxFirewall(this); - if (fwDeviceVO != null) { - SrxFirewallResponse response = _srxFwService.createSrxFirewallResponse(fwDeviceVO); - response.setObjectName("srxfirewall"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to configure SRX firewall device due to internal error."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getEventDescription() { - return "Configuring a SRX firewall device"; - } - - @Override - public String getEventType() { - return EventTypes.EVENT_EXTERNAL_FIREWALL_DEVICE_CONFIGURE; - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } -} diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/DeleteExternalFirewallCmd.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/DeleteExternalFirewallCmd.java deleted file mode 100644 index d5a3619e399..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/DeleteExternalFirewallCmd.java +++ /dev/null @@ -1,84 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.HostResponse; -import org.apache.cloudstack.api.response.SuccessResponse; - -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.user.Account; - -@APICommand(name = "deleteExternalFirewall", description = "Deletes an external firewall appliance.", responseObject = SuccessResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class DeleteExternalFirewallCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteExternalFirewallCmd.class.getName()); - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = HostResponse.class, required = true, description = "Id of the external firewall appliance.") - private Long id; - - /////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getId() { - return id; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Inject - JuniperSRXFirewallElementService _srxElementService; - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - - @SuppressWarnings("deprecation") - @Override - public void execute() { - try { - boolean result = _srxElementService.deleteExternalFirewall(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete external firewall."); - } - } catch (InvalidParameterValueException e) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Failed to delete external firewall."); - } - } -} diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/DeleteSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/DeleteSrxFirewallCmd.java deleted file mode 100644 index b5964016ad1..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/DeleteSrxFirewallCmd.java +++ /dev/null @@ -1,105 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.SrxFirewallResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "deleteSrxFirewall", responseObject = SuccessResponse.class, description = " delete a SRX firewall device", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class DeleteSrxFirewallCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteSrxFirewallCmd.class.getName()); - @Inject - JuniperSRXFirewallElementService _srxElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.FIREWALL_DEVICE_ID, - type = CommandType.UUID, - entityType = SrxFirewallResponse.class, - required = true, - description = "srx firewall device ID") - private Long fwDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getFirewallDeviceId() { - return fwDeviceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - boolean result = _srxElementService.deleteSrxFirewall(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete SRX firewall device"); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getEventDescription() { - return "Deleting SRX firewall device"; - } - - @Override - public String getEventType() { - return EventTypes.EVENT_EXTERNAL_FIREWALL_DEVICE_DELETE; - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } -} diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListExternalFirewallsCmd.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListExternalFirewallsCmd.java deleted file mode 100644 index 4e2c26e4b12..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListExternalFirewallsCmd.java +++ /dev/null @@ -1,83 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.ExternalFirewallResponse; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.ZoneResponse; - -import com.cloud.host.Host; -import com.cloud.network.element.JuniperSRXFirewallElementService; - -@APICommand(name = "listExternalFirewalls", description = "List external firewall appliances.", responseObject = ExternalFirewallResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListExternalFirewallsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListExternalFirewallsCmd.class.getName()); - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = true, description = "zone Id") - private long zoneId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public long getZoneId() { - return zoneId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Inject - JuniperSRXFirewallElementService _srxElementService; - - @SuppressWarnings("deprecation") - @Override - public void execute() { - - List externalFirewalls = _srxElementService.listExternalFirewalls(this); - - ListResponse listResponse = new ListResponse(); - List responses = new ArrayList(); - for (Host externalFirewall : externalFirewalls) { - ExternalFirewallResponse response = _srxElementService.createExternalFirewallResponse(externalFirewall); - response.setObjectName("externalfirewall"); - response.setResponseName(getCommandName()); - responses.add(response); - } - - listResponse.setResponses(responses); - listResponse.setResponseName(getCommandName()); - this.setResponseObject(listResponse); - } -} diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java deleted file mode 100644 index f8d3f8f63dc..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java +++ /dev/null @@ -1,102 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ResponseObject.ResponseView; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.NetworkResponse; - -import com.cloud.api.response.SrxFirewallResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Network; -import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listSrxFirewallNetworks", responseObject = NetworkResponse.class, description = "lists network that are using SRX firewall device", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListSrxFirewallNetworksCmd extends BaseListCmd { - - public static final Logger s_logger = Logger.getLogger(ListSrxFirewallNetworksCmd.class.getName()); - @Inject - JuniperSRXFirewallElementService _srxFwService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.LOAD_BALANCER_DEVICE_ID, - type = CommandType.UUID, - entityType = SrxFirewallResponse.class, - required = true, - description = "netscaler load balancer device ID") - private Long fwDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getFirewallDeviceId() { - return fwDeviceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - List networks = _srxFwService.listNetworks(this); - ListResponse response = new ListResponse(); - List networkResponses = new ArrayList(); - - if (networks != null && !networks.isEmpty()) { - for (Network network : networks) { - NetworkResponse networkResponse = _responseGenerator.createNetworkResponse(ResponseView.Full, network); - networkResponses.add(networkResponse); - } - } - - response.setResponses(networkResponses); - response.setResponseName(getCommandName()); - setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - } diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListSrxFirewallsCmd.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListSrxFirewallsCmd.java deleted file mode 100644 index 244da1bb632..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/commands/ListSrxFirewallsCmd.java +++ /dev/null @@ -1,109 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; - -import com.cloud.api.response.SrxFirewallResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.dao.ExternalFirewallDeviceVO; -import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listSrxFirewalls", responseObject = SrxFirewallResponse.class, description = "lists SRX firewall devices in a physical network", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListSrxFirewallsCmd extends BaseListCmd { - - public static final Logger s_logger = Logger.getLogger(ListSrxFirewallsCmd.class.getName()); - private static final String s_name = "listsrxfirewallresponse"; - @Inject - JuniperSRXFirewallElementService _srxFwService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "the Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.FIREWALL_DEVICE_ID, type = CommandType.UUID, entityType = SrxFirewallResponse.class, description = "SRX firewall device ID") - private Long fwDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getFirewallDeviceId() { - return fwDeviceId; - } - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - List fwDevices = _srxFwService.listSrxFirewalls(this); - ListResponse response = new ListResponse(); - List fwDevicesResponse = new ArrayList(); - - if (fwDevices != null && !fwDevices.isEmpty()) { - for (ExternalFirewallDeviceVO fwDeviceVO : fwDevices) { - SrxFirewallResponse lbdeviceResponse = _srxFwService.createSrxFirewallResponse(fwDeviceVO); - fwDevicesResponse.add(lbdeviceResponse); - } - } - - response.setResponses(fwDevicesResponse); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } -} diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/response/SrxFirewallResponse.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/response/SrxFirewallResponse.java deleted file mode 100644 index 21c5721811d..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/api/response/SrxFirewallResponse.java +++ /dev/null @@ -1,159 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.network.dao.ExternalFirewallDeviceVO; -import com.cloud.serializer.Param; - -@EntityReference(value = ExternalFirewallDeviceVO.class) -@SuppressWarnings("unused") -public class SrxFirewallResponse extends BaseResponse { - - @SerializedName(ApiConstants.FIREWALL_DEVICE_ID) - @Param(description = "device id of the SRX firewall") - private String id; - - @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) - @Param(description = "the physical network to which this SRX firewall belongs to") - private String physicalNetworkId; - - @SerializedName(ApiConstants.PROVIDER) - @Param(description = "name of the provider") - private String providerName; - - @SerializedName(ApiConstants.FIREWALL_DEVICE_NAME) - @Param(description = "device name") - private String deviceName; - - @SerializedName(ApiConstants.FIREWALL_DEVICE_STATE) - @Param(description = "device state") - private String deviceState; - - @SerializedName(ApiConstants.FIREWALL_DEVICE_CAPACITY) - @Param(description = "device capacity") - private Long deviceCapacity; - - @SerializedName(ApiConstants.ZONE_ID) - @Param(description = "the zone ID of the external firewall") - private String zoneId; - - @SerializedName(ApiConstants.IP_ADDRESS) - @Param(description = "the management IP address of the external firewall") - private String ipAddress; - - @SerializedName(ApiConstants.USERNAME) - @Param(description = "the username that's used to log in to the external firewall") - private String username; - - @SerializedName(ApiConstants.PUBLIC_INTERFACE) - @Param(description = "the public interface of the external firewall") - private String publicInterface; - - @SerializedName(ApiConstants.USAGE_INTERFACE) - @Param(description = "the usage interface of the external firewall") - private String usageInterface; - - @SerializedName(ApiConstants.PRIVATE_INTERFACE) - @Param(description = "the private interface of the external firewall") - private String privateInterface; - - @SerializedName(ApiConstants.PUBLIC_ZONE) - @Param(description = "the public security zone of the external firewall") - private String publicZone; - - @SerializedName(ApiConstants.PRIVATE_ZONE) - @Param(description = "the private security zone of the external firewall") - private String privateZone; - - @SerializedName(ApiConstants.NUM_RETRIES) - @Param(description = "the number of times to retry requests to the external firewall") - private String numRetries; - - @SerializedName(ApiConstants.TIMEOUT) - @Param(description = "the timeout (in seconds) for requests to the external firewall") - private String timeout; - - public void setId(String lbDeviceId) { - this.id = lbDeviceId; - } - - public void setPhysicalNetworkId(String physicalNetworkId) { - this.physicalNetworkId = physicalNetworkId; - } - - public void setProvider(String provider) { - this.providerName = provider; - } - - public void setDeviceName(String deviceName) { - this.deviceName = deviceName; - } - - public void setDeviceCapacity(long deviceCapacity) { - this.deviceCapacity = deviceCapacity; - } - - public void setDeviceState(String deviceState) { - this.deviceState = deviceState; - } - - public void setIpAddress(String ipAddress) { - this.ipAddress = ipAddress; - } - - public void setPublicInterface(String publicInterface) { - this.publicInterface = publicInterface; - } - - public void setUsageInterface(String usageInterface) { - this.usageInterface = usageInterface; - } - - public void setPrivateInterface(String privateInterface) { - this.privateInterface = privateInterface; - } - - public void setPublicZone(String publicZone) { - this.publicZone = publicZone; - } - - public void setPrivateZone(String privateZone) { - this.privateZone = privateZone; - } - - public String getNumRetries() { - return numRetries; - } - - public void setNumRetries(String numRetries) { - this.numRetries = numRetries; - } - - public String getTimeout() { - return timeout; - } - - public void setTimeout(String timeout) { - this.timeout = timeout; - } -} diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/element/JuniperSRXExternalFirewallElement.java deleted file mode 100644 index baa05124983..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ /dev/null @@ -1,551 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.element; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; - -import org.apache.log4j.Logger; - -import org.apache.cloudstack.api.response.ExternalFirewallResponse; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; - -import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.AddExternalFirewallCmd; -import com.cloud.api.commands.AddSrxFirewallCmd; -import com.cloud.api.commands.ConfigureSrxFirewallCmd; -import com.cloud.api.commands.DeleteExternalFirewallCmd; -import com.cloud.api.commands.DeleteSrxFirewallCmd; -import com.cloud.api.commands.ListExternalFirewallsCmd; -import com.cloud.api.commands.ListSrxFirewallNetworksCmd; -import com.cloud.api.commands.ListSrxFirewallsCmd; -import com.cloud.api.response.SrxFirewallResponse; -import com.cloud.configuration.Config; -import com.cloud.configuration.ConfigurationManager; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InsufficientNetworkCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.ExternalFirewallDeviceManagerImpl; -import com.cloud.network.Network; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.dao.ExternalFirewallDeviceDao; -import com.cloud.network.dao.ExternalFirewallDeviceVO; -import com.cloud.network.dao.ExternalFirewallDeviceVO.FirewallDeviceState; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkExternalFirewallDao; -import com.cloud.network.dao.NetworkExternalFirewallVO; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.network.resource.JuniperSrxResource; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.PortForwardingRule; -import com.cloud.network.rules.StaticNat; -import com.cloud.offering.NetworkOffering; -import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.db.EntityManager; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; - -public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceManagerImpl implements SourceNatServiceProvider, FirewallServiceProvider, - PortForwardingServiceProvider, IpDeployer, JuniperSRXFirewallElementService, StaticNatServiceProvider { - - private static final Logger s_logger = Logger.getLogger(JuniperSRXExternalFirewallElement.class); - - private static final Map> capabilities = setCapabilities(); - - @Inject - NetworkModel _networkManager; - @Inject - HostDao _hostDao; - @Inject - ConfigurationManager _configMgr; - @Inject - NetworkOfferingDao _networkOfferingDao; - @Inject - NetworkDao _networksDao; - @Inject - DataCenterDao _dcDao; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - ExternalFirewallDeviceDao _fwDevicesDao; - @Inject - NetworkExternalFirewallDao _networkFirewallDao; - @Inject - NetworkDao _networkDao; - @Inject - NetworkServiceMapDao _ntwkSrvcDao; - @Inject - HostDetailsDao _hostDetailDao; - @Inject - ConfigurationDao _configDao; - @Inject - EntityManager _entityMgr; - - private boolean canHandle(Network network, Service service) { - DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); - if ((zone.getNetworkType() == NetworkType.Advanced && !(network.getGuestType() == Network.GuestType.Isolated || network.getGuestType() == Network.GuestType.Shared)) || - (zone.getNetworkType() == NetworkType.Basic && network.getGuestType() != Network.GuestType.Shared)) { - s_logger.trace("Element " + getProvider().getName() + "is not handling network type = " + network.getGuestType()); - return false; - } - - if (service == null) { - if (!_networkManager.isProviderForNetwork(getProvider(), network.getId())) { - s_logger.trace("Element " + getProvider().getName() + " is not a provider for the network " + network); - return false; - } - } else { - if (!_networkManager.isProviderSupportServiceInNetwork(network.getId(), service, getProvider())) { - s_logger.trace("Element " + getProvider().getName() + " doesn't support service " + service.getName() + " in the network " + network); - return false; - } - } - - return true; - } - - @Override - public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, - ConcurrentOperationException, InsufficientNetworkCapacityException { - DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); - - // don't have to implement network is Basic zone - if (zone.getNetworkType() == NetworkType.Basic) { - s_logger.debug("Not handling network implement in zone of type " + NetworkType.Basic); - return false; - } - - if (!canHandle(network, null)) { - return false; - } - - try { - return manageGuestNetworkWithExternalFirewall(true, network); - } catch (InsufficientCapacityException capacityException) { - // TODO: handle out of capacity exception in more gracefule manner when multiple providers are present for - // the network - s_logger.error("Fail to implement the JuniperSRX for network " + network, capacityException); - return false; - } - } - - @Override - public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, InsufficientNetworkCapacityException, ResourceUnavailableException { - return true; - } - - @Override - public boolean release(Network config, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) { - return true; - } - - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ResourceUnavailableException, ConcurrentOperationException { - DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); - - // don't have to implement network is Basic zone - if (zone.getNetworkType() == NetworkType.Basic) { - s_logger.debug("Not handling network shutdown in zone of type " + NetworkType.Basic); - return false; - } - - if (!canHandle(network, null)) { - return false; - } - try { - return manageGuestNetworkWithExternalFirewall(false, network); - } catch (InsufficientCapacityException capacityException) { - // TODO: handle out of capacity exception - return false; - } - } - - @Override - public boolean destroy(Network config, ReservationContext context) { - return true; - } - - @Override - public boolean applyFWRules(Network config, List rules) throws ResourceUnavailableException { - if (!canHandle(config, Service.Firewall)) { - return false; - } - - if (rules != null && rules.size() == 1) { - // for SRX no need to add default egress rule to DENY traffic - if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System && - !_networkManager.getNetworkEgressDefaultPolicy(config.getId())) - return true; - } - - return applyFirewallRules(config, rules); - } - - @Override - public Provider getProvider() { - return Provider.JuniperSRX; - } - - @Override - public Map> getCapabilities() { - return capabilities; - } - - private static Map> setCapabilities() { - Map> capabilities = new HashMap>(); - - // Set capabilities for Firewall service - Map firewallCapabilities = new HashMap(); - firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp"); - firewallCapabilities.put(Capability.SupportedEgressProtocols, "tcp,udp,icmp,all"); - firewallCapabilities.put(Capability.MultipleIps, "true"); - firewallCapabilities.put(Capability.TrafficStatistics, "per public ip"); - firewallCapabilities.put(Capability.SupportedTrafficDirection, "ingress, egress"); - capabilities.put(Service.Firewall, firewallCapabilities); - - // Disabling VPN for Juniper in Acton as it 1) Was never tested 2) probably just doesn't work -// // Set VPN capabilities -// Map vpnCapabilities = new HashMap(); -// vpnCapabilities.put(Capability.SupportedVpnTypes, "ipsec"); -// capabilities.put(Service.Vpn, vpnCapabilities); - - capabilities.put(Service.Gateway, null); - - Map sourceNatCapabilities = new HashMap(); - // Specifies that this element supports either one source NAT rule per account, or no source NAT rules at all; - // in the latter case a shared interface NAT rule will be used - sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "peraccount, perzone"); - capabilities.put(Service.SourceNat, sourceNatCapabilities); - - // Specifies that port forwarding rules are supported by this element - capabilities.put(Service.PortForwarding, null); - - // Specifies that static NAT rules are supported by this element - capabilities.put(Service.StaticNat, null); - - return capabilities; - } - - @Override - public boolean applyPFRules(Network network, List rules) throws ResourceUnavailableException { - if (!canHandle(network, Service.PortForwarding)) { - return false; - } - - return applyPortForwardingRules(network, rules); - } - - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - - List fwDevices = _fwDevicesDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.JuniperSRX.getName()); - // true if at-least one SRX device is added in to physical network and is in configured (in enabled state) state - if (fwDevices != null && !fwDevices.isEmpty()) { - for (ExternalFirewallDeviceVO fwDevice : fwDevices) { - if (fwDevice.getDeviceState() == FirewallDeviceState.Enabled) { - return true; - } - } - } - return false; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - // TODO Auto-generated method stub - return true; - } - - @Override - public boolean canEnableIndividualServices() { - return true; - } - - @Override - @Deprecated - // should use more generic addNetworkDevice command to add firewall - public - Host addExternalFirewall(AddExternalFirewallCmd cmd) { - Long zoneId = cmd.getZoneId(); - DataCenterVO zone = null; - PhysicalNetworkVO pNetwork = null; - HostVO fwHost = null; - - zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); - } - - List physicalNetworks = _physicalNetworkDao.listByZone(zoneId); - if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) { - throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: " + zoneId + - " to add this device."); - } - pNetwork = physicalNetworks.get(0); - - String deviceType = NetworkDevice.JuniperSRXFirewall.getName(); - ExternalFirewallDeviceVO fwDeviceVO = - addExternalFirewall(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, new JuniperSrxResource()); - if (fwDeviceVO != null) { - fwHost = _hostDao.findById(fwDeviceVO.getHostId()); - } - - return fwHost; - } - - @Override - public boolean deleteExternalFirewall(DeleteExternalFirewallCmd cmd) { - return deleteExternalFirewall(cmd.getId()); - } - - @Override - @Deprecated - // should use more generic listNetworkDevice command - public - List listExternalFirewalls(ListExternalFirewallsCmd cmd) { - List firewallHosts = new ArrayList(); - Long zoneId = cmd.getZoneId(); - DataCenterVO zone = null; - PhysicalNetworkVO pNetwork = null; - - if (zoneId != null) { - zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); - } - - List physicalNetworks = _physicalNetworkDao.listByZone(zoneId); - if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) { - throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: " + zoneId + - " to add this device."); - } - pNetwork = physicalNetworks.get(0); - } - - firewallHosts.addAll(listExternalFirewalls(pNetwork.getId(), NetworkDevice.JuniperSRXFirewall.getName())); - return firewallHosts; - } - - @Override - public ExternalFirewallResponse createExternalFirewallResponse(Host externalFirewall) { - return super.createExternalFirewallResponse(externalFirewall); - } - - @Override - public List> getCommands() { - List> cmdList = new ArrayList>(); - cmdList.add(AddExternalFirewallCmd.class); - cmdList.add(AddSrxFirewallCmd.class); - cmdList.add(ConfigureSrxFirewallCmd.class); - cmdList.add(DeleteExternalFirewallCmd.class); - cmdList.add(DeleteSrxFirewallCmd.class); - cmdList.add(ListExternalFirewallsCmd.class); - cmdList.add(ListSrxFirewallNetworksCmd.class); - cmdList.add(ListSrxFirewallsCmd.class); - return cmdList; - } - - @Override - public ExternalFirewallDeviceVO addSrxFirewall(AddSrxFirewallCmd cmd) { - String deviceName = cmd.getDeviceType(); - if (!deviceName.equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) { - throw new InvalidParameterValueException("Invalid SRX firewall device type"); - } - return addExternalFirewall(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, new JuniperSrxResource()); - } - - @Override - public boolean deleteSrxFirewall(DeleteSrxFirewallCmd cmd) { - Long fwDeviceId = cmd.getFirewallDeviceId(); - - ExternalFirewallDeviceVO fwDeviceVO = _fwDevicesDao.findById(fwDeviceId); - if (fwDeviceVO == null || !fwDeviceVO.getDeviceName().equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) { - throw new InvalidParameterValueException("No SRX firewall device found with ID: " + fwDeviceId); - } - return deleteExternalFirewall(fwDeviceVO.getHostId()); - } - - @Override - public ExternalFirewallDeviceVO configureSrxFirewall(ConfigureSrxFirewallCmd cmd) { - Long fwDeviceId = cmd.getFirewallDeviceId(); - Long deviceCapacity = cmd.getFirewallCapacity(); - - ExternalFirewallDeviceVO fwDeviceVO = _fwDevicesDao.findById(fwDeviceId); - if (fwDeviceVO == null || !fwDeviceVO.getDeviceName().equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) { - throw new InvalidParameterValueException("No SRX firewall device found with ID: " + fwDeviceId); - } - - if (deviceCapacity != null) { - // check if any networks are using this SRX device - List networks = _networkFirewallDao.listByFirewallDeviceId(fwDeviceId); - if ((networks != null) && !networks.isEmpty()) { - if (deviceCapacity < networks.size()) { - throw new CloudRuntimeException("There are more number of networks already using this SRX firewall device than configured capacity"); - } - } - if (deviceCapacity != null) { - fwDeviceVO.setCapacity(deviceCapacity); - } - } - - fwDeviceVO.setDeviceState(FirewallDeviceState.Enabled); - _fwDevicesDao.update(fwDeviceId, fwDeviceVO); - return fwDeviceVO; - } - - @Override - public List listSrxFirewalls(ListSrxFirewallsCmd cmd) { - Long physcialNetworkId = cmd.getPhysicalNetworkId(); - Long fwDeviceId = cmd.getFirewallDeviceId(); - PhysicalNetworkVO pNetwork = null; - List fwDevices = new ArrayList(); - - if (physcialNetworkId == null && fwDeviceId == null) { - throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified"); - } - - if (fwDeviceId != null) { - ExternalFirewallDeviceVO fwDeviceVo = _fwDevicesDao.findById(fwDeviceId); - if (fwDeviceVo == null || !fwDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) { - throw new InvalidParameterValueException("Could not find SRX firewall device with ID: " + fwDeviceId); - } - fwDevices.add(fwDeviceVo); - } - - if (physcialNetworkId != null) { - pNetwork = _physicalNetworkDao.findById(physcialNetworkId); - if (pNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physcialNetworkId); - } - fwDevices = _fwDevicesDao.listByPhysicalNetworkAndProvider(physcialNetworkId, Provider.JuniperSRX.getName()); - } - - return fwDevices; - } - - @Override - public List listNetworks(ListSrxFirewallNetworksCmd cmd) { - Long fwDeviceId = cmd.getFirewallDeviceId(); - List networks = new ArrayList(); - - ExternalFirewallDeviceVO fwDeviceVo = _fwDevicesDao.findById(fwDeviceId); - if (fwDeviceVo == null || !fwDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.JuniperSRXFirewall.getName())) { - throw new InvalidParameterValueException("Could not find SRX firewall device with ID " + fwDeviceId); - } - - List networkFirewallMaps = _networkFirewallDao.listByFirewallDeviceId(fwDeviceId); - if (networkFirewallMaps != null && !networkFirewallMaps.isEmpty()) { - for (NetworkExternalFirewallVO networkFirewallMap : networkFirewallMaps) { - NetworkVO network = _networkDao.findById(networkFirewallMap.getNetworkId()); - networks.add(network); - } - } - - return networks; - } - - @Override - public SrxFirewallResponse createSrxFirewallResponse(ExternalFirewallDeviceVO fwDeviceVO) { - SrxFirewallResponse response = new SrxFirewallResponse(); - Map fwDetails = _hostDetailDao.findDetails(fwDeviceVO.getHostId()); - Host fwHost = _hostDao.findById(fwDeviceVO.getHostId()); - - response.setId(fwDeviceVO.getUuid()); - PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(fwDeviceVO.getPhysicalNetworkId()); - if (pnw != null) { - response.setPhysicalNetworkId(pnw.getUuid()); - } - response.setDeviceName(fwDeviceVO.getDeviceName()); - if (fwDeviceVO.getCapacity() == 0) { - long defaultFwCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalFirewallCapacity.key()), 50); - response.setDeviceCapacity(defaultFwCapacity); - } else { - response.setDeviceCapacity(fwDeviceVO.getCapacity()); - } - response.setProvider(fwDeviceVO.getProviderName()); - response.setDeviceState(fwDeviceVO.getDeviceState().name()); - response.setIpAddress(fwHost.getPrivateIpAddress()); - response.setPublicInterface(fwDetails.get("publicInterface")); - response.setUsageInterface(fwDetails.get("usageInterface")); - response.setPrivateInterface(fwDetails.get("privateInterface")); - response.setPublicZone(fwDetails.get("publicZone")); - response.setPrivateZone(fwDetails.get("privateZone")); - response.setNumRetries(fwDetails.get("numRetries")); - response.setTimeout(fwDetails.get("timeout")); - response.setObjectName("srxfirewall"); - return response; - } - - @Override - public boolean verifyServicesCombination(Set services) { - if (!services.contains(Service.Firewall)) { - s_logger.warn("SRX must be used as Firewall Service Provider in the network"); - return false; - } - return true; - } - - @Override - public IpDeployer getIpDeployer(Network network) { - return this; - } - - @Override - public boolean applyIps(Network network, List ipAddress, Set service) throws ResourceUnavailableException { - // return true, as IP will be associated as part of static NAT/port forwarding rule configuration - return true; - } - - @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - if (!canHandle(config, Service.StaticNat)) { - return false; - } - return applyStaticNatRules(config, rules); - } -} diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/element/JuniperSRXFirewallElementService.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/element/JuniperSRXFirewallElementService.java deleted file mode 100644 index 8ee756acc0c..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/element/JuniperSRXFirewallElementService.java +++ /dev/null @@ -1,95 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.element; - -import java.util.List; - -import org.apache.cloudstack.api.response.ExternalFirewallResponse; - -import com.cloud.api.commands.AddExternalFirewallCmd; -import com.cloud.api.commands.AddSrxFirewallCmd; -import com.cloud.api.commands.ConfigureSrxFirewallCmd; -import com.cloud.api.commands.DeleteExternalFirewallCmd; -import com.cloud.api.commands.DeleteSrxFirewallCmd; -import com.cloud.api.commands.ListExternalFirewallsCmd; -import com.cloud.api.commands.ListSrxFirewallNetworksCmd; -import com.cloud.api.commands.ListSrxFirewallsCmd; -import com.cloud.api.response.SrxFirewallResponse; -import com.cloud.host.Host; -import com.cloud.network.Network; -import com.cloud.network.dao.ExternalFirewallDeviceVO; -import com.cloud.utils.component.PluggableService; - -public interface JuniperSRXFirewallElementService extends PluggableService { - - /** - * adds a SRX firewall device in to a physical network - * @param AddSrxFirewallCmd - * @return ExternalFirewallDeviceVO object for the firewall added - */ - public ExternalFirewallDeviceVO addSrxFirewall(AddSrxFirewallCmd cmd); - - /** - * removes SRX firewall device from a physical network - * @param DeleteSrxFirewallCmd - * @return true if firewall device successfully deleted - */ - public boolean deleteSrxFirewall(DeleteSrxFirewallCmd cmd); - - /** - * configures a SRX firewal device added in a physical network - * @param ConfigureSrxFirewallCmd - * @return ExternalFirewallDeviceVO for the device configured - */ - public ExternalFirewallDeviceVO configureSrxFirewall(ConfigureSrxFirewallCmd cmd); - - /** - * lists all the SRX firewall devices added in to a physical network - * @param ListSrxFirewallsCmd - * @return list of ExternalFirewallDeviceVO for the devices in the physical network. - */ - public List listSrxFirewalls(ListSrxFirewallsCmd cmd); - - /** - * lists all the guest networks using a SRX firewall device - * @param ListSrxFirewallNetworksCmd - * @return list of the guest networks that are using this F5 load balancer - */ - public List listNetworks(ListSrxFirewallNetworksCmd cmd); - - public SrxFirewallResponse createSrxFirewallResponse(ExternalFirewallDeviceVO fwDeviceVO); - - @Deprecated - // API helper function supported for backward compatibility - public - Host addExternalFirewall(AddExternalFirewallCmd cmd); - - @Deprecated - // API helper function supported for backward compatibility - public - boolean deleteExternalFirewall(DeleteExternalFirewallCmd cmd); - - @Deprecated - // API helper function supported for backward compatibility - public - List listExternalFirewalls(ListExternalFirewallsCmd cmd); - - @Deprecated - // API helper function supported for backward compatibility - public - ExternalFirewallResponse createExternalFirewallResponse(Host externalFirewall); -} diff --git a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/resource/JuniperSrxResource.java b/plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/resource/JuniperSrxResource.java deleted file mode 100644 index e97706491f0..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/java/com/cloud/network/resource/JuniperSrxResource.java +++ /dev/null @@ -1,3795 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.resource; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.StringReader; -import java.net.Socket; -import java.net.SocketTimeoutException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.utils.security.ParserUtils; -import org.apache.log4j.Logger; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; - -import com.cloud.agent.IAgentControl; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.ExternalNetworkResourceUsageAnswer; -import com.cloud.agent.api.ExternalNetworkResourceUsageCommand; -import com.cloud.agent.api.MaintainAnswer; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.ReadyAnswer; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupExternalFirewallCommand; -import com.cloud.agent.api.routing.IpAssocAnswer; -import com.cloud.agent.api.routing.IpAssocCommand; -import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; -import com.cloud.agent.api.routing.SetFirewallRulesCommand; -import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; -import com.cloud.agent.api.routing.SetStaticNatRulesCommand; -import com.cloud.agent.api.routing.VpnUsersCfgCommand; -import com.cloud.agent.api.routing.VpnUsersCfgCommand.UsernamePassword; -import com.cloud.agent.api.to.FirewallRuleTO; -import com.cloud.agent.api.to.IpAddressTO; -import com.cloud.agent.api.to.PortForwardingRuleTO; -import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.host.Host; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.FirewallRule.Purpose; -import com.cloud.resource.ServerResource; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.exception.ExecutionException; -import com.cloud.utils.net.NetUtils; -import com.cloud.utils.script.Script; - -public class JuniperSrxResource implements ServerResource { - - private String _name; - private String _zoneId; - private String _ip; - private String _username; - private String _password; - private String _guid; - private String _objectNameWordSep; - private BufferedWriter _toSrx; - private BufferedReader _fromSrx; - private BufferedWriter _UsagetoSrx; - private BufferedReader _UsagefromSrx; - private Integer _numRetries; - private Integer _timeoutInSeconds; - private String _publicZone; - private String _privateZone; - private String _publicZoneInputFilterName; - private String _publicInterface; - private String _usageInterface; - private String _privateInterface; - private String _ikeProposalName; - private String _ipsecPolicyName; - private String _primaryDnsAddress; - private String _ikeGatewayHostname; - private String _vpnObjectPrefix; - private UsageFilter _usageFilterVlanInput; - private UsageFilter _usageFilterVlanOutput; - private UsageFilter _usageFilterIPInput; - private UsageFilter _usageFilterIPOutput; - private static final Logger s_logger = Logger.getLogger(JuniperSrxResource.class); - - private enum SrxXml { - LOGIN("login.xml"), - PRIVATE_INTERFACE_ADD("private-interface-add.xml"), - PRIVATE_INTERFACE_WITH_FILTERS_ADD("private-interface-with-filters-add.xml"), - PRIVATE_INTERFACE_GETONE("private-interface-getone.xml"), - PROXY_ARP_ADD("proxy-arp-add.xml"), - PROXY_ARP_GETONE("proxy-arp-getone.xml"), - PROXY_ARP_GETALL("proxy-arp-getall.xml"), - ZONE_INTERFACE_ADD("zone-interface-add.xml"), - ZONE_INTERFACE_GETONE("zone-interface-getone.xml"), - SRC_NAT_POOL_ADD("src-nat-pool-add.xml"), - SRC_NAT_POOL_GETONE("src-nat-pool-getone.xml"), - SRC_NAT_RULE_ADD("src-nat-rule-add.xml"), - SRC_NAT_RULE_GETONE("src-nat-rule-getone.xml"), - SRC_NAT_RULE_GETALL("src-nat-rule-getall.xml"), - DEST_NAT_POOL_ADD("dest-nat-pool-add.xml"), - DEST_NAT_POOL_GETONE("dest-nat-pool-getone.xml"), - DEST_NAT_POOL_GETALL("dest-nat-pool-getall.xml"), - DEST_NAT_RULE_ADD("dest-nat-rule-add.xml"), - DEST_NAT_RULE_GETONE("dest-nat-rule-getone.xml"), - DEST_NAT_RULE_GETALL("dest-nat-rule-getall.xml"), - STATIC_NAT_RULE_ADD("static-nat-rule-add.xml"), - STATIC_NAT_RULE_GETONE("static-nat-rule-getone.xml"), - STATIC_NAT_RULE_GETALL("static-nat-rule-getall.xml"), - ADDRESS_BOOK_ENTRY_ADD("address-book-entry-add.xml"), - ADDRESS_BOOK_ENTRY_GETONE("address-book-entry-getone.xml"), - ADDRESS_BOOK_ENTRY_GETALL("address-book-entry-getall.xml"), - APPLICATION_ADD("application-add.xml"), - APPLICATION_GETONE("application-getone.xml"), - SECURITY_POLICY_ADD("security-policy-add.xml"), - SECURITY_POLICY_GETONE("security-policy-getone.xml"), - SECURITY_POLICY_GETALL("security-policy-getall.xml"), - SECURITY_POLICY_GROUP("security-policy-group.xml"), - GUEST_VLAN_FILTER_TERM_ADD("guest-vlan-filter-term-add.xml"), - PUBLIC_IP_FILTER_TERM_ADD("public-ip-filter-term-add.xml"), - FILTER_TERM_GETONE("filter-term-getone.xml"), - FILTER_GETONE("filter-getone.xml"), - FIREWALL_FILTER_BYTES_GETALL("firewall-filter-bytes-getall.xml"), - IKE_POLICY_ADD("ike-policy-add.xml"), - IKE_POLICY_GETONE("ike-policy-getone.xml"), - IKE_POLICY_GETALL("ike-policy-getall.xml"), - IKE_GATEWAY_ADD("ike-gateway-add.xml"), - IKE_GATEWAY_GETONE("ike-gateway-getone.xml"), - IKE_GATEWAY_GETALL("ike-gateway-getall.xml"), - IPSEC_VPN_ADD("ipsec-vpn-add.xml"), - IPSEC_VPN_GETONE("ipsec-vpn-getone.xml"), - IPSEC_VPN_GETALL("ipsec-vpn-getall.xml"), - DYNAMIC_VPN_CLIENT_ADD("dynamic-vpn-client-add.xml"), - DYNAMIC_VPN_CLIENT_GETONE("dynamic-vpn-client-getone.xml"), - DYNAMIC_VPN_CLIENT_GETALL("dynamic-vpn-client-getall.xml"), - ADDRESS_POOL_ADD("address-pool-add.xml"), - ADDRESS_POOL_GETONE("address-pool-getone.xml"), - ADDRESS_POOL_GETALL("address-pool-getall.xml"), - ACCESS_PROFILE_ADD("access-profile-add.xml"), - ACCESS_PROFILE_GETONE("access-profile-getone.xml"), - ACCESS_PROFILE_GETALL("access-profile-getall.xml"), - FIREWALL_FILTER_TERM_ADD("firewall-filter-term-add.xml"), - FIREWALL_FILTER_TERM_GETONE("firewall-filter-term-getone.xml"), - TEMPLATE_ENTRY("template-entry.xml"), - OPEN_CONFIGURATION("open-configuration.xml"), - CLOSE_CONFIGURATION("close-configuration.xml"), - COMMIT("commit.xml"), - ROLLBACK("rollback.xml"), - TEST("test.xml"); - - private final String scriptsDir = "scripts/network/juniper"; - private final String xml; - private static final Logger s_logger = Logger.getLogger(JuniperSrxResource.class); - - private SrxXml(String filename) { - String contents = getXml(filename); - - // Strip the apache header and add the filename as a header to aid debugging - contents = contents.replaceAll( "(?s)", "" ).trim(); - if (!contents.startsWith("" + contents; - } - - xml = contents; - } - - public String getXml() { - return xml; - } - - private String getXml(String filename) { - try { - String xmlFilePath = Script.findScript(scriptsDir, filename); - - if (xmlFilePath == null) { - throw new Exception("Failed to find Juniper SRX XML file: " + filename); - } - - try(InputStreamReader fr = new InputStreamReader(new FileInputStream(xmlFilePath),"UTF-8"); - BufferedReader br = new BufferedReader(fr);) { - String xml = ""; - String line; - while ((line = br.readLine()) != null) { - xml += line.trim(); - } - return xml; - }catch (Exception e) { - s_logger.debug(e); - return null; - } - } catch (Exception e) { - s_logger.debug(e); - return null; - } - } - } - - public class UsageFilter { - private final String name; - private final String counterIdentifier; - private final String addressType; - - private UsageFilter(String name, String addressType, String counterIdentifier) { - this.name = name; - this.addressType = addressType; - - if (_usageInterface != null) { - counterIdentifier = _usageInterface + counterIdentifier; - } - - this.counterIdentifier = counterIdentifier; - } - - public String getName() { - return name; - } - - public String getCounterIdentifier() { - return counterIdentifier; - } - - public String getAddressType() { - return addressType; - } - } - - public class FirewallFilterTerm { - private final String name; - private final List sourceCidrs; - private final String destIp; - private String portRange; - private final String protocol; - private String icmpType; - private String icmpCode; - private final String countName; - - private FirewallFilterTerm(String name, List sourceCidrs, String destIp, String protocol, Integer startPort, Integer endPort, Integer icmpType, - Integer icmpCode, String countName) { - this.name = name; - this.sourceCidrs = sourceCidrs; - this.destIp = destIp; - this.protocol = protocol; - - if (protocol.equals("tcp") || protocol.equals("udp")) { - portRange = String.valueOf(startPort) + "-" + String.valueOf(endPort); - } else if (protocol.equals("icmp")) { - this.icmpType = String.valueOf(icmpType); - this.icmpCode = String.valueOf(icmpCode); - } else { - assert protocol.equals("any"); - } - this.countName = countName; - - } - - public String getName() { - return name; - } - - public List getSourceCidrs() { - return sourceCidrs; - } - - public String getDestIp() { - return destIp; - } - - public String getPortRange() { - return portRange; - } - - public String getProtocol() { - return protocol; - } - - public String getIcmpType() { - return icmpType; - } - - public String getIcmpCode() { - return icmpCode; - } - - public String getCountName() { - return countName; - } - } - - private enum SrxCommand { - LOGIN, OPEN_CONFIGURATION, CLOSE_CONFIGURATION, COMMIT, ROLLBACK, CHECK_IF_EXISTS, CHECK_IF_IN_USE, ADD, DELETE, GET_ALL, CHECK_PRIVATE_IF_EXISTS; - } - - private enum Protocol { - tcp, udp, icmp, all, any; - } - - private enum RuleMatchCondition { - ALL, PUBLIC_PRIVATE_IPS, PRIVATE_SUBNET; - } - - private enum GuestNetworkType { - SOURCE_NAT, INTERFACE_NAT; - } - - private enum SecurityPolicyType { - STATIC_NAT("staticnat"), DESTINATION_NAT("destnat"), VPN("vpn"), SECURITYPOLICY_EGRESS("egress"), SECURITYPOLICY_EGRESS_DEFAULT("egress-default"); - - private final String identifier; - - private SecurityPolicyType(String identifier) { - this.identifier = identifier; - } - - private String getIdentifier() { - return identifier; - } - } - - @Override - public Answer executeRequest(Command cmd) { - if (cmd instanceof ReadyCommand) { - return execute((ReadyCommand)cmd); - } else if (cmd instanceof MaintainCommand) { - return execute((MaintainCommand)cmd); - } else if (cmd instanceof IpAssocCommand) { - return execute((IpAssocCommand)cmd); - } else if (cmd instanceof SetStaticNatRulesCommand) { - return execute((SetStaticNatRulesCommand)cmd); - } else if (cmd instanceof SetPortForwardingRulesCommand) { - return execute((SetPortForwardingRulesCommand)cmd); - } else if (cmd instanceof SetFirewallRulesCommand) { - return execute((SetFirewallRulesCommand)cmd); - } else if (cmd instanceof ExternalNetworkResourceUsageCommand) { - return execute((ExternalNetworkResourceUsageCommand)cmd); - } else if (cmd instanceof RemoteAccessVpnCfgCommand) { - return execute((RemoteAccessVpnCfgCommand)cmd); - } else if (cmd instanceof VpnUsersCfgCommand) { - return execute((VpnUsersCfgCommand)cmd); - } else { - return Answer.createUnsupportedCommandAnswer(cmd); - } - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - try { - _name = (String)params.get("name"); - if (_name == null) { - throw new ConfigurationException("Unable to find name"); - } - - _zoneId = (String)params.get("zoneId"); - if (_zoneId == null) { - throw new ConfigurationException("Unable to find zone"); - } - - _ip = (String)params.get("ip"); - if (_ip == null) { - throw new ConfigurationException("Unable to find IP"); - } - - _username = (String)params.get("username"); - if (_username == null) { - throw new ConfigurationException("Unable to find username"); - } - - _password = (String)params.get("password"); - if (_password == null) { - throw new ConfigurationException("Unable to find password"); - } - - _publicInterface = (String)params.get("publicinterface"); - if (_publicInterface == null) { - throw new ConfigurationException("Unable to find public interface."); - } - - _privateInterface = (String)params.get("privateinterface"); - if (_privateInterface == null) { - throw new ConfigurationException("Unable to find private interface."); - } - - _publicZone = (String)params.get("publiczone"); - if (_publicZone == null) { - _publicZone = "untrust"; - } - - _privateZone = (String)params.get("privatezone"); - if (_privateZone == null) { - _privateZone = "trust"; - } - - _guid = (String)params.get("guid"); - if (_guid == null) { - throw new ConfigurationException("Unable to find the guid"); - } - - _numRetries = NumbersUtil.parseInt((String)params.get("numretries"), 1); - - _timeoutInSeconds = NumbersUtil.parseInt((String)params.get("timeout"), 300); - - _objectNameWordSep = "-"; - - _ikeProposalName = "cloud-ike-proposal"; - _ipsecPolicyName = "cloud-ipsec-policy"; - _ikeGatewayHostname = "cloud"; - _vpnObjectPrefix = "vpn-a"; - _primaryDnsAddress = "4.2.2.2"; - - // Open a socket and login - if (!refreshSrxConnection()) { - throw new ConfigurationException("Unable to open a connection to the SRX."); - } - - _publicZoneInputFilterName = _publicZone; - - _usageFilterVlanInput = new UsageFilter("vlan-input", null, "vlan-input"); - _usageFilterVlanOutput = new UsageFilter("vlan-output", null, "vlan-output"); - _usageFilterIPInput = new UsageFilter(_publicZone, "destination-address", "-i"); - _usageFilterIPOutput = new UsageFilter(_privateZone, "source-address", "-o"); - - return true; - } catch (Exception e) { - throw new ConfigurationException(e.getMessage()); - } - - } - - @Override - public StartupCommand[] initialize() { - StartupExternalFirewallCommand cmd = new StartupExternalFirewallCommand(); - cmd.setName(_name); - cmd.setDataCenter(_zoneId); - cmd.setPod(""); - cmd.setPrivateIpAddress(_ip); - cmd.setStorageIpAddress(""); - cmd.setVersion(JuniperSrxResource.class.getPackage().getImplementationVersion()); - cmd.setGuid(_guid); - return new StartupCommand[] {cmd}; - } - - @Override - public Host.Type getType() { - return Host.Type.ExternalFirewall; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public PingCommand getCurrentStatus(final long id) { - return new PingCommand(Host.Type.ExternalFirewall, id); - } - - @Override - public void disconnected() { - closeSocket(); - } - - @Override - public IAgentControl getAgentControl() { - return null; - } - - @Override - public void setAgentControl(IAgentControl agentControl) { - return; - } - - private Answer execute(ReadyCommand cmd) { - return new ReadyAnswer(cmd); - } - - private Answer execute(MaintainCommand cmd) { - return new MaintainAnswer(cmd); - } - - private ExternalNetworkResourceUsageAnswer execute(ExternalNetworkResourceUsageCommand cmd) { - try { - return getUsageAnswer(cmd); - } catch (ExecutionException e) { - return new ExternalNetworkResourceUsageAnswer(cmd, e); - } - } - - /* - * Login - */ - - private boolean refreshSrxConnection() { - if (!(closeSocket() && openSocket())) { - return false; - } - - try { - return login(); - } catch (ExecutionException e) { - s_logger.error("Failed to login due to " + e.getMessage()); - return false; - } - } - - private boolean login() throws ExecutionException { - String xml = SrxXml.LOGIN.getXml(); - xml = replaceXmlValue(xml, "username", _username); - xml = replaceXmlValue(xml, "password", _password); - return sendRequestAndCheckResponse(SrxCommand.LOGIN, xml); - } - - private boolean openSocket() { - try { - Socket s = new Socket(_ip, 3221); - s.setKeepAlive(true); - s.setSoTimeout(_timeoutInSeconds * 1000); - _toSrx = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8")); - _fromSrx = new BufferedReader(new InputStreamReader(s.getInputStream(),"UTF-8")); - return true; - } catch (IOException e) { - s_logger.error(e); - return false; - } - } - - private boolean closeSocket() { - try { - if (_toSrx != null) { - _toSrx.close(); - } - - if (_fromSrx != null) { - _fromSrx.close(); - } - - return true; - } catch (IOException e) { - s_logger.error(e); - return false; - } - } - - /* - * The usage data will be handled on it's own socket, so usage - * commands will use the following methods... - */ - private boolean usageLogin() throws ExecutionException { - String xml = SrxXml.LOGIN.getXml(); - xml = replaceXmlValue(xml, "username", _username); - xml = replaceXmlValue(xml, "password", _password); - return sendUsageRequestAndCheckResponse(SrxCommand.LOGIN, xml); - } - - private boolean openUsageSocket() throws ExecutionException { - try { - Socket s = new Socket(_ip, 3221); - s.setKeepAlive(true); - s.setSoTimeout(_timeoutInSeconds * 1000); - _UsagetoSrx = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8")); - _UsagefromSrx = new BufferedReader(new InputStreamReader(s.getInputStream(),"UTF-8")); - return usageLogin(); - } catch (IOException e) { - s_logger.error(e); - return false; - } - } - - private boolean closeUsageSocket() { - try { - if (_UsagetoSrx != null) { - _UsagetoSrx.close(); - } - - if (_UsagefromSrx != null) { - _UsagefromSrx.close(); - } - - return true; - } catch (IOException e) { - s_logger.error(e); - return false; - } - } - - /* - * Commit/rollback - */ - - private void openConfiguration() throws ExecutionException { - String xml = SrxXml.OPEN_CONFIGURATION.getXml(); - String successMsg = "Opened a private configuration."; - String errorMsg = "Failed to open a private configuration."; - - if (!sendRequestAndCheckResponse(SrxCommand.OPEN_CONFIGURATION, xml)) { - throw new ExecutionException(errorMsg); - } else { - s_logger.debug(successMsg); - } - } - - private void closeConfiguration() { - String xml = SrxXml.CLOSE_CONFIGURATION.getXml(); - String successMsg = "Closed private configuration."; - String errorMsg = "Failed to close private configuration."; - - try { - if (!sendRequestAndCheckResponse(SrxCommand.CLOSE_CONFIGURATION, xml)) { - s_logger.error(errorMsg); - } - } catch (ExecutionException e) { - s_logger.error(errorMsg); - } - - s_logger.debug(successMsg); - } - - private void commitConfiguration() throws ExecutionException { - String xml = SrxXml.COMMIT.getXml(); - String successMsg = "Committed to global configuration."; - String errorMsg = "Failed to commit to global configuration."; - - if (!sendRequestAndCheckResponse(SrxCommand.COMMIT, xml)) { - throw new ExecutionException(errorMsg); - } else { - s_logger.debug(successMsg); - closeConfiguration(); - } - } - - /* - * Guest networks - */ - - private synchronized Answer execute(IpAssocCommand cmd) { - refreshSrxConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(IpAssocCommand cmd, int numRetries) { - String[] results = new String[cmd.getIpAddresses().length]; - int i = 0; - try { - IpAddressTO ip; - if (cmd.getIpAddresses().length != 1) { - throw new ExecutionException("Received an invalid number of guest IPs to associate."); - } else { - ip = cmd.getIpAddresses()[0]; - } - - String sourceNatIpAddress = null; - GuestNetworkType type = GuestNetworkType.INTERFACE_NAT; - - if (ip.isSourceNat()) { - type = GuestNetworkType.SOURCE_NAT; - - if (ip.getPublicIp() == null) { - throw new ExecutionException("Source NAT IP address must not be null."); - } else { - sourceNatIpAddress = ip.getPublicIp(); - } - } - - long guestVlanTag = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG)); - String guestVlanGateway = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY); - String cidr = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR); - long cidrSize = NetUtils.cidrToLong(cidr)[1]; - String guestVlanSubnet = NetUtils.getCidrSubNet(guestVlanGateway, cidrSize); - - Long publicVlanTag = null; - if (ip.getBroadcastUri() != null && !ip.getBroadcastUri().equals("untagged")) { - try { - publicVlanTag = Long.parseLong(BroadcastDomainType.getValue(ip.getBroadcastUri())); - } catch (Exception e) { - throw new ExecutionException("Could not parse public VLAN tag: " + ip.getBroadcastUri()); - } - } - - openConfiguration(); - - // Remove the guest network: - // Remove source, static, and destination NAT rules - // Remove VPN - shutdownGuestNetwork(type, ip.getAccountId(), publicVlanTag, sourceNatIpAddress, guestVlanTag, guestVlanGateway, guestVlanSubnet, cidrSize); - - if (ip.isAdd()) { - // Implement the guest network for this VLAN - implementGuestNetwork(type, publicVlanTag, sourceNatIpAddress, guestVlanTag, guestVlanGateway, guestVlanSubnet, cidrSize); - } - - commitConfiguration(); - results[i++] = ip.getPublicIp() + " - success"; - } catch (ExecutionException e) { - s_logger.error(e); - closeConfiguration(); - - if (numRetries > 0 && refreshSrxConnection()) { - int numRetriesRemaining = numRetries - 1; - s_logger.debug("Retrying IPAssocCommand. Number of retries remaining: " + numRetriesRemaining); - return execute(cmd, numRetriesRemaining); - } else { - results[i++] = IpAssocAnswer.errorResult; - } - } - - return new IpAssocAnswer(cmd, results); - } - - private void implementGuestNetwork(GuestNetworkType type, Long publicVlanTag, String publicIp, long privateVlanTag, String privateGateway, String privateSubnet, - long privateCidrNumber) throws ExecutionException { - privateGateway = privateGateway + "/" + privateCidrNumber; - privateSubnet = privateSubnet + "/" + privateCidrNumber; - - managePrivateInterface(SrxCommand.ADD, !type.equals(GuestNetworkType.SOURCE_NAT), privateVlanTag, privateGateway); - manageZoneInterface(SrxCommand.ADD, privateVlanTag); - - if (type.equals(GuestNetworkType.SOURCE_NAT)) { - manageSourceNatPool(SrxCommand.ADD, publicIp); - manageSourceNatRule(SrxCommand.ADD, publicIp, privateSubnet); - manageProxyArp(SrxCommand.ADD, publicVlanTag, publicIp); - manageUsageFilter(SrxCommand.ADD, _usageFilterIPOutput, privateSubnet, null, genIpFilterTermName(publicIp)); - manageUsageFilter(SrxCommand.ADD, _usageFilterIPInput, publicIp, null, genIpFilterTermName(publicIp)); - } else if (type.equals(GuestNetworkType.INTERFACE_NAT)) { - manageUsageFilter(SrxCommand.ADD, _usageFilterVlanOutput, null, privateVlanTag, null); - manageUsageFilter(SrxCommand.ADD, _usageFilterVlanInput, null, privateVlanTag, null); - } - - String msg = "Implemented guest network with type " + type + ". Guest VLAN tag: " + privateVlanTag + ", guest gateway: " + privateGateway; - msg += type.equals(GuestNetworkType.SOURCE_NAT) ? ", source NAT IP: " + publicIp : ""; - s_logger.debug(msg); - } - - private void shutdownGuestNetwork(GuestNetworkType type, long accountId, Long publicVlanTag, String sourceNatIpAddress, long privateVlanTag, String privateGateway, - String privateSubnet, long privateCidrSize) throws ExecutionException { - // Remove static and destination NAT rules for the guest network - removeStaticAndDestNatRulesInPrivateVlan(privateVlanTag, privateGateway, privateCidrSize); - - privateGateway = privateGateway + "/" + privateCidrSize; - privateSubnet = privateSubnet + "/" + privateCidrSize; - - managePrivateInterface(SrxCommand.DELETE, false, privateVlanTag, privateGateway); - manageZoneInterface(SrxCommand.DELETE, privateVlanTag); - deleteVpnObjectsForAccount(accountId); - - if (type.equals(GuestNetworkType.SOURCE_NAT)) { - manageSourceNatRule(SrxCommand.DELETE, sourceNatIpAddress, privateSubnet); - manageSourceNatPool(SrxCommand.DELETE, sourceNatIpAddress); - manageProxyArp(SrxCommand.DELETE, publicVlanTag, sourceNatIpAddress); - manageUsageFilter(SrxCommand.DELETE, _usageFilterIPOutput, privateSubnet, null, genIpFilterTermName(sourceNatIpAddress)); - manageUsageFilter(SrxCommand.DELETE, _usageFilterIPInput, sourceNatIpAddress, null, genIpFilterTermName(sourceNatIpAddress)); - } else if (type.equals(GuestNetworkType.INTERFACE_NAT)) { - manageUsageFilter(SrxCommand.DELETE, _usageFilterVlanOutput, null, privateVlanTag, null); - manageUsageFilter(SrxCommand.DELETE, _usageFilterVlanInput, null, privateVlanTag, null); - } - - String msg = "Shut down guest network with type " + type + ". Guest VLAN tag: " + privateVlanTag + ", guest gateway: " + privateGateway; - msg += type.equals(GuestNetworkType.SOURCE_NAT) ? ", source NAT IP: " + sourceNatIpAddress : ""; - s_logger.debug(msg); - } - - private Map> getActiveFirewallEgressRules(FirewallRuleTO[] allRules) { - Map> activeRules = new HashMap>(); - - for (FirewallRuleTO rule : allRules) { - String guestVlan; - guestVlan = rule.getSrcVlanTag(); - - ArrayList activeRulesForNetwork = activeRules.get(guestVlan); - - if (activeRulesForNetwork == null) { - activeRulesForNetwork = new ArrayList(); - } - - if (!rule.revoked() || rule.isAlreadyAdded()) { - activeRulesForNetwork.add(rule); - } - - activeRules.put(guestVlan, activeRulesForNetwork); - } - - return activeRules; - } - - private List extractCidrs(List rules) throws ExecutionException { - List allCidrs = new ArrayList(); - List cidrs = new ArrayList(); - - for (FirewallRuleTO rule : rules) { - cidrs = (rule.getSourceCidrList()); - for (String cidr : cidrs) { - if (!allCidrs.contains(cidr)) { - allCidrs.add(cidr); - } - } - } - return allCidrs; - } - - /* security policies */ - private synchronized Answer execute(SetFirewallRulesCommand cmd) { - refreshSrxConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(SetFirewallRulesCommand cmd, int numRetries) { - FirewallRuleTO[] rules = cmd.getRules(); - try { - openConfiguration(); - if (rules[0].getTrafficType() == FirewallRule.TrafficType.Egress) { - Map> activeRules = getActiveFirewallEgressRules(rules); - Set guestVlans = activeRules.keySet(); - // List cidrs = new ArrayList(); - boolean defaultEgressPolicy = rules[0].isDefaultEgressPolicy(); - FirewallRule.FirewallRuleType type = rules[0].getType(); - //getting - String guestCidr = rules[0].getGuestCidr(); - List cidrs = new ArrayList(); - cidrs.add(guestCidr); - - List applications = new ArrayList(); - Object[] application = new Object[3]; - application[0] = Protocol.all; - application[1] = NetUtils.PORT_RANGE_MIN; - application[2] = NetUtils.PORT_RANGE_MAX; - applications.add(application); - - for (String guestVlan : guestVlans) { - List activeRulesForGuestNw = activeRules.get(guestVlan); - - removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS, guestVlan, extractCidrs(activeRulesForGuestNw), - defaultEgressPolicy); - if (activeRulesForGuestNw.size() > 0 && type == FirewallRule.FirewallRuleType.User) { - addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS, guestVlan, extractApplications(activeRulesForGuestNw), - extractCidrs(activeRulesForGuestNw), defaultEgressPolicy); - - /* Adding default policy rules are required because the order of rules is important. - * Depending on the rules order the traffic accept/drop is performed - */ - removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, cidrs, defaultEgressPolicy); - addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, applications, cidrs, defaultEgressPolicy); - } - - //remove required with out comparing default policy because in upgrade network offering we may required to delete - // the previously added rule - removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, cidrs, false); - if (defaultEgressPolicy == true && type == FirewallRule.FirewallRuleType.System) { - removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, cidrs, defaultEgressPolicy); - if (activeRulesForGuestNw.size() > 0) { - //add default egress security policy - addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, applications, cidrs, defaultEgressPolicy); - } - } - } - commitConfiguration(); - } else { - for (FirewallRuleTO rule : rules) { - int startPort = NetUtils.PORT_RANGE_MIN, endPort = NetUtils.PORT_RANGE_MAX; - if (rule.getSrcPortRange() != null) { - startPort = rule.getSrcPortRange()[0]; - endPort = rule.getSrcPortRange()[1]; - } - - FirewallFilterTerm term = - new FirewallFilterTerm(genIpIdentifier(rule.getSrcIp()) + "-" + String.valueOf(rule.getId()), rule.getSourceCidrList(), rule.getSrcIp(), - rule.getProtocol(), startPort, endPort, rule.getIcmpType(), rule.getIcmpCode(), genIpIdentifier(rule.getSrcIp()) + - _usageFilterIPInput.getCounterIdentifier()); - if (!rule.revoked()) { - manageProxyArp(SrxCommand.ADD, getVlanTag(rule.getSrcVlanTag()), rule.getSrcIp()); - manageFirewallFilter(SrxCommand.ADD, term, _publicZoneInputFilterName); - } else { - manageFirewallFilter(SrxCommand.DELETE, term, _publicZoneInputFilterName); - manageProxyArp(SrxCommand.DELETE, getVlanTag(rule.getSrcVlanTag()), rule.getSrcIp()); - } - } - commitConfiguration(); - } - - return new Answer(cmd); - } catch (ExecutionException e) { - s_logger.error(e); - closeConfiguration(); - - if (numRetries > 0 && refreshSrxConnection()) { - int numRetriesRemaining = numRetries - 1; - s_logger.debug("Retrying SetFirewallRulesCommand. Number of retries remaining: " + numRetriesRemaining); - return execute(cmd, numRetriesRemaining); - } else { - return new Answer(cmd, e); - } - } - } - - /* - * Static NAT - */ - - private synchronized Answer execute(SetStaticNatRulesCommand cmd) { - refreshSrxConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(SetStaticNatRulesCommand cmd, int numRetries) { - StaticNatRuleTO[] allRules = cmd.getRules(); - Map> activeRules = getActiveRules(allRules); - Map vlanTagMap = getVlanTagMap(allRules); - - try { - openConfiguration(); - - Set ipPairs = activeRules.keySet(); - for (String ipPair : ipPairs) { - String[] ipPairComponents = ipPair.split("-"); - String publicIp = ipPairComponents[0]; - String privateIp = ipPairComponents[1]; - - List activeRulesForIpPair = activeRules.get(ipPair); - Long publicVlanTag = getVlanTag(vlanTagMap.get(publicIp)); - - // Delete the existing static NAT rule for this IP pair - removeStaticNatRule(publicVlanTag, publicIp, privateIp); - - if (activeRulesForIpPair.size() > 0) { - // If there are active FirewallRules for this IP pair, add the static NAT rule and open the specified port ranges - addStaticNatRule(publicVlanTag, publicIp, privateIp, activeRulesForIpPair); - } - } - - commitConfiguration(); - return new Answer(cmd); - } catch (ExecutionException e) { - s_logger.error(e); - closeConfiguration(); - - if (numRetries > 0 && refreshSrxConnection()) { - int numRetriesRemaining = numRetries - 1; - s_logger.debug("Retrying SetPortForwardingRulesCommand. Number of retries remaining: " + numRetriesRemaining); - return execute(cmd, numRetriesRemaining); - } else { - return new Answer(cmd, e); - } - } - } - - private void addStaticNatRule(Long publicVlanTag, String publicIp, String privateIp, List rules) throws ExecutionException { - manageStaticNatRule(SrxCommand.ADD, publicIp, privateIp); - manageAddressBookEntry(SrxCommand.ADD, _privateZone, privateIp, null); - manageProxyArp(SrxCommand.ADD, publicVlanTag, publicIp); - - // Add a new security policy with the current set of applications - addSecurityPolicyAndApplications(SecurityPolicyType.STATIC_NAT, privateIp, extractApplications(rules)); - - s_logger.debug("Added static NAT rule for public IP " + publicIp + ", and private IP " + privateIp); - } - - private void removeStaticNatRule(Long publicVlanTag, String publicIp, String privateIp) throws ExecutionException { - manageStaticNatRule(SrxCommand.DELETE, publicIp, privateIp); - - // Remove any existing security policy and clean up applications - removeSecurityPolicyAndApplications(SecurityPolicyType.STATIC_NAT, privateIp); - - manageAddressBookEntry(SrxCommand.DELETE, _privateZone, privateIp, null); - manageProxyArp(SrxCommand.DELETE, publicVlanTag, publicIp); - - s_logger.debug("Removed static NAT rule for public IP " + publicIp + ", and private IP " + privateIp); - } - - private void removeStaticNatRules(Long privateVlanTag, Map publicVlanTags, List staticNatRules) throws ExecutionException { - for (String[] staticNatRuleToRemove : staticNatRules) { - String staticNatRulePublicIp = staticNatRuleToRemove[0]; - String staticNatRulePrivateIp = staticNatRuleToRemove[1]; - - Long publicVlanTag = null; - if (publicVlanTags.containsKey(staticNatRulePublicIp)) { - publicVlanTag = publicVlanTags.get(staticNatRulePublicIp); - } - - if (privateVlanTag != null) { - s_logger.warn("Found a static NAT rule (" + staticNatRulePublicIp + " <-> " + staticNatRulePrivateIp + ") for guest VLAN with tag " + privateVlanTag + - " that is active when the guest network is being removed. Removing rule..."); - } - - removeStaticNatRule(publicVlanTag, staticNatRulePublicIp, staticNatRulePrivateIp); - } - } - - /* - * VPN - */ - - private synchronized Answer execute(RemoteAccessVpnCfgCommand cmd) { - refreshSrxConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(RemoteAccessVpnCfgCommand cmd, int numRetries) { - long accountId = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.ACCOUNT_ID)); - String guestNetworkCidr = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR); - String preSharedKey = cmd.getPresharedKey(); - String[] ipRange = cmd.getIpRange().split("-"); - - try { - openConfiguration(); - - // Delete existing VPN objects for this account - deleteVpnObjectsForAccount(accountId); - - if (cmd.isCreate()) { - // Add IKE policy - manageIkePolicy(SrxCommand.ADD, null, accountId, preSharedKey); - - // Add address pool - manageAddressPool(SrxCommand.ADD, null, accountId, guestNetworkCidr, ipRange[0], ipRange[1], _primaryDnsAddress); - } - - commitConfiguration(); - - return new Answer(cmd); - } catch (ExecutionException e) { - s_logger.error(e); - closeConfiguration(); - - if (numRetries > 0 && refreshSrxConnection()) { - int numRetriesRemaining = numRetries - 1; - s_logger.debug("Retrying RemoteAccessVpnCfgCommand. Number of retries remaining: " + numRetriesRemaining); - return execute(cmd, numRetriesRemaining); - } else { - return new Answer(cmd, e); - } - } - - } - - private void deleteVpnObjectsForAccount(long accountId) throws ExecutionException { - // Delete all IKE policies - for (String ikePolicyName : getVpnObjectNames(SrxXml.IKE_POLICY_GETALL, accountId)) { - manageIkePolicy(SrxCommand.DELETE, ikePolicyName, null, null); - } - - // Delete all address pools - for (String addressPoolName : getVpnObjectNames(SrxXml.ADDRESS_POOL_GETALL, accountId)) { - manageAddressPool(SrxCommand.DELETE, addressPoolName, null, null, null, null, null); - } - - // Delete all IKE gateways - for (String ikeGatewayName : getVpnObjectNames(SrxXml.IKE_GATEWAY_GETALL, accountId)) { - manageIkeGateway(SrxCommand.DELETE, ikeGatewayName, null, null, null, null); - } - - // Delete all IPsec VPNs - for (String ipsecVpnName : getVpnObjectNames(SrxXml.IPSEC_VPN_GETALL, accountId)) { - manageIpsecVpn(SrxCommand.DELETE, ipsecVpnName, null, null, null, null); - } - - // Delete all dynamic VPN clients - for (String dynamicVpnClientName : getVpnObjectNames(SrxXml.DYNAMIC_VPN_CLIENT_GETALL, accountId)) { - manageDynamicVpnClient(SrxCommand.DELETE, dynamicVpnClientName, null, null, null, null); - } - - // Delete all access profiles - for (String accessProfileName : getVpnObjectNames(SrxXml.ACCESS_PROFILE_GETALL, accountId)) { - manageAccessProfile(SrxCommand.DELETE, accessProfileName, null, null, null, null); - } - - // Delete all security policies - for (String securityPolicyName : getVpnObjectNames(SrxXml.SECURITY_POLICY_GETALL, accountId)) { - manageSecurityPolicy(SecurityPolicyType.VPN, SrxCommand.DELETE, accountId, null, null, null, null, securityPolicyName, false); - } - - // Delete all address book entries - for (String addressBookEntryName : getVpnObjectNames(SrxXml.ADDRESS_BOOK_ENTRY_GETALL, accountId)) { - manageAddressBookEntry(SrxCommand.DELETE, _privateZone, null, addressBookEntryName); - } - - } - - public List getVpnObjectNames(SrxXml xmlObj, long accountId) throws ExecutionException { - List vpnObjectNames = new ArrayList(); - - String xmlRequest = xmlObj.getXml(); - if (xmlObj.equals(SrxXml.SECURITY_POLICY_GETALL)) { - xmlRequest = replaceXmlValue(xmlRequest, "from-zone", _publicZone); - xmlRequest = replaceXmlValue(xmlRequest, "to-zone", _privateZone); - } else if (xmlObj.equals(SrxXml.ADDRESS_BOOK_ENTRY_GETALL)) { - xmlRequest = replaceXmlValue(xmlRequest, "zone", _privateZone); - } - - String xmlResponse = sendRequest(xmlRequest); - Document doc = getDocument(xmlResponse); - NodeList vpnObjectNameNodes = doc.getElementsByTagName("name"); - for (int i = 0; i < vpnObjectNameNodes.getLength(); i++) { - NodeList vpnObjectNameEntries = vpnObjectNameNodes.item(i).getChildNodes(); - for (int j = 0; j < vpnObjectNameEntries.getLength(); j++) { - String vpnObjectName = vpnObjectNameEntries.item(j).getNodeValue(); - if (vpnObjectName.startsWith(genObjectName(_vpnObjectPrefix, String.valueOf(accountId)))) { - vpnObjectNames.add(vpnObjectName); - } - } - } - - return vpnObjectNames; - } - - private synchronized Answer execute(VpnUsersCfgCommand cmd) { - refreshSrxConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(VpnUsersCfgCommand cmd, int numRetries) { - long accountId = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.ACCOUNT_ID)); - String guestNetworkCidr = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR); - String ikePolicyName = genIkePolicyName(accountId); - UsernamePassword[] users = cmd.getUserpwds(); - - try { - openConfiguration(); - - for (UsernamePassword user : users) { - SrxCommand srxCmd = user.isAdd() ? SrxCommand.ADD : SrxCommand.DELETE; - - String ipsecVpnName = genIpsecVpnName(accountId, user.getUsername()); - - // IKE gateway - manageIkeGateway(srxCmd, null, accountId, ikePolicyName, _ikeGatewayHostname, user.getUsername()); - - // IPSec VPN - manageIpsecVpn(srxCmd, null, accountId, guestNetworkCidr, user.getUsername(), _ipsecPolicyName); - - // Dynamic VPN client - manageDynamicVpnClient(srxCmd, null, accountId, guestNetworkCidr, ipsecVpnName, user.getUsername()); - - // Access profile - manageAccessProfile(srxCmd, null, accountId, user.getUsername(), user.getPassword(), genAddressPoolName(accountId)); - - // Address book entry - manageAddressBookEntry(srxCmd, _privateZone, guestNetworkCidr, ipsecVpnName); - - // Security policy - manageSecurityPolicy(SecurityPolicyType.VPN, srxCmd, null, null, guestNetworkCidr, null, null, ipsecVpnName, false); - } - - commitConfiguration(); - - return new Answer(cmd); - } catch (ExecutionException e) { - s_logger.error(e); - closeConfiguration(); - - if (numRetries > 0 && refreshSrxConnection()) { - int numRetriesRemaining = numRetries - 1; - s_logger.debug("Retrying RemoteAccessVpnCfgCommand. Number of retries remaining: " + numRetriesRemaining); - return execute(cmd, numRetriesRemaining); - } else { - return new Answer(cmd, e); - } - } - - } - - /* - * Destination NAT - */ - - private synchronized Answer execute(SetPortForwardingRulesCommand cmd) { - refreshSrxConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(SetPortForwardingRulesCommand cmd, int numRetries) { - PortForwardingRuleTO[] allRules = cmd.getRules(); - Map> activeRules = getActiveRules(allRules); - - try { - openConfiguration(); - - Set ipPairs = activeRules.keySet(); - for (String ipPair : ipPairs) { - String[] ipPairComponents = ipPair.split("-"); - String publicIp = ipPairComponents[0]; - String privateIp = ipPairComponents[1]; - - List activeRulesForIpPair = activeRules.get(ipPair); - - // Get a list of all destination NAT rules for the public/private IP address pair - List destNatRules = getDestNatRules(RuleMatchCondition.PUBLIC_PRIVATE_IPS, publicIp, privateIp, null, null); - Map publicVlanTags = getPublicVlanTagsForNatRules(destNatRules); - - // Delete all of these rules, along with the destination NAT pools and security policies they use - removeDestinationNatRules(null, publicVlanTags, destNatRules); - - // If there are active rules for the public/private IP address pair, add them back - for (FirewallRuleTO rule : activeRulesForIpPair) { - Long publicVlanTag = getVlanTag(rule.getSrcVlanTag()); - PortForwardingRuleTO portForwardingRule = (PortForwardingRuleTO)rule; - addDestinationNatRule(getProtocol(rule.getProtocol()), publicVlanTag, portForwardingRule.getSrcIp(), portForwardingRule.getDstIp(), - portForwardingRule.getSrcPortRange()[0], portForwardingRule.getSrcPortRange()[1], portForwardingRule.getDstPortRange()[0], - portForwardingRule.getDstPortRange()[1]); - } - } - - commitConfiguration(); - return new Answer(cmd); - } catch (ExecutionException e) { - s_logger.error(e); - closeConfiguration(); - - if (numRetries > 0 && refreshSrxConnection()) { - int numRetriesRemaining = numRetries - 1; - s_logger.debug("Retrying SetPortForwardingRulesCommand. Number of retries remaining: " + numRetriesRemaining); - return execute(cmd, numRetriesRemaining); - } else { - return new Answer(cmd, e); - } - } - } - - private void addDestinationNatRule(Protocol protocol, Long publicVlanTag, String publicIp, String privateIp, int srcPortStart, int srcPortEnd, int destPortStart, - int destPortEnd) throws ExecutionException { - - int offset = 0; - for (int srcPort = srcPortStart; srcPort <= srcPortEnd; srcPort++) { - int destPort = destPortStart + offset; - manageDestinationNatPool(SrxCommand.ADD, privateIp, destPort); - manageDestinationNatRule(SrxCommand.ADD, publicIp, privateIp, srcPort, destPort); - offset += 1; - } - - manageAddressBookEntry(SrxCommand.ADD, _privateZone, privateIp, null); - - List applications = new ArrayList(); - applications.add(new Object[] {protocol, destPortStart, destPortEnd}); - addSecurityPolicyAndApplications(SecurityPolicyType.DESTINATION_NAT, privateIp, applications); - manageProxyArp(SrxCommand.ADD, publicVlanTag, publicIp); - - String srcPortRange = srcPortStart + "-" + srcPortEnd; - String destPortRange = destPortStart + "-" + destPortEnd; - s_logger.debug("Added destination NAT rule for protocol " + protocol + ", public IP " + publicIp + ", private IP " + privateIp + ", source port range " + - srcPortRange + ", and dest port range " + destPortRange); - } - - private void removeDestinationNatRule(Long publicVlanTag, String publicIp, String privateIp, int srcPort, int destPort) throws ExecutionException { - manageDestinationNatRule(SrxCommand.DELETE, publicIp, privateIp, srcPort, destPort); - manageDestinationNatPool(SrxCommand.DELETE, privateIp, destPort); - manageProxyArp(SrxCommand.DELETE, publicVlanTag, publicIp); - - removeSecurityPolicyAndApplications(SecurityPolicyType.DESTINATION_NAT, privateIp); - - manageAddressBookEntry(SrxCommand.DELETE, _privateZone, privateIp, null); - - s_logger.debug("Removed destination NAT rule for public IP " + publicIp + ", private IP " + privateIp + ", source port " + srcPort + ", and dest port " + - destPort); - } - - private void removeDestinationNatRules(Long privateVlanTag, Map publicVlanTags, List destNatRules) throws ExecutionException { - for (String[] destNatRule : destNatRules) { - String publicIp = destNatRule[0]; - String privateIp = destNatRule[1]; - int srcPort = Integer.parseInt(destNatRule[2]); - int destPort = Integer.parseInt(destNatRule[3]); - - Long publicVlanTag = null; - if (publicVlanTags.containsKey(publicIp)) { - publicVlanTag = publicVlanTags.get(publicIp); - } - - if (privateVlanTag != null) { - s_logger.warn("Found a destination NAT rule (public IP: " + publicIp + ", private IP: " + privateIp + ", public port: " + srcPort + ", private port: " + - destPort + ") for guest VLAN with tag " + privateVlanTag + " that is active when the guest network is being removed. Removing rule..."); - } - - removeDestinationNatRule(publicVlanTag, publicIp, privateIp, srcPort, destPort); - } - } - - /* - * General NAT utils - */ - - private List getAllStaticAndDestNatRules() throws ExecutionException { - List staticAndDestNatRules = new ArrayList(); - staticAndDestNatRules.addAll(getStaticNatRules(RuleMatchCondition.ALL, null, null)); - staticAndDestNatRules.addAll(getDestNatRules(RuleMatchCondition.ALL, null, null, null, null)); - return staticAndDestNatRules; - } - - private void removeStaticAndDestNatRulesInPrivateVlan(long privateVlanTag, String privateGateway, long privateCidrSize) throws ExecutionException { - List staticNatRulesToRemove = getStaticNatRules(RuleMatchCondition.PRIVATE_SUBNET, privateGateway, privateCidrSize); - List destNatRulesToRemove = getDestNatRules(RuleMatchCondition.PRIVATE_SUBNET, null, null, privateGateway, privateCidrSize); - - List publicIps = new ArrayList(); - addPublicIpsToList(staticNatRulesToRemove, publicIps); - addPublicIpsToList(destNatRulesToRemove, publicIps); - - Map publicVlanTags = getPublicVlanTagsForPublicIps(publicIps); - - removeStaticNatRules(privateVlanTag, publicVlanTags, staticNatRulesToRemove); - removeDestinationNatRules(privateVlanTag, publicVlanTags, destNatRulesToRemove); - } - - private Map> getActiveRules(FirewallRuleTO[] allRules) { - Map> activeRules = new HashMap>(); - - for (FirewallRuleTO rule : allRules) { - String ipPair; - - if (rule.getPurpose().equals(Purpose.StaticNat)) { - StaticNatRuleTO staticNatRule = (StaticNatRuleTO)rule; - ipPair = staticNatRule.getSrcIp() + "-" + staticNatRule.getDstIp(); - } else if (rule.getPurpose().equals(Purpose.PortForwarding)) { - PortForwardingRuleTO portForwardingRule = (PortForwardingRuleTO)rule; - ipPair = portForwardingRule.getSrcIp() + "-" + portForwardingRule.getDstIp(); - } else { - continue; - } - - ArrayList activeRulesForIpPair = activeRules.get(ipPair); - - if (activeRulesForIpPair == null) { - activeRulesForIpPair = new ArrayList(); - } - - if (!rule.revoked() || rule.isAlreadyAdded()) { - activeRulesForIpPair.add(rule); - } - - activeRules.put(ipPair, activeRulesForIpPair); - } - - return activeRules; - } - - private Map getVlanTagMap(FirewallRuleTO[] allRules) { - Map vlanTagMap = new HashMap(); - - for (FirewallRuleTO rule : allRules) { - vlanTagMap.put(rule.getSrcIp(), rule.getSrcVlanTag()); - } - - return vlanTagMap; - } - - /* - * VPN - */ - - private String genIkePolicyName(long accountId) { - return genObjectName(_vpnObjectPrefix, String.valueOf(accountId)); - } - - private boolean manageIkePolicy(SrxCommand command, String ikePolicyName, Long accountId, String preSharedKey) throws ExecutionException { - if (ikePolicyName == null) { - ikePolicyName = genIkePolicyName(accountId); - } - - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.IKE_GATEWAY_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "policy-name", ikePolicyName); - return sendRequestAndCheckResponse(command, xml, "name", ikePolicyName); - - case ADD: - if (manageIkePolicy(SrxCommand.CHECK_IF_EXISTS, ikePolicyName, accountId, preSharedKey)) { - return true; - } - - xml = SrxXml.IKE_POLICY_ADD.getXml(); - xml = replaceXmlValue(xml, "policy-name", ikePolicyName); - xml = replaceXmlValue(xml, "proposal-name", _ikeProposalName); - xml = replaceXmlValue(xml, "pre-shared-key", preSharedKey); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add IKE policy: " + ikePolicyName); - } else { - return true; - } - - case DELETE: - if (!manageIkePolicy(SrxCommand.CHECK_IF_EXISTS, ikePolicyName, accountId, preSharedKey)) { - return true; - } - - xml = SrxXml.IKE_GATEWAY_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "policy-name", ikePolicyName); - - if (!sendRequestAndCheckResponse(command, xml, "name", ikePolicyName)) { - throw new ExecutionException("Failed to delete IKE policy: " + ikePolicyName); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - - } - - private String genIkeGatewayName(long accountId, String username) { - return genObjectName(_vpnObjectPrefix, String.valueOf(accountId), username); - } - - private boolean manageIkeGateway(SrxCommand command, String ikeGatewayName, Long accountId, String ikePolicyName, String ikeGatewayHostname, String username) - throws ExecutionException { - if (ikeGatewayName == null) { - ikeGatewayName = genIkeGatewayName(accountId, username); - } - - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.IKE_GATEWAY_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "gateway-name", ikeGatewayName); - return sendRequestAndCheckResponse(command, xml, "name", ikeGatewayName); - - case ADD: - if (manageIkeGateway(SrxCommand.CHECK_IF_EXISTS, ikeGatewayName, accountId, ikePolicyName, ikeGatewayHostname, username)) { - return true; - } - - xml = SrxXml.IKE_GATEWAY_ADD.getXml(); - xml = replaceXmlValue(xml, "gateway-name", ikeGatewayName); - xml = replaceXmlValue(xml, "ike-policy-name", ikePolicyName); - xml = replaceXmlValue(xml, "ike-gateway-hostname", ikeGatewayHostname); - xml = replaceXmlValue(xml, "public-interface-name", _publicInterface); - xml = replaceXmlValue(xml, "access-profile-name", genAccessProfileName(accountId, username)); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add IKE gateway: " + ikeGatewayName); - } else { - return true; - } - - case DELETE: - if (!manageIkeGateway(SrxCommand.CHECK_IF_EXISTS, ikeGatewayName, accountId, ikePolicyName, ikeGatewayHostname, username)) { - return true; - } - - xml = SrxXml.IKE_GATEWAY_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "gateway-name", ikeGatewayName); - - if (!sendRequestAndCheckResponse(command, xml, "name", ikeGatewayName)) { - throw new ExecutionException("Failed to delete IKE gateway: " + ikeGatewayName); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - } - - private String genIpsecVpnName(long accountId, String username) { - return genObjectName(_vpnObjectPrefix, String.valueOf(accountId), username); - } - - private boolean manageIpsecVpn(SrxCommand command, String ipsecVpnName, Long accountId, String guestNetworkCidr, String username, String ipsecPolicyName) - throws ExecutionException { - if (ipsecVpnName == null) { - ipsecVpnName = genIpsecVpnName(accountId, username); - } - - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.IPSEC_VPN_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "ipsec-vpn-name", ipsecVpnName); - return sendRequestAndCheckResponse(command, xml, "name", ipsecVpnName); - - case ADD: - if (manageIpsecVpn(SrxCommand.CHECK_IF_EXISTS, ipsecVpnName, accountId, guestNetworkCidr, username, ipsecPolicyName)) { - return true; - } - - xml = SrxXml.IPSEC_VPN_ADD.getXml(); - xml = replaceXmlValue(xml, "ipsec-vpn-name", ipsecVpnName); - xml = replaceXmlValue(xml, "ike-gateway", genIkeGatewayName(accountId, username)); - xml = replaceXmlValue(xml, "ipsec-policy-name", ipsecPolicyName); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add IPSec VPN: " + ipsecVpnName); - } else { - return true; - } - - case DELETE: - if (!manageIpsecVpn(SrxCommand.CHECK_IF_EXISTS, ipsecVpnName, accountId, guestNetworkCidr, username, ipsecPolicyName)) { - return true; - } - - xml = SrxXml.IPSEC_VPN_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "ipsec-vpn-name", ipsecVpnName); - - if (!sendRequestAndCheckResponse(command, xml, "name", ipsecVpnName)) { - throw new ExecutionException("Failed to delete IPSec VPN: " + ipsecVpnName); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - } - - private String genDynamicVpnClientName(long accountId, String username) { - return genObjectName(_vpnObjectPrefix, String.valueOf(accountId), username); - } - - private boolean manageDynamicVpnClient(SrxCommand command, String clientName, Long accountId, String guestNetworkCidr, String ipsecVpnName, String username) - throws ExecutionException { - if (clientName == null) { - clientName = genDynamicVpnClientName(accountId, username); - } - - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.DYNAMIC_VPN_CLIENT_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "client-name", clientName); - return sendRequestAndCheckResponse(command, xml, "name", clientName); - - case ADD: - if (manageDynamicVpnClient(SrxCommand.CHECK_IF_EXISTS, clientName, accountId, guestNetworkCidr, ipsecVpnName, username)) { - return true; - } - - xml = SrxXml.DYNAMIC_VPN_CLIENT_ADD.getXml(); - xml = replaceXmlValue(xml, "client-name", clientName); - xml = replaceXmlValue(xml, "guest-network-cidr", guestNetworkCidr); - xml = replaceXmlValue(xml, "ipsec-vpn-name", ipsecVpnName); - xml = replaceXmlValue(xml, "username", username); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add dynamic VPN client: " + clientName); - } else { - return true; - } - - case DELETE: - if (!manageDynamicVpnClient(SrxCommand.CHECK_IF_EXISTS, clientName, accountId, guestNetworkCidr, ipsecVpnName, username)) { - return true; - } - - xml = SrxXml.DYNAMIC_VPN_CLIENT_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "client-name", clientName); - - if (!sendRequestAndCheckResponse(command, xml, "name", clientName)) { - throw new ExecutionException("Failed to delete dynamic VPN client: " + clientName); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - } - - private String genAddressPoolName(long accountId) { - return genObjectName(_vpnObjectPrefix, String.valueOf(accountId)); - } - - private boolean manageAddressPool(SrxCommand command, String addressPoolName, Long accountId, String guestNetworkCidr, String lowAddress, String highAddress, - String primaryDnsAddress) throws ExecutionException { - if (addressPoolName == null) { - addressPoolName = genAddressPoolName(accountId); - } - - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.ADDRESS_POOL_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "address-pool-name", addressPoolName); - return sendRequestAndCheckResponse(command, xml, "name", addressPoolName); - - case ADD: - if (manageAddressPool(SrxCommand.CHECK_IF_EXISTS, addressPoolName, accountId, guestNetworkCidr, lowAddress, highAddress, primaryDnsAddress)) { - return true; - } - - xml = SrxXml.ADDRESS_POOL_ADD.getXml(); - xml = replaceXmlValue(xml, "address-pool-name", addressPoolName); - xml = replaceXmlValue(xml, "guest-network-cidr", guestNetworkCidr); - xml = replaceXmlValue(xml, "address-range-name", "r-" + addressPoolName); - xml = replaceXmlValue(xml, "low-address", lowAddress); - xml = replaceXmlValue(xml, "high-address", highAddress); - xml = replaceXmlValue(xml, "primary-dns-address", primaryDnsAddress); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add address pool: " + addressPoolName); - } else { - return true; - } - - case DELETE: - if (!manageAddressPool(SrxCommand.CHECK_IF_EXISTS, addressPoolName, accountId, guestNetworkCidr, lowAddress, highAddress, primaryDnsAddress)) { - return true; - } - - xml = SrxXml.ADDRESS_POOL_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "address-pool-name", addressPoolName); - - if (!sendRequestAndCheckResponse(command, xml, "name", addressPoolName)) { - throw new ExecutionException("Failed to delete address pool: " + addressPoolName); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - } - - private String genAccessProfileName(long accountId, String username) { - return genObjectName(_vpnObjectPrefix, String.valueOf(accountId), username); - } - - private boolean manageAccessProfile(SrxCommand command, String accessProfileName, Long accountId, String username, String password, String addressPoolName) - throws ExecutionException { - if (accessProfileName == null) { - accessProfileName = genAccessProfileName(accountId, username); - } - - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.ACCESS_PROFILE_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "access-profile-name", accessProfileName); - return sendRequestAndCheckResponse(command, xml, "name", username); - - case ADD: - if (manageAccessProfile(SrxCommand.CHECK_IF_EXISTS, accessProfileName, accountId, username, password, addressPoolName)) { - return true; - } - - xml = SrxXml.ACCESS_PROFILE_ADD.getXml(); - xml = replaceXmlValue(xml, "access-profile-name", accessProfileName); - xml = replaceXmlValue(xml, "username", username); - xml = replaceXmlValue(xml, "password", password); - xml = replaceXmlValue(xml, "address-pool-name", addressPoolName); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add access profile: " + accessProfileName); - } else { - return true; - } - - case DELETE: - if (!manageAccessProfile(SrxCommand.CHECK_IF_EXISTS, accessProfileName, accountId, username, password, addressPoolName)) { - return true; - } - - xml = SrxXml.ACCESS_PROFILE_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "access-profile-name", accessProfileName); - - if (!sendRequestAndCheckResponse(command, xml, "name", username)) { - throw new ExecutionException("Failed to delete access profile: " + accessProfileName); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - } - - /* - * Private interfaces - */ - - private boolean managePrivateInterface(SrxCommand command, boolean addFilters, long vlanTag, String privateInterfaceIp) throws ExecutionException { - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.PRIVATE_INTERFACE_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "private-interface-name", _privateInterface); - xml = replaceXmlValue(xml, "vlan-id", String.valueOf(vlanTag)); - return sendRequestAndCheckResponse(command, xml, "name", String.valueOf(vlanTag)); - - case ADD: - if (managePrivateInterface(SrxCommand.CHECK_IF_EXISTS, false, vlanTag, privateInterfaceIp)) { - return true; - } - - xml = addFilters ? SrxXml.PRIVATE_INTERFACE_WITH_FILTERS_ADD.getXml() : SrxXml.PRIVATE_INTERFACE_ADD.getXml(); - xml = replaceXmlValue(xml, "private-interface-name", _privateInterface); - xml = replaceXmlValue(xml, "vlan-id", String.valueOf(vlanTag)); - xml = replaceXmlValue(xml, "private-interface-ip", privateInterfaceIp); - - if (addFilters) { - xml = replaceXmlValue(xml, "input-filter-name", _usageFilterVlanInput.getName() + "-" + vlanTag); - xml = replaceXmlValue(xml, "output-filter-name", _usageFilterVlanOutput.getName() + "-" + vlanTag); - } - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add private interface for guest VLAN tag " + vlanTag); - } else { - return true; - } - - case DELETE: - if (!managePrivateInterface(SrxCommand.CHECK_IF_EXISTS, false, vlanTag, privateInterfaceIp)) { - return true; - } - - xml = SrxXml.PRIVATE_INTERFACE_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "private-interface-name", _privateInterface); - xml = replaceXmlValue(xml, "vlan-id", String.valueOf(vlanTag)); - - if (!sendRequestAndCheckResponse(command, xml, "name", String.valueOf(vlanTag))) { - throw new ExecutionException("Failed to delete private interface for guest VLAN tag " + vlanTag); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - - } - - private Long getVlanTagFromInterfaceName(String interfaceName) throws ExecutionException { - Long vlanTag = null; - - if (interfaceName.contains(".")) { - try { - String unitNum = interfaceName.split("\\.")[1]; - if (!unitNum.equals("0")) { - vlanTag = Long.parseLong(unitNum); - } - } catch (Exception e) { - s_logger.error(e); - throw new ExecutionException("Unable to parse VLAN tag from interface name: " + interfaceName); - } - } - - return vlanTag; - } - - /* - * Proxy ARP - */ - - private boolean manageProxyArp(SrxCommand command, Long publicVlanTag, String publicIp) throws ExecutionException { - String publicInterface = genPublicInterface(publicVlanTag); - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.PROXY_ARP_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "public-interface-name", publicInterface); - xml = replaceXmlValue(xml, "public-ip-address", publicIp); - return sendRequestAndCheckResponse(command, xml, "name", publicIp + "/32"); - - case CHECK_IF_IN_USE: - // Check if any NAT rules are using this proxy ARP entry - String poolName = genSourceNatPoolName(publicIp); - - String allStaticNatRules = sendRequest(SrxXml.STATIC_NAT_RULE_GETALL.getXml()); - String allDestNatRules = sendRequest(replaceXmlValue(SrxXml.DEST_NAT_RULE_GETALL.getXml(), "rule-set", _publicZone)); - String allSrcNatRules = sendRequest(SrxXml.SRC_NAT_RULE_GETALL.getXml()); - - return (allStaticNatRules.contains(publicIp) || allDestNatRules.contains(publicIp) || allSrcNatRules.contains(poolName)); - - case ADD: - if (manageProxyArp(SrxCommand.CHECK_IF_EXISTS, publicVlanTag, publicIp)) { - return true; - } - - xml = SrxXml.PROXY_ARP_ADD.getXml(); - xml = replaceXmlValue(xml, "public-interface-name", publicInterface); - xml = replaceXmlValue(xml, "public-ip-address", publicIp); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add proxy ARP entry for public IP " + publicIp); - } else { - return true; - } - - case DELETE: - if (!manageProxyArp(SrxCommand.CHECK_IF_EXISTS, publicVlanTag, publicIp)) { - return true; - } - - if (manageProxyArp(SrxCommand.CHECK_IF_IN_USE, publicVlanTag, publicIp)) { - return true; - } - - xml = SrxXml.PROXY_ARP_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "public-interface-name", publicInterface); - xml = replaceXmlValue(xml, "public-ip-address", publicIp); - - if (!sendRequestAndCheckResponse(command, xml, "name", publicIp)) { - throw new ExecutionException("Failed to delete proxy ARP entry for public IP " + publicIp); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - - } - - } - - private Map getPublicVlanTagsForPublicIps(List publicIps) throws ExecutionException { - Map publicVlanTags = new HashMap(); - - List interfaceNames = new ArrayList(); - - String xmlRequest = SrxXml.PROXY_ARP_GETALL.getXml(); - xmlRequest = replaceXmlValue(xmlRequest, "interface-name", ""); - String xmlResponse = sendRequest(xmlRequest); - - Document doc = getDocument(xmlResponse); - NodeList interfaces = doc.getElementsByTagName("interface"); - for (int i = 0; i < interfaces.getLength(); i++) { - String interfaceName = null; - NodeList interfaceEntries = interfaces.item(i).getChildNodes(); - for (int j = 0; j < interfaceEntries.getLength(); j++) { - Node interfaceEntry = interfaceEntries.item(j); - if (interfaceEntry.getNodeName().equals("name")) { - interfaceName = interfaceEntry.getFirstChild().getNodeValue(); - break; - } - } - - if (interfaceName != null) { - interfaceNames.add(interfaceName); - } - } - - if (interfaceNames.size() == 1) { - populatePublicVlanTagsMap(xmlResponse, interfaceNames.get(0), publicIps, publicVlanTags); - } else if (interfaceNames.size() > 1) { - for (String interfaceName : interfaceNames) { - xmlRequest = SrxXml.PROXY_ARP_GETALL.getXml(); - xmlRequest = replaceXmlValue(xmlRequest, "interface-name", interfaceName); - xmlResponse = sendRequest(xmlRequest); - populatePublicVlanTagsMap(xmlResponse, interfaceName, publicIps, publicVlanTags); - } - } - - return publicVlanTags; - } - - private void populatePublicVlanTagsMap(String xmlResponse, String interfaceName, List publicIps, Map publicVlanTags) throws ExecutionException { - Long publicVlanTag = getVlanTagFromInterfaceName(interfaceName); - if (publicVlanTag != null) { - for (String publicIp : publicIps) { - if (xmlResponse.contains(publicIp)) { - publicVlanTags.put(publicIp, publicVlanTag); - } - } - } - } - - private Map getPublicVlanTagsForNatRules(List natRules) throws ExecutionException { - List publicIps = new ArrayList(); - addPublicIpsToList(natRules, publicIps); - return getPublicVlanTagsForPublicIps(publicIps); - } - - private void addPublicIpsToList(List natRules, List publicIps) { - for (String[] natRule : natRules) { - if (!publicIps.contains(natRule[0])) { - publicIps.add(natRule[0]); - } - } - } - - private String genPublicInterface(Long vlanTag) { - String publicInterface = _publicInterface; - - if (!publicInterface.contains(".")) { - if (vlanTag == null) { - publicInterface += ".0"; - } else { - publicInterface += "." + vlanTag; - } - } - - return publicInterface; - } - - /* - * Zone interfaces - */ - - private String genZoneInterfaceName(long vlanTag) { - return _privateInterface + "." + String.valueOf(vlanTag); - } - - private boolean manageZoneInterface(SrxCommand command, long vlanTag) throws ExecutionException { - String zoneInterfaceName = genZoneInterfaceName(vlanTag); - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.ZONE_INTERFACE_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "private-zone-name", _privateZone); - xml = replaceXmlValue(xml, "zone-interface-name", zoneInterfaceName); - return sendRequestAndCheckResponse(command, xml, "name", zoneInterfaceName); - - case ADD: - if (manageZoneInterface(SrxCommand.CHECK_IF_EXISTS, vlanTag)) { - return true; - } - - xml = SrxXml.ZONE_INTERFACE_ADD.getXml(); - xml = replaceXmlValue(xml, "private-zone-name", _privateZone); - xml = replaceXmlValue(xml, "zone-interface-name", zoneInterfaceName); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add interface " + zoneInterfaceName + " to zone " + _privateZone); - } else { - return true; - } - - case DELETE: - if (!manageZoneInterface(SrxCommand.CHECK_IF_EXISTS, vlanTag)) { - return true; - } - - xml = SrxXml.ZONE_INTERFACE_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "private-zone-name", _privateZone); - xml = replaceXmlValue(xml, "zone-interface-name", zoneInterfaceName); - - if (!sendRequestAndCheckResponse(command, xml, "name", zoneInterfaceName)) { - throw new ExecutionException("Failed to delete interface " + zoneInterfaceName + " from zone " + _privateZone); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - } - - /* - * Static NAT rules - */ - - private String genStaticNatRuleName(String publicIp, String privateIp) { - return genObjectName(genIpIdentifier(publicIp), genIpIdentifier(privateIp)); - } - - private boolean manageStaticNatRule(SrxCommand command, String publicIp, String privateIp) throws ExecutionException { - String ruleName = genStaticNatRuleName(publicIp, privateIp); - String ruleName_private = genStaticNatRuleName(privateIp, publicIp); - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.STATIC_NAT_RULE_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "rule-set", _publicZone); - xml = replaceXmlValue(xml, "from-zone", _publicZone); - xml = replaceXmlValue(xml, "rule-name", ruleName); - return sendRequestAndCheckResponse(command, xml, "name", ruleName); - case CHECK_PRIVATE_IF_EXISTS: - xml = SrxXml.STATIC_NAT_RULE_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "rule-set", _privateZone); - xml = replaceXmlValue(xml, "from-zone", _privateZone); - xml = replaceXmlValue(xml, "rule-name", ruleName_private); - return sendRequestAndCheckResponse(command, xml, "name", ruleName_private); - case ADD: - if (!manageStaticNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateIp)) { - xml = SrxXml.STATIC_NAT_RULE_ADD.getXml(); - xml = replaceXmlValue(xml, "rule-set", _publicZone); - xml = replaceXmlValue(xml, "from-zone", _publicZone); - xml = replaceXmlValue(xml, "rule-name", ruleName); - xml = replaceXmlValue(xml, "original-ip", publicIp); - xml = replaceXmlValue(xml, "translated-ip", privateIp); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException(String.format("Failed to add static NAT rule %s -> %s on %s ", publicIp, privateIp, _publicZone)); - } - } else { - s_logger.debug(String.format("Static NAT rule %s -> %s on %s already exists", publicIp, privateIp, _publicZone)); - } - - if (!manageStaticNatRule(SrxCommand.CHECK_PRIVATE_IF_EXISTS, publicIp, privateIp)) { - xml = SrxXml.STATIC_NAT_RULE_ADD.getXml(); - xml = replaceXmlValue(xml, "rule-set", _privateZone); - xml = replaceXmlValue(xml, "from-zone", _privateZone); - xml = replaceXmlValue(xml, "rule-name", ruleName_private); - xml = replaceXmlValue(xml, "original-ip", publicIp); - xml = replaceXmlValue(xml, "translated-ip", privateIp); - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException(String.format("Failed to add static NAT rule %s -> %s on %s ", publicIp, privateIp, _privateZone)); - } - } else { - s_logger.debug(String.format("Static NAT rule %s -> %s on %s already exists", publicIp, privateIp, _privateZone)); - } - - return true; - - case DELETE: - if (manageStaticNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateIp)) { - xml = SrxXml.STATIC_NAT_RULE_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "rule-set", _publicZone); - xml = replaceXmlValue(xml, "from-zone", _publicZone); - xml = replaceXmlValue(xml, "rule-name", ruleName); - - if (!sendRequestAndCheckResponse(command, xml, "name", ruleName)) { - throw new ExecutionException(String.format("Failed to delete static NAT rule %s -> %s on %s", publicIp, privateIp, _publicZone)); - } - } else { - s_logger.debug(String.format("Static NAT rule %s -> %s on %s not found", publicIp, privateIp, _publicZone)); - } - - if (manageStaticNatRule(SrxCommand.CHECK_PRIVATE_IF_EXISTS, publicIp, privateIp)){ - xml = SrxXml.STATIC_NAT_RULE_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "rule-set", _privateZone); - xml = replaceXmlValue(xml, "from-zone", _privateZone); - xml = replaceXmlValue(xml, "rule-name", ruleName_private); - - if (!sendRequestAndCheckResponse(command, xml, "name", ruleName_private)) - { - throw new ExecutionException(String.format("Failed to delete static NAT rule %s -> %s on %s", publicIp, privateIp, _privateZone)); - } - } else { - s_logger.debug(String.format("Static NAT rule %s -> %s on %s not found", publicIp, privateIp, _privateZone)); - } - - return true; - - default: - throw new ExecutionException("Unrecognized command."); - - } - } - - private List getStaticNatRules(RuleMatchCondition condition, String privateGateway, Long privateCidrSize) throws ExecutionException { - List staticNatRules = new ArrayList(); - - String xmlRequest = SrxXml.STATIC_NAT_RULE_GETALL.getXml(); - String xmlResponse = sendRequest(xmlRequest); - Document doc = getDocument(xmlResponse); - NodeList rules = doc.getElementsByTagName("rule"); - for (int i = 0; i < rules.getLength(); i++) { - NodeList ruleEntries = rules.item(i).getChildNodes(); - for (int j = 0; j < ruleEntries.getLength(); j++) { - Node ruleEntry = ruleEntries.item(j); - if (ruleEntry.getNodeName().equals("name")) { - String name = ruleEntry.getFirstChild().getNodeValue(); - String[] nameContents = name.split("-"); - - if (nameContents.length != 8) { - continue; - } - - String rulePublicIp = nameContents[0] + "." + nameContents[1] + "." + nameContents[2] + "." + nameContents[3]; - String rulePrivateIp = nameContents[4] + "." + nameContents[5] + "." + nameContents[6] + "." + nameContents[7]; - - boolean addToList = false; - if (condition.equals(RuleMatchCondition.ALL)) { - addToList = true; - } else if (condition.equals(RuleMatchCondition.PRIVATE_SUBNET)) { - assert (privateGateway != null && privateCidrSize != null); - addToList = NetUtils.sameSubnetCIDR(rulePrivateIp, privateGateway, privateCidrSize); - } else { - s_logger.error("Invalid rule match condition."); - assert false; - } - - if (addToList) { - staticNatRules.add(new String[] {rulePublicIp, rulePrivateIp}); - } - } - } - } - - return staticNatRules; - } - - /* - * Destination NAT pools - */ - - private String genDestinationNatPoolName(String privateIp, long destPort) { - return genObjectName(genIpIdentifier(privateIp), String.valueOf(destPort)); - } - - private boolean manageDestinationNatPool(SrxCommand command, String privateIp, long destPort) throws ExecutionException { - String poolName = genDestinationNatPoolName(privateIp, destPort); - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.DEST_NAT_POOL_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "pool-name", poolName); - return sendRequestAndCheckResponse(command, xml, "name", poolName); - - case CHECK_IF_IN_USE: - // Check if any destination nat rules refer to this pool - xml = SrxXml.DEST_NAT_RULE_GETALL.getXml(); - xml = replaceXmlValue(xml, "rule-set", _publicZone); - return sendRequestAndCheckResponse(command, xml, "pool-name", poolName); - - case ADD: - if (!manageDestinationNatPool(SrxCommand.CHECK_IF_EXISTS, privateIp, destPort)) { - xml = SrxXml.DEST_NAT_POOL_ADD.getXml(); - xml = replaceXmlValue(xml, "pool-name", poolName); - xml = replaceXmlValue(xml, "private-address", privateIp + "/32"); - xml = replaceXmlValue(xml, "dest-port", String.valueOf(destPort)); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException(String.format("Failed to add Destination NAT pool for %s:%s", privateIp, destPort)); - } - } else { - s_logger.debug(String.format("Destination NAT pool for %s:%s already exists", privateIp, destPort)); - return true; - } - - return true; - - case DELETE: - if (manageDestinationNatPool(SrxCommand.CHECK_IF_EXISTS, privateIp, destPort)) { - if (!manageDestinationNatPool(SrxCommand.CHECK_IF_IN_USE, privateIp, destPort)) { - xml = SrxXml.DEST_NAT_POOL_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "pool-name", poolName); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException(String.format("Failed to delete Destination NAT pool for %s:%s", privateIp, destPort)); - } - } else { - s_logger.debug(String.format("Destination NAT pool for %s:%s is in use, not deleting", privateIp, destPort)); - } - } else { - s_logger.debug(String.format("Did not find Destination NAT pool for %s:%s to delete", privateIp, destPort)); - } - return true; - - default: - throw new ExecutionException("Unrecognized command."); - } - } - - /* - * Destination NAT rules - */ - - private String genDestinationNatRuleName(String publicIp, String privateIp, long srcPort, long destPort) { - return "destnatrule-" + - String.valueOf(genObjectName(publicIp, privateIp, String.valueOf(srcPort), String.valueOf(destPort)).hashCode()).replaceAll("[^a-zA-Z0-9]", ""); - } - - private boolean manageDestinationNatRule(SrxCommand command, String publicIp, String privateIp, long srcPort, long destPort) throws ExecutionException { - String ruleName = genDestinationNatRuleName(publicIp, privateIp, srcPort, destPort); - String ruleName_private = ruleName + "p"; - String poolName = genDestinationNatPoolName(privateIp, destPort); - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.DEST_NAT_RULE_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "rule-set", _publicZone); - xml = replaceXmlValue(xml, "from-zone", _publicZone); - xml = replaceXmlValue(xml, "rule-name", ruleName); - return sendRequestAndCheckResponse(command, xml, "name", ruleName); - case CHECK_PRIVATE_IF_EXISTS: - xml = SrxXml.DEST_NAT_RULE_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "rule-set", _privateZone); - xml = replaceXmlValue(xml, "from-zone", _privateZone); - xml = replaceXmlValue(xml, "rule-name", ruleName_private); - return sendRequestAndCheckResponse(command, xml, "name", ruleName_private); - case ADD: - // Add untrust rule - if (!manageDestinationNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateIp, srcPort, destPort)) { - if (!manageDestinationNatPool(SrxCommand.CHECK_IF_EXISTS, privateIp, destPort)) { // Added elsewhere - throw new ExecutionException(String.format("Destination NAT pool for %s:%s does not exist", privateIp, destPort)); - } - - xml = SrxXml.DEST_NAT_RULE_ADD.getXml(); - xml = replaceXmlValue(xml, "rule-set", _publicZone); - xml = replaceXmlValue(xml, "from-zone", _publicZone); - xml = replaceXmlValue(xml, "rule-name", ruleName); - xml = replaceXmlValue(xml, "public-address", publicIp); - xml = replaceXmlValue(xml, "src-port", String.valueOf(srcPort)); - xml = replaceXmlValue(xml, "pool-name", poolName); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException(String.format("Failed to add Destination NAT rule %s:%s -> %s:%s on %s", - publicIp, srcPort, privateIp, destPort, _publicZone)); - } - } else { - s_logger.debug(String.format("Destination NAT rule for %s:%s -> %s:%s on %s already exists", - publicIp, srcPort, privateIp, destPort, _publicZone)); - } - - // Add trust rule - if (!manageDestinationNatRule(SrxCommand.CHECK_PRIVATE_IF_EXISTS, publicIp, privateIp, srcPort, destPort)) { - xml = SrxXml.DEST_NAT_RULE_ADD.getXml(); - xml = replaceXmlValue(xml, "rule-set", _privateZone); - xml = replaceXmlValue(xml, "from-zone", _privateZone); - xml = replaceXmlValue(xml, "rule-name", ruleName_private); - xml = replaceXmlValue(xml, "public-address", publicIp); - xml = replaceXmlValue(xml, "src-port", String.valueOf(srcPort)); - xml = replaceXmlValue(xml, "pool-name", poolName); - - if (!sendRequestAndCheckResponse(command, xml)) - { - throw new ExecutionException(String.format("Failed to add Destination NAT rule %s:%s -> %s:%s on %s", - publicIp, srcPort, privateIp, destPort, _privateZone)); - } - } else { - s_logger.debug(String.format("Destination NAT rule for %s:%s -> %s:%s on %s already exists", - publicIp, srcPort, privateIp, destPort, _privateZone)); - } - - return true; - - case DELETE: - // Delete public rule - if (manageDestinationNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateIp, srcPort, destPort)) { - xml = SrxXml.DEST_NAT_RULE_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "rule-set", _publicZone); - xml = replaceXmlValue(xml, "from-zone", _publicZone); - xml = replaceXmlValue(xml, "rule-name", ruleName); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException(String.format("Failed to delete destination NAT rule %s[%s] -> %s[%s] on rule %s", - publicIp, srcPort, privateIp, destPort, _publicZone)); - } - } else { - s_logger.debug(String.format("Destination NAT rule %s[%s] -> %s[%s] not found on %s, not deleting", - publicIp, srcPort, privateIp, destPort, _publicZone)); - } - - // Delete private rule - if (manageDestinationNatRule(SrxCommand.CHECK_PRIVATE_IF_EXISTS, publicIp, privateIp, srcPort, destPort)) { - xml = SrxXml.DEST_NAT_RULE_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "rule-set", _privateZone); - xml = replaceXmlValue(xml, "from-zone", _privateZone); - xml = replaceXmlValue(xml, "rule-name", ruleName_private); - - if (!sendRequestAndCheckResponse(command, xml)) - { - throw new ExecutionException(String.format("Failed to delete destination NAT rule %s[%s] -> %s[%s] on rule %s", - publicIp, srcPort, privateIp, destPort, _privateZone)); - } - } else { - s_logger.debug(String.format("Destination NAT rule %s[%s] -> %s[%s] not found on %s, not deleting", - publicIp, srcPort, privateIp, destPort, _privateZone)); - } - - return true; - - default: - s_logger.debug("Unrecognized command."); - return false; - } - - } - - private List getDestNatRules(RuleMatchCondition condition, String publicIp, String privateIp, String privateGateway, Long privateCidrSize) - throws ExecutionException { - List destNatRules = new ArrayList(); - - String xmlRequest = SrxXml.DEST_NAT_RULE_GETALL.getXml(); - xmlRequest = replaceXmlValue(xmlRequest, "rule-set", _publicZone); - String xmlResponse = sendRequest(xmlRequest); - Document doc = getDocument(xmlResponse); - NodeList rules = doc.getElementsByTagName("rule"); - for (int ruleIndex = 0; ruleIndex < rules.getLength(); ruleIndex++) { - String rulePublicIp = null; - String rulePrivateIp = null; - String ruleSrcPort = null; - String ruleDestPort = null; - NodeList ruleEntries = rules.item(ruleIndex).getChildNodes(); - for (int ruleEntryIndex = 0; ruleEntryIndex < ruleEntries.getLength(); ruleEntryIndex++) { - Node ruleEntry = ruleEntries.item(ruleEntryIndex); - if (ruleEntry.getNodeName().equals("dest-nat-rule-match")) { - NodeList ruleMatchEntries = ruleEntry.getChildNodes(); - for (int ruleMatchIndex = 0; ruleMatchIndex < ruleMatchEntries.getLength(); ruleMatchIndex++) { - Node ruleMatchEntry = ruleMatchEntries.item(ruleMatchIndex); - if (ruleMatchEntry.getNodeName().equals("destination-address")) { - NodeList destAddressEntries = ruleMatchEntry.getChildNodes(); - for (int destAddressIndex = 0; destAddressIndex < destAddressEntries.getLength(); destAddressIndex++) { - Node destAddressEntry = destAddressEntries.item(destAddressIndex); - if (destAddressEntry.getNodeName().equals("dst-addr")) { - rulePublicIp = destAddressEntry.getFirstChild().getNodeValue().split("/")[0]; - } - } - } else if (ruleMatchEntry.getNodeName().equals("destination-port")) { - NodeList destPortEntries = ruleMatchEntry.getChildNodes(); - for (int destPortIndex = 0; destPortIndex < destPortEntries.getLength(); destPortIndex++) { - Node destPortEntry = destPortEntries.item(destPortIndex); - if (destPortEntry.getNodeName().equals("dst-port") || destPortEntry.getNodeName().equals("name")) { - ruleSrcPort = destPortEntry.getFirstChild().getNodeValue(); - } - } - } - } - } else if (ruleEntry.getNodeName().equals("then")) { - NodeList ruleThenEntries = ruleEntry.getChildNodes(); - for (int ruleThenIndex = 0; ruleThenIndex < ruleThenEntries.getLength(); ruleThenIndex++) { - Node ruleThenEntry = ruleThenEntries.item(ruleThenIndex); - if (ruleThenEntry.getNodeName().equals("destination-nat")) { - NodeList destNatEntries = ruleThenEntry.getChildNodes(); - for (int destNatIndex = 0; destNatIndex < destNatEntries.getLength(); destNatIndex++) { - Node destNatEntry = destNatEntries.item(destNatIndex); - if (destNatEntry.getNodeName().equals("pool")) { - NodeList poolEntries = destNatEntry.getChildNodes(); - for (int poolIndex = 0; poolIndex < poolEntries.getLength(); poolIndex++) { - Node poolEntry = poolEntries.item(poolIndex); - if (poolEntry.getNodeName().equals("pool-name")) { - String[] poolName = poolEntry.getFirstChild().getNodeValue().split("-"); - if (poolName.length == 5) { - rulePrivateIp = poolName[0] + "." + poolName[1] + "." + poolName[2] + "." + poolName[3]; - ruleDestPort = poolName[4]; - } - } - } - } - } - } - } - } - } - - if (rulePublicIp == null || rulePrivateIp == null || ruleSrcPort == null || ruleDestPort == null) { - continue; - } - - boolean addToList = false; - if (condition.equals(RuleMatchCondition.ALL)) { - addToList = true; - } else if (condition.equals(RuleMatchCondition.PUBLIC_PRIVATE_IPS)) { - assert (publicIp != null && privateIp != null); - addToList = publicIp.equals(rulePublicIp) && privateIp.equals(rulePrivateIp); - } else if (condition.equals(RuleMatchCondition.PRIVATE_SUBNET)) { - assert (privateGateway != null && privateCidrSize != null); - addToList = NetUtils.sameSubnetCIDR(rulePrivateIp, privateGateway, privateCidrSize); - } - - if (addToList) { - destNatRules.add(new String[] {rulePublicIp, rulePrivateIp, ruleSrcPort, ruleDestPort}); - } - } - - return destNatRules; - } - - /* - * Source NAT pools - */ - - private String genSourceNatPoolName(String publicIp) { - return genObjectName(genIpIdentifier(publicIp)); - } - - private boolean manageSourceNatPool(SrxCommand command, String publicIp) throws ExecutionException { - String poolName = genSourceNatPoolName(publicIp); - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.SRC_NAT_POOL_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "pool-name", poolName); - return sendRequestAndCheckResponse(command, xml, "name", poolName); - - case CHECK_IF_IN_USE: - // Check if any source nat rules refer to this pool - xml = SrxXml.SRC_NAT_RULE_GETALL.getXml(); - return sendRequestAndCheckResponse(command, xml, "pool-name", poolName); - - case ADD: - if (manageSourceNatPool(SrxCommand.CHECK_IF_EXISTS, publicIp)) { - return true; - } - - xml = SrxXml.SRC_NAT_POOL_ADD.getXml(); - xml = replaceXmlValue(xml, "pool-name", poolName); - xml = replaceXmlValue(xml, "address", publicIp + "/32"); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add source NAT pool for public IP " + publicIp); - } else { - return true; - } - - case DELETE: - if (!manageSourceNatPool(SrxCommand.CHECK_IF_EXISTS, publicIp)) { - return true; - } - - if (manageSourceNatPool(SrxCommand.CHECK_IF_IN_USE, publicIp)) { - return true; - } - - xml = SrxXml.SRC_NAT_POOL_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "pool-name", poolName); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to delete source NAT pool for public IP " + publicIp); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - } - - /* - * Source NAT rules - */ - - private String genSourceNatRuleName(String publicIp, String privateSubnet) { - return genObjectName(genIpIdentifier(publicIp), genIpIdentifier(privateSubnet)); - } - - private boolean manageSourceNatRule(SrxCommand command, String publicIp, String privateSubnet) throws ExecutionException { - String ruleName = genSourceNatRuleName(publicIp, privateSubnet); - String poolName = genSourceNatPoolName(publicIp); - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.SRC_NAT_RULE_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "rule-set", _privateZone); - xml = replaceXmlValue(xml, "from-zone", _privateZone); - xml = replaceXmlValue(xml, "rule-name", ruleName); - return sendRequestAndCheckResponse(command, xml, "name", ruleName); - - case ADD: - if (manageSourceNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateSubnet)) { - return true; - } - - if (!manageSourceNatPool(SrxCommand.CHECK_IF_EXISTS, publicIp)) { - throw new ExecutionException("The source NAT pool corresponding to " + publicIp + " does not exist."); - } - - xml = SrxXml.SRC_NAT_RULE_ADD.getXml(); - xml = replaceXmlValue(xml, "rule-set", _privateZone); - xml = replaceXmlValue(xml, "from-zone", _privateZone); - xml = replaceXmlValue(xml, "to-zone", _publicZone); - xml = replaceXmlValue(xml, "rule-name", ruleName); - xml = replaceXmlValue(xml, "private-subnet", privateSubnet); - xml = replaceXmlValue(xml, "pool-name", poolName); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add source NAT rule for public IP " + publicIp + " and private subnet " + privateSubnet); - } else { - return true; - } - - case DELETE: - if (!manageSourceNatRule(SrxCommand.CHECK_IF_EXISTS, publicIp, privateSubnet)) { - return true; - } - - xml = SrxXml.SRC_NAT_RULE_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "rule-set", _privateZone); - xml = replaceXmlValue(xml, "from-zone", _privateZone); - xml = replaceXmlValue(xml, "rule-name", ruleName); - - if (!sendRequestAndCheckResponse(command, xml, "name", ruleName)) { - throw new ExecutionException("Failed to delete source NAT rule for public IP " + publicIp + " and private subnet " + privateSubnet); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - - } - - /* - * Address book entries - */ - - private String genAddressBookEntryName(String ip) { - if (ip == null) { - return "any"; - } else { - return genIpIdentifier(ip); - } - } - - private boolean manageAddressBookEntry(SrxCommand command, String zone, String ip, String entryName) throws ExecutionException { - if (!zone.equals(_publicZone) && !zone.equals(_privateZone)) { - throw new ExecutionException("Invalid zone."); - } - - if (entryName == null) { - entryName = genAddressBookEntryName(ip); - } - - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.ADDRESS_BOOK_ENTRY_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "zone", zone); - xml = replaceXmlValue(xml, "entry-name", entryName); - return sendRequestAndCheckResponse(command, xml, "name", entryName); - - case CHECK_IF_IN_USE: - // Check if any security policies refer to this address book entry - xml = SrxXml.SECURITY_POLICY_GETALL.getXml(); - String fromZone = zone.equals(_publicZone) ? _privateZone : _publicZone; - xml = replaceXmlValue(xml, "from-zone", fromZone); - xml = replaceXmlValue(xml, "to-zone", zone); - return sendRequestAndCheckResponse(command, xml, "destination-address", entryName); - - case ADD: - if (manageAddressBookEntry(SrxCommand.CHECK_IF_EXISTS, zone, ip, entryName)) { - return true; - } - - xml = SrxXml.ADDRESS_BOOK_ENTRY_ADD.getXml(); - xml = replaceXmlValue(xml, "zone", zone); - xml = replaceXmlValue(xml, "entry-name", entryName); - xml = replaceXmlValue(xml, "ip", ip); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add address book entry for IP " + ip + " in zone " + zone); - } else { - return true; - } - - case DELETE: - if (!manageAddressBookEntry(SrxCommand.CHECK_IF_EXISTS, zone, ip, entryName)) { - return true; - } - - if (manageAddressBookEntry(SrxCommand.CHECK_IF_IN_USE, zone, ip, entryName)) { - return true; - } - - xml = SrxXml.ADDRESS_BOOK_ENTRY_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "zone", zone); - xml = replaceXmlValue(xml, "entry-name", entryName); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to delete address book entry for IP " + ip + " in zone " + zone); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - - } - - } - - /* - * Applications - */ - - private String genApplicationName(SecurityPolicyType type, Protocol protocol, int startPort, int endPort) { - if (protocol.equals(Protocol.any)) { - return Protocol.any.toString(); - } else { - if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) { - return genObjectName(type.getIdentifier(), protocol.toString(), String.valueOf(startPort), String.valueOf(endPort)); - } else { - return genObjectName(protocol.toString(), String.valueOf(startPort), String.valueOf(endPort)); - } - } - } - - private Object[] parseApplicationName(SecurityPolicyType type, String applicationName) throws ExecutionException { - String errorMsg = "Invalid application: " + applicationName; - String[] applicationComponents = applicationName.split("-"); - - Protocol protocol; - Integer startPort; - Integer endPort; - int offset = 0; - try { - offset = (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) ? 1 : 0; - protocol = getProtocol(applicationComponents[offset + 0]); - startPort = Integer.parseInt(applicationComponents[offset + 1]); - endPort = Integer.parseInt(applicationComponents[offset + 2]); - } catch (Exception e) { - throw new ExecutionException(errorMsg); - } - - return new Object[] {protocol, startPort, endPort}; - } - - private boolean manageApplication(SecurityPolicyType type, SrxCommand command, Protocol protocol, int startPort, int endPort) throws ExecutionException { - if (protocol.equals(Protocol.any)) { - return true; - } - - String applicationName = genApplicationName(type, protocol, startPort, endPort); - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.APPLICATION_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "name", applicationName); - return sendRequestAndCheckResponse(command, xml, "name", applicationName); - - case ADD: - if (manageApplication(type, SrxCommand.CHECK_IF_EXISTS, protocol, startPort, endPort)) { - return true; - } - String icmpOrDestPort; - xml = SrxXml.APPLICATION_ADD.getXml(); - xml = replaceXmlValue(xml, "name", applicationName); - xml = replaceXmlValue(xml, "protocol", protocol.toString()); - if (protocol.toString().equals(Protocol.icmp.toString())) { - icmpOrDestPort = "" + startPort + ""; - icmpOrDestPort += "" + endPort + ""; - } else { - String destPort; - - if (startPort == endPort) { - destPort = String.valueOf(startPort); - } else { - destPort = startPort + "-" + endPort; - } - icmpOrDestPort = "" + destPort + ""; - } - - xml = replaceXmlValue(xml, "dest-port-icmp", icmpOrDestPort); - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add application " + applicationName); - } else { - return true; - } - - case DELETE: - if (!manageApplication(type, SrxCommand.CHECK_IF_EXISTS, protocol, startPort, endPort)) { - return true; - } - - xml = SrxXml.APPLICATION_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "name", applicationName); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to delete application " + applicationName); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - } - - } - - private List getUnusedApplications(List applications, String fromZone, String toZone) throws ExecutionException { - List unusedApplications = new ArrayList(); - - // Check if any of the applications are unused by existing security policies - String xml = SrxXml.SECURITY_POLICY_GETALL.getXml(); - xml = replaceXmlValue(xml, "from-zone", fromZone); - xml = replaceXmlValue(xml, "to-zone", toZone); - String allPolicies = sendRequest(xml); - - for (String application : applications) { - if (!application.equals(Protocol.any.toString()) && !allPolicies.contains(application)) { - unusedApplications.add(application); - } - } - - return unusedApplications; - } - - private List getApplicationsForSecurityPolicy(SecurityPolicyType type, String privateIp, String fromZone, String toZone) throws ExecutionException { - String policyName = genSecurityPolicyName(type, null, null, fromZone, toZone, privateIp); - String xml = SrxXml.SECURITY_POLICY_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "from-zone", fromZone); - xml = replaceXmlValue(xml, "to-zone", toZone); - xml = replaceXmlValue(xml, "policy-name", policyName); - String policy = sendRequest(xml); - - Document doc = getDocument(policy); - - List policyApplications = new ArrayList(); - NodeList applicationNodes = doc.getElementsByTagName("application"); - - for (int i = 0; i < applicationNodes.getLength(); i++) { - Node applicationNode = applicationNodes.item(i); - policyApplications.add(applicationNode.getFirstChild().getNodeValue()); - } - - return policyApplications; - } - - private List extractApplications(List rules) throws ExecutionException { - List applications = new ArrayList(); - - for (FirewallRuleTO rule : rules) { - Object[] application = new Object[3]; - application[0] = getProtocol(rule.getProtocol()); - if (application[0] == Protocol.icmp) { - if (rule.getIcmpType() == -1) { - application[1] = 255; - } else { - application[1] = rule.getIcmpType(); - } - - if (rule.getIcmpCode() == -1) { - application[2] = 255; - } else { - application[2] = rule.getIcmpCode(); - } - } else if (application[0] == Protocol.tcp || application[0] == Protocol.udp) { - if (rule.getSrcPortRange() != null) { - application[1] = rule.getSrcPortRange()[0]; - application[2] = rule.getSrcPortRange()[1]; - } else { - application[1] = 0; - application[2] = 65535; - } - } else if (application[0] == Protocol.all) { - application[1] = 0; - application[2] = 65535; - } - - applications.add(application); - } - - return applications; - } - - /* - * Security policies - */ - - private String genSecurityPolicyName(SecurityPolicyType type, Long accountId, String username, String fromZone, String toZone, String translatedIp) { - if (type.equals(SecurityPolicyType.VPN)) { - return genObjectName(_vpnObjectPrefix, String.valueOf(accountId), username); - } else { - return genObjectName(type.getIdentifier(), fromZone, toZone, genIpIdentifier(translatedIp)); - } - } - - private boolean manageSecurityPolicy(SecurityPolicyType type, SrxCommand command, Long accountId, String username, String privateIp, List applicationNames, - List cidrs, String ipsecVpnName, boolean defaultEgressAction) throws ExecutionException { - String fromZone = _publicZone; - String toZone = _privateZone; - - String securityPolicyName; - String addressBookEntryName = null; - - if (type.equals(SecurityPolicyType.VPN) && ipsecVpnName != null) { - securityPolicyName = ipsecVpnName; - addressBookEntryName = ipsecVpnName; - } else if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) { - fromZone = _privateZone; - toZone = _publicZone; - securityPolicyName = genSecurityPolicyName(type, accountId, username, fromZone, toZone, privateIp); - } else { - securityPolicyName = genSecurityPolicyName(type, accountId, username, fromZone, toZone, privateIp); - addressBookEntryName = genAddressBookEntryName(privateIp); - } - - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.SECURITY_POLICY_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "from-zone", fromZone); - xml = replaceXmlValue(xml, "to-zone", toZone); - xml = replaceXmlValue(xml, "policy-name", securityPolicyName); - - return sendRequestAndCheckResponse(command, xml, "name", securityPolicyName); - - case CHECK_IF_IN_USE: - List rulesToCheck = null; - if (type.equals(SecurityPolicyType.STATIC_NAT)) { - // Check if any static NAT rules rely on this security policy - rulesToCheck = getStaticNatRules(RuleMatchCondition.ALL, null, null); - } else if (type.equals(SecurityPolicyType.DESTINATION_NAT)) { - // Check if any destination NAT rules rely on this security policy - rulesToCheck = getDestNatRules(RuleMatchCondition.ALL, null, null, null, null); - } else { - return false; - } - - for (String[] rule : rulesToCheck) { - String rulePrivateIp = rule[1]; - if (privateIp.equals(rulePrivateIp)) { - return true; - } - } - - return false; - - case ADD: - if (!(type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT))) { - if (!manageAddressBookEntry(SrxCommand.CHECK_IF_EXISTS, toZone, privateIp, addressBookEntryName)) { - throw new ExecutionException("No address book entry for policy: " + securityPolicyName); - } - } - - String srcAddrs = ""; - String dstAddrs = ""; - String action = ""; - xml = SrxXml.SECURITY_POLICY_ADD.getXml(); - xml = replaceXmlValue(xml, "policy-name", securityPolicyName); - if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) { - xml = replaceXmlValue(xml, "from-zone", _privateZone); - xml = replaceXmlValue(xml, "to-zone", _publicZone); - if (cidrs == null || cidrs.size() == 0) { - srcAddrs = "any"; - } else { - for (String cidr : cidrs) { - srcAddrs += "" + genAddressBookEntryName(cidr) + ""; - } - } - xml = replaceXmlValue(xml, "src-address", srcAddrs); - dstAddrs = "any"; - xml = replaceXmlValue(xml, "dst-address", dstAddrs); - if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) { - if (defaultEgressAction == false) { - //for default policy is false add default deny rules - action = ""; - } else { - action = ""; - } - } else { - if (defaultEgressAction == true) { - //configure egress rules to deny the traffic when default egress is allow - action = ""; - } else { - action = ""; - } - - } - xml = replaceXmlValue(xml, "action", action); - } else { - xml = replaceXmlValue(xml, "from-zone", fromZone); - xml = replaceXmlValue(xml, "to-zone", toZone); - srcAddrs = "any"; - xml = replaceXmlValue(xml, "src-address", srcAddrs); - dstAddrs = "" + addressBookEntryName + ""; - xml = replaceXmlValue(xml, "dst-address", dstAddrs); - } - - if (type.equals(SecurityPolicyType.VPN) && ipsecVpnName != null) { - xml = replaceXmlValue(xml, "tunnel", "" + ipsecVpnName + ""); - } else { - xml = replaceXmlValue(xml, "tunnel", ""); - if (!(type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS))) { - action = ""; - xml = replaceXmlValue(xml, "action", action); - } - } - - String applications; - if (applicationNames == null || applicationNames.size() == 0) { - applications = "any"; - } else { - applications = ""; - for (String applicationName : applicationNames) { - applications += "" + applicationName + ""; - } - } - - xml = replaceXmlValue(xml, "applications", applications); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add security policy for privateIp " + privateIp + " and applications " + applicationNames); - } else { - return true; - } - - case DELETE: - if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, privateIp, applicationNames, cidrs, ipsecVpnName, defaultEgressAction)) { - return true; - } - - if (manageSecurityPolicy(type, SrxCommand.CHECK_IF_IN_USE, null, null, privateIp, applicationNames, cidrs, ipsecVpnName, defaultEgressAction)) { - return true; - } - - xml = SrxXml.SECURITY_POLICY_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "from-zone", fromZone); - xml = replaceXmlValue(xml, "to-zone", toZone); - xml = replaceXmlValue(xml, "policy-name", securityPolicyName); - - boolean success = sendRequestAndCheckResponse(command, xml); - - if (success) { - xml = SrxXml.SECURITY_POLICY_GETALL.getXml(); - xml = replaceXmlValue(xml, "from-zone", fromZone); - xml = replaceXmlValue(xml, "to-zone", toZone); - String getAllResponseXml = sendRequest(xml); - - if (getAllResponseXml == null) { - throw new ExecutionException("Deleted security policy, but failed to delete security policy group."); - } - - if (!getAllResponseXml.contains(fromZone) || !getAllResponseXml.contains(toZone)) { - return true; - } else if (!getAllResponseXml.contains("match") && !getAllResponseXml.contains("then")) { - xml = SrxXml.SECURITY_POLICY_GROUP.getXml(); - xml = replaceXmlValue(xml, "from-zone", fromZone); - xml = replaceXmlValue(xml, "to-zone", toZone); - xml = setDelete(xml, true); - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Deleted security policy, but failed to delete security policy group."); - } else { - return true; - } - } else { - return true; - } - } else { - throw new ExecutionException("Failed to delete security policy for privateIp " + privateIp + " and applications " + applicationNames); - } - - default: - s_logger.debug("Unrecognized command."); - return false; - - } - } - - private boolean addSecurityPolicyAndApplications(SecurityPolicyType type, String privateIp, List applications) throws ExecutionException { - // Add all necessary applications - List applicationNames = new ArrayList(); - for (Object[] application : applications) { - Protocol protocol = (Protocol)application[0]; - int startPort = application[1] != null ? ((Integer)application[1]) : -1; - int endPort = application[2] != null ? ((Integer)application[2]) : -1; - - String applicationName = genApplicationName(type, protocol, startPort, endPort); - if (!applicationNames.contains(applicationName)) { - applicationNames.add(applicationName); - } - - manageApplication(type, SrxCommand.ADD, protocol, startPort, endPort); - } - - // Add a new security policy - manageSecurityPolicy(type, SrxCommand.ADD, null, null, privateIp, applicationNames, null, null, false); - - return true; - } - - private boolean removeSecurityPolicyAndApplications(SecurityPolicyType type, String privateIp) throws ExecutionException { - if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, privateIp, null, null, null, false)) { - return true; - } - - if (manageSecurityPolicy(type, SrxCommand.CHECK_IF_IN_USE, null, null, privateIp, null, null, null, false)) { - return true; - } - - // Get a list of applications for this security policy - List applications = getApplicationsForSecurityPolicy(type, privateIp, _publicZone, _privateZone); - - // Remove the security policy - manageSecurityPolicy(type, SrxCommand.DELETE, null, null, privateIp, null, null, null, false); - - // Remove any applications for the removed security policy that are no longer in use - List unusedApplications = getUnusedApplications(applications, _publicZone, _privateZone); - for (String application : unusedApplications) { - Object[] applicationComponents; - - try { - applicationComponents = parseApplicationName(type, application); - } catch (ExecutionException e) { - s_logger.error("Found an invalid application: " + application + ". Not attempting to clean up."); - continue; - } - - Protocol protocol = (Protocol)applicationComponents[0]; - Integer startPort = (Integer)applicationComponents[1]; - Integer endPort = (Integer)applicationComponents[2]; - manageApplication(type, SrxCommand.DELETE, protocol, startPort, endPort); - } - - return true; - } - - private boolean removeEgressSecurityPolicyAndApplications(SecurityPolicyType type, String guestVlan, List cidrs, boolean defaultEgressAction) - throws ExecutionException { - if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, guestVlan, null, cidrs, null, defaultEgressAction)) { - return true; - } - // Get a list of applications for this security policy - List applications; - applications = getApplicationsForSecurityPolicy(type, guestVlan, _privateZone, _publicZone); - - // Remove the security policy even if it is in use - manageSecurityPolicy(type, SrxCommand.DELETE, null, null, guestVlan, null, cidrs, null, defaultEgressAction); - - // Remove any applications for the removed security policy that are no longer in use - List unusedApplications; - unusedApplications = getUnusedApplications(applications, _privateZone, _publicZone); - - for (String application : unusedApplications) { - Object[] applicationComponents; - - try { - applicationComponents = parseApplicationName(type, application); - } catch (ExecutionException e) { - s_logger.error("Found an invalid application: " + application + ". Not attempting to clean up."); - continue; - } - - Protocol protocol = (Protocol)applicationComponents[0]; - Integer startPort = (Integer)applicationComponents[1]; - Integer endPort = (Integer)applicationComponents[2]; - manageApplication(type, SrxCommand.DELETE, protocol, startPort, endPort); - } - for (String cidr : cidrs) { - manageAddressBookEntry(SrxCommand.DELETE, _publicZone, cidr, null); - } - - return true; - } - - private boolean addEgressSecurityPolicyAndApplications(SecurityPolicyType type, String guestVlan, List applications, List cidrs, - boolean defaultEgressAction) throws ExecutionException { - // Add all necessary applications - List applicationNames = new ArrayList(); - for (Object[] application : applications) { - Protocol protocol = (Protocol)application[0]; - if (!protocol.equals(Protocol.all)) { - int startPort = application[1] != null ? ((Integer)application[1]) : 0; - int endPort = application[2] != null ? ((Integer)application[2]) : 65535; - - String applicationName = genApplicationName(type, protocol, startPort, endPort); - if (!applicationNames.contains(applicationName)) { - applicationNames.add(applicationName); - } - manageApplication(type, SrxCommand.ADD, protocol, startPort, endPort); - } - } - - for (String cidr : cidrs) { - manageAddressBookEntry(SrxCommand.ADD, _privateZone, cidr, null); - } - - // Add a new security policy - manageSecurityPolicy(type, SrxCommand.ADD, null, null, guestVlan, applicationNames, cidrs, null, defaultEgressAction); - s_logger.debug("Added Egress firewall rule for guest network " + guestVlan); - return true; - } - - /* - * Filter terms - */ - - private String genIpFilterTermName(String ipAddress) { - return genIpIdentifier(ipAddress); - } - - private boolean manageUsageFilter(SrxCommand command, UsageFilter filter, String ip, Long guestVlanTag, String filterTermName) throws ExecutionException { - String filterName; - String filterDescription; - String xml; - - if (filter.equals(_usageFilterIPInput) || filter.equals(_usageFilterIPOutput)) { - assert (ip != null && guestVlanTag == null); - filterName = filter.getName(); - filterDescription = filter.toString() + ", public IP = " + ip; - xml = SrxXml.PUBLIC_IP_FILTER_TERM_ADD.getXml(); - } else if (filter.equals(_usageFilterVlanInput) || filter.equals(_usageFilterVlanOutput)) { - assert (ip == null && guestVlanTag != null); - filterName = filter.getName() + "-" + guestVlanTag; - filterDescription = filter.toString() + ", guest VLAN tag = " + guestVlanTag; - filterTermName = filterName; - xml = SrxXml.GUEST_VLAN_FILTER_TERM_ADD.getXml(); - } else { - return false; - } - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.FILTER_TERM_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "filter-name", filterName); - xml = replaceXmlValue(xml, "term-name", filterTermName); - return sendRequestAndCheckResponse(command, xml, "name", filterTermName); - - case ADD: - if (manageUsageFilter(SrxCommand.CHECK_IF_EXISTS, filter, ip, guestVlanTag, filterTermName)) { - return true; - } - - xml = replaceXmlValue(xml, "filter-name", filterName); - xml = replaceXmlValue(xml, "term-name", filterTermName); - - if (filter.equals(_usageFilterIPInput) || filter.equals(_usageFilterIPOutput)) { - xml = replaceXmlValue(xml, "ip-address", ip); - xml = replaceXmlValue(xml, "address-type", filter.getAddressType()); - } - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add usage filter: " + filterDescription); - } else { - return true; - } - - case DELETE: - if (!manageUsageFilter(SrxCommand.CHECK_IF_EXISTS, filter, ip, guestVlanTag, filterTermName)) { - return true; - } - - boolean deleteFilter = filter.equals(_usageFilterVlanInput) || filter.equals(_usageFilterVlanOutput); - xml = deleteFilter ? SrxXml.FILTER_GETONE.getXml() : SrxXml.FILTER_TERM_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "filter-name", filterName); - xml = !deleteFilter ? replaceXmlValue(xml, "term-name", filterTermName) : xml; - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to delete usage filter: " + filterDescription); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - - } - } - - private String genNameValueEntry(String name, String value) { - String xml = SrxXml.TEMPLATE_ENTRY.getXml(); - xml = replaceXmlValue(xml, "name", name); - xml = replaceXmlValue(xml, "value", value); - return xml; - } - - private String genMultipleEntries(String name, List values) { - String result = ""; - for (String value : values) { - result = result + genNameValueEntry(name, value); - } - return result; - } - - private String genPortRangeEntry(String protocol, String portRange) { - String result = ""; - result = result + genNameValueEntry("protocol", protocol); - result = result + genNameValueEntry("destination-port", portRange); - return result; - } - - private String genIcmpEntries(String icmpType, String icmpCode) { - String result = ""; - result = result + genNameValueEntry("protocol", "icmp"); - if (icmpType.equals("-1")) { - result = result + genNameValueEntry("icmp-type", "0-255"); - } else { - result = result + genNameValueEntry("icmp-type", icmpType); - } - if (icmpCode.equals("-1")) { - result = result + genNameValueEntry("icmp-code", "0-255"); - } else { - result = result + genNameValueEntry("icmp-code", icmpCode); - } - return result; - } - - private boolean manageFirewallFilter(SrxCommand command, FirewallFilterTerm term, String filterName) throws ExecutionException { - String xml; - - switch (command) { - - case CHECK_IF_EXISTS: - xml = SrxXml.FIREWALL_FILTER_TERM_GETONE.getXml(); - xml = setDelete(xml, false); - xml = replaceXmlValue(xml, "filter-name", filterName); - xml = replaceXmlValue(xml, "term-name", term.getName()); - return sendRequestAndCheckResponse(command, xml, "name", term.getName()); - - case ADD: - if (manageFirewallFilter(SrxCommand.CHECK_IF_EXISTS, term, filterName)) { - return true; - } - - xml = SrxXml.FIREWALL_FILTER_TERM_ADD.getXml(); - - xml = replaceXmlValue(xml, "filter-name", filterName); - xml = replaceXmlValue(xml, "term-name", term.getName()); - xml = replaceXmlValue(xml, "source-address-entries", genMultipleEntries("source-address", term.getSourceCidrs())); - xml = replaceXmlValue(xml, "dest-ip-address", term.getDestIp()); - - String protocol = term.getProtocol(); - if (protocol.equals("tcp") || protocol.equals("udp")) { - xml = replaceXmlValue(xml, "protocol-options", genPortRangeEntry(protocol, term.getPortRange())); - } else if (protocol.equals("icmp")) { - xml = replaceXmlValue(xml, "protocol-options", genIcmpEntries(term.getIcmpType(), term.getIcmpCode())); - } else { - assert protocol.equals("any"); - xml = replaceXmlValue(xml, "protocol-options", ""); - } - xml = replaceXmlValue(xml, "count-name", term.getCountName()); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to add firewall filter: " + term.getName()); - } else { - return true; - } - - case DELETE: - if (!manageFirewallFilter(SrxCommand.CHECK_IF_EXISTS, term, filterName)) { - return true; - } - - xml = SrxXml.FIREWALL_FILTER_TERM_GETONE.getXml(); - xml = setDelete(xml, true); - xml = replaceXmlValue(xml, "filter-name", filterName); - xml = replaceXmlValue(xml, "term-name", term.getName()); - - if (!sendRequestAndCheckResponse(command, xml)) { - throw new ExecutionException("Failed to delete firewall filter: " + term.getName()); - } else { - return true; - } - - default: - s_logger.debug("Unrecognized command."); - return false; - - } - } - - /* - * Usage - */ - - private ExternalNetworkResourceUsageAnswer getUsageAnswer(ExternalNetworkResourceUsageCommand cmd) throws ExecutionException { - try { - String socOpenException = "Failed to open a connection for Usage data."; - String socCloseException = "Unable to close connection for Usage data."; - if (!openUsageSocket()) { - throw new ExecutionException(socOpenException); - } - - ExternalNetworkResourceUsageAnswer answer = new ExternalNetworkResourceUsageAnswer(cmd); - - String xml = SrxXml.FIREWALL_FILTER_BYTES_GETALL.getXml(); - String rawUsageData = sendUsageRequest(xml); - Document doc = getDocument(rawUsageData); - - NodeList counters = doc.getElementsByTagName("counter"); - for (int i = 0; i < counters.getLength(); i++) { - Node n = counters.item(i); - if (n.getNodeName().equals("counter")) { - NodeList counterInfoList = n.getChildNodes(); - String counterName = null; - long byteCount = 0; - - for (int j = 0; j < counterInfoList.getLength(); j++) { - Node counterInfo = counterInfoList.item(j); - if (counterInfo.getNodeName().equals("counter-name")) { - counterName = counterInfo.getFirstChild().getNodeValue(); - } else if (counterInfo.getNodeName().equals("byte-count")) { - try { - byteCount = Long.parseLong(counterInfo.getFirstChild().getNodeValue()); - } catch (Exception e) { - s_logger.debug(e); - byteCount = 0; - } - } - } - - if (byteCount >= 0) { - updateUsageAnswer(answer, counterName, byteCount); - } - } - } - if (!closeUsageSocket()) { - throw new ExecutionException(socCloseException); - } - return answer; - } catch (Exception e) { - closeUsageSocket(); - throw new ExecutionException(e.getMessage()); - } - - } - - private void updateBytesMap(Map bytesMap, UsageFilter filter, String usageAnswerKey, long additionalBytes) { - long[] bytesSentAndReceived = bytesMap.get(usageAnswerKey); - if (bytesSentAndReceived == null) { - bytesSentAndReceived = new long[] {0, 0}; - } - - int index = 0; - if (filter.equals(_usageFilterVlanOutput) || filter.equals(_usageFilterIPInput)) { - index = 1; - } - - bytesSentAndReceived[index] += additionalBytes; - bytesMap.put(usageAnswerKey, bytesSentAndReceived); - } - - private String getIpAddress(String counterName) { - String[] counterNameArray = counterName.split("-"); - - if (counterNameArray.length < 4) { - return null; - } else { - return counterNameArray[0] + "." + counterNameArray[1] + "." + counterNameArray[2] + "." + counterNameArray[3]; - } - } - - private String getGuestVlanTag(String counterName) { - String[] counterNameArray = counterName.split("-"); - - if (counterNameArray.length != 3) { - return null; - } else { - return counterNameArray[2]; - } - } - - private UsageFilter getUsageFilter(String counterName) { - - if (counterName.contains(_usageFilterVlanInput.getCounterIdentifier())) { - return _usageFilterVlanInput; - } else if (counterName.contains(_usageFilterVlanOutput.getCounterIdentifier())) { - return _usageFilterVlanOutput; - } else if (counterName.contains(_usageFilterIPInput.getCounterIdentifier())) { - return _usageFilterIPInput; - } else if (counterName.contains(_usageFilterIPOutput.getCounterIdentifier())) { - return _usageFilterIPOutput; - } - - return null; - } - - private String getUsageAnswerKey(UsageFilter filter, String counterName) { - if (filter.equals(_usageFilterVlanInput) || filter.equals(_usageFilterVlanOutput)) { - return getGuestVlanTag(counterName); - } else if (filter.equals(_usageFilterIPInput) || filter.equals(_usageFilterIPOutput)) { - return getIpAddress(counterName); - } else { - return null; - } - } - - private Map getBytesMap(ExternalNetworkResourceUsageAnswer answer, UsageFilter filter, String usageAnswerKey) { - if (filter.equals(_usageFilterVlanInput) || filter.equals(_usageFilterVlanOutput)) { - return answer.guestVlanBytes; - } else if (filter.equals(_usageFilterIPInput) || filter.equals(_usageFilterIPOutput)) { - return answer.ipBytes; - } else { - return null; - } - } - - private void updateUsageAnswer(ExternalNetworkResourceUsageAnswer answer, String counterName, long byteCount) { - if (counterName == null || byteCount <= 0) { - return; - } - - UsageFilter filter = getUsageFilter(counterName); - if (filter == null) { - s_logger.debug("Failed to parse counter name in usage answer: " + counterName); - return; - } - String usageAnswerKey = getUsageAnswerKey(filter, counterName); - Map bytesMap = getBytesMap(answer, filter, usageAnswerKey); - updateBytesMap(bytesMap, filter, usageAnswerKey, byteCount); - } - - /* - * XML API commands - */ - - private String sendRequestPrim(BufferedWriter sendStream, BufferedReader recvStream, String xmlRequest) throws ExecutionException { - if (!xmlRequest.contains("request-login")) { - s_logger.debug("Sending request: " + xmlRequest); - } else { - s_logger.debug("Sending login request"); - } - - boolean timedOut = false; - StringBuffer xmlResponseBuffer = new StringBuffer(""); - try { - sendStream.write(xmlRequest); - sendStream.flush(); - - String line = ""; - while ((line = recvStream.readLine()) != null) { - xmlResponseBuffer.append(line); - if (line.contains("")) { - break; - } - } - - } catch (SocketTimeoutException e) { - s_logger.debug(e); - timedOut = true; - } catch (IOException e) { - s_logger.debug(e); - return null; - } - - String xmlResponse = xmlResponseBuffer.toString(); - String errorMsg = null; - - if (timedOut) { - errorMsg = "Timed out on XML request: " + xmlRequest; - } else if (xmlResponse.isEmpty()) { - errorMsg = "Received an empty XML response."; - } else if (xmlResponse.contains("Unexpected XML tag type")) { - errorMsg = "Sent a command without being logged in."; - } else if (!xmlResponse.contains("")) { - errorMsg = "Didn't find the rpc-reply tag in the XML response."; - } - - if (errorMsg == null) { - return xmlResponse; - } else { - s_logger.error(errorMsg); - throw new ExecutionException(errorMsg); - } - } - - private String sendRequest(String xmlRequest) throws ExecutionException { - return sendRequestPrim(_toSrx, _fromSrx, xmlRequest); - } - - private String sendUsageRequest(String xmlRequest) throws ExecutionException { - return sendRequestPrim(_UsagetoSrx, _UsagefromSrx, xmlRequest); - } - - private boolean checkResponse(String xmlResponse, boolean errorKeyAndValue, String key, String value) { - if (xmlResponse == null) { - s_logger.error("Failed to communicate with SRX!"); - return false; - } - - if (!xmlResponse.contains("authentication-response")) { - s_logger.debug("Checking response: " + xmlResponse); - } else { - s_logger.debug("Checking login response"); - } - - String textToSearchFor = key; - if (value != null) { - textToSearchFor = "<" + key + ">" + value + ""; - } - - if ((errorKeyAndValue && !xmlResponse.contains(textToSearchFor)) || (!errorKeyAndValue && xmlResponse.contains(textToSearchFor))) { - return true; - } - - String responseMessage = extractXml(xmlResponse, "message"); - if (responseMessage != null) { - s_logger.error("Request failed due to: " + responseMessage); - } else { - if (errorKeyAndValue) { - s_logger.error("Found error (" + textToSearchFor + ") in response."); - } else { - s_logger.debug("Didn't find " + textToSearchFor + " in response."); - } - } - - return false; - } - - private boolean sendRequestAndCheckResponse(SrxCommand command, String xmlRequest, String... keyAndValue) throws ExecutionException { - boolean errorKeyAndValue = false; - String key; - String value; - - switch (command) { - - case LOGIN: - key = "status"; - value = "success"; - break; - - case OPEN_CONFIGURATION: - case CLOSE_CONFIGURATION: - errorKeyAndValue = true; - key = "error"; - value = null; - break; - - case COMMIT: - key = "commit-success"; - value = null; - break; - - case CHECK_IF_EXISTS: - case CHECK_IF_IN_USE: - case CHECK_PRIVATE_IF_EXISTS: - assert (keyAndValue != null && keyAndValue.length == 2) : "If the SrxCommand is " + command + ", both a key and value must be specified."; - - key = keyAndValue[0]; - value = keyAndValue[1]; - break; - - default: - key = "load-success"; - value = null; - break; - - } - - String xmlResponse = sendRequest(xmlRequest); - return checkResponse(xmlResponse, errorKeyAndValue, key, value); - } - - private boolean sendUsageRequestAndCheckResponse(SrxCommand command, String xmlRequest, String... keyAndValue) throws ExecutionException { - boolean errorKeyAndValue = false; - String key; - String value; - - switch (command) { - - case LOGIN: - key = "status"; - value = "success"; - break; - - case OPEN_CONFIGURATION: - case CLOSE_CONFIGURATION: - errorKeyAndValue = true; - key = "error"; - value = null; - break; - - case COMMIT: - key = "commit-success"; - value = null; - break; - - case CHECK_IF_EXISTS: - case CHECK_IF_IN_USE: - assert (keyAndValue != null && keyAndValue.length == 2) : "If the SrxCommand is " + command + ", both a key and value must be specified."; - - key = keyAndValue[0]; - value = keyAndValue[1]; - break; - - default: - key = "load-success"; - value = null; - break; - - } - - String xmlResponse = sendUsageRequest(xmlRequest); - return checkResponse(xmlResponse, errorKeyAndValue, key, value); - } - - /* - * XML utils - */ - - private String replaceXmlTag(String xml, String oldTag, String newTag) { - return xml.replaceAll(oldTag, newTag); - } - - private String replaceXmlValue(String xml, String marker, String value) { - marker = "\\s*%" + marker + "%\\s*"; - - if (value == null) { - value = ""; - } - - return xml.replaceAll(marker, value); - } - - private String extractXml(String xml, String marker) { - String startMarker = "<" + marker + ">"; - String endMarker = ""; - if (xml.contains(startMarker) && xml.contains(endMarker)) { - return xml.substring(xml.indexOf(startMarker) + startMarker.length(), xml.indexOf(endMarker)); - } else { - return null; - } - - } - - private String setDelete(String xml, boolean delete) { - if (delete) { - String deleteMarker = " delete=\"delete\""; - xml = replaceXmlTag(xml, "get-configuration", "load-configuration"); - xml = replaceXmlValue(xml, "delete", deleteMarker); - } else { - xml = replaceXmlTag(xml, "load-configuration", "get-configuration"); - xml = replaceXmlValue(xml, "delete", ""); - } - - return xml; - } - - /* - * Misc - */ - - private Long getVlanTag(String vlan) throws ExecutionException { - Long publicVlanTag = null; - if (!vlan.contains("untagged")) { - try { - // make sure this vlan is numeric - publicVlanTag = Long.parseLong(BroadcastDomainType.getValue(vlan)); - } catch (Exception e) { - throw new ExecutionException("Unable to parse VLAN tag: " + vlan); - } - } - - return publicVlanTag; - } - - private String genObjectName(String... args) { - String objectName = ""; - - for (int i = 0; i < args.length; i++) { - objectName += args[i]; - if (i != args.length - 1) { - objectName += _objectNameWordSep; - } - } - - return objectName; - } - - private String genIpIdentifier(String ip) { - return ip.replace('.', '-').replace('/', '-'); - } - - private Protocol getProtocol(String protocolName) throws ExecutionException { - protocolName = protocolName.toLowerCase(); - - try { - return Protocol.valueOf(protocolName); - } catch (Exception e) { - throw new ExecutionException("Invalid protocol: " + protocolName); - } - } - - private Document getDocument(String xml) throws ExecutionException { - StringReader srcNatRuleReader = new StringReader(xml); - InputSource srcNatRuleSource = new InputSource(srcNatRuleReader); - Document doc = null; - - try { - doc = ParserUtils.getSaferDocumentBuilderFactory().newDocumentBuilder().parse(srcNatRuleSource); - } catch (Exception e) { - s_logger.error(e); - throw new ExecutionException(e.getMessage()); - } - - if (doc == null) { - throw new ExecutionException("Failed to parse xml " + xml); - } else { - return doc; - } - } - - @Override - public void setName(String name) { - // TODO Auto-generated method stub - - } - - @Override - public void setConfigParams(Map params) { - // TODO Auto-generated method stub - - } - - @Override - public Map getConfigParams() { - // TODO Auto-generated method stub - return null; - } - - @Override - public int getRunLevel() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void setRunLevel(int level) { - // TODO Auto-generated method stub - - } - -} diff --git a/plugins/network-elements/juniper-srx/src/main/resources/META-INF/cloudstack/srx/module.properties b/plugins/network-elements/juniper-srx/src/main/resources/META-INF/cloudstack/srx/module.properties deleted file mode 100644 index dde649bf753..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/resources/META-INF/cloudstack/srx/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -name=srx -parent=network \ No newline at end of file diff --git a/plugins/network-elements/juniper-srx/src/main/resources/META-INF/cloudstack/srx/spring-srx-context.xml b/plugins/network-elements/juniper-srx/src/main/resources/META-INF/cloudstack/srx/spring-srx-context.xml deleted file mode 100644 index 6a92ed5a1ba..00000000000 --- a/plugins/network-elements/juniper-srx/src/main/resources/META-INF/cloudstack/srx/spring-srx-context.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - diff --git a/plugins/pom.xml b/plugins/pom.xml index 736b5de0dba..d89f982221a 100755 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -168,17 +168,6 @@ - - srx - - - noredist - - - - network-elements/juniper-srx - - vmware diff --git a/server/src/main/java/com/cloud/api/ApiResponseHelper.java b/server/src/main/java/com/cloud/api/ApiResponseHelper.java index f6d30d52dfa..d70ade2e697 100644 --- a/server/src/main/java/com/cloud/api/ApiResponseHelper.java +++ b/server/src/main/java/com/cloud/api/ApiResponseHelper.java @@ -2894,7 +2894,7 @@ public class ApiResponseHelper implements ResponseGenerator { for (Network.Provider serviceProvider : serviceProviders) { // return only Virtual Router/JuniperSRX/CiscoVnmc as a provider for the firewall if (service == Service.Firewall - && !(serviceProvider == Provider.VirtualRouter || serviceProvider == Provider.JuniperSRX || serviceProvider == Provider.CiscoVnmc || serviceProvider == Provider.PaloAlto || serviceProvider == Provider.BigSwitchBcf)) { + && !(serviceProvider == Provider.VirtualRouter || serviceProvider == Provider.CiscoVnmc || serviceProvider == Provider.PaloAlto || serviceProvider == Provider.BigSwitchBcf)) { continue; } diff --git a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java index e073323c10e..27837af8465 100644 --- a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java @@ -5957,7 +5957,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr); } - if (provider == Provider.JuniperSRX || provider == Provider.CiscoVnmc) { + if (provider == Provider.CiscoVnmc) { firewallProvider = provider; } diff --git a/server/src/main/java/com/cloud/network/ExternalFirewallDeviceManager.java b/server/src/main/java/com/cloud/network/ExternalFirewallDeviceManager.java index c225932d43e..dcf33e417a6 100644 --- a/server/src/main/java/com/cloud/network/ExternalFirewallDeviceManager.java +++ b/server/src/main/java/com/cloud/network/ExternalFirewallDeviceManager.java @@ -28,7 +28,7 @@ import com.cloud.resource.ServerResource; import com.cloud.utils.component.Manager; /* ExternalFirewallDeviceManager provides a abstract implementation for managing a external firewall in devices agnostic manner. - * Device specific managers for external firewall (like SRX) should be implemented as pluggable service extending + * Device specific managers for external firewall should be implemented as pluggable service extending * ExternalFirewallDeviceManager implementation. An implementation of device specific manager can override default behaviour when needed. */ diff --git a/test/metadata/func/srxstresswithportfwd.xml b/test/metadata/func/srxstresswithportfwd.xml deleted file mode 100644 index 3d34369b86e..00000000000 --- a/test/metadata/func/srxstresswithportfwd.xml +++ /dev/null @@ -1,595 +0,0 @@ - - - - - createAccount - Creating account - - - account - accountname - - - accounttype - 1 - - - domainid - 1 - - - email - srxstress@gmail.com - - - firstname - srxstress - - - lastname - srxstresslastname - - - username - usernameparam - - - password - password - - - - - id - accountid - - - - - - - createNetwork - Creating default network - - - zoneid - globalzoneid - - - networkOfferingId - globalnetworkofferingid - - - account - accountname - - - domainid - 1 - - - name - srxstressnetwork - - - displaytext - srxstressnetwork - - - - - id - networkid - - - - - - deployVirtualMachine - deploying virtual machine - - - zoneid - globalzoneid - - - serviceofferingid - globalserviceofferingid - - - templateid - globaltemplateid - - - account - accountname - - - domainid - 1 - - - networkids - networkid - - - - - id - vmid - - - name - vmname - - - ipaddress - vmipaddress - - - - - - deployVirtualMachine - deploying virtual machine - - - zoneid - globalzoneid - - - serviceofferingid - globalserviceofferingid - - - templateid - globaltemplateid - - - account - accountname - - - domainid - 1 - - - networkids - networkid - - - - - id - vmid1 - - - name - vmname1 - - - ipaddress1 - vmipaddress - - - - - - associateIpAddress - Associating first public ip address - - - zoneid - globalzoneid - - - account - accountname - - - domainid - 1 - - - - - id - nonsourcenatpublicip1id - - - ipaddress - nonsourcenatpublicip1 - - - - - - associateIpAddress - Associating second public ip address - - - zoneid - globalzoneid - - - account - accountname - - - domainid - 1 - - - - - id - nonsourcenatpublicip2id - - - ipaddress - nonsourcenatpublicip2 - - - - - - enableStaticNat - Enable Static NAT - 1 - - - ipaddressid - nonsourcenatpublicip1id - - - virtualmachineid - vmid - - - - - - enableStaticNat - Enable Static NAT - 2 - - - ipaddressid - nonsourcenatpublicip2id - - - virtualmachineid - vmid1 - - - - - - - createIpForwardingRule - Creating Ip forwarding rule - 1 - - - ipaddressid - nonsourcenatpublicip1id - - - startPort - 22 - - - endPort - 22 - - - protocol - TCP - - - - - id - ipfwdrule1 - - - - - - createIpForwardingRule - Creating Ip forwarding rule - 2 - - - ipaddressid - nonsourcenatpublicip1id - - - startPort - 33 - - - endPort - 35 - - - protocol - TCP - - - - - id - ipfwdrule2 - - - - - - createIpForwardingRule - Creating Ip forwarding rule - 3 - - - ipaddressid - nonsourcenatpublicip1id - - - startPort - 44 - - - endPort - 55 - - - protocol - TCP - - - - - id - ipfwdrule3 - - - - - - sleep.sh - - Sleeping for 2 mins to ensure that vm comes up for ssh test - - - s - 120 - - - - - - ssh.sh - - Ssh test for the vm - - - h - nonsourcenatpublicip1 - - - p - password - - - u - http://yahoo.com - - - - - - deleteIpForwardingRule - Delete Ip forwarding rule - 1 - - - id - ipfwdrule1 - - - - - - deleteIpForwardingRule - Delete Ip forwarding rule - 2 - - - id - ipfwdrule2 - - - - - - - deleteIpForwardingRule - Delete Ip forwarding rule - 3 - - - id - ipfwdrule3 - - - - - - sleep.sh - - Sleeping for 1 min - - - s - 60 - - - - - - createIpForwardingRule - Creating Ip forwarding rule - 4 - - - ipaddressid - nonsourcenatpublicip2id - - - startPort - 22 - - - endPort - 22 - - - protocol - TCP - - - - - id - ipfwdrule1 - - - - - - createIpForwardingRule - Creating Ip forwarding rule - 5 - - - ipaddressid - nonsourcenatpublicip2id - - - startPort - 33 - - - endPort - 35 - - - protocol - TCP - - - - - id - ipfwdrule2 - - - - - - createIpForwardingRule - Creating Ip forwarding rule - 6 - - - ipaddressid - nonsourcenatpublicip3id - - - startPort - 44 - - - endPort - 55 - - - protocol - TCP - - - - - id - ipfwdrule3 - - - - - - disableStaticNat - Disable Static NAT - 2 - - - ipaddressid - nonsourcenatpublicip2id - - - - - - - disassociateIpAddress - Dissociating second public ip address - - - id - nonsourcenatpublicip2id - - - - - - disableStaticNat - Disable Static NAT - 1 - - - ipaddressid - nonsourcenatpublicip1id - - - - - - disassociateIpAddress - Dissociating first public ip address - - - id - nonsourcenatpublicip1id - - - - - - deleteAccount - Delete account - - - id - accountid - - - - - - - - - diff --git a/tools/marvin/marvin/configGenerator.py b/tools/marvin/marvin/configGenerator.py index 7804ade0a3d..7e82119531f 100644 --- a/tools/marvin/marvin/configGenerator.py +++ b/tools/marvin/marvin/configGenerator.py @@ -270,31 +270,6 @@ class netscaler(object): return self.hostname + "?" + "&".join(["=".join([r[0], r[1]]) for r in req]) - -class srx(object): - - def __init__(self, hostname=None, username='root', password='admin'): - self.hostname = hostname - self.username = username - self.password = password - self.networkdevicetype = 'JuniperSRXFirewall' - self.publicinterface = '1/1' - self.privateinterface = '1/1' - self.numretries = '2' - self.fwdevicededicated = 'false' - self.timeout = '300' - self.publicnetwork = 'untrusted' - self.privatenetwork = 'trusted' - - def getUrl(self): - return repr(self) - - def __repr__(self): - req = list(zip(list(self.__dict__.keys()), list(self.__dict__.values()))) - return self.hostname + "?" + "&".join(["=".join([r[0], r[1]]) - for r in req]) - - class bigip(object): def __init__(self, hostname=None, username='root', password='default'): @@ -701,13 +676,7 @@ def descSetupInAdvancedMode(): nsprovider = provider('Netscaler') nsprovider.devices.append(netscaler(hostname='10.147.40.100')) - srxprovider = provider('JuniperSRX') - srxprovider.devices.append(srx(hostname='10.147.40.3')) - - f5provider = provider('F5BigIp') - f5provider.devices.append(bigip(hostname='10.147.40.3')) - - pn.providers.extend([vpcprovider, nsprovider, srxprovider, f5provider]) + pn.providers.extend([vpcprovider, nsprovider]) z.physical_networks.append(pn) '''create 10 pods''' diff --git a/ui/src/views/infra/network/ServiceProvidersTab.vue b/ui/src/views/infra/network/ServiceProvidersTab.vue index d58a004e244..8ed396ea8c3 100644 --- a/ui/src/views/infra/network/ServiceProvidersTab.vue +++ b/ui/src/views/infra/network/ServiceProvidersTab.vue @@ -682,65 +682,6 @@ export default { } ] }, - { - title: 'JuniperSRX', - actions: [ - { - api: 'addSrxFirewall', - listView: true, - icon: 'plus-outlined', - label: 'label.add.srx.device', - component: shallowRef(defineAsyncComponent(() => import('@/views/infra/network/providers/AddSrxFirewall.vue'))) - }, - { - api: 'updateNetworkServiceProvider', - icon: 'stop-outlined', - listView: true, - label: 'label.disable.provider', - confirm: 'message.confirm.disable.provider', - show: (record) => { return record && record.id && record.state === 'Enabled' }, - mapping: { - state: { - value: (record) => { return 'Disabled' } - } - } - }, - { - api: 'updateNetworkServiceProvider', - icon: 'play-circle-outlined', - listView: true, - label: 'label.enable.provider', - confirm: 'message.confirm.enable.provider', - show: (record) => { return record && record.id && record.state === 'Disabled' }, - mapping: { - state: { - value: (record) => { return 'Enabled' } - } - } - }, - { - api: 'deleteNetworkServiceProvider', - listView: true, - icon: 'poweroff-outlined', - label: 'label.shutdown.provider', - confirm: 'message.confirm.delete.provider', - show: (record) => { return record && record.id } - } - ], - details: ['name', 'state', 'id', 'servicelist'], - lists: [ - { - title: 'label.devices', - api: 'listSrxFirewalls', - mapping: { - physicalnetworkid: { - value: (record) => { return record.physicalnetworkid } - } - }, - columns: ['ipaddress', 'fwdevicestate', 'action'] - } - ] - }, { title: 'Netscaler', actions: [ diff --git a/ui/src/views/infra/network/providers/AddSrxFirewall.vue b/ui/src/views/infra/network/providers/AddSrxFirewall.vue deleted file mode 100644 index 3f53a2fe0dd..00000000000 --- a/ui/src/views/infra/network/providers/AddSrxFirewall.vue +++ /dev/null @@ -1,381 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - - - - diff --git a/ui/src/views/infra/network/providers/ProviderListView.vue b/ui/src/views/infra/network/providers/ProviderListView.vue index 3625a166f8a..baa65175817 100644 --- a/ui/src/views/infra/network/providers/ProviderListView.vue +++ b/ui/src/views/infra/network/providers/ProviderListView.vue @@ -55,8 +55,6 @@ {{ $t('label.delete.bigswitchbcf') }} {{ $t('label.delete.brocadevcs') }} {{ $t('label.delete.niciranvp') }} - {{ $t('label.delete.f5') }} - {{ $t('label.delete.srx') }} {{ $t('label.delete.netscaler') }} {{ $t('label.delete.opendaylight.device') }} {{ $t('label.delete.pa') }} @@ -232,13 +230,6 @@ export default { confirmation = 'message.confirm.delete.brocadevcs' params.vcsdeviceid = record.vcsdeviceid break - case 'JuniperSRX': - label = 'label.delete.srx' - name = record.ipaddress - apiName = 'deleteSrxFirewall' - confirmation = 'message.confirm.delete.srx' - params.fwdeviceid = record.fwdeviceid - break case 'Netscaler': label = 'label.delete.netscaler' name = record.ipaddress