Exemplo n.º 1
0
  private void createOrUpdateVlanCapacity(long dcId) {

    SearchCriteria<CapacityVO> capacitySC = _capacityDao.createSearchCriteria();

    List<CapacityVO> capacities = _capacityDao.search(capacitySC, null);
    capacitySC = _capacityDao.createSearchCriteria();
    capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ, dcId);
    capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, Capacity.CAPACITY_TYPE_VLAN);
    capacities = _capacityDao.search(capacitySC, null);

    int totalVlans = _dcDao.countZoneVlans(dcId, false);
    int allocatedVlans = _dcDao.countZoneVlans(dcId, true);

    if (capacities.size() == 0) {
      CapacityVO newPublicIPCapacity =
          new CapacityVO(
              null, dcId, null, null, allocatedVlans, totalVlans, Capacity.CAPACITY_TYPE_VLAN);
      _capacityDao.persist(newPublicIPCapacity);
    } else if (!(capacities.get(0).getUsedCapacity() == allocatedVlans
        && capacities.get(0).getTotalCapacity() == totalVlans)) {
      CapacityVO capacity = capacities.get(0);
      capacity.setUsedCapacity(allocatedVlans);
      capacity.setTotalCapacity(totalVlans);
      _capacityDao.update(capacity.getId(), capacity);
    }
  }
 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;
 }
 protected void cleanDb() {
   if (volumeId != null) {
     volumeDao.remove(volumeId);
     volumeId = null;
   }
   if (diskOfferingId != null) {
     diskOfferingDao.remove(diskOfferingId);
     diskOfferingId = null;
   }
   if (storagePoolId != null) {
     storagePoolDao.remove(storagePoolId);
     storagePoolId = null;
   }
   if (clusterId != null) {
     clusterDao.remove(clusterId);
     clusterId = null;
   }
   if (podId != null) {
     podDao.remove(podId);
     podId = null;
   }
   if (dcId != null) {
     dcDao.remove(dcId);
     dcId = null;
   }
 }
Exemplo n.º 4
0
  @Override
  public boolean applyLBRules(final Network network, final List<LoadBalancingRule> rules)
      throws ResourceUnavailableException {
    boolean result = true;
    if (canHandle(network, Service.Lb)) {
      if (!canHandleLbRules(rules)) {
        return false;
      }

      final List<DomainRouterVO> routers =
          _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
      if (routers == null || routers.isEmpty()) {
        s_logger.debug(
            "Virtual router elemnt doesn't need to apply firewall rules on the backend; virtual "
                + "router doesn't exist in the network "
                + network.getId());
        return true;
      }

      final DataCenterVO dcVO = _dcDao.findById(network.getDataCenterId());
      final NetworkTopology networkTopology = _networkTopologyContext.retrieveNetworkTopology(dcVO);

      for (final DomainRouterVO domainRouterVO : routers) {
        result = result && networkTopology.applyLoadBalancingRules(network, rules, domainRouterVO);
        if (!result) {
          s_logger.debug("Failed to apply load balancing rules in network " + network.getId());
        }
      }
    }
    return result;
  }
  @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;
    }
  }
  @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);
  }
  public DomainRouterVO deployLoadBalancerVM(Long networkId, IPAddressVO ipAddr, Long accountId) {
    NetworkVO network = _networkDao.findById(networkId);
    DataCenter dc = _dcDao.findById(network.getDataCenterId());
    Long podId = getPodIdForDirectIp(ipAddr);
    Pod pod = podId == null ? null : _podDao.findById(podId);
    Map<VirtualMachineProfile.Param, Object> params =
        new HashMap<VirtualMachineProfile.Param, Object>(1);
    params.put(VirtualMachineProfile.Param.ReProgramGuestNetworks, true);
    Account owner = _accountService.getActiveAccountByName("system", new Long(1));
    DeployDestination dest = new DeployDestination(dc, pod, null, null);
    s_logger.debug("About to deploy ELB vm ");

    try {
      DomainRouterVO elbVm = deployELBVm(network, dest, owner, params);
      if (elbVm == null) {
        throw new InvalidParameterValueException("Could not deploy or find existing ELB VM");
      }
      s_logger.debug("Deployed ELB  vm = " + elbVm);

      return elbVm;

    } catch (Throwable t) {
      s_logger.warn("Error while deploying ELB VM:  ", t);
      return null;
    }
  }
  @Override
  public void reserve(
      NicProfile nic,
      Network config,
      VirtualMachineProfile<? extends VirtualMachine> vm,
      DeployDestination dest,
      ReservationContext context)
      throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException {
    assert nic.getTrafficType() == TrafficType.Control;

    if (dest.getHost().getHypervisorType() == HypervisorType.VmWare
        && vm.getType() == VirtualMachine.Type.DomainRouter) {
      super.reserve(nic, config, vm, dest, context);

      String mac = _networkMgr.getNextAvailableMacAddressInNetwork(config.getId());
      nic.setMacAddress(mac);
      return;
    }

    String ip =
        _dcDao.allocateLinkLocalIpAddress(
            dest.getDataCenter().getId(),
            dest.getPod().getId(),
            nic.getId(),
            context.getReservationId());
    nic.setIp4Address(ip);
    nic.setMacAddress(NetUtils.long2Mac(NetUtils.ip2Long(ip) | (14l << 40)));
    nic.setNetmask("255.255.0.0");
    nic.setFormat(AddressFormat.Ip4);
    nic.setGateway(NetUtils.getLinkLocalGateway());
  }
Exemplo n.º 9
0
 @Override
 public void updateNicProfile(NicProfile profile, Network network) {
   DataCenter dc = _dcDao.findById(network.getDataCenterId());
   if (profile != null) {
     profile.setDns1(dc.getDns1());
     profile.setDns2(dc.getDns2());
   }
 }
  private void initializeForTest(VirtualMachineProfileImpl vmProfile, DataCenterDeployment plan) {
    DataCenterVO mockDc = mock(DataCenterVO.class);
    VMInstanceVO vm = mock(VMInstanceVO.class);
    UserVmVO userVm = mock(UserVmVO.class);
    ServiceOfferingVO offering = mock(ServiceOfferingVO.class);

    AccountVO account = mock(AccountVO.class);
    when(account.getId()).thenReturn(accountId);
    when(account.getAccountId()).thenReturn(accountId);
    when(vmProfile.getOwner()).thenReturn(account);
    when(vmProfile.getVirtualMachine()).thenReturn(vm);
    when(vmProfile.getId()).thenReturn(12L);
    when(vmDao.findById(12L)).thenReturn(userVm);
    when(userVm.getAccountId()).thenReturn(accountId);

    when(vm.getDataCenterId()).thenReturn(dataCenterId);
    when(dcDao.findById(1L)).thenReturn(mockDc);
    when(plan.getDataCenterId()).thenReturn(dataCenterId);
    when(plan.getClusterId()).thenReturn(null);
    when(plan.getPodId()).thenReturn(null);
    when(configDao.getValue(anyString())).thenReturn("false").thenReturn("CPU");

    // Mock offering details.
    when(vmProfile.getServiceOffering()).thenReturn(offering);
    when(offering.getId()).thenReturn(offeringId);
    when(vmProfile.getServiceOfferingId()).thenReturn(offeringId);
    when(offering.getCpu()).thenReturn(noOfCpusInOffering);
    when(offering.getSpeed()).thenReturn(cpuSpeedInOffering);
    when(offering.getRamSize()).thenReturn(ramInOffering);

    List<Long> clustersWithEnoughCapacity = new ArrayList<Long>();
    clustersWithEnoughCapacity.add(1L);
    clustersWithEnoughCapacity.add(2L);
    clustersWithEnoughCapacity.add(3L);
    when(capacityDao.listClustersInZoneOrPodByHostCapacities(
            dataCenterId,
            noOfCpusInOffering * cpuSpeedInOffering,
            ramInOffering * 1024L * 1024L,
            CapacityVO.CAPACITY_TYPE_CPU,
            true))
        .thenReturn(clustersWithEnoughCapacity);

    Map<Long, Double> clusterCapacityMap = new HashMap<Long, Double>();
    clusterCapacityMap.put(1L, 2048D);
    clusterCapacityMap.put(2L, 2048D);
    clusterCapacityMap.put(3L, 2048D);
    Pair<List<Long>, Map<Long, Double>> clustersOrderedByCapacity =
        new Pair<List<Long>, Map<Long, Double>>(clustersWithEnoughCapacity, clusterCapacityMap);
    when(capacityDao.orderClustersByAggregateCapacity(
            dataCenterId, CapacityVO.CAPACITY_TYPE_CPU, true))
        .thenReturn(clustersOrderedByCapacity);

    List<Long> disabledClusters = new ArrayList<Long>();
    List<Long> clustersWithDisabledPods = new ArrayList<Long>();
    when(clusterDao.listDisabledClusters(dataCenterId, null)).thenReturn(disabledClusters);
    when(clusterDao.listClustersWithDisabledPods(dataCenterId))
        .thenReturn(clustersWithDisabledPods);
  }
Exemplo n.º 11
0
 private void validateZone(Long zoneId) throws InvalidParameterValueException {
   // Check if zone with specified id exists
   DataCenterVO zone = _dcDao.findById(zoneId);
   if (zone == null) {
     InvalidParameterValueException ex =
         new InvalidParameterValueException("Can't find zone by the id specified.");
     throw ex;
   }
 }
 @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);
 }
  @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);
    }
  }
Exemplo n.º 14
0
  @Override
  public Network design(
      NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) {
    DataCenter dc = _dcDao.findById(plan.getDataCenterId());

    if (!canHandle(offering, dc)) {
      return null;
    }

    State state = State.Allocated;
    if (dc.getNetworkType() == NetworkType.Basic) {
      state = State.Setup;
    }

    NetworkVO config =
        new NetworkVO(
            offering.getTrafficType(),
            Mode.Dhcp,
            BroadcastDomainType.Vlan,
            offering.getId(),
            state,
            plan.getDataCenterId(),
            plan.getPhysicalNetworkId());

    if (userSpecified != null) {
      if ((userSpecified.getCidr() == null && userSpecified.getGateway() != null)
          || (userSpecified.getCidr() != null && userSpecified.getGateway() == null)) {
        throw new InvalidParameterValueException("cidr and gateway must be specified together.");
      }

      if (userSpecified.getCidr() != null) {
        config.setCidr(userSpecified.getCidr());
        config.setGateway(userSpecified.getGateway());
      }

      if (userSpecified.getBroadcastUri() != null) {
        config.setBroadcastUri(userSpecified.getBroadcastUri());
        config.setState(State.Setup);
      }

      if (userSpecified.getBroadcastDomainType() != null) {
        config.setBroadcastDomainType(userSpecified.getBroadcastDomainType());
      }
    }

    boolean isSecurityGroupEnabled =
        _networkMgr.areServicesSupportedByNetworkOffering(offering.getId(), Service.SecurityGroup);
    if (isSecurityGroupEnabled) {
      config.setName("SecurityGroupEnabledNetwork");
      config.setDisplayText("SecurityGroupEnabledNetwork");
    }

    return config;
  }
  @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;
  }
Exemplo n.º 16
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;
 }
  @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);
  }
  @Test
  public void checkWhenDcInAvoidList() throws InsufficientServerCapacityException {
    DataCenterVO mockDc = mock(DataCenterVO.class);
    ExcludeList avoids = mock(ExcludeList.class);
    VirtualMachineProfileImpl vmProfile = mock(VirtualMachineProfileImpl.class);
    VMInstanceVO vm = mock(VMInstanceVO.class);
    DataCenterDeployment plan = mock(DataCenterDeployment.class);

    when(avoids.shouldAvoid(mockDc)).thenReturn(true);
    when(vmProfile.getVirtualMachine()).thenReturn(vm);
    when(vm.getDataCenterId()).thenReturn(1L);
    when(dcDao.findById(1L)).thenReturn(mockDc);

    List<Long> clusterList = planner.orderClusters(vmProfile, plan, avoids);
    assertTrue(
        "Cluster list should be null/empty if the dc is in avoid list",
        (clusterList == null || clusterList.isEmpty()));
  }
  @Override
  public boolean release(
      NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, String reservationId) {
    assert nic.getTrafficType() == TrafficType.Control;

    if (vm.getHypervisorType() == HypervisorType.VmWare
        && vm.getType() == VirtualMachine.Type.DomainRouter) {
      super.release(nic, vm, reservationId);
      return true;
    }

    _dcDao.releaseLinkLocalIpAddress(nic.getId(), reservationId);
    nic.setIp4Address(null);
    nic.setMacAddress(null);
    nic.setNetmask(null);
    nic.setFormat(null);
    nic.setGateway(null);

    return true;
  }
Exemplo n.º 20
0
  @Override
  public NicProfile allocate(
      Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm)
      throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException,
          ConcurrentOperationException {

    DataCenter dc = _dcDao.findById(network.getDataCenterId());

    if (nic == null) {
      nic = new NicProfile(ReservationStrategy.Create, null, null, null, null);
    } else if (nic.getIp4Address() == null) {
      nic.setStrategy(ReservationStrategy.Start);
    } else {
      nic.setStrategy(ReservationStrategy.Create);
    }

    _networkMgr.allocateDirectIp(nic, dc, vm, network, nic.getRequestedIp());
    nic.setStrategy(ReservationStrategy.Create);

    return nic;
  }
 // 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);
     }
   }
 }
Exemplo n.º 22
0
  @Override
  public boolean applyIps(
      final Network network,
      final List<? extends PublicIpAddress> ipAddress,
      final Set<Service> services)
      throws ResourceUnavailableException {
    boolean canHandle = true;
    for (final Service service : services) {
      // check if Ovs can handle services except SourceNat & Firewall
      if (!canHandle(network, service)
          && service != Service.SourceNat
          && service != Service.Firewall) {
        canHandle = false;
        break;
      }
    }
    boolean result = true;
    if (canHandle) {
      final List<DomainRouterVO> routers =
          _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
      if (routers == null || routers.isEmpty()) {
        s_logger.debug(
            "Virtual router element doesn't need to associate ip addresses on the backend; virtual "
                + "router doesn't exist in the network "
                + network.getId());
        return true;
      }

      final DataCenterVO dcVO = _dcDao.findById(network.getDataCenterId());
      final NetworkTopology networkTopology = _networkTopologyContext.retrieveNetworkTopology(dcVO);

      for (final DomainRouterVO domainRouterVO : routers) {
        result = result && networkTopology.associatePublicIP(network, ipAddress, domainRouterVO);
      }
    }
    return result;
  }
Exemplo n.º 23
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;
  }
Exemplo n.º 24
0
  @Override
  public boolean applyStaticNats(final Network network, final List<? extends StaticNat> rules)
      throws ResourceUnavailableException {
    if (!canHandle(network, Service.StaticNat)) {
      return false;
    }
    final List<DomainRouterVO> routers =
        _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
    if (routers == null || routers.isEmpty()) {
      s_logger.debug(
          "Ovs element doesn't need to apply static nat on the backend; virtual "
              + "router doesn't exist in the network "
              + network.getId());
      return true;
    }

    final DataCenterVO dcVO = _dcDao.findById(network.getDataCenterId());
    final NetworkTopology networkTopology = _networkTopologyContext.retrieveNetworkTopology(dcVO);
    boolean result = true;
    for (final DomainRouterVO domainRouterVO : routers) {
      result = result && networkTopology.applyStaticNats(network, rules, domainRouterVO);
    }
    return result;
  }
  @Override
  public NicProfile allocate(
      Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm)
      throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException,
          ConcurrentOperationException {
    if (network.getTrafficType() != TrafficType.Public) {
      return null;
    }

    if (nic == null) {
      nic = new NicProfile(ReservationStrategy.Create, null, null, null, null);
    }

    DataCenter dc = _dcDao.findById(network.getDataCenterId());
    getIp(nic, dc, vm, network);

    if (nic.getIp4Address() == null) {
      nic.setStrategy(ReservationStrategy.Start);
    } else {
      nic.setStrategy(ReservationStrategy.Create);
    }

    return nic;
  }
  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;
  }
  @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();
    }
  }
Exemplo n.º 28
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);
  }
  @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;
  }
Exemplo n.º 30
0
 @Override
 public void updateNetworkProfile(NetworkProfile networkProfile) {
   DataCenter dc = _dcDao.findById(networkProfile.getDataCenterId());
   networkProfile.setDns1(dc.getDns1());
   networkProfile.setDns2(dc.getDns2());
 }