use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.
the class ApiServer method handleAsyncJobPublishEvent.
@MessageHandler(topic = AsyncJob.Topics.JOB_EVENT_PUBLISH)
private void handleAsyncJobPublishEvent(final String subject, final String senderAddress, final Object args) {
assert (args != null);
final Pair<AsyncJob, String> eventInfo = (Pair<AsyncJob, String>) args;
final AsyncJob job = eventInfo.first();
final String jobEvent = eventInfo.second();
if (s_logger.isTraceEnabled()) {
s_logger.trace("Handle asyjob publish event " + jobEvent);
}
final EventBus eventBus;
try {
eventBus = ComponentContext.getComponent(EventBus.class);
} catch (final NoSuchBeanDefinitionException nbe) {
// no provider is configured to provide events bus, so just return
return;
}
if (!job.getDispatcher().equalsIgnoreCase("ApiAsyncJobDispatcher")) {
return;
}
final User userJobOwner = _accountMgr.getUserIncludingRemoved(job.getUserId());
final Account jobOwner = _accountMgr.getAccount(userJobOwner.getAccountId());
// Get the event type from the cmdInfo json string
final String info = job.getCmdInfo();
String cmdEventType = "unknown";
if (info != null) {
final Type type = new TypeToken<Map<String, String>>() {
}.getType();
final Map<String, String> cmdInfo = ApiGsonHelper.getBuilder().create().fromJson(info, type);
final String eventTypeObj = cmdInfo.get("cmdEventType");
if (eventTypeObj != null) {
cmdEventType = eventTypeObj;
if (s_logger.isDebugEnabled()) {
s_logger.debug("Retrieved cmdEventType from job info: " + cmdEventType);
}
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to locate cmdEventType marker in job info. publish as unknown event");
}
}
}
// For some reason, the instanceType / instanceId are not abstract, which means we may get null values.
final String instanceType = job.getInstanceType() != null ? job.getInstanceType() : "unknown";
final String instanceUuid = job.getInstanceId() != null ? ApiDBUtils.findJobInstanceUuid(job) : "";
final Event event = new Event("management-server", EventCategory.ASYNC_JOB_CHANGE_EVENT.getName(), jobEvent, instanceType, instanceUuid);
final Map<String, String> eventDescription = new HashMap<>();
eventDescription.put("command", job.getCmd());
eventDescription.put("user", userJobOwner.getUuid());
eventDescription.put("account", jobOwner.getUuid());
eventDescription.put("processStatus", "" + job.getProcessStatus());
eventDescription.put("resultCode", "" + job.getResultCode());
eventDescription.put("instanceUuid", instanceUuid);
eventDescription.put("instanceType", instanceType);
eventDescription.put("commandEventType", cmdEventType);
eventDescription.put("jobId", job.getUuid());
eventDescription.put("jobResult", job.getResult());
eventDescription.put("cmdInfo", job.getCmdInfo());
eventDescription.put("status", "" + job.getStatus());
// If the event.accountinfo boolean value is set, get the human readable value for the username / domainname
final Map<String, String> configs = _configDao.getConfiguration("management-server", new HashMap<String, String>());
if (Boolean.valueOf(configs.get("event.accountinfo"))) {
final DomainVO domain = _domainDao.findById(jobOwner.getDomainId());
eventDescription.put("username", userJobOwner.getUsername());
eventDescription.put("accountname", jobOwner.getAccountName());
eventDescription.put("domainname", domain.getName());
}
event.setDescription(eventDescription);
try {
eventBus.publish(event);
} catch (final EventBusException evx) {
final String errMsg = "Failed to publish async job event on the the event bus.";
s_logger.warn(errMsg, evx);
}
}
use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.
the class ApiDBUtils method getDomainNetworkDetails.
public static Pair<Long, Boolean> getDomainNetworkDetails(final long networkId) {
final NetworkDomainVO map = s_networkDomainDao.getDomainNetworkMapByNetworkId(networkId);
final boolean subdomainAccess = (map.isSubdomainAccess() != null) ? map.isSubdomainAccess() : s_networkModel.getAllowSubdomainAccessGlobal();
return new Pair<>(map.getDomainId(), subdomainAccess);
}
use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.
the class XenServer610MigrateWithStorageSendCommandWrapper method execute.
@Override
public Answer execute(final MigrateWithStorageSendCommand command, final XenServer610Resource xenServer610Resource) {
final Connection connection = xenServer610Resource.getConnection();
final VirtualMachineTO vmSpec = command.getVirtualMachine();
final List<Pair<VolumeTO, Object>> volumeToSr = command.getVolumeToSr();
final List<Pair<NicTO, Object>> nicToNetwork = command.getNicToNetwork();
final Map<String, String> token = command.getToken();
final String vmName = vmSpec.getName();
Task task = null;
try {
// In a cluster management server setup, the migrate with storage receive and send
// commands and answers may have to be forwarded to another management server. This
// happens when the host/resource on which the command has to be executed is owned
// by the second management server. The serialization/deserialization of the command
// and answers fails as the xapi SR and Network class type isn't understand by the
// agent attache. Seriliaze the SR and Network objects here to a string and pass in
// the answer object. It'll be deserialzed and object created in migrate with
// storage send command execution.
final Gson gson = new Gson();
final Map<String, String> other = new HashMap<>();
other.put("live", "true");
// Create the vdi map which tells what volumes of the vm need to go
// on which sr on the destination.
final Map<VDI, SR> vdiMap = new HashMap<>();
for (final Pair<VolumeTO, Object> entry : volumeToSr) {
if (entry.second() instanceof SR) {
final SR sr = (SR) entry.second();
final VDI vdi = xenServer610Resource.getVDIbyUuid(connection, entry.first().getPath());
vdiMap.put(vdi, sr);
} else {
throw new CloudRuntimeException("The object " + entry.second() + " passed is not of type SR.");
}
}
final Set<VM> vms = VM.getByNameLabel(connection, vmSpec.getName());
VM vmToMigrate = null;
if (vms != null) {
vmToMigrate = vms.iterator().next();
}
// Create the vif map.
final Map<VIF, Network> vifMap = new HashMap<>();
for (final Pair<NicTO, Object> entry : nicToNetwork) {
if (entry.second() instanceof Network) {
final Network network = (Network) entry.second();
final VIF vif = xenServer610Resource.getVifByMac(connection, vmToMigrate, entry.first().getMac());
vifMap.put(vif, network);
} else {
throw new CloudRuntimeException("The object " + entry.second() + " passed is not of type Network.");
}
}
// Check migration with storage is possible.
task = vmToMigrate.assertCanMigrateAsync(connection, token, true, vdiMap, vifMap, other);
try {
// poll every 1 seconds.
final long timeout = xenServer610Resource.getMigrateWait() * 1000L;
xenServer610Resource.waitForTask(connection, task, 1000, timeout);
xenServer610Resource.checkForSuccess(connection, task);
} catch (final Types.HandleInvalid e) {
s_logger.error("Error while checking if vm " + vmName + " can be migrated.", e);
throw new CloudRuntimeException("Error while checking if vm " + vmName + " can be migrated.", e);
}
// Migrate now.
task = vmToMigrate.migrateSendAsync(connection, token, true, vdiMap, vifMap, other);
try {
// poll every 1 seconds.
final long timeout = xenServer610Resource.getMigrateWait() * 1000L;
xenServer610Resource.waitForTask(connection, task, 1000, timeout);
xenServer610Resource.checkForSuccess(connection, task);
} catch (final Types.HandleInvalid e) {
s_logger.error("Error while migrating vm " + vmName, e);
throw new CloudRuntimeException("Error while migrating vm " + vmName, e);
}
final Set<VolumeTO> volumeToSet = null;
return new MigrateWithStorageSendAnswer(command, volumeToSet);
} catch (final CloudRuntimeException e) {
s_logger.error("Migration of vm " + vmName + " with storage failed due to " + e.toString(), e);
return new MigrateWithStorageSendAnswer(command, e);
} catch (final Exception e) {
s_logger.error("Migration of vm " + vmName + " with storage failed due to " + e.toString(), e);
return new MigrateWithStorageSendAnswer(command, e);
} finally {
if (task != null) {
try {
task.destroy(connection);
} catch (final Exception e) {
s_logger.debug("Unable to destroy task " + task.toString() + " on host " + xenServer610Resource.getHost().getUuid() + " due to " + e.toString());
}
}
}
}
use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.
the class LoadBalancingRulesManagerImpl method listLoadBalancerInstances.
@Override
public Pair<List<? extends UserVm>, List<String>> listLoadBalancerInstances(final ListLoadBalancerRuleInstancesCmd cmd) throws PermissionDeniedException {
final Account caller = CallContext.current().getCallingAccount();
final Long loadBalancerId = cmd.getId();
Boolean applied = cmd.isApplied();
if (applied == null) {
applied = Boolean.TRUE;
}
final LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
if (loadBalancer == null) {
return null;
}
_accountMgr.checkAccess(caller, null, true, loadBalancer);
final List<UserVmVO> loadBalancerInstances = new ArrayList<>();
final List<String> serviceStates = new ArrayList<>();
List<LoadBalancerVMMapVO> vmLoadBalancerMappings = null;
vmLoadBalancerMappings = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
if (vmLoadBalancerMappings == null) {
final String msg = "no VM Loadbalancer Mapping found";
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
final Map<Long, String> vmServiceState = new HashMap<>(vmLoadBalancerMappings.size());
final List<Long> appliedInstanceIdList = new ArrayList<>();
if ((vmLoadBalancerMappings != null) && !vmLoadBalancerMappings.isEmpty()) {
for (final LoadBalancerVMMapVO vmLoadBalancerMapping : vmLoadBalancerMappings) {
appliedInstanceIdList.add(vmLoadBalancerMapping.getInstanceId());
vmServiceState.put(vmLoadBalancerMapping.getInstanceId(), vmLoadBalancerMapping.getState());
}
}
final List<UserVmVO> userVms = _vmDao.listVirtualNetworkInstancesByAcctAndNetwork(loadBalancer.getAccountId(), loadBalancer.getNetworkId());
for (final UserVmVO userVm : userVms) {
// an unknown state, skip it
switch(userVm.getState()) {
case Destroyed:
case Expunging:
case Error:
case Unknown:
continue;
}
final boolean isApplied = appliedInstanceIdList.contains(userVm.getId());
if ((isApplied && applied) || (!isApplied && !applied)) {
loadBalancerInstances.add(userVm);
serviceStates.add(vmServiceState.get(userVm.getId()));
}
}
return new Pair<>(loadBalancerInstances, serviceStates);
}
use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.
the class FirewallManagerImpl method listFirewallRules.
@Override
public Pair<List<? extends FirewallRule>, Integer> listFirewallRules(final IListFirewallRulesCmd cmd) {
final Long ipId = cmd.getIpAddressId();
final Long id = cmd.getId();
final Long networkId = cmd.getNetworkId();
final Map<String, String> tags = cmd.getTags();
final FirewallRule.TrafficType trafficType = cmd.getTrafficType();
final Boolean display = cmd.getDisplay();
final Account caller = CallContext.current().getCallingAccount();
final List<Long> permittedAccounts = new ArrayList<>();
if (ipId != null) {
final IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);
if (ipAddressVO == null || !ipAddressVO.readyToUse()) {
throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for firewall rules yet");
}
_accountMgr.checkAccess(caller, null, true, ipAddressVO);
}
final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
final Long domainId = domainIdRecursiveListProject.first();
final Boolean isRecursive = domainIdRecursiveListProject.second();
final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
final Filter filter = new Filter(FirewallRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
final SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), Op.EQ);
sb.and("trafficType", sb.entity().getTrafficType(), Op.EQ);
sb.and("networkId", sb.entity().getNetworkId(), Op.EQ);
sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
sb.and("display", sb.entity().isDisplay(), Op.EQ);
if (tags != null && !tags.isEmpty()) {
final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
for (int count = 0; count < tags.size(); count++) {
tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
tagSearch.cp();
}
tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
sb.groupBy(sb.entity().getId());
sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
}
final SearchCriteria<FirewallRuleVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
if (id != null) {
sc.setParameters("id", id);
}
if (tags != null && !tags.isEmpty()) {
int count = 0;
sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.FirewallRule.toString());
for (final String key : tags.keySet()) {
sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
count++;
}
}
if (display != null) {
sc.setParameters("display", display);
}
if (ipId != null) {
sc.setParameters("ip", ipId);
}
if (networkId != null) {
sc.setParameters("networkId", networkId);
}
sc.setParameters("purpose", Purpose.Firewall);
sc.setParameters("trafficType", trafficType);
final Pair<List<FirewallRuleVO>, Integer> result = _firewallDao.searchAndCount(sc, filter);
return new Pair<>(result.first(), result.second());
}
Aggregations