DaanHoogland commented on a change in pull request #3610: [WIP DO NOT MERGE] 
KVM: Rolling maintenance
URL: https://github.com/apache/cloudstack/pull/3610#discussion_r366415767
 
 

 ##########
 File path: 
server/src/main/java/com/cloud/resource/RollingMaintenanceManagerImpl.java
 ##########
 @@ -0,0 +1,488 @@
+// 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.resource;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.RollingMaintenanceAnswer;
+import com.cloud.agent.api.RollingMaintenanceCommand;
+import com.cloud.capacity.CapacityManager;
+import com.cloud.dc.ClusterDetailsDao;
+import com.cloud.dc.ClusterDetailsVO;
+import com.cloud.dc.ClusterVO;
+import com.cloud.dc.dao.ClusterDao;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.dc.dao.HostPodDao;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.AgentUnavailableException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.OperationTimedoutException;
+import com.cloud.host.Host;
+import com.cloud.host.HostVO;
+import com.cloud.host.Status;
+import com.cloud.host.dao.HostDao;
+import com.cloud.host.dao.HostTagsDao;
+import com.cloud.hypervisor.Hypervisor;
+import com.cloud.org.Cluster;
+import com.cloud.org.Grouping;
+import com.cloud.service.ServiceOfferingVO;
+import com.cloud.service.dao.ServiceOfferingDao;
+import com.cloud.utils.Pair;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.VMInstanceVO;
+import com.cloud.vm.VirtualMachineProfileImpl;
+import com.cloud.vm.dao.VMInstanceDao;
+import org.apache.cloudstack.affinity.AffinityGroupProcessor;
+import 
org.apache.cloudstack.api.command.admin.resource.StartRollingMaintenanceCmd;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.tuple.ImmutableTriple;
+import org.apache.commons.lang3.tuple.Triple;
+import org.apache.log4j.Logger;
+
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class RollingMaintenanceManagerImpl extends ManagerBase implements 
RollingMaintenanceManager {
+
+    @Inject
+    private HostPodDao podDao;
+    @Inject
+    private ClusterDao clusterDao;
+    @Inject
+    private DataCenterDao dataCenterDao;
+    @Inject
+    private HostDao hostDao;
+    @Inject
+    private AgentManager agentManager;
+    @Inject
+    private ResourceManager resourceManager;
+    @Inject
+    private CapacityManager capacityManager;
+    @Inject
+    private VMInstanceDao vmInstanceDao;
+    @Inject
+    private ServiceOfferingDao serviceOfferingDao;
+    @Inject
+    private ClusterDetailsDao clusterDetailsDao;
+    @Inject
+    private HostTagsDao hostTagsDao;
+
+    protected List<AffinityGroupProcessor> _affinityProcessors;
+
+    public void setAffinityGroupProcessors(List<AffinityGroupProcessor> 
affinityProcessors) {
+        _affinityProcessors = affinityProcessors;
+    }
+
+    public static final Logger s_logger = 
Logger.getLogger(RollingMaintenanceManagerImpl.class.getName());
+
+    private static final String unsopportedHypervisorErrorMsg = "Rolling 
maintenance is currently supported on KVM only";
+
+    private Pair<ResourceType, List<Long>> getResourceTypeAndIdPair(List<Long> 
podIds, List<Long> clusterIds, List<Long> zoneIds, List<Long> hostIds) {
+        Pair<ResourceType, List<Long>> pair = 
CollectionUtils.isNotEmpty(podIds) ? new Pair<>(ResourceType.Pod, podIds) :
+               CollectionUtils.isNotEmpty(clusterIds) ? new 
Pair<>(ResourceType.Cluster, clusterIds) :
+               CollectionUtils.isNotEmpty(zoneIds) ? new 
Pair<>(ResourceType.Zone, zoneIds) :
+               CollectionUtils.isNotEmpty(hostIds) ? new 
Pair<>(ResourceType.Host, hostIds) : null;
+        if (pair == null) {
+            throw new CloudRuntimeException("Parameters podId, clusterId, 
zoneId, hostId are mutually exclusive, " +
+                    "please set only one of them");
+        }
+        return pair;
+    }
+
+    @Override
+    public boolean configure(String name, Map<String, Object> params) throws 
ConfigurationException {
+        return true;
+    }
+
+    private void updateCluster(long clusterId, String state) {
+        Cluster cluster = resourceManager.getCluster(clusterId);
+        if (cluster == null) {
+            throw new InvalidParameterValueException("Unable to find the 
cluster by id=" + clusterId);
+        }
+        resourceManager.updateCluster(cluster, "", "", state, "");
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_START_ROLLING_MAINTENANCE, 
eventDescription = "starting rolling maintenance", async = true)
+    public Triple<Boolean, String, Pair<List<HostUpdated>, List<HostSkipped>>> 
startRollingMaintenance(StartRollingMaintenanceCmd cmd) {
+        Pair<ResourceType, List<Long>> pair = 
getResourceTypeAndIdPair(cmd.getPodIds(), cmd.getClusterIds(), 
cmd.getZoneIds(), cmd.getHostIds());
+        ResourceType type = pair.first();
+        List<Long> ids = pair.second();
+        int timeout = cmd.getTimeout() == null ? 
KvmRollingMaintenanceTimeout.value() : cmd.getTimeout();
+        String payload = cmd.getPayload();
+        Boolean forced = cmd.getForced();
+        Triple<Boolean, String, Boolean> result;
+
+        Set<Long> disabledClusters = new HashSet<>();
+        Map<Long, String> hostsToAvoidMaintenance = new HashMap<>();
+
+        List<HostUpdated> hostsUpdated = new ArrayList<>();
+        List<HostSkipped> hostsSkipped = new ArrayList<>();
+        try {
+            Map<Long, List<Host>> hostsByCluster = 
getHostsByClusterForRollingMaintenance(type, ids);
+            s_logger.debug("Checking hosts capacity before attempting rolling 
maintenance");
+            performCapacityChecks(hostsByCluster, forced);
+            s_logger.debug("Attempting pre-flight stages on each host before 
starting rolling maintenance");
+            performPreFlightChecks(hostsByCluster, timeout, payload, forced, 
hostsToAvoidMaintenance);
+
+            for (Long clusterId : hostsByCluster.keySet()) {
+                Cluster cluster = resourceManager.getCluster(clusterId);
+                // Disable cluster (if hasn't been disabled yet)
+                if (cluster.getAllocationState() == 
Grouping.AllocationState.Enabled && !disabledClusters.contains(clusterId)) {
+                    updateCluster(clusterId, "Disabled");
+                    disabledClusters.add(clusterId);
+                }
+
+                List<Host> hosts = hostsByCluster.get(clusterId);
+                for (Host host : hosts) {
+                    if (!isMaintenanceScriptDefinedOnHost(host)) {
+                        hostsSkipped.add(new HostSkipped(host, "There is no 
maintenance script on the host"));
+                        continue;
+                    }
+                    result = performStageOnHost(host, Stage.PreMaintenance, 
timeout, payload, forced);
+                    if (result.getRight() && 
!hostsToAvoidMaintenance.containsKey(host.getId())) {
+                        s_logger.debug("Host " + host.getId() + " added to the 
avoid maintenance set");
+                        hostsToAvoidMaintenance.put(host.getId(), 
"Pre-maintenance stage set to avoid maintenance");
+                    }
+                    if (!result.getLeft()) {
+                        if (forced) {
+                            String msg = "Pre-maintenance script failed: " + 
result.getMiddle();
+                            hostsSkipped.add(new HostSkipped(host, msg));
+                            continue;
+                        }
+                        return new ImmutableTriple<>(result.getLeft(), 
result.getMiddle(), new Pair<>(hostsUpdated, hostsSkipped));
+                    }
+
+                    if (hostsToAvoidMaintenance.containsKey(host.getId())) {
+                        s_logger.debug("Host " + host.getId() + " is not being 
put into maintenance, skipping it");
+                        HostSkipped hostSkipped = new HostSkipped(host, 
hostsToAvoidMaintenance.get(host.getId()));
+                        hostsSkipped.add(hostSkipped);
+                        continue;
+                    }
+
+                    Pair<Boolean, String> capacityCheckBeforeMaintenance = 
performCapacityChecksBeforeHostInMaintenance(host, cluster);
+                    if (!capacityCheckBeforeMaintenance.first()) {
+                        String errorMsg = "Capacity check failed for host " + 
host.getUuid() + ": " + capacityCheckBeforeMaintenance.second();
+                        if (forced) {
+                            s_logger.info("Skipping host " + host.getUuid() + 
" as: " + errorMsg);
+                            hostsSkipped.add(new HostSkipped(host, errorMsg));
+                            continue;
+                        }
+                        return new ImmutableTriple<>(false, 
capacityCheckBeforeMaintenance.second(), new Pair<>(hostsUpdated, 
hostsSkipped));
+                    }
+                    Date startTime = new Date();
+                    s_logger.debug("Trying to set the host " + host.getId() + 
" into maintenance");
+                    resourceManager.maintain(host.getId());
+                    waitForHostInMaintenance(host.getId());
+
+                    result = performStageOnHost(host, Stage.Maintenance, 
timeout, payload, forced);
+                    if (!result.getLeft()) {
+                        if (forced) {
+                            String msg = "Maintenance script failed: " + 
result.getMiddle();
+                            hostsSkipped.add(new HostSkipped(host, msg));
+                            continue;
+                        }
+                        return new ImmutableTriple<>(result.getLeft(), 
result.getMiddle(), new Pair<>(hostsUpdated, hostsSkipped));
+                    }
+
+                    if (!resourceManager.cancelMaintenance(host.getId())) {
+                        String message = "Could not cancel maintenance on host 
" + host.getUuid();
+                        s_logger.error(message);
+                        throw new CloudRuntimeException(message);
+                    }
+                    Date endTime = new Date();
+
+                    HostUpdated hostUpdated = new HostUpdated(host, startTime, 
endTime);
+                    hostsUpdated.add(hostUpdated);
+
+                    result = performStageOnHost(host, Stage.PostMaintenance, 
timeout, payload, forced);
+                    if (!result.getLeft()) {
+                        if (forced) {
+                            String msg = "Post-maintenance script failed: " + 
result.getMiddle();
+                            hostsSkipped.add(new HostSkipped(host, msg));
+                            continue;
+                        }
+                        return new ImmutableTriple<>(result.getLeft(), 
result.getMiddle(), new Pair<>(hostsUpdated, hostsSkipped));
+                    }
+                }
+
+                // Enable back disabled cluster
+                if (cluster.getAllocationState() == 
Grouping.AllocationState.Disabled && disabledClusters.contains(clusterId)) {
+                    updateCluster(clusterId, "Enabled");
+                }
+            }
+        } catch (AgentUnavailableException | InterruptedException | 
CloudRuntimeException e) {
+            String err = "Error starting rolling maintenance: " + 
e.getMessage();
+            s_logger.error(err, e);
+            return new ImmutableTriple<>(false, err, new Pair<>(hostsUpdated, 
hostsSkipped));
+        } finally {
+            // Enable back disabled clusters
+            for (Long clusterId : disabledClusters) {
+                Cluster cluster = resourceManager.getCluster(clusterId);
+                if (cluster.getAllocationState() == 
Grouping.AllocationState.Disabled) {
+                    updateCluster(clusterId, "Enabled");
+                }
+            }
+        }
+        return new ImmutableTriple<>(true, "OK", new Pair<>(hostsUpdated, 
hostsSkipped));
+    }
 
 Review comment:
   123 lines is way to long to get it. please refactor into screen size chucks 
(i'm on an old terminal, or at least my head is!)

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to