// TODO: add test for method
  @Override
  public final HostVO createHostVOForDirectConnectAgent(
      final HostVO host,
      final StartupCommand[] startup,
      final ServerResource resource,
      final Map<String, String> details,
      final List<String> hostTags) {
    StartupCommand firstCmd = startup[0];
    if (!(firstCmd instanceof StartupRoutingCommand)) {
      return null;
    }

    StartupRoutingCommand ssCmd = ((StartupRoutingCommand) firstCmd);
    if (ssCmd.getHypervisorType() != HypervisorType.Hyperv) {
      return null;
    }

    s_logger.info(
        "Host: "
            + host.getName()
            + " connected with hypervisor type: "
            + HypervisorType.Hyperv
            + ". Checking CIDR...");

    HostPodVO pod = _podDao.findById(host.getPodId());
    DataCenterVO dc = _dcDao.findById(host.getDataCenterId());

    _resourceMgr.checkCIDR(pod, dc, ssCmd.getPrivateIpAddress(), ssCmd.getPrivateNetmask());

    return _resourceMgr.fillRoutingHostVO(host, ssCmd, HypervisorType.Hyperv, details, hostTags);
  }
  @Override
  public List<DomainRouterVO> startRouters(
      final RouterDeploymentDefinition routerDeploymentDefinition)
      throws StorageUnavailableException, InsufficientCapacityException,
          ConcurrentOperationException, ResourceUnavailableException {

    final List<DomainRouterVO> runningRouters = new ArrayList<DomainRouterVO>();

    for (DomainRouterVO router : routerDeploymentDefinition.getRouters()) {
      boolean skip = false;
      final State state = router.getState();
      if (router.getHostId() != null && state != State.Running) {
        final HostVO host = _hostDao.findById(router.getHostId());
        if (host == null || host.getState() != Status.Up) {
          skip = true;
        }
      }
      if (!skip) {
        if (state != State.Running) {
          router =
              startVirtualRouter(
                  router,
                  _accountMgr.getSystemUser(),
                  _accountMgr.getSystemAccount(),
                  routerDeploymentDefinition.getParams());
        }
        if (router != null) {
          runningRouters.add(router);
        }
      }
    }
    return runningRouters;
  }
  @Override
  public void shutdown(final NetworkProfile profile, final NetworkOffering offering) {
    final NetworkVO networkObject = networkDao.findById(profile.getId());
    if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Lswitch
        || networkObject.getBroadcastUri() == null) {
      s_logger.warn(
          "BroadcastUri is empty or incorrect for guestnetwork " + networkObject.getDisplayText());
      return;
    }

    final List<NiciraNvpDeviceVO> devices =
        niciraNvpDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId());
    if (devices.isEmpty()) {
      s_logger.error(
          "No NiciraNvp Controller on physical network " + networkObject.getPhysicalNetworkId());
      return;
    }
    final NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
    final HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());

    final DeleteLogicalSwitchCommand cmd =
        new DeleteLogicalSwitchCommand(
            BroadcastDomainType.getValue(networkObject.getBroadcastUri()));
    final DeleteLogicalSwitchAnswer answer =
        (DeleteLogicalSwitchAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd);

    if (answer == null || !answer.getResult()) {
      s_logger.error("DeleteLogicalSwitchCommand failed");
    }

    super.shutdown(profile, offering);
  }
 @Override
 public boolean processDisconnect(long agentId, Status state) {
   UserContext context = UserContext.current();
   context.setAccountId(1);
   /* Stopped VMware Host's virtual routers */
   HostVO host = _hostDao.findById(agentId);
   if (host.getHypervisorType() != HypervisorType.VMware) {
     return true;
   }
   List<DomainRouterVO> routers = _routerDao.listByHostId(agentId);
   for (DomainRouterVO router : routers) {
     try {
       State oldState = router.getState();
       _routerMgr.stopRouter(router.getId(), true);
       // In case only vCenter is disconnected, we want to shut down router directly
       if (oldState == State.Running) {
         shutdownRouterVM(router);
       }
     } catch (ResourceUnavailableException e) {
       s_logger.warn(
           "Fail to stop router " + router.getInstanceName() + " when host disconnected!", e);
     } catch (ConcurrentOperationException e) {
       s_logger.warn(
           "Fail to stop router " + router.getInstanceName() + " when host disconnected!", e);
     }
   }
   return true;
 }
  @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 boolean deleteCiscoVnmcResource(DeleteCiscoVnmcResourceCmd cmd) {
    Long vnmcResourceId = cmd.getCiscoVnmcResourceId();
    CiscoVnmcControllerVO vnmcResource = _ciscoVnmcDao.findById(vnmcResourceId);
    if (vnmcResource == null) {
      throw new InvalidParameterValueException(
          "Could not find a Cisco VNMC appliance with id " + vnmcResourceId);
    }

    // Check if there any ASA 1000v appliances
    Long physicalNetworkId = vnmcResource.getPhysicalNetworkId();
    PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
    if (physicalNetwork != null) {
      List<CiscoAsa1000vDeviceVO> responseList =
          _ciscoAsa1000vDao.listByPhysicalNetwork(physicalNetworkId);
      if (responseList.size() > 0) {
        throw new CloudRuntimeException(
            "Cisco VNMC appliance with id "
                + vnmcResourceId
                + " cannot be deleted as there Cisco ASA 1000v appliances using it");
      }
    }

    HostVO vnmcHost = _hostDao.findById(vnmcResource.getHostId());
    Long hostId = vnmcHost.getId();
    vnmcHost.setResourceState(ResourceState.Maintenance);
    _hostDao.update(hostId, vnmcHost);
    _resourceMgr.deleteHost(hostId, false, false);
    _ciscoVnmcDao.remove(vnmcResourceId);

    return true;
  }
  @Override
  public boolean attachCluster(DataStore store, ClusterScope scope) {
    PrimaryDataStoreInfo primarystore = (PrimaryDataStoreInfo) store;
    // Check if there is host up in this cluster
    List<HostVO> allHosts =
        _resourceMgr.listAllUpAndEnabledHosts(
            Host.Type.Routing,
            primarystore.getClusterId(),
            primarystore.getPodId(),
            primarystore.getDataCenterId());
    if (allHosts.isEmpty()) {
      primaryDataStoreDao.expunge(primarystore.getId());
      throw new CloudRuntimeException(
          "No host up to associate a storage pool with in cluster " + primarystore.getClusterId());
    }

    if (primarystore.getPoolType() == StoragePoolType.OCFS2
        && !_ocfs2Mgr.prepareNodes(allHosts, primarystore)) {
      s_logger.warn(
          "Can not create storage pool "
              + primarystore
              + " on cluster "
              + primarystore.getClusterId());
      primaryDataStoreDao.expunge(primarystore.getId());
      return false;
    }

    boolean success = false;
    for (HostVO h : allHosts) {
      success = createStoragePool(h.getId(), primarystore);
      if (success) {
        break;
      }
    }

    s_logger.debug("In createPool Adding the pool to each of the hosts");
    List<HostVO> poolHosts = new ArrayList<HostVO>();
    for (HostVO h : allHosts) {
      try {
        storageMgr.connectHostToSharedPool(h.getId(), primarystore.getId());
        poolHosts.add(h);
      } catch (Exception e) {
        s_logger.warn("Unable to establish a connection between " + h + " and " + primarystore, e);
      }
    }

    if (poolHosts.isEmpty()) {
      s_logger.warn(
          "No host can access storage pool "
              + primarystore
              + " on cluster "
              + primarystore.getClusterId());
      primaryDataStoreDao.expunge(primarystore.getId());
      throw new CloudRuntimeException("Failed to access storage pool");
    }

    dataStoreHelper.attachCluster(store);
    return true;
  }
 @Override
 public BaremetalPxeType getPxeServerType(HostVO host) {
   if (host.getResource().equalsIgnoreCase(BaremetalPingPxeResource.class.getName())) {
     return BaremetalPxeType.PING;
   } else {
     throw new CloudRuntimeException("Unkown PXE server resource " + host.getResource());
   }
 }
  @Override
  public boolean generateVMSetupCommand(Long ssAHostId) {
    HostVO ssAHost = _hostDao.findById(ssAHostId);
    if (ssAHost.getType() != Host.Type.SecondaryStorageVM) {
      return false;
    }
    SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findByInstanceName(ssAHost.getName());
    if (secStorageVm == null) {
      s_logger.warn("secondary storage VM " + ssAHost.getName() + " doesn't exist");
      return false;
    }

    SecStorageVMSetupCommand setupCmd = new SecStorageVMSetupCommand();
    if (_allowedInternalSites != null) {
      List<String> allowedCidrs = new ArrayList<String>();
      String[] cidrs = _allowedInternalSites.split(",");
      for (String cidr : cidrs) {
        if (NetUtils.isValidCIDR(cidr) || NetUtils.isValidIp(cidr)) {
          allowedCidrs.add(cidr);
        }
      }
      List<? extends Nic> nics =
          _networkMgr.getNicsForTraffic(secStorageVm.getId(), TrafficType.Management);
      Nic privateNic = nics.get(0);
      String privateCidr =
          NetUtils.ipAndNetMaskToCidr(privateNic.getIp4Address(), privateNic.getNetmask());
      String publicCidr =
          NetUtils.ipAndNetMaskToCidr(
              secStorageVm.getPublicIpAddress(), secStorageVm.getPublicNetmask());
      if (NetUtils.isNetworkAWithinNetworkB(privateCidr, publicCidr)
          || NetUtils.isNetworkAWithinNetworkB(publicCidr, privateCidr)) {
        s_logger.info(
            "private and public interface overlaps, add a default route through private interface. privateCidr: "
                + privateCidr
                + ", publicCidr: "
                + publicCidr);
        allowedCidrs.add(NetUtils.ALL_CIDRS);
      }
      setupCmd.setAllowedInternalSites(allowedCidrs.toArray(new String[allowedCidrs.size()]));
    }
    String copyPasswd = _configDao.getValue("secstorage.copy.password");
    setupCmd.setCopyPassword(copyPasswd);
    setupCmd.setCopyUserName(TemplateConstants.DEFAULT_HTTP_AUTH_USER);
    Answer answer = _agentMgr.easySend(ssAHostId, setupCmd);
    if (answer != null && answer.getResult()) {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Successfully programmed http auth into " + secStorageVm.getHostName());
      }
      return true;
    } else {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug(
            "failed to program http auth into secondary storage vm : "
                + secStorageVm.getHostName());
      }
      return false;
    }
  }
 @Test
 public void scheduleRestartForVmsOnHost() {
   Mockito.when(hostVO.getType()).thenReturn(Host.Type.Routing);
   Mockito.when(hostVO.getHypervisorType()).thenReturn(HypervisorType.KVM);
   Mockito.when(_instanceDao.listByHostId(42l))
       .thenReturn(Arrays.asList(Mockito.mock(VMInstanceVO.class)));
   Mockito.when(_podDao.findById(Mockito.anyLong())).thenReturn(Mockito.mock(HostPodVO.class));
   Mockito.when(_dcDao.findById(Mockito.anyLong())).thenReturn(Mockito.mock(DataCenterVO.class));
   highAvailabilityManager.scheduleRestartForVmsOnHost(hostVO, true);
 }
 // TODO: add test for method
 @Override
 public final DeleteHostAnswer deleteHost(
     final HostVO host, final boolean isForced, final boolean isForceDeleteStorage)
     throws UnableDeleteHostException {
   // assert
   if (host.getType() != Host.Type.Routing || host.getHypervisorType() != HypervisorType.Hyperv) {
     return null;
   }
   _resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage);
   return new DeleteHostAnswer(true);
 }
  @Override
  public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage)
      throws UnableDeleteHostException {
    if (host.getType() != com.cloud.host.Host.Type.Routing
        || host.getHypervisorType() != HypervisorType.VMware) {
      return null;
    }

    _resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage);
    return new DeleteHostAnswer(true);
  }
  @DB
  public void handleDownloadEvent(HostVO host, VolumeVO volume, Status dnldStatus) {
    if ((dnldStatus == VMTemplateStorageResourceAssoc.Status.DOWNLOADED)
        || (dnldStatus == Status.ABANDONED)) {
      VolumeHostVO volumeHost = new VolumeHostVO(host.getId(), volume.getId());
      synchronized (_listenerVolumeMap) {
        _listenerVolumeMap.remove(volumeHost);
      }
    }

    VolumeHostVO volumeHost = _volumeHostDao.findByHostVolume(host.getId(), volume.getId());

    Transaction txn = Transaction.currentTxn();
    txn.start();

    if (dnldStatus == Status.DOWNLOADED) {

      // Create usage event
      long size = -1;
      if (volumeHost != null) {
        size = volumeHost.getSize();
        volume.setSize(size);
        this._volumeDao.update(volume.getId(), volume);
      } else {
        s_logger.warn("Failed to get size for volume" + volume.getName());
      }
      String eventType = EventTypes.EVENT_VOLUME_UPLOAD;
      if (volume.getAccountId() != Account.ACCOUNT_ID_SYSTEM) {
        UsageEventUtils.publishUsageEvent(
            eventType,
            volume.getAccountId(),
            host.getDataCenterId(),
            volume.getId(),
            volume.getName(),
            null,
            0l,
            size,
            volume.getClass().getName(),
            volume.getUuid());
      }
    } else if (dnldStatus == Status.DOWNLOAD_ERROR
        || dnldStatus == Status.ABANDONED
        || dnldStatus == Status.UNKNOWN) {
      // Decrement the volume and secondary storage space count
      _resourceLimitMgr.decrementResourceCount(
          volume.getAccountId(), com.cloud.configuration.Resource.ResourceType.volume);
      _resourceLimitMgr.recalculateResourceCount(
          volume.getAccountId(),
          volume.getDomainId(),
          com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal());
    }
    txn.commit();
  }
  @Override
  public ConsoleProxyInfo assignProxy(long dataCenterId, long userVmId) {
    UserVmVO userVm = _userVmDao.findById(userVmId);
    if (userVm == null) {
      s_logger.warn(
          "User VM " + userVmId + " no longer exists, return a null proxy for user vm:" + userVmId);
      return null;
    }

    HostVO host = findHost(userVm);
    if (host != null) {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug(
            "Assign embedded console proxy running at "
                + host.getName()
                + " to user vm "
                + userVmId
                + " with public IP "
                + host.getPublicIpAddress());
      }

      // only private IP, public IP, host id have meaningful values, rest
      // of all are place-holder values
      String publicIp = host.getPublicIpAddress();
      if (publicIp == null) {
        if (s_logger.isDebugEnabled()) {
          s_logger.debug(
              "Host "
                  + host.getName()
                  + "/"
                  + host.getPrivateIpAddress()
                  + " does not have public interface, we will return its private IP for cosole proxy.");
        }
        publicIp = host.getPrivateIpAddress();
      }

      int urlPort = _consoleProxyUrlPort;

      if (host.getProxyPort() != null && host.getProxyPort().intValue() > 0) {
        urlPort = host.getProxyPort().intValue();
      }

      return new ConsoleProxyInfo(
          _sslEnabled, publicIp, _consoleProxyPort, urlPort, _consoleProxyUrlDomain);
    } else {
      s_logger.warn(
          "Host that VM is running is no longer available, console access to VM "
              + userVmId
              + " will be temporarily unavailable.");
    }
    return null;
  }
  @Override
  public CiscoVnmcResourceResponse createCiscoVnmcResourceResponse(
      CiscoVnmcController ciscoVnmcResourceVO) {
    HostVO ciscoVnmcHost = _hostDao.findById(ciscoVnmcResourceVO.getHostId());

    CiscoVnmcResourceResponse response = new CiscoVnmcResourceResponse();
    response.setId(ciscoVnmcResourceVO.getUuid());
    response.setPhysicalNetworkId(ciscoVnmcResourceVO.getPhysicalNetworkId());
    response.setProviderName(ciscoVnmcResourceVO.getProviderName());
    response.setResourceName(ciscoVnmcHost.getName());

    return response;
  }
 @Override
 public BaremetalPxeResponse getApiResponse(BaremetalPxeVO vo) {
   BaremetalPxeResponse response = new BaremetalPxeResponse();
   response.setId(vo.getUuid());
   HostVO host = _hostDao.findById(vo.getHostId());
   response.setUrl(host.getPrivateIpAddress());
   PhysicalNetworkServiceProviderVO providerVO =
       _physicalNetworkServiceProviderDao.findById(vo.getNetworkServiceProviderId());
   response.setPhysicalNetworkId(providerVO.getUuid());
   PhysicalNetworkVO nwVO = _physicalNetworkDao.findById(vo.getPhysicalNetworkId());
   response.setPhysicalNetworkId(nwVO.getUuid());
   response.setObjectName("baremetalpxeserver");
   return response;
 }
  private Map<Long, TemplateInfo> listVolume(HostVO ssHost) {
    ListVolumeCommand cmd = new ListVolumeCommand(ssHost.getStorageUrl());
    Answer answer = _agentMgr.sendToSecStorage(ssHost, cmd);
    if (answer != null && answer.getResult()) {
      ListVolumeAnswer tanswer = (ListVolumeAnswer) answer;
      return tanswer.getTemplateInfo();
    } else {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Can not list volumes for secondary storage host " + ssHost.getId());
      }
    }

    return null;
  }
  private void updateNetworkLabels(HostVO host) {
    // check if networkLabels need to be updated in details
    // we send only private and storage network label to the resource.
    String privateNetworkLabel =
        _networkMgr.getDefaultManagementTrafficLabel(
            host.getDataCenterId(), host.getHypervisorType());
    String storageNetworkLabel =
        _networkMgr.getDefaultStorageTrafficLabel(host.getDataCenterId(), host.getHypervisorType());

    String privateDevice = host.getDetail("private.network.device");
    String storageDevice = host.getDetail("storage.network.device1");

    boolean update = false;

    if (privateNetworkLabel != null && !privateNetworkLabel.equalsIgnoreCase(privateDevice)) {
      host.setDetail("private.network.device", privateNetworkLabel);
      update = true;
    }
    if (storageNetworkLabel != null && !storageNetworkLabel.equalsIgnoreCase(storageDevice)) {
      host.setDetail("storage.network.device1", storageNetworkLabel);
      update = true;
    }
    if (update) {
      _hostDao.saveDetails(host);
    }
  }
  @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 void addSystemVMTemplatesToHost(HostVO host, Map<String, TemplateInfo> templateInfos) {
   if (templateInfos == null) {
     return;
   }
   Long hostId = host.getId();
   List<VMTemplateVO> rtngTmplts = _templateDao.listAllSystemVMTemplates();
   for (VMTemplateVO tmplt : rtngTmplts) {
     TemplateInfo tmpltInfo = templateInfos.get(tmplt.getUniqueName());
     if (tmpltInfo == null) {
       continue;
     }
     VMTemplateHostVO tmpltHost = _vmTemplateHostDao.findByHostTemplate(hostId, tmplt.getId());
     if (tmpltHost == null) {
       tmpltHost =
           new VMTemplateHostVO(
               hostId,
               tmplt.getId(),
               new Date(),
               100,
               Status.DOWNLOADED,
               null,
               null,
               null,
               tmpltInfo.getInstallPath(),
               tmplt.getUrl());
       tmpltHost.setSize(tmpltInfo.getSize());
       tmpltHost.setPhysicalSize(tmpltInfo.getPhysicalSize());
       _vmTemplateHostDao.persist(tmpltHost);
     }
   }
 }
  @DB
  private void updateClusterNativeHAState(HostVO host, StartupCommand cmd) {
    ClusterVO cluster = _clusterDao.findById(host.getClusterId());
    if (cluster.getClusterType() == ClusterType.ExternalManaged) {
      if (cmd instanceof StartupRoutingCommand) {
        StartupRoutingCommand hostStartupCmd = (StartupRoutingCommand) cmd;
        Map<String, String> details = hostStartupCmd.getHostDetails();

        if (details.get("NativeHA") != null && details.get("NativeHA").equalsIgnoreCase("true")) {
          _clusterDetailsDao.persist(host.getClusterId(), "NativeHA", "true");
        } else {
          _clusterDetailsDao.persist(host.getClusterId(), "NativeHA", "false");
        }
      }
    }
  }
 @Override
 public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage)
     throws UnableDeleteHostException {
   if (host.getType() != com.cloud.host.Host.Type.ExternalFirewall) {
     return null;
   }
   return new DeleteHostAnswer(true);
 }
  public boolean isZoneReady(Map<Long, ZoneHostInfo> zoneHostInfoMap, long dataCenterId) {
    ZoneHostInfo zoneHostInfo = zoneHostInfoMap.get(dataCenterId);
    if (zoneHostInfo != null
        && (zoneHostInfo.getFlags() & RunningHostInfoAgregator.ZoneHostInfo.ROUTING_HOST_MASK)
            != 0) {
      VMTemplateVO template = _templateDao.findSystemVMTemplate(dataCenterId);
      HostVO secHost = _hostDao.findSecondaryStorageHost(dataCenterId);
      if (secHost == null) {
        if (s_logger.isDebugEnabled()) {
          s_logger.debug(
              "No secondary storage available in zone "
                  + dataCenterId
                  + ", wait until it is ready to launch secondary storage vm");
        }
        return false;
      }

      boolean templateReady = false;
      if (template != null) {
        VMTemplateHostVO templateHostRef =
            _vmTemplateHostDao.findByHostTemplate(secHost.getId(), template.getId());
        templateReady =
            (templateHostRef != null) && (templateHostRef.getDownloadState() == Status.DOWNLOADED);
      }

      if (templateReady) {

        List<Pair<Long, Integer>> l =
            _storagePoolHostDao.getDatacenterStoragePoolHostInfo(dataCenterId, !_useLocalStorage);
        if (l != null && l.size() > 0 && l.get(0).second().intValue() > 0) {

          return true;
        } else {
          if (s_logger.isDebugEnabled()) {
            s_logger.debug(
                "Primary storage is not ready, wait until it is ready to launch secondary storage vm");
          }
        }
      } else {
        if (s_logger.isTraceEnabled()) {
          s_logger.trace("Zone host is ready, but secondary storage vm template is not ready");
        }
      }
    }
    return false;
  }
Beispiel #24
0
  @Override
  public Boolean fenceOff(VirtualMachine vm, Host host) {
    if (host.getHypervisorType() != HypervisorType.KVM
        && host.getHypervisorType() != HypervisorType.LXC) {
      s_logger.warn("Don't know how to fence non kvm hosts " + host.getHypervisorType());
      return null;
    }

    List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId());
    FenceCommand fence = new FenceCommand(vm, host);

    int i = 0;
    for (HostVO h : hosts) {
      if (h.getHypervisorType() == HypervisorType.KVM
          || h.getHypervisorType() == HypervisorType.LXC) {
        if (h.getStatus() != Status.Up) {
          continue;
        }

        i++;

        if (h.getId() == host.getId()) {
          continue;
        }
        FenceAnswer answer;
        try {
          answer = (FenceAnswer) _agentMgr.send(h.getId(), fence);
        } catch (AgentUnavailableException e) {
          s_logger.info("Moving on to the next host because " + h.toString() + " is unavailable");
          continue;
        } catch (OperationTimedoutException e) {
          s_logger.info("Moving on to the next host because " + h.toString() + " is unavailable");
          continue;
        }
        if (answer != null && answer.getResult()) {
          return true;
        }
      }
    }

    _alertMgr.sendAlert(
        AlertManager.AlertType.ALERT_TYPE_HOST,
        host.getDataCenterId(),
        host.getPodId(),
        "Unable to fence off host: " + host.getId(),
        "Fencing off host "
            + host.getId()
            + " did not succeed after asking "
            + i
            + " hosts. "
            + "Check Agent logs for more information.");

    s_logger.error("Unable to fence off " + vm.toString() + " on " + host.toString());

    return false;
  }
  @DB
  public void handleDownloadEvent(HostVO host, VMTemplateVO template, Status dnldStatus) {
    if ((dnldStatus == VMTemplateStorageResourceAssoc.Status.DOWNLOADED)
        || (dnldStatus == Status.ABANDONED)) {
      VMTemplateHostVO vmTemplateHost = new VMTemplateHostVO(host.getId(), template.getId());
      synchronized (_listenerMap) {
        _listenerMap.remove(vmTemplateHost);
      }
    }

    VMTemplateHostVO vmTemplateHost =
        _vmTemplateHostDao.findByHostTemplate(host.getId(), template.getId());

    Transaction txn = Transaction.currentTxn();
    txn.start();

    if (dnldStatus == Status.DOWNLOADED) {
      long size = -1;
      if (vmTemplateHost != null) {
        size = vmTemplateHost.getPhysicalSize();
        template.setSize(size);
        this._templateDao.update(template.getId(), template);
      } else {
        s_logger.warn("Failed to get size for template" + template.getName());
      }
      String eventType = EventTypes.EVENT_TEMPLATE_CREATE;
      if ((template.getFormat()).equals(ImageFormat.ISO)) {
        eventType = EventTypes.EVENT_ISO_CREATE;
      }
      if (template.getAccountId() != Account.ACCOUNT_ID_SYSTEM) {
        UsageEventUtils.publishUsageEvent(
            eventType,
            template.getAccountId(),
            host.getDataCenterId(),
            template.getId(),
            template.getName(),
            null,
            template.getSourceTemplateId(),
            size,
            template.getClass().getName(),
            template.getUuid());
      }
    }
    txn.commit();
  }
 @Override
 public DeleteHostAnswer deleteHost(
     final HostVO host, final boolean isForced, final boolean isForceDeleteStorage)
     throws UnableDeleteHostException {
   if (!(host.getType() == Host.Type.L2Networking)) {
     return null;
   }
   return new DeleteHostAnswer(true);
 }
  @Override
  public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage)
      throws UnableDeleteHostException {
    if (host.getType() != Host.Type.TrafficMonitor) {
      return null;
    }

    return new DeleteHostAnswer(true);
  }
  @Override
  public boolean shutdown(Network network, ReservationContext context, boolean cleanup)
      throws ConcurrentOperationException, ResourceUnavailableException {

    unassignAsa1000vFromNetwork(network);

    String vlan = network.getBroadcastUri().getHost();
    long vlanId = Long.parseLong(vlan);
    List<CiscoVnmcControllerVO> devices =
        _ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
    if (!devices.isEmpty()) {
      CiscoVnmcControllerVO ciscoVnmcDevice = devices.get(0);
      HostVO ciscoVnmcHost = _hostDao.findById(ciscoVnmcDevice.getHostId());
      cleanupLogicalEdgeFirewall(vlanId, ciscoVnmcHost.getId());
    }

    return true;
  }
  @Override
  public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage)
      throws UnableDeleteHostException {
    if (host.getType() != Host.Type.Routing || host.getHypervisorType() != HypervisorType.KVM) {
      return null;
    }

    _resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage);
    try {
      ShutdownCommand cmd = new ShutdownCommand(ShutdownCommand.DeleteHost, null);
      _agentMgr.send(host.getId(), cmd);
    } catch (AgentUnavailableException e) {
      s_logger.warn("Sending ShutdownCommand failed: ", e);
    } catch (OperationTimedoutException e) {
      s_logger.warn("Sending ShutdownCommand failed: ", e);
    }

    return new DeleteHostAnswer(true);
  }
 @Override
 public void processConnect(HostVO host, StartupCommand cmd, boolean forRebalance) {
   if (cmd instanceof StartupCommand) {
     if (host.getHypervisorType() == HypervisorType.VMware) {
       updateClusterNativeHAState(host, cmd);
     } else {
       return;
     }
   }
 }