Search in sources :

Example 31 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class SnapshotManagerImpl method createSnapshot.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_CREATE, eventDescription = "creating snapshot", async = true)
public Snapshot createSnapshot(Long volumeId, Long policyId, Long snapshotId, Account snapshotOwner) {
    VolumeInfo volume = volFactory.getVolume(volumeId);
    if (volume == null) {
        throw new InvalidParameterValueException("No such volume exist");
    }
    if (volume.getState() != Volume.State.Ready) {
        throw new InvalidParameterValueException("Volume is not in ready state");
    }
    // does the caller have the authority to act on this volume
    _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
    SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
    if (snapshot == null) {
        s_logger.debug("Failed to create snapshot");
        throw new CloudRuntimeException("Failed to create snapshot");
    }
    try {
        postCreateSnapshot(volumeId, snapshot.getId(), policyId);
        //Check if the snapshot was removed while backingUp. If yes, do not log snapshot create usage event
        SnapshotVO freshSnapshot = _snapshotDao.findById(snapshot.getId());
        if (freshSnapshot != null) {
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null, volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid());
        }
        _resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot);
    } catch (Exception e) {
        s_logger.debug("Failed to create snapshot", e);
        throw new CloudRuntimeException("Failed to create snapshot", e);
    }
    return snapshot;
}
Also used : SnapshotInfo(org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 32 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class TaggedResourceManagerImpl method createTags.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_TAGS_CREATE, eventDescription = "creating resource tags")
public List<ResourceTag> createTags(final List<String> resourceIds, final ResourceObjectType resourceType, final Map<String, String> tags, final String customer) {
    final Account caller = CallContext.current().getCallingAccount();
    final List<ResourceTag> resourceTags = new ArrayList<ResourceTag>(tags.size());
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            for (String key : tags.keySet()) {
                for (String resourceId : resourceIds) {
                    if (!resourceType.resourceTagsSupport()) {
                        throw new InvalidParameterValueException("The resource type " + resourceType + " doesn't support resource tags");
                    }
                    long id = getResourceId(resourceId, resourceType);
                    String resourceUuid = getUuid(resourceId, resourceType);
                    Pair<Long, Long> accountDomainPair = getAccountDomain(id, resourceType);
                    Long domainId = accountDomainPair.second();
                    Long accountId = accountDomainPair.first();
                    if ((domainId != null) && (domainId == -1)) {
                        throw new CloudRuntimeException("Invalid DomainId : -1");
                    }
                    if (accountId != null) {
                        _accountMgr.checkAccess(caller, null, false, _accountMgr.getAccount(accountId));
                    } else if (domainId != null && !_accountMgr.isNormalUser(caller.getId())) {
                        //check permissions;
                        _accountMgr.checkAccess(caller, _domainMgr.getDomain(domainId));
                    } else {
                        throw new PermissionDeniedException("Account " + caller + " doesn't have permissions to create tags" + " for resource " + key);
                    }
                    String value = tags.get(key);
                    if (value == null || value.isEmpty()) {
                        throw new InvalidParameterValueException("Value for the key " + key + " is either null or empty");
                    }
                    ResourceTagVO resourceTag = new ResourceTagVO(key, value, accountDomainPair.first(), accountDomainPair.second(), id, resourceType, customer, resourceUuid);
                    resourceTag = _resourceTagDao.persist(resourceTag);
                    resourceTags.add(resourceTag);
                }
            }
        }
    });
    return resourceTags;
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ResourceTag(com.cloud.server.ResourceTag) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Pair(com.cloud.utils.Pair) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 33 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class IAMApiServiceImpl method createIAMGroup.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_IAM_GROUP_CREATE, eventDescription = "Creating Acl Group", create = true)
public IAMGroup createIAMGroup(Account caller, String iamGroupName, String description) {
    Long domainId = caller.getDomainId();
    Domain callerDomain = _domainDao.findById(domainId);
    if (callerDomain == null) {
        throw new InvalidParameterValueException("Caller does not have a domain");
    }
    return _iamSrv.createIAMGroup(iamGroupName, description, callerDomain.getPath());
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Domain(com.cloud.domain.Domain) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 34 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class ConfigurationManagerImpl method updateDiskOffering.

@Override
@ActionEvent(eventType = EventTypes.EVENT_DISK_OFFERING_EDIT, eventDescription = "updating disk offering")
public DiskOffering updateDiskOffering(final UpdateDiskOfferingCmd cmd) {
    final Long diskOfferingId = cmd.getId();
    final String name = cmd.getDiskOfferingName();
    final String displayText = cmd.getDisplayText();
    final Integer sortKey = cmd.getSortKey();
    final Boolean displayDiskOffering = cmd.getDisplayOffering();
    // Check if diskOffering exists
    final DiskOffering diskOfferingHandle = _entityMgr.findById(DiskOffering.class, diskOfferingId);
    if (diskOfferingHandle == null) {
        throw new InvalidParameterValueException("Unable to find disk offering by id " + diskOfferingId);
    }
    Long userId = CallContext.current().getCallingUserId();
    if (userId == null) {
        userId = Long.valueOf(User.UID_SYSTEM);
    }
    final User user = _userDao.findById(userId);
    if (user == null || user.getRemoved() != null) {
        throw new InvalidParameterValueException("Unable to find active user by id " + userId);
    }
    final Account account = _accountDao.findById(user.getAccountId());
    if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
        if (diskOfferingHandle.getDomainId() == null) {
            throw new InvalidParameterValueException("Unable to update public disk offering by id " + userId + " because it is domain-admin");
        }
        if (!_domainDao.isChildDomain(account.getDomainId(), diskOfferingHandle.getDomainId())) {
            throw new InvalidParameterValueException("Unable to update disk offering by another domain admin with id " + userId);
        }
    } else if (account.getType() != Account.ACCOUNT_TYPE_ADMIN) {
        throw new InvalidParameterValueException("Unable to update disk offering by id " + userId + " because it is not root-admin or domain-admin");
    }
    final boolean updateNeeded = name != null || displayText != null || sortKey != null || displayDiskOffering != null;
    if (!updateNeeded) {
        return _diskOfferingDao.findById(diskOfferingId);
    }
    final DiskOfferingVO diskOffering = _diskOfferingDao.createForUpdate(diskOfferingId);
    if (name != null) {
        diskOffering.setName(name);
    }
    if (displayText != null) {
        diskOffering.setDisplayText(displayText);
    }
    if (sortKey != null) {
        diskOffering.setSortKey(sortKey);
    }
    if (displayDiskOffering != null) {
        diskOffering.setDisplayOffering(displayDiskOffering);
    }
    if (_diskOfferingDao.update(diskOfferingId, diskOffering)) {
        CallContext.current().setEventDetails("Disk offering id=" + diskOffering.getId());
        return _diskOfferingDao.findById(diskOfferingId);
    } else {
        return null;
    }
}
Also used : Account(com.cloud.user.Account) DiskOffering(com.cloud.offering.DiskOffering) User(com.cloud.user.User) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) ActionEvent(com.cloud.event.ActionEvent)

Example 35 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class ConfigurationManagerImpl method editZone.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_ZONE_EDIT, eventDescription = "editing zone", async = false)
public DataCenter editZone(final UpdateZoneCmd cmd) {
    // Parameter validation as from execute() method in V1
    final Long zoneId = cmd.getId();
    String zoneName = cmd.getZoneName();
    String dns1 = cmd.getDns1();
    String dns2 = cmd.getDns2();
    String ip6Dns1 = cmd.getIp6Dns1();
    String ip6Dns2 = cmd.getIp6Dns2();
    String internalDns1 = cmd.getInternalDns1();
    String internalDns2 = cmd.getInternalDns2();
    String guestCidr = cmd.getGuestCidrAddress();
    final List<String> dnsSearchOrder = cmd.getDnsSearchOrder();
    final Boolean isPublic = cmd.isPublic();
    final String allocationStateStr = cmd.getAllocationState();
    final String dhcpProvider = cmd.getDhcpProvider();
    final Map<?, ?> detailsMap = cmd.getDetails();
    final String networkDomain = cmd.getDomain();
    final Boolean localStorageEnabled = cmd.getLocalStorageEnabled();
    final Map<String, String> newDetails = new HashMap<String, String>();
    if (detailsMap != null) {
        final Collection<?> zoneDetailsCollection = detailsMap.values();
        final Iterator<?> iter = zoneDetailsCollection.iterator();
        while (iter.hasNext()) {
            final HashMap<?, ?> detail = (HashMap<?, ?>) iter.next();
            final String key = (String) detail.get("key");
            final String value = (String) detail.get("value");
            if (key == null || value == null) {
                throw new InvalidParameterValueException("Invalid Zone Detail specified, fields 'key' and 'value' cannot be null, please specify details in the form:  details[0].key=XXX&details[0].value=YYY");
            }
            // validate the zone detail keys are known keys
            /*
                 * if(!ZoneConfig.doesKeyExist(key)){ throw new
                 * InvalidParameterValueException
                 * ("Invalid Zone Detail parameter: "+ key); }
                 */
            newDetails.put(key, value);
        }
    }
    // add the domain prefix list to details if not null
    if (dnsSearchOrder != null) {
        for (final String dom : dnsSearchOrder) {
            if (!NetUtils.verifyDomainName(dom)) {
                throw new InvalidParameterValueException("Invalid network domain suffixes. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
            }
        }
        newDetails.put(ZoneConfig.DnsSearchOrder.getName(), StringUtils.join(dnsSearchOrder, ","));
    }
    final DataCenterVO zone = _zoneDao.findById(zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("unable to find zone by id " + zoneId);
    }
    if (zoneName == null) {
        zoneName = zone.getName();
    }
    if (guestCidr != null && !NetUtils.validateGuestCidr(guestCidr)) {
        throw new InvalidParameterValueException("Please enter a valid guest cidr");
    }
    // Make sure the zone exists
    if (!validZone(zoneId)) {
        throw new InvalidParameterValueException("A zone with ID: " + zoneId + " does not exist.");
    }
    final String oldZoneName = zone.getName();
    if (zoneName == null) {
        zoneName = oldZoneName;
    }
    if (dns1 == null) {
        dns1 = zone.getDns1();
    }
    if (dns2 == null) {
        dns2 = zone.getDns2();
    }
    if (ip6Dns1 == null) {
        ip6Dns1 = zone.getIp6Dns1();
    }
    if (ip6Dns2 == null) {
        ip6Dns2 = zone.getIp6Dns2();
    }
    if (internalDns1 == null) {
        internalDns1 = zone.getInternalDns1();
    }
    if (internalDns2 == null) {
        internalDns2 = zone.getInternalDns2();
    }
    if (guestCidr == null) {
        guestCidr = zone.getGuestNetworkCidr();
    }
    // validate network domain
    if (networkDomain != null && !networkDomain.isEmpty()) {
        if (!NetUtils.verifyDomainName(networkDomain)) {
            throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
        }
    }
    final boolean checkForDuplicates = !zoneName.equals(oldZoneName);
    // not allowing updating
    checkZoneParameters(zoneName, dns1, dns2, internalDns1, internalDns2, checkForDuplicates, null, allocationStateStr, ip6Dns1, ip6Dns2);
    // domain associated with
    // a zone, once created
    zone.setName(zoneName);
    zone.setDns1(dns1);
    zone.setDns2(dns2);
    zone.setIp6Dns1(ip6Dns1);
    zone.setIp6Dns2(ip6Dns2);
    zone.setInternalDns1(internalDns1);
    zone.setInternalDns2(internalDns2);
    zone.setGuestNetworkCidr(guestCidr);
    if (localStorageEnabled != null) {
        zone.setLocalStorageEnabled(localStorageEnabled.booleanValue());
    }
    if (networkDomain != null) {
        if (networkDomain.isEmpty()) {
            zone.setDomain(null);
        } else {
            zone.setDomain(networkDomain);
        }
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            final Map<String, String> updatedDetails = new HashMap<String, String>();
            _zoneDao.loadDetails(zone);
            if (zone.getDetails() != null) {
                updatedDetails.putAll(zone.getDetails());
            }
            updatedDetails.putAll(newDetails);
            zone.setDetails(updatedDetails);
            if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
                final Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr);
                if (allocationState == Grouping.AllocationState.Enabled) {
                    // check if zone has necessary trafficTypes before enabling
                    try {
                        PhysicalNetwork mgmtPhyNetwork;
                        // zone should have a physical network with management
                        // traffiType
                        mgmtPhyNetwork = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Management);
                        if (NetworkType.Advanced == zone.getNetworkType() && !zone.isSecurityGroupEnabled()) {
                            // advanced zone without SG should have a physical
                            // network with public Thpe
                            _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public);
                        }
                        try {
                            _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage);
                        } catch (final InvalidParameterValueException noStorage) {
                            final PhysicalNetworkTrafficTypeVO mgmtTraffic = _trafficTypeDao.findBy(mgmtPhyNetwork.getId(), TrafficType.Management);
                            _networkSvc.addTrafficTypeToPhysicalNetwork(mgmtPhyNetwork.getId(), TrafficType.Storage.toString(), "vlan", mgmtTraffic.getXenNetworkLabel(), mgmtTraffic.getKvmNetworkLabel(), mgmtTraffic.getVmwareNetworkLabel(), mgmtTraffic.getSimulatorNetworkLabel(), mgmtTraffic.getVlan(), mgmtTraffic.getHypervNetworkLabel(), mgmtTraffic.getOvm3NetworkLabel());
                            s_logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network " + mgmtPhyNetwork.getId() + " with same configure of management traffic type");
                        }
                    } catch (final InvalidParameterValueException ex) {
                        throw new InvalidParameterValueException("Cannot enable this Zone since: " + ex.getMessage());
                    }
                }
                zone.setAllocationState(allocationState);
            }
            if (dhcpProvider != null) {
                zone.setDhcpProvider(dhcpProvider);
            }
            // update a private zone to public; not vice versa
            if (isPublic != null && isPublic) {
                zone.setDomainId(null);
                zone.setDomain(null);
                // release the dedication for this zone
                final DedicatedResourceVO resource = _dedicatedDao.findByZoneId(zoneId);
                Long resourceId = null;
                if (resource != null) {
                    resourceId = resource.getId();
                    if (!_dedicatedDao.remove(resourceId)) {
                        throw new CloudRuntimeException("Failed to delete dedicated Zone Resource " + resourceId);
                    }
                    // find the group associated and check if there are any more
                    // resources under that group
                    final List<DedicatedResourceVO> resourcesInGroup = _dedicatedDao.listByAffinityGroupId(resource.getAffinityGroupId());
                    if (resourcesInGroup.isEmpty()) {
                        // delete the group
                        _affinityGroupService.deleteAffinityGroup(resource.getAffinityGroupId(), null, null, null, null);
                    }
                }
            }
            if (!_zoneDao.update(zoneId, zone)) {
                throw new CloudRuntimeException("Failed to edit zone. Please contact Cloud Support.");
            }
        }
    });
    return zone;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) HashMap(java.util.HashMap) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) PhysicalNetworkTrafficTypeVO(com.cloud.network.dao.PhysicalNetworkTrafficTypeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) AllocationState(com.cloud.org.Grouping.AllocationState) PhysicalNetwork(com.cloud.network.PhysicalNetwork) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) Map(java.util.Map) HashMap(java.util.HashMap) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

ActionEvent (com.cloud.event.ActionEvent)209 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)174 Account (com.cloud.user.Account)114 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)80 DB (com.cloud.utils.db.DB)79 TransactionStatus (com.cloud.utils.db.TransactionStatus)40 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)32 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)32 ArrayList (java.util.ArrayList)31 CallContext (org.apache.cloudstack.context.CallContext)22 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)20 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)20 DataCenterVO (com.cloud.dc.DataCenterVO)18 Network (com.cloud.network.Network)18 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)17 InvalidParameterException (java.security.InvalidParameterException)16 List (java.util.List)16 NetworkVO (com.cloud.network.dao.NetworkVO)15 ConfigurationException (javax.naming.ConfigurationException)15 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)14