sureshanaparti commented on code in PR #10560:
URL: https://github.com/apache/cloudstack/pull/10560#discussion_r2053592885


##########
server/src/main/java/org/apache/cloudstack/vm/lease/VMLeaseManagerImpl.java:
##########
@@ -0,0 +1,353 @@
+/*
+ * 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.vm.lease;
+
+import com.cloud.alert.AlertManager;
+import com.cloud.api.ApiGsonHelper;
+import com.cloud.api.query.dao.UserVmJoinDao;
+import com.cloud.api.query.vo.UserVmJoinVO;
+import com.cloud.event.ActionEventUtils;
+import com.cloud.event.EventTypes;
+import com.cloud.user.Account;
+import com.cloud.user.User;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.StringUtils;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.concurrency.NamedThreadFactory;
+import com.cloud.utils.db.GlobalLock;
+import com.cloud.vm.VmDetailConstants;
+import com.cloud.vm.dao.UserVmDetailsDao;
+import org.apache.cloudstack.api.ApiCommandResourceType;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd;
+import org.apache.cloudstack.api.command.user.vm.StopVMCmd;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.config.Configurable;
+import org.apache.cloudstack.framework.jobs.AsyncJobDispatcher;
+import org.apache.cloudstack.framework.jobs.AsyncJobManager;
+import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO;
+import org.apache.cloudstack.managed.context.ManagedContextRunnable;
+import org.apache.commons.lang3.time.DateUtils;
+
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+public class VMLeaseManagerImpl extends ManagerBase implements VMLeaseManager, 
Configurable {
+    public static final String INSTANCE_LEASE_ENABLED = 
"instance.lease.enabled";
+
+    public static ConfigKey<Boolean> InstanceLeaseEnabled = new 
ConfigKey<>(ConfigKey.CATEGORY_ADVANCED, Boolean.class,
+            INSTANCE_LEASE_ENABLED, "false", "Indicates whether to enable the 
Instance lease," +
+            " will be applicable only on instances created after lease is 
enabled. Disabling the feature cancels lease on existing instances with lease." 
+
+            "Re-enabling feature will not cause lease expiry actions on 
grandfathered instances",
+            true, List.of(ConfigKey.Scope.Global));
+
+    private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5;  
 // 5 seconds
+
+    @Inject
+    private UserVmDetailsDao userVmDetailsDao;
+
+    @Inject
+    private UserVmJoinDao userVmJoinDao;
+
+    @Inject
+    private AlertManager alertManager;
+
+    @Inject
+    private AsyncJobManager asyncJobManager;
+
+    private AsyncJobDispatcher asyncJobDispatcher;
+
+    ScheduledExecutorService vmLeaseExecutor;
+    ScheduledExecutorService vmLeaseAlertExecutor;
+
+    @Override
+    public String getConfigComponentName() {
+        return VMLeaseManager.class.getSimpleName();
+    }
+
+    @Override
+    public ConfigKey<?>[] getConfigKeys() {
+        return new ConfigKey[]{
+                InstanceLeaseEnabled,
+                InstanceLeaseSchedulerInterval,
+                InstanceLeaseAlertSchedule,
+                InstanceLeaseExpiryAlertDaysBefore
+        };
+    }
+
+    public void setAsyncJobDispatcher(final AsyncJobDispatcher dispatcher) {
+        asyncJobDispatcher = dispatcher;
+    }
+
+    @Override
+    public boolean configure(String name, Map<String, Object> params) throws 
ConfigurationException {
+        if (InstanceLeaseEnabled.value()) {
+           scheduleLeaseExecutors();
+        }
+        return true;
+    }
+
+    @Override
+    public boolean start() {
+        return true;
+    }
+
+    @Override
+    public boolean stop() {
+        shutDownLeaseExecutors();
+        return true;
+    }
+
+    /**
+     * This method will cancel lease on instances running under lease
+     * will be primarily used when feature gets disabled
+     */
+    public void cancelLeaseOnExistingInstances() {
+        List<UserVmJoinVO> leaseExpiringForInstances = 
userVmJoinDao.listLeaseInstancesExpiringInDays(-1);
+        logger.debug("Total instances found for lease cancellation: {}", 
leaseExpiringForInstances.size());
+        for (UserVmJoinVO instance : leaseExpiringForInstances) {
+            userVmDetailsDao.addDetail(instance.getId(), 
VmDetailConstants.INSTANCE_LEASE_EXECUTION, "CANCELLED", false);
+            String leaseCancellationMsg = String.format("Lease is cancelled 
for the instancedId: %s ", instance.getUuid());
+            ActionEventUtils.onActionEvent(instance.getUserId(), 
instance.getAccountId(), instance.getDomainId(),
+                    EventTypes.VM_LEASE_CANCELLED, leaseCancellationMsg, 
instance.getId(), ApiCommandResourceType.VirtualMachine.toString());
+        }
+    }
+
+    @Override
+    public void onLeaseFeatureToggle() {
+        boolean isLeaseFeatureEnabled = 
VMLeaseManagerImpl.InstanceLeaseEnabled.value();
+        if (isLeaseFeatureEnabled) {
+            scheduleLeaseExecutors();
+        } else {
+            cancelLeaseOnExistingInstances();
+            shutDownLeaseExecutors();
+        }
+    }
+
+    private void scheduleLeaseExecutors() {
+        if (vmLeaseExecutor == null || vmLeaseExecutor.isShutdown()) {
+            logger.debug("Scheduling lease executor");
+            vmLeaseExecutor = Executors.newSingleThreadScheduledExecutor(new 
NamedThreadFactory("VMLeasePollExecutor"));
+            vmLeaseExecutor.scheduleAtFixedRate(new VMLeaseSchedulerTask(),5L, 
InstanceLeaseSchedulerInterval.value(), TimeUnit.SECONDS);
+        }
+
+        if (vmLeaseAlertExecutor == null || vmLeaseAlertExecutor.isShutdown()) 
{
+            logger.debug("Scheduling lease alert executor");
+            vmLeaseAlertExecutor = 
Executors.newSingleThreadScheduledExecutor(new 
NamedThreadFactory("VMLeaseAlertPollExecutor"));
+            vmLeaseAlertExecutor.scheduleAtFixedRate(new 
VMLeaseAlertSchedulerTask(), 5L, InstanceLeaseAlertSchedule.value(), 
TimeUnit.SECONDS);
+        }
+    }
+
+    private void shutDownLeaseExecutors() {
+        if (vmLeaseExecutor != null) {
+                logger.debug("Shutting down lease executor");
+            vmLeaseExecutor.shutdown();
+            vmLeaseExecutor = null;
+        }
+
+        if (vmLeaseAlertExecutor != null) {
+            logger.debug("Shutting down lease alert executor");
+            vmLeaseAlertExecutor.shutdown();
+            vmLeaseAlertExecutor = null;
+        }
+    }
+
+    class VMLeaseSchedulerTask extends ManagedContextRunnable {
+        @Override
+        protected void runInContext() {
+            Date currentTimestamp = DateUtils.round(new Date(), 
Calendar.MINUTE);
+            String displayTime = 
DateUtil.displayDateInTimezone(DateUtil.GMT_TIMEZONE, currentTimestamp);
+            logger.debug("VMLeaseSchedulerTask is being called at {}", 
displayTime);
+            if (!InstanceLeaseEnabled.value()) {
+                logger.debug("Instance lease feature is disabled, no action is 
required");
+                return;
+            }
+
+            GlobalLock scanLock = 
GlobalLock.getInternLock("VMLeaseSchedulerTask");
+            try {
+                if 
(scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) {
+                    try {
+                        reallyRun();
+                    } finally {
+                        scanLock.unlock();
+                    }
+                }
+            } finally {
+                scanLock.releaseRef();
+            }
+        }
+    }
+
+    class VMLeaseAlertSchedulerTask extends ManagedContextRunnable {
+        @Override
+        protected void runInContext() {
+            // as feature is disabled, no action is required
+            if (!InstanceLeaseEnabled.value()) {
+                return;
+            }
+
+            GlobalLock scanLock = 
GlobalLock.getInternLock("VMLeaseAlertSchedulerTask");
+            try {
+                if 
(scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) {
+                    try {
+                        List<UserVmJoinVO> leaseExpiringForInstances = 
userVmJoinDao.listLeaseInstancesExpiringInDays(InstanceLeaseExpiryAlertDaysBefore.value().intValue());
+                        for (UserVmJoinVO instance : 
leaseExpiringForInstances) {
+                            String leaseExpiryEventMsg =  String.format("Lease 
expiring for for instanceId: %s with action: %s", instance.getUuid(), 
instance.getLeaseExpiryAction());

Review Comment:
   ```suggestion
                               String leaseExpiryEventMsg =  
String.format("Lease expiring for instance: %s (id: %s) with action: %s", 
instance.getName(), instance.getUuid(), instance.getLeaseExpiryAction());
   ```
   
   better to include instance name also in the message
   



-- 
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: commits-unsubscr...@cloudstack.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to