@Override
  @DB
  public BaremetalPxeVO addPxeServer(AddBaremetalPxeCmd cmd) {
    AddBaremetalPxePingServerCmd pcmd = (AddBaremetalPxePingServerCmd) cmd;

    PhysicalNetworkVO pNetwork = null;
    long zoneId;

    if (cmd.getPhysicalNetworkId() == null
        || cmd.getUrl() == null
        || cmd.getUsername() == null
        || cmd.getPassword() == null) {
      throw new IllegalArgumentException(
          "At least one of the required parameters(physical network id, url, username, password) is null");
    }

    pNetwork = _physicalNetworkDao.findById(cmd.getPhysicalNetworkId());
    if (pNetwork == null) {
      throw new IllegalArgumentException(
          "Could not find phyical network with ID: " + cmd.getPhysicalNetworkId());
    }
    zoneId = pNetwork.getDataCenterId();

    PhysicalNetworkServiceProviderVO ntwkSvcProvider =
        _physicalNetworkServiceProviderDao.findByServiceProvider(
            pNetwork.getId(), BaremetalPxeManager.BAREMETAL_PXE_SERVICE_PROVIDER.getName());
    if (ntwkSvcProvider == null) {
      throw new CloudRuntimeException(
          "Network Service Provider: "
              + BaremetalPxeManager.BAREMETAL_PXE_SERVICE_PROVIDER.getName()
              + " is not enabled in the physical network: "
              + cmd.getPhysicalNetworkId()
              + "to add this device");
    } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
      throw new CloudRuntimeException(
          "Network Service Provider: "
              + ntwkSvcProvider.getProviderName()
              + " is in shutdown state in the physical network: "
              + cmd.getPhysicalNetworkId()
              + "to add this device");
    }

    HostPodVO pod = _podDao.findById(cmd.getPodId());
    if (pod == null) {
      throw new IllegalArgumentException("Could not find pod with ID: " + cmd.getPodId());
    }

    List<HostVO> pxes =
        _resourceMgr.listAllUpAndEnabledHosts(Host.Type.BaremetalPxe, null, cmd.getPodId(), zoneId);
    if (pxes.size() != 0) {
      throw new IllegalArgumentException(
          "Already had a PXE server in Pod: " + cmd.getPodId() + " zone: " + zoneId);
    }

    String storageServerIp = pcmd.getPingStorageServerIp();
    if (storageServerIp == null) {
      throw new IllegalArgumentException("No IP for storage server specified");
    }
    String pingDir = pcmd.getPingDir();
    if (pingDir == null) {
      throw new IllegalArgumentException("No direcotry for storage server specified");
    }
    String tftpDir = pcmd.getTftpDir();
    if (tftpDir == null) {
      throw new IllegalArgumentException("No TFTP directory specified");
    }

    String cifsUsername = pcmd.getPingStorageServerUserName();
    if (cifsUsername == null || cifsUsername.equalsIgnoreCase("")) {
      cifsUsername = "******";
    }
    String cifsPassword = pcmd.getPingStorageServerPassword();
    if (cifsPassword == null || cifsPassword.equalsIgnoreCase("")) {
      cifsPassword = "******";
    }

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

    String guid =
        getPxeServerGuid(
            Long.toString(zoneId) + "-" + pod.getId(), BaremetalPxeType.PING.toString(), ipAddress);

    ServerResource resource = null;
    Map params = new HashMap<String, String>();
    params.put(BaremetalPxeService.PXE_PARAM_ZONE, Long.toString(zoneId));
    params.put(BaremetalPxeService.PXE_PARAM_POD, String.valueOf(pod.getId()));
    params.put(BaremetalPxeService.PXE_PARAM_IP, ipAddress);
    params.put(BaremetalPxeService.PXE_PARAM_USERNAME, cmd.getUsername());
    params.put(BaremetalPxeService.PXE_PARAM_PASSWORD, cmd.getPassword());
    params.put(BaremetalPxeService.PXE_PARAM_PING_STORAGE_SERVER_IP, storageServerIp);
    params.put(BaremetalPxeService.PXE_PARAM_PING_ROOT_DIR, pingDir);
    params.put(BaremetalPxeService.PXE_PARAM_TFTP_DIR, tftpDir);
    params.put(BaremetalPxeService.PXE_PARAM_PING_STORAGE_SERVER_USERNAME, cifsUsername);
    params.put(BaremetalPxeService.PXE_PARAM_PING_STORAGE_SERVER_PASSWORD, cifsPassword);
    params.put(BaremetalPxeService.PXE_PARAM_GUID, guid);

    resource = new BaremetalPingPxeResource();
    try {
      resource.configure("PING PXE resource", params);
    } catch (Exception e) {
      s_logger.debug(e);
      throw new CloudRuntimeException(e.getMessage());
    }

    Host pxeServer = _resourceMgr.addHost(zoneId, resource, Host.Type.BaremetalPxe, params);
    if (pxeServer == null) {
      throw new CloudRuntimeException("Cannot add PXE server as a host");
    }

    BaremetalPxeVO vo = new BaremetalPxeVO();
    Transaction txn = Transaction.currentTxn();
    vo.setHostId(pxeServer.getId());
    vo.setNetworkServiceProviderId(ntwkSvcProvider.getId());
    vo.setPodId(pod.getId());
    vo.setPhysicalNetworkId(pcmd.getPhysicalNetworkId());
    vo.setDeviceType(BaremetalPxeType.PING.toString());
    txn.start();
    _pxeDao.persist(vo);
    txn.commit();
    return vo;
  }
  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();
  }
Ejemplo n.º 3
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);
  }
Ejemplo n.º 4
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);
  }
Ejemplo n.º 5
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);
    }
  }
Ejemplo n.º 6
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);
        }
      }
    }
  }
Ejemplo n.º 7
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);
    }
  }