@Override
  public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException {
    TemplateProfile profile = super.prepare(cmd);

    if (profile.getZoneId() == null || profile.getZoneId() == -1) {
      List<DataCenterVO> dcs = _dcDao.listAllIncludingRemoved();
      for (DataCenterVO dc : dcs) {
        List<HostVO> pxeServers =
            _resourceMgr.listAllHostsInOneZoneByType(Host.Type.BaremetalPxe, dc.getId());
        if (pxeServers.size() == 0) {
          throw new CloudRuntimeException(
              "Please add PXE server before adding baremetal template in zone " + dc.getName());
        }
      }
    } else {
      List<HostVO> pxeServers =
          _resourceMgr.listAllHostsInOneZoneByType(Host.Type.BaremetalPxe, profile.getZoneId());
      if (pxeServers.size() == 0) {
        throw new CloudRuntimeException(
            "Please add PXE server before adding baremetal template in zone "
                + profile.getZoneId());
      }
    }

    return profile;
  }
  @Override
  public boolean prepareCreateTemplate(Long pxeServerId, UserVm vm, String templateUrl) {
    List<NicVO> nics = _nicDao.listByVmId(vm.getId());
    if (nics.size() != 1) {
      throw new CloudRuntimeException("Wrong nic number " + nics.size() + " of vm " + vm.getId());
    }

    /* use last host id when VM stopped */
    Long hostId = (vm.getHostId() == null ? vm.getLastHostId() : vm.getHostId());
    HostVO host = _hostDao.findById(hostId);
    DataCenterVO dc = _dcDao.findById(host.getDataCenterId());
    NicVO nic = nics.get(0);
    String mask = nic.getNetmask();
    String mac = nic.getMacAddress();
    String ip = nic.getIp4Address();
    String gateway = nic.getGateway();
    String dns = dc.getDns1();
    if (dns == null) {
      dns = dc.getDns2();
    }

    try {
      prepareCreateTemplateCommand cmd =
          new prepareCreateTemplateCommand(ip, mac, mask, gateway, dns, templateUrl);
      Answer ans = _agentMgr.send(pxeServerId, cmd);
      return ans.getResult();
    } catch (Exception e) {
      s_logger.debug("Prepare for creating baremetal template failed", e);
      return false;
    }
  }
  @Override
  public Network design(
      NetworkOffering offering, DeploymentPlan plan, Network network, Account owner) {
    if (offering.getTrafficType() != TrafficType.Public
        || (offering.getGuestIpType() != null
            && offering.getGuestIpType() != GuestIpType.Virtual)) {
      s_logger.trace("We only take care of Public Virtual Network");
      return null;
    }

    if (offering.getTrafficType() == TrafficType.Public) {
      NetworkVO ntwk =
          new NetworkVO(
              offering.getTrafficType(),
              offering.getGuestIpType(),
              Mode.Static,
              BroadcastDomainType.Vlan,
              offering.getId(),
              plan.getDataCenterId());
      DataCenterVO dc = _dcDao.findById(plan.getDataCenterId());
      ntwk.setDns1(dc.getDns1());
      ntwk.setDns2(dc.getDns2());
      return ntwk;
    } else {
      return null;
    }
  }
 private boolean isSecondaryStorageVmRequired(long dcId) {
   DataCenterVO dc = _dcDao.findById(dcId);
   _dcDao.loadDetails(dc);
   String ssvmReq = dc.getDetail(ZoneConfig.EnableSecStorageVm.key());
   if (ssvmReq != null) {
     return Boolean.parseBoolean(ssvmReq);
   }
   return true;
 }
  @Override
  public void scheduleRestartForVmsOnHost(final HostVO host) {

    if (host.getType() != Host.Type.Routing) {
      return;
    }
    s_logger.warn("Scheduling restart for VMs on host " + host.getId());

    final List<VMInstanceVO> vms = _instanceDao.listByHostId(host.getId());
    final DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());

    // send an email alert that the host is down
    StringBuilder sb = null;
    if ((vms != null) && !vms.isEmpty()) {
      sb = new StringBuilder();
      sb.append("  Starting HA on the following VMs: ");
      // collect list of vm names for the alert email
      VMInstanceVO vm = vms.get(0);
      if (vm.isHaEnabled()) {
        sb.append(" " + vm.getName());
      }
      for (int i = 1; i < vms.size(); i++) {
        vm = vms.get(i);
        if (vm.isHaEnabled()) {
          sb.append(" " + vm.getName());
        }
      }
    }

    // send an email alert that the host is down, include VMs
    HostPodVO podVO = _podDao.findById(host.getPodId());
    String hostDesc =
        "name: "
            + host.getName()
            + " (id:"
            + host.getId()
            + "), availability zone: "
            + dcVO.getName()
            + ", pod: "
            + podVO.getName();

    _alertMgr.sendAlert(
        AlertManager.ALERT_TYPE_HOST,
        host.getDataCenterId(),
        host.getPodId(),
        "Host is down, " + hostDesc,
        "Host [" + hostDesc + "] is down." + ((sb != null) ? sb.toString() : ""));

    for (final VMInstanceVO vm : vms) {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Notifying HA Mgr of to investigate vm " + vm.getId() + "-" + vm.getName());
      }
      scheduleRestart(vm, true);
    }
  }
  @Override
  public Long[] getScannablePools() {
    List<DataCenterVO> zones = _dcDao.listEnabledZones();

    Long[] dcIdList = new Long[zones.size()];
    int i = 0;
    for (DataCenterVO dc : zones) {
      dcIdList[i++] = dc.getId();
    }

    return dcIdList;
  }
  @Override
  public List<StoragePool> allocateToPool(
      DiskProfile dskCh,
      VirtualMachineProfile vmProfile,
      DeploymentPlan plan,
      ExcludeList avoid,
      int returnUpTo) {
    DataCenterVO dc = _dcDao.findById(plan.getDataCenterId());
    if (!dc.isLocalStorageEnabled()) {
      return null;
    }

    return super.allocateToPool(dskCh, vmProfile, plan, avoid, returnUpTo);
  }
  @Before
  public void testSetUp() {
    ComponentContext.initComponentsLifeCycle();

    PlannerHostReservationVO reservationVO =
        new PlannerHostReservationVO(200L, 1L, 2L, 3L, PlannerResourceUsage.Shared);
    Mockito.when(_plannerHostReserveDao.persist(Matchers.any(PlannerHostReservationVO.class)))
        .thenReturn(reservationVO);
    Mockito.when(_plannerHostReserveDao.findById(Matchers.anyLong())).thenReturn(reservationVO);
    Mockito.when(_affinityGroupVMMapDao.countAffinityGroupsForVm(Matchers.anyLong()))
        .thenReturn(0L);

    VMInstanceVO vm = new VMInstanceVO();
    Mockito.when(vmProfile.getVirtualMachine()).thenReturn(vm);

    Mockito.when(_dcDao.findById(Matchers.anyLong())).thenReturn(dc);
    Mockito.when(dc.getId()).thenReturn(dataCenterId);

    ClusterVO clusterVO = new ClusterVO();
    clusterVO.setHypervisorType(HypervisorType.XenServer.toString());
    Mockito.when(_clusterDao.findById(Matchers.anyLong())).thenReturn(clusterVO);

    Mockito.when(_planner.getName()).thenReturn("FirstFitPlanner");
    List<DeploymentPlanner> planners = new ArrayList<DeploymentPlanner>();
    planners.add(_planner);
    _dpm.setPlanners(planners);
  }
 // persist entry in template_zone_ref table. zoneId can be empty for
 // region-wide image store, in that case,
 // we will associate the template to all the zones.
 @Override
 public void associateTemplateToZone(long templateId, Long zoneId) {
   List<Long> dcs = new ArrayList<Long>();
   if (zoneId != null) {
     dcs.add(zoneId);
   } else {
     List<DataCenterVO> zones = _dcDao.listAll();
     for (DataCenterVO zone : zones) {
       dcs.add(zone.getId());
     }
   }
   for (Long id : dcs) {
     VMTemplateZoneVO tmpltZoneVO = _vmTemplateZoneDao.findByZoneTemplate(id, templateId);
     if (tmpltZoneVO == null) {
       tmpltZoneVO = new VMTemplateZoneVO(id, templateId, new Date());
       _vmTemplateZoneDao.persist(tmpltZoneVO);
     } else {
       tmpltZoneVO.setLastUpdated(new Date());
       _vmTemplateZoneDao.update(tmpltZoneVO.getId(), tmpltZoneVO);
     }
   }
 }
示例#10
0
 @Override
 public boolean downloadTemplateToStorage(VMTemplateVO template, Long zoneId) {
   List<DataCenterVO> dcs = new ArrayList<DataCenterVO>();
   if (zoneId == null) {
     dcs.addAll(_dcDao.listAll());
   } else {
     dcs.add(_dcDao.findById(zoneId));
   }
   long templateId = template.getId();
   boolean isPublic = template.isFeatured() || template.isPublicTemplate();
   for (DataCenterVO dc : dcs) {
     List<HostVO> ssHosts = _ssvmMgr.listAllTypesSecondaryStorageHostsInOneZone(dc.getId());
     for (HostVO ssHost : ssHosts) {
       if (isTemplateUpdateable(templateId, ssHost.getId())) {
         initiateTemplateDownload(templateId, ssHost);
         if (!isPublic) {
           break;
         }
       }
     }
   }
   return true;
 }
示例#11
0
  protected VMTemplateVO persistTemplate(TemplateProfile profile) {
    Long zoneId = profile.getZoneId();
    VMTemplateVO template =
        new VMTemplateVO(
            profile.getTemplateId(),
            profile.getName(),
            profile.getFormat(),
            profile.getIsPublic(),
            profile.getFeatured(),
            profile.getIsExtractable(),
            TemplateType.USER,
            profile.getUrl(),
            profile.getRequiresHVM(),
            profile.getBits(),
            profile.getAccountId(),
            profile.getCheckSum(),
            profile.getDisplayText(),
            profile.getPasswordEnabled(),
            profile.getGuestOsId(),
            profile.getBootable(),
            profile.getHypervisorType(),
            profile.getTemplateTag(),
            profile.getDetails());

    if (zoneId == null || zoneId == -1) {
      List<DataCenterVO> dcs = _dcDao.listAllIncludingRemoved();

      for (DataCenterVO dc : dcs) {
        _tmpltDao.addTemplateToZone(template, dc.getId());
      }
      template.setCrossZones(true);
    } else {
      _tmpltDao.addTemplateToZone(template, zoneId);
    }
    return template;
  }
  @Override
  public Host addTrafficMonitor(AddTrafficMonitorCmd cmd) {

    long zoneId = cmd.getZoneId();

    DataCenterVO zone = _dcDao.findById(zoneId);
    String zoneName;
    if (zone == null) {
      throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
    } else {
      zoneName = zone.getName();
    }

    List<HostVO> trafficMonitorsInZone =
        _resourceMgr.listAllHostsInOneZoneByType(Host.Type.TrafficMonitor, zoneId);
    if (trafficMonitorsInZone.size() != 0) {
      throw new InvalidParameterValueException(
          "Already added an traffic monitor in zone: " + zoneName);
    }

    URI uri;
    try {
      uri = new URI(cmd.getUrl());
    } catch (Exception e) {
      s_logger.debug(e);
      throw new InvalidParameterValueException(e.getMessage());
    }

    String ipAddress = uri.getHost();
    // String numRetries = params.get("numretries");
    // String timeout = params.get("timeout");

    TrafficSentinelResource resource = new TrafficSentinelResource();
    String guid =
        getTrafficMonitorGuid(zoneId, NetworkUsageResourceName.TrafficSentinel, ipAddress);

    Map<String, Object> hostParams = new HashMap<String, Object>();
    hostParams.put("zone", String.valueOf(zoneId));
    hostParams.put("ipaddress", ipAddress);
    hostParams.put("url", cmd.getUrl());
    hostParams.put("inclZones", (cmd.getInclZones() != null) ? cmd.getInclZones() : _TSinclZones);
    hostParams.put("exclZones", (cmd.getExclZones() != null) ? cmd.getExclZones() : _TSexclZones);
    hostParams.put("guid", guid);
    hostParams.put("name", guid);

    try {
      resource.configure(guid, hostParams);
    } catch (ConfigurationException e) {
      throw new CloudRuntimeException(e.getMessage());
    }

    Map<String, String> hostDetails = new HashMap<String, String>();
    hostDetails.put("url", cmd.getUrl());
    hostDetails.put("last_collection", "" + System.currentTimeMillis());
    if (cmd.getInclZones() != null) {
      hostDetails.put("inclZones", cmd.getInclZones());
    }
    if (cmd.getExclZones() != null) {
      hostDetails.put("exclZones", cmd.getExclZones());
    }

    Host trafficMonitor =
        _resourceMgr.addHost(zoneId, resource, Host.Type.TrafficMonitor, hostDetails);
    return trafficMonitor;
  }
  protected void createDb() {
    DataCenterVO dc =
        new DataCenterVO(
            UUID.randomUUID().toString(),
            "test",
            "8.8.8.8",
            null,
            "10.0.0.1",
            null,
            "10.0.0.1/24",
            null,
            null,
            NetworkType.Basic,
            null,
            null,
            true,
            true,
            null,
            null);
    dc = dcDao.persist(dc);
    dcId = dc.getId();

    HostPodVO pod =
        new HostPodVO(UUID.randomUUID().toString(), dc.getId(), "255.255.255.255", "", 8, "test");
    pod = podDao.persist(pod);
    podId = pod.getId();

    ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster");
    cluster.setHypervisorType(HypervisorType.XenServer.toString());
    cluster.setClusterType(ClusterType.CloudManaged);
    cluster.setManagedState(ManagedState.Managed);
    cluster = clusterDao.persist(cluster);
    clusterId = cluster.getId();

    DataStoreProvider provider =
        providerMgr.getDataStoreProvider("ancient primary data store provider");
    storage = new StoragePoolVO();
    storage.setDataCenterId(dcId);
    storage.setPodId(podId);
    storage.setPoolType(StoragePoolType.NetworkFilesystem);
    storage.setClusterId(clusterId);
    storage.setStatus(StoragePoolStatus.Up);
    storage.setScope(ScopeType.CLUSTER);
    storage.setAvailableBytes(1000);
    storage.setCapacityBytes(20000);
    storage.setHostAddress(UUID.randomUUID().toString());
    storage.setPath(UUID.randomUUID().toString());
    storage.setStorageProviderName(provider.getName());
    storage = storagePoolDao.persist(storage);
    storagePoolId = storage.getId();

    storageMgr.createCapacityEntry(storage.getId());

    diskOffering = new DiskOfferingVO();
    diskOffering.setDiskSize(500);
    diskOffering.setName("test-disk");
    diskOffering.setSystemUse(false);
    diskOffering.setUseLocalStorage(false);
    diskOffering.setCustomized(false);
    diskOffering.setRecreatable(false);
    diskOffering = diskOfferingDao.persist(diskOffering);
    diskOfferingId = diskOffering.getId();

    volume =
        new VolumeVO(
            Volume.Type.ROOT,
            "volume",
            dcId,
            1,
            1,
            diskOffering.getId(),
            diskOffering.getDiskSize());
    volume = volumeDao.persist(volume);
    volumeId = volume.getId();
  }
示例#14
0
  public void checkForAlerts() {

    recalculateCapacity();

    // abort if we can't possibly send an alert...
    if (_emailAlert == null) {
      return;
    }

    // Get all datacenters, pods and clusters in the system.
    List<DataCenterVO> dataCenterList = _dcDao.listAll();
    List<ClusterVO> clusterList = _clusterDao.listAll();
    List<HostPodVO> podList = _podDao.listAll();
    // Get capacity types at different levels
    List<Short> dataCenterCapacityTypes = getCapacityTypesAtZoneLevel();
    List<Short> podCapacityTypes = getCapacityTypesAtPodLevel();
    List<Short> clusterCapacityTypes = getCapacityTypesAtClusterLevel();

    // Generate Alerts for Zone Level capacities
    for (DataCenterVO dc : dataCenterList) {
      for (Short capacityType : dataCenterCapacityTypes) {
        List<SummedCapacity> capacity = new ArrayList<SummedCapacity>();
        capacity = _capacityDao.findCapacityBy(capacityType.intValue(), dc.getId(), null, null);

        if (capacityType == Capacity.CAPACITY_TYPE_SECONDARY_STORAGE) {
          capacity.add(getUsedStats(capacityType, dc.getId(), null, null));
        }
        if (capacity == null || capacity.size() == 0) {
          continue;
        }
        double totalCapacity = capacity.get(0).getTotalCapacity();
        double usedCapacity = capacity.get(0).getUsedCapacity();
        if (totalCapacity != 0
            && usedCapacity / totalCapacity > _capacityTypeThresholdMap.get(capacityType)) {
          generateEmailAlert(dc, null, null, totalCapacity, usedCapacity, capacityType);
        }
      }
    }

    // Generate Alerts for Pod Level capacities
    for (HostPodVO pod : podList) {
      for (Short capacityType : podCapacityTypes) {
        List<SummedCapacity> capacity =
            _capacityDao.findCapacityBy(
                capacityType.intValue(), pod.getDataCenterId(), pod.getId(), null);
        if (capacity == null || capacity.size() == 0) {
          continue;
        }
        double totalCapacity = capacity.get(0).getTotalCapacity();
        double usedCapacity = capacity.get(0).getUsedCapacity();
        if (totalCapacity != 0
            && usedCapacity / totalCapacity > _capacityTypeThresholdMap.get(capacityType)) {
          generateEmailAlert(
              ApiDBUtils.findZoneById(pod.getDataCenterId()),
              pod,
              null,
              totalCapacity,
              usedCapacity,
              capacityType);
        }
      }
    }

    // Generate Alerts for Cluster Level capacities
    for (ClusterVO cluster : clusterList) {
      for (Short capacityType : clusterCapacityTypes) {
        List<SummedCapacity> capacity = new ArrayList<SummedCapacity>();
        float overProvFactor = 1f;
        capacity =
            _capacityDao.findCapacityBy(
                capacityType.intValue(), cluster.getDataCenterId(), null, cluster.getId());

        if (capacityType == Capacity.CAPACITY_TYPE_STORAGE) {
          capacity.add(
              getUsedStats(
                  capacityType, cluster.getDataCenterId(), cluster.getPodId(), cluster.getId()));
        }
        if (capacity == null || capacity.size() == 0) {
          continue;
        }
        if (capacityType == Capacity.CAPACITY_TYPE_CPU) {
          overProvFactor = ApiDBUtils.getCpuOverprovisioningFactor();
        }

        double totalCapacity = capacity.get(0).getTotalCapacity() * overProvFactor;
        double usedCapacity =
            capacity.get(0).getUsedCapacity() + capacity.get(0).getReservedCapacity();
        if (totalCapacity != 0
            && usedCapacity / totalCapacity > _capacityTypeThresholdMap.get(capacityType)) {
          generateEmailAlert(
              ApiDBUtils.findZoneById(cluster.getDataCenterId()),
              ApiDBUtils.findPodById(cluster.getPodId()),
              cluster,
              totalCapacity,
              usedCapacity,
              capacityType);
        }
      }
    }
  }
  public Long migrate(final HaWorkVO work) {
    final long vmId = work.getInstanceId();

    final VirtualMachineGuru<VMInstanceVO> mgr = findManager(work.getType());

    VMInstanceVO vm = mgr.get(vmId);
    if (vm == null || vm.getRemoved() != null) {
      s_logger.debug("Unable to find the vm " + vmId);
      return null;
    }

    s_logger.info("Migrating vm: " + vm.toString());
    if (vm.getHostId() == null || vm.getHostId() != work.getHostId()) {
      s_logger.info("VM is not longer running on the current hostId");
      return null;
    }

    short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE;
    if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
      alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
    } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
      alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
    }

    HostVO fromHost = _hostDao.findById(vm.getHostId());
    String fromHostName = ((fromHost == null) ? "unknown" : fromHost.getName());
    HostVO toHost = null;
    if (work.getStep() == Step.Scheduled) {
      if (vm.getState() != State.Running) {
        s_logger.info(
            "VM's state is not ready for migration. "
                + vm.toString()
                + " State is "
                + vm.getState().toString());
        return (System.currentTimeMillis() >> 10) + _migrateRetryInterval;
      }

      DataCenterVO dcVO = _dcDao.findById(fromHost.getDataCenterId());
      HostPodVO podVO = _podDao.findById(fromHost.getPodId());

      try {
        toHost = mgr.prepareForMigration(vm);
        if (toHost == null) {
          if (s_logger.isDebugEnabled()) {
            s_logger.debug("Unable to find a host for migrating vm " + vmId);
          }
          _alertMgr.sendAlert(
              alertType,
              vm.getDataCenterId(),
              vm.getPodId(),
              "Unable to migrate vm "
                  + vm.getName()
                  + " from host "
                  + fromHostName
                  + " in zone "
                  + dcVO.getName()
                  + " and pod "
                  + podVO.getName(),
              "Unable to find a suitable host");
        }
      } catch (final InsufficientCapacityException e) {
        s_logger.warn("Unable to mgirate due to insufficient capacity " + vm.toString());
        _alertMgr.sendAlert(
            alertType,
            vm.getDataCenterId(),
            vm.getPodId(),
            "Unable to migrate vm "
                + vm.getName()
                + " from host "
                + fromHostName
                + " in zone "
                + dcVO.getName()
                + " and pod "
                + podVO.getName(),
            "Insufficient capacity");
      } catch (final StorageUnavailableException e) {
        s_logger.warn("Storage is unavailable: " + vm.toString());
        _alertMgr.sendAlert(
            alertType,
            vm.getDataCenterId(),
            vm.getPodId(),
            "Unable to migrate vm "
                + vm.getName()
                + " from host "
                + fromHostName
                + " in zone "
                + dcVO.getName()
                + " and pod "
                + podVO.getName(),
            "Storage is gone.");
      }

      if (toHost == null) {
        _agentMgr.maintenanceFailed(vm.getHostId());
        return null;
      }

      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Migrating from " + work.getHostId() + " to " + toHost.getId());
      }
      work.setStep(Step.Migrating);
      work.setHostId(toHost.getId());
      _haDao.update(work.getId(), work);
    }

    if (work.getStep() == Step.Migrating) {
      vm = mgr.get(vmId); // let's see if anything has changed.
      boolean migrated = false;
      if (vm == null
          || vm.getRemoved() != null
          || vm.getHostId() == null
          || !_itMgr.stateTransitTo(vm, Event.MigrationRequested, vm.getHostId())) {
        s_logger.info("Migration cancelled because state has changed: " + vm.toString());
      } else {
        try {
          boolean isWindows =
              _guestOSCategoryDao
                  .findById(_guestOSDao.findById(vm.getGuestOSId()).getCategoryId())
                  .getName()
                  .equalsIgnoreCase("Windows");
          MigrateCommand cmd =
              new MigrateCommand(vm.getInstanceName(), toHost.getPrivateIpAddress(), isWindows);
          Answer answer = _agentMgr.send(fromHost.getId(), cmd);
          if (answer != null && answer.getResult()) {
            migrated = true;
            _storageMgr.unshare(vm, fromHost);
            work.setStep(Step.Investigating);
            _haDao.update(work.getId(), work);
          }
        } catch (final AgentUnavailableException e) {
          s_logger.debug("host became unavailable");
        } catch (final OperationTimedoutException e) {
          s_logger.debug("operation timed out");
          if (e.isActive()) {
            scheduleRestart(vm, true);
          }
        }
      }

      if (!migrated) {
        s_logger.info("Migration was unsuccessful.  Cleaning up: " + vm.toString());

        DataCenterVO dcVO = _dcDao.findById(vm.getDataCenterId());
        HostPodVO podVO = _podDao.findById(vm.getPodId());
        _alertMgr.sendAlert(
            alertType,
            fromHost.getDataCenterId(),
            fromHost.getPodId(),
            "Unable to migrate vm "
                + vm.getName()
                + " from host "
                + fromHost.getName()
                + " in zone "
                + dcVO.getName()
                + " and pod "
                + podVO.getName(),
            "Migrate Command failed.  Please check logs.");

        _itMgr.stateTransitTo(vm, Event.MigrationFailedOnSource, toHost.getId());
        _agentMgr.maintenanceFailed(vm.getHostId());

        Command cleanup = mgr.cleanup(vm, null);
        _agentMgr.easySend(toHost.getId(), cleanup);
        _storageMgr.unshare(vm, toHost);

        return null;
      }
    }

    if (toHost == null) {
      toHost = _hostDao.findById(work.getHostId());
    }
    DataCenterVO dcVO = _dcDao.findById(toHost.getDataCenterId());
    HostPodVO podVO = _podDao.findById(toHost.getPodId());

    try {
      if (!mgr.completeMigration(vm, toHost)) {
        _alertMgr.sendAlert(
            alertType,
            toHost.getDataCenterId(),
            toHost.getPodId(),
            "Unable to migrate "
                + vmId
                + " to host "
                + toHost.getName()
                + " in zone "
                + dcVO.getName()
                + " and pod "
                + podVO.getName(),
            "Migration not completed");
        s_logger.warn("Unable to complete migration: " + vm.toString());
      } else {
        s_logger.info("Migration is complete: " + vm.toString());
      }
      return null;
    } catch (final AgentUnavailableException e) {
      s_logger.warn("Agent is unavailable for " + vm.toString());
    } catch (final OperationTimedoutException e) {
      s_logger.warn("Operation timed outfor " + vm.toString());
    }
    _itMgr.stateTransitTo(vm, Event.MigrationFailedOnDest, toHost.getId());
    return (System.currentTimeMillis() >> 10) + _migrateRetryInterval;
  }
  @Override
  public boolean finalizeCommandsOnStart(
      Commands cmds, VirtualMachineProfile<DomainRouterVO> profile) {
    DomainRouterVO elbVm = profile.getVirtualMachine();
    DataCenterVO dcVo = _dcDao.findById(elbVm.getDataCenterId());

    NicProfile controlNic = null;
    Long guestNetworkId = null;

    if (profile.getHypervisorType() == HypervisorType.VMware
        && dcVo.getNetworkType() == NetworkType.Basic) {
      // TODO this is a ugly to test hypervisor type here
      // for basic network mode, we will use the guest NIC for control NIC
      for (NicProfile nic : profile.getNics()) {
        if (nic.getTrafficType() == TrafficType.Guest && nic.getIp4Address() != null) {
          controlNic = nic;
          guestNetworkId = nic.getNetworkId();
        }
      }
    } else {
      for (NicProfile nic : profile.getNics()) {
        if (nic.getTrafficType() == TrafficType.Control && nic.getIp4Address() != null) {
          controlNic = nic;
        } else if (nic.getTrafficType() == TrafficType.Guest) {
          guestNetworkId = nic.getNetworkId();
        }
      }
    }

    if (controlNic == null) {
      s_logger.error("Control network doesn't exist for the ELB vm " + elbVm);
      return false;
    }

    cmds.addCommand(
        "checkSsh",
        new CheckSshCommand(profile.getInstanceName(), controlNic.getIp4Address(), 3922));

    // Re-apply load balancing rules
    List<LoadBalancerVO> lbs = _elbVmMapDao.listLbsForElbVm(elbVm.getId());
    List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>();
    for (LoadBalancerVO lb : lbs) {
      List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
      List<LbStickinessPolicy> policyList = _lbMgr.getStickinessPolicies(lb.getId());
      List<LbHealthCheckPolicy> hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId());
      LoadBalancingRule loadBalancing =
          new LoadBalancingRule(lb, dstList, policyList, hcPolicyList);
      lbRules.add(loadBalancing);
    }

    s_logger.debug(
        "Found "
            + lbRules.size()
            + " load balancing rule(s) to apply as a part of ELB vm "
            + elbVm
            + " start.");
    if (!lbRules.isEmpty()) {
      createApplyLoadBalancingRulesCommands(lbRules, elbVm, cmds, guestNetworkId);
    }

    return true;
  }
  protected Long restart(HaWorkVO work) {
    List<HaWorkVO> items = _haDao.listFutureHaWorkForVm(work.getInstanceId(), work.getId());
    if (items.size() > 0) {
      StringBuilder str =
          new StringBuilder(
              "Cancelling this work item because newer ones have been scheduled.  Work Ids = [");
      for (HaWorkVO item : items) {
        str.append(item.getId()).append(", ");
      }
      str.delete(str.length() - 2, str.length()).append("]");
      s_logger.info(str.toString());
      return null;
    }

    items = _haDao.listRunningHaWorkForVm(work.getInstanceId());
    if (items.size() > 0) {
      StringBuilder str =
          new StringBuilder(
              "Waiting because there's HA work being executed on an item currently.  Work Ids =[");
      for (HaWorkVO item : items) {
        str.append(item.getId()).append(", ");
      }
      str.delete(str.length() - 2, str.length()).append("]");
      s_logger.info(str.toString());
      return (System.currentTimeMillis() >> 10) + _investigateRetryInterval;
    }

    long vmId = work.getInstanceId();

    VMInstanceVO vm = _itMgr.findByIdAndType(work.getType(), work.getInstanceId());
    if (vm == null) {
      s_logger.info("Unable to find vm: " + vmId);
      return null;
    }

    s_logger.info("HA on " + vm);
    if (vm.getState() != work.getPreviousState() || vm.getUpdated() != work.getUpdateTime()) {
      s_logger.info(
          "VM "
              + vm
              + " has been changed.  Current State = "
              + vm.getState()
              + " Previous State = "
              + work.getPreviousState()
              + " last updated = "
              + vm.getUpdated()
              + " previous updated = "
              + work.getUpdateTime());
      return null;
    }

    short alertType = AlertManager.ALERT_TYPE_USERVM;
    if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
      alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER;
    } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
      alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY;
    } else if (VirtualMachine.Type.SecondaryStorageVm.equals(vm.getType())) {
      alertType = AlertManager.ALERT_TYPE_SSVM;
    }

    HostVO host = _hostDao.findById(work.getHostId());
    boolean isHostRemoved = false;
    if (host == null) {
      host = _hostDao.findByIdIncludingRemoved(work.getHostId());
      if (host != null) {
        s_logger.debug(
            "VM "
                + vm.toString()
                + " is now no longer on host "
                + work.getHostId()
                + " as the host is removed");
        isHostRemoved = true;
      }
    }

    DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
    HostPodVO podVO = _podDao.findById(host.getPodId());
    String hostDesc =
        "name: "
            + host.getName()
            + "(id:"
            + host.getId()
            + "), availability zone: "
            + dcVO.getName()
            + ", pod: "
            + podVO.getName();

    Boolean alive = null;
    if (work.getStep() == Step.Investigating) {
      if (!isHostRemoved) {
        if (vm.getHostId() == null || vm.getHostId() != work.getHostId()) {
          s_logger.info("VM " + vm.toString() + " is now no longer on host " + work.getHostId());
          return null;
        }

        Enumeration<Investigator> en = _investigators.enumeration();
        Investigator investigator = null;
        while (en.hasMoreElements()) {
          investigator = en.nextElement();
          alive = investigator.isVmAlive(vm, host);
          s_logger.info(investigator.getName() + " found " + vm + "to be alive? " + alive);
          if (alive != null) {
            break;
          }
        }
        boolean fenced = false;
        if (alive == null) {
          s_logger.debug("Fencing off VM that we don't know the state of");
          Enumeration<FenceBuilder> enfb = _fenceBuilders.enumeration();
          while (enfb.hasMoreElements()) {
            FenceBuilder fb = enfb.nextElement();
            Boolean result = fb.fenceOff(vm, host);
            s_logger.info("Fencer " + fb.getName() + " returned " + result);
            if (result != null && result) {
              fenced = true;
              break;
            }
          }
        } else if (!alive) {
          fenced = true;
        } else {
          s_logger.debug(
              "VM " + vm.getHostName() + " is found to be alive by " + investigator.getName());
          if (host.getStatus() == Status.Up) {
            s_logger.info(vm + " is alive and host is up. No need to restart it.");
            return null;
          } else {
            s_logger.debug("Rescheduling because the host is not up but the vm is alive");
            return (System.currentTimeMillis() >> 10) + _investigateRetryInterval;
          }
        }

        if (!fenced) {
          s_logger.debug("We were unable to fence off the VM " + vm);
          _alertMgr.sendAlert(
              alertType,
              vm.getDataCenterIdToDeployIn(),
              vm.getPodIdToDeployIn(),
              "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc,
              "Insufficient capacity to restart VM, name: "
                  + vm.getHostName()
                  + ", id: "
                  + vmId
                  + " which was running on host "
                  + hostDesc);
          return (System.currentTimeMillis() >> 10) + _restartRetryInterval;
        }

        try {
          _itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
        } catch (ResourceUnavailableException e) {
          assert false : "How do we hit this when force is true?";
          throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
        } catch (OperationTimedoutException e) {
          assert false : "How do we hit this when force is true?";
          throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
        } catch (ConcurrentOperationException e) {
          assert false : "How do we hit this when force is true?";
          throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
        }

        work.setStep(Step.Scheduled);
        _haDao.update(work.getId(), work);
      } else {
        s_logger.debug(
            "How come that HA step is Investigating and the host is removed? Calling forced Stop on Vm anyways");
        try {
          _itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
        } catch (ResourceUnavailableException e) {
          assert false : "How do we hit this when force is true?";
          throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
        } catch (OperationTimedoutException e) {
          assert false : "How do we hit this when force is true?";
          throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
        } catch (ConcurrentOperationException e) {
          assert false : "How do we hit this when force is true?";
          throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
        }
      }
    }

    vm = _itMgr.findByIdAndType(vm.getType(), vm.getId());

    if (!_forceHA && !vm.isHaEnabled()) {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("VM is not HA enabled so we're done.");
      }
      return null; // VM doesn't require HA
    }

    if (!_storageMgr.canVmRestartOnAnotherServer(vm.getId())) {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("VM can not restart on another server.");
      }
      return null;
    }

    if (work.getTimesTried() > _maxRetries) {
      s_logger.warn("Retried to max times so deleting: " + vmId);
      return null;
    }

    try {
      VMInstanceVO started =
          _itMgr.advanceStart(
              vm,
              new HashMap<VirtualMachineProfile.Param, Object>(),
              _accountMgr.getSystemUser(),
              _accountMgr.getSystemAccount());
      if (started != null) {
        s_logger.info("VM is now restarted: " + vmId + " on " + started.getHostId());
        return null;
      }

      if (s_logger.isDebugEnabled()) {
        s_logger.debug(
            "Rescheduling VM " + vm.toString() + " to try again in " + _restartRetryInterval);
      }
    } catch (final InsufficientCapacityException e) {
      s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
      _alertMgr.sendAlert(
          alertType,
          vm.getDataCenterIdToDeployIn(),
          vm.getPodIdToDeployIn(),
          "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc,
          "Insufficient capacity to restart VM, name: "
              + vm.getHostName()
              + ", id: "
              + vmId
              + " which was running on host "
              + hostDesc);
    } catch (final ResourceUnavailableException e) {
      s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
      _alertMgr.sendAlert(
          alertType,
          vm.getDataCenterIdToDeployIn(),
          vm.getPodIdToDeployIn(),
          "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc,
          "The Storage is unavailable for trying to restart VM, name: "
              + vm.getHostName()
              + ", id: "
              + vmId
              + " which was running on host "
              + hostDesc);
    } catch (ConcurrentOperationException e) {
      s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
      _alertMgr.sendAlert(
          alertType,
          vm.getDataCenterIdToDeployIn(),
          vm.getPodIdToDeployIn(),
          "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc,
          "The Storage is unavailable for trying to restart VM, name: "
              + vm.getHostName()
              + ", id: "
              + vmId
              + " which was running on host "
              + hostDesc);
    } catch (OperationTimedoutException e) {
      s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
      _alertMgr.sendAlert(
          alertType,
          vm.getDataCenterIdToDeployIn(),
          vm.getPodIdToDeployIn(),
          "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc,
          "The Storage is unavailable for trying to restart VM, name: "
              + vm.getHostName()
              + ", id: "
              + vmId
              + " which was running on host "
              + hostDesc);
    }
    vm = _itMgr.findByIdAndType(vm.getType(), vm.getId());
    work.setUpdateTime(vm.getUpdated());
    work.setPreviousState(vm.getState());
    return (System.currentTimeMillis() >> 10) + _restartRetryInterval;
  }
示例#18
0
  @Test(priority = -1)
  public void setUp() {
    ComponentContext.initComponentsLifeCycle();

    host = hostDao.findByGuid(this.getHostGuid());
    if (host != null) {
      dcId = host.getDataCenterId();
      clusterId = host.getClusterId();
      podId = host.getPodId();
      return;
    }
    // create data center
    DataCenterVO dc =
        new DataCenterVO(
            UUID.randomUUID().toString(),
            "test",
            "8.8.8.8",
            null,
            "10.0.0.1",
            null,
            "10.0.0.1/24",
            null,
            null,
            NetworkType.Basic,
            null,
            null,
            true,
            true,
            null,
            null);
    dc = dcDao.persist(dc);
    dcId = dc.getId();
    // create pod

    HostPodVO pod =
        new HostPodVO(
            UUID.randomUUID().toString(),
            dc.getId(),
            this.getHostGateway(),
            this.getHostCidr(),
            8,
            "test");
    pod = podDao.persist(pod);
    podId = pod.getId();
    // create xen cluster
    ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster");
    cluster.setHypervisorType(HypervisorType.XenServer.toString());
    cluster.setClusterType(ClusterType.CloudManaged);
    cluster.setManagedState(ManagedState.Managed);
    cluster = clusterDao.persist(cluster);
    clusterId = cluster.getId();
    // create xen host

    host = new HostVO(this.getHostGuid());
    host.setName("devcloud xen host");
    host.setType(Host.Type.Routing);
    host.setPrivateIpAddress(this.getHostIp());
    host.setDataCenterId(dc.getId());
    host.setVersion("6.0.1");
    host.setAvailable(true);
    host.setSetup(true);
    host.setPodId(podId);
    host.setLastPinged(0);
    host.setResourceState(ResourceState.Enabled);
    host.setHypervisorType(HypervisorType.XenServer);
    host.setClusterId(cluster.getId());

    host = hostDao.persist(host);

    imageStore = new ImageStoreVO();
    imageStore.setName("test");
    imageStore.setDataCenterId(dcId);
    imageStore.setProviderName("CloudStack ImageStore Provider");
    imageStore.setRole(DataStoreRole.Image);
    imageStore.setUrl(this.getSecondaryStorage());
    imageStore.setUuid(UUID.randomUUID().toString());
    imageStore = imageStoreDao.persist(imageStore);
  }
示例#19
0
  @Test(priority = -1)
  public void setUp() {
    ComponentContext.initComponentsLifeCycle();

    host = hostDao.findByGuid(this.getHostGuid());
    if (host != null) {
      dcId = host.getDataCenterId();
      clusterId = host.getClusterId();
      podId = host.getPodId();
      imageStore = this.imageStoreDao.findByName(imageStoreName);
    } else {
      // create data center
      DataCenterVO dc =
          new DataCenterVO(
              UUID.randomUUID().toString(),
              "test",
              "8.8.8.8",
              null,
              "10.0.0.1",
              null,
              "10.0.0.1/24",
              null,
              null,
              NetworkType.Basic,
              null,
              null,
              true,
              true,
              null,
              null);
      dc = dcDao.persist(dc);
      dcId = dc.getId();
      // create pod

      HostPodVO pod =
          new HostPodVO(
              UUID.randomUUID().toString(),
              dc.getId(),
              this.getHostGateway(),
              this.getHostCidr(),
              8,
              "test");
      pod = podDao.persist(pod);
      podId = pod.getId();
      // create xen cluster
      ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster");
      cluster.setHypervisorType(HypervisorType.VMware.toString());
      cluster.setClusterType(ClusterType.ExternalManaged);
      cluster.setManagedState(ManagedState.Managed);
      cluster = clusterDao.persist(cluster);
      clusterId = cluster.getId();

      // setup vcenter
      ClusterDetailsVO clusterDetailVO = new ClusterDetailsVO(cluster.getId(), "url", null);
      this.clusterDetailsDao.persist(clusterDetailVO);
      clusterDetailVO = new ClusterDetailsVO(cluster.getId(), "username", null);
      this.clusterDetailsDao.persist(clusterDetailVO);
      clusterDetailVO = new ClusterDetailsVO(cluster.getId(), "password", null);
      this.clusterDetailsDao.persist(clusterDetailVO);
      // create xen host

      host = new HostVO(this.getHostGuid());
      host.setName("devcloud vmware host");
      host.setType(Host.Type.Routing);
      host.setPrivateIpAddress(this.getHostIp());
      host.setDataCenterId(dc.getId());
      host.setVersion("6.0.1");
      host.setAvailable(true);
      host.setSetup(true);
      host.setPodId(podId);
      host.setLastPinged(0);
      host.setResourceState(ResourceState.Enabled);
      host.setHypervisorType(HypervisorType.VMware);
      host.setClusterId(cluster.getId());

      host = hostDao.persist(host);

      imageStore = new ImageStoreVO();
      imageStore.setName(imageStoreName);
      imageStore.setDataCenterId(dcId);
      imageStore.setProviderName("CloudStack ImageStore Provider");
      imageStore.setRole(DataStoreRole.Image);
      imageStore.setUrl(this.getSecondaryStorage());
      imageStore.setUuid(UUID.randomUUID().toString());
      imageStore.setProtocol("nfs");
      imageStore = imageStoreDao.persist(imageStore);
    }

    image = new VMTemplateVO();
    image.setTemplateType(TemplateType.USER);
    image.setUrl(this.getTemplateUrl());
    image.setUniqueName(UUID.randomUUID().toString());
    image.setName(UUID.randomUUID().toString());
    image.setPublicTemplate(true);
    image.setFeatured(true);
    image.setRequiresHvm(true);
    image.setBits(64);
    image.setFormat(Storage.ImageFormat.VHD);
    image.setEnablePassword(true);
    image.setEnableSshKey(true);
    image.setGuestOSId(1);
    image.setBootable(true);
    image.setPrepopulate(true);
    image.setCrossZones(true);
    image.setExtractable(true);

    image = imageDataDao.persist(image);

    /*
     * TemplateDataStoreVO templateStore = new TemplateDataStoreVO();
     *
     * templateStore.setDataStoreId(imageStore.getId());
     * templateStore.setDownloadPercent(100);
     * templateStore.setDownloadState(Status.DOWNLOADED);
     * templateStore.setDownloadUrl(imageStore.getUrl());
     * templateStore.setInstallPath(this.getImageInstallPath());
     * templateStore.setTemplateId(image.getId());
     * templateStoreDao.persist(templateStore);
     */

    DataStore store = this.dataStoreMgr.getDataStore(imageStore.getId(), DataStoreRole.Image);
    TemplateInfo template = templateFactory.getTemplate(image.getId(), DataStoreRole.Image);
    DataObject templateOnStore = store.create(template);
    TemplateObjectTO to = new TemplateObjectTO();
    to.setPath(this.getImageInstallPath());
    CopyCmdAnswer answer = new CopyCmdAnswer(to);
    templateOnStore.processEvent(Event.CreateOnlyRequested);
    templateOnStore.processEvent(Event.OperationSuccessed, answer);
  }
示例#20
0
  public TemplateProfile prepare(
      boolean isIso,
      Long userId,
      String name,
      String displayText,
      Integer bits,
      Boolean passwordEnabled,
      Boolean requiresHVM,
      String url,
      Boolean isPublic,
      Boolean featured,
      Boolean isExtractable,
      String format,
      Long guestOSId,
      Long zoneId,
      HypervisorType hypervisorType,
      String chksum,
      Boolean bootable,
      String templateTag,
      Account templateOwner,
      Map details)
      throws ResourceAllocationException {
    // Long accountId = null;
    // parameters verification

    if (isPublic == null) {
      isPublic = Boolean.FALSE;
    }

    if (zoneId.longValue() == -1) {
      zoneId = null;
    }

    if (isIso) {
      if (bootable == null) {
        bootable = Boolean.TRUE;
      }
      GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE);
      if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true) {
        throw new InvalidParameterValueException("Please pass a valid GuestOS Id");
      }
      if (bootable == false) {
        guestOSId = noneGuestOs.getId(); // Guest os id of None.
      }
    } else {
      if (bits == null) {
        bits = Integer.valueOf(64);
      }
      if (passwordEnabled == null) {
        passwordEnabled = false;
      }
      if (requiresHVM == null) {
        requiresHVM = true;
      }
    }

    if (isExtractable == null) {
      isExtractable = Boolean.FALSE;
    }

    boolean isAdmin =
        _accountDao.findById(templateOwner.getId()).getType() == Account.ACCOUNT_TYPE_ADMIN;

    if (!isAdmin && zoneId == null) {
      throw new InvalidParameterValueException("Please specify a valid zone Id.");
    }

    if (url.toLowerCase().contains("file://")) {
      throw new InvalidParameterValueException("File:// type urls are currently unsupported");
    }

    boolean allowPublicUserTemplates =
        Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates"));
    if (!isAdmin && !allowPublicUserTemplates && isPublic) {
      throw new InvalidParameterValueException("Only private templates/ISO can be created.");
    }

    if (!isAdmin || featured == null) {
      featured = Boolean.FALSE;
    }

    // If command is executed via 8096 port, set userId to the id of System
    // account (1)
    if (userId == null) {
      userId = Long.valueOf(1);
    }

    ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase());
    if (imgfmt == null) {
      throw new IllegalArgumentException(
          "Image format is incorrect "
              + format
              + ". Supported formats are "
              + EnumUtils.listValues(ImageFormat.values()));
    }

    // Check that the resource limit for templates/ISOs won't be exceeded
    UserVO user = _userDao.findById(userId);
    if (user == null) {
      throw new IllegalArgumentException("Unable to find user with id " + userId);
    }

    _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);

    if (templateOwner.getType() != Account.ACCOUNT_TYPE_ADMIN && zoneId == null) {
      throw new IllegalArgumentException("Only admins can create templates in all zones");
    }

    // If a zoneId is specified, make sure it is valid
    if (zoneId != null) {
      DataCenterVO zone = _dcDao.findById(zoneId);
      if (zone == null) {
        throw new IllegalArgumentException("Please specify a valid zone.");
      }
      Account caller = UserContext.current().getCaller();
      if (Grouping.AllocationState.Disabled == zone.getAllocationState()
          && !_accountMgr.isRootAdmin(caller.getType())) {
        throw new PermissionDeniedException(
            "Cannot perform this operation, Zone is currently disabled: " + zoneId);
      }
    }

    List<VMTemplateVO> systemvmTmplts = _tmpltDao.listAllSystemVMTemplates();
    for (VMTemplateVO template : systemvmTmplts) {
      if (template.getName().equalsIgnoreCase(name)
          || template.getDisplayText().equalsIgnoreCase(displayText)) {
        throw new IllegalArgumentException("Cannot use reserved names for templates");
      }
    }

    Long id = _tmpltDao.getNextInSequence(Long.class, "id");
    UserContext.current().setEventDetails("Id: " + id + " name: " + name);
    return new TemplateProfile(
        id,
        userId,
        name,
        displayText,
        bits,
        passwordEnabled,
        requiresHVM,
        url,
        isPublic,
        featured,
        isExtractable,
        imgfmt,
        guestOSId,
        zoneId,
        hypervisorType,
        templateOwner.getAccountName(),
        templateOwner.getDomainId(),
        templateOwner.getAccountId(),
        chksum,
        bootable,
        templateTag,
        details);
  }
示例#21
0
  private void generateEmailAlert(
      DataCenterVO dc,
      HostPodVO pod,
      ClusterVO cluster,
      double totalCapacity,
      double usedCapacity,
      short capacityType) {

    String msgSubject = null;
    String msgContent = null;
    String totalStr;
    String usedStr;
    String pctStr = formatPercent(usedCapacity / totalCapacity);
    short alertType = -1;
    Long podId = pod == null ? null : pod.getId();
    Long clusterId = cluster == null ? null : cluster.getId();

    switch (capacityType) {

        // Cluster Level
      case CapacityVO.CAPACITY_TYPE_MEMORY:
        msgSubject =
            "System Alert: Low Available Memory in cluster "
                + cluster.getName()
                + " pod "
                + pod.getName()
                + " of availablity zone "
                + dc.getName();
        totalStr = formatBytesToMegabytes(totalCapacity);
        usedStr = formatBytesToMegabytes(usedCapacity);
        msgContent =
            "System memory is low, total: "
                + totalStr
                + " MB, used: "
                + usedStr
                + " MB ("
                + pctStr
                + "%)";
        alertType = ALERT_TYPE_MEMORY;
        break;
      case CapacityVO.CAPACITY_TYPE_CPU:
        msgSubject =
            "System Alert: Low Unallocated CPU in cluster "
                + cluster.getName()
                + " pod "
                + pod.getName()
                + " of availablity zone "
                + dc.getName();
        totalStr = _dfWhole.format(totalCapacity);
        usedStr = _dfWhole.format(usedCapacity);
        msgContent =
            "Unallocated CPU is low, total: "
                + totalStr
                + " Mhz, used: "
                + usedStr
                + " Mhz ("
                + pctStr
                + "%)";
        alertType = ALERT_TYPE_CPU;
        break;
      case CapacityVO.CAPACITY_TYPE_STORAGE:
        msgSubject =
            "System Alert: Low Available Storage in cluster "
                + cluster.getName()
                + " pod "
                + pod.getName()
                + " of availablity zone "
                + dc.getName();
        totalStr = formatBytesToMegabytes(totalCapacity);
        usedStr = formatBytesToMegabytes(usedCapacity);
        msgContent =
            "Available storage space is low, total: "
                + totalStr
                + " MB, used: "
                + usedStr
                + " MB ("
                + pctStr
                + "%)";
        alertType = ALERT_TYPE_STORAGE;
        break;
      case CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED:
        msgSubject =
            "System Alert: Remaining unallocated Storage is low in cluster "
                + cluster.getName()
                + " pod "
                + pod.getName()
                + " of availablity zone "
                + dc.getName();
        totalStr = formatBytesToMegabytes(totalCapacity);
        usedStr = formatBytesToMegabytes(usedCapacity);
        msgContent =
            "Unallocated storage space is low, total: "
                + totalStr
                + " MB, allocated: "
                + usedStr
                + " MB ("
                + pctStr
                + "%)";
        alertType = ALERT_TYPE_STORAGE_ALLOCATED;
        break;
      case CapacityVO.CAPACITY_TYPE_LOCAL_STORAGE:
        msgSubject =
            "System Alert: Remaining unallocated Local Storage is low in cluster "
                + cluster.getName()
                + " pod "
                + pod.getName()
                + " of availablity zone "
                + dc.getName();
        totalStr = formatBytesToMegabytes(totalCapacity);
        usedStr = formatBytesToMegabytes(usedCapacity);
        msgContent =
            "Unallocated storage space is low, total: "
                + totalStr
                + " MB, allocated: "
                + usedStr
                + " MB ("
                + pctStr
                + "%)";
        alertType = ALERT_TYPE_LOCAL_STORAGE;
        break;

        // Pod Level
      case CapacityVO.CAPACITY_TYPE_PRIVATE_IP:
        msgSubject =
            "System Alert: Number of unallocated private IPs is low in pod "
                + pod.getName()
                + " of availablity zone "
                + dc.getName();
        totalStr = Double.toString(totalCapacity);
        usedStr = Double.toString(usedCapacity);
        msgContent =
            "Number of unallocated private IPs is low, total: "
                + totalStr
                + ", allocated: "
                + usedStr
                + " ("
                + pctStr
                + "%)";
        alertType = ALERT_TYPE_PRIVATE_IP;
        break;

        // Zone Level
      case CapacityVO.CAPACITY_TYPE_SECONDARY_STORAGE:
        msgSubject =
            "System Alert: Low Available Secondary Storage in availablity zone " + dc.getName();
        totalStr = formatBytesToMegabytes(totalCapacity);
        usedStr = formatBytesToMegabytes(usedCapacity);
        msgContent =
            "Available secondary storage space is low, total: "
                + totalStr
                + " MB, used: "
                + usedStr
                + " MB ("
                + pctStr
                + "%)";
        alertType = ALERT_TYPE_SECONDARY_STORAGE;
        break;
      case CapacityVO.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP:
        msgSubject =
            "System Alert: Number of unallocated virtual network public IPs is low in availablity zone "
                + dc.getName();
        totalStr = Double.toString(totalCapacity);
        usedStr = Double.toString(usedCapacity);
        msgContent =
            "Number of unallocated public IPs is low, total: "
                + totalStr
                + ", allocated: "
                + usedStr
                + " ("
                + pctStr
                + "%)";
        alertType = ALERT_TYPE_VIRTUAL_NETWORK_PUBLIC_IP;
        break;
      case CapacityVO.CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP:
        msgSubject =
            "System Alert: Number of unallocated direct attached public IPs is low in availablity zone "
                + dc.getName();
        totalStr = Double.toString(totalCapacity);
        usedStr = Double.toString(usedCapacity);
        msgContent =
            "Number of unallocated direct attached public IPs is low, total: "
                + totalStr
                + ", allocated: "
                + usedStr
                + " ("
                + pctStr
                + "%)";
        alertType = ALERT_TYPE_DIRECT_ATTACHED_PUBLIC_IP;
        break;
      case CapacityVO.CAPACITY_TYPE_VLAN:
        msgSubject =
            "System Alert: Number of unallocated VLANs is low in availablity zone " + dc.getName();
        totalStr = Double.toString(totalCapacity);
        usedStr = Double.toString(usedCapacity);
        msgContent =
            "Number of unallocated VLANs is low, total: "
                + totalStr
                + ", allocated: "
                + usedStr
                + " ("
                + pctStr
                + "%)";
        alertType = ALERT_TYPE_VLAN;
        break;
    }

    try {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug(msgSubject);
        s_logger.debug(msgContent);
      }
      _emailAlert.sendAlert(alertType, dc.getId(), podId, clusterId, msgSubject, msgContent);
    } catch (Exception ex) {
      s_logger.error("Exception in CapacityChecker", ex);
    }
  }
示例#22
0
  @Override
  @DB
  public void recalculateCapacity() {
    // FIXME: the right way to do this is to register a listener (see RouterStatsListener,
    // VMSyncListener)
    //        for the vm sync state.  The listener model has connects/disconnects to keep things in
    // sync much better
    //        than this model right now, so when a VM is started, we update the amount allocated,
    // and when a VM
    //        is stopped we updated the amount allocated, and when VM sync reports a changed state,
    // we update
    //        the amount allocated.  Hopefully it's limited to 3 entry points and will keep the
    // amount allocated
    //        per host accurate.

    try {

      if (s_logger.isDebugEnabled()) {
        s_logger.debug("recalculating system capacity");
        s_logger.debug("Executing cpu/ram capacity update");
      }

      // Calculate CPU and RAM capacities
      // 	get all hosts...even if they are not in 'UP' state
      List<HostVO> hosts = _resourceMgr.listAllHostsInAllZonesByType(Host.Type.Routing);
      for (HostVO host : hosts) {
        _capacityMgr.updateCapacityForHost(host);
      }

      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Done executing cpu/ram capacity update");
        s_logger.debug("Executing storage capacity update");
      }
      // Calculate storage pool capacity
      List<StoragePoolVO> storagePools = _storagePoolDao.listAll();
      for (StoragePoolVO pool : storagePools) {
        long disk = 0l;
        Pair<Long, Long> sizes = _volumeDao.getCountAndTotalByPool(pool.getId());
        disk = sizes.second();
        if (pool.isShared()) {
          _storageMgr.createCapacityEntry(pool, Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, disk);
        } else {
          _storageMgr.createCapacityEntry(pool, Capacity.CAPACITY_TYPE_LOCAL_STORAGE, disk);
        }
      }

      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Done executing storage capacity update");
        s_logger.debug("Executing capacity updates public ip and Vlans");
      }

      List<DataCenterVO> datacenters = _dcDao.listAll();
      for (DataCenterVO datacenter : datacenters) {
        long dcId = datacenter.getId();

        // NOTE
        // What happens if we have multiple vlans? Dashboard currently shows stats
        // with no filter based on a vlan
        // ideal way would be to remove out the vlan param, and filter only on dcId
        // implementing the same

        // Calculate new Public IP capacity for Virtual Network
        if (datacenter.getNetworkType() == NetworkType.Advanced) {
          createOrUpdateIpCapacity(dcId, null, CapacityVO.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP);
        }

        // Calculate new Public IP capacity for Direct Attached Network
        createOrUpdateIpCapacity(dcId, null, CapacityVO.CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP);

        if (datacenter.getNetworkType() == NetworkType.Advanced) {
          // Calculate VLAN's capacity
          createOrUpdateVlanCapacity(dcId);
        }
      }

      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Done capacity updates for public ip and Vlans");
        s_logger.debug("Executing capacity updates for private ip");
      }

      // Calculate new Private IP capacity
      List<HostPodVO> pods = _podDao.listAll();
      for (HostPodVO pod : pods) {
        long podId = pod.getId();
        long dcId = pod.getDataCenterId();

        createOrUpdateIpCapacity(dcId, podId, CapacityVO.CAPACITY_TYPE_PRIVATE_IP);
      }

      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Done executing capacity updates for private ip");
        s_logger.debug("Done recalculating system capacity");
      }

    } catch (Throwable t) {
      s_logger.error("Caught exception in recalculating capacity", t);
    }
  }
  @Override
  public Map<? extends ServerResource, Map<String, String>> find(
      long dcId,
      Long podId,
      Long clusterId,
      URI url,
      String username,
      String password,
      List<String> hostTags)
      throws DiscoveryException {

    if (s_logger.isInfoEnabled())
      s_logger.info(
          "Discover host. dc: "
              + dcId
              + ", pod: "
              + podId
              + ", cluster: "
              + clusterId
              + ", uri host: "
              + url.getHost());

    if (podId == null) {
      if (s_logger.isInfoEnabled())
        s_logger.info(
            "No pod is assigned, assuming that it is not for vmware and skip it to next discoverer");
      return null;
    }

    ClusterVO cluster = _clusterDao.findById(clusterId);
    if (cluster == null || cluster.getHypervisorType() != HypervisorType.VMware) {
      if (s_logger.isInfoEnabled())
        s_logger.info("invalid cluster id or cluster is not for VMware hypervisors");
      return null;
    }

    List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
    if (hosts != null && hosts.size() > 0) {
      int maxHostsPerCluster =
          _hvCapabilitiesDao.getMaxHostsPerCluster(
              hosts.get(0).getHypervisorType(), hosts.get(0).getHypervisorVersion());
      if (hosts.size() > maxHostsPerCluster) {
        String msg =
            "VMware cluster "
                + cluster.getName()
                + " is too big to add new host now. (current configured cluster size: "
                + maxHostsPerCluster
                + ")";
        s_logger.error(msg);
        throw new DiscoveredWithErrorException(msg);
      }
    }

    String privateTrafficLabel = null;
    String publicTrafficLabel = null;
    String guestTrafficLabel = null;
    Map<String, String> vsmCredentials = null;

    VirtualSwitchType defaultVirtualSwitchType = VirtualSwitchType.StandardVirtualSwitch;

    String paramGuestVswitchType = null;
    String paramGuestVswitchName = null;
    String paramPublicVswitchType = null;
    String paramPublicVswitchName = null;

    VmwareTrafficLabel guestTrafficLabelObj = new VmwareTrafficLabel(TrafficType.Guest);
    VmwareTrafficLabel publicTrafficLabelObj = new VmwareTrafficLabel(TrafficType.Public);
    Map<String, String> clusterDetails = _clusterDetailsDao.findDetails(clusterId);
    DataCenterVO zone = _dcDao.findById(dcId);
    NetworkType zoneType = zone.getNetworkType();
    _readGlobalConfigParameters();

    // Set default physical network end points for public and guest traffic
    // Private traffic will be only on standard vSwitch for now.
    if (useDVS) {
      // Parse url parameters for type of vswitch and name of vswitch specified at cluster level
      paramGuestVswitchType = _urlParams.get(ApiConstants.VSWITCH_TYPE_GUEST_TRAFFIC);
      paramGuestVswitchName = _urlParams.get(ApiConstants.VSWITCH_NAME_GUEST_TRAFFIC);
      paramPublicVswitchType = _urlParams.get(ApiConstants.VSWITCH_TYPE_PUBLIC_TRAFFIC);
      paramPublicVswitchName = _urlParams.get(ApiConstants.VSWITCH_NAME_PUBLIC_TRAFFIC);
      defaultVirtualSwitchType = getDefaultVirtualSwitchType();
    }

    // Zone level vSwitch Type depends on zone level traffic labels
    //
    // User can override Zone wide vswitch type (for public and guest) by providing following
    // optional parameters in addClusterCmd
    // param "guestvswitchtype" with valid values vmwaredvs, vmwaresvs, nexusdvs
    // param "publicvswitchtype" with valid values vmwaredvs, vmwaresvs, nexusdvs
    //
    // Format of label is <VSWITCH>,<VLANID>,<VSWITCHTYPE>
    // If a field <VLANID> OR <VSWITCHTYPE> is not present leave it empty.
    // Ex: 1) vswitch0
    // 2) dvswitch0,200,vmwaredvs
    // 3) nexusepp0,300,nexusdvs
    // 4) vswitch1,400,vmwaresvs
    // 5) vswitch0
    // default vswitchtype is 'vmwaresvs'.
    // <VSWITCHTYPE> 'vmwaresvs' is for vmware standard vswitch
    // <VSWITCHTYPE> 'vmwaredvs' is for vmware distributed virtual switch
    // <VSWITCHTYPE> 'nexusdvs' is for cisco nexus distributed virtual switch
    // Get zone wide traffic labels for Guest traffic and Public traffic
    guestTrafficLabel = _netmgr.getDefaultGuestTrafficLabel(dcId, HypervisorType.VMware);

    // Process traffic label information provided at zone level and cluster level
    guestTrafficLabelObj =
        getTrafficInfo(
            TrafficType.Guest,
            guestTrafficLabel,
            defaultVirtualSwitchType,
            paramGuestVswitchType,
            paramGuestVswitchName,
            clusterId);

    if (zoneType == NetworkType.Advanced) {
      // Get zone wide traffic label for Public traffic
      publicTrafficLabel = _netmgr.getDefaultPublicTrafficLabel(dcId, HypervisorType.VMware);

      // Process traffic label information provided at zone level and cluster level
      publicTrafficLabelObj =
          getTrafficInfo(
              TrafficType.Public,
              publicTrafficLabel,
              defaultVirtualSwitchType,
              paramPublicVswitchType,
              paramPublicVswitchName,
              clusterId);

      // Configuration Check: A physical network cannot be shared by different types of virtual
      // switches.
      //
      // Check if different vswitch types are chosen for same physical network
      // 1. Get physical network for guest traffic - multiple networks
      // 2. Get physical network for public traffic - single network
      // See if 2 is in 1
      //  if no - pass
      //  if yes - compare publicTrafficLabelObj.getVirtualSwitchType() ==
      // guestTrafficLabelObj.getVirtualSwitchType()
      //      true  - pass
      //      false - throw exception - fail cluster add operation

      List<? extends PhysicalNetwork> pNetworkListGuestTraffic =
          _netmgr.getPhysicalNtwksSupportingTrafficType(dcId, TrafficType.Guest);
      List<? extends PhysicalNetwork> pNetworkListPublicTraffic =
          _netmgr.getPhysicalNtwksSupportingTrafficType(dcId, TrafficType.Public);
      // Public network would be on single physical network hence getting first object of the list
      // would suffice.
      PhysicalNetwork pNetworkPublic = pNetworkListPublicTraffic.get(0);
      if (pNetworkListGuestTraffic.contains(pNetworkPublic)) {
        if (publicTrafficLabelObj.getVirtualSwitchType()
            != guestTrafficLabelObj.getVirtualSwitchType()) {
          String msg =
              "Both public traffic and guest traffic is over same physical network "
                  + pNetworkPublic
                  + ". And virtual switch type chosen for each traffic is different"
                  + ". A physical network cannot be shared by different types of virtual switches.";
          s_logger.error(msg);
          throw new InvalidParameterValueException(msg);
        }
      }
    } else {
      // Distributed virtual switch is not supported in Basic zone for now.
      // Private / Management network traffic is not yet supported over distributed virtual switch.
      if (guestTrafficLabelObj.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch) {
        String msg =
            "Detected that Guest traffic is over Distributed virtual switch in Basic zone. Only Standard vSwitch is supported in Basic zone.";
        s_logger.error(msg);
        throw new DiscoveredWithErrorException(msg);
      }
    }

    privateTrafficLabel = _netmgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.VMware);
    if (privateTrafficLabel != null) {
      s_logger.info("Detected private network label : " + privateTrafficLabel);
    }

    if (nexusDVS) {
      if (zoneType != NetworkType.Basic) {
        publicTrafficLabel = _netmgr.getDefaultPublicTrafficLabel(dcId, HypervisorType.VMware);
        if (publicTrafficLabel != null) {
          s_logger.info("Detected public network label : " + publicTrafficLabel);
        }
      }
      // Get physical network label
      guestTrafficLabel = _netmgr.getDefaultGuestTrafficLabel(dcId, HypervisorType.VMware);
      if (guestTrafficLabel != null) {
        s_logger.info("Detected guest network label : " + guestTrafficLabel);
      }
      vsmCredentials = _vmwareMgr.getNexusVSMCredentialsByClusterId(clusterId);
    }

    VmwareContext context = null;
    try {
      context = VmwareContextFactory.create(url.getHost(), username, password);
      if (privateTrafficLabel != null)
        context.registerStockObject("privateTrafficLabel", privateTrafficLabel);

      if (nexusDVS) {
        if (vsmCredentials != null) {
          s_logger.info("Stocking credentials of Nexus VSM");
          context.registerStockObject("vsmcredentials", vsmCredentials);
        }
      }
      List<ManagedObjectReference> morHosts =
          _vmwareMgr.addHostToPodCluster(
              context, dcId, podId, clusterId, URLDecoder.decode(url.getPath()));
      if (morHosts == null) s_logger.info("Found 0 hosts.");
      if (privateTrafficLabel != null) context.uregisterStockObject("privateTrafficLabel");

      if (morHosts == null) {
        s_logger.error(
            "Unable to find host or cluster based on url: " + URLDecoder.decode(url.getPath()));
        return null;
      }

      ManagedObjectReference morCluster = null;
      clusterDetails = _clusterDetailsDao.findDetails(clusterId);
      if (clusterDetails.get("url") != null) {
        URI uriFromCluster = new URI(UriUtils.encodeURIComponent(clusterDetails.get("url")));
        morCluster = context.getHostMorByPath(URLDecoder.decode(uriFromCluster.getPath()));

        if (morCluster == null
            || !morCluster.getType().equalsIgnoreCase("ClusterComputeResource")) {
          s_logger.warn(
              "Cluster url does not point to a valid vSphere cluster, url: "
                  + clusterDetails.get("url"));
          return null;
        } else {
          ClusterMO clusterMo = new ClusterMO(context, morCluster);
          ClusterDasConfigInfo dasConfig = clusterMo.getDasConfig();
          if (dasConfig != null
              && dasConfig.isEnabled() != null
              && dasConfig.isEnabled().booleanValue()) {
            clusterDetails.put("NativeHA", "true");
            _clusterDetailsDao.persist(clusterId, clusterDetails);
          }
        }
      }

      if (!validateDiscoveredHosts(context, morCluster, morHosts)) {
        if (morCluster == null)
          s_logger.warn(
              "The discovered host is not standalone host, can not be added to a standalone cluster");
        else s_logger.warn("The discovered host does not belong to the cluster");
        return null;
      }

      Map<VmwareResource, Map<String, String>> resources =
          new HashMap<VmwareResource, Map<String, String>>();
      for (ManagedObjectReference morHost : morHosts) {
        Map<String, String> details = new HashMap<String, String>();
        Map<String, Object> params = new HashMap<String, Object>();

        HostMO hostMo = new HostMO(context, morHost);
        details.put("url", hostMo.getHostName());
        details.put("username", username);
        details.put("password", password);
        String guid = morHost.getType() + ":" + morHost.getValue() + "@" + url.getHost();
        details.put("guid", guid);

        params.put("url", hostMo.getHostName());
        params.put("username", username);
        params.put("password", password);
        params.put("zone", Long.toString(dcId));
        params.put("pod", Long.toString(podId));
        params.put("cluster", Long.toString(clusterId));
        params.put("guid", guid);
        if (privateTrafficLabel != null) {
          params.put("private.network.vswitch.name", privateTrafficLabel);
        }
        params.put("guestTrafficInfo", guestTrafficLabelObj);
        params.put("publicTrafficInfo", publicTrafficLabelObj);

        VmwareResource resource = new VmwareResource();
        try {
          resource.configure("VMware", params);
        } catch (ConfigurationException e) {
          _alertMgr.sendAlert(
              AlertManager.ALERT_TYPE_HOST,
              dcId,
              podId,
              "Unable to add " + url.getHost(),
              "Error is " + e.getMessage());
          s_logger.warn("Unable to instantiate " + url.getHost(), e);
        }
        resource.start();

        resources.put(resource, details);
      }

      // place a place holder guid derived from cluster ID
      cluster.setGuid(UUID.nameUUIDFromBytes(String.valueOf(clusterId).getBytes()).toString());
      _clusterDao.update(clusterId, cluster);

      return resources;
    } catch (DiscoveredWithErrorException e) {
      throw e;
    } catch (Exception e) {
      s_logger.warn(
          "Unable to connect to Vmware vSphere server. service address: " + url.getHost());
      return null;
    } finally {
      if (context != null) context.close();
    }
  }
  @Override
  public boolean finalizeVirtualMachineProfile(
      VirtualMachineProfile<SecondaryStorageVmVO> profile,
      DeployDestination dest,
      ReservationContext context) {

    SecondaryStorageVmVO vm = profile.getVirtualMachine();
    Map<String, String> details = _vmDetailsDao.findDetails(vm.getId());
    vm.setDetails(details);

    HostVO secHost = _hostDao.findSecondaryStorageHost(dest.getDataCenter().getId());
    assert (secHost != null);

    StringBuilder buf = profile.getBootArgsBuilder();
    buf.append(" template=domP type=secstorage");
    buf.append(" host=").append(_mgmt_host);
    buf.append(" port=").append(_mgmt_port);
    buf.append(" name=").append(profile.getVirtualMachine().getHostName());

    buf.append(" zone=").append(dest.getDataCenter().getId());
    buf.append(" pod=").append(dest.getPod().getId());

    buf.append(" guid=").append(profile.getVirtualMachine().getHostName());

    if (_configDao.isPremium()) {
      if (profile.getHypervisorType() == HypervisorType.Hyperv) {
        buf.append(" resource=com.cloud.storage.resource.CifsSecondaryStorageResource");
      } else {
        buf.append(" resource=com.cloud.storage.resource.PremiumSecondaryStorageResource");
      }
    } else {
      buf.append(" resource=com.cloud.storage.resource.NfsSecondaryStorageResource");
    }
    buf.append(" instance=SecStorage");
    buf.append(" sslcopy=").append(Boolean.toString(_useSSlCopy));
    buf.append(" role=").append(profile.getVirtualMachine().getRole().toString());

    boolean externalDhcp = false;
    String externalDhcpStr =
        _configDao.getValue("direct.attach.network.externalIpAllocator.enabled");
    if (externalDhcpStr != null && externalDhcpStr.equalsIgnoreCase("true")) {
      externalDhcp = true;
    }

    for (NicProfile nic : profile.getNics()) {
      int deviceId = nic.getDeviceId();
      if (nic.getIp4Address() == null) {
        buf.append(" eth").append(deviceId).append("mask=").append("0.0.0.0");
        buf.append(" eth").append(deviceId).append("ip=").append("0.0.0.0");
      } else {
        buf.append(" eth").append(deviceId).append("ip=").append(nic.getIp4Address());
        buf.append(" eth").append(deviceId).append("mask=").append(nic.getNetmask());
      }

      buf.append(" eth").append(deviceId).append("mask=").append(nic.getNetmask());
      if (nic.isDefaultNic()) {
        buf.append(" gateway=").append(nic.getGateway());
      }
      if (nic.getTrafficType() == TrafficType.Management) {
        String mgmt_cidr = _configDao.getValue(Config.ManagementNetwork.key());
        if (NetUtils.isValidCIDR(mgmt_cidr)) {
          buf.append(" mgmtcidr=").append(mgmt_cidr);
        }
        buf.append(" localgw=").append(dest.getPod().getGateway());
        buf.append(" private.network.device=").append("eth").append(deviceId);
      } else if (nic.getTrafficType() == TrafficType.Public) {
        buf.append(" public.network.device=").append("eth").append(deviceId);
      }
    }

    /* External DHCP mode */
    if (externalDhcp) {
      buf.append(" bootproto=dhcp");
    }

    DataCenterVO dc = _dcDao.findById(profile.getVirtualMachine().getDataCenterIdToDeployIn());
    buf.append(" internaldns1=").append(dc.getInternalDns1());
    if (dc.getInternalDns2() != null) {
      buf.append(" internaldns2=").append(dc.getInternalDns2());
    }
    buf.append(" dns1=").append(dc.getDns1());
    if (dc.getDns2() != null) {
      buf.append(" dns2=").append(dc.getDns2());
    }

    String bootArgs = buf.toString();
    if (s_logger.isDebugEnabled()) {
      s_logger.debug("Boot Args for " + profile + ": " + bootArgs);
    }

    return true;
  }
  @Override
  @DB
  public boolean delete(TemplateProfile profile) {
    VMTemplateVO template = profile.getTemplate();
    Long templateId = template.getId();
    boolean success = true;
    String zoneName;

    if (!template.isCrossZones() && profile.getZoneId() != null) {
      zoneName = profile.getZoneId().toString();
    } else {
      zoneName = "all zones";
    }

    s_logger.debug(
        "Attempting to mark template host refs for template: "
            + template.getName()
            + " as destroyed in zone: "
            + zoneName);
    Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId());
    String eventType = EventTypes.EVENT_TEMPLATE_DELETE;
    List<TemplateDataStoreVO> templateHostVOs = this._tmpltStoreDao.listByTemplate(templateId);

    for (TemplateDataStoreVO vo : templateHostVOs) {
      TemplateDataStoreVO lock = null;
      try {
        lock = _tmpltStoreDao.acquireInLockTable(vo.getId());
        if (lock == null) {
          s_logger.debug(
              "Failed to acquire lock when deleting templateDataStoreVO with ID: " + vo.getId());
          success = false;
          break;
        }

        vo.setDestroyed(true);
        _tmpltStoreDao.update(vo.getId(), vo);

      } finally {
        if (lock != null) {
          _tmpltStoreDao.releaseFromLockTable(lock.getId());
        }
      }
    }

    if (profile.getZoneId() != null) {
      UsageEventVO usageEvent =
          new UsageEventVO(eventType, account.getId(), profile.getZoneId(), templateId, null);
      _usageEventDao.persist(usageEvent);
    } else {
      List<DataCenterVO> dcs = _dcDao.listAllIncludingRemoved();
      for (DataCenterVO dc : dcs) {
        UsageEventVO usageEvent =
            new UsageEventVO(eventType, account.getId(), dc.getId(), templateId, null);
        _usageEventDao.persist(usageEvent);
      }
    }

    VMTemplateZoneVO templateZone =
        _tmpltZoneDao.findByZoneTemplate(profile.getZoneId(), templateId);

    if (templateZone != null) {
      _tmpltZoneDao.remove(templateZone.getId());
    }

    s_logger.debug(
        "Successfully marked template host refs for template: "
            + template.getName()
            + " as destroyed in zone: "
            + zoneName);

    // If there are no more non-destroyed template host entries for this template, delete it
    if (success && (_tmpltStoreDao.listByTemplate(templateId).size() == 0)) {
      long accountId = template.getAccountId();

      VMTemplateVO lock = _tmpltDao.acquireInLockTable(templateId);

      try {
        if (lock == null) {
          s_logger.debug("Failed to acquire lock when deleting template with ID: " + templateId);
          success = false;
        } else if (_tmpltDao.remove(templateId)) {
          // Decrement the number of templates and total secondary storage space used by the
          // account.
          _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
          _resourceLimitMgr.recalculateResourceCount(
              accountId, template.getDomainId(), ResourceType.secondary_storage.getOrdinal());
        }

      } finally {
        if (lock != null) {
          _tmpltDao.releaseFromLockTable(lock.getId());
        }
      }
      s_logger.debug(
          "Removed template: "
              + template.getName()
              + " because all of its template host refs were marked as destroyed.");
    }

    return success;
  }
  protected Long restart(final HaWorkVO work) {
    final long vmId = work.getInstanceId();

    final VirtualMachineGuru<VMInstanceVO> mgr = findManager(work.getType());
    if (mgr == null) {
      s_logger.warn(
          "Unable to find a handler for " + work.getType().toString() + ", throwing out " + vmId);
      return null;
    }

    VMInstanceVO vm = mgr.get(vmId);
    if (vm == null) {
      s_logger.info("Unable to find vm: " + vmId);
      return null;
    }

    s_logger.info("HA on " + vm.toString());
    if (vm.getState() != work.getPreviousState() || vm.getUpdated() != work.getUpdateTime()) {
      s_logger.info(
          "VM "
              + vm.toString()
              + " has been changed.  Current State = "
              + vm.getState()
              + " Previous State = "
              + work.getPreviousState()
              + " last updated = "
              + vm.getUpdated()
              + " previous updated = "
              + work.getUpdateTime());
      return null;
    }

    final HostVO host = _hostDao.findById(work.getHostId());

    DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
    HostPodVO podVO = _podDao.findById(host.getPodId());
    String hostDesc =
        "name: "
            + host.getName()
            + "(id:"
            + host.getId()
            + "), availability zone: "
            + dcVO.getName()
            + ", pod: "
            + podVO.getName();

    short alertType = AlertManager.ALERT_TYPE_USERVM;
    if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
      alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER;
    } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
      alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY;
    }

    Boolean alive = null;
    if (work.getStep() == Step.Investigating) {
      if (vm.getHostId() == null || vm.getHostId() != work.getHostId()) {
        s_logger.info("VM " + vm.toString() + " is now no longer on host " + work.getHostId());
        if (vm.getState() == State.Starting && vm.getUpdated() == work.getUpdateTime()) {
          _itMgr.stateTransitTo(vm, Event.AgentReportStopped, null);
        }
        return null;
      }

      Enumeration<Investigator> en = _investigators.enumeration();
      Investigator investigator = null;
      while (en.hasMoreElements()) {
        investigator = en.nextElement();
        alive = investigator.isVmAlive(vm, host);
        if (alive != null) {
          s_logger.debug(
              investigator.getName() + " found VM " + vm.getName() + "to be alive? " + alive);
          break;
        }
      }
      if (alive != null && alive) {
        s_logger.debug("VM " + vm.getName() + " is found to be alive by " + investigator.getName());
        if (host.getStatus() == Status.Up) {
          compareState(vm, new AgentVmInfo(vm.getInstanceName(), mgr, State.Running), false);
          return null;
        } else {
          s_logger.debug("Rescheduling because the host is not up but the vm is alive");
          return (System.currentTimeMillis() >> 10) + _investigateRetryInterval;
        }
      }

      boolean fenced = false;
      if (alive == null || !alive) {
        fenced = true;
        s_logger.debug("Fencing off VM that we don't know the state of");
        Enumeration<FenceBuilder> enfb = _fenceBuilders.enumeration();
        while (enfb.hasMoreElements()) {
          final FenceBuilder fb = enfb.nextElement();
          Boolean result = fb.fenceOff(vm, host);
          if (result != null && !result) {
            fenced = false;
          }
        }
      }

      if (alive == null && !fenced) {
        s_logger.debug("We were unable to fence off the VM " + vm.toString());
        _alertMgr.sendAlert(
            alertType,
            vm.getDataCenterId(),
            vm.getPodId(),
            "Unable to restart " + vm.getName() + " which was running on host " + hostDesc,
            "Insufficient capacity to restart VM, name: "
                + vm.getName()
                + ", id: "
                + vmId
                + " which was running on host "
                + hostDesc);
        return (System.currentTimeMillis() >> 10) + _restartRetryInterval;
      }

      mgr.completeStopCommand(vm);

      work.setStep(Step.Scheduled);
      _haDao.update(work.getId(), work);
    }

    // send an alert for VMs that stop unexpectedly
    _alertMgr.sendAlert(
        alertType,
        vm.getDataCenterId(),
        vm.getPodId(),
        "VM (name: "
            + vm.getName()
            + ", id: "
            + vmId
            + ") stopped unexpectedly on host "
            + hostDesc,
        "Virtual Machine "
            + vm.getName()
            + " (id: "
            + vm.getId()
            + ") running on host ["
            + hostDesc
            + "] stopped unexpectedly.");

    vm = mgr.get(vm.getId());

    if (!_forceHA && !vm.isHaEnabled()) {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("VM is not HA enabled so we're done.");
      }
      return null; // VM doesn't require HA
    }

    if (!_storageMgr.canVmRestartOnAnotherServer(vm.getId())) {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("VM can not restart on another server.");
      }
      return null;
    }

    if (work.getTimesTried() > _maxRetries) {
      s_logger.warn("Retried to max times so deleting: " + vmId);
      return null;
    }

    try {
      VMInstanceVO started = mgr.start(vm.getId(), 0);
      if (started != null) {
        s_logger.info("VM is now restarted: " + vmId + " on " + started.getHostId());
        return null;
      }

      if (s_logger.isDebugEnabled()) {
        s_logger.debug(
            "Rescheduling VM " + vm.toString() + " to try again in " + _restartRetryInterval);
      }
      vm = mgr.get(vm.getId());
      work.setUpdateTime(vm.getUpdated());
      work.setPreviousState(vm.getState());
      return (System.currentTimeMillis() >> 10) + _restartRetryInterval;
    } catch (final InsufficientCapacityException e) {
      s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
      _alertMgr.sendAlert(
          alertType,
          vm.getDataCenterId(),
          vm.getPodId(),
          "Unable to restart " + vm.getName() + " which was running on host " + hostDesc,
          "Insufficient capacity to restart VM, name: "
              + vm.getName()
              + ", id: "
              + vmId
              + " which was running on host "
              + hostDesc);
      return null;
    } catch (final StorageUnavailableException e) {
      s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
      _alertMgr.sendAlert(
          alertType,
          vm.getDataCenterId(),
          vm.getPodId(),
          "Unable to restart " + vm.getName() + " which was running on host " + hostDesc,
          "The Storage is unavailable for trying to restart VM, name: "
              + vm.getName()
              + ", id: "
              + vmId
              + " which was running on host "
              + hostDesc);
      return null;
    } catch (ConcurrentOperationException e) {
      s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
      _alertMgr.sendAlert(
          alertType,
          vm.getDataCenterId(),
          vm.getPodId(),
          "Unable to restart " + vm.getName() + " which was running on host " + hostDesc,
          "The Storage is unavailable for trying to restart VM, name: "
              + vm.getName()
              + ", id: "
              + vmId
              + " which was running on host "
              + hostDesc);
      return null;
    } catch (ExecutionException e) {
      s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
      _alertMgr.sendAlert(
          alertType,
          vm.getDataCenterId(),
          vm.getPodId(),
          "Unable to restart " + vm.getName() + " which was running on host " + hostDesc,
          "The Storage is unavailable for trying to restart VM, name: "
              + vm.getName()
              + ", id: "
              + vmId
              + " which was running on host "
              + hostDesc);
      return null;
    }
  }
  @Override
  @DB
  public boolean delete(TemplateProfile profile) {
    boolean success = true;

    VMTemplateVO template = profile.getTemplate();
    Long zoneId = profile.getZoneId();
    Long templateId = template.getId();

    String zoneName;
    List<HostVO> secondaryStorageHosts;
    if (!template.isCrossZones() && zoneId != null) {
      DataCenterVO zone = _dcDao.findById(zoneId);
      zoneName = zone.getName();
      secondaryStorageHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId);
    } else {
      zoneName = "(all zones)";
      secondaryStorageHosts = _ssvmMgr.listSecondaryStorageHostsInAllZones();
    }

    s_logger.debug(
        "Attempting to mark template host refs for template: "
            + template.getName()
            + " as destroyed in zone: "
            + zoneName);

    // Make sure the template is downloaded to all the necessary secondary storage hosts
    for (HostVO secondaryStorageHost : secondaryStorageHosts) {
      long hostId = secondaryStorageHost.getId();
      List<VMTemplateHostVO> templateHostVOs = _tmpltHostDao.listByHostTemplate(hostId, templateId);
      for (VMTemplateHostVO templateHostVO : templateHostVOs) {
        if (templateHostVO.getDownloadState() == Status.DOWNLOAD_IN_PROGRESS) {
          String errorMsg = "Please specify a template that is not currently being downloaded.";
          s_logger.debug(
              "Template: "
                  + template.getName()
                  + " is currently being downloaded to secondary storage host: "
                  + secondaryStorageHost.getName()
                  + "; cant' delete it.");
          throw new CloudRuntimeException(errorMsg);
        }
      }
    }

    Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId());
    String eventType = "";

    if (template.getFormat().equals(ImageFormat.ISO)) {
      eventType = EventTypes.EVENT_ISO_DELETE;
    } else {
      eventType = EventTypes.EVENT_TEMPLATE_DELETE;
    }

    // Iterate through all necessary secondary storage hosts and mark the template on each host as
    // destroyed
    for (HostVO secondaryStorageHost : secondaryStorageHosts) {
      long hostId = secondaryStorageHost.getId();
      long sZoneId = secondaryStorageHost.getDataCenterId();
      List<VMTemplateHostVO> templateHostVOs = _tmpltHostDao.listByHostTemplate(hostId, templateId);
      for (VMTemplateHostVO templateHostVO : templateHostVOs) {
        VMTemplateHostVO lock = _tmpltHostDao.acquireInLockTable(templateHostVO.getId());
        try {
          if (lock == null) {
            s_logger.debug(
                "Failed to acquire lock when deleting templateHostVO with ID: "
                    + templateHostVO.getId());
            success = false;
            break;
          }
          UsageEventVO usageEvent =
              new UsageEventVO(eventType, account.getId(), sZoneId, templateId, null);
          _usageEventDao.persist(usageEvent);
          templateHostVO.setDestroyed(true);
          _tmpltHostDao.update(templateHostVO.getId(), templateHostVO);
          String installPath = templateHostVO.getInstallPath();
          if (installPath != null) {
            Answer answer =
                _agentMgr.sendToSecStorage(
                    secondaryStorageHost,
                    new DeleteTemplateCommand(secondaryStorageHost.getStorageUrl(), installPath));

            if (answer == null || !answer.getResult()) {
              s_logger.debug(
                  "Failed to delete "
                      + templateHostVO
                      + " due to "
                      + ((answer == null) ? "answer is null" : answer.getDetails()));
            } else {
              _tmpltHostDao.remove(templateHostVO.getId());
              s_logger.debug("Deleted template at: " + installPath);
            }
          } else {
            _tmpltHostDao.remove(templateHostVO.getId());
          }
          VMTemplateZoneVO templateZone = _tmpltZoneDao.findByZoneTemplate(sZoneId, templateId);

          if (templateZone != null) {
            _tmpltZoneDao.remove(templateZone.getId());
          }
        } finally {
          if (lock != null) {
            _tmpltHostDao.releaseFromLockTable(lock.getId());
          }
        }
      }

      if (!success) {
        break;
      }
    }

    s_logger.debug(
        "Successfully marked template host refs for template: "
            + template.getName()
            + " as destroyed in zone: "
            + zoneName);

    // If there are no more non-destroyed template host entries for this template, delete it
    if (success && (_tmpltHostDao.listByTemplateId(templateId).size() == 0)) {
      long accountId = template.getAccountId();

      VMTemplateVO lock = _tmpltDao.acquireInLockTable(templateId);

      try {
        if (lock == null) {
          s_logger.debug("Failed to acquire lock when deleting template with ID: " + templateId);
          success = false;
        } else if (_tmpltDao.remove(templateId)) {
          // Decrement the number of templates
          _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
        }

      } finally {
        if (lock != null) {
          _tmpltDao.releaseFromLockTable(lock.getId());
        }
      }

      s_logger.debug(
          "Removed template: "
              + template.getName()
              + " because all of its template host refs were marked as destroyed.");
    }

    return success;
  }
  /**
   * compareState does as its name suggests and compares the states between management server and
   * agent. It returns whether something should be cleaned up
   */
  protected Command compareState(VMInstanceVO vm, final AgentVmInfo info, final boolean fullSync) {
    State agentState = info.state;
    final String agentName = info.name;
    final State serverState = vm.getState();
    final String serverName = vm.getName();

    Command command = null;

    if (s_logger.isDebugEnabled()) {
      s_logger.debug(
          "VM "
              + serverName
              + ": server state = "
              + serverState.toString()
              + " and agent state = "
              + agentState.toString());
    }

    if (agentState == State.Error) {
      agentState = State.Stopped;

      short alertType = AlertManager.ALERT_TYPE_USERVM;
      if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
        alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER;
      } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
        alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY;
      }

      HostPodVO podVO = _podDao.findById(vm.getPodId());
      DataCenterVO dcVO = _dcDao.findById(vm.getDataCenterId());
      HostVO hostVO = _hostDao.findById(vm.getHostId());

      String hostDesc =
          "name: "
              + hostVO.getName()
              + " (id:"
              + hostVO.getId()
              + "), availability zone: "
              + dcVO.getName()
              + ", pod: "
              + podVO.getName();
      _alertMgr.sendAlert(
          alertType,
          vm.getDataCenterId(),
          vm.getPodId(),
          "VM (name: "
              + vm.getName()
              + ", id: "
              + vm.getId()
              + ") stopped on host "
              + hostDesc
              + " due to storage failure",
          "Virtual Machine "
              + vm.getName()
              + " (id: "
              + vm.getId()
              + ") running on host ["
              + vm.getHostId()
              + "] stopped due to storage failure.");
    }

    if (serverState == State.Migrating) {
      s_logger.debug("Skipping vm in migrating state: " + vm.toString());
      return null;
    }

    if (agentState == serverState) {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Both states are " + agentState.toString() + " for " + serverName);
      }
      assert (agentState == State.Stopped || agentState == State.Running)
          : "If the states we send up is changed, this must be changed.";
      _itMgr.stateTransitTo(
          vm,
          agentState == State.Stopped
              ? VirtualMachine.Event.AgentReportStopped
              : VirtualMachine.Event.AgentReportRunning,
          vm.getHostId());
      if (agentState == State.Stopped) {
        s_logger.debug("State matches but the agent said stopped so let's send a cleanup anyways.");
        return info.mgr.cleanup(vm, agentName);
      }
      return null;
    }

    if (agentState == State.Stopped) {
      // This state means the VM on the agent was detected previously
      // and now is gone.  This is slightly different than if the VM
      // was never completed but we still send down a Stop Command
      // to ensure there's cleanup.
      if (serverState == State.Running) {
        // Our records showed that it should be running so let's restart it.
        vm = info.mgr.get(vm.getId());
        scheduleRestart(vm, false);
        command = info.mgr.cleanup(vm, agentName);
      } else if (serverState == State.Stopping) {
        if (fullSync) {
          s_logger.debug("VM is in stopping state on full sync.  Updating the status to stopped");
          vm = info.mgr.get(vm.getId());
          info.mgr.completeStopCommand(vm);
          command = info.mgr.cleanup(vm, agentName);
        } else {
          s_logger.debug("Ignoring VM in stopping mode: " + vm.getName());
        }
      } else if (serverState == State.Starting) {
        s_logger.debug("Ignoring VM in starting mode: " + vm.getName());
      } else {
        s_logger.debug("Sending cleanup to a stopped vm: " + agentName);
        _itMgr.stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null);
        command = info.mgr.cleanup(vm, agentName);
      }
    } else if (agentState == State.Running) {
      if (serverState == State.Starting) {
        if (fullSync) {
          s_logger.debug("VM state is starting on full sync so updating it to running");
          vm = info.mgr.get(vm.getId());
          info.mgr.completeStartCommand(vm);
        }
      } else if (serverState == State.Stopping) {
        if (fullSync) {
          s_logger.debug("VM state is in stopping on fullsync so resend stop.");
          vm = info.mgr.get(vm.getId());
          info.mgr.completeStopCommand(vm);
          command = info.mgr.cleanup(vm, agentName);
        } else {
          s_logger.debug("VM is in stopping state so no action.");
        }
      } else if (serverState == State.Destroyed
          || serverState == State.Stopped
          || serverState == State.Expunging) {
        s_logger.debug("VM state is in stopped so stopping it on the agent");
        vm = info.mgr.get(vm.getId());
        command = info.mgr.cleanup(vm, agentName);
      } else {
        _itMgr.stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, vm.getHostId());
      }
    } /*else if (agentState == State.Unknown) {
          if (serverState == State.Running) {
              if (fullSync) {
                  vm = info.handler.get(vm.getId());
              }
              scheduleRestart(vm, false);
          } else if (serverState == State.Starting) {
              if (fullSync) {
                  vm = info.handler.get(vm.getId());
              }
              scheduleRestart(vm, false);
          } else if (serverState == State.Stopping) {
              if (fullSync) {
                  s_logger.debug("VM state is stopping in full sync.  Resending stop");
                  command = info.handler.cleanup(vm, agentName);
              }
          }
      }*/
    return command;
  }