Damans227 commented on code in PR #13478:
URL: https://github.com/apache/cloudstack/pull/13478#discussion_r4764759919


##########
server/src/main/java/com/cloud/alert/ResourceAlertServiceImpl.java:
##########
@@ -0,0 +1,662 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package com.cloud.alert;
+
+import org.apache.cloudstack.alert.ResourceAlertService;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.acl.ControlledEntity;
+import org.apache.cloudstack.api.InternalIdentity;
+import org.apache.cloudstack.api.response.ListResponse;
+import 
org.apache.cloudstack.api.command.user.resourcealert.CreateResourceAlertRuleCmd;
+import 
org.apache.cloudstack.api.command.user.resourcealert.DeleteResourceAlertRuleCmd;
+import 
org.apache.cloudstack.api.command.user.resourcealert.ListResourceAlertRulesCmd;
+import 
org.apache.cloudstack.api.command.user.resourcealert.ListResourceAlertsCmd;
+import 
org.apache.cloudstack.api.command.user.resourcealert.UpdateResourceAlertRuleCmd;
+import org.apache.cloudstack.api.response.ResourceAlertResponse;
+import org.apache.cloudstack.api.response.ResourceAlertRuleResponse;
+import com.cloud.alert.dao.ResourceAlertDao;
+import com.cloud.alert.dao.ResourceAlertRuleDao;
+import com.cloud.api.query.dao.ResourceAlertRuleJoinDao;
+import com.cloud.alert.dao.ResourceAlertRuleWebhookDao;
+import com.cloud.api.query.vo.ResourceAlertRuleJoinVO;
+import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+import org.apache.cloudstack.webhook.WebhookHelper;
+import org.apache.commons.lang3.EnumUtils;
+import org.springframework.beans.factory.NoSuchBeanDefinitionException;
+import org.apache.commons.lang3.StringUtils;
+
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.PermissionDeniedException;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.projects.Project;
+import com.cloud.storage.VolumeVO;
+import com.cloud.storage.dao.VolumeDao;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.Pair;
+import com.cloud.utils.Ternary;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.GlobalLock;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.UserVmVO;
+import com.cloud.vm.dao.UserVmDao;
+
+import org.apache.cloudstack.context.CallContext;
+
+public class ResourceAlertServiceImpl extends ManagerBase implements 
ResourceAlertService {
+
+    static final int OWNER_LOCK_WAIT_SECONDS = 30;
+
+    @Inject
+    AccountManager accountManager;
+    @Inject
+    ResourceAlertRuleDao ruleDao;
+    @Inject
+    ResourceAlertRuleJoinDao ruleJoinDao;
+    @Inject
+    ResourceAlertDao alertDao;
+    @Inject
+    ResourceAlertRuleWebhookDao ruleWebhookDao;
+    @Inject
+    UserVmDao userVmDao;
+    @Inject
+    VolumeDao volumeDao;
+    @Inject
+    HostDao hostDao;
+    @Inject
+    PrimaryDataStoreDao storagePoolDao;
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_RESOURCE_ALERT_RULE_CREATE, 
eventDescription = "creating resource alert rule")
+    public ResourceAlertRuleResponse 
createResourceAlertRule(CreateResourceAlertRuleCmd cmd) {
+        ResourceAlertRule.ResourceType resourceType = 
parseResourceType(cmd.getResourceType());
+        AlertCondition condition = parseCondition(cmd.getCondition());
+        AlertSeverity severity = parseSeverity(cmd.getSeverity());
+        ResourceAlertMetric metric = parseMetric(cmd.getMetric(), 
resourceType);
+
+        validateThreshold(metric, cmd.getThreshold());
+        validateResetInterval(cmd.getResetInterval());
+        int resetInterval = cmd.getResetInterval() != null ? 
cmd.getResetInterval() : 
ResourceAlertManagerImpl.DEFAULT_RESET_INTERVAL.value();
+        boolean email = cmd.getEmail() != null && cmd.getEmail();
+
+        Account caller = CallContext.current().getCallingAccount();
+        checkInfrastructureAccess(caller, resourceType);
+        checkEmailAccess(caller, email);
+        Account owner = accountManager.finalizeOwner(caller, 
cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());
+
+        long domainId = owner.getDomainId();
+
+        InternalIdentity resource = findResourceOrFail(resourceType, 
cmd.getResourceId());
+        checkResourceReportsMetrics(resource);
+        if (resource instanceof ControlledEntity) {
+            accountManager.checkAccess(owner, null, false, (ControlledEntity) 
resource);
+        }
+        Long resourceId = resource != null ? resource.getId() : null;
+        List<Long> webhookIds = resolveWebhookIds(owner, cmd.getWebhookIds());
+
+        // Held across management servers so parallel creates can't go over 
the limit or reuse a name.
+        GlobalLock lock = getOwnerLock(owner.getId());
+        if (!lock.lock(OWNER_LOCK_WAIT_SECONDS)) {
+            throw new CloudRuntimeException("Unable to create the resource 
alert rule as another rule is being created for the account, please try again");
+        }
+        ResourceAlertRuleVO rule;
+        try {
+            int limit = 
ResourceAlertManagerImpl.RULES_PER_ACCOUNT_LIMIT.valueIn(owner.getId());
+            if (limit >= 0 && ruleDao.countActiveByAccountId(owner.getId()) >= 
limit) {
+                throw new InvalidParameterValueException(
+                        "Account has reached the maximum of " + limit + " 
resource alert rules");
+            }
+            String name = validateName(owner.getId(), cmd.getName(), null);
+
+            rule = new ResourceAlertRuleVO(
+                    name, resourceType, resourceId,
+                    owner.getId(), domainId,
+                    metric.name(), condition, cmd.getThreshold(), severity,
+                    cmd.getMessage(), email, resetInterval);
+            ruleDao.persist(rule);
+            if (!webhookIds.isEmpty()) {
+                ruleWebhookDao.replaceWebhooksForRule(rule.getId(), 
webhookIds);
+            }
+        } finally {
+            lock.unlock();
+            lock.releaseRef();
+        }
+        CallContext.current().setEventResourceId(rule.getId());
+        CallContext.current().setEventDetails("Rule: " + rule.getName());
+        return toRuleResponse(ruleJoinDao.findById(rule.getId()));
+    }
+
+    @Override
+    public ListResponse<ResourceAlertRuleResponse> 
listResourceAlertRules(ListResourceAlertRulesCmd cmd) {
+        ResourceAlertRule.ResourceType resourceType = 
StringUtils.isNotBlank(cmd.getResourceType()) ?
+                parseResourceType(cmd.getResourceType()) : null;
+        Long resourceId = null;
+        if (StringUtils.isNotBlank(cmd.getResourceId())) {
+            Pair<ResourceAlertRule.ResourceType, Long> resource = 
findRuleResourceOrFail(resourceType, cmd.getResourceId());
+            resourceType = resource.first();
+            resourceId = resource.second();
+        }
+        String metric = StringUtils.isNotBlank(cmd.getMetric()) ? 
parseMetricName(cmd.getMetric()) : null;
+        AlertSeverity severity = StringUtils.isNotBlank(cmd.getSeverity()) ? 
parseSeverity(cmd.getSeverity()) : null;
+
+        Account caller = CallContext.current().getCallingAccount();
+        List<Long> permittedAccounts = new ArrayList<>();
+        Ternary<Long, Boolean, Project.ListProjectResourcesCriteria> 
domainIdRecursiveListProject =
+                new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
+        accountManager.buildACLSearchParameters(caller, cmd.getId(), 
cmd.getAccountName(), cmd.getProjectId(),
+                permittedAccounts, domainIdRecursiveListProject, 
cmd.listAll(), false);
+        SearchBuilder<ResourceAlertRuleJoinVO> sb = 
createAclSearchBuilder(domainIdRecursiveListProject, permittedAccounts);
+        sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+        sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
+        sb.and("keyword", sb.entity().getName(), SearchCriteria.Op.LIKE);
+        sb.and("resourceType", sb.entity().getResourceType(), 
SearchCriteria.Op.EQ);
+        sb.and("resourceId", sb.entity().getResourceId(), 
SearchCriteria.Op.EQ);
+        sb.and("metric", sb.entity().getMetric(), SearchCriteria.Op.EQ);
+        sb.and("severity", sb.entity().getSeverity(), SearchCriteria.Op.EQ);
+        SearchCriteria<ResourceAlertRuleJoinVO> sc = 
createAclSearchCriteria(sb, domainIdRecursiveListProject, permittedAccounts);
+        if (cmd.getId() != null) sc.setParameters("id", cmd.getId());
+        if (StringUtils.isNotBlank(cmd.getRuleName())) 
sc.setParameters("name", cmd.getRuleName());
+        if (StringUtils.isNotBlank(cmd.getKeyword())) 
sc.setParameters("keyword", "%" + cmd.getKeyword() + "%");
+        if (resourceType != null) sc.setParameters("resourceType", 
resourceType);
+        if (resourceId != null) sc.setParameters("resourceId", resourceId);
+        if (metric != null) sc.setParameters("metric", metric);
+        if (severity != null) sc.setParameters("severity", severity);
+
+        Filter filter = new Filter(ResourceAlertRuleJoinVO.class, "id", true, 
cmd.getStartIndex(), cmd.getPageSizeVal());
+        Pair<List<ResourceAlertRuleJoinVO>, Integer> rules = 
ruleJoinDao.searchAndCount(sc, filter);
+
+        List<ResourceAlertRuleResponse> responses = rules.first().stream()
+                .map(this::toRuleResponse)
+                .collect(Collectors.toList());
+
+        ListResponse<ResourceAlertRuleResponse> response = new 
ListResponse<>();
+        response.setResponses(responses, rules.second());
+        return response;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_RESOURCE_ALERT_RULE_UPDATE, 
eventDescription = "updating resource alert rule")
+    public ResourceAlertRuleResponse 
updateResourceAlertRule(UpdateResourceAlertRuleCmd cmd) {
+        ResourceAlertRuleVO rule = findRuleForCaller(cmd.getId());
+        checkEmailAccess(CallContext.current().getCallingAccount(), 
Boolean.TRUE.equals(cmd.getEmail()));
+
+        // Same lock as create, so a rename can't reuse a name taken at the 
same time.
+        GlobalLock lock = null;
+        if (cmd.getName() != null) {
+            lock = getOwnerLock(rule.getAccountId());
+            if (!lock.lock(OWNER_LOCK_WAIT_SECONDS)) {
+                throw new CloudRuntimeException("Unable to rename the resource 
alert rule as another rule is being changed for the account, please try again");
+            }
+        }
+        try {
+            return applyRuleUpdate(rule, cmd);
+        } finally {
+            if (lock != null) {
+                lock.unlock();
+                lock.releaseRef();
+            }
+        }
+    }
+
+    private ResourceAlertRuleResponse applyRuleUpdate(ResourceAlertRuleVO 
rule, UpdateResourceAlertRuleCmd cmd) {
+        if (cmd.getName() != null) 
rule.setName(validateName(rule.getAccountId(), cmd.getName(), rule.getId()));
+        if (StringUtils.isNotBlank(cmd.getCondition())) 
rule.setCondition(parseCondition(cmd.getCondition()));
+        if (cmd.getThreshold() != null) {
+            validateThreshold(ResourceAlertMetric.valueOf(rule.getMetric()), 
cmd.getThreshold());
+            rule.setThreshold(cmd.getThreshold());
+        }
+        if (StringUtils.isNotBlank(cmd.getSeverity())) 
rule.setSeverity(parseSeverity(cmd.getSeverity()));
+        if (cmd.getMessage() != null) rule.setMessage(cmd.getMessage());
+        if (cmd.getEmail() != null) rule.setEmail(cmd.getEmail());
+        if (cmd.getResetInterval() != null) {
+            validateResetInterval(cmd.getResetInterval());
+            rule.setResetInterval(cmd.getResetInterval());
+        }
+        if (StringUtils.isNotBlank(cmd.getState())) 
rule.setState(parseState(cmd.getState()));
+        rule.setUpdated(new Date());
+
+        if (cmd.isCleanupWebhooks()) {
+            ruleWebhookDao.replaceWebhooksForRule(rule.getId(), new 
ArrayList<>());
+        } else if (cmd.getWebhookIds() != null) {
+            Account owner = accountManager.getAccount(rule.getAccountId());
+            ruleWebhookDao.replaceWebhooksForRule(rule.getId(), 
resolveWebhookIds(owner, cmd.getWebhookIds()));
+        }
+        ruleDao.update(rule.getId(), rule);
+        return toRuleResponse(ruleJoinDao.findById(rule.getId()));
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_RESOURCE_ALERT_RULE_DELETE, 
eventDescription = "deleting resource alert rule")
+    public boolean deleteResourceAlertRule(DeleteResourceAlertRuleCmd cmd) {
+        findRuleForCaller(cmd.getId());
+        // Rule first, so an alert fired by a run in progress is cleared with 
the history.
+        boolean removed = ruleDao.remove(cmd.getId());
+        alertDao.removeByAlertRuleId(cmd.getId());
+        return removed;

Review Comment:
   fixed in bf203af. the alert now checks the rule again after its saved. if 
the rule was deleted in between, the alert is removed and not sent



##########
server/src/main/java/com/cloud/alert/ResourceAlertServiceImpl.java:
##########
@@ -0,0 +1,641 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package com.cloud.alert;
+
+import org.apache.cloudstack.alert.ResourceAlertService;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.acl.ControlledEntity;
+import org.apache.cloudstack.api.InternalIdentity;
+import org.apache.cloudstack.api.response.ListResponse;
+import 
org.apache.cloudstack.api.command.user.resourcealert.CreateResourceAlertRuleCmd;
+import 
org.apache.cloudstack.api.command.user.resourcealert.DeleteResourceAlertRuleCmd;
+import 
org.apache.cloudstack.api.command.user.resourcealert.ListResourceAlertRulesCmd;
+import 
org.apache.cloudstack.api.command.user.resourcealert.ListResourceAlertsCmd;
+import 
org.apache.cloudstack.api.command.user.resourcealert.UpdateResourceAlertRuleCmd;
+import org.apache.cloudstack.api.response.ResourceAlertResponse;
+import org.apache.cloudstack.api.response.ResourceAlertRuleResponse;
+import com.cloud.alert.dao.ResourceAlertDao;
+import com.cloud.alert.dao.ResourceAlertRuleDao;
+import com.cloud.api.query.dao.ResourceAlertRuleJoinDao;
+import com.cloud.alert.dao.ResourceAlertRuleWebhookDao;
+import com.cloud.api.query.vo.ResourceAlertRuleJoinVO;
+import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+import org.apache.cloudstack.webhook.WebhookHelper;
+import org.apache.commons.lang3.EnumUtils;
+import org.springframework.beans.factory.NoSuchBeanDefinitionException;
+import org.apache.commons.lang3.StringUtils;
+
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.PermissionDeniedException;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.projects.Project;
+import com.cloud.storage.VolumeVO;
+import com.cloud.storage.dao.VolumeDao;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.Pair;
+import com.cloud.utils.Ternary;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.GlobalLock;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.UserVmVO;
+import com.cloud.vm.dao.UserVmDao;
+
+import org.apache.cloudstack.context.CallContext;
+
+public class ResourceAlertServiceImpl extends ManagerBase implements 
ResourceAlertService {
+
+    static final int OWNER_LOCK_WAIT_SECONDS = 30;
+
+    @Inject
+    AccountManager accountManager;
+    @Inject
+    ResourceAlertRuleDao ruleDao;
+    @Inject
+    ResourceAlertRuleJoinDao ruleJoinDao;
+    @Inject
+    ResourceAlertDao alertDao;
+    @Inject
+    ResourceAlertRuleWebhookDao ruleWebhookDao;
+    @Inject
+    UserVmDao userVmDao;
+    @Inject
+    VolumeDao volumeDao;
+    @Inject
+    HostDao hostDao;
+    @Inject
+    PrimaryDataStoreDao storagePoolDao;
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_RESOURCE_ALERT_RULE_CREATE, 
eventDescription = "creating resource alert rule")
+    public ResourceAlertRuleResponse 
createResourceAlertRule(CreateResourceAlertRuleCmd cmd) {
+        ResourceAlertRule.ResourceType resourceType = 
parseResourceType(cmd.getResourceType());
+        AlertCondition condition = parseCondition(cmd.getCondition());
+        AlertSeverity severity = parseSeverity(cmd.getSeverity());
+        ResourceAlertMetric metric = parseMetric(cmd.getMetric(), 
resourceType);
+
+        validateThreshold(metric, cmd.getThreshold());
+        validateResetInterval(cmd.getResetInterval());
+        int resetInterval = cmd.getResetInterval() != null ? 
cmd.getResetInterval() : 
ResourceAlertManagerImpl.DEFAULT_RESET_INTERVAL.value();
+        boolean email = cmd.getEmail() != null && cmd.getEmail();
+
+        Account caller = CallContext.current().getCallingAccount();
+        checkInfrastructureAccess(caller, resourceType);
+        checkEmailAccess(caller, email);
+        Account owner = accountManager.finalizeOwner(caller, 
cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());
+
+        long domainId = owner.getDomainId();
+
+        InternalIdentity resource = findResourceOrFail(resourceType, 
cmd.getResourceId());
+        checkResourceReportsMetrics(resource);
+        if (resource instanceof ControlledEntity) {
+            accountManager.checkAccess(owner, null, false, (ControlledEntity) 
resource);
+        }
+        Long resourceId = resource != null ? resource.getId() : null;
+        List<Long> webhookIds = resolveWebhookIds(owner, cmd.getWebhookIds());
+
+        // Held across management servers so parallel creates can't go over 
the limit or reuse a name.
+        GlobalLock lock = getOwnerLock(owner.getId());
+        if (!lock.lock(OWNER_LOCK_WAIT_SECONDS)) {
+            throw new CloudRuntimeException("Unable to create the resource 
alert rule as another rule is being created for the account, please try again");
+        }
+        ResourceAlertRuleVO rule;
+        try {
+            int limit = 
ResourceAlertManagerImpl.RULES_PER_ACCOUNT_LIMIT.valueIn(owner.getId());
+            if (limit >= 0 && ruleDao.countActiveByAccountId(owner.getId()) >= 
limit) {
+                throw new InvalidParameterValueException(
+                        "Account has reached the maximum of " + limit + " 
resource alert rules");
+            }
+            String name = validateName(owner.getId(), cmd.getName(), null);
+
+            rule = new ResourceAlertRuleVO(
+                    name, resourceType, resourceId,
+                    owner.getId(), domainId,
+                    metric.name(), condition, cmd.getThreshold(), severity,
+                    cmd.getMessage(), email, resetInterval);
+            ruleDao.persist(rule);
+            if (!webhookIds.isEmpty()) {
+                ruleWebhookDao.replaceWebhooksForRule(rule.getId(), 
webhookIds);
+            }
+        } finally {
+            lock.unlock();
+            lock.releaseRef();
+        }
+        CallContext.current().setEventResourceId(rule.getId());
+        CallContext.current().setEventDetails("Rule: " + rule.getName());
+        return toRuleResponse(ruleJoinDao.findById(rule.getId()));
+    }
+
+    @Override
+    public ListResponse<ResourceAlertRuleResponse> 
listResourceAlertRules(ListResourceAlertRulesCmd cmd) {
+        ResourceAlertRule.ResourceType resourceType = 
StringUtils.isNotBlank(cmd.getResourceType()) ?
+                parseResourceType(cmd.getResourceType()) : null;
+        Long resourceId = null;
+        if (StringUtils.isNotBlank(cmd.getResourceId())) {
+            Pair<ResourceAlertRule.ResourceType, Long> resource = 
findRuleResourceOrFail(resourceType, cmd.getResourceId());
+            resourceType = resource.first();
+            resourceId = resource.second();
+        }
+        String metric = StringUtils.isNotBlank(cmd.getMetric()) ? 
parseMetricName(cmd.getMetric()) : null;
+        AlertSeverity severity = StringUtils.isNotBlank(cmd.getSeverity()) ? 
parseSeverity(cmd.getSeverity()) : null;
+
+        Account caller = CallContext.current().getCallingAccount();
+        List<Long> permittedAccounts = new ArrayList<>();
+        Ternary<Long, Boolean, Project.ListProjectResourcesCriteria> 
domainIdRecursiveListProject =
+                new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
+        accountManager.buildACLSearchParameters(caller, cmd.getId(), 
cmd.getAccountName(), cmd.getProjectId(),
+                permittedAccounts, domainIdRecursiveListProject, 
cmd.listAll(), false);
+        SearchBuilder<ResourceAlertRuleJoinVO> sb = 
createAclSearchBuilder(domainIdRecursiveListProject, permittedAccounts);
+        sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+        sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
+        sb.and("keyword", sb.entity().getName(), SearchCriteria.Op.LIKE);
+        sb.and("resourceType", sb.entity().getResourceType(), 
SearchCriteria.Op.EQ);
+        sb.and("resourceId", sb.entity().getResourceId(), 
SearchCriteria.Op.EQ);
+        sb.and("metric", sb.entity().getMetric(), SearchCriteria.Op.EQ);
+        sb.and("severity", sb.entity().getSeverity(), SearchCriteria.Op.EQ);
+        SearchCriteria<ResourceAlertRuleJoinVO> sc = 
createAclSearchCriteria(sb, domainIdRecursiveListProject, permittedAccounts);
+        if (cmd.getId() != null) sc.setParameters("id", cmd.getId());
+        if (StringUtils.isNotBlank(cmd.getRuleName())) 
sc.setParameters("name", cmd.getRuleName());
+        if (StringUtils.isNotBlank(cmd.getKeyword())) 
sc.setParameters("keyword", "%" + cmd.getKeyword() + "%");
+        if (resourceType != null) sc.setParameters("resourceType", 
resourceType);
+        if (resourceId != null) sc.setParameters("resourceId", resourceId);
+        if (metric != null) sc.setParameters("metric", metric);
+        if (severity != null) sc.setParameters("severity", severity);
+
+        Filter filter = new Filter(ResourceAlertRuleJoinVO.class, "id", true, 
cmd.getStartIndex(), cmd.getPageSizeVal());
+        Pair<List<ResourceAlertRuleJoinVO>, Integer> rules = 
ruleJoinDao.searchAndCount(sc, filter);
+
+        List<ResourceAlertRuleResponse> responses = rules.first().stream()
+                .map(this::toRuleResponse)
+                .collect(Collectors.toList());
+
+        ListResponse<ResourceAlertRuleResponse> response = new 
ListResponse<>();
+        response.setResponses(responses, rules.second());
+        return response;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_RESOURCE_ALERT_RULE_UPDATE, 
eventDescription = "updating resource alert rule")
+    public ResourceAlertRuleResponse 
updateResourceAlertRule(UpdateResourceAlertRuleCmd cmd) {
+        ResourceAlertRuleVO rule = findRuleForCaller(cmd.getId());
+        checkEmailAccess(CallContext.current().getCallingAccount(), 
Boolean.TRUE.equals(cmd.getEmail()));
+
+        if (cmd.getName() != null) 
rule.setName(validateName(rule.getAccountId(), cmd.getName(), rule.getId()));
+        if (StringUtils.isNotBlank(cmd.getCondition())) 
rule.setCondition(parseCondition(cmd.getCondition()));
+        if (cmd.getThreshold() != null) {
+            validateThreshold(ResourceAlertMetric.valueOf(rule.getMetric()), 
cmd.getThreshold());
+            rule.setThreshold(cmd.getThreshold());
+        }
+        if (StringUtils.isNotBlank(cmd.getSeverity())) 
rule.setSeverity(parseSeverity(cmd.getSeverity()));
+        if (cmd.getMessage() != null) rule.setMessage(cmd.getMessage());
+        if (cmd.getEmail() != null) rule.setEmail(cmd.getEmail());
+        if (cmd.getResetInterval() != null) {
+            validateResetInterval(cmd.getResetInterval());
+            rule.setResetInterval(cmd.getResetInterval());
+        }
+        if (StringUtils.isNotBlank(cmd.getState())) 
rule.setState(parseState(cmd.getState()));
+        rule.setUpdated(new Date());
+
+        if (cmd.isCleanupWebhooks()) {
+            ruleWebhookDao.replaceWebhooksForRule(rule.getId(), new 
ArrayList<>());
+        } else if (cmd.getWebhookIds() != null) {
+            Account owner = accountManager.getAccount(rule.getAccountId());
+            ruleWebhookDao.replaceWebhooksForRule(rule.getId(), 
resolveWebhookIds(owner, cmd.getWebhookIds()));
+        }
+        ruleDao.update(rule.getId(), rule);
+        return toRuleResponse(ruleJoinDao.findById(rule.getId()));
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_RESOURCE_ALERT_RULE_DELETE, 
eventDescription = "deleting resource alert rule")
+    public boolean deleteResourceAlertRule(DeleteResourceAlertRuleCmd cmd) {
+        findRuleForCaller(cmd.getId());
+        alertDao.removeByAlertRuleId(cmd.getId());
+        return ruleDao.remove(cmd.getId());

Review Comment:
   same fix as the delete one above, in bf203af



##########
ui/src/views/resourcealert/CreateResourceAlertRule.vue:
##########
@@ -0,0 +1,339 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+<template>
+  <a-spin :spinning="loading">
+    <a-form
+      class="form"
+      layout="vertical"
+      ref="formRef"
+      :model="form"
+      :rules="rules"
+      @finish="handleSubmit"
+      v-ctrl-enter="handleSubmit">
+
+      <a-form-item name="name" ref="name">
+        <template #label>{{ $t('label.name') }}</template>
+        <a-input v-focus="true" v-model:value="form.name" />
+      </a-form-item>
+
+      <a-form-item name="domainid" ref="domainid" v-if="canPickOwner">
+        <template #label>{{ $t('label.domain') }}</template>
+        <a-select
+          v-model:value="form.domainid"
+          allowClear
+          showSearch
+          optionFilterProp="label"
+          :loading="domainsLoading"
+          :placeholder="$t('label.resource.alert.owner.self')"
+          @change="onDomainChange">
+          <a-select-option v-for="d in domains" :key="d.id" :value="d.id" 
:label="d.path || d.name">{{ d.path || d.name }}</a-select-option>
+        </a-select>
+      </a-form-item>
+
+      <a-form-item name="account" ref="account" v-if="canPickOwner && 
form.domainid">
+        <template #label>{{ $t('label.account') }}</template>
+        <a-select
+          v-model:value="form.account"
+          showSearch
+          optionFilterProp="label"
+          :loading="accountsLoading"
+          @change="onOwnerChange">
+          <a-select-option v-for="a in accounts" :key="a.id" :value="a.name" 
:label="a.name">{{ a.name }}</a-select-option>
+        </a-select>
+      </a-form-item>
+
+      <a-form-item name="resourcetype" ref="resourcetype">
+        <template #label>{{ $t('label.resourcetype') }}</template>
+        <a-select v-model:value="form.resourcetype" 
@change="onResourceTypeChange">
+          <a-select-option v-for="rt in resourceTypes" :key="rt" 
:value="rt">{{ resourceTypeLabels[rt] || rt }}</a-select-option>
+        </a-select>
+      </a-form-item>
+
+      <a-form-item name="resourceid" ref="resourceid">
+        <template #label>{{ $t('label.resource') }}</template>
+        <a-select
+          v-model:value="form.resourceid"
+          :disabled="!form.resourcetype"
+          showSearch
+          optionFilterProp="label"
+          :loading="resourcesLoading">
+          <a-select-option value="" 
:label="$t('label.resource.alert.all.resources')">{{ 
$t('label.resource.alert.all.resources') }}</a-select-option>
+          <a-select-option v-for="r in resources" :key="r.id" :value="r.id" 
:label="r.displayname || r.name">{{ r.displayname || r.name }}</a-select-option>
+        </a-select>
+      </a-form-item>
+
+      <a-form-item name="metric" ref="metric">
+        <template #label>{{ $t('label.metric') }}</template>
+        <a-select v-model:value="form.metric" :disabled="!form.resourcetype">
+          <a-select-option v-for="m in availableMetrics" :key="m" 
:value="m">{{ metricLabels[m] || m }}</a-select-option>
+        </a-select>
+      </a-form-item>
+
+      <a-form-item name="condition" ref="condition">
+        <template #label>{{ $t('label.condition') }}</template>
+        <a-select v-model:value="form.condition">
+          <a-select-option v-for="c in conditions" :key="c" :value="c">{{ 
conditionLabels[c] || c }}</a-select-option>
+        </a-select>
+      </a-form-item>
+
+      <a-form-item name="threshold" ref="threshold">
+        <template #label>{{ $t('label.threshold') }}</template>
+        <a-input-number v-model:value="form.threshold" :min="0" style="width: 
100%" />
+      </a-form-item>
+
+      <a-form-item name="severity" ref="severity">
+        <template #label>{{ $t('label.severity') }}</template>
+        <a-select v-model:value="form.severity">
+          <a-select-option v-for="s in severities" :key="s" :value="s">{{ 
severityLabels[s] || s }}</a-select-option>
+        </a-select>
+      </a-form-item>
+
+      <a-form-item name="message" ref="message">
+        <template #label>{{ $t('label.message') }}</template>
+        <a-input v-model:value="form.message" />
+      </a-form-item>
+
+      <a-form-item name="email" ref="email" v-if="isRootAdmin">
+        <template #label>{{ $t('label.email') }}</template>
+        <a-switch v-model:checked="form.email" />
+      </a-form-item>
+
+      <a-form-item name="resetinterval" ref="resetinterval">
+        <template #label>{{ $t('label.resetinterval') }}</template>
+        <a-input-number v-model:value="form.resetinterval" :min="0" 
:placeholder="$t('label.resource.alert.cooldown.default')" style="width: 100%" 
/>
+      </a-form-item>
+
+      <a-form-item name="webhookids" ref="webhookids" v-if="'listWebhooks' in 
$store.getters.apis">
+        <template #label>{{ $t('label.webhooks') }}</template>
+        <a-select
+          v-model:value="form.webhookids"
+          mode="multiple"
+          :loading="webhooksLoading"
+          :disabled="!webhooksLoading && webhooks.length === 0 && 
form.webhookids.length === 0"
+          :placeholder="!webhooksLoading && webhooks.length === 0 ? 
$t('label.resource.alert.no.webhooks') : undefined"
+          optionFilterProp="label"
+          :filterOption="(input, option) => 
option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0">
+          <a-select-option v-for="wh in webhooks" :key="wh.id" :value="wh.id" 
:label="wh.name">{{ wh.name }}</a-select-option>
+        </a-select>
+      </a-form-item>
+
+      <div :span="24" class="action-button">
+        <a-button @click="() => { this.$emit('close-action') }">{{ 
$t('label.cancel') }}</a-button>
+        <a-button type="primary" ref="submit" :loading="loading" 
@click="handleSubmit">{{ $t('label.ok') }}</a-button>
+      </div>
+    </a-form>
+  </a-spin>
+</template>
+
+<script>
+import { getAPI, postAPI } from '@/api'
+import { METRICS_BY_TYPE, CONDITIONS, SEVERITIES, RESOURCE_TYPE_LABELS, 
METRIC_LABELS, CONDITION_LABELS, SEVERITY_LABELS } from './resourceAlertOptions'
+
+export default {
+  name: 'CreateResourceAlertRule',
+  props: {
+    resource: {
+      type: Object,
+      default: () => ({})
+    },
+    presetResourceType: {
+      type: String,
+      default: ''
+    }
+  },
+  data () {
+    return {
+      loading: false,
+      webhooks: [],
+      webhooksLoading: false,
+      resources: [],
+      resourcesLoading: false,
+      domains: [],
+      domainsLoading: false,
+      accounts: [],
+      accountsLoading: false,
+      form: {
+        name: '',
+        domainid: undefined,
+        account: undefined,
+        resourcetype: undefined,
+        resourceid: '',
+        metric: undefined,
+        condition: undefined,
+        threshold: undefined,
+        severity: undefined,
+        message: '',
+        email: false,
+        resetinterval: undefined,
+        webhookids: []
+      },
+      rules: {
+        name: [{ required: true, message: this.$t('label.required') }],
+        resourcetype: [{ required: true, message: this.$t('label.required') }],
+        metric: [{ required: true, message: this.$t('label.required') }],
+        condition: [{ required: true, message: this.$t('label.required') }],
+        threshold: [{ required: true, message: this.$t('label.required') }],
+        severity: [{ required: true, message: this.$t('label.required') }]
+      },
+
+      conditions: CONDITIONS,
+      severities: SEVERITIES,
+      resourceTypeLabels: RESOURCE_TYPE_LABELS,
+      metricLabels: METRIC_LABELS,
+      conditionLabels: CONDITION_LABELS,
+      severityLabels: SEVERITY_LABELS
+    }
+  },
+  computed: {
+    isAdminOrDomainAdmin () {
+      return ['Admin', 
'DomainAdmin'].includes(this.$store.getters.userInfo.roletype)
+    },
+    // In project view the project owns the rule, so there is no owner to pick
+    canPickOwner () {
+      return this.isAdminOrDomainAdmin && !this.$store.getters.project?.id
+    },
+    ownerParams () {
+      return this.form.domainid && this.form.account ? { domainid: 
this.form.domainid, account: this.form.account } : {}
+    },
+    isRootAdmin () {
+      return this.$store.getters.userInfo.roletype === 'Admin'
+    },
+    resourceTypes () {
+      return this.isRootAdmin ? ['VirtualMachine', 'Host', 'Volume', 
'StoragePool'] : ['VirtualMachine', 'Volume']
+    },
+    availableMetrics () {
+      return METRICS_BY_TYPE[this.form.resourcetype] || []
+    }
+  },
+  created () {
+    this.fetchWebhooks()
+    if (this.canPickOwner) this.fetchDomains()
+    this.presetResource()
+  },
+  watch: {
+    'resource.id' () {
+      this.presetResource()
+    }
+  },
+  methods: {
+    // Opened from a resource's own page: pick its type and the resource itself
+    presetResource () {
+      if (!this.presetResourceType || !this.resource?.id) return
+      this.form.resourcetype = this.presetResourceType
+      this.form.metric = undefined
+      this.fetchResources().then(() => {
+        this.form.resourceid = this.resource.id
+      })

Review Comment:
   fixed in bf203af. the resource is set right away now, not after the list 
loads



##########
api/src/main/java/org/apache/cloudstack/api/command/user/resourcealert/UpdateResourceAlertRuleCmd.java:
##########
@@ -0,0 +1,120 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.cloudstack.api.command.user.resourcealert;
+
+import java.util.List;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.acl.RoleType;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.context.CallContext;
+import com.cloud.alert.ResourceAlertRule;
+import org.apache.cloudstack.alert.ResourceAlertService;
+import org.apache.cloudstack.api.response.ResourceAlertRuleResponse;
+
+
+@APICommand(name = "updateResourceAlertRule",
+        description = "Updates a resource alert rule",
+        responseObject = ResourceAlertRuleResponse.class,
+        entityType = {ResourceAlertRule.class},
+        authorized = {RoleType.Admin, RoleType.ResourceAdmin, 
RoleType.DomainAdmin, RoleType.User},
+        since = "24.0.0")
+public class UpdateResourceAlertRuleCmd extends BaseCmd {
+
+    @Inject
+    ResourceAlertService resourceAlertService;
+
+    @Parameter(name = ApiConstants.ID, type = CommandType.UUID,
+            entityType = ResourceAlertRuleResponse.class,
+            required = true,
+            description = "the ID of the alert rule to update")
+    private Long id;
+
+    @Parameter(name = ApiConstants.NAME, type = CommandType.STRING,
+            description = "new name for the rule")
+    private String name;
+
+    @Parameter(name = ApiConstants.CONDITION, type = CommandType.STRING,
+            description = "new comparison operator: GT, GTE, LT, LTE, EQ")
+    private String condition;
+
+    @Parameter(name = ApiConstants.THRESHOLD, type = CommandType.DOUBLE,
+            description = "new threshold value")
+    private Double threshold;
+
+    @Parameter(name = ApiConstants.SEVERITY, type = CommandType.STRING,
+            description = "new severity: CRITICAL, HIGH, MEDIUM, LOW")
+    private String severity;
+
+    @Parameter(name = ApiConstants.MESSAGE, type = CommandType.STRING,
+            description = "new alert message", length = 4096)

Review Comment:
   added in bf203af



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to