Merge branch '3.0.x' of ssh://git.cloud.com/var/lib/git/cloudstack-oss into 3.0.x

This commit is contained in:
prachi 2012-07-26 11:37:36 -07:00
commit 5f433ff7bc
46 changed files with 3773 additions and 3357 deletions

View File

@ -0,0 +1,55 @@
package com.cloud.agent.api;
import java.util.HashMap;
import java.util.Map;
public class CheckS2SVpnConnectionsAnswer extends Answer {
Map<String, Boolean> ipToConnected;
Map<String, String> ipToDetail;
String details;
protected CheckS2SVpnConnectionsAnswer() {
ipToConnected = new HashMap<String, Boolean>();
ipToDetail = new HashMap<String, String>();
}
public CheckS2SVpnConnectionsAnswer(CheckS2SVpnConnectionsCommand cmd, boolean result, String details) {
super(cmd, result, details);
ipToConnected = new HashMap<String, Boolean>();
ipToDetail = new HashMap<String, String>();
this.details = details;
if (result) {
parseDetails(details);
}
}
protected void parseDetails(String details) {
String[] lines = details.split("&");
for (String line : lines) {
String[] words = line.split(":");
if (words.length != 3) {
//Not something we can parse
return;
}
String ip = words[0];
boolean connected = words[1].equals("0");
String detail = words[2];
ipToConnected.put(ip, connected);
ipToDetail.put(ip, detail);
}
}
public boolean isConnected(String ip) {
if (this.getResult()) {
return ipToConnected.get(ip);
}
return false;
}
public String getDetail(String ip) {
if (this.getResult()) {
return ipToDetail.get(ip);
}
return null;
}
}

View File

@ -0,0 +1,23 @@
package com.cloud.agent.api;
import java.util.List;
import com.cloud.agent.api.routing.NetworkElementCommand;
public class CheckS2SVpnConnectionsCommand extends NetworkElementCommand {
List<String> vpnIps;
@Override
public boolean executeInSequence() {
return true;
}
public CheckS2SVpnConnectionsCommand(List<String> vpnIps) {
super();
this.vpnIps = vpnIps;
}
public List<String> getVpnIps() {
return vpnIps;
}
}

View File

@ -120,7 +120,7 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd {
public long getEntityOwnerId() {
LoadBalancer lb = _entityMgr.findById(LoadBalancer.class, getLbRuleId());
if (lb == null) {
throw new InvalidParameterValueException("Unable to find loadbalancer from lbRuleId=" + getLbRuleId());
throw new InvalidParameterValueException("Unable to find loadbalancer by lbRuleId", null);
}
return lb.getAccountId();
}

View File

@ -156,7 +156,7 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd {
for (String keyValue : keyValues) { // keyValue == "hostid=123"
String[] keyAndValue = keyValue.split("="); // keyValue = hostid, 123
if (keyAndValue.length != 2) {
throw new InvalidParameterValueException("Invalid parameter in otherDeployParam : " + keyValue);
throw new InvalidParameterValueException("Invalid parameter in otherDeployParam : " + keyValue, null);
}
String paramName = keyAndValue[0]; // hostid
String paramValue = keyAndValue[1]; // 123

View File

@ -20,17 +20,19 @@ package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseAsyncCmd;
import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.AutoScaleVmGroupResponse;
import com.cloud.event.EventTypes;
import com.cloud.network.as.AutoScaleVmGroup;
import com.cloud.user.Account;
@Implementation(description = "Disables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class)
public class DisableAutoScaleVmGroupCmd extends BaseCmd {
public class DisableAutoScaleVmGroupCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(DisableAutoScaleVmGroupCmd.class.getName());
private static final String s_name = "disableautoscalevmGroupresponse";
@ -38,8 +40,8 @@ public class DisableAutoScaleVmGroupCmd extends BaseCmd {
// ////////////// API parameters /////////////////////
// ///////////////////////////////////////////////////
@IdentityMapper(entityTableName = "account")
@Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "Account id")
@IdentityMapper(entityTableName="autoscale_vmgroups")
@Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the autoscale group")
private Long id;
// ///////////////////////////////////////////////////
@ -81,4 +83,13 @@ public class DisableAutoScaleVmGroupCmd extends BaseCmd {
// tracked
}
@Override
public String getEventType() {
return EventTypes.EVENT_AUTOSCALEVMGROUP_DISABLE;
}
@Override
public String getEventDescription() {
return "Disabling AutoScale Vm Group. Vm Group Id: " + getId();
}
}

View File

@ -20,17 +20,19 @@ package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseAsyncCmd;
import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.AutoScaleVmGroupResponse;
import com.cloud.event.EventTypes;
import com.cloud.network.as.AutoScaleVmGroup;
import com.cloud.user.Account;
@Implementation(description = "Enables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class)
public class EnableAutoScaleVmGroupCmd extends BaseCmd {
public class EnableAutoScaleVmGroupCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(EnableAutoScaleVmGroupCmd.class.getName());
private static final String s_name = "enableautoscalevmGroupresponse";
@ -81,4 +83,14 @@ public class EnableAutoScaleVmGroupCmd extends BaseCmd {
// tracked
}
@Override
public String getEventType() {
return EventTypes.EVENT_AUTOSCALEVMGROUP_ENABLE;
}
@Override
public String getEventDescription() {
return "Enabling AutoScale Vm Group. Vm Group Id: "+getId();
}
}

View File

@ -92,7 +92,7 @@ public class ListAutoScaleVmGroupsCmd extends BaseListProjectAndAccountResources
@Override
public void execute() {
if(id != null && (loadBalancerId != null || profileId != null || policyId != null))
throw new InvalidParameterValueException("When id is specified other parameters need not be specified");
throw new InvalidParameterValueException("When id is specified other parameters need not be specified", null);
List<? extends AutoScaleVmGroup> autoScaleGroups = _autoScaleService.listAutoScaleVmGroups(this);
ListResponse<AutoScaleVmGroupResponse> response = new ListResponse<AutoScaleVmGroupResponse>();

View File

@ -99,7 +99,7 @@ public class UpdateAutoScalePolicyCmd extends BaseAsyncCmd {
@Override
public String getEventDescription() {
return "Updating Auto Scale Policy.";
return "Updating Auto Scale Policy. Policy Id: " + getId();
}
@Override

View File

@ -113,12 +113,12 @@ public class UpdateAutoScaleVmGroupCmd extends BaseAsyncCmd {
@Override
public String getEventType() {
return "Update AutoScale Vm Group";
return EventTypes.EVENT_AUTOSCALEVMGROUP_UPDATE;
}
@Override
public String getEventDescription() {
return EventTypes.EVENT_AUTOSCALEVMGROUP_UPDATE;
return "Updating AutoScale Vm Group. Vm Group Id: "+getId();
}
@Override

View File

@ -116,7 +116,7 @@ public class UpdateAutoScaleVmProfileCmd extends BaseAsyncCmd {
@Override
public String getEventDescription() {
return "Updating AutoScale Vm Profile";
return "Updating AutoScale Vm Profile. Vm Profile Id: " + getId();
}
@Override

BIN
awsapi.log.2012-07-25.gz Normal file

Binary file not shown.

View File

@ -116,7 +116,7 @@ public class ApiConstants {
public static final String DELETE_SSH_KEY_PAIR = "deleteSSHKeyPair";
public static final String DELETE_SSH_KEY_PAIR_RESPONSE = "deletesshkeypairresponse";
public static final String DELETE_TAGS = "deleteTags";
public static final String DELETE_TAGS_RESPONSE = "deleteTagsresponse";
public static final String DELETE_TAGS_RESPONSE = "deletetagsresponse";
public static final String DELETE_TEMPLATE = "deleteTemplate";
public static final String DELETE_TEMPLATE_RESPONSE = "deletetemplateresponse";
public static final String DELETE_VOLUME = "deleteVolume";

View File

@ -38,6 +38,8 @@ import com.cloud.agent.api.Answer;
import com.cloud.agent.api.BumpUpPriorityCommand;
import com.cloud.agent.api.CheckRouterAnswer;
import com.cloud.agent.api.CheckRouterCommand;
import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer;
import com.cloud.agent.api.CheckS2SVpnConnectionsCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.GetDomRVersionAnswer;
import com.cloud.agent.api.GetDomRVersionCmd;
@ -135,6 +137,8 @@ public class VirtualRoutingResource implements Manager {
return execute((GetDomRVersionCmd)cmd);
} else if (cmd instanceof Site2SiteVpnCfgCommand) {
return execute((Site2SiteVpnCfgCommand)cmd);
} else if (cmd instanceof CheckS2SVpnConnectionsCommand) {
return execute((CheckS2SVpnConnectionsCommand)cmd);
}
else {
return Answer.createUnsupportedCommandAnswer(cmd);
@ -506,6 +510,21 @@ public class VirtualRoutingResource implements Manager {
return command.execute();
}
private CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) {
final String routerIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
String args = "";
for (String ip : cmd.getVpnIps()) {
args += " " + ip;
}
final String result = routerProxyWithParser("checkbatchs2svpn.sh", routerIP, args);
if (result == null || result.isEmpty()) {
return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed");
}
return new CheckS2SVpnConnectionsAnswer(cmd, true, result);
}
protected Answer execute(CheckRouterCommand cmd) {
final String routerPrivateIPAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);

View File

@ -54,6 +54,8 @@ import com.cloud.agent.api.CheckOnHostAnswer;
import com.cloud.agent.api.CheckOnHostCommand;
import com.cloud.agent.api.CheckRouterAnswer;
import com.cloud.agent.api.CheckRouterCommand;
import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer;
import com.cloud.agent.api.CheckS2SVpnConnectionsCommand;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.Command;
@ -443,6 +445,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
answer = execute((SetPortForwardingRulesVpcCommand) cmd);
} else if (clz == Site2SiteVpnCfgCommand.class) {
answer = execute((Site2SiteVpnCfgCommand) cmd);
} else if (clz == CheckS2SVpnConnectionsCommand.class) {
answer = execute((CheckS2SVpnConnectionsCommand) cmd);
} else {
answer = Answer.createUnsupportedCommandAnswer(cmd);
}
@ -1567,6 +1571,35 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
return new Answer(cmd);
}
protected CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Executing resource CheckS2SVpnConnectionsCommand: " + _gson.toJson(cmd));
s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkbatchs2svpn.sh ");
}
Pair<Boolean, String> result;
try {
VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
String controlIp = getRouterSshControlIp(cmd);
result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null,
"/opt/cloud/bin/checkbatchs2svpn.sh ");
if (!result.first()) {
s_logger.error("check site-to-site vpn connections command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second());
return new CheckS2SVpnConnectionsAnswer(cmd, false, result.second());
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("check site-to-site vpn connections command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed");
}
} catch (Throwable e) {
String msg = "CheckS2SVpnConnectionsCommand failed due to " + VmwareHelper.getExceptionMessage(e);
s_logger.error(msg, e);
return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed");
}
return new CheckS2SVpnConnectionsAnswer(cmd, true, result.second());
}
protected Answer execute(CheckRouterCommand cmd) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Executing resource CheckRouterCommand: " + _gson.toJson(cmd));

View File

@ -66,6 +66,8 @@ import com.cloud.agent.api.CheckOnHostAnswer;
import com.cloud.agent.api.CheckOnHostCommand;
import com.cloud.agent.api.CheckRouterAnswer;
import com.cloud.agent.api.CheckRouterCommand;
import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer;
import com.cloud.agent.api.CheckS2SVpnConnectionsCommand;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.CleanupNetworkRulesCmd;
@ -545,6 +547,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
return execute((SetStaticRouteCommand) cmd);
} else if (clazz == Site2SiteVpnCfgCommand.class) {
return execute((Site2SiteVpnCfgCommand) cmd);
} else if (clazz == CheckS2SVpnConnectionsCommand.class) {
return execute((CheckS2SVpnConnectionsCommand) cmd);
} else {
return Answer.createUnsupportedCommandAnswer(cmd);
}
@ -1386,6 +1390,19 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
return new Answer(cmd);
}
private CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) {
Connection conn = getConnection();
String args = "checkbatchs2svpn.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
for (String ip : cmd.getVpnIps()) {
args += " " + ip;
}
String result = callHostPlugin(conn, "vmops", "routerProxy", "args", args);
if (result == null || result.isEmpty()) {
return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed");
}
return new CheckS2SVpnConnectionsAnswer(cmd, true, result);
}
private CheckRouterAnswer execute(CheckRouterCommand cmd) {
Connection conn = getConnection();
String args = "checkrouter.sh " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);

View File

@ -228,35 +228,12 @@ public class NetscalerResource implements ServerResource {
}
private ArrayList<com.citrix.netscaler.nitro.service.nitro_service> netscalerServices = new ArrayList<com.citrix.netscaler.nitro.service.nitro_service>();
private com.citrix.netscaler.nitro.service.nitro_service login_get_service(Boolean forAutoScale) throws ExecutionException {
if(forAutoScale == null) {
return _netscalerService;
}
com.citrix.netscaler.nitro.service.nitro_service _netscalerService = null;
try {
_netscalerService = new com.citrix.netscaler.nitro.service.nitro_service(_ip, "https");
_netscalerService.set_credential(_username, _password);
_netscalerService.set_timeout(_timeout);
base_response apiCallResult = _netscalerService.login();
if (apiCallResult.errorcode != 0) {
throw new ExecutionException ("AuotoScale Failed to log in to Netscaler device at " + _ip + " due to error " + apiCallResult.errorcode + " and message " + apiCallResult.message);
}
} catch(ExecutionException ee) {
throw ee;
}
catch(Exception ee) {
throw new ExecutionException ("AutoScale Exception happend during login" + ee.getMessage());
}
netscalerServices.add(_netscalerService);
return _netscalerService;
}
private void login() throws ExecutionException {
try {
if (!_isSdx) {
_netscalerService = new com.citrix.netscaler.nitro.service.nitro_service(_ip, "https");
_netscalerService.set_credential(_username, _password);
_netscalerService.set_timeout(_timeout);
// _netscalerService.set_timeout(_timeout);
apiCallResult = _netscalerService.login();
if (apiCallResult.errorcode != 0) {
throw new ExecutionException ("Failed to log in to Netscaler device at " + _ip + " due to error " + apiCallResult.errorcode + " and message " + apiCallResult.message);
@ -281,7 +258,7 @@ public class NetscalerResource implements ServerResource {
return;
}
try {
String[] features = login_get_service(true).get_enabled_features();
String[] features = _netscalerService.get_enabled_features();
if (features != null) {
for (String feature : features) {
if (feature.equalsIgnoreCase("LB")) {
@ -293,7 +270,7 @@ public class NetscalerResource implements ServerResource {
// enable load balancing on the device
String[] feature = new String[1];
feature[0] = "LB";
apiCallResult = login_get_service(true).enable_features(feature);
apiCallResult = _netscalerService.enable_features(feature);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Enabling load balancing feature on the device failed.");
}
@ -307,8 +284,8 @@ public class NetscalerResource implements ServerResource {
private void validateInterfaces(String publicInterface, String privateInterface) throws ExecutionException {
try {
if (!_isSdx && !_cloudManaged) {
Interface publicIf = Interface.get(login_get_service(true), publicInterface);
Interface privateIf = Interface.get(login_get_service(true), privateInterface);
Interface publicIf = Interface.get(_netscalerService, publicInterface);
Interface privateIf = Interface.get(_netscalerService, privateInterface);
if (publicIf != null || privateIf != null) {
return;
} else {
@ -329,7 +306,7 @@ public class NetscalerResource implements ServerResource {
private void validateDeviceType(String deviceType) throws ExecutionException {
try {
if (!_isSdx && !_cloudManaged) {
nshardware nsHw = com.citrix.netscaler.nitro.resource.config.ns.nshardware.get(login_get_service(true));
nshardware nsHw = com.citrix.netscaler.nitro.resource.config.ns.nshardware.get(_netscalerService);
if (nsHw == null) {
throw new ExecutionException("Failed to get the hardware description of the Netscaler device at " + _ip);
} else {
@ -473,7 +450,7 @@ public class NetscalerResource implements ServerResource {
timer_policy_binding.set_name(timerName);
timer_policy_binding.set_policyname(policyName);
timer_policy_binding.set_global("DEFAULT");
timer_policy_binding.delete(login_get_service(true), timer_policy_binding);
timer_policy_binding.delete(_netscalerService, timer_policy_binding);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -484,7 +461,7 @@ public class NetscalerResource implements ServerResource {
com.citrix.netscaler.nitro.resource.config.timer.timerpolicy timerPolicy = new com.citrix.netscaler.nitro.resource.config.timer.timerpolicy();
try {
timerPolicy.set_name(policyName);
timerPolicy.delete(login_get_service(true), timerPolicy);
timerPolicy.delete(_netscalerService, timerPolicy);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -508,7 +485,7 @@ public class NetscalerResource implements ServerResource {
try {
vserver_servicegroup_binding.set_name(nsVirtualServerName);
vserver_servicegroup_binding.set_servicegroupname(serviceGroupName);
vserver_servicegroup_binding.delete(login_get_service(true), vserver_servicegroup_binding);
vserver_servicegroup_binding.delete(_netscalerService, vserver_servicegroup_binding);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -518,7 +495,7 @@ public class NetscalerResource implements ServerResource {
com.citrix.netscaler.nitro.resource.config.basic.servicegroup serviceGroup = new com.citrix.netscaler.nitro.resource.config.basic.servicegroup();
try {
serviceGroup.set_servicegroupname(serviceGroupName);
serviceGroup.delete(login_get_service(true), serviceGroup);
serviceGroup.delete(_netscalerService, serviceGroup);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -531,7 +508,7 @@ public class NetscalerResource implements ServerResource {
// lbvserver.set_name(nsVirtualServerName);
// lbvserver.set_minautoscalemembers(0);
// lbvserver.set_maxautoscalemembers(0);
// lbvserver.update(login_get_service(true), lbvserver);
// lbvserver.update(_netscalerService, lbvserver);
// } catch (Exception e) {
// // Ignore Exception
// throw e;
@ -589,7 +566,7 @@ public class NetscalerResource implements ServerResource {
com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction scaleDownAction = new com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction();
try {
scaleDownAction.set_name(scaleDownActionName);
scaleDownAction.delete(login_get_service(true), scaleDownAction);
scaleDownAction.delete(_netscalerService, scaleDownAction);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -599,7 +576,7 @@ public class NetscalerResource implements ServerResource {
com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction scaleUpAction = new com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction();
try {
scaleUpAction.set_name(scaleUpActionName);
scaleUpAction.delete(login_get_service(true), scaleUpAction);
scaleUpAction.delete(_netscalerService, scaleUpAction);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -609,7 +586,7 @@ public class NetscalerResource implements ServerResource {
com.citrix.netscaler.nitro.resource.config.timer.timertrigger timer = new com.citrix.netscaler.nitro.resource.config.timer.timertrigger();
try {
timer.set_name(timerName);
timer.delete(login_get_service(true), timer);
timer.delete(_netscalerService, timer);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -619,7 +596,7 @@ public class NetscalerResource implements ServerResource {
com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleprofile autoscaleProfile = new com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleprofile();
try {
autoscaleProfile.set_name(profileName);
autoscaleProfile.delete(login_get_service(true), autoscaleProfile);
autoscaleProfile.delete(_netscalerService, autoscaleProfile);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -630,7 +607,7 @@ public class NetscalerResource implements ServerResource {
try {
monitor_servicegroup_binding.set_monitorname(monitorName);
monitor_servicegroup_binding.set_servicegroupname(serviceGroupName);
monitor_servicegroup_binding.delete(login_get_service(true), monitor_servicegroup_binding);
monitor_servicegroup_binding.delete(_netscalerService, monitor_servicegroup_binding);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -642,7 +619,7 @@ public class NetscalerResource implements ServerResource {
try {
monitor.set_monitorname(monitorName);
monitor.set_type("LOAD");
monitor.delete(login_get_service(true), monitor);
monitor.delete(_netscalerService, monitor);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -652,7 +629,7 @@ public class NetscalerResource implements ServerResource {
com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable metricTable = new com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable();
try {
metricTable.set_metrictable(mtName);
metricTable.delete(login_get_service(true), metricTable);
metricTable.delete(_netscalerService, metricTable);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -686,7 +663,7 @@ public class NetscalerResource implements ServerResource {
serviceGroup.set_servicetype(lbProtocol);
serviceGroup.set_autoscale("POLICY"); // TODO: Values not displayed in API
serviceGroup.set_memberport(memberPort);
serviceGroup.add(login_get_service(true), serviceGroup);
serviceGroup.add(_netscalerService, serviceGroup);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -699,7 +676,7 @@ public class NetscalerResource implements ServerResource {
try {
vserver_servicegroup_binding.set_name(nsVirtualServerName);
vserver_servicegroup_binding.set_servicegroupname(serviceGroupName);
vserver_servicegroup_binding.add(login_get_service(true), vserver_servicegroup_binding);
vserver_servicegroup_binding.add(_netscalerService, vserver_servicegroup_binding);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -741,7 +718,7 @@ public class NetscalerResource implements ServerResource {
lbvserver.set_name(nsVirtualServerName);
lbvserver.set_minautoscalemembers(minAutoScaleMembers);
lbvserver.set_maxautoscalemembers(maxAutoScaleMembers);
lbvserver.update(login_get_service(true), lbvserver);
lbvserver.update(_netscalerService, lbvserver);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -762,7 +739,7 @@ public class NetscalerResource implements ServerResource {
autoscaleProfile.set_apikey(apiKey);
autoscaleProfile.set_sharedsecret(secretKey);
autoscaleProfile.set_url(url);
autoscaleProfile.add(login_get_service(true), autoscaleProfile);
autoscaleProfile.add(_netscalerService, autoscaleProfile);
} catch (Exception e) {
// Ignore Exception
@ -774,7 +751,7 @@ public class NetscalerResource implements ServerResource {
try {
timer.set_name(timerName);
timer.set_interval(interval);
timer.add(login_get_service(true), timer);
timer.add(_netscalerService, timer);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -820,7 +797,7 @@ public class NetscalerResource implements ServerResource {
((profileTO.getOtherDeployParams() == null)? "" : (profileTO.getOtherDeployParams() + "&")) +
"lbruleid=" + loadBalancerTO.getId();
scaleUpAction.set_parameters(scaleUpParameters);
scaleUpAction.add(login_get_service(true), scaleUpAction);
scaleUpAction.add(_netscalerService, scaleUpAction);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -839,7 +816,7 @@ public class NetscalerResource implements ServerResource {
"lbruleid=" + loadBalancerTO.getId();
scaleDownAction.set_parameters(scaleDownParameters);
scaleDownAction.set_vmdestroygraceperiod(destroyVmGracePeriod);
scaleDownAction.add(login_get_service(true), scaleDownAction);
scaleDownAction.add(_netscalerService, scaleDownAction);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -881,7 +858,7 @@ public class NetscalerResource implements ServerResource {
com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable metricTable = new com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable();
try {
metricTable.set_metrictable(mtName);
metricTable.add(login_get_service(true), metricTable);
metricTable.add(_netscalerService, metricTable);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -898,7 +875,7 @@ public class NetscalerResource implements ServerResource {
monitor.set_snmpcommunity(snmpCommunity);
monitor.set_metrictable(mtName);
monitor.set_interval((int)(interval * 0.8));
monitor.add(login_get_service(true), monitor);
monitor.add(_netscalerService, monitor);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -912,7 +889,7 @@ public class NetscalerResource implements ServerResource {
monitor_servicegroup_binding.set_servicegroupname(serviceGroupName);
monitor_servicegroup_binding.set_passive(true); // Mark the monitor to do only collect
// metrics, basically use it for autoscaling purpose only.
monitor_servicegroup_binding.add(login_get_service(true), monitor_servicegroup_binding);
monitor_servicegroup_binding.add(_netscalerService, monitor_servicegroup_binding);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -933,7 +910,7 @@ public class NetscalerResource implements ServerResource {
metrictable_metric_binding.set_metrictable(mtName);
metrictable_metric_binding.set_metric(counterName);
metrictable_metric_binding.set_Snmpoid(counterOid);
metrictable_metric_binding.add(login_get_service(true), metrictable_metric_binding);
metrictable_metric_binding.add(_netscalerService, metrictable_metric_binding);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -945,7 +922,7 @@ public class NetscalerResource implements ServerResource {
monitor_metrictable_binding.set_monitorname(monitorName);
monitor_metrictable_binding.set_metric(counterName);
monitor_metrictable_binding.set_metricthreshold(1); // 1 is a dummy threshold
monitor_metrictable_binding.add(login_get_service(true), monitor_metrictable_binding);
monitor_metrictable_binding.add(_netscalerService, monitor_metrictable_binding);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -999,7 +976,7 @@ public class NetscalerResource implements ServerResource {
timerPolicy.set_name(policyName);
timerPolicy.set_action(action);
timerPolicy.set_rule(policyExpression);
timerPolicy.add(login_get_service(true), timerPolicy);
timerPolicy.add(_netscalerService, timerPolicy);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -1021,7 +998,7 @@ public class NetscalerResource implements ServerResource {
timer_policy_binding.set_thresholdsize(sampleSize); // We are not exposing this parameter as of now.
// i.e. n(m) is not exposed to CS user. So thresholdSize == sampleSize
timer_policy_binding.set_priority(priority);
timer_policy_binding.add(login_get_service(true), timer_policy_binding);
timer_policy_binding.add(_netscalerService, timer_policy_binding);
} catch (Exception e) {
// Ignore Exception
throw e;
@ -1056,7 +1033,7 @@ public class NetscalerResource implements ServerResource {
private boolean isAutoScaleSupportedInNetScaler() throws ExecutionException {
autoscaleprofile autoscaleProfile = new autoscaleprofile();
try {
autoscaleProfile.get(login_get_service(true));
autoscaleProfile.get(_netscalerService);
} catch (Exception ex) {
// Looks like autoscale is not supported in this netscaler.
// TODO: Config team has introduce a new command to check
@ -1120,7 +1097,7 @@ public class NetscalerResource implements ServerResource {
com.citrix.netscaler.nitro.resource.config.basic.server nsServer = new com.citrix.netscaler.nitro.resource.config.basic.server();
nsServer.set_name(nsServerName);
nsServer.set_ipaddress(destination.getDestIp());
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.add(login_get_service(null), nsServer);
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.add(_netscalerService, nsServer);
if ((apiCallResult.errorcode != 0) && (apiCallResult.errorcode != NitroError.NS_RESOURCE_EXISTS)) {
throw new ExecutionException("Failed to add server " + destination.getDestIp() + " due to" + apiCallResult.message);
}
@ -1135,7 +1112,7 @@ public class NetscalerResource implements ServerResource {
newService.set_state("ENABLED");
newService.set_servicetype(lbProtocol);
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.add(login_get_service(null), newService);
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.add(_netscalerService, newService);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to create service " + nsServiceName + " using server " + nsServerName + " due to" + apiCallResult.message);
}
@ -1146,7 +1123,7 @@ public class NetscalerResource implements ServerResource {
com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding svcBinding = new com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding();
svcBinding.set_name(nsVirtualServerName);
svcBinding.set_servicename(nsServiceName);
apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.add(login_get_service(null), svcBinding);
apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.add(_netscalerService, svcBinding);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to bind service: " + nsServiceName + " to the lb virtual server: " + nsVirtualServerName + " on Netscaler device");
@ -1157,13 +1134,13 @@ public class NetscalerResource implements ServerResource {
}
} else {
// remove a destination from the deployed load balancing rule
com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(login_get_service(null),
com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(_netscalerService,
nsVirtualServerName);
if (serviceBindings != null) {
for (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
if (nsServiceName.equalsIgnoreCase(binding.get_servicename())) {
// delete the binding
apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.delete(login_get_service(null), binding);
apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.delete(_netscalerService, binding);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to delete the binding between the virtual server: " + nsVirtualServerName + " and service:" + nsServiceName + " due to"
+ apiCallResult.message);
@ -1172,16 +1149,16 @@ public class NetscalerResource implements ServerResource {
// check if service is bound to any other virtual server
if (!isServiceBoundToVirtualServer(nsServiceName)) {
// no lb virtual servers are bound to this service so delete it
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(login_get_service(null), nsServiceName);
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(_netscalerService, nsServiceName);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to delete service: " + nsServiceName + " due to " + apiCallResult.message);
}
}
// delete the server if there is no associated services
server_service_binding[] services = server_service_binding.get(login_get_service(null), nsServerName);
server_service_binding[] services = server_service_binding.get(_netscalerService, nsServerName);
if ((services == null) || (services.length == 0)) {
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(login_get_service(null), nsServerName);
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(_netscalerService, nsServerName);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to remove server:" + nsServerName + " due to " + apiCallResult.message);
}
@ -1196,33 +1173,33 @@ public class NetscalerResource implements ServerResource {
lbvserver lbserver = getVirtualServerIfExisits(nsVirtualServerName);
if (lbserver != null) {
//unbind the all services associated with this virtual server
com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(login_get_service(null),
com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(_netscalerService,
nsVirtualServerName);
if (serviceBindings != null) {
for (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
String serviceName = binding.get_servicename();
apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.delete(login_get_service(null), binding);
apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.delete(_netscalerService, binding);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to unbind service from the lb virtual server: " + nsVirtualServerName + " due to " + apiCallResult.message);
}
com.citrix.netscaler.nitro.resource.config.basic.service svc = com.citrix.netscaler.nitro.resource.config.basic.service.get(login_get_service(null), serviceName);
com.citrix.netscaler.nitro.resource.config.basic.service svc = com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService, serviceName);
String nsServerName = svc.get_servername();
// check if service is bound to any other virtual server
if (!isServiceBoundToVirtualServer(serviceName)) {
// no lb virtual servers are bound to this service so delete it
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(login_get_service(null), serviceName);
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(_netscalerService, serviceName);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to delete service: " + serviceName + " due to " + apiCallResult.message);
}
}
//delete the server if no more services attached
server_service_binding[] services = server_service_binding.get(login_get_service(null), nsServerName);
server_service_binding[] services = server_service_binding.get(_netscalerService, nsServerName);
if ((services == null) || (services.length == 0)) {
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(login_get_service(null), nsServerName);
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(_netscalerService, nsServerName);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to remove server:" + nsServerName + " due to " + apiCallResult.message);
}
@ -1341,7 +1318,7 @@ public class NetscalerResource implements ServerResource {
try {
nitro_service _netscalerService = new nitro_service(cmd.getLoadBalancerIP(), "https");
_netscalerService.set_credential(username, password);
_netscalerService.set_timeout(_timeout);
// _netscalerService.set_timeout(_timeout);
apiCallResult = _netscalerService.login();
if (apiCallResult.errorcode == 0) {
nsServiceUp = true;
@ -1537,7 +1514,7 @@ public class NetscalerResource implements ServerResource {
if (!rule.revoked()) {
try {
iNatRule = inat.get(login_get_service(null), iNatRuleName);
iNatRule = inat.get(_netscalerService, iNatRuleName);
} catch (nitro_exception e) {
if (e.getErrorCode() != NitroError.NS_RESOURCE_NOT_EXISTS) {
throw e;
@ -1552,7 +1529,7 @@ public class NetscalerResource implements ServerResource {
iNatRule.set_usnip("OFF");
iNatRule.set_usip("ON");
try {
apiCallResult = inat.add(login_get_service(null), iNatRule);
apiCallResult = inat.add(_netscalerService, iNatRule);
} catch (nitro_exception e) {
if (e.getErrorCode() != NitroError.NS_RESOURCE_EXISTS) {
throw e;
@ -1562,7 +1539,7 @@ public class NetscalerResource implements ServerResource {
}
} else {
try {
inat.delete(login_get_service(null), iNatRuleName);
inat.delete(_netscalerService, iNatRuleName);
} catch (nitro_exception e) {
if (e.getErrorCode() != NitroError.NS_RESOURCE_NOT_EXISTS) {
throw e;
@ -1608,7 +1585,7 @@ public class NetscalerResource implements ServerResource {
selfIp.set_ipaddress(snip);
selfIp.set_netmask(netmask);
selfIp.set_type("SNIP");
apiCallResult = nsip.add(login_get_service(null), selfIp);
apiCallResult = nsip.add(_netscalerService, selfIp);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to add SNIP object on the Netscaler device due to "+ apiCallResult.message);
}
@ -1626,7 +1603,7 @@ public class NetscalerResource implements ServerResource {
try {
vlan vlanObj = new vlan();
vlanObj.set_id(vlanTag);
apiCallResult = vlan.add(login_get_service(null), vlanObj);
apiCallResult = vlan.add(_netscalerService, vlanObj);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to add new vlan with tag:" + vlanTag + "on the NetScaler device due to " + apiCallResult.message);
}
@ -1642,7 +1619,7 @@ public class NetscalerResource implements ServerResource {
selfIp.set_ipaddress(vlanSelfIp);
selfIp.set_netmask(vlanNetmask);
selfIp.set_type("SNIP");
apiCallResult = nsip.add(login_get_service(null), selfIp);
apiCallResult = nsip.add(_netscalerService, selfIp);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to add SNIP object for the guest network on the Netscaler device due to "+ apiCallResult.message);
}
@ -1658,7 +1635,7 @@ public class NetscalerResource implements ServerResource {
ipVlanBinding.set_id(vlanTag);
ipVlanBinding.set_ipaddress(vlanSelfIp);
ipVlanBinding.set_netmask(vlanNetmask);
apiCallResult = vlan_nsip_binding.add(login_get_service(null), ipVlanBinding);
apiCallResult = vlan_nsip_binding.add(_netscalerService, ipVlanBinding);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to bind VLAN with tag:" + vlanTag + " to the subnet due to " + apiCallResult.message);
}
@ -1677,7 +1654,7 @@ public class NetscalerResource implements ServerResource {
}
vlanBinding.set_tagged(true);
vlanBinding.set_id(vlanTag);
apiCallResult = vlan_interface_binding.add(login_get_service(null), vlanBinding);
apiCallResult = vlan_interface_binding.add(_netscalerService, vlanBinding);
if (apiCallResult.errorcode != 0) {
String vlanInterface = guestVlan ? _privateInterface : _publicInterface;
throw new ExecutionException("Failed to bind vlan with tag:" + vlanTag + " with the interface " + vlanInterface + " due to " + apiCallResult.message);
@ -1706,7 +1683,7 @@ public class NetscalerResource implements ServerResource {
vlanIfBinding.set_id(vlanTag);
vlanIfBinding.set_ifnum(_privateInterface);
vlanIfBinding.set_tagged(true);
apiCallResult = vlan_interface_binding.delete(login_get_service(null), vlanIfBinding);
apiCallResult = vlan_interface_binding.delete(_netscalerService, vlanIfBinding);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to unbind vlan:" + vlanTag + " with the private interface due to " + apiCallResult.message);
}
@ -1723,7 +1700,7 @@ public class NetscalerResource implements ServerResource {
vlanSnipBinding.set_netmask(vlanNetmask);
vlanSnipBinding.set_ipaddress(vlanSelfIp);
vlanSnipBinding.set_id(vlanTag);
apiCallResult = vlan_nsip_binding.delete(login_get_service(null), vlanSnipBinding);
apiCallResult = vlan_nsip_binding.delete(_netscalerService, vlanSnipBinding);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to unbind vlan:" + vlanTag + " with the subnet due to " + apiCallResult.message);
}
@ -1736,8 +1713,8 @@ public class NetscalerResource implements ServerResource {
// remove subnet IP
try {
nsip subnetIp = nsip.get(login_get_service(null), vlanSelfIp);
apiCallResult = nsip.delete(login_get_service(null), subnetIp);
nsip subnetIp = nsip.get(_netscalerService, vlanSelfIp);
apiCallResult = nsip.delete(_netscalerService, subnetIp);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to remove subnet ip:" + vlanSelfIp + " from the NetScaler device due to" + apiCallResult.message);
}
@ -1751,7 +1728,7 @@ public class NetscalerResource implements ServerResource {
// remove the vlan from the NetScaler device
if (nsVlanExists(vlanTag)) {
// remove vlan
apiCallResult = com.citrix.netscaler.nitro.resource.config.network.vlan.delete(login_get_service(null), vlanTag);
apiCallResult = com.citrix.netscaler.nitro.resource.config.network.vlan.delete(_netscalerService, vlanTag);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to remove vlan with tag:" + vlanTag + "due to" + apiCallResult.message);
}
@ -1765,7 +1742,7 @@ public class NetscalerResource implements ServerResource {
private boolean nsVlanExists(long vlanTag) throws ExecutionException {
try {
if (vlan.get(login_get_service(null), new Long(vlanTag)) != null) {
if (vlan.get(_netscalerService, new Long(vlanTag)) != null) {
return true;
} else {
return false;
@ -1783,7 +1760,7 @@ public class NetscalerResource implements ServerResource {
private boolean nsSnipExists(String subnetIP) throws ExecutionException {
try {
nsip snip = nsip.get(login_get_service(null), subnetIP);
nsip snip = nsip.get(_netscalerService, subnetIP);
return (snip != null);
} catch (nitro_exception e) {
if (e.getErrorCode() == NitroError.NS_RESOURCE_NOT_EXISTS) {
@ -1798,7 +1775,7 @@ public class NetscalerResource implements ServerResource {
private boolean nsServerExists(String serverName) throws ExecutionException {
try {
if (com.citrix.netscaler.nitro.resource.config.basic.server.get(login_get_service(null), serverName) != null) {
if (com.citrix.netscaler.nitro.resource.config.basic.server.get(_netscalerService, serverName) != null) {
return true;
} else {
return false;
@ -1816,7 +1793,7 @@ public class NetscalerResource implements ServerResource {
private boolean nsVlanNsipBindingExists(long vlanTag, String vlanSelfIp) throws ExecutionException {
try {
vlan_nsip_binding[] vlanNsipBindings = vlan_nsip_binding.get(login_get_service(null), vlanTag);
vlan_nsip_binding[] vlanNsipBindings = vlan_nsip_binding.get(_netscalerService, vlanTag);
if (vlanNsipBindings != null && vlanNsipBindings[0] != null && vlanNsipBindings[0].get_ipaddress().equalsIgnoreCase(vlanSelfIp)) {
return true;
} else {
@ -1835,7 +1812,7 @@ public class NetscalerResource implements ServerResource {
private lbvserver getVirtualServerIfExisits(String lbVServerName ) throws ExecutionException {
try {
return lbvserver.get(login_get_service(true), lbVServerName);
return lbvserver.get(_netscalerService, lbVServerName);
} catch (nitro_exception e) {
if (e.getErrorCode() == NitroError.NS_RESOURCE_NOT_EXISTS) {
return null;
@ -1849,11 +1826,11 @@ public class NetscalerResource implements ServerResource {
private boolean isServiceBoundToVirtualServer(String serviceName) throws ExecutionException {
try {
lbvserver[] lbservers = lbvserver.get(login_get_service(null));
lbvserver[] lbservers = lbvserver.get(_netscalerService);
for (lbvserver vserver : lbservers) {
filtervalue[] filter = new filtervalue[1];
filter[0] = new filtervalue("servicename", serviceName);
lbvserver_service_binding[] result = lbvserver_service_binding.get_filtered(login_get_service(null), vserver.get_name(), filter);
lbvserver_service_binding[] result = lbvserver_service_binding.get_filtered(_netscalerService, vserver.get_name(), filter);
if (result != null && result.length > 0) {
return true;
}
@ -1866,7 +1843,7 @@ public class NetscalerResource implements ServerResource {
private boolean nsServiceExists(String serviceName) throws ExecutionException {
try {
if (com.citrix.netscaler.nitro.resource.config.basic.service.get(login_get_service(null), serviceName) != null) {
if (com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService, serviceName) != null) {
return true;
} else {
return false;
@ -1884,7 +1861,7 @@ public class NetscalerResource implements ServerResource {
private boolean nsServiceBindingExists(String lbVirtualServer, String serviceName) throws ExecutionException {
try {
com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(login_get_service(null), lbVirtualServer);
com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(_netscalerService, lbVirtualServer);
if (serviceBindings != null) {
for (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
if (serviceName.equalsIgnoreCase(binding.get_servicename())) {
@ -1902,7 +1879,7 @@ public class NetscalerResource implements ServerResource {
private void deleteServersInGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask) throws ExecutionException {
try {
com.citrix.netscaler.nitro.resource.config.basic.server[] serverList = com.citrix.netscaler.nitro.resource.config.basic.server.get(login_get_service(null));
com.citrix.netscaler.nitro.resource.config.basic.server[] serverList = com.citrix.netscaler.nitro.resource.config.basic.server.get(_netscalerService);
if (serverList == null) {
return;
@ -1913,11 +1890,11 @@ public class NetscalerResource implements ServerResource {
// check if server belong to same subnet as one associated with vlan
if (NetUtils.sameSubnet(vlanSelfIp, server.get_ipaddress(), vlanNetmask)) {
// first remove services associated with this server
com.citrix.netscaler.nitro.resource.config.basic.service serveicesList[] = com.citrix.netscaler.nitro.resource.config.basic.service.get(login_get_service(null));
com.citrix.netscaler.nitro.resource.config.basic.service serveicesList[] = com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService);
if (serveicesList != null) {
for (com.citrix.netscaler.nitro.resource.config.basic.service svc : serveicesList) {
if (svc.get_servername().equals(server.get_ipaddress())) {
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(login_get_service(null), svc.get_name());
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(_netscalerService, svc.get_name());
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to remove service:" + svc.get_name());
}
@ -1925,7 +1902,7 @@ public class NetscalerResource implements ServerResource {
}
}
// remove the server
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(login_get_service(null), server.get_name());
apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(_netscalerService, server.get_name());
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to remove server:" + server.get_name());
}
@ -2034,11 +2011,18 @@ public class NetscalerResource implements ServerResource {
vserver.set_persistencetype("NONE");
}
}
if(vmGroupTO != null) {
vserver.set_mysqlcharacterset(null);
vserver.set_mysqlprotocolversion(null);
vserver.set_mysqlservercapabilities(null);
vserver.set_mysqlserverversion(null);
}
if (vserverExisis) {
apiCallResult = lbvserver.update(login_get_service(vmGroupTO != null),vserver);
apiCallResult = lbvserver.update(_netscalerService,vserver);
} else {
apiCallResult = lbvserver.add(login_get_service(vmGroupTO != null),vserver);
apiCallResult = lbvserver.add(_netscalerService,vserver);
}
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to create new load balancing virtual server:" + virtualServerName + " due to " + apiCallResult.message);
@ -2057,11 +2041,11 @@ public class NetscalerResource implements ServerResource {
private void removeLBVirtualServer (String virtualServerName) throws ExecutionException {
try {
lbvserver vserver = lbvserver.get(login_get_service(true), virtualServerName);
lbvserver vserver = lbvserver.get(_netscalerService, virtualServerName);
if (vserver == null) {
return;
}
apiCallResult = lbvserver.delete(login_get_service(true), vserver);
apiCallResult = lbvserver.delete(_netscalerService, vserver);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Failed to delete virtual server:" + virtualServerName + " due to " + apiCallResult.message);
}
@ -2078,7 +2062,7 @@ public class NetscalerResource implements ServerResource {
private void saveConfiguration() throws ExecutionException {
try {
apiCallResult = nsconfig.save(login_get_service(true));
apiCallResult = nsconfig.save(_netscalerService);
if (apiCallResult.errorcode != 0) {
throw new ExecutionException("Error occured while saving configuration changes to Netscaler device due to " + apiCallResult.message);
}
@ -2093,7 +2077,7 @@ public class NetscalerResource implements ServerResource {
ExternalNetworkResourceUsageAnswer answer = new ExternalNetworkResourceUsageAnswer(cmd);
try {
lbvserver_stats[] stats = lbvserver_stats.get(login_get_service(null));
lbvserver_stats[] stats = lbvserver_stats.get(_netscalerService);
if (stats == null || stats.length == 0) {
return answer;
@ -2101,7 +2085,7 @@ public class NetscalerResource implements ServerResource {
for (lbvserver_stats stat_entry : stats) {
String lbvserverName = stat_entry.get_name();
lbvserver vserver = lbvserver.get(login_get_service(null), lbvserverName);
lbvserver vserver = lbvserver.get(_netscalerService, lbvserverName);
if(vserver != null){
String lbVirtualServerIp = vserver.get_ipv46();

View File

@ -0,0 +1,9 @@
#!/bin/bash
for i in $*
do
info=`/opt/cloud/bin/checks2svpn.sh $i`
ret=$?
echo -n "$i:$ret:$info&"
done

View File

@ -12,20 +12,20 @@ cat /tmp/vpn-$1.status | grep "ISAKMP SA established" > /dev/null
isakmpok=$?
if [ $isakmpok -ne 0 ]
then
echo "ISAKMP SA not found"
echo -n "ISAKMP SA not found"
echo "Site-to-site VPN have not connected"
exit 12
fi
echo "ISAKMP SA found"
echo -n "ISAKMP SA found;"
cat /tmp/vpn-$1.status | grep "IPsec SA established" > /dev/null
ipsecok=$?
if [ $ipsecok -ne 0 ]
then
echo "IPsec SA not found"
echo -n "IPsec SA not found;"
echo "Site-to-site VPN have not connected"
exit 11
fi
echo "IPsec SA found"
echo -n "IPsec SA found;"
echo "Site-to-site VPN have connected"
exit 0

View File

@ -12,6 +12,7 @@
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.baremetal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -44,6 +45,7 @@ import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceStateAdapter;
import com.cloud.resource.ServerResource;
import com.cloud.resource.UnableDeleteHostException;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
@ -58,192 +60,195 @@ import com.cloud.vm.dao.UserVmDao;
@Local(value = {ExternalDhcpManager.class})
public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceStateAdapter {
private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalDhcpManagerImpl.class);
protected String _name;
@Inject DataCenterDao _dcDao;
@Inject HostDao _hostDao;
@Inject AgentManager _agentMgr;
@Inject HostPodDao _podDao;
@Inject UserVmDao _userVmDao;
@Inject ResourceManager _resourceMgr;
@Inject NicDao _nicDao;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
return true;
}
private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalDhcpManagerImpl.class);
protected String _name;
@Inject DataCenterDao _dcDao;
@Inject HostDao _hostDao;
@Inject AgentManager _agentMgr;
@Inject HostPodDao _podDao;
@Inject UserVmDao _userVmDao;
@Inject ResourceManager _resourceMgr;
@Inject NicDao _nicDao;
@Override
public boolean start() {
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
return true;
}
@Override
public boolean stop() {
_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public boolean stop() {
_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
return true;
}
protected String getDhcpServerGuid(String zoneId, String name, String ip) {
return zoneId + "-" + name + "-" + ip;
}
@Override @DB
public Host addDhcpServer(Long zoneId, Long podId, String type, String url, String username, String password) {
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
}
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new InvalidParameterValueException("Could not find pod with ID: " + podId);
}
List<HostVO> dhcps = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.ExternalDhcp, null, podId, zoneId);
if (dhcps.size() != 0) {
throw new InvalidParameterValueException("Already had a DHCP server in Pod: " + podId + " zone: " + zoneId);
}
String ipAddress = url;
String guid = getDhcpServerGuid(Long.toString(zoneId) + "-" + Long.toString(podId), "ExternalDhcp", ipAddress);
Map params = new HashMap<String, String>();
params.put("type", type);
params.put("zone", Long.toString(zoneId));
params.put("pod", podId.toString());
params.put("ip", ipAddress);
params.put("username", username);
params.put("password", password);
params.put("guid", guid);
params.put("pod", Long.toString(podId));
params.put("gateway", pod.getGateway());
String dns = zone.getDns1();
if (dns == null) {
dns = zone.getDns2();
}
params.put("dns", dns);
ServerResource resource = null;
try {
if (type.equalsIgnoreCase(DhcpServerType.Dnsmasq.getName())) {
resource = new DnsmasqResource();
resource.configure("Dnsmasq resource", params);
} else if (type.equalsIgnoreCase(DhcpServerType.Dhcpd.getName())) {
resource = new DhcpdResource();
resource.configure("Dhcpd resource", params);
} else {
throw new CloudRuntimeException("Unsupport DHCP server " + type);
}
} catch (Exception e) {
s_logger.debug(e);
throw new CloudRuntimeException(e.getMessage());
}
Host dhcpServer = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalDhcp, params);
if (dhcpServer == null) {
throw new CloudRuntimeException("Cannot add external Dhcp server as a host");
}
Transaction txn = Transaction.currentTxn();
@Override
public String getName() {
return _name;
}
protected String getDhcpServerGuid(String zoneId, String name, String ip) {
return zoneId + "-" + name + "-" + ip;
}
@Override @DB
public Host addDhcpServer(Long zoneId, Long podId, String type, String url, String username, String password) {
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Could not find zone by ID", null);
}
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new InvalidParameterValueException("Could not find pod by ID", null);
}
List<HostVO> dhcps = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.ExternalDhcp, null, podId, zoneId);
if (dhcps.size() != 0) {
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(pod, podId, "podId"));
idList.add(new IdentityProxy(zone, zoneId, "zoneId"));
throw new InvalidParameterValueException("Already had a DHCP server in Pod with specified podId in zone with specified zoneId", idList);
}
String ipAddress = url;
String guid = getDhcpServerGuid(Long.toString(zoneId) + "-" + Long.toString(podId), "ExternalDhcp", ipAddress);
Map params = new HashMap<String, String>();
params.put("type", type);
params.put("zone", Long.toString(zoneId));
params.put("pod", podId.toString());
params.put("ip", ipAddress);
params.put("username", username);
params.put("password", password);
params.put("guid", guid);
params.put("pod", Long.toString(podId));
params.put("gateway", pod.getGateway());
String dns = zone.getDns1();
if (dns == null) {
dns = zone.getDns2();
}
params.put("dns", dns);
ServerResource resource = null;
try {
if (type.equalsIgnoreCase(DhcpServerType.Dnsmasq.getName())) {
resource = new DnsmasqResource();
resource.configure("Dnsmasq resource", params);
} else if (type.equalsIgnoreCase(DhcpServerType.Dhcpd.getName())) {
resource = new DhcpdResource();
resource.configure("Dhcpd resource", params);
} else {
throw new CloudRuntimeException("Unsupport DHCP server " + type);
}
} catch (Exception e) {
s_logger.debug(e);
throw new CloudRuntimeException(e.getMessage());
}
Host dhcpServer = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalDhcp, params);
if (dhcpServer == null) {
throw new CloudRuntimeException("Cannot add external Dhcp server as a host");
}
Transaction txn = Transaction.currentTxn();
txn.start();
pod.setExternalDhcp(true);
_podDao.update(pod.getId(), pod);
txn.commit();
return dhcpServer;
}
@Override
public DhcpServerResponse getApiResponse(Host dhcpServer) {
DhcpServerResponse response = new DhcpServerResponse();
response.setId(dhcpServer.getId());
return response;
}
private void prepareBareMetalDhcpEntry(NicProfile nic, DhcpEntryCommand cmd) {
Long vmId = nic.getVmId();
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null || vm.getHypervisorType() != HypervisorType.BareMetal) {
s_logger.debug("VM " + vmId + " is not baremetal machine, skip preparing baremetal DHCP entry");
return;
}
List<HostVO> servers = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.PxeServer, null, vm.getPodIdToDeployIn(), vm.getDataCenterIdToDeployIn());
if (servers.size() != 1) {
throw new CloudRuntimeException("Wrong number of PXE server found in zone " + vm.getDataCenterIdToDeployIn()
+ " Pod " + vm.getPodIdToDeployIn() + ", number is " + servers.size());
}
HostVO pxeServer = servers.get(0);
cmd.setNextServer(pxeServer.getPrivateIpAddress());
s_logger.debug("Set next-server to " + pxeServer.getPrivateIpAddress() + " for VM " + vm.getId());
}
@Override
public boolean addVirtualMachineIntoNetwork(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> profile, DeployDestination dest,
ReservationContext context) throws ResourceUnavailableException {
Long zoneId = profile.getVirtualMachine().getDataCenterIdToDeployIn();
Long podId = profile.getVirtualMachine().getPodIdToDeployIn();
List<HostVO> hosts = _resourceMgr.listAllUpAndEnabledHosts(Type.ExternalDhcp, null, podId, zoneId);
if (hosts.size() == 0) {
throw new CloudRuntimeException("No external Dhcp found in zone " + zoneId + " pod " + podId);
}
if (hosts.size() > 1) {
throw new CloudRuntimeException("Something wrong, more than 1 external Dhcp found in zone " + zoneId + " pod " + podId);
}
HostVO h = hosts.get(0);
String dns = nic.getDns1();
if (dns == null) {
dns = nic.getDns2();
}
DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), profile.getVirtualMachine().getHostName(), dns, nic.getGateway());
String errMsg = String.format("Set dhcp entry on external DHCP %1$s failed(ip=%2$s, mac=%3$s, vmname=%4$s)",
h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName());
//prepareBareMetalDhcpEntry(nic, dhcpCommand);
try {
Answer ans = _agentMgr.send(h.getId(), dhcpCommand);
if (ans.getResult()) {
s_logger.debug(String.format("Set dhcp entry on external DHCP %1$s successfully(ip=%2$s, mac=%3$s, vmname=%4$s)",
h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName()));
return true;
} else {
s_logger.debug(errMsg + " " + ans.getDetails());
throw new ResourceUnavailableException(errMsg, DataCenter.class, zoneId);
}
} catch (Exception e) {
s_logger.debug(errMsg, e);
throw new ResourceUnavailableException(errMsg + e.getMessage(), DataCenter.class, zoneId);
}
}
@Override
public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
// TODO Auto-generated method stub
return null;
return dhcpServer;
}
@Override
@Override
public DhcpServerResponse getApiResponse(Host dhcpServer) {
DhcpServerResponse response = new DhcpServerResponse();
response.setId(dhcpServer.getId());
return response;
}
private void prepareBareMetalDhcpEntry(NicProfile nic, DhcpEntryCommand cmd) {
Long vmId = nic.getVmId();
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null || vm.getHypervisorType() != HypervisorType.BareMetal) {
s_logger.debug("VM " + vmId + " is not baremetal machine, skip preparing baremetal DHCP entry");
return;
}
List<HostVO> servers = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.PxeServer, null, vm.getPodIdToDeployIn(), vm.getDataCenterIdToDeployIn());
if (servers.size() != 1) {
throw new CloudRuntimeException("Wrong number of PXE server found in zone " + vm.getDataCenterIdToDeployIn()
+ " Pod " + vm.getPodIdToDeployIn() + ", number is " + servers.size());
}
HostVO pxeServer = servers.get(0);
cmd.setNextServer(pxeServer.getPrivateIpAddress());
s_logger.debug("Set next-server to " + pxeServer.getPrivateIpAddress() + " for VM " + vm.getId());
}
@Override
public boolean addVirtualMachineIntoNetwork(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> profile, DeployDestination dest,
ReservationContext context) throws ResourceUnavailableException {
Long zoneId = profile.getVirtualMachine().getDataCenterIdToDeployIn();
Long podId = profile.getVirtualMachine().getPodIdToDeployIn();
List<HostVO> hosts = _resourceMgr.listAllUpAndEnabledHosts(Type.ExternalDhcp, null, podId, zoneId);
if (hosts.size() == 0) {
throw new CloudRuntimeException("No external Dhcp found in zone " + zoneId + " pod " + podId);
}
if (hosts.size() > 1) {
throw new CloudRuntimeException("Something wrong, more than 1 external Dhcp found in zone " + zoneId + " pod " + podId);
}
HostVO h = hosts.get(0);
String dns = nic.getDns1();
if (dns == null) {
dns = nic.getDns2();
}
DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), profile.getVirtualMachine().getHostName(), dns, nic.getGateway());
String errMsg = String.format("Set dhcp entry on external DHCP %1$s failed(ip=%2$s, mac=%3$s, vmname=%4$s)",
h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName());
//prepareBareMetalDhcpEntry(nic, dhcpCommand);
try {
Answer ans = _agentMgr.send(h.getId(), dhcpCommand);
if (ans.getResult()) {
s_logger.debug(String.format("Set dhcp entry on external DHCP %1$s successfully(ip=%2$s, mac=%3$s, vmname=%4$s)",
h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName()));
return true;
} else {
s_logger.debug(errMsg + " " + ans.getDetails());
throw new ResourceUnavailableException(errMsg, DataCenter.class, zoneId);
}
} catch (Exception e) {
s_logger.debug(errMsg, e);
throw new ResourceUnavailableException(errMsg + e.getMessage(), DataCenter.class, zoneId);
}
}
@Override
public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
// TODO Auto-generated method stub
return null;
}
@Override
public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map<String, String> details,
List<String> hostTags) {
if (!(startup[0] instanceof StartupExternalDhcpCommand)) {
return null;
}
host.setType(Host.Type.ExternalDhcp);
return host;
}
@Override
@Override
public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException {
// TODO Auto-generated method stub
return null;
// TODO Auto-generated method stub
return null;
}
}

View File

@ -224,7 +224,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
RulesManager _rulesMgr;
@Inject
IPAddressDao _ipAddressDao;
private ConsoleProxyListener _listener;
private ServiceOfferingVO _serviceOffering;
@ -257,7 +257,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
private Map<Long, ZoneHostInfo> _zoneHostInfoMap; // map <zone id, info about running host in zone>
private Map<Long, ConsoleProxyLoadInfo> _zoneProxyCountMap; // map <zone id, info about proxy VMs count in zone>
private Map<Long, ConsoleProxyLoadInfo> _zoneVmCountMap; // map <zone id, info about running VMs count in zone>
private String _hashKey;
private final GlobalLock _allocProxyLock = GlobalLock.getInternLock(getAllocProxyLockName());
@ -879,26 +879,26 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
if(!cmd.isReauthenticating()) {
String ticket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 1 minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + ticket);
}
if (!ticket.equals(ticketInUrl)) {
Date now = new Date();
// considering of minute round-up
String minuteEarlyTicket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId(), new Date(now.getTime() - 60 * 1000));
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 2-minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + minuteEarlyTicket);
}
if (!minuteEarlyTicket.equals(ticketInUrl)) {
s_logger.error("Access ticket expired or has been modified. vmId: " + cmd.getVmId() + "ticket in URL: " + ticketInUrl + ", tickets to check against: " + ticket + ","
+ minuteEarlyTicket);
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
}
String ticket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 1 minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + ticket);
}
if (!ticket.equals(ticketInUrl)) {
Date now = new Date();
// considering of minute round-up
String minuteEarlyTicket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId(), new Date(now.getTime() - 60 * 1000));
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 2-minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + minuteEarlyTicket);
}
if (!minuteEarlyTicket.equals(ticketInUrl)) {
s_logger.error("Access ticket expired or has been modified. vmId: " + cmd.getVmId() + "ticket in URL: " + ticketInUrl + ", tickets to check against: " + ticket + ","
+ minuteEarlyTicket);
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
}
}
if (cmd.getVmId() != null && cmd.getVmId().isEmpty()) {
@ -935,38 +935,38 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
s_logger.warn("sid " + sid + " in url does not match stored sid " + vm.getVncPassword());
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
if(cmd.isReauthenticating()) {
ConsoleAccessAuthenticationAnswer authenticationAnswer = new ConsoleAccessAuthenticationAnswer(cmd, true);
authenticationAnswer.setReauthenticating(true);
s_logger.info("Re-authentication request, ask host " + vm.getHostId() + " for new console info");
GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new
GetVncPortCommand(vm.getId(), vm.getInstanceName()));
GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new
GetVncPortCommand(vm.getId(), vm.getInstanceName()));
if (answer != null && answer.getResult()) {
Ternary<String, String, String> parsedHostInfo = ConsoleProxyServlet.parseHostInfo(answer.getAddress());
if(parsedHostInfo.second() != null && parsedHostInfo.third() != null) {
Ternary<String, String, String> parsedHostInfo = ConsoleProxyServlet.parseHostInfo(answer.getAddress());
if(parsedHostInfo.second() != null && parsedHostInfo.third() != null) {
s_logger.info("Re-authentication result. vm: " + vm.getId() + ", tunnel url: " + parsedHostInfo.second()
+ ", tunnel session: " + parsedHostInfo.third());
authenticationAnswer.setTunnelUrl(parsedHostInfo.second());
authenticationAnswer.setTunnelSession(parsedHostInfo.third());
} else {
+ ", tunnel session: " + parsedHostInfo.third());
authenticationAnswer.setTunnelUrl(parsedHostInfo.second());
authenticationAnswer.setTunnelSession(parsedHostInfo.third());
} else {
s_logger.info("Re-authentication result. vm: " + vm.getId() + ", host address: " + parsedHostInfo.first()
+ ", port: " + answer.getPort());
authenticationAnswer.setHost(parsedHostInfo.first());
authenticationAnswer.setPort(answer.getPort());
}
+ ", port: " + answer.getPort());
authenticationAnswer.setHost(parsedHostInfo.first());
authenticationAnswer.setPort(answer.getPort());
}
} else {
s_logger.warn("Re-authentication request failed");
authenticationAnswer.setSuccess(false);
authenticationAnswer.setSuccess(false);
}
return authenticationAnswer;
}
@ -1383,7 +1383,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
result = result && _hostDao.remove(host.getId());
}
}
return result;
} catch (ResourceUnavailableException e) {
s_logger.warn("Unable to expunge " + proxy, e);
@ -1497,7 +1497,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this);
boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));
//check if there is a default service offering configured
String cpvmSrvcOffIdStr = configs.get(Config.ConsoleProxyServiceOffering.key());
if (cpvmSrvcOffIdStr != null) {
@ -1538,7 +1538,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
// verify parameters
ConsoleProxyVO proxy = _consoleProxyDao.findById(proxyId);
if (proxy == null) {
throw new InvalidParameterValueException("unable to find a console proxy with id " + proxyId);
throw new InvalidParameterValueException("unable to find a console proxy by id", null);
}
return destroyProxy(proxyId);
@ -1981,7 +1981,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
sc.addAnd(sc.getEntity().getName(), Op.EQ, name);
return sc.find();
}
public String getHashKey() {
// although we may have race conditioning here, database transaction serialization should
// give us the same key
@ -2007,15 +2007,15 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType());
}
@Override
public void prepareStop(VirtualMachineProfile<ConsoleProxyVO> profile) {
}
@Override
public void prepareStop(VirtualMachineProfile<ConsoleProxyVO> profile) {
}
@Override
public boolean recreateNeeded(
VirtualMachineProfile<ConsoleProxyVO> profile, long hostId,
Commands cmds, ReservationContext context) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean recreateNeeded(
VirtualMachineProfile<ConsoleProxyVO> profile, long hostId,
Commands cmds, ReservationContext context) {
// TODO Auto-generated method stub
return false;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -12,41 +12,38 @@
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.agent.api.StartupCommand;
import com.cloud.api.ApiConstants;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.ClusterVSMMapVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.ClusterVSMMapDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.host.DetailVO;
import com.cloud.exception.ResourceInUseException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDetailsDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.vmware.manager.VmwareManager;
import com.cloud.network.dao.CiscoNexusVSMDeviceDao;
import com.cloud.network.dao.PortProfileDao;
import com.cloud.resource.ResourceManager;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.network.dao.CiscoNexusVSMDeviceDao;
import com.cloud.network.dao.PortProfileDao;
import com.cloud.exception.ResourceInUseException;
import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper;
public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
@Inject
@Inject
CiscoNexusVSMDeviceDao _ciscoNexusVSMDeviceDao;
@Inject
ClusterDao _clusterDao;
@ -54,8 +51,8 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
ClusterVSMMapDao _clusterVSMDao;
@Inject
ResourceManager _resourceMgr;
@Inject
VmwareManager _vmwareMgr;
@Inject
VmwareManager _vmwareMgr;
@Inject
ClusterDetailsDao _clusterDetailsDao;
@Inject
@ -63,126 +60,129 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
@Inject
PortProfileDao _ppDao;
private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class);
@DB
//public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, ServerResource resource, String vsmName) {
public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, String vCenterIpaddr, String vCenterDcName) {
// In this function, we associate this VSM with each host
// in the clusterId specified.
// In this function, we associate this VSM with each host
// in the clusterId specified.
// First check if the cluster is of type vmware. If not,
// throw an exception. VSMs are tightly integrated with vmware clusters.
ClusterVO cluster = _clusterDao.findById(clusterId);
if (cluster == null) {
throw new InvalidParameterValueException("Cluster with specified ID not found!");
}
if (cluster.getHypervisorType() != HypervisorType.VMware) {
InvalidParameterValueException ex = new InvalidParameterValueException("Cluster with specified id is not a VMWare hypervisor cluster");
throw ex;
}
// First check if the cluster is of type vmware. If not,
// throw an exception. VSMs are tightly integrated with vmware clusters.
// Next, check if the cluster already has a VSM associated with it.
// If so, throw an exception disallowing this operation. The user must first
// delete the current VSM and then only attempt to add the new one.
if (_clusterVSMDao.findByClusterId(clusterId) != null) {
// We can't have two VSMs for the same cluster. Throw exception.
throw new InvalidParameterValueException("Cluster with specified id already has a VSM tied to it. Please remove that first and retry the operation.");
}
ClusterVO cluster = _clusterDao.findById(clusterId);
if (cluster == null) {
throw new InvalidParameterValueException("Cluster could not be found by id", null);
}
if (cluster.getHypervisorType() != HypervisorType.VMware) {
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(cluster, clusterId, "clusterId"));
throw new InvalidParameterValueException("Cluster with specified id is not a VMWare hypervisor cluster", idList);
}
// TODO: Confirm whether we should be checking for VSM reachability here.
// Next, check if this VSM is reachable. Use the XML-RPC VSM API Java bindings to talk to
// the VSM.
//NetconfHelper (String ip, String username, String password)
// Next, check if the cluster already has a VSM associated with it.
// If so, throw an exception disallowing this operation. The user must first
// delete the current VSM and then only attempt to add the new one.
NetconfHelper netconfClient;
try {
netconfClient = new NetconfHelper(ipaddress, username, password);
} catch(CloudRuntimeException e) {
String msg = "Failed to connect to Nexus VSM " + ipaddress + " with credentials of user " + username;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
if (_clusterVSMDao.findByClusterId(clusterId) != null) {
// We can't have two VSMs for the same cluster. Throw exception.
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(cluster, clusterId, "clusterId"));
throw new InvalidParameterValueException("Cluster with specified id already has a VSM tied to it. Please remove that first and retry the operation.", idList);
}
// Disconnect from the VSM. A VSM has a default of 8 maximum parallel connections that it allows.
netconfClient.disconnect();
// TODO: Confirm whether we should be checking for VSM reachability here.
// Now, go ahead and associate the cluster with this VSM.
// First, check if VSM already exists in the table "virtual_supervisor_module".
// If it's not there already, create it.
// If it's there already, return success.
// TODO - Right now, we only check if the ipaddress matches for both requests.
// We must really check whether every field of the VSM matches. Anyway, the
// advantage of our approach for now is that existing infrastructure using
// the existing VSM won't be affected if the new request to add the VSM
// assumed different information on the VSM (mgmt vlan, username, password etc).
CiscoNexusVSMDeviceVO VSMObj;
try {
VSMObj = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress);
} catch (Exception e) {
throw new CloudRuntimeException(e.getMessage());
}
// Next, check if this VSM is reachable. Use the XML-RPC VSM API Java bindings to talk to
// the VSM.
//NetconfHelper (String ip, String username, String password)
NetconfHelper netconfClient;
try {
netconfClient = new NetconfHelper(ipaddress, username, password);
} catch(CloudRuntimeException e) {
String msg = "Failed to connect to Nexus VSM " + ipaddress + " with credentials of user " + username;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
// Disconnect from the VSM. A VSM has a default of 8 maximum parallel connections that it allows.
netconfClient.disconnect();
// Now, go ahead and associate the cluster with this VSM.
// First, check if VSM already exists in the table "virtual_supervisor_module".
// If it's not there already, create it.
// If it's there already, return success.
// TODO - Right now, we only check if the ipaddress matches for both requests.
// We must really check whether every field of the VSM matches. Anyway, the
// advantage of our approach for now is that existing infrastructure using
// the existing VSM won't be affected if the new request to add the VSM
// assumed different information on the VSM (mgmt vlan, username, password etc).
CiscoNexusVSMDeviceVO VSMObj;
try {
VSMObj = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress);
} catch (Exception e) {
throw new CloudRuntimeException(e.getMessage());
}
if (VSMObj == null) {
// Create the VSM record. For now, we aren't using the vsmName field.
VSMObj = new CiscoNexusVSMDeviceVO(ipaddress, username, password);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(VSMObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
// At this stage, we have a VSM record for sure. Connect the VSM to the cluster Id.
long vsmId = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress).getId();
ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsmId);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_clusterVSMDao.persist(connectorObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
// Now, get a list of all the ESXi servers in this cluster.
// This is effectively a select * from host where cluster_id=clusterId;
// All ESXi servers are stored in the host table, and their resource
// type is vmwareresource.
if (VSMObj == null) {
// Create the VSM record. For now, we aren't using the vsmName field.
VSMObj = new CiscoNexusVSMDeviceVO(ipaddress, username, password);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(VSMObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
// At this stage, we have a VSM record for sure. Connect the VSM to the cluster Id.
long vsmId = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress).getId();
ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsmId);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_clusterVSMDao.persist(connectorObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
// Now, get a list of all the ESXi servers in this cluster.
// This is effectively a select * from host where cluster_id=clusterId;
// All ESXi servers are stored in the host table, and their resource
// type is vmwareresource.
//List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
//TODO: Activate the code below if we make the Nexus VSM a separate resource.
// Iterate through each of the hosts in this list. Each host has a host id.
// Given this host id, we can reconfigure the in-memory resource representing
// the host via the agent manager. Thus we inject VSM related information
// into each host's resource. Also, we first configure each resource's
// entries in the database to contain this VSM information before the injection.
//for (HostVO host : hosts) {
// Create a host details VO object and write it out for this hostid.
//Long hostid = new Long(vsmId);
//DetailVO vsmDetail = new DetailVO(host.getId(), "vsmId", hostid.toString());
//Transaction tx = Transaction.currentTxn();
//try {
//tx.start();
//_hostDetailDao.persist(vsmDetail);
//tx.commit();
//} catch (Exception e) {
//tx.rollback();
//throw new CloudRuntimeException(e.getMessage());
//}
// Create a host details VO object and write it out for this hostid.
//Long hostid = new Long(vsmId);
//DetailVO vsmDetail = new DetailVO(host.getId(), "vsmId", hostid.toString());
//Transaction tx = Transaction.currentTxn();
//try {
//tx.start();
//_hostDetailDao.persist(vsmDetail);
//tx.commit();
//} catch (Exception e) {
//tx.rollback();
//throw new CloudRuntimeException(e.getMessage());
//}
//}
// Reconfigure the resource.
//Map hostDetails = new HashMap<String, String>();
@ -191,40 +191,40 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
//hostDetails.put(ApiConstants.USERNAME, username);
//hostDetails.put(ApiConstants.PASSWORD, password);
//_agentMrg.send(host.getId(), )
return VSMObj;
}
@DB
public boolean deleteCiscoNexusVSM(long vsmId) throws ResourceInUseException {
CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId);
if (cisconexusvsm == null) {
// This entry is already not present. Return success.
return true;
// This entry is already not present. Return success.
return true;
}
// First, check whether this VSM is part of any non-empty cluster.
// Search ClusterVSMMap's table for a list of clusters using this vsmId.
List<ClusterVSMMapVO> clusterList = _clusterVSMDao.listByVSMId(vsmId);
if (clusterList != null) {
for (ClusterVSMMapVO record : clusterList) {
// If this cluster id has any hosts in it, fail this operation.
Long clusterId = record.getClusterId();
List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
if (hosts != null && hosts.size() > 0) {
for (Host host: hosts) {
if (host.getType() == Host.Type.Routing) {
s_logger.info("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
throw new ResourceInUseException("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
}
}
}
}
for (ClusterVSMMapVO record : clusterList) {
// If this cluster id has any hosts in it, fail this operation.
Long clusterId = record.getClusterId();
List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
if (hosts != null && hosts.size() > 0) {
for (Host host: hosts) {
if (host.getType() == Host.Type.Routing) {
s_logger.info("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
throw new ResourceInUseException("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
}
}
}
}
}
// Iterate through the cluster list again, this time, delete the VSM.
Transaction txn = Transaction.currentTxn();
try {
@ -237,8 +237,8 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
// to notify any resources or remove host details.
txn.commit();
} catch (Exception e) {
s_logger.info("Caught exception when trying to delete VSM record.." + e.getMessage());
throw new CloudRuntimeException("Failed to delete VSM");
s_logger.info("Caught exception when trying to delete VSM record.." + e.getMessage());
throw new CloudRuntimeException("Failed to delete VSM");
}
return true;
}
@ -247,67 +247,67 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
public CiscoNexusVSMDeviceVO enableCiscoNexusVSM(long vsmId) {
CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId);
if (cisconexusvsm == null) {
throw new InvalidParameterValueException("Invalid vsm Id specified");
throw new InvalidParameterValueException("Invalid vsm Id specified", null);
}
// Else, check if this db record shows that this VSM is enabled or not.
if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled) {
// it's currently disabled. So change it to enabled and write it out to the db.
cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(cisconexusvsm);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
// it's currently disabled. So change it to enabled and write it out to the db.
cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(cisconexusvsm);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
return cisconexusvsm;
}
@DB
public CiscoNexusVSMDeviceVO disableCiscoNexusVSM(long vsmId) {
CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId);
if (cisconexusvsm == null) {
throw new InvalidParameterValueException("Invalid vsm Id specified");
throw new InvalidParameterValueException("Invalid vsm Id specified", null);
}
// Else, check if this db record shows that this VSM is enabled or not.
if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled) {
// it's currently disabled. So change it to enabled and write it out to the db.
cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(cisconexusvsm);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
// it's currently disabled. So change it to enabled and write it out to the db.
cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(cisconexusvsm);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
return cisconexusvsm;
}
@DB
public CiscoNexusVSMDeviceVO getCiscoVSMbyVSMId(long vsmId) {
return _ciscoNexusVSMDeviceDao.findById(vsmId);
return _ciscoNexusVSMDeviceDao.findById(vsmId);
}
@DB
public CiscoNexusVSMDeviceVO getCiscoVSMbyClusId(long clusterId) {
ClusterVSMMapVO mapVO = _clusterVSMDao.findByClusterId(clusterId);
if (mapVO == null) {
s_logger.info("Couldn't find a VSM associated with the specified cluster Id");
return null;
}
// Else, pull out the VSM associated with the VSM id in mapVO.
CiscoNexusVSMDeviceVO result = _ciscoNexusVSMDeviceDao.findById(mapVO.getVsmId());
return result;
ClusterVSMMapVO mapVO = _clusterVSMDao.findByClusterId(clusterId);
if (mapVO == null) {
s_logger.info("Couldn't find a VSM associated with the specified cluster Id");
return null;
}
// Else, pull out the VSM associated with the VSM id in mapVO.
CiscoNexusVSMDeviceVO result = _ciscoNexusVSMDeviceDao.findById(mapVO.getVsmId());
return result;
}
public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
// TODO Auto-generated method stub
return null;

View File

@ -26,7 +26,6 @@ import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupExternalFirewallCommand;
import com.cloud.agent.api.StartupExternalLoadBalancerCommand;
import com.cloud.agent.api.routing.IpAssocCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand;
@ -55,10 +54,7 @@ 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.ExternalFirewallDeviceVO.FirewallDeviceState;
import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Service;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.ExternalFirewallDeviceDao;
import com.cloud.network.dao.IPAddressDao;
@ -151,12 +147,12 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null) ) {
throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," +
" server resource, zone id/physical network id) is not specified or a valid parameter.");
" server resource, zone id/physical network id) is not specified or a valid parameter.", null);
}
pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (pNetwork == null) {
throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
throw new InvalidParameterValueException("Could not find phyical network by ID", null);
}
zoneId = pNetwork.getDataCenterId();
@ -174,7 +170,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
uri = new URI(url);
} catch (Exception e) {
s_logger.debug(e);
throw new InvalidParameterValueException(e.getMessage());
throw new InvalidParameterValueException(e.getMessage(), null);
}
String ipAddress = uri.getHost();
@ -205,7 +201,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
txn.start();
boolean dedicatedUse = (configParams.get(ApiConstants.FIREWALL_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.FIREWALL_DEVICE_DEDICATED)) : false;
long capacity = NumbersUtil.parseLong((String)configParams.get(ApiConstants.FIREWALL_DEVICE_CAPACITY), 0);
long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.FIREWALL_DEVICE_CAPACITY), 0);
if (capacity == 0) {
capacity = _defaultFwCapacity;
}
@ -229,7 +225,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
public boolean deleteExternalFirewall(Long hostId) {
HostVO externalFirewall = _hostDao.findById(hostId);
if (externalFirewall == null) {
throw new InvalidParameterValueException("Could not find an external firewall with ID: " + hostId);
throw new InvalidParameterValueException("Could not find an external firewall by ID", null);
}
try {
@ -252,11 +248,11 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (pNetwork == null) {
throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
throw new InvalidParameterValueException("Could not find phyical network by ID", null);
}
if ((pNetwork == null) || (fwNetworkDevice == null)) {
throw new InvalidParameterValueException("Atleast one of ther required parameter physical networkId, device name is missing or invalid.");
throw new InvalidParameterValueException("Atleast one of ther required parameter physical networkId, device name is missing or invalid.", null);
}
PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), fwNetworkDevice.getNetworkServiceProvder());
@ -270,7 +266,8 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
}
return firewallHosts;
}
@Override
public ExternalFirewallDeviceVO getExternalFirewallForNetwork(Network network) {
NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId());
if (fwDeviceForNetwork != null) {
@ -366,17 +363,17 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
if (fwDeviceVO == null) {
s_logger.warn("Network shutdown requested on external firewall element, which did not implement the network." +
" Either network implement failed half way through or already network shutdown is completed.");
" Either network implement failed half way through or already network shutdown is completed.");
return true;
}
externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
}
Account account = _accountDao.findByIdIncludingRemoved(network.getAccountId());
NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
boolean sharedSourceNat = offering.getSharedSourceNat();
IPAddressVO sourceNatIp = null;
if (!sharedSourceNat) {
// Get the source NAT IP address for this account
@ -385,7 +382,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if (sourceNatIps.size() != 1) {
String errorMsg = "External firewall was unable to find the source NAT IP address for account "
+ account.getAccountName();
+ account.getAccountName();
s_logger.error(errorMsg);
return true;
} else {
@ -431,18 +428,18 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
// Insert a new NIC for this guest network to reserve the gateway address
savePlaceholderNic(network, network.getGateway());
}
// Delete any mappings used for inline external load balancers in this network
List<NicVO> nicsInNetwork = _nicDao.listByNetworkId(network.getId());
for (NicVO nic : nicsInNetwork) {
InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByNicId(nic.getId());
if (mapping != null) {
_nicDao.expunge(mapping.getNicId());
_inlineLoadBalancerNicMapDao.expunge(mapping.getId());
}
}
String action = add ? "implemented" : "shut down";
s_logger.debug("External firewall has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag);
@ -527,39 +524,39 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if (externalFirewall == null) {
return false;
}
// Create/delete VPN
IpAddress ip = _networkMgr.getIp(vpn.getServerAddressId());
// Mask the IP range with the network's VLAN tag
String[] ipRange = vpn.getIpRange().split("-");
DataCenterVO zone = _dcDao.findById(network.getDataCenterId());
int vlanTag = Integer.parseInt(network.getBroadcastUri().getHost());
int offset = getVlanOffset(network.getPhysicalNetworkId(), vlanTag);
int cidrSize = getGloballyConfiguredCidrSize();
for (int i = 0; i < 2; i++) {
ipRange[i] = NetUtils.long2Ip((NetUtils.ip2Long(ipRange[i]) & 0xff000000) | (offset << (32 - cidrSize)));
}
String maskedIpRange = ipRange[0] + "-" + ipRange[1];
RemoteAccessVpnCfgCommand createVpnCmd = new RemoteAccessVpnCfgCommand(create, ip.getAddress().addr(), vpn.getLocalIp(), maskedIpRange, vpn.getIpsecPresharedKey());
createVpnCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId()));
createVpnCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr());
Answer answer = _agentMgr.easySend(externalFirewall.getId(), createVpnCmd);
if (answer == null || !answer.getResult()) {
String details = (answer != null) ? answer.getDetails() : "details unavailable";
String msg = "External firewall was unable to create a remote access VPN in zone " + zone.getName() + " due to: " + details + ".";
s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId());
String details = (answer != null) ? answer.getDetails() : "details unavailable";
String msg = "External firewall was unable to create a remote access VPN in zone " + zone.getName() + " due to: " + details + ".";
s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId());
}
// Add/delete users
List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
return manageRemoteAccessVpnUsers(network, vpn, vpnUsers);
}
public boolean manageRemoteAccessVpnUsers(Network network, RemoteAccessVpn vpn, List<? extends VpnUser> vpnUsers) throws ResourceUnavailableException {
ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
@ -567,31 +564,31 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if (externalFirewall == null) {
return false;
}
List<VpnUser> addUsers = new ArrayList<VpnUser>();
List<VpnUser> removeUsers = new ArrayList<VpnUser>();
for (VpnUser user : vpnUsers) {
if (user.getState() == VpnUser.State.Add ||
user.getState() == VpnUser.State.Active) {
user.getState() == VpnUser.State.Active) {
addUsers.add(user);
} else if (user.getState() == VpnUser.State.Revoke) {
removeUsers.add(user);
}
}
VpnUsersCfgCommand addUsersCmd = new VpnUsersCfgCommand(addUsers, removeUsers);
addUsersCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId()));
addUsersCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr());
Answer answer = _agentMgr.easySend(externalFirewall.getId(), addUsersCmd);
if (answer == null || !answer.getResult()) {
String details = (answer != null) ? answer.getDetails() : "details unavailable";
DataCenterVO zone = _dcDao.findById(network.getDataCenterId());
String msg = "External firewall was unable to add remote access users in zone " + zone.getName() + " due to: " + details + ".";
s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId());
String details = (answer != null) ? answer.getDetails() : "details unavailable";
DataCenterVO zone = _dcDao.findById(network.getDataCenterId());
String msg = "External firewall was unable to add remote access users in zone " + zone.getName() + " due to: " + details + ".";
s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId());
}
return true;
}
@ -608,7 +605,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
int lowestVlanTag = Integer.valueOf(vlanRange[0]);
return vlanTag - lowestVlanTag;
}
private NicVO savePlaceholderNic(Network network, String ipAddress) {
NicVO nic = new NicVO(null, null, network.getId(), null);
nic.setIp4Address(ipAddress);
@ -616,7 +613,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
nic.setState(State.Reserved);
return _nicDao.persist(nic);
}
public int getGloballyConfiguredCidrSize() {
try {
String globalVlanBits = _configDao.getValue(Config.GuestVlanBits.key());

View File

@ -76,7 +76,6 @@ import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmGroup;
import com.cloud.network.lb.LoadBalancingRule.LbDestination;
import com.cloud.network.resource.CreateLoadBalancerApplianceAnswer;
import com.cloud.network.resource.DestroyLoadBalancerApplianceAnswer;
@ -184,12 +183,12 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) {
throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," +
" server resource, zone id/physical network id) is not specified or a valid parameter.");
" server resource, zone id/physical network id) is not specified or a valid parameter.", null);
}
pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (pNetwork == null) {
throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
throw new InvalidParameterValueException("Could not find phyical network by ID", null);
}
zoneId = pNetwork.getDataCenterId();
@ -207,7 +206,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
uri = new URI(url);
} catch (Exception e) {
s_logger.debug(e);
throw new InvalidParameterValueException(e.getMessage());
throw new InvalidParameterValueException(e.getMessage(), null);
}
String ipAddress = uri.getHost();
@ -236,7 +235,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false;
boolean inline = (configParams.get(ApiConstants.INLINE) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.INLINE)) : false;
long capacity = NumbersUtil.parseLong((String) configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0);
long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0);
if (capacity == 0) {
capacity = _defaultLbCapacity;
}
@ -264,7 +263,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
public boolean deleteExternalLoadBalancer(long hostId) {
HostVO externalLoadBalancer = _hostDao.findById(hostId);
if (externalLoadBalancer == null) {
throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId);
throw new InvalidParameterValueException("Could not find an external load balancer by ID", null);
}
DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID);
@ -314,7 +313,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if ((pNetwork == null) || (lbNetworkDevice == null)) {
throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid.");
throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid.", null);
}
PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(),

View File

@ -537,12 +537,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return ipToReturn;
}
@Override
public PublicIp assignVpnGatewayIpAddress(long dcId, Account owner, long vpcId) throws InsufficientAddressCapacityException, ConcurrentOperationException {
return assignDedicateIpAddress(owner, null, vpcId, dcId, false);
}
@DB
public PublicIp assignDedicateIpAddress(Account owner, Long guestNtwkId, Long vpcId, long dcId, boolean isSourceNat)
@ -1143,7 +1143,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@Override
public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId, boolean releaseOnFailure)
throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException {
InsufficientAddressCapacityException, ConcurrentOperationException {
Account caller = UserContext.current().getCaller();
Account owner = null;
@ -1467,7 +1467,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
offering.setState(NetworkOffering.State.Enabled);
_networkOfferingDao.update(offering.getId(), offering);
}
if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB) == null) {
//remove LB service
defaultVPCOffProviders.remove(Service.Lb);
@ -2282,7 +2282,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@Override
public void releaseNic(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, Nic nic)
throws ConcurrentOperationException, ResourceUnavailableException {
NicVO nicVO = _nicDao.findById(nic.getId());
releaseNic(vmProfile, nicVO);
}
@ -2356,7 +2356,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (broadcastUri != null) {
nic = _nicDao.findByNetworkIdInstanceIdAndBroadcastUri(networkId, vm.getId(), broadcastUri);
} else {
nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId());
nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId());
}
NetworkVO network = _networksDao.findById(networkId);
Integer networkRate = getNetworkRate(network.getId(), vm.getId());
@ -3189,7 +3189,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
Filter searchFilter = new Filter(NetworkVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<NetworkVO> sb = _networksDao.createSearchBuilder();
if (forVpc != null) {
if (forVpc) {
sb.and("vpc", sb.entity().getVpcId(), Op.NNULL);
@ -4260,14 +4260,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
long physicalNetworkId = findPhysicalNetworkId(zoneId, requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType());
// Validate physical network
PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags());
throw new InvalidParameterValueException("Unable to find physical network by id, with tag: " +requiredOfferings.get(0).getTags(), null);
}
s_logger.debug("Creating network for account " + owner + " from the network offering id=" +
requiredOfferings.get(0).getId() + " as a part of createVlanIpRange process");
guestNetwork = createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network"
@ -5301,7 +5301,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
txn.start();
// Create the new physical network in the database
long id = _physicalNetworkDao.getNextInSequence(Long.class, "id");
PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRange, name);
pNetwork.setTags(tags);
pNetwork.setIsolationMethods(isolationMethods);
@ -6954,7 +6954,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (networkId == null) {
networkId = userIp.getAssociatedWithNetworkId();
}
NetworkVO network = _networksDao.findById(networkId);
NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
if (offering.getGuestType() != GuestType.Isolated) {
@ -7212,7 +7212,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (network.getVpcId() != null) {
throw new InvalidParameterValueException("Can't assign ip to the network directly when network belongs" +
" to VPC.Specify vpcId to associate ip address to VPC", null);
" to VPC.Specify vpcId to associate ip address to VPC", null);
}
return associateIPToGuestNetwork(ipId, networkId, true);
}
@ -7244,11 +7244,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (ipUsedInVpc(ip)) {
return;
}
if (ip == null || ip.getVpcId() == null) {
return;
}
s_logger.debug("Releasing VPC ip address " + ip + " from vpc network id=" + networkId);
long vpcId = ip.getVpcId();
@ -7389,41 +7389,41 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
return true;
}
@Override
public NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context,
VirtualMachineProfileImpl<VMInstanceVO> vmProfile, boolean prepare)
throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException,
ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException,
ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
VirtualMachine vm = vmProfile.getVirtualMachine();
NetworkVO networkVO = _networksDao.findById(network.getId());
DataCenter dc = _configMgr.getZone(network.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
DeployDestination dest = new DeployDestination(dc, null, null, host);
NicProfile nic = getNicProfileForVm(network, requested, vm);
//1) allocate nic (if needed)
if (nic == null) {
int deviceId = _nicDao.countNics(vm.getId());
nic = allocateNic(requested, network, false,
deviceId, vmProfile).first();
if (nic == null) {
throw new CloudRuntimeException("Failed to allocate nic for vm " + vm + " in network " + network);
}
s_logger.debug("Nic is allocated successfully for vm " + vm + " in network " + network);
}
//2) prepare nic
if (prepare) {
nic = prepareNic(vmProfile, dest, context, nic.getId(), networkVO);
s_logger.debug("Nic is prepared successfully for vm " + vm + " in network " + network);
}
return nic;
}
@ -7446,5 +7446,5 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
return nic;
}
}

View File

@ -101,7 +101,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
@Inject HostDetailsDao _detailsDao;
@Inject AccountManager _accountMgr;
@Inject NetworkDao _networksDao = null;
@Inject ResourceManager _resourceMgr;
@Inject ResourceManager _resourceMgr;
ScheduledExecutorService _executor;
int _networkStatsInterval;
String _TSinclZones;
@ -116,7 +116,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
DataCenterVO zone = _dcDao.findById(zoneId);
String zoneName;
if (zone == null) {
throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
throw new InvalidParameterValueException("Could not find zone by ID", null);
} else {
zoneName = zone.getName();
}
@ -124,7 +124,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
List<HostVO> trafficMonitorsInZone = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.TrafficMonitor, zoneId);
if (trafficMonitorsInZone.size() != 0) {
throw new InvalidParameterValueException("Already added an traffic monitor in zone: " + zoneName);
throw new InvalidParameterValueException("Already added an traffic monitor in zone: " + zoneName, null);
}
URI uri;
@ -132,7 +132,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
uri = new URI(cmd.getUrl());
} catch (Exception e) {
s_logger.debug(e);
throw new InvalidParameterValueException(e.getMessage());
throw new InvalidParameterValueException(e.getMessage(), null);
}
String ipAddress = uri.getHost();
@ -161,13 +161,13 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
hostDetails.put("url", cmd.getUrl());
hostDetails.put("last_collection", ""+System.currentTimeMillis());
if(cmd.getInclZones() != null){
hostDetails.put("inclZones", cmd.getInclZones());
hostDetails.put("inclZones", cmd.getInclZones());
}
if(cmd.getExclZones() != null){
hostDetails.put("exclZones", cmd.getExclZones());
hostDetails.put("exclZones", cmd.getExclZones());
}
Host trafficMonitor = _resourceMgr.addHost(zoneId, resource, Host.Type.TrafficMonitor, hostDetails);
return trafficMonitor;
}
@ -182,12 +182,12 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId());
HostVO trafficMonitor = _hostDao.findById(hostId);
if (trafficMonitor == null) {
throw new InvalidParameterValueException("Could not find an traffic monitor with ID: " + hostId);
throw new InvalidParameterValueException("Could not find an traffic monitor by ID", null);
}
try {
if (_resourceMgr.maintain(hostId) && _resourceMgr.deleteHost(hostId, false, false)) {
return true;
try {
if (_resourceMgr.maintain(hostId) && _resourceMgr.deleteHost(hostId, false, false)) {
return true;
} else {
return false;
}
@ -225,7 +225,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
networkJoin.and("guestType", networkJoin.entity().getGuestType(), Op.EQ);
AllocatedIpSearch.join("network", networkJoin, AllocatedIpSearch.entity().getSourceNetworkId(), networkJoin.entity().getId(), JoinBuilder.JoinType.INNER);
AllocatedIpSearch.done();
_networkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.DirectNetworkStatsInterval.key()), 86400);
_TSinclZones = _configDao.getValue(Config.TrafficSentinelIncludeZones.key());
_TSexclZones = _configDao.getValue(Config.TrafficSentinelExcludeZones.key());
@ -241,7 +241,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
@Override
public boolean stop() {
_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
return true;
}
@ -262,7 +262,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
private int _interval;
private long mgmtSrvrId = MacAddress.getMacAddress().toLong();
private final long mgmtSrvrId = MacAddress.getMacAddress().toLong();
protected DirectNetworkStatsListener(int interval) {
_interval = interval;
@ -324,7 +324,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
rightNow.add(Calendar.HOUR_OF_DAY, -2);
Date now = rightNow.getTime();
if(lastCollection.after(now)){
s_logger.debug("Current time is less than 2 hours after last collection time : " + lastCollection.toString() + ". Skipping direct network usage collection");
return false;
@ -376,7 +376,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
}
List<UserStatisticsVO> collectedStats = new ArrayList<UserStatisticsVO>();
//Get usage for Ips which were assigned for the entire duration
if(fullDurationIpUsage.size() > 0){
DirectNetworkUsageCommand cmd = new DirectNetworkUsageCommand(IpList, lastCollection, now, _TSinclZones, _TSexclZones);
@ -441,8 +441,8 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
}
if(collectedStats.size() == 0){
s_logger.debug("No new direct network stats. No need to persist");
return false;
s_logger.debug("No new direct network stats. No need to persist");
return false;
}
//Persist all the stats and last_collection time in a single transaction
Transaction txn = Transaction.open(Transaction.CLOUD_DB);
@ -496,9 +496,9 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
s_logger.debug("Sending RecurringNetworkUsageCommand to " + agentId);
RecurringNetworkUsageCommand watch = new RecurringNetworkUsageCommand(_interval);
try {
_agentMgr.send(agentId, new Commands(watch), this);
_agentMgr.send(agentId, new Commands(watch), this);
} catch (AgentUnavailableException e) {
s_logger.debug("Can not process connect for host " + agentId, e);
s_logger.debug("Can not process connect for host " + agentId, e);
}
}
return;
@ -516,34 +516,34 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
protected DirectNetworkStatsListener() {
}
}
@Override
@Override
public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
// TODO Auto-generated method stub
return null;
// TODO Auto-generated method stub
return null;
}
@Override
@Override
public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map<String, String> details,
List<String> hostTags) {
if (!(startup[0] instanceof StartupTrafficMonitorCommand)) {
return null;
}
host.setType(Host.Type.TrafficMonitor);
return host;
}
@Override
@Override
public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException {
if(host.getType() != Host.Type.TrafficMonitor){
return null;
}
return new DeleteHostAnswer(true);
if(host.getType() != Host.Type.TrafficMonitor){
return null;
}
return new DeleteHostAnswer(true);
}
}

View File

@ -15,107 +15,107 @@ package com.cloud.network;
import org.apache.log4j.Logger;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.network.PortProfileVO.BindingType;
import com.cloud.network.PortProfileVO.PortType;
import com.cloud.network.dao.PortProfileDaoImpl;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
public class PortProfileManagerImpl {
private PortProfileDaoImpl _portProfileDao;
private final PortProfileDaoImpl _portProfileDao;
private static final org.apache.log4j.Logger s_logger = Logger.getLogger(PortProfileManagerImpl.class);
public PortProfileManagerImpl() {
_portProfileDao = new PortProfileDaoImpl();
_portProfileDao = new PortProfileDaoImpl();
}
@DB
public PortProfileVO addPortProfile(String portProfName, long vsmId, int vlanId, PortType pType, BindingType bType) {
// In this function, we create a port profile record in the port_profile table.
// First, check if a port profile with the given name already exists. If it does, throw an exception.
if (_portProfileDao.findByName(portProfName) != null) {
s_logger.info("Port Profile with specified name: " + portProfName + " already exists");
throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists");
}
// Check if the VSM id is a valid one.
// TODO: Should we also check whether a port profile for the specified vlanId already exists, and if so,
// fail this function? Do we want to enforce such a 1:1 mapping b/w port profile and vlanId?
// Else, go ahead and create the port profile.
PortProfileVO portProfileObj = new PortProfileVO(portProfName, vsmId, vlanId, pType, bType);
// In this function, we create a port profile record in the port_profile table.
// First, check if a port profile with the given name already exists. If it does, throw an exception.
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_portProfileDao.persist(portProfileObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
if (_portProfileDao.findByName(portProfName) != null) {
s_logger.info("Port Profile with specified name: " + portProfName + " already exists");
throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists", null);
}
// Check if the VSM id is a valid one.
// Return the PortProfileVO object created.
// TODO: Should we also check whether a port profile for the specified vlanId already exists, and if so,
// fail this function? Do we want to enforce such a 1:1 mapping b/w port profile and vlanId?
// Else, go ahead and create the port profile.
PortProfileVO portProfileObj = new PortProfileVO(portProfName, vsmId, vlanId, pType, bType);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_portProfileDao.persist(portProfileObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
// Return the PortProfileVO object created.
return portProfileObj;
}
@DB
public PortProfileVO addPortProfile(String portProfName, long vsmId, int lowVlanId, int highVlanId, PortType pType, BindingType bType) {
// In this function, we create a port profile record in the port_profile table.
// First, check if a port profile with the given name already exists. If it does, throw an exception.
PortProfileVO portProfileObj;
portProfileObj = _portProfileDao.findByName(portProfName);
if (portProfileObj != null) {
s_logger.info("Port Profile with specified name: " + portProfName + " already exists");
throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists");
}
// In this function, we create a port profile record in the port_profile table.
// Next, check if there is any existing port profile that uses a VLAN ID range that clashes with the
// range passed to this function. If so, throw an exception.
if (_portProfileDao.doesVlanRangeClash(lowVlanId, highVlanId) == true) {
s_logger.info("Port Profile's vlanId range clashes with an existing Port Profile's");
throw new InvalidParameterValueException("Port Profile's vlanId range clashes with an existing Port Profile's");
}
// Else, go ahead and create the port profile.
portProfileObj = new PortProfileVO(portProfName, vsmId, lowVlanId, highVlanId, pType, bType);
// First, check if a port profile with the given name already exists. If it does, throw an exception.
PortProfileVO portProfileObj;
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_portProfileDao.persist(portProfileObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
portProfileObj = _portProfileDao.findByName(portProfName);
// Return the PortProfileVO object created.
if (portProfileObj != null) {
s_logger.info("Port Profile with specified name: " + portProfName + " already exists");
throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists", null);
}
// Next, check if there is any existing port profile that uses a VLAN ID range that clashes with the
// range passed to this function. If so, throw an exception.
if (_portProfileDao.doesVlanRangeClash(lowVlanId, highVlanId) == true) {
s_logger.info("Port Profile's vlanId range clashes with an existing Port Profile's");
throw new InvalidParameterValueException("Port Profile's vlanId range clashes with an existing Port Profile's", null);
}
// Else, go ahead and create the port profile.
portProfileObj = new PortProfileVO(portProfName, vsmId, lowVlanId, highVlanId, pType, bType);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_portProfileDao.persist(portProfileObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
// Return the PortProfileVO object created.
return portProfileObj;
}
@DB
public boolean deletePortProfile(long portProfileId) {
PortProfileVO ppObj = _portProfileDao.findById(portProfileId);
if (ppObj == null) {
// This entry is already not present. Return success.
return true;
// This entry is already not present. Return success.
return true;
}
//Else, remove it.
// TODO: Should we be putting any checks here before removing
// the port profile record from the db?
Transaction txn = Transaction.currentTxn();
try {
txn.start();
@ -123,8 +123,8 @@ public class PortProfileManagerImpl {
_portProfileDao.remove(portProfileId);
txn.commit();
} catch (Exception e) {
s_logger.info("Caught exception when trying to delete Port Profile record.." + e.getMessage());
throw new CloudRuntimeException("Failed to delete Port Profile");
s_logger.info("Caught exception when trying to delete Port Profile record.." + e.getMessage());
throw new CloudRuntimeException("Failed to delete Port Profile");
}
return true;
}

View File

@ -26,6 +26,7 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.cloud.exception.InvalidParameterValueException;
/**
@ -36,56 +37,56 @@ import com.cloud.exception.InvalidParameterValueException;
@Entity
@Table(name="port_profile")
public class PortProfileVO {
// We need to know what properties a VSM has. Put them here.
// We need to know what properties a VSM has. Put them here.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name="uuid")
private String uuid;
private final String uuid;
@Column(name = "port_profile_name")
private String portProfileName;
@Column(name = "port_mode")
private PortMode portMode;
@Column(name = "vsm_id")
private long vsmId;
@Column(name = "trunk_low_vlan_id")
private int lowVlanId;
@Column(name = "trunk_high_vlan_id")
private int highVlanId;
@Column(name = "access_vlan_id")
private int accessVlanId;
@Column(name = "port_type")
private PortType portType;
@Column(name = "port_binding")
private BindingType portBinding;
public enum BindingType {
Static,
Ephemeral
Static,
Ephemeral
}
public enum PortType {
Ethernet,
vEthernet
Ethernet,
vEthernet
}
// This tells us whether the port trunks multiple VLANs
// or carries traffic of a single VLAN.
public enum PortMode {
Access,
Trunk
Access,
Trunk
}
// Accessor methods
@ -98,79 +99,79 @@ public class PortProfileVO {
}
public String getPortProfileName() {
return portProfileName;
return portProfileName;
}
public PortMode getPortMode() {
return portMode;
return portMode;
}
public long getVsmId() {
return vsmId;
return vsmId;
}
public int getLowVlanId() {
return lowVlanId;
return lowVlanId;
}
public int getHighVlanId() {
return highVlanId;
return highVlanId;
}
public int getAccessVlanId() {
return accessVlanId;
return accessVlanId;
}
public PortType getPortType() {
return portType;
return portType;
}
public BindingType getPortBinding() {
return portBinding;
return portBinding;
}
// Setter methods
public void setPortProfileName(String name) {
portProfileName = name;
portProfileName = name;
}
public void setPortMode(PortMode mode) {
portMode = mode;
portMode = mode;
}
public void setVsmId(long id) {
vsmId = id;
vsmId = id;
}
public void setLowVlanId(int vlanId) {
lowVlanId = vlanId;
lowVlanId = vlanId;
}
public void setHighVlanId(int vlanId) {
highVlanId = vlanId;
highVlanId = vlanId;
}
public void setAccessVlanId(int vlanId) {
accessVlanId = vlanId;
accessVlanId = vlanId;
}
public void setPortType(PortType type) {
portType = type;
portType = type;
}
public void setPortBinding(BindingType bindingType) {
portBinding = bindingType;
portBinding = bindingType;
}
// Constructor methods.
public PortProfileVO(String portProfName, long vsmId, int vlanId, PortType pType, BindingType bType) {
// Set the relevant portprofile properties here.
// When supplied with a single vlanId, we set this portprofile as an access port profile.
this.setPortMode(PortMode.Access);
// Set the relevant portprofile properties here.
// When supplied with a single vlanId, we set this portprofile as an access port profile.
this.setPortMode(PortMode.Access);
this.uuid = UUID.randomUUID().toString();
this.setPortProfileName(portProfName);
this.setVsmId(vsmId);
@ -178,16 +179,16 @@ public class PortProfileVO {
this.setPortType(pType);
this.setPortBinding(bType);
}
public PortProfileVO(String portProfName, long vsmId, int lowVlanId, int highVlanId, PortType pType, BindingType bType) {
// Set the relevant portprofile properties here.
// When supplied with a vlan range, we set this portprofile as a trunk port profile.
if (lowVlanId >= highVlanId) {
throw new InvalidParameterValueException("Low Vlan Id cannot be greater than or equal to high Vlan Id");
}
this.setPortMode(PortMode.Trunk);
// Set the relevant portprofile properties here.
// When supplied with a vlan range, we set this portprofile as a trunk port profile.
if (lowVlanId >= highVlanId) {
throw new InvalidParameterValueException("Low Vlan Id cannot be greater than or equal to high Vlan Id", null);
}
this.setPortMode(PortMode.Trunk);
this.uuid = UUID.randomUUID().toString();
this.setPortProfileName(portProfName);
this.setVsmId(vsmId);
@ -196,7 +197,7 @@ public class PortProfileVO {
this.setPortType(pType);
this.setPortBinding(bType);
}
public PortProfileVO() {
this.uuid = UUID.randomUUID().toString();
}

View File

@ -5,6 +5,8 @@ import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@ -30,6 +32,7 @@ public class Site2SiteVpnConnectionVO implements Site2SiteVpnConnection {
private long customerGatewayId;
@Column(name="state")
@Enumerated(value=EnumType.STRING)
private State state;
@Column(name="domain_id")

View File

@ -12,370 +12,366 @@
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.commands.CreateStorageNetworkIpRangeCmd;
import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd;
import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd;
import com.cloud.api.commands.listStorageNetworkIpRangeCmd;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.StorageNetworkIpRange;
import com.cloud.dc.StorageNetworkIpAddressVO;
import com.cloud.dc.StorageNetworkIpRangeVO;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.StorageNetworkIpAddressDao;
import com.cloud.dc.dao.StorageNetworkIpRangeDao;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.host.HostVO;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchCriteria2;
import com.cloud.utils.db.SearchCriteriaService;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.SecondaryStorageVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.SecondaryStorageVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.commands.CreateStorageNetworkIpRangeCmd;
import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd;
import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd;
import com.cloud.api.commands.listStorageNetworkIpRangeCmd;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.StorageNetworkIpAddressVO;
import com.cloud.dc.StorageNetworkIpRange;
import com.cloud.dc.StorageNetworkIpRangeVO;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.StorageNetworkIpAddressDao;
import com.cloud.dc.dao.StorageNetworkIpRangeDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.SearchCriteria2;
import com.cloud.utils.db.SearchCriteriaService;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.SecondaryStorageVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.SecondaryStorageVmDao;
@Local(value = {StorageNetworkManager.class, StorageNetworkService.class})
public class StorageNetworkManagerImpl implements StorageNetworkManager, StorageNetworkService {
private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class);
String _name;
@Inject
StorageNetworkIpAddressDao _sNwIpDao;
@Inject
StorageNetworkIpRangeDao _sNwIpRangeDao;
private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class);
String _name;
@Inject
StorageNetworkIpAddressDao _sNwIpDao;
@Inject
StorageNetworkIpRangeDao _sNwIpRangeDao;
@Inject
NetworkDao _networkDao;
@Inject
HostPodDao _podDao;
@Inject
SecondaryStorageVmDao _ssvmDao;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
return true;
}
@Inject
HostPodDao _podDao;
@Inject
SecondaryStorageVmDao _ssvmDao;
@Override
public boolean start() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
return true;
}
@Override
public boolean stop() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean start() {
// TODO Auto-generated method stub
return true;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean stop() {
// TODO Auto-generated method stub
return true;
}
private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) {
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new CloudRuntimeException("Cannot find pod " + podId);
}
String[] IpRange = pod.getDescription().split("-");
if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) {
return;
}
if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) {
throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1]);
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) {
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new CloudRuntimeException("Cannot find pod " + podId);
}
}
private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) {
List<StorageNetworkIpRangeVO> curRanges = _sNwIpRangeDao.listByPodId(podId);
for (StorageNetworkIpRangeVO range : curRanges) {
if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) {
throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + range.getStartIp() + " - " + range.getEndIp());
}
}
}
private void createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException {
String[] IpRange = pod.getDescription().split("-");
if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) {
return;
}
if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) {
throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1], null);
}
}
private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) {
List<StorageNetworkIpRangeVO> curRanges = _sNwIpRangeDao.listByPodId(podId);
for (StorageNetworkIpRangeVO range : curRanges) {
if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) {
throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + range.getStartIp() + " - " + range.getEndIp(), null);
}
}
}
private void createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException {
long startIPLong = NetUtils.ip2Long(startIp);
long endIPLong = NetUtils.ip2Long(endIp);
String insertSql = "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)";
String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
PreparedStatement stmt = null;
Connection conn = txn.getConnection();
String insertSql = "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)";
String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
PreparedStatement stmt = null;
Connection conn = txn.getConnection();
while (startIPLong <= endIPLong) {
stmt = conn.prepareStatement(insertSql);
stmt.setLong(1, rangeId);
stmt.setString(2, NetUtils.long2Ip(startIPLong++));
stmt.setLong(3, zoneId);
stmt.setNull(4, java.sql.Types.DATE);
stmt = conn.prepareStatement(insertSql);
stmt.setLong(1, rangeId);
stmt.setString(2, NetUtils.long2Ip(startIPLong++));
stmt.setLong(3, zoneId);
stmt.setNull(4, java.sql.Types.DATE);
stmt.executeUpdate();
stmt.close();
stmt = txn.prepareStatement(updateSql);
stmt.setLong(1, zoneId);
stmt.executeUpdate();
stmt.close();
}
}
@Override
@DB
}
@Override
@DB
public StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd) {
Integer vlan = cmd.getVlan();
Long rangeId = cmd.getId();
String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp();
String netmask = cmd.getNetmask();
if (netmask != null && !NetUtils.isValidNetmask(netmask)) {
throw new CloudRuntimeException("Invalid netmask:" + netmask);
}
if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId));
}
StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
if (range == null) {
throw new CloudRuntimeException("Cannot find storage ip range " + rangeId);
}
if (startIp != null || endIp != null) {
long podId = range.getPodId();
startIp = startIp == null ? range.getStartIp() : startIp;
endIp = endIp == null ? range.getEndIp() : endIp;
checkOverlapPrivateIpRange(podId, startIp, endIp);
checkOverlapStorageIpRange(podId, startIp, endIp);
}
Transaction txn = Transaction.currentTxn();
txn.start();
try {
range = _sNwIpRangeDao.acquireInLockTable(range.getId());
if (range == null) {
throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId);
}
StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate();
if (vlan != null) {
vo.setVlan(vlan);
}
if (startIp != null) {
vo.setStartIp(startIp);
}
if (endIp != null) {
vo.setEndIp(endIp);
}
if (netmask != null) {
vo.setNetmask(netmask);
}
_sNwIpRangeDao.update(rangeId, vo);
} finally {
if (range != null) {
_sNwIpRangeDao.releaseFromLockTable(range.getId());
}
}
txn.commit();
return _sNwIpRangeDao.findById(rangeId);
Integer vlan = cmd.getVlan();
Long rangeId = cmd.getId();
String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp();
String netmask = cmd.getNetmask();
if (netmask != null && !NetUtils.isValidNetmask(netmask)) {
throw new CloudRuntimeException("Invalid netmask:" + netmask);
}
if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId));
}
StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
if (range == null) {
throw new CloudRuntimeException("Cannot find storage ip range " + rangeId);
}
if (startIp != null || endIp != null) {
long podId = range.getPodId();
startIp = startIp == null ? range.getStartIp() : startIp;
endIp = endIp == null ? range.getEndIp() : endIp;
checkOverlapPrivateIpRange(podId, startIp, endIp);
checkOverlapStorageIpRange(podId, startIp, endIp);
}
Transaction txn = Transaction.currentTxn();
txn.start();
try {
range = _sNwIpRangeDao.acquireInLockTable(range.getId());
if (range == null) {
throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId);
}
StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate();
if (vlan != null) {
vo.setVlan(vlan);
}
if (startIp != null) {
vo.setStartIp(startIp);
}
if (endIp != null) {
vo.setEndIp(endIp);
}
if (netmask != null) {
vo.setNetmask(netmask);
}
_sNwIpRangeDao.update(rangeId, vo);
} finally {
if (range != null) {
_sNwIpRangeDao.releaseFromLockTable(range.getId());
}
}
txn.commit();
return _sNwIpRangeDao.findById(rangeId);
}
@Override
@DB
public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException {
Long podId = cmd.getPodId();
String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp();
Integer vlan = cmd.getVlan();
String netmask = cmd.getNetmask();
if (endIp == null) {
endIp = startIp;
}
if (!NetUtils.isValidNetmask(netmask)) {
throw new CloudRuntimeException("Invalid netmask:" + netmask);
}
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new CloudRuntimeException("Cannot find pod " + podId);
}
Long zoneId = pod.getDataCenterId();
List<NetworkVO> nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage);
if (nws.size() == 0) {
throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId);
}
if (nws.size() > 1) {
throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found");
}
NetworkVO nw = nws.get(0);
checkOverlapPrivateIpRange(podId, startIp, endIp);
checkOverlapStorageIpRange(podId, startIp, endIp);
@Override
@DB
public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException {
Long podId = cmd.getPodId();
String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp();
Integer vlan = cmd.getVlan();
String netmask = cmd.getNetmask();
Transaction txn = Transaction.currentTxn();
StorageNetworkIpRangeVO range = null;
if (endIp == null) {
endIp = startIp;
}
txn.start();
range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay());
_sNwIpRangeDao.persist(range);
try {
createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId);
} catch (SQLException e) {
txn.rollback();
StringBuilder err = new StringBuilder();
err.append("Create storage network range failed.");
err.append("startIp=" + startIp);
err.append("endIp=" + endIp);
err.append("netmask=" + netmask);
err.append("zoneId=" + zoneId);
s_logger.debug(err.toString(), e);
throw e;
}
if (!NetUtils.isValidNetmask(netmask)) {
throw new CloudRuntimeException("Invalid netmask:" + netmask);
}
txn.commit();
return range;
}
private String getInUseIpAddress(long rangeId) {
List<String> ips = _sNwIpDao.listInUseIpByRangeId(rangeId);
StringBuilder res = new StringBuilder();
res.append("Below IP of range " + rangeId + " is still in use:");
for (String ip : ips) {
res.append(ip).append(",");
}
return res.toString();
}
@Override
@DB
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new CloudRuntimeException("Cannot find pod " + podId);
}
Long zoneId = pod.getDataCenterId();
List<NetworkVO> nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage);
if (nws.size() == 0) {
throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId);
}
if (nws.size() > 1) {
throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found");
}
NetworkVO nw = nws.get(0);
checkOverlapPrivateIpRange(podId, startIp, endIp);
checkOverlapStorageIpRange(podId, startIp, endIp);
Transaction txn = Transaction.currentTxn();
StorageNetworkIpRangeVO range = null;
txn.start();
range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay());
_sNwIpRangeDao.persist(range);
try {
createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId);
} catch (SQLException e) {
txn.rollback();
StringBuilder err = new StringBuilder();
err.append("Create storage network range failed.");
err.append("startIp=" + startIp);
err.append("endIp=" + endIp);
err.append("netmask=" + netmask);
err.append("zoneId=" + zoneId);
s_logger.debug(err.toString(), e);
throw e;
}
txn.commit();
return range;
}
private String getInUseIpAddress(long rangeId) {
List<String> ips = _sNwIpDao.listInUseIpByRangeId(rangeId);
StringBuilder res = new StringBuilder();
res.append("Below IP of range " + rangeId + " is still in use:");
for (String ip : ips) {
res.append(ip).append(",");
}
return res.toString();
}
@Override
@DB
public void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd) {
long rangeId = cmd.getId();
StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
if (range == null) {
throw new CloudRuntimeException("Can not find storage network ip range " + rangeId);
}
if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
throw new CloudRuntimeException(getInUseIpAddress(rangeId));
}
long rangeId = cmd.getId();
StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
if (range == null) {
throw new CloudRuntimeException("Can not find storage network ip range " + rangeId);
}
final Transaction txn = Transaction.currentTxn();
txn.start();
try {
range = _sNwIpRangeDao.acquireInLockTable(rangeId);
if (range == null) {
String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
/* entries in op_dc_storage_network_ip_address will be deleted automatically due to fk_storage_ip_address__range_id constraint key */
_sNwIpRangeDao.remove(rangeId);
} finally {
if (range != null) {
_sNwIpRangeDao.releaseFromLockTable(rangeId);
}
}
txn.commit();
}
@Override
if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
throw new CloudRuntimeException(getInUseIpAddress(rangeId));
}
final Transaction txn = Transaction.currentTxn();
txn.start();
try {
range = _sNwIpRangeDao.acquireInLockTable(rangeId);
if (range == null) {
String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
/* entries in op_dc_storage_network_ip_address will be deleted automatically due to fk_storage_ip_address__range_id constraint key */
_sNwIpRangeDao.remove(rangeId);
} finally {
if (range != null) {
_sNwIpRangeDao.releaseFromLockTable(rangeId);
}
}
txn.commit();
}
@Override
public List<StorageNetworkIpRange> listIpRange(listStorageNetworkIpRangeCmd cmd) {
Long rangeId = cmd.getRangeId();
Long podId = cmd.getPodId();
Long zoneId = cmd.getZoneId();
List result = null;
if (rangeId != null) {
result = _sNwIpRangeDao.listByRangeId(rangeId);
} else if (podId != null) {
result = _sNwIpRangeDao.listByPodId(podId);
} else if (zoneId != null) {
result = _sNwIpRangeDao.listByDataCenterId(zoneId);
} else {
result = _sNwIpRangeDao.listAll();
}
return (List<StorageNetworkIpRange>)result;
}
Long rangeId = cmd.getRangeId();
Long podId = cmd.getPodId();
Long zoneId = cmd.getZoneId();
@Override
public void releaseIpAddress(String ip) {
_sNwIpDao.releaseIpAddress(ip);
}
@Override
List result = null;
if (rangeId != null) {
result = _sNwIpRangeDao.listByRangeId(rangeId);
} else if (podId != null) {
result = _sNwIpRangeDao.listByPodId(podId);
} else if (zoneId != null) {
result = _sNwIpRangeDao.listByDataCenterId(zoneId);
} else {
result = _sNwIpRangeDao.listAll();
}
return result;
}
@Override
public void releaseIpAddress(String ip) {
_sNwIpDao.releaseIpAddress(ip);
}
@Override
public StorageNetworkIpAddressVO acquireIpAddress(long podId) {
List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByPodId(podId);
for (StorageNetworkIpRangeVO r : ranges) {
try {
r = _sNwIpRangeDao.acquireInLockTable(r.getId());
if (r == null) {
String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId());
if (ip != null) {
return ip;
}
} finally {
if (r != null) {
_sNwIpRangeDao.releaseFromLockTable(r.getId());
}
}
}
return null;
List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByPodId(podId);
for (StorageNetworkIpRangeVO r : ranges) {
try {
r = _sNwIpRangeDao.acquireInLockTable(r.getId());
if (r == null) {
String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId());
if (ip != null) {
return ip;
}
} finally {
if (r != null) {
_sNwIpRangeDao.releaseFromLockTable(r.getId());
}
}
}
return null;
}
@Override
@Override
public boolean isStorageIpRangeAvailable(long zoneId) {
SearchCriteriaService<StorageNetworkIpRangeVO, StorageNetworkIpRangeVO> sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class);
sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId);
List<StorageNetworkIpRangeVO> entries = sc.list();
return entries.size() > 0;
SearchCriteriaService<StorageNetworkIpRangeVO, StorageNetworkIpRangeVO> sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class);
sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId);
List<StorageNetworkIpRangeVO> entries = sc.list();
return entries.size() > 0;
}
@Override
@Override
public List<SecondaryStorageVmVO> getSSVMWithNoStorageNetwork(long zoneId) {
List<SecondaryStorageVmVO> ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping);
return ssvms;
List<SecondaryStorageVmVO> ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping);
return ssvms;
}
@Override
@Override
public boolean isAnyStorageIpInUseInZone(long zoneId) {
List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByDataCenterId(zoneId);
for (StorageNetworkIpRangeVO r : ranges) {
if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) {
return true;
}
}
return false;
List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByDataCenterId(zoneId);
for (StorageNetworkIpRangeVO r : ranges) {
if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) {
return true;
}
}
return false;
}
}

View File

@ -76,6 +76,7 @@ import com.cloud.user.User;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
@ -172,7 +173,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
for (Counter counter : counters) {
if (!supportedCounters.contains(counter.getSource().name().toString())) {
throw new InvalidParameterException("AutoScale counter with source='" + counter.getSource() + "' is not supported " +
"in the network where lb is configured");
"in the network where lb is configured");
}
}
}
@ -183,7 +184,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
VO vo = dao.findById(id);
if (vo == null) {
throw new InvalidParameterValueException("Unable to find " + paramName);
throw new InvalidParameterValueException("Unable to find " + paramName, null);
}
_accountMgr.checkAccess(caller, null, false, (ControlledEntity) vo);
@ -215,25 +216,25 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
}
int duration = policy.getDuration();
if (duration < interval) {
throw new InvalidParameterValueException("duration : " + duration + " specified in a policy cannot be less than vm group's interval : " + interval);
throw new InvalidParameterValueException("duration : " + duration + " specified in a policy cannot be less than vm group's interval : " + interval, null);
}
if (quietTime < interval) {
throw new InvalidParameterValueException("quietTime : " + quietTime + " specified in a policy cannot be less than vm group's interval : " + interval);
throw new InvalidParameterValueException("quietTime : " + quietTime + " specified in a policy cannot be less than vm group's interval : " + interval, null);
}
if (quietTime != prevQuietTime) {
throw new InvalidParameterValueException("quietTime should be same for all the policies specified in " + paramName);
throw new InvalidParameterValueException("quietTime should be same for all the policies specified in " + paramName, null);
}
if (scaleUpPolicies) {
if (!isAutoScaleScaleUpPolicy(policy)) {
throw new InvalidParameterValueException("Only scaleup policies can be specified in scaleuppolicyids");
throw new InvalidParameterValueException("Only scaleup policies can be specified in scaleuppolicyids", null);
}
}
else {
if (isAutoScaleScaleUpPolicy(policy)) {
throw new InvalidParameterValueException("Only scaledown policies can be specified in scaledownpolicyids");
throw new InvalidParameterValueException("Only scaledown policies can be specified in scaledownpolicyids", null);
}
}
List<AutoScalePolicyConditionMapVO> policyConditionMapVOs = _autoScalePolicyConditionMapDao.listByAll(policy.getId(), null);
@ -255,16 +256,16 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
VirtualMachineTemplate template = _templateMgr.getTemplate(templateId);
// Make sure a valid template ID was specified
if (template == null) {
throw new InvalidParameterValueException("Unable to use the given template.");
throw new InvalidParameterValueException("Unable to use the given template.", null);
}
if (destroyVmGraceperiod < 0) {
throw new InvalidParameterValueException("Destroy Vm Grace Period cannot be less than 0.");
throw new InvalidParameterValueException("Destroy Vm Grace Period cannot be less than 0.", null);
}
User user = _userDao.findById(autoscaleUserId);
if (user.getAccountId() != vmProfile.getAccountId()) {
throw new InvalidParameterValueException("AutoScale User id does not belong to the same account");
throw new InvalidParameterValueException("AutoScale User id does not belong to the same account", null);
}
String apiKey = user.getApiKey();
@ -272,15 +273,15 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
String csUrl = _configDao.getValue(Config.EndpointeUrl.key());
if(apiKey == null) {
throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it");
throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it", null);
}
if(secretKey == null) {
throw new InvalidParameterValueException("secretKey for user: " + user.getUsername() + " is empty. Please generate it");
throw new InvalidParameterValueException("secretKey for user: " + user.getUsername() + " is empty. Please generate it", null);
}
if(csUrl == null || csUrl.contains("localhost")) {
throw new InvalidParameterValueException("Global setting endpointe.url has to be set to the Management Server's API end point");
throw new InvalidParameterValueException("Global setting endpointe.url has to be set to the Management Server's API end point", null);
}
vmProfile = _autoScaleVmProfileDao.persist(vmProfile);
@ -303,12 +304,12 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
DataCenter zone = _configMgr.getZone(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find zone by id=" + zoneId);
throw new InvalidParameterValueException("Unable to find zone by id", null);
}
ServiceOffering serviceOffering = _configMgr.getServiceOffering(serviceOfferingId);
if (serviceOffering == null) {
throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId);
throw new InvalidParameterValueException("Unable to find service offering by id", null);
}
// validations
@ -368,7 +369,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
List<AutoScaleVmGroupVO> vmGroupList = _autoScaleVmGroupDao.listByAll(null, profileId);
for (AutoScaleVmGroupVO vmGroupVO : vmGroupList) {
if (vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) {
throw new InvalidParameterValueException("The AutoScale Vm Profile can be updated only if the Vm Group it is associated with is disabled in state");
throw new InvalidParameterValueException("The AutoScale Vm Profile can be updated only if the Vm Group it is associated with is disabled in state", null);
}
}
@ -384,7 +385,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
/* Check if entity is in database */
getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Profile", id, _autoScaleVmProfileDao);
if (_autoScaleVmGroupDao.isProfileInUse(id)) {
throw new InvalidParameterValueException("Cannot delete AutoScale Vm Profile when it is in use by one more vm groups");
throw new InvalidParameterValueException("Cannot delete AutoScale Vm Profile when it is in use by one more vm groups", null);
}
boolean success = _autoScaleVmProfileDao.remove(id);
if (success) {
@ -425,11 +426,11 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
int quietTime = autoScalePolicyVO.getQuietTime();
if (duration < 0) {
throw new InvalidParameterValueException("duration is an invalid value: " + duration);
throw new InvalidParameterValueException("duration is an invalid value: " + duration, null);
}
if (quietTime < 0) {
throw new InvalidParameterValueException("quiettime is an invalid value: " + quietTime);
throw new InvalidParameterValueException("quiettime is an invalid value: " + quietTime, null);
}
final Transaction txn = Transaction.currentTxn();
@ -452,13 +453,13 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
if (conditionIds.size() != conditions.size()) {
// TODO report the condition id which could not be found
throw new InvalidParameterValueException("Unable to find the condition specified");
throw new InvalidParameterValueException("Unable to find the condition specified", null);
}
ArrayList<Long> counterIds = new ArrayList<Long>();
for (ConditionVO condition : conditions) {
if (counterIds.contains(condition.getCounterid())) {
throw new InvalidParameterValueException("atleast two conditions in the conditionids have the same counter. It is not right to apply two different conditions for the same counter");
throw new InvalidParameterValueException("atleast two conditions in the conditionids have the same counter. It is not right to apply two different conditions for the same counter", null);
}
counterIds.add(condition.getCounterid());
}
@ -490,7 +491,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
action = action.toLowerCase();
if (!NetUtils.isValidAutoScaleAction(action)) {
throw new InvalidParameterValueException("action is invalid, only 'scaleup' and 'scaledown' is supported");
throw new InvalidParameterValueException("action is invalid, only 'scaleup' and 'scaledown' is supported", null);
}
AutoScalePolicyVO policyVO = new AutoScalePolicyVO(cmd.getDomainId(), cmd.getAccountId(), duration, quietTime, action);
@ -508,7 +509,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Policy", id, _autoScalePolicyDao);
if (_autoScaleVmGroupPolicyMapDao.isAutoScalePolicyInUse(id)) {
throw new InvalidParameterValueException("Cannot delete AutoScale Policy when it is in use by one or more AutoScale Vm Groups");
throw new InvalidParameterValueException("Cannot delete AutoScale Policy when it is in use by one or more AutoScale Vm Groups", null);
}
Transaction txn = Transaction.currentTxn();
@ -535,7 +536,9 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
Account caller = UserContext.current().getCaller();
Account owner = _accountDao.findActiveAccount(accountName, domainId);
if (owner == null) {
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy("domain", domainId, "domainId"));
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specifed domainId", idList);
}
_accountMgr.checkAccess(caller, null, false, owner);
}
@ -563,7 +566,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
Account caller = UserContext.current().getCaller();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
ListProjectResourcesCriteria>(domainId, isRecursive, null);
ListProjectResourcesCriteria>(domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject,
listAll, false);
domainId = domainIdRecursiveListProject.first();
@ -661,13 +664,13 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
}
if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) {
throw new InvalidParameterValueException("The AutoScale Policy can be updated only if the Vm Group it is associated with is disabled in state");
throw new InvalidParameterValueException("The AutoScale Policy can be updated only if the Vm Group it is associated with is disabled in state", null);
}
if (vmGroupVO.getInterval() < policy.getDuration()) {
throw new InvalidParameterValueException("duration is less than the associated AutoScaleVmGroup's interval");
throw new InvalidParameterValueException("duration is less than the associated AutoScaleVmGroup's interval", null);
}
if (vmGroupVO.getInterval() < policy.getQuietTime()) {
throw new InvalidParameterValueException("quietTime is less than the associated AutoScaleVmGroup's interval");
throw new InvalidParameterValueException("quietTime is less than the associated AutoScaleVmGroup's interval", null);
}
}
@ -692,11 +695,11 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
Long zoneId = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId()).getDataCenterId();
if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancer.getId())) {
throw new InvalidParameterValueException("an AutoScaleVmGroup is already attached to the lb rule, the existing vm group has to be first deleted");
throw new InvalidParameterValueException("an AutoScaleVmGroup is already attached to the lb rule, the existing vm group has to be first deleted", null);
}
if (_lb2VmMapDao.isVmAttachedToLoadBalancer(loadBalancer.getId())) {
throw new InvalidParameterValueException("there are Vms already bound to the specified LoadBalancing Rule. User bound Vms and AutoScaled Vm Group cannot co-exist on a Load Balancing Rule");
throw new InvalidParameterValueException("there are Vms already bound to the specified LoadBalancing Rule. User bound Vms and AutoScaled Vm Group cannot co-exist on a Load Balancing Rule", null);
}
AutoScaleVmGroupVO vmGroupVO = new AutoScaleVmGroupVO(cmd.getLbRuleId(), zoneId, loadBalancer.getDomainId(), loadBalancer.getAccountId(), minMembers, maxMembers,
@ -729,7 +732,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
}
// This should never happen, because today loadbalancerruleid is manadatory for AutoScaleVmGroup.
throw new InvalidParameterValueException("Only LoadBalancer based AutoScale is supported");
throw new InvalidParameterValueException("Only LoadBalancer based AutoScale is supported", null);
}
@Override
@ -829,19 +832,19 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
List<Long> policyIds = new ArrayList<Long>();
if (minMembers < 0) {
throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " is an invalid value: " + minMembers);
throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " is an invalid value: " + minMembers, null);
}
if (maxMembers < 0) {
throw new InvalidParameterValueException(ApiConstants.MAX_MEMBERS + " is an invalid value: " + minMembers);
throw new InvalidParameterValueException(ApiConstants.MAX_MEMBERS + " is an invalid value: " + minMembers, null);
}
if (minMembers > maxMembers) {
throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " (" + minMembers + ")cannot be greater than " + ApiConstants.MAX_MEMBERS + " (" + maxMembers + ")");
throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " (" + minMembers + ")cannot be greater than " + ApiConstants.MAX_MEMBERS + " (" + maxMembers + ")", null);
}
if (interval < 0) {
throw new InvalidParameterValueException("interval is an invalid value: " + interval);
throw new InvalidParameterValueException("interval is an invalid value: " + interval, null);
}
if (scaleUpPolicyIds != null) {
@ -906,7 +909,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
AutoScaleVmGroupVO vmGroupVO = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", vmGroupId, _autoScaleVmGroupDao);
if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) {
throw new InvalidParameterValueException("An AutoScale Vm Group can be updated only when it is in disabled state");
throw new InvalidParameterValueException("An AutoScale Vm Group can be updated only when it is in disabled state", null);
}
if (minMembers != null) {
@ -936,7 +939,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
AutoScaleVmGroupVO vmGroup = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao);
boolean success = false;
if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Disabled)) {
throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be enabled.");
throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be enabled.", null);
}
try {
@ -963,7 +966,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
AutoScaleVmGroupVO vmGroup = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao);
boolean success = false;
if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Enabled)) {
throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be disabled.");
throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be disabled.", null);
}
try {
@ -993,7 +996,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
try {
src = Counter.Source.valueOf(source);
} catch (Exception ex) {
throw new InvalidParameterValueException("The Source " + source + " does not exist; Unable to create Counter");
throw new InvalidParameterValueException("The Source " + source + " does not exist; Unable to create Counter", null);
}
CounterVO counter = null;
@ -1017,14 +1020,14 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
try {
op = Condition.Operator.valueOf(opr);
} catch (IllegalArgumentException ex) {
throw new InvalidParameterValueException("The Operator " + opr + " does not exist; Unable to create Condition.");
throw new InvalidParameterValueException("The Operator " + opr + " does not exist; Unable to create Condition.", null);
}
// TODO - Validate threshold
CounterVO counter = _counterDao.findById(cid);
if (counter == null) {
throw new InvalidParameterValueException("Unable to find counter");
throw new InvalidParameterValueException("Unable to find counter", null);
}
ConditionVO condition = null;
@ -1090,7 +1093,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
// Verify Counter id
CounterVO counter = _counterDao.findById(counterId);
if (counter == null) {
throw new InvalidParameterValueException("Unable to find Counter");
throw new InvalidParameterValueException("Unable to find Counter", null);
}
// Verify if it is used in any Condition
@ -1115,7 +1118,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
/* Check if entity is in database */
ConditionVO condition = getEntityInDatabase(UserContext.current().getCaller(), "Condition", conditionId, _conditionDao);
if (condition == null) {
throw new InvalidParameterValueException("Unable to find Condition");
throw new InvalidParameterValueException("Unable to find Condition", null);
}
// Verify if condition is used in any autoscale policy

View File

@ -73,8 +73,8 @@ import com.cloud.network.resource.F5BigIpResource;
import com.cloud.network.rules.LbStickinessMethod;
import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
import com.cloud.offering.NetworkOffering;
import com.cloud.resource.ServerResource;
import com.cloud.server.api.response.ExternalLoadBalancerResponse;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.Inject;
import com.cloud.utils.exception.CloudRuntimeException;
@ -123,7 +123,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
@Override
public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientNetworkCapacityException {
InsufficientNetworkCapacityException {
if (!canHandle(guestConfig)) {
return false;
@ -138,7 +138,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
@Override
public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
InsufficientNetworkCapacityException, ResourceUnavailableException {
InsufficientNetworkCapacityException, ResourceUnavailableException {
return true;
}
@ -239,7 +239,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
@Override
public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
ResourceUnavailableException {
ResourceUnavailableException {
// TODO Auto-generated method stub
return true;
}
@ -265,18 +265,20 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
throw new InvalidParameterValueException("Could not find zone by ID", null);
}
List<PhysicalNetworkVO> 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.");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(zone, zoneId, "zoneId"));
throw new InvalidParameterValueException("There are no physical networks or multiple physical networks " +
"configured in zone with specified zoneId to add this device.", idList);
}
pNetwork = physicalNetworks.get(0);
String deviceType = NetworkDevice.F5BigIpLoadBalancer.getName();
lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, (ServerResource) new F5BigIpResource());
lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, new F5BigIpResource());
if (lbDeviceVO != null) {
lbHost = _hostDao.findById(lbDeviceVO.getHostId());
@ -301,18 +303,21 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
if (zoneId != null) {
zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
throw new InvalidParameterValueException("Could not find zone by ID", null);
}
List<PhysicalNetworkVO> 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.");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(zone, zoneId, "zoneId"));
throw new InvalidParameterValueException("There are no physical networks or multiple " +
"physical networks configured in zone with specified zoneId " +
"to add this device.", idList);
}
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");
throw new InvalidParameterValueException("Zone Id must be specified to list the external load balancers", null);
}
}
@ -326,10 +331,10 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
public ExternalLoadBalancerDeviceVO addF5LoadBalancer(AddF5LoadBalancerCmd cmd) {
String deviceName = cmd.getDeviceType();
if (!deviceName.equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
throw new InvalidParameterValueException("Invalid F5 load balancer device type");
throw new InvalidParameterValueException("Invalid F5 load balancer device type", null);
}
return addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, (ServerResource) new F5BigIpResource());
return addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, new F5BigIpResource());
}
@ -339,7 +344,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
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);
throw new InvalidParameterValueException("Couldn't find F5 load balancer device by ID", null);
}
return deleteExternalLoadBalancer(lbDeviceVo.getHostId());
@ -352,7 +357,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
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);
throw new InvalidParameterValueException("Couldn't find F5 load balancer device by ID", null);
}
if (capacity != null) {
@ -381,13 +386,13 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO>();
if (physcialNetworkId == null && lbDeviceId == null) {
throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified");
throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified", null);
}
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);
throw new InvalidParameterValueException("Could not find F5 load balancer device by ID", null);
}
lbDevices.add(lbDeviceVo);
return lbDevices;
@ -396,7 +401,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
if (physcialNetworkId != null) {
pNetwork = _physicalNetworkDao.findById(physcialNetworkId);
if (pNetwork == null) {
throw new InvalidParameterValueException("Could not find phyical network with ID: " + physcialNetworkId);
throw new InvalidParameterValueException("Could not find phyical network by ID", null);
}
lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(physcialNetworkId, Provider.F5BigIp.getName());
return lbDevices;
@ -412,7 +417,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
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);
throw new InvalidParameterValueException("Could not find F5 load balancer device by ID ", null);
}
List<NetworkExternalLoadBalancerVO> networkLbMaps = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId);

View File

@ -288,11 +288,13 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
capabilities.putAll(VirtualRouterElement.capabilities);
Map<Capability, String> sourceNatCapabilities = capabilities.get(Service.SourceNat);
Map<Capability, String> sourceNatCapabilities = new HashMap<Capability, String>();
sourceNatCapabilities.putAll(capabilities.get(Service.SourceNat));
sourceNatCapabilities.put(Capability.RedundantRouter, "false");
capabilities.put(Service.SourceNat, sourceNatCapabilities);
Map<Capability, String> vpnCapabilities = capabilities.get(Service.Vpn);
Map<Capability, String> vpnCapabilities = new HashMap<Capability, String>();
vpnCapabilities.putAll(capabilities.get(Service.Vpn));
vpnCapabilities.put(Capability.VpnTypes, "s2svpn");
capabilities.put(Service.Vpn, vpnCapabilities);

View File

@ -462,9 +462,11 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma
//remove the rule
_firewallDao.remove(rule.getId());
//if the rule is the last one for the ip address assigned to VPC, unassign it from the network
IpAddress ip = _ipAddressDao.findById(rule.getSourceIpAddressId());
_networkMgr.unassignIPFromVpcNetwork(ip.getId(), rule.getNetworkId());
if (rule.getSourceIpAddressId() != null) {
//if the rule is the last one for the ip address assigned to VPC, unassign it from the network
IpAddress ip = _ipAddressDao.findById(rule.getSourceIpAddressId());
_networkMgr.unassignIPFromVpcNetwork(ip.getId(), rule.getNetworkId());
}
}
@Override

View File

@ -42,6 +42,8 @@ import com.cloud.agent.api.Answer;
import com.cloud.agent.api.BumpUpPriorityCommand;
import com.cloud.agent.api.CheckRouterAnswer;
import com.cloud.agent.api.CheckRouterCommand;
import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer;
import com.cloud.agent.api.CheckS2SVpnConnectionsCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.GetDomRVersionAnswer;
import com.cloud.agent.api.GetDomRVersionCmd;
@ -127,6 +129,11 @@ import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetworkServiceProvider;
import com.cloud.network.PublicIpAddress;
import com.cloud.network.RemoteAccessVpn;
import com.cloud.network.Site2SiteCustomerGateway;
import com.cloud.network.Site2SiteCustomerGatewayVO;
import com.cloud.network.Site2SiteVpnConnection;
import com.cloud.network.Site2SiteVpnConnectionVO;
import com.cloud.network.Site2SiteVpnGatewayVO;
import com.cloud.network.SshKeysDistriMonitor;
import com.cloud.network.VirtualNetworkApplianceService;
import com.cloud.network.VirtualRouterProvider;
@ -160,6 +167,7 @@ import com.cloud.network.rules.StaticNat;
import com.cloud.network.rules.StaticNatImpl;
import com.cloud.network.rules.StaticNatRule;
import com.cloud.network.rules.dao.PortForwardingRulesDao;
import com.cloud.network.vpn.Site2SiteVpnManager;
import com.cloud.offering.ServiceOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
@ -313,6 +321,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
Site2SiteVpnGatewayDao _s2sVpnGatewayDao;
@Inject
Site2SiteVpnConnectionDao _s2sVpnConnectionDao;
@Inject
Site2SiteVpnManager _s2sVpnMgr;
int _routerRamSize;
int _routerCpuMHz;
@ -896,7 +906,79 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
}
}
protected void updateSite2SiteVpnConnectionState(List<DomainRouterVO> routers) {
for (DomainRouterVO router : routers) {
List<Site2SiteVpnConnectionVO> conns = _s2sVpnMgr.getConnectionsForRouter(router);
if (conns == null || conns.isEmpty()) {
continue;
}
if (router.getState() != State.Running) {
for (Site2SiteVpnConnectionVO conn : conns) {
conn.setState(Site2SiteVpnConnection.State.Disconnected);
_s2sVpnConnectionDao.persist(conn);
}
continue;
}
List<String> ipList = new ArrayList<String>();
for (Site2SiteVpnConnectionVO conn : conns) {
if (conn.getState() != Site2SiteVpnConnection.State.Connected &&
conn.getState() != Site2SiteVpnConnection.State.Disconnected) {
continue;
}
Site2SiteCustomerGateway gw = _s2sCustomerGatewayDao.findById(conn.getCustomerGatewayId());
ipList.add(gw.getGatewayIp());
}
String privateIP = router.getPrivateIpAddress();
HostVO host = _hostDao.findById(router.getHostId());
if (host == null || host.getStatus() != Status.Up) {
continue;
} else if (host.getManagementServerId() != ManagementServerNode.getManagementServerId()) {
/* Only cover hosts managed by this management server */
continue;
} else if (privateIP != null) {
final CheckS2SVpnConnectionsCommand command = new CheckS2SVpnConnectionsCommand(ipList);
command.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
command.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
command.setWait(30);
final Answer origAnswer = _agentMgr.easySend(router.getHostId(), command);
CheckS2SVpnConnectionsAnswer answer = null;
if (origAnswer instanceof CheckS2SVpnConnectionsAnswer) {
answer = (CheckS2SVpnConnectionsAnswer)origAnswer;
} else {
s_logger.warn("Unable to update router " + router.getHostName() + "'s VPN connection status");
continue;
}
if (!answer.getResult()) {
s_logger.warn("Unable to update router " + router.getHostName() + "'s VPN connection status");
continue;
}
for (Site2SiteVpnConnectionVO conn : conns) {
if (conn.getState() != Site2SiteVpnConnection.State.Connected &&
conn.getState() != Site2SiteVpnConnection.State.Disconnected) {
continue;
}
Site2SiteVpnConnection.State oldState = conn.getState();
Site2SiteCustomerGateway gw = _s2sCustomerGatewayDao.findById(conn.getCustomerGatewayId());
if (answer.isConnected(gw.getGatewayIp())) {
conn.setState(Site2SiteVpnConnection.State.Connected);
} else {
conn.setState(Site2SiteVpnConnection.State.Disconnected);
}
_s2sVpnConnectionDao.persist(conn);
if (oldState != conn.getState()) {
String title = "Site-to-site Vpn Connection to " + gw.getName() +
" just switch from " + oldState + " to " + conn.getState();
String context = "Site-to-site Vpn Connection to " + gw.getName() + " on router " + router.getHostName() +
"(id: " + router.getId() + ") " + " just switch from " + oldState + " to " + conn.getState();
s_logger.info(context);
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_DOMAIN_ROUTER,
router.getDataCenterIdToDeployIn(), router.getPodIdToDeployIn(), title, context);
}
}
}
}
}
protected void updateRoutersRedundantState(List<DomainRouterVO> routers) {
boolean updated = false;
for (DomainRouterVO router : routers) {
@ -1089,6 +1171,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian
s_logger.debug("Found " + routers.size() + " routers. ");
updateRoutersRedundantState(routers);
updateSite2SiteVpnConnectionState(routers);
/* FIXME assumed the a pair of redundant routers managed by same mgmt server,
* then the update above can get the latest status */

View File

@ -891,7 +891,7 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian
super.finalizeNetworkRulesForNetwork(cmds, router, provider, guestNetworkId);
if (router.getVpcId() == null) {
if (router.getVpcId() != null) {
if (_networkMgr.isProviderSupportServiceInNetwork(guestNetworkId, Service.NetworkACL, Provider.VPCVirtualRouter)) {
List<? extends FirewallRule> networkACLs = _networkACLMgr.listNetworkACLs(guestNetworkId);
s_logger.debug("Found " + networkACLs.size() + " network ACLs to apply as a part of VPC VR " + router

View File

@ -917,7 +917,7 @@ public class VpcManagerImpl implements VpcManager, Manager{
&& _ntwkMgr.areServicesSupportedByNetworkOffering(guestNtwkOff.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("Only networks of type " + GuestType.Isolated + " with service "
+ Service.SourceNat +
+ Service.SourceNat.getName() +
" can be added as a part of VPC", null);
}

View File

@ -61,6 +61,7 @@ import com.cloud.user.AccountManager;
import com.cloud.user.DomainManager;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.PasswordGenerator;
@ -81,7 +82,7 @@ import com.cloud.utils.net.NetUtils;
public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manager {
private final static Logger s_logger = Logger.getLogger(RemoteAccessVpnManagerImpl.class);
String _name;
@Inject AccountDao _accountDao;
@Inject VpnUserDao _vpnUsersDao;
@Inject RemoteAccessVpnDao _remoteAccessVpnDao;
@ -95,7 +96,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
@Inject FirewallRulesDao _rulesDao;
@Inject FirewallManager _firewallMgr;
@Inject UsageEventDao _usageEventDao;
int _userLimit;
int _pskLength;
String _clientIpRange;
@ -110,26 +111,26 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
// make sure ip address exists
PublicIpAddress ipAddr = _networkMgr.getPublicIpAddress(publicIpId);
if (ipAddr == null) {
throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId);
throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId, null);
}
_accountMgr.checkAccess(caller, null, true, ipAddr);
if (!ipAddr.readyToUse()) {
throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress());
throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress(), null);
}
IPAddressVO ipAddress = _ipAddressDao.findById(publicIpId);
_networkMgr.checkIpForService(ipAddress, Service.Vpn, null);
RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIpId);
if (vpnVO != null) {
//if vpn is in Added state, return it to the api
if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
return vpnVO;
}
throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address");
throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address", null);
}
// TODO: assumes one virtual network / domr per account per zone
@ -139,13 +140,15 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
return vpnVO;
}
throw new InvalidParameterValueException("A Remote Access VPN already exists for this account");
throw new InvalidParameterValueException("A Remote Access VPN already exists for this account", null);
}
//Verify that vpn service is enabled for the network
Network network = _networkMgr.getNetwork(networkId);
if (!_networkMgr.areServicesSupportedInNetwork(network.getId(), Service.Vpn)) {
throw new InvalidParameterValueException("Vpn service is not supported in network id=" + ipAddr.getAssociatedWithNetworkId());
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(ipAddr, ipAddr.getAssociatedWithNetworkId(), "ipAddressId"));
throw new InvalidParameterValueException("Vpn service is not supported in network containing specified ipAddressId", idList);
}
if (ipRange == null) {
@ -153,13 +156,13 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
}
String[] range = ipRange.split("-");
if (range.length != 2) {
throw new InvalidParameterValueException("Invalid ip range");
throw new InvalidParameterValueException("Invalid ip range", null);
}
if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])) {
throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange);
throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange, null);
}
if (!NetUtils.validIpRange(range[0], range[1])) {
throw new InvalidParameterValueException("Invalid ip range " + ipRange);
throw new InvalidParameterValueException("Invalid ip range " + ipRange, null);
}
Pair<String, Integer> cidr = NetUtils.getCidr(network.getCidr());
@ -169,7 +172,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
String[] guestIpRange = NetUtils.getIpRangeFromCidr(cidr.first(), cidr.second());
if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-"
+ guestIpRange[1]);
+ guestIpRange[1], null);
}
// TODO: check sufficient range
// TODO: check overlap with private and public ip ranges in datacenter
@ -212,21 +215,21 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
@Override @DB
public void destroyRemoteAccessVpn(long ipId) throws ResourceUnavailableException {
Account caller = UserContext.current().getCaller();
RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(ipId);
if (vpn == null) {
s_logger.debug("vpn id=" + ipId + " does not exists ");
return;
}
_accountMgr.checkAccess(caller, null, true, vpn);
Network network = _networkMgr.getNetwork(vpn.getNetworkId());
vpn.setState(RemoteAccessVpn.State.Removed);
_remoteAccessVpnDao.update(vpn.getServerAddressId(), vpn);
List<? extends RemoteAccessVPNServiceProvider> elements = _networkMgr.getRemoteAccessVpnElements();
boolean success = false;
try {
@ -241,32 +244,32 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
//Cleanup corresponding ports
List<? extends FirewallRule> vpnFwRules = _rulesDao.listByIpAndPurpose(ipId, Purpose.Vpn);
Transaction txn = Transaction.currentTxn();
boolean applyFirewall = false;
List<FirewallRuleVO> fwRules = new ArrayList<FirewallRuleVO>();
//if related firewall rule is created for the first vpn port, it would be created for the 2 other ports as well, so need to cleanup the backend
if (_rulesDao.findByRelatedId(vpnFwRules.get(0).getId()) != null) {
applyFirewall = true;
}
if (applyFirewall) {
txn.start();
for (FirewallRule vpnFwRule : vpnFwRules) {
//don't apply on the backend yet; send all 3 rules in a banch
_firewallMgr.revokeRelatedFirewallRule(vpnFwRule.getId(), false);
fwRules.add(_rulesDao.findByRelatedId(vpnFwRule.getId()));
}
s_logger.debug("Marked " + fwRules.size() + " firewall rules as Revoked as a part of disable remote access vpn");
txn.commit();
//now apply vpn rules on the backend
s_logger.debug("Reapplying firewall rules for ip id=" + ipId + " as a part of disable remote access vpn");
success = _firewallMgr.applyFirewallRules(ipId, caller);
}
if (success) {
try {
txn.start();
@ -274,11 +277,11 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
// Stop billing of VPN users when VPN is removed. VPN_User_ADD events will be generated when VPN is created again
List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
for(VpnUserVO user : vpnUsers){
// VPN_USER_REMOVE event is already generated for users in Revoke state
if(user.getState() != VpnUser.State.Revoke){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername());
_usageEventDao.persist(usageEvent);
}
// VPN_USER_REMOVE event is already generated for users in Revoke state
if(user.getState() != VpnUser.State.Revoke){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername());
_usageEventDao.persist(usageEvent);
}
}
if (vpnFwRules != null) {
for (FirewallRule vpnFwRule : vpnFwRules) {
@ -303,30 +306,30 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
if (!username.matches("^[a-zA-Z0-9][a-zA-Z0-9@._-]{2,63}$")) {
throw new InvalidParameterValueException(
"Username has to be begin with an alphabet have 3-64 characters including alphabets, numbers and the set '@.-_'");
"Username has to be begin with an alphabet have 3-64 characters including alphabets, numbers and the set '@.-_'", null);
}
if (!password.matches("^[a-zA-Z0-9][a-zA-Z0-9@#+=._-]{2,31}$")) {
throw new InvalidParameterValueException("Password has to be 3-32 characters including alphabets, numbers and the set '@#+=.-_'");
throw new InvalidParameterValueException("Password has to be 3-32 characters including alphabets, numbers and the set '@#+=.-_'", null);
}
Transaction txn = Transaction.currentTxn();
txn.start();
Account owner = _accountDao.lockRow(vpnOwnerId, true);
if (owner == null) {
throw new InvalidParameterValueException("Unable to add vpn user: Another operation active");
throw new InvalidParameterValueException("Unable to add vpn user: Another operation active", null);
}
_accountMgr.checkAccess(caller, null, true, owner);
//don't allow duplicated user names for the same account
VpnUserVO vpnUser = _vpnUsersDao.findByAccountAndUsername(owner.getId(), username);
if (vpnUser != null) {
throw new InvalidParameterValueException("VPN User with name " + username + " is already added for account " + owner);
throw new InvalidParameterValueException("VPN User with name " + username + " is already added for account " + owner, null);
}
long userCount = _vpnUsersDao.getVpnUserCount(owner.getId());
if (userCount >= _userLimit) {
throw new AccountLimitException("Cannot add more than " + _userLimit + " remote access vpn users");
}
VpnUser user = _vpnUsersDao.persist(new VpnUserVO(vpnOwnerId, owner.getDomainId(), username, password));
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername());
_usageEventDao.persist(usageEvent);
@ -340,7 +343,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
VpnUserVO user = _vpnUsersDao.findByAccountAndUsername(vpnOwnerId, username);
if (user == null) {
throw new InvalidParameterValueException("Could not find vpn user " + username);
throw new InvalidParameterValueException("Could not find vpn user " + username, null);
}
_accountMgr.checkAccess(caller, null, true, user);
Transaction txn = Transaction.currentTxn();
@ -367,12 +370,12 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(vpnId);
if (vpn == null) {
throw new InvalidParameterValueException("Unable to find your vpn: " + vpnId);
throw new InvalidParameterValueException("Unable to find your vpn by id", null);
}
_accountMgr.checkAccess(caller, null, true, vpn);
Network network = _networkMgr.getNetwork(vpn.getNetworkId());
@ -383,7 +386,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
if (openFirewall) {
firewallOpened = _firewallMgr.applyFirewallRules(vpn.getServerAddressId(), caller);
}
if (firewallOpened) {
for (RemoteAccessVPNServiceProvider element : elements) {
if (element.startVpn(network, vpn)) {
@ -392,7 +395,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
}
}
}
return vpn;
} finally {
if (started) {
@ -400,14 +403,14 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
txn.start();
vpn.setState(RemoteAccessVpn.State.Running);
_remoteAccessVpnDao.update(vpn.getServerAddressId(), vpn);
// Start billing of existing VPN users in ADD and Active state
List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
for(VpnUserVO user : vpnUsers){
if(user.getState() != VpnUser.State.Revoke){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername());
_usageEventDao.persist(usageEvent);
}
if(user.getState() != VpnUser.State.Revoke){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername());
_usageEventDao.persist(usageEvent);
}
}
txn.commit();
}
@ -425,7 +428,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
List<RemoteAccessVpnVO> vpns = _remoteAccessVpnDao.findByAccount(vpnOwnerId);
List<VpnUserVO> users = _vpnUsersDao.listByAccount(vpnOwnerId);
//If user is in Active state, we still have to resend them therefore their status has to be Add
for (VpnUserVO user : users) {
if (user.getState() == State.Active) {
@ -433,7 +436,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
_vpnUsersDao.update(user.getId(), user);
}
}
List<? extends RemoteAccessVPNServiceProvider> elements = _networkMgr.getRemoteAccessVpnElements();
boolean success = true;
@ -461,7 +464,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
} catch (ResourceUnavailableException e) {
s_logger.warn("Unable to apply vpn users ", e);
success= false;
for (int i = 0; i < finals.length; i++) {
finals[i] = false;
}
@ -479,7 +482,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
_vpnUsersDao.remove(user.getId());
}
} else {
if (user.getState() == State.Add) {
if (user.getState() == State.Add) {
Transaction txn = Transaction.currentTxn();
txn.start();
_vpnUsersDao.remove(user.getId());
@ -498,7 +501,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
public List<VpnUserVO> searchForVpnUsers(ListVpnUsersCmd cmd) {
String username = cmd.getUsername();
Long id = cmd.getId();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
@ -511,14 +514,14 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
SearchBuilder<VpnUserVO> sb = _vpnUsersDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.EQ);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
SearchCriteria<VpnUserVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
//list only active users
sc.setParameters("state", State.Active);
@ -539,40 +542,40 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
Account caller = UserContext.current().getCaller();
Long ipAddressId = cmd.getPublicIpId();
List<Long> permittedAccounts = new ArrayList<Long>();
if (ipAddressId != null) {
PublicIpAddress publicIp = _networkMgr.getPublicIpAddress(ipAddressId);
if (publicIp == null) {
throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId + " not found.");
throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId + " not found.", null);
} else {
Long ipAddrAcctId = publicIp.getAccountId();
if (ipAddrAcctId == null) {
throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId
+ " is not associated with an account.");
+ " is not associated with an account.", null);
}
}
_accountMgr.checkAccess(caller, null, true, publicIp);
}
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter filter = new Filter(RemoteAccessVpnVO.class, "serverAddressId", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<RemoteAccessVpnVO> sb = _remoteAccessVpnDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("serverAddressId", sb.entity().getServerAddressId(), Op.EQ);
sb.and("state", sb.entity().getState(), Op.EQ);
SearchCriteria<RemoteAccessVpnVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sc.setParameters("state", RemoteAccessVpn.State.Running);
if (ipAddressId != null) {
sc.setParameters("serverAddressId", ipAddressId);
}
@ -620,12 +623,12 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
public String getName() {
return _name;
}
@Override
public List<? extends RemoteAccessVpn> listRemoteAccessVpns(long networkId) {
return _remoteAccessVpnDao.listByNetworkId(networkId);
}
@Override
public RemoteAccessVpn getRemoteAccessVpn(long vpnId) {
return _remoteAccessVpnDao.findById(vpnId);

View File

@ -1,7 +1,13 @@
package com.cloud.network.vpn;
import java.util.List;
import com.cloud.network.Site2SiteVpnConnectionVO;
import com.cloud.vm.DomainRouterVO;
public interface Site2SiteVpnManager extends Site2SiteVpnService {
boolean cleanupVpnConnectionByVpc(long vpcId);
boolean cleanupVpnGatewayByVpc(long vpcId);
void markDisconnectVpnConnByVpc(long vpcId);
List<Site2SiteVpnConnectionVO> getConnectionsForRouter(DomainRouterVO router);
}

View File

@ -9,6 +9,7 @@ import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.BaseListProjectAndAccountResourcesCmd;
import com.cloud.api.commands.CreateVpnConnectionCmd;
import com.cloud.api.commands.CreateVpnCustomerGatewayCmd;
import com.cloud.api.commands.CreateVpnGatewayCmd;
@ -44,14 +45,23 @@ import com.cloud.network.element.Site2SiteVpnServiceProvider;
import com.cloud.network.vpc.VpcManager;
import com.cloud.network.vpc.VpcVO;
import com.cloud.network.vpc.Dao.VpcDao;
import com.cloud.projects.Project.ListProjectResourcesCriteria;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GenericDao;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.DomainRouterVO;
@Local(value = { Site2SiteVpnManager.class, Site2SiteVpnService.class } )
public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
@ -66,9 +76,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
@Inject AccountDao _accountDao;
@Inject VpcManager _vpcMgr;
@Inject AccountManager _accountMgr;
String _name;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
@ -99,14 +109,16 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
//Verify that caller can perform actions in behalf of vpc owner
_accountMgr.checkAccess(caller, null, false, owner);
Long vpcId = cmd.getVpcId();
Long vpcId = cmd.getVpcId();
VpcVO vpc = _vpcDao.findById(vpcId);
if (vpc == null) {
throw new InvalidParameterValueException("Invalid VPC " + vpcId + " for site to site vpn gateway creation!");
throw new InvalidParameterValueException("Invalid VPC " + vpcId + " for site to site vpn gateway creation!", null);
}
Site2SiteVpnGatewayVO gws = _vpnGatewayDao.findByVpcId(vpcId);
if (gws != null) {
throw new InvalidParameterValueException("The VPN gateway of VPC " + vpcId + " already existed!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(vpc, vpcId, "vpcId"));
throw new InvalidParameterValueException("The VPN gateway of VPC with specified vpcId already exists!", idList);
}
Long accountId = cmd.getEntityOwnerId();
Long domainId = cmd.getDomainId();
@ -118,7 +130,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
if (ips.size() != 1) {
throw new CloudRuntimeException("Cannot found source nat ip of vpc " + vpcId);
}
Site2SiteVpnGatewayVO gw = new Site2SiteVpnGatewayVO(accountId, domainId, ips.get(0).getId(), vpcId);
_vpnGatewayDao.persist(gw);
return gw;
@ -136,23 +148,23 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
String name = cmd.getName();
String gatewayIp = cmd.getGatewayIp();
if (!NetUtils.isValidIp(gatewayIp)) {
throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!");
throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!", null);
}
if (name == null) {
name = "VPN-" + gatewayIp;
}
String guestCidrList = cmd.getGuestCidrList();
if (!NetUtils.validateGuestCidrList(guestCidrList)) {
throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " is invalid guest cidr!");
throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " is invalid guest cidr!", null);
}
String ipsecPsk = cmd.getIpsecPsk();
String ikePolicy = cmd.getIkePolicy();
String espPolicy = cmd.getEspPolicy();
if (!NetUtils.isValidS2SVpnPolicy(ikePolicy)) {
throw new InvalidParameterValueException("The customer gateway IKE policy " + ikePolicy + " is invalid!");
throw new InvalidParameterValueException("The customer gateway IKE policy " + ikePolicy + " is invalid!", null);
}
if (!NetUtils.isValidS2SVpnPolicy(espPolicy)) {
throw new InvalidParameterValueException("The customer gateway ESP policy " + espPolicy + " is invalid!");
throw new InvalidParameterValueException("The customer gateway ESP policy " + espPolicy + " is invalid!", null);
}
Long lifetime = cmd.getLifetime();
if (lifetime == null) {
@ -160,13 +172,13 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
lifetime = (long) 86400;
}
if (lifetime > 86400) {
throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!");
throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!", null);
}
if (_customerGatewayDao.findByGatewayIp(gatewayIp) != null) {
throw new InvalidParameterValueException("The customer gateway with ip " + gatewayIp + " already existed!");
throw new InvalidParameterValueException("The customer gateway with ip " + gatewayIp + " already existed!", null);
}
if (_customerGatewayDao.findByName(name) != null) {
throw new InvalidParameterValueException("The customer gateway with name " + name + " already existed!");
throw new InvalidParameterValueException("The customer gateway with name " + name + " already existed!", null);
}
Long accountId = cmd.getEntityOwnerId();
Long domainId = cmd.getDomainId();
@ -191,20 +203,23 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long customerGatewayId = cmd.getCustomerGatewayId();
Site2SiteCustomerGateway customerGateway = _customerGatewayDao.findById(customerGatewayId);
if (customerGateway == null) {
throw new InvalidParameterValueException("Unable to found specified Site to Site VPN customer gateway " + customerGatewayId + " !");
throw new InvalidParameterValueException("Unable to find specified Site to Site VPN customer gateway by id!", null);
}
_accountMgr.checkAccess(caller, null, false, customerGateway);
Long vpnGatewayId = cmd.getVpnGatewayId();
Site2SiteVpnGateway vpnGateway = _vpnGatewayDao.findById(vpnGatewayId);
if (vpnGateway == null) {
throw new InvalidParameterValueException("Unable to found specified Site to Site VPN gateway " + vpnGatewayId + " !");
throw new InvalidParameterValueException("Unable to find specified Site to Site VPN gateway by id", null);
}
_accountMgr.checkAccess(caller, null, false, vpnGateway);
if (_vpnConnectionDao.findByVpnGatewayIdAndCustomerGatewayId(vpnGatewayId, customerGatewayId) != null) {
throw new InvalidParameterValueException("The vpn connection with customer gateway id " + customerGatewayId + " or vpn gateway id "
+ vpnGatewayId + " already existed!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(vpnGateway, vpnGatewayId, "vpnGatewayId"));
idList.add(new IdentityProxy(customerGateway, customerGatewayId, "customerGatewayId"));
throw new InvalidParameterValueException("The vpn connection with specified customer gateway id or vpn gateway id " +
" already exists!", idList);
}
Long accountId = cmd.getEntityOwnerId();
Long domainId = cmd.getDomainId();
@ -221,7 +236,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
public Site2SiteVpnConnection startVpnConnection(long id) throws ResourceUnavailableException {
Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id);
if (conn.getState() != State.Pending && conn.getState() != State.Disconnected) {
throw new InvalidParameterValueException("Site to site VPN connection " + id + " not in correct state(pending or disconnected) to process!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(conn, id, "connectionId"));
throw new InvalidParameterValueException("Site to site VPN connection with specified connectionId not in correct state(pending or disconnected) to process!", idList);
}
conn.setState(State.Pending);
@ -258,13 +275,15 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Site2SiteCustomerGateway customerGateway = _customerGatewayDao.findById(id);
if (customerGateway == null) {
throw new InvalidParameterValueException("Fail to find customer gateway with " + id + " !");
throw new InvalidParameterValueException("Fail to find customer gateway by id", null);
}
_accountMgr.checkAccess(caller, null, false, customerGateway);
List<Site2SiteVpnConnectionVO> vpnConnections = _vpnConnectionDao.listByCustomerGatewayId(id);
if (vpnConnections != null && vpnConnections.size() != 0) {
throw new InvalidParameterValueException("Unable to delete VPN customer gateway " + id + " because there is still related VPN connections!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(customerGateway, id, "customerGatewayId"));
throw new InvalidParameterValueException("Unable to delete VPN customer gateway with specified id because there is still related VPN connections!", idList);
}
_customerGatewayDao.remove(id);
return true;
@ -273,11 +292,13 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
protected void doDeleteVpnGateway(Site2SiteVpnGateway gw) {
List<Site2SiteVpnConnectionVO> conns = _vpnConnectionDao.listByVpnGatewayId(gw.getId());
if (conns != null && conns.size() != 0) {
throw new InvalidParameterValueException("Unable to delete VPN gateway " + gw.getId() + " because there is still related VPN connections!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(gw, gw.getId(), "vpnGatewayId"));
throw new InvalidParameterValueException("Unable to delete VPN gateway with specified id because there is still related VPN connections!", idList);
}
_vpnGatewayDao.remove(gw.getId());
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_S2S_VPN_GATEWAY_DELETE, eventDescription = "deleting s2s vpn gateway", create=true)
public boolean deleteVpnGateway(DeleteVpnGatewayCmd cmd) {
@ -287,9 +308,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Site2SiteVpnGateway vpnGateway = _vpnGatewayDao.findById(id);
if (vpnGateway == null) {
throw new InvalidParameterValueException("Fail to find vpn gateway with " + id + " !");
throw new InvalidParameterValueException("Fail to find vpn gateway by id", null);
}
_accountMgr.checkAccess(caller, null, false, vpnGateway);
doDeleteVpnGateway(vpnGateway);
@ -305,7 +326,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Site2SiteCustomerGatewayVO gw = _customerGatewayDao.findById(id);
if (gw == null) {
throw new InvalidParameterValueException("Find to find customer gateway with id " + id);
throw new InvalidParameterValueException("Find to find customer gateway by id", null);
}
_accountMgr.checkAccess(caller, null, false, gw);
@ -313,26 +334,28 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
if (conns != null) {
for (Site2SiteVpnConnection conn : conns) {
if (conn.getState() != State.Disconnected || conn.getState() != State.Error) {
throw new InvalidParameterValueException("Unable to update customer gateway because there is active VPN connection " + conn.getId());
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(conn, conn.getId(), "vpnConnectionId"));
throw new InvalidParameterValueException("Unable to update customer gateway because there is an active VPN connection with specified vpn connection id", idList);
}
}
}
String gatewayIp = cmd.getGatewayIp();
if (!NetUtils.isValidIp(gatewayIp)) {
throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!");
throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!", null);
}
String guestCidrList = cmd.getGuestCidrList();
if (!NetUtils.validateGuestCidrList(guestCidrList)) {
throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " contains invalid guest cidr!");
throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " contains invalid guest cidr!", null);
}
String ipsecPsk = cmd.getIpsecPsk();
String ikePolicy = cmd.getIkePolicy();
String espPolicy = cmd.getEspPolicy();
if (!NetUtils.isValidS2SVpnPolicy(ikePolicy)) {
throw new InvalidParameterValueException("The customer gateway IKE policy" + ikePolicy + " is invalid!");
throw new InvalidParameterValueException("The customer gateway IKE policy" + ikePolicy + " is invalid!", null);
}
if (!NetUtils.isValidS2SVpnPolicy(espPolicy)) {
throw new InvalidParameterValueException("The customer gateway ESP policy" + espPolicy + " is invalid!");
throw new InvalidParameterValueException("The customer gateway ESP policy" + espPolicy + " is invalid!", null);
}
Long lifetime = cmd.getLifetime();
if (lifetime == null) {
@ -340,7 +363,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
lifetime = (long) 86400;
}
if (lifetime > 86400) {
throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!");
throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!", null);
}
gw.setGatewayIp(gatewayIp);
gw.setGuestCidrList(guestCidrList);
@ -361,9 +384,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id);
if (conn == null) {
throw new InvalidParameterValueException("Fail to find site to site VPN connection " + id + " to delete!");
throw new InvalidParameterValueException("Fail to find site to site VPN connection to delete!", null);
}
_accountMgr.checkAccess(caller, null, false, conn);
if (conn.getState() == State.Connected) {
@ -376,7 +399,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
private void stopVpnConnection(Long id) throws ResourceUnavailableException {
Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id);
if (conn.getState() != State.Connected && conn.getState() != State.Error) {
throw new InvalidParameterValueException("Site to site VPN connection " + id + " not in correct state(connected) to process disconnect!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(conn, id, "vpnConnectionId"));
throw new InvalidParameterValueException("Site to site VPN connection with specified id is not in correct state(connected) to process disconnect!", idList);
}
List <? extends Site2SiteVpnServiceProvider> elements = _networkMgr.getSite2SiteVpnElements();
@ -403,12 +428,14 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id);
if (conn == null) {
throw new InvalidParameterValueException("Fail to find site to site VPN connection " + id + " to reset!");
throw new InvalidParameterValueException("Fail to find site to site VPN connection to reset!", null);
}
_accountMgr.checkAccess(caller, null, false, conn);
if (conn.getState() == State.Pending) {
throw new InvalidParameterValueException("VPN connection " + id + " cannot be reseted when state is Pending!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(conn, id, "vpnConnectionId"));
throw new InvalidParameterValueException("VPN connection with specified id cannot be reseted when state is Pending!", idList);
}
if (conn.getState() == State.Connected || conn.getState() == State.Error) {
stopVpnConnection(id);
@ -421,12 +448,38 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
@Override
public List<Site2SiteCustomerGateway> searchForCustomerGateways(ListVpnCustomerGatewaysCmd cmd) {
Long id = cmd.getId();
List<Site2SiteCustomerGateway> results = new ArrayList<Site2SiteCustomerGateway>();
Long domainId = cmd.getDomainId();
boolean isRecursive = cmd.isRecursive();
String accountName = cmd.getAccountName();
boolean listAll = cmd.listAll();
long startIndex = cmd.getStartIndex();
long pageSizeVal = cmd.getPageSizeVal();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
ListProjectResourcesCriteria>(domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false);
domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(Site2SiteCustomerGatewayVO.class, "id", false, startIndex, pageSizeVal);
SearchBuilder<Site2SiteCustomerGatewayVO> sb = _customerGatewayDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
SearchCriteria<Site2SiteCustomerGatewayVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
if (id != null) {
results.add(_customerGatewayDao.findById(cmd.getId()));
} else {
results.addAll(_customerGatewayDao.listAll());
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
List<Site2SiteCustomerGateway> results = new ArrayList<Site2SiteCustomerGateway>();
results.addAll(_customerGatewayDao.search(sc, searchFilter));
return results;
}
@ -435,14 +488,43 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Long vpcId = cmd.getVpcId();
List<Site2SiteVpnGateway> results = new ArrayList<Site2SiteVpnGateway>();
Long domainId = cmd.getDomainId();
boolean isRecursive = cmd.isRecursive();
String accountName = cmd.getAccountName();
boolean listAll = cmd.listAll();
long startIndex = cmd.getStartIndex();
long pageSizeVal = cmd.getPageSizeVal();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
ListProjectResourcesCriteria>(domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false);
domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(Site2SiteVpnGatewayVO.class, "id", false, startIndex, pageSizeVal);
SearchBuilder<Site2SiteVpnGatewayVO> sb = _vpnGatewayDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
SearchCriteria<Site2SiteVpnGatewayVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
if (id != null) {
results.add(_vpnGatewayDao.findById(cmd.getId()));
} else if (vpcId != null) {
results.add(_vpnGatewayDao.findByVpcId(vpcId));
} else { //id == null && vpcId == null
results.addAll(_vpnGatewayDao.listAll());
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (vpcId != null) {
sc.addAnd("vpcId", SearchCriteria.Op.EQ, vpcId);
}
List<Site2SiteVpnGateway> results = new ArrayList<Site2SiteVpnGateway>();
results.addAll(_vpnGatewayDao.search(sc, searchFilter));
return results;
}
@ -451,14 +533,48 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Long vpcId = cmd.getVpcId();
List<Site2SiteVpnConnection> results = new ArrayList<Site2SiteVpnConnection>();
if (id != null) {
results.add(_vpnConnectionDao.findById(cmd.getId()));
} else if (vpcId != null) {
results.addAll(_vpnConnectionDao.listByVpcId(vpcId));
} else { //id == null && vpcId == null
results.addAll(_vpnConnectionDao.listAll());
Long domainId = cmd.getDomainId();
boolean isRecursive = cmd.isRecursive();
String accountName = cmd.getAccountName();
boolean listAll = cmd.listAll();
long startIndex = cmd.getStartIndex();
long pageSizeVal = cmd.getPageSizeVal();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
ListProjectResourcesCriteria>(domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, listAll, false);
domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(Site2SiteVpnConnectionVO.class, "id", false, startIndex, pageSizeVal);
SearchBuilder<Site2SiteVpnConnectionVO> sb = _vpnConnectionDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
if (vpcId != null) {
SearchBuilder<Site2SiteVpnGatewayVO> gwSearch = _vpnGatewayDao.createSearchBuilder();
gwSearch.and("vpcId", gwSearch.entity().getVpcId(), SearchCriteria.Op.EQ);
sb.join("gwSearch", gwSearch, sb.entity().getVpnGatewayId(), gwSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
SearchCriteria<Site2SiteVpnConnectionVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (vpcId != null) {
sc.setJoinParameters("gwSearch", "vpcId", vpcId);
}
List<Site2SiteVpnConnection> results = new ArrayList<Site2SiteVpnConnection>();
results.addAll(_vpnConnectionDao.search(sc, searchFilter));
return results;
}
@ -480,7 +596,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
doDeleteVpnGateway(gw);
return true;
}
@Override
public void markDisconnectVpnConnByVpc(long vpcId) {
List<Site2SiteVpnConnectionVO> conns = _vpnConnectionDao.listByVpcId(vpcId);
@ -494,4 +610,16 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
}
}
}
@Override
public List<Site2SiteVpnConnectionVO> getConnectionsForRouter(DomainRouterVO router) {
List<Site2SiteVpnConnectionVO> conns = new ArrayList<Site2SiteVpnConnectionVO>();
// One router for one VPC
Long vpcId = router.getVpcId();
if (router.getVpcId() == null) {
return conns;
}
conns.addAll(_vpnConnectionDao.listByVpcId(vpcId));
return conns;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -61,6 +61,7 @@ import com.cloud.user.AccountVO;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
@ -371,7 +372,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
try {
resourceType = ResourceType.values()[type];
} catch (ArrayIndexOutOfBoundsException e) {
throw new InvalidParameterValueException("Please specify a valid resource type.");
throw new InvalidParameterValueException("Please specify a valid resource type.", null);
}
}
@ -482,7 +483,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
if (max == null) {
max = new Long(Resource.RESOURCE_UNLIMITED);
} else if (max.longValue() < Resource.RESOURCE_UNLIMITED) {
throw new InvalidParameterValueException("Please specify either '-1' for an infinite limit, or a limit that is at least '0'.");
throw new InvalidParameterValueException("Please specify either '-1' for an infinite limit, or a limit that is at least '0'.", null);
}
// Map resource type
@ -494,7 +495,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
}
}
if (resourceType == null) {
throw new InvalidParameterValueException("Please specify valid resource type");
throw new InvalidParameterValueException("Please specify valid resource type", null);
}
}
@ -504,17 +505,17 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
if (accountId != null) {
Account account = _entityMgr.findById(Account.class, accountId);
if (account.getId() == Account.ACCOUNT_ID_SYSTEM) {
throw new InvalidParameterValueException("Can't update system account");
throw new InvalidParameterValueException("Can't update system account", null);
}
//only Unlimited value is accepted if account is Root Admin
if (_accountMgr.isRootAdmin(account.getType()) && max.shortValue() != ResourceLimit.RESOURCE_UNLIMITED) {
throw new InvalidParameterValueException("Only " + ResourceLimit.RESOURCE_UNLIMITED + " limit is supported for Root Admin accounts");
throw new InvalidParameterValueException("Only " + ResourceLimit.RESOURCE_UNLIMITED + " limit is supported for Root Admin accounts", null);
}
if ((caller.getAccountId() == accountId.longValue()) &&
(caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN ||
caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
(caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN ||
caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
// If the admin is trying to update his own account, disallow.
throw new PermissionDeniedException("Unable to update resource limit for his own account " + accountId + ", permission denied");
}
@ -546,8 +547,11 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
DomainVO parentDomain = _domainDao.findById(parentDomainId);
long parentMaximum = findCorrectResourceLimitForDomain(parentDomain, resourceType);
if ((parentMaximum >= 0) && (max.longValue() > parentMaximum)) {
throw new InvalidParameterValueException("Domain " + domain.getName() + "(id: " + parentDomain.getId() + ") has maximum allowed resource limit " + parentMaximum + " for " + resourceType
+ ", please specify a value less that or equal to " + parentMaximum);
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(parentDomain, parentDomain.getId(), "domainId"));
throw new InvalidParameterValueException("Domain " + domain.getName() + " with specified domainId " +
"has maximum allowed resource limit " + parentMaximum + " for " + resourceType +
", please specify a value less that or equal to " + parentMaximum, idList);
}
}
ownerType = ResourceOwnerType.Domain;
@ -555,7 +559,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
}
if (ownerId == null) {
throw new InvalidParameterValueException("AccountId or domainId have to be specified in order to update resource limit");
throw new InvalidParameterValueException("AccountId or domainId have to be specified in order to update resource limit", null);
}
ResourceLimitVO limit = _resourceLimitDao.findByOwnerIdAndType(ownerId, ownerType, resourceType);
@ -584,13 +588,13 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
}
}
if (resourceType == null) {
throw new InvalidParameterValueException("Please specify valid resource type");
throw new InvalidParameterValueException("Please specify valid resource type", null);
}
}
DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Please specify a valid domain ID.");
throw new InvalidParameterValueException("Please specify a valid domain ID.", null);
}
_accountMgr.checkAccess(callerAccount, domain);
@ -734,7 +738,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
} else if (type == Resource.ResourceType.network) {
newCount = _networkDao.countNetworksUserCanCreate(accountId);
} else {
throw new InvalidParameterValueException("Unsupported resource type " + type);
throw new InvalidParameterValueException("Unsupported resource type " + type, null);
}
_resourceCountDao.setResourceCount(accountId, ResourceOwnerType.Account, type, (newCount == null) ? 0 : newCount.longValue());

View File

@ -90,6 +90,7 @@ import com.cloud.user.Account;
import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
@ -373,7 +374,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
// now insert the user
insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) " +
"VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())";
"VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())";
txn = Transaction.currentTxn();
try {
@ -400,10 +401,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
// save default security group
if (tableName.equals("security_group")) {
insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id) " +
"VALUES ('default', 'Default Security Group', 2, 1)";
"VALUES ('default', 'Default Security Group', 2, 1)";
} else {
insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id, account_name) " +
"VALUES ('default', 'Default Security Group', 2, 1, 'admin')";
"VALUES ('default', 'Default Security Group', 2, 1, 'admin')";
}
txn = Transaction.currentTxn();
@ -561,8 +562,8 @@ public class ConfigurationServerImpl implements ConfigurationServer {
try {
String rpassword = PasswordGenerator.generatePresharedKey(8);
String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) "
+ "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword
+ "','randmon password generated each management server starts for system vm')";
+ "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword
+ "','randmon password generated each management server starts for system vm')";
PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql);
stmt.executeUpdate(wSql);
s_logger.info("Updated systemvm password in database");
@ -635,9 +636,9 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String publicKey = new String(arr2).trim();
String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '" + DBEncryptionUtil.encrypt(privateKey) + "','Private key for the entire CloudStack')";
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '" + DBEncryptionUtil.encrypt(privateKey) + "','Private key for the entire CloudStack')";
String insertSql2 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '" + DBEncryptionUtil.encrypt(publicKey) + "','Public key for the entire CloudStack')";
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '" + DBEncryptionUtil.encrypt(publicKey) + "','Public key for the entire CloudStack')";
Transaction txn = Transaction.currentTxn();
try {
@ -749,7 +750,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String password = PasswordGenerator.generateRandomPassword(12);
String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + "','Password used to authenticate zone-to-zone template copy requests')";
"VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + "','Password used to authenticate zone-to-zone template copy requests')";
Transaction txn = Transaction.currentTxn();
try {
@ -818,12 +819,12 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String ipNums = _configDao.getValue("linkLocalIp.nums");
int nums = Integer.parseInt(ipNums);
if (nums > 16 || nums <= 0) {
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16");
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16", null);
}
/* local link ip address starts from 169.254.0.2 - 169.254.(nums) */
String[] linkLocalIpRanges = NetUtils.getLinkLocalIPRange(nums);
if (linkLocalIpRanges == null) {
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16");
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16", null);
} else {
_zoneDao.addLinkLocalIpAddress(zoneId, pod.getId(), linkLocalIpRanges[0], linkLocalIpRanges[1]);
}
@ -977,7 +978,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
for (Service service : defaultIsolatedSourceNatEnabledNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO
(defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service));
(defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService);
}
@ -1041,7 +1042,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
for (Service service : defaultVpcNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO
(defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service));
(defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService);
}
@ -1070,7 +1071,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
for (Service service : defaultVpcNetworkOfferingProvidersNoLB.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO
(defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service));
(defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service));
_ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService);
}
@ -1173,12 +1174,15 @@ public class ConfigurationServerImpl implements ConfigurationServer {
}
if (networkOfferingId == null) {
throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType);
throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType, null);
}
List<NetworkVO> networks = _networkDao.listBy(Account.ACCOUNT_ID_SYSTEM, networkOfferingId, zoneId);
if (networks == null || networks.isEmpty()) {
throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone " + zoneId);
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy("data_center", zoneId, "zoneId"));
throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType +
" in zone with specified zoneId", idList);
}
return networks.get(0).getId();
}

View File

@ -2196,7 +2196,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
// Validate physical network
PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags());
throw new InvalidParameterValueException("Unable to find physical network by id and tag: " +requiredOfferings.get(0).getTags(), null);
}
s_logger.debug("Creating network for account " + owner + " from the network offering id=" +
requiredOfferings.get(0).getId() + " as a part of deployVM process");
@ -2429,7 +2429,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
String instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance);
String uuidName = UUID.randomUUID().toString();
//verify hostname information
if (hostName == null) {
hostName = uuidName;
@ -2453,16 +2453,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
ntwkDomains.put(ntwkDomain, ntwkIds);
}
}
for (String ntwkDomain : ntwkDomains.keySet()) {
for (Long ntwkId : ntwkDomains.get(ntwkDomain)) {
//* get all vms hostNames in the network
//* get all vms hostNames in the network
List<String> hostNames = _vmInstanceDao.listDistinctHostNames(ntwkId);
//* verify that there are no duplicates
if (hostNames.contains(hostName)) {
throw new InvalidParameterValueException("The vm with hostName " + hostName
+ " already exists in the network domain: " + ntwkDomain + "; network="
+ _networkMgr.getNetwork(ntwkId));
+ _networkMgr.getNetwork(ntwkId), null);
}
}
}
@ -3259,7 +3259,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
}
return usesLocalStorage;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
@ -3592,7 +3592,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags());
}
s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" +
requiredOfferings.get(0).getId() + " as a part of deployVM process");
Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(),
@ -3745,9 +3745,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
}
@Override
public boolean recreateNeeded(VirtualMachineProfile<UserVmVO> profile,
long hostId, Commands cmds, ReservationContext context) {
// TODO Auto-generated method stub
return false;
long hostId, Commands cmds, ReservationContext context) {
// TODO Auto-generated method stub
return false;
}
}

View File

@ -1884,8 +1884,7 @@ class TestUploadAttachVolume(cloudstackTestCase):
'Stopped',
"Check VM state is Running or not"
)
try:
with self.assertRaises(Exception):
virtual_machine.attach_volume(self.apiclient, volume)
except Exception as e:
self.fail("Failed to attach the volume: %s" % e)
self.debug("Failed to attach the volume as expected")
return