shwstppr commented on code in PR #7397:
URL: https://github.com/apache/cloudstack/pull/7397#discussion_r1173711069


##########
server/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduleManagerImpl.java:
##########
@@ -0,0 +1,322 @@
+/*
+ * 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.schedule;
+
+import com.cloud.api.query.MutualExclusiveIdsManagerBase;
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.Pair;
+import com.cloud.utils.component.PluggableService;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import org.apache.cloudstack.api.command.user.vm.CreateVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.DeleteVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.ListVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.UpdateVMScheduleCmd;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.VMScheduleResponse;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.messagebus.MessageBus;
+import org.apache.cloudstack.vm.schedule.dao.VMScheduleDao;
+import org.apache.log4j.Logger;
+import org.springframework.scheduling.support.CronExpression;
+
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
+import java.util.TimeZone;
+
+public class VMScheduleManagerImpl extends MutualExclusiveIdsManagerBase 
implements VMScheduleManager, PluggableService {
+
+    private static Logger LOGGER = 
Logger.getLogger(VMScheduleManagerImpl.class);
+
+    @Inject
+    private VMScheduleDao vmScheduleDao;
+    @Inject
+    private VirtualMachineManager virtualMachineManager;
+    @Inject
+    private VMScheduler vmScheduler;
+    @Inject
+    private MessageBus messageBus;
+    @Inject
+    private AccountManager accountManager;
+
+    @Override
+    public List<Class<?>> getCommands() {
+        final List<Class<?>> cmdList = new ArrayList<>();
+        cmdList.add(CreateVMScheduleCmd.class);
+        cmdList.add(ListVMScheduleCmd.class);
+        cmdList.add(UpdateVMScheduleCmd.class);
+        cmdList.add(DeleteVMScheduleCmd.class);
+        return cmdList;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_VM_SCHEDULE_CREATE, 
eventDescription = "Creating VM Schedule")
+    public VMScheduleResponse createSchedule(CreateVMScheduleCmd cmd) {
+        VirtualMachine vm = virtualMachineManager.findById(cmd.getVmId());
+        accountManager.checkAccess(CallContext.current().getCallingAccount(), 
null, false, vm);
+        if (vm == null) {
+            throw new InvalidParameterValueException(String.format("Invalid 
value for vmId: %s", cmd.getVmId()));
+        }
+
+        VMSchedule.Action action = null;
+        if (cmd.getAction() != null) {
+            try {
+                action = 
VMSchedule.Action.valueOf(cmd.getAction().toUpperCase());
+            } catch (IllegalArgumentException exception) {
+                throw new 
InvalidParameterValueException(String.format("Invalid value for action: %s", 
cmd.getAction()));
+            }
+        }
+
+        Date startDate = cmd.getStartDate();
+        Date endDate = cmd.getEndDate();
+
+        validateStartDateEndDate(startDate, endDate);
+
+        CronExpression cronExpression = 
DateUtil.parseSchedule(cmd.getSchedule());
+
+        String cmdTimeZone = cmd.getTimeZone();
+        TimeZone timeZone = TimeZone.getTimeZone(cmdTimeZone);
+        String timeZoneId = timeZone.getID();
+
+        String description = null;
+        if (cmd.getDescription() == null || cmd.getDescription().isBlank()) {

Review Comment:
   ```suggestion
           if (StringUtils.isEmpty(cmd.getDescription())) {
   ```



##########
engine/schema/src/main/resources/META-INF/db/schema-41810to41900.sql:
##########
@@ -9,7 +9,7 @@
 --   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
+-- software distributed unde-r the License is distributed on an

Review Comment:
   unnecessary



##########
ui/public/locales/en.json:
##########
@@ -2626,6 +2632,7 @@
 "message.error.remove.nic": "There was an error",
 "message.error.remove.secondary.ipaddress": "There was an error removing the 
secondary IP Address",
 "message.error.remove.tungsten.routing.policy": "Removing Tungsten-Fabric 
Routing Policy from network failed",
+"message.error.remove.vm.schedule": "Removing VMSchedule failed",

Review Comment:
   ```suggestion
   "message.error.remove.vm.schedule": "Removing VM schedule failed",
   ```



##########
ui/src/views/compute/InstanceTab.vue:
##########
@@ -116,6 +116,11 @@
           :routerlinks="(record) => { return { name: '/securitygroups/' + 
record.id } }"
           :showSearch="false"/>
       </a-tab-pane>
+      <a-tab-pane :tab="$t('label.vm.schedules')" key="schedules" 
v-if="'listVMSchedule' in $store.getters.apis">

Review Comment:
   Maybe use label.schedules here as already on instance page



##########
ui/src/components/view/ListView.vue:
##########
@@ -86,6 +86,9 @@
             <router-link :to="{ path: $route.path + '/' + record.uuid, query: 
{ zoneid: $route.query.zoneid } }" v-else-if="record.uuid && 
$route.query.zoneid">{{ $t(text.toLowerCase()) }}</router-link>
             <router-link :to="{ path: $route.path }" v-else>{{ 
$t(text.toLowerCase()) }}</router-link>
           </span>
+          <span v-else-if="$route?.query?.tab === 'schedules'">

Review Comment:
   afik chaining doesn't work in html part
   ```suggestion
             <span v-else-if="$route && $route.query && $route.query.tab === 
'schedules'">
   ```



##########
server/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduleManagerImpl.java:
##########
@@ -0,0 +1,322 @@
+/*
+ * 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.schedule;
+
+import com.cloud.api.query.MutualExclusiveIdsManagerBase;
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.Pair;
+import com.cloud.utils.component.PluggableService;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import org.apache.cloudstack.api.command.user.vm.CreateVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.DeleteVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.ListVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.UpdateVMScheduleCmd;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.VMScheduleResponse;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.messagebus.MessageBus;
+import org.apache.cloudstack.vm.schedule.dao.VMScheduleDao;
+import org.apache.log4j.Logger;
+import org.springframework.scheduling.support.CronExpression;
+
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
+import java.util.TimeZone;
+
+public class VMScheduleManagerImpl extends MutualExclusiveIdsManagerBase 
implements VMScheduleManager, PluggableService {
+
+    private static Logger LOGGER = 
Logger.getLogger(VMScheduleManagerImpl.class);
+
+    @Inject
+    private VMScheduleDao vmScheduleDao;
+    @Inject
+    private VirtualMachineManager virtualMachineManager;
+    @Inject
+    private VMScheduler vmScheduler;
+    @Inject
+    private MessageBus messageBus;
+    @Inject
+    private AccountManager accountManager;
+
+    @Override
+    public List<Class<?>> getCommands() {
+        final List<Class<?>> cmdList = new ArrayList<>();
+        cmdList.add(CreateVMScheduleCmd.class);
+        cmdList.add(ListVMScheduleCmd.class);
+        cmdList.add(UpdateVMScheduleCmd.class);
+        cmdList.add(DeleteVMScheduleCmd.class);
+        return cmdList;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_VM_SCHEDULE_CREATE, 
eventDescription = "Creating VM Schedule")
+    public VMScheduleResponse createSchedule(CreateVMScheduleCmd cmd) {
+        VirtualMachine vm = virtualMachineManager.findById(cmd.getVmId());
+        accountManager.checkAccess(CallContext.current().getCallingAccount(), 
null, false, vm);
+        if (vm == null) {
+            throw new InvalidParameterValueException(String.format("Invalid 
value for vmId: %s", cmd.getVmId()));
+        }
+
+        VMSchedule.Action action = null;
+        if (cmd.getAction() != null) {
+            try {
+                action = 
VMSchedule.Action.valueOf(cmd.getAction().toUpperCase());
+            } catch (IllegalArgumentException exception) {
+                throw new 
InvalidParameterValueException(String.format("Invalid value for action: %s", 
cmd.getAction()));
+            }
+        }
+
+        Date startDate = cmd.getStartDate();
+        Date endDate = cmd.getEndDate();
+
+        validateStartDateEndDate(startDate, endDate);
+
+        CronExpression cronExpression = 
DateUtil.parseSchedule(cmd.getSchedule());
+
+        String cmdTimeZone = cmd.getTimeZone();
+        TimeZone timeZone = TimeZone.getTimeZone(cmdTimeZone);
+        String timeZoneId = timeZone.getID();
+
+        String description = null;
+        if (cmd.getDescription() == null || cmd.getDescription().isBlank()) {
+            description = String.format("%s - %s", action, 
DateUtil.getHumanReadableSchedule(cronExpression));
+        } else description = cmd.getDescription();
+
+        LOGGER.warn(String.format("Using timezone [%s] for running the 
schedule [%s] for VM [%s], as an equivalent of [%s].", cmd.getVmId(), 
cmd.getName(), cmd.getVmId(),
+                cmdTimeZone));
+
+        String finalDescription = description;
+        VMSchedule.Action finalAction = action;
+        return Transaction.execute((TransactionCallback<VMScheduleResponse>) 
status -> {
+            VMScheduleVO vmSchedule = vmScheduleDao.persist(new 
VMScheduleVO(cmd.getVmId(), cmd.getName(), finalDescription, 
cronExpression.toString(), timeZoneId, finalAction, startDate, endDate, 
cmd.getEnabled()));
+            vmScheduler.scheduleNextJob(vmSchedule);
+
+            return createResponse(vmSchedule);
+        });
+    }
+
+    @Override
+    public VMScheduleResponse createResponse(VMSchedule vmSchedule) {
+        VirtualMachine vm = 
virtualMachineManager.findById(vmSchedule.getVmId());
+        VMScheduleResponse response = new VMScheduleResponse();
+
+        response.setObjectName(VMSchedule.class.getSimpleName().toLowerCase());
+        response.setId(vmSchedule.getUuid());
+        response.setVmId(vm.getUuid());
+        response.setName(vmSchedule.getName());
+        response.setDescription(vmSchedule.getDescription());
+        response.setSchedule(vmSchedule.getSchedule());
+        response.setTimeZone(vmSchedule.getTimeZone());
+        response.setAction(vmSchedule.getAction());
+        response.setEnabled(vmSchedule.getEnabled());
+        response.setStartDate(vmSchedule.getStartDate());
+        response.setEndDate(vmSchedule.getEndDate());
+        return response;
+    }
+
+    @Override
+    public ListResponse<VMScheduleResponse> listSchedule(ListVMScheduleCmd 
cmd) {
+        Long id = cmd.getId();
+        Boolean enabled = cmd.getEnabled();
+        Long vmId = cmd.getVmId();
+
+        VirtualMachine vm = virtualMachineManager.findById(vmId);

Review Comment:
   Same as create method
   
   ```
   (local) 🍀 > list vmschedule 
virtualmachineid=b2bd4347-6157-485e-9422-936a509908de
   {
     "count": 1,
     "vmschedule": [
       {
         "action": "STOP",
         "description": "gfdgfd",
         "enabled": true,
         "id": "b1972d7e-62f2-4f01-854b-d89b6cc7fae5",
         "name": "gfdgfd",
         "schedule": "10 5 * * 1",
         "startdate": "2023-04-21T20:10:10+0530",
         "timezone": "UTC",
         "virtualmachineid": "b2bd4347-6157-485e-9422-936a509908de"
       }
     ]
   }
   ```



##########
server/src/main/java/org/apache/cloudstack/vm/schedule/VMSchedulerImpl.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * 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.schedule;
+
+import com.cloud.api.ApiGsonHelper;
+import com.cloud.event.ActionEventUtils;
+import com.cloud.event.EventTypes;
+import com.cloud.user.User;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.GlobalLock;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import com.google.common.primitives.Longs;
+import org.apache.cloudstack.api.ApiCommandResourceType;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.command.user.vm.RebootVMCmd;
+import org.apache.cloudstack.api.command.user.vm.StartVMCmd;
+import org.apache.cloudstack.api.command.user.vm.StopVMCmd;
+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.ManagedContextTimerTask;
+import org.apache.cloudstack.vm.schedule.dao.VMScheduleDao;
+import org.apache.cloudstack.vm.schedule.dao.VMScheduledJobDao;
+import org.apache.commons.lang.time.DateUtils;
+import org.apache.log4j.Logger;
+import org.springframework.scheduling.support.CronExpression;
+
+import javax.inject.Inject;
+import javax.persistence.EntityExistsException;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Timer;
+import java.util.TimerTask;
+
+public class VMSchedulerImpl extends ManagerBase implements VMScheduler {
+    private static Logger LOGGER = Logger.getLogger(VMSchedulerImpl.class);
+    @Inject
+    private VMScheduledJobDao vmScheduledJobDao;
+    @Inject
+    private VMScheduleDao vmScheduleDao;
+    @Inject
+    private VirtualMachineManager virtualMachineManager;
+    @Inject
+    private AsyncJobManager asyncJobManager;
+    private AsyncJobDispatcher asyncJobDispatcher;
+    private Timer vmSchedulerTimer;
+    private Date currentTimestamp;
+
+    public AsyncJobDispatcher getAsyncJobDispatcher() {
+        return asyncJobDispatcher;
+    }
+
+    public void setAsyncJobDispatcher(final AsyncJobDispatcher dispatcher) {
+        asyncJobDispatcher = dispatcher;
+    }
+
+    @Override
+    public void removeScheduledJobs(List<Long> vmScheduleIds) {
+        if (vmScheduleIds == null || vmScheduleIds.isEmpty()) {
+            LOGGER.debug("Removed 0 scheduled jobs");
+            return;
+        }
+        int rowsRemoved = 
vmScheduledJobDao.expungeJobsForSchedules(vmScheduleIds, null);
+        LOGGER.debug(String.format("Removed %s VM scheduled jobs", 
rowsRemoved));
+    }
+
+    @Override
+    public void updateScheduledJob(VMScheduleVO vmSchedule) {
+        removeScheduledJobs(Longs.asList(vmSchedule.getId()));
+        scheduleNextJob(vmSchedule);
+    }
+
+    public Date scheduleNextJob(Long vmScheduleId) {
+        VMScheduleVO vmSchedule = vmScheduleDao.findById(vmScheduleId);
+        if (vmSchedule != null) {
+            return scheduleNextJob(vmSchedule);
+        }
+        LOGGER.debug(String.format("VM Schedule [id=%s] is removed. Not 
scheduling next job.", vmScheduleId));
+        return null;
+    }
+
+    @Override
+    public Date scheduleNextJob(VMScheduleVO vmSchedule) {
+        if (!vmSchedule.getEnabled()) {
+            LOGGER.debug(String.format("VM Schedule [id=%s] for VM [id=%s] is 
disabled. Not scheduling next job.", vmSchedule.getUuid(), 
vmSchedule.getVmId()));
+            return null;
+        }
+
+        CronExpression cron = DateUtil.parseSchedule(vmSchedule.getSchedule());
+        Date startDate = vmSchedule.getStartDate();
+        Date endDate = vmSchedule.getEndDate();
+        VirtualMachine vm = 
virtualMachineManager.findById(vmSchedule.getVmId());
+
+        Date now = new Date();
+        if (endDate != null && now.after(endDate)) {
+            LOGGER.info(String.format("End time is less than current time. 
Disabling VM schedule [id=%s] for VM [id=%s].", vmSchedule.getUuid(), 
vmSchedule.getVmId()));
+            vmSchedule.setEnabled(false);
+            vmScheduleDao.persist(vmSchedule);
+            return null;
+        }
+
+        ZonedDateTime ts = null;
+        ZoneId tz = vmSchedule.getTimeZoneId();
+        if (startDate.after(now)) {
+            ts = cron.next(ZonedDateTime.ofInstant(startDate.toInstant(), tz));
+        } else {
+            ts = cron.next(ZonedDateTime.ofInstant(now.toInstant(), tz));
+        }
+        Date scheduledDateTime = Date.from(ts.toInstant());
+        VMScheduledJobVO scheduledJob = new 
VMScheduledJobVO(vmSchedule.getVmId(), vmSchedule.getId(), 
vmSchedule.getAction(), scheduledDateTime);
+        try {
+            vmScheduledJobDao.persist(scheduledJob);
+            ActionEventUtils.onScheduledActionEvent(User.UID_SYSTEM, 
vm.getAccountId(), EventTypes.EVENT_VM_SCHEDULE_SCHEDULED,
+                    String.format("Scheduled action (%s) [vmId: %s scheduleId: 
%s]  at %s", vmSchedule.getAction(), vm.getUuid(), vmSchedule.getUuid(), 
scheduledDateTime),
+                    vm.getId(), 
ApiCommandResourceType.VirtualMachine.toString(), true, 0);
+        } catch (EntityExistsException exception) {
+            LOGGER.debug("Job is already scheduled.");
+        }
+        return scheduledDateTime;
+    }
+
+    @Override
+    public boolean start() {
+
+        // Adding 1 minute to currentTimestamp to ensure that
+        // jobs which were to be run at current time, doesn't cause issues
+        currentTimestamp = DateUtils.addMinutes(new Date(), 1);
+
+        scheduleNextJobs();
+
+        final TimerTask schedulerPollTask = new ManagedContextTimerTask() {
+            @Override
+            protected void runInContext() {
+                try {
+                    poll(new Date());
+                } catch (final Throwable t) {
+                    LOGGER.warn("Catch throwable in VM scheduler ", t);
+                }
+            }
+        };
+
+        vmSchedulerTimer = new Timer("VMSchedulerPollTask");
+        /*
+         TODO: Check if we should use schedule or scheduleAtFixedRate here?
+          scheduleAtFixedRate can result in issues if the task is taking more 
than 1 minute
+          schedule might result in skipping of some scheduled jobs
+        */

Review Comment:
   Address todo or remove



##########
ui/src/views/compute/Schedules.vue:
##########
@@ -0,0 +1,412 @@
+// Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   Should this be called InstanceSchedules or something for clarity?



##########
engine/schema/src/main/java/org/apache/cloudstack/vm/schedule/dao/VMScheduleDaoImpl.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.schedule.dao;
+
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import org.apache.cloudstack.vm.schedule.VMScheduleVO;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import java.util.Date;
+import java.util.List;
+
+@Component
+public class VMScheduleDaoImpl extends GenericDaoBase<VMScheduleVO, Long> 
implements VMScheduleDao {
+    private static final Logger LOGGER = 
Logger.getLogger(VMScheduleDaoImpl.class);
+
+    @Override
+    public List<VMScheduleVO> listAllActiveSchedules() {
+        // TODO: Add check for time zone here.
+        // WHERE enabled = true AND (end_date IS NULL OR end_date < 
current_date)

Review Comment:
   Address todo or remove



##########
server/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduleManagerImpl.java:
##########
@@ -0,0 +1,322 @@
+/*
+ * 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.schedule;
+
+import com.cloud.api.query.MutualExclusiveIdsManagerBase;
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.Pair;
+import com.cloud.utils.component.PluggableService;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import org.apache.cloudstack.api.command.user.vm.CreateVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.DeleteVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.ListVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.UpdateVMScheduleCmd;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.VMScheduleResponse;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.messagebus.MessageBus;
+import org.apache.cloudstack.vm.schedule.dao.VMScheduleDao;
+import org.apache.log4j.Logger;
+import org.springframework.scheduling.support.CronExpression;
+
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
+import java.util.TimeZone;
+
+public class VMScheduleManagerImpl extends MutualExclusiveIdsManagerBase 
implements VMScheduleManager, PluggableService {
+
+    private static Logger LOGGER = 
Logger.getLogger(VMScheduleManagerImpl.class);
+
+    @Inject
+    private VMScheduleDao vmScheduleDao;
+    @Inject
+    private VirtualMachineManager virtualMachineManager;
+    @Inject
+    private VMScheduler vmScheduler;
+    @Inject
+    private MessageBus messageBus;
+    @Inject
+    private AccountManager accountManager;
+
+    @Override
+    public List<Class<?>> getCommands() {
+        final List<Class<?>> cmdList = new ArrayList<>();
+        cmdList.add(CreateVMScheduleCmd.class);
+        cmdList.add(ListVMScheduleCmd.class);
+        cmdList.add(UpdateVMScheduleCmd.class);
+        cmdList.add(DeleteVMScheduleCmd.class);
+        return cmdList;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_VM_SCHEDULE_CREATE, 
eventDescription = "Creating VM Schedule")
+    public VMScheduleResponse createSchedule(CreateVMScheduleCmd cmd) {
+        VirtualMachine vm = virtualMachineManager.findById(cmd.getVmId());
+        accountManager.checkAccess(CallContext.current().getCallingAccount(), 
null, false, vm);
+        if (vm == null) {
+            throw new InvalidParameterValueException(String.format("Invalid 
value for vmId: %s", cmd.getVmId()));
+        }
+
+        VMSchedule.Action action = null;
+        if (cmd.getAction() != null) {
+            try {
+                action = 
VMSchedule.Action.valueOf(cmd.getAction().toUpperCase());
+            } catch (IllegalArgumentException exception) {
+                throw new 
InvalidParameterValueException(String.format("Invalid value for action: %s", 
cmd.getAction()));
+            }
+        }
+
+        Date startDate = cmd.getStartDate();
+        Date endDate = cmd.getEndDate();
+
+        validateStartDateEndDate(startDate, endDate);
+
+        CronExpression cronExpression = 
DateUtil.parseSchedule(cmd.getSchedule());
+
+        String cmdTimeZone = cmd.getTimeZone();
+        TimeZone timeZone = TimeZone.getTimeZone(cmdTimeZone);
+        String timeZoneId = timeZone.getID();
+
+        String description = null;
+        if (cmd.getDescription() == null || cmd.getDescription().isBlank()) {
+            description = String.format("%s - %s", action, 
DateUtil.getHumanReadableSchedule(cronExpression));
+        } else description = cmd.getDescription();
+
+        LOGGER.warn(String.format("Using timezone [%s] for running the 
schedule [%s] for VM [%s], as an equivalent of [%s].", cmd.getVmId(), 
cmd.getName(), cmd.getVmId(),
+                cmdTimeZone));
+
+        String finalDescription = description;
+        VMSchedule.Action finalAction = action;
+        return Transaction.execute((TransactionCallback<VMScheduleResponse>) 
status -> {
+            VMScheduleVO vmSchedule = vmScheduleDao.persist(new 
VMScheduleVO(cmd.getVmId(), cmd.getName(), finalDescription, 
cronExpression.toString(), timeZoneId, finalAction, startDate, endDate, 
cmd.getEnabled()));
+            vmScheduler.scheduleNextJob(vmSchedule);
+
+            return createResponse(vmSchedule);
+        });
+    }
+
+    @Override
+    public VMScheduleResponse createResponse(VMSchedule vmSchedule) {
+        VirtualMachine vm = 
virtualMachineManager.findById(vmSchedule.getVmId());
+        VMScheduleResponse response = new VMScheduleResponse();
+
+        response.setObjectName(VMSchedule.class.getSimpleName().toLowerCase());
+        response.setId(vmSchedule.getUuid());
+        response.setVmId(vm.getUuid());
+        response.setName(vmSchedule.getName());
+        response.setDescription(vmSchedule.getDescription());
+        response.setSchedule(vmSchedule.getSchedule());
+        response.setTimeZone(vmSchedule.getTimeZone());
+        response.setAction(vmSchedule.getAction());
+        response.setEnabled(vmSchedule.getEnabled());
+        response.setStartDate(vmSchedule.getStartDate());
+        response.setEndDate(vmSchedule.getEndDate());
+        return response;
+    }
+
+    @Override
+    public ListResponse<VMScheduleResponse> listSchedule(ListVMScheduleCmd 
cmd) {
+        Long id = cmd.getId();
+        Boolean enabled = cmd.getEnabled();
+        Long vmId = cmd.getVmId();
+
+        VirtualMachine vm = virtualMachineManager.findById(vmId);
+        accountManager.checkAccess(CallContext.current().getCallingAccount(), 
null, false, vm);
+
+        VMSchedule.Action action = null;
+        if (cmd.getAction() != null) {
+            try {
+                action = VMSchedule.Action.valueOf(cmd.getAction());
+            } catch (IllegalArgumentException exception) {
+                throw new InvalidParameterValueException("Invalid value for 
action: " + cmd.getAction());
+            }
+        }
+
+        Filter searchFilter = new Filter(VMScheduleVO.class, "id", true, 
cmd.getStartIndex(), cmd.getPageSizeVal());
+        SearchBuilder<VMScheduleVO> sb = vmScheduleDao.createSearchBuilder();
+        sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+        sb.and("vm_id", sb.entity().getVmId(), SearchCriteria.Op.EQ);
+        sb.and("action", sb.entity().getAction(), SearchCriteria.Op.EQ);
+        sb.and("enabled", sb.entity().getEnabled(), SearchCriteria.Op.EQ);
+
+        SearchCriteria<VMScheduleVO> sc = sb.create();
+
+        if (id != null) {
+            sc.setParameters("id", id);
+        }
+        if (enabled != null) {
+            sc.setParameters("enabled", enabled);
+        }
+        if (action != null) {
+            sc.setParameters("action", action);
+        }
+        sc.setParameters("vm_id", vmId);
+
+        Pair<List<VMScheduleVO>, Integer> result = 
vmScheduleDao.searchAndCount(sc, searchFilter);
+        ListResponse<VMScheduleResponse> response = new ListResponse<>();
+        List<VMScheduleResponse> responsesList = new ArrayList<>();
+        for (VMSchedule vmSchedule : result.first()) {
+            responsesList.add(createResponse(vmSchedule));
+        }
+        response.setResponses(responsesList, result.second());
+        return response;
+    }
+
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_VM_SCHEDULE_UPDATE, 
eventDescription = "Updating VM Schedule")
+    public VMScheduleResponse updateSchedule(UpdateVMScheduleCmd cmd) {
+        Long id = cmd.getId();
+        VMScheduleVO vmSchedule = vmScheduleDao.findById(id);
+
+        if (vmSchedule == null) {
+            throw new CloudRuntimeException("VM schedule doesn't exist");
+        }
+
+        VirtualMachine vm = 
virtualMachineManager.findById(vmSchedule.getVmId());

Review Comment:
   user vm check if needed



##########
engine/schema/src/main/java/org/apache/cloudstack/vm/schedule/dao/VMScheduleDaoImpl.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.schedule.dao;
+
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import org.apache.cloudstack.vm.schedule.VMScheduleVO;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import java.util.Date;
+import java.util.List;
+
+@Component
+public class VMScheduleDaoImpl extends GenericDaoBase<VMScheduleVO, Long> 
implements VMScheduleDao {
+    private static final Logger LOGGER = 
Logger.getLogger(VMScheduleDaoImpl.class);
+
+    @Override
+    public List<VMScheduleVO> listAllActiveSchedules() {
+        // TODO: Add check for time zone here.
+        // WHERE enabled = true AND (end_date IS NULL OR end_date < 
current_date)
+        SearchBuilder<VMScheduleVO> sb = createSearchBuilder();
+        sb.and("enabled", sb.entity().getEnabled(), SearchCriteria.Op.EQ);
+        sb.and().op(sb.entity().getEndDate(), SearchCriteria.Op.NULL);
+        sb.or("end_date", sb.entity().getEndDate(), SearchCriteria.Op.LT);
+        sb.cp();
+
+        SearchCriteria<VMScheduleVO> sc = sb.create();
+        sc.setParameters("enabled", true);
+        sc.setParameters("end_date", new Date());
+        // TODO: Check if we need to take lock on schedules here.

Review Comment:
   same as start of the method



##########
engine/schema/src/main/resources/META-INF/db/schema-41810to41900.sql:
##########
@@ -131,3 +131,37 @@ CREATE VIEW `cloud`.`async_job_view` AS
             left join
         `cloud`.`autoscale_vmgroups` ON async_job.instance_id = 
autoscale_vmgroups.id;
 
+--TODO: Create indexes

Review Comment:
   Address



##########
server/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduleManagerImpl.java:
##########
@@ -0,0 +1,322 @@
+/*
+ * 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.schedule;
+
+import com.cloud.api.query.MutualExclusiveIdsManagerBase;
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.Pair;
+import com.cloud.utils.component.PluggableService;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import org.apache.cloudstack.api.command.user.vm.CreateVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.DeleteVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.ListVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.UpdateVMScheduleCmd;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.VMScheduleResponse;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.messagebus.MessageBus;
+import org.apache.cloudstack.vm.schedule.dao.VMScheduleDao;
+import org.apache.log4j.Logger;
+import org.springframework.scheduling.support.CronExpression;
+
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
+import java.util.TimeZone;
+
+public class VMScheduleManagerImpl extends MutualExclusiveIdsManagerBase 
implements VMScheduleManager, PluggableService {
+
+    private static Logger LOGGER = 
Logger.getLogger(VMScheduleManagerImpl.class);
+
+    @Inject
+    private VMScheduleDao vmScheduleDao;
+    @Inject
+    private VirtualMachineManager virtualMachineManager;
+    @Inject
+    private VMScheduler vmScheduler;
+    @Inject
+    private MessageBus messageBus;
+    @Inject
+    private AccountManager accountManager;
+
+    @Override
+    public List<Class<?>> getCommands() {
+        final List<Class<?>> cmdList = new ArrayList<>();
+        cmdList.add(CreateVMScheduleCmd.class);
+        cmdList.add(ListVMScheduleCmd.class);
+        cmdList.add(UpdateVMScheduleCmd.class);
+        cmdList.add(DeleteVMScheduleCmd.class);
+        return cmdList;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_VM_SCHEDULE_CREATE, 
eventDescription = "Creating VM Schedule")
+    public VMScheduleResponse createSchedule(CreateVMScheduleCmd cmd) {
+        VirtualMachine vm = virtualMachineManager.findById(cmd.getVmId());

Review Comment:
   This will give any VM and not just user vm.
   I was able to create a job for SSVM
   ```
   (local) 🦅 > create vmschedule name=gfdgfd description=gfdgfd schedule="10 5 
* * 1" timezone=UTC action=STOP 
virtualmachineid=b2bd4347-6157-485e-9422-936a509908de startdate="2023-04-21 
20:10:10" enabled=true
   {
     "vmschedule": {
       "action": "STOP",
       "description": "gfdgfd",
       "enabled": true,
       "id": "b1972d7e-62f2-4f01-854b-d89b6cc7fae5",
       "name": "gfdgfd",
       "schedule": "10 5 * * 1",
       "startdate": "2023-04-21T20:10:10+0530",
       "timezone": "UTC",
       "virtualmachineid": "b2bd4347-6157-485e-9422-936a509908de"
     }
   }
   (local) 🐒 > list systemvms id=b2bd4347-6157-485e-9422-936a509908de
   {
     "count": 1,
     "systemvm": [
       {
         "agentstate": "Up",
         "created": "2023-04-21T18:27:27+0530",
         "dns1": "10.147.28.6",
         "gateway": "192.168.2.1",
         "hasannotations": false,
         "hostcontrolstate": "Enabled",
         "hostid": "34bb6388-9674-45e6-a1c2-21c380cfc8d7",
         "hostname": "SimulatedAgent.288cd369-c7ff-46a5-924b-abe17d18c6a4",
         "hypervisor": "Simulator",
         "id": "b2bd4347-6157-485e-9422-936a509908de",
         "isdynamicallyscalable": false,
         "linklocalip": "169.254.224.254",
         "linklocalmacaddress": "0e:00:a9:fe:e0:fe",
         "linklocalnetmask": "255.255.0.0",
         "name": "s-1-VM",
         "podid": "dbfef4bd-ceb5-4d64-96fc-d9b014e42014",
         "podname": "POD0",
         "privateip": "172.16.15.147",
         "privatemacaddress": "1e:00:23:00:00:92",
         "privatenetmask": "255.255.255.0",
         "publicip": "192.168.2.2",
         "publicmacaddress": "1e:00:36:00:00:c8",
         "publicnetmask": "255.255.255.0",
         "state": "Running",
         "systemvmtype": "secondarystoragevm",
         "templateid": "00715843-e043-11ed-abc1-645d8651f45a",
         "templatename": "SystemVM Template (simulator)",
         "version": "4.19.0.0-SNAPSHOT",
         "zoneid": "f80d6c12-a17d-4ca9-bace-c5e4b1db6108",
         "zonename": "Sandbox-simulator"
       }
     ]
   }
   ```
   Use UserVmDao or Manager unless it is meant purposefully to allow all VMs



##########
server/src/main/java/org/apache/cloudstack/vm/schedule/VMScheduleManagerImpl.java:
##########
@@ -0,0 +1,322 @@
+/*
+ * 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.schedule;
+
+import com.cloud.api.query.MutualExclusiveIdsManagerBase;
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.Pair;
+import com.cloud.utils.component.PluggableService;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import org.apache.cloudstack.api.command.user.vm.CreateVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.DeleteVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.ListVMScheduleCmd;
+import org.apache.cloudstack.api.command.user.vm.UpdateVMScheduleCmd;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.VMScheduleResponse;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.messagebus.MessageBus;
+import org.apache.cloudstack.vm.schedule.dao.VMScheduleDao;
+import org.apache.log4j.Logger;
+import org.springframework.scheduling.support.CronExpression;
+
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
+import java.util.TimeZone;
+
+public class VMScheduleManagerImpl extends MutualExclusiveIdsManagerBase 
implements VMScheduleManager, PluggableService {
+
+    private static Logger LOGGER = 
Logger.getLogger(VMScheduleManagerImpl.class);
+
+    @Inject
+    private VMScheduleDao vmScheduleDao;
+    @Inject
+    private VirtualMachineManager virtualMachineManager;
+    @Inject
+    private VMScheduler vmScheduler;
+    @Inject
+    private MessageBus messageBus;
+    @Inject
+    private AccountManager accountManager;
+
+    @Override
+    public List<Class<?>> getCommands() {
+        final List<Class<?>> cmdList = new ArrayList<>();
+        cmdList.add(CreateVMScheduleCmd.class);
+        cmdList.add(ListVMScheduleCmd.class);
+        cmdList.add(UpdateVMScheduleCmd.class);
+        cmdList.add(DeleteVMScheduleCmd.class);
+        return cmdList;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_VM_SCHEDULE_CREATE, 
eventDescription = "Creating VM Schedule")
+    public VMScheduleResponse createSchedule(CreateVMScheduleCmd cmd) {
+        VirtualMachine vm = virtualMachineManager.findById(cmd.getVmId());
+        accountManager.checkAccess(CallContext.current().getCallingAccount(), 
null, false, vm);
+        if (vm == null) {
+            throw new InvalidParameterValueException(String.format("Invalid 
value for vmId: %s", cmd.getVmId()));
+        }
+
+        VMSchedule.Action action = null;
+        if (cmd.getAction() != null) {
+            try {
+                action = 
VMSchedule.Action.valueOf(cmd.getAction().toUpperCase());
+            } catch (IllegalArgumentException exception) {
+                throw new 
InvalidParameterValueException(String.format("Invalid value for action: %s", 
cmd.getAction()));
+            }
+        }
+
+        Date startDate = cmd.getStartDate();
+        Date endDate = cmd.getEndDate();
+
+        validateStartDateEndDate(startDate, endDate);
+
+        CronExpression cronExpression = 
DateUtil.parseSchedule(cmd.getSchedule());
+
+        String cmdTimeZone = cmd.getTimeZone();
+        TimeZone timeZone = TimeZone.getTimeZone(cmdTimeZone);
+        String timeZoneId = timeZone.getID();
+
+        String description = null;
+        if (cmd.getDescription() == null || cmd.getDescription().isBlank()) {
+            description = String.format("%s - %s", action, 
DateUtil.getHumanReadableSchedule(cronExpression));
+        } else description = cmd.getDescription();
+
+        LOGGER.warn(String.format("Using timezone [%s] for running the 
schedule [%s] for VM [%s], as an equivalent of [%s].", cmd.getVmId(), 
cmd.getName(), cmd.getVmId(),
+                cmdTimeZone));
+
+        String finalDescription = description;
+        VMSchedule.Action finalAction = action;
+        return Transaction.execute((TransactionCallback<VMScheduleResponse>) 
status -> {
+            VMScheduleVO vmSchedule = vmScheduleDao.persist(new 
VMScheduleVO(cmd.getVmId(), cmd.getName(), finalDescription, 
cronExpression.toString(), timeZoneId, finalAction, startDate, endDate, 
cmd.getEnabled()));
+            vmScheduler.scheduleNextJob(vmSchedule);
+
+            return createResponse(vmSchedule);
+        });
+    }
+
+    @Override
+    public VMScheduleResponse createResponse(VMSchedule vmSchedule) {
+        VirtualMachine vm = 
virtualMachineManager.findById(vmSchedule.getVmId());
+        VMScheduleResponse response = new VMScheduleResponse();
+
+        response.setObjectName(VMSchedule.class.getSimpleName().toLowerCase());
+        response.setId(vmSchedule.getUuid());
+        response.setVmId(vm.getUuid());
+        response.setName(vmSchedule.getName());
+        response.setDescription(vmSchedule.getDescription());
+        response.setSchedule(vmSchedule.getSchedule());
+        response.setTimeZone(vmSchedule.getTimeZone());
+        response.setAction(vmSchedule.getAction());
+        response.setEnabled(vmSchedule.getEnabled());
+        response.setStartDate(vmSchedule.getStartDate());
+        response.setEndDate(vmSchedule.getEndDate());
+        return response;
+    }
+
+    @Override
+    public ListResponse<VMScheduleResponse> listSchedule(ListVMScheduleCmd 
cmd) {
+        Long id = cmd.getId();
+        Boolean enabled = cmd.getEnabled();
+        Long vmId = cmd.getVmId();
+
+        VirtualMachine vm = virtualMachineManager.findById(vmId);
+        accountManager.checkAccess(CallContext.current().getCallingAccount(), 
null, false, vm);
+
+        VMSchedule.Action action = null;
+        if (cmd.getAction() != null) {
+            try {
+                action = VMSchedule.Action.valueOf(cmd.getAction());
+            } catch (IllegalArgumentException exception) {
+                throw new InvalidParameterValueException("Invalid value for 
action: " + cmd.getAction());
+            }
+        }
+
+        Filter searchFilter = new Filter(VMScheduleVO.class, "id", true, 
cmd.getStartIndex(), cmd.getPageSizeVal());
+        SearchBuilder<VMScheduleVO> sb = vmScheduleDao.createSearchBuilder();
+        sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+        sb.and("vm_id", sb.entity().getVmId(), SearchCriteria.Op.EQ);
+        sb.and("action", sb.entity().getAction(), SearchCriteria.Op.EQ);
+        sb.and("enabled", sb.entity().getEnabled(), SearchCriteria.Op.EQ);
+
+        SearchCriteria<VMScheduleVO> sc = sb.create();
+
+        if (id != null) {
+            sc.setParameters("id", id);
+        }
+        if (enabled != null) {
+            sc.setParameters("enabled", enabled);
+        }
+        if (action != null) {
+            sc.setParameters("action", action);
+        }
+        sc.setParameters("vm_id", vmId);
+
+        Pair<List<VMScheduleVO>, Integer> result = 
vmScheduleDao.searchAndCount(sc, searchFilter);
+        ListResponse<VMScheduleResponse> response = new ListResponse<>();
+        List<VMScheduleResponse> responsesList = new ArrayList<>();
+        for (VMSchedule vmSchedule : result.first()) {
+            responsesList.add(createResponse(vmSchedule));
+        }
+        response.setResponses(responsesList, result.second());
+        return response;
+    }
+
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_VM_SCHEDULE_UPDATE, 
eventDescription = "Updating VM Schedule")
+    public VMScheduleResponse updateSchedule(UpdateVMScheduleCmd cmd) {
+        Long id = cmd.getId();
+        VMScheduleVO vmSchedule = vmScheduleDao.findById(id);
+
+        if (vmSchedule == null) {
+            throw new CloudRuntimeException("VM schedule doesn't exist");
+        }
+
+        VirtualMachine vm = 
virtualMachineManager.findById(vmSchedule.getVmId());
+        accountManager.checkAccess(CallContext.current().getCallingAccount(), 
null, false, vm);
+
+        String name = cmd.getName();
+        CronExpression cronExpression = Objects.requireNonNullElse(
+                DateUtil.parseSchedule(cmd.getSchedule()),
+                DateUtil.parseSchedule(vmSchedule.getSchedule())
+        );
+
+        VMSchedule.Action action = null;
+        if (cmd.getAction() != null) {
+            try {
+                action = 
VMSchedule.Action.valueOf(cmd.getAction().toUpperCase());
+            } catch (IllegalArgumentException exception) {
+                throw new InvalidParameterValueException("Invalid value for 
action: " + cmd.getAction());
+            }
+        }
+
+        String description = cmd.getDescription();
+
+        String cmdTimeZone = cmd.getTimeZone();
+
+        Date startDate = Objects.requireNonNullElse(cmd.getStartDate(), 
vmSchedule.getStartDate());
+
+        Date endDate = cmd.getEndDate();
+        if (endDate == null && vmSchedule.getEndDate() != null) {
+            endDate = vmSchedule.getEndDate();
+        }
+
+        validateStartDateEndDate(startDate, endDate);
+
+        Boolean enabled = cmd.getEnabled();
+
+        if (name != null) {
+            vmSchedule.setName(name);
+        }
+        if (enabled != null) {
+            vmSchedule.setEnabled(enabled);
+        }
+        if (description != null) {
+            vmSchedule.setDescription(description);
+        }
+        if (endDate != null) {
+            vmSchedule.setEndDate(endDate);
+        }
+        if (action != null) {
+            vmSchedule.setAction(action);
+        }
+
+        vmSchedule.setStartDate(startDate);
+        if (cmdTimeZone != null) {
+            TimeZone timeZone = TimeZone.getTimeZone(cmdTimeZone);
+            String timeZoneId = timeZone.getID();
+            if (!timeZoneId.equals(cmdTimeZone)) {
+                LOGGER.warn(String.format("Using timezone [%s] for running the 
schedule [%s] for VM %s, as an equivalent of [%s].",
+                        timeZoneId, vmSchedule.getSchedule(), 
vmSchedule.getVmId(), cmdTimeZone));
+            }
+            vmSchedule.setTimeZone(timeZoneId);
+        }
+        vmSchedule.setSchedule(cronExpression.toString());
+
+        return Transaction.execute((TransactionCallback<VMScheduleResponse>) 
status -> {
+            vmScheduleDao.update(cmd.getId(), vmSchedule);
+            vmScheduler.updateScheduledJob(vmSchedule);
+            return createResponse(vmSchedule);
+        });
+    }
+
+    private void validateStartDateEndDate(Date startDate, Date endDate) {
+        Date now = new Date();
+        if (startDate.before(now)) {
+            throw new InvalidParameterValueException(String.format("Invalid 
value for start date. Start date [%s] can't be less than current time [%s].", 
startDate, now));
+        }
+
+        if (endDate != null) {
+            if (endDate.before(now)) {
+                throw new 
InvalidParameterValueException(String.format("Invalid value for end date. End 
date [%s] can't be less than current time [%s].", endDate, now));
+            }
+            if (endDate.before(startDate)) {
+                throw new 
InvalidParameterValueException(String.format("Invalid value for end date. End 
date [%s] can't be less than start date [%s].", endDate, startDate));
+            }
+        }
+    }
+
+    @Override
+    public long removeScheduleByVmId(long vmId, boolean expunge) {

Review Comment:
   Should this also publish `EVENT_VM_SCHEDULE_DELETE` event?



-- 
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