vmwareDc = _vmwareDcDao.getVmwareDatacenterByGuid(vmwareDcName + "@" + vCenterHost);
if (vmwareDc != null) {
throw new ResourceInUseException("This DC is already part of other CloudStack zone(s). Cannot add this DC to more zones.");
}
VmwareContext context = null;
DatacenterMO dcMo = null;
String dcCustomFieldValue;
boolean addDcCustomFieldDef = false;
boolean dcInUse = false;
String guid;
ManagedObjectReference dcMor;
try {
context = VmwareContextFactory.create(vCenterHost, userName, password);
// Check if DC exists on vCenter
dcMo = new DatacenterMO(context, vmwareDcName);
dcMor = dcMo.getMor();
if (dcMor == null) {
String msg = "Unable to find VMware DC " + vmwareDcName + " in vCenter " + vCenterHost + ". ";
s_logger.error(msg);
throw new InvalidParameterValueException(msg);
}
// Check if DC is already associated with another cloudstack deployment
// Get custom field property cloud.zone over this DC
guid = vmwareDcName + "@" + vCenterHost;
dcCustomFieldValue = dcMo.getCustomFieldValue(CustomFieldConstants.CLOUD_ZONE);
if (dcCustomFieldValue == null) {
addDcCustomFieldDef = true;
}
dcInUse = Boolean.parseBoolean(dcCustomFieldValue);
if (dcInUse) {
throw new ResourceInUseException("This DC is being managed by other CloudStack deployment. Cannot add this DC to zone.");
}
// Add DC to database into vmware_data_center table
vmwareDc = new VmwareDatacenterVO(guid, vmwareDcName, vCenterHost, userName, password);
vmwareDc = _vmwareDcDao.persist(vmwareDc);
// Map zone with vmware datacenter
vmwareDcZoneMap = new VmwareDatacenterZoneMapVO(zoneId, vmwareDc.getId());
vmwareDcZoneMap = _vmwareDcZoneMapDao.persist(vmwareDcZoneMap);
// Set custom field for this DC
if (addDcCustomFieldDef) {
dcMo.ensureCustomFieldDef(CustomFieldConstants.CLOUD_ZONE);
}
dcMo.setCustomFieldValue(CustomFieldConstants.CLOUD_ZONE, "true");
} catch (Throwable e) {
String msg = "Failed to add VMware DC to zone ";
if (e instanceof RemoteException) {
msg = "Encountered remote exception at vCenter. " + VmwareHelper.getExceptionMessage(e);
} else {
msg += "due to : " + e.getMessage();
}
throw new CloudRuntimeException(msg);
} finally {
if (context != null) {
context.close();
}
context = null;
}
return vmwareDc;
}