Search in sources :

Example 41 with Pair

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);
    }
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) User(com.cloud.legacymodel.user.User) HashMap(java.util.HashMap) EventBus(com.cloud.framework.events.EventBus) AsyncJob(com.cloud.framework.jobs.AsyncJob) DomainVO(com.cloud.domain.DomainVO) Type(java.lang.reflect.Type) Event(com.cloud.framework.events.Event) EventBusException(com.cloud.framework.events.EventBusException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) Map(java.util.Map) HashMap(java.util.HashMap) NameValuePair(org.apache.http.NameValuePair) Pair(com.cloud.legacymodel.utils.Pair) MessageHandler(com.cloud.framework.messagebus.MessageHandler)

Example 42 with Pair

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);
}
Also used : NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) Pair(com.cloud.legacymodel.utils.Pair)

Example 43 with Pair

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());
            }
        }
    }
}
Also used : Types(com.xensource.xenapi.Types) Task(com.xensource.xenapi.Task) MigrateWithStorageSendAnswer(com.cloud.legacymodel.communication.answer.MigrateWithStorageSendAnswer) HashMap(java.util.HashMap) Gson(com.google.gson.Gson) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) VolumeTO(com.cloud.legacymodel.to.VolumeTO) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.xensource.xenapi.Network) VDI(com.xensource.xenapi.VDI) Pair(com.cloud.legacymodel.utils.Pair) SR(com.xensource.xenapi.SR) NicTO(com.cloud.legacymodel.to.NicTO) Connection(com.xensource.xenapi.Connection) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) VIF(com.xensource.xenapi.VIF) VM(com.xensource.xenapi.VM)

Example 44 with Pair

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);
}
Also used : Account(com.cloud.legacymodel.user.Account) UserVmVO(com.cloud.vm.UserVmVO) HashMap(java.util.HashMap) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ArrayList(java.util.ArrayList) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) Pair(com.cloud.legacymodel.utils.Pair)

Example 45 with Pair

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());
}
Also used : Account(com.cloud.legacymodel.user.Account) ArrayList(java.util.ArrayList) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ResourceTagVO(com.cloud.tags.ResourceTagVO) List(java.util.List) ArrayList(java.util.ArrayList) FirewallRule(com.cloud.legacymodel.network.FirewallRule) Pair(com.cloud.legacymodel.utils.Pair) Ternary(com.cloud.legacymodel.utils.Ternary) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) Filter(com.cloud.utils.db.Filter) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Aggregations

Pair (com.cloud.legacymodel.utils.Pair)139 ArrayList (java.util.ArrayList)87 List (java.util.List)64 Account (com.cloud.legacymodel.user.Account)49 Filter (com.cloud.utils.db.Filter)48 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)38 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)27 HashMap (java.util.HashMap)27 Ternary (com.cloud.legacymodel.utils.Ternary)23 ListProjectResourcesCriteria (com.cloud.projects.Project.ListProjectResourcesCriteria)22 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)20 SSHKeyPair (com.cloud.legacymodel.user.SSHKeyPair)16 TemplateFilter (com.cloud.legacymodel.storage.VirtualMachineTemplate.TemplateFilter)13 Map (java.util.Map)13 DB (com.cloud.utils.db.DB)11 DomainVO (com.cloud.domain.DomainVO)10 VolumeVO (com.cloud.storage.VolumeVO)10 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)9 Network (com.cloud.legacymodel.network.Network)9 ResourceTagVO (com.cloud.tags.ResourceTagVO)9