@Override
  public void run(FlowTrigger trigger, Map data) {
    PrimaryStorageAllocationSpec spec =
        (PrimaryStorageAllocationSpec) data.get(AllocatorParams.SPEC);
    List<PrimaryStorageVO> candidates =
        (List<PrimaryStorageVO>) data.get(AllocatorParams.CANDIDATES);
    DebugUtils.Assert(
        candidates != null && !candidates.isEmpty(),
        "PrimaryStorageTagAllocatorFlow cannot be the first element in allocator chain");

    List<SystemTagVO> tvos = null;
    if (spec.getVmInstanceUuid() != null) {
      SimpleQuery<SystemTagVO> q = dbf.createQuery(SystemTagVO.class);
      q.add(SystemTagVO_.resourceType, Op.EQ, VmInstanceVO.class.getSimpleName());
      q.add(SystemTagVO_.resourceUuid, Op.EQ, spec.getVmInstanceUuid());
      tvos = q.list();
    } else if (spec.getDiskOfferingUuid() != null) {
      SimpleQuery<SystemTagVO> q = dbf.createQuery(SystemTagVO.class);
      q.add(SystemTagVO_.resourceType, Op.EQ, DiskOfferingVO.class.getSimpleName());
      q.add(SystemTagVO_.resourceUuid, Op.EQ, spec.getDiskOfferingUuid());
      tvos = q.list();
    }

    if (tvos != null && !tvos.isEmpty()) {
      candidates = callTagExtensions(SystemTagInventory.valueOf(tvos), candidates);
      data.put(AllocatorParams.CANDIDATES, candidates);
    }

    trigger.next();
  }
  @Override
  public UsedIpInventory allocateIp(IpAllocateMessage msg) {
    if (msg.getRequiredIp() != null) {
      return allocateRequiredIp(msg);
    }

    SimpleQuery<IpRangeVO> query = dbf.createQuery(IpRangeVO.class);
    query.add(IpRangeVO_.l3NetworkUuid, Op.EQ, msg.getL3NetworkUuid());
    List<IpRangeVO> ranges = query.list();

    Collections.shuffle(ranges);

    do {
      String ip = null;
      IpRangeVO tr = null;

      for (IpRangeVO r : ranges) {
        ip = allocateIp(r);
        tr = r;
        if (ip != null) {
          break;
        }
      }

      if (ip == null) {
        /* No available ip in ranges */
        return null;
      }

      UsedIpInventory inv = l3NwMgr.reserveIp(IpRangeInventory.valueOf(tr), ip);
      if (inv != null) {
        return inv;
      }
    } while (true);
  }
Пример #3
0
 private void prepareFirewallInfo(FlowChain chain) {
   SimpleQuery<ApplianceVmFirewallRuleVO> q = dbf.createQuery(ApplianceVmFirewallRuleVO.class);
   q.add(ApplianceVmFirewallRuleVO_.applianceVmUuid, Op.EQ, getSelf().getUuid());
   List<ApplianceVmFirewallRuleVO> vos = q.list();
   List<ApplianceVmFirewallRuleInventory> rules = ApplianceVmFirewallRuleInventory.valueOf(vos);
   chain.getData().put(ApplianceVmConstant.Params.applianceVmFirewallRules.toString(), rules);
 }
Пример #4
0
 private void prepare() {
   int offset = 0;
   int step = 1000;
   while (offset < total) {
     SimpleQuery<ApplianceVmFirewallRuleVO> q =
         dbf.createQuery(ApplianceVmFirewallRuleVO.class);
     q.add(ApplianceVmFirewallRuleVO_.applianceVmUuid, Op.EQ, self.getUuid());
     q.setLimit(step);
     q.setStart(offset);
     List<ApplianceVmFirewallRuleVO> vos = q.list();
     for (ApplianceVmFirewallRuleVO vo : vos) {
       String key =
           String.format(
               "%s-%s-%s-%s-%s",
               vo.getL3NetworkUuid(),
               vo.getProtocol(),
               vo.getSourceIp(),
               vo.getDestIp(),
               vo.getAllowCidr());
       List<ApplianceVmFirewallRuleVO> lst = rules.get(key);
       if (lst == null) {
         lst = new ArrayList<ApplianceVmFirewallRuleVO>();
         rules.put(key, lst);
       }
       lst.add(vo);
     }
     offset += step;
   }
 }
 @Override
 public void run(FlowTrigger trigger, Map data) {
   final String vrUuid = (String) data.get(Param.VR_UUID.toString());
   SimpleQuery<VirtualRouterVipVO> q = dbf.createQuery(VirtualRouterVipVO.class);
   q.add(VirtualRouterVipVO_.virtualRouterVmUuid, Op.EQ, vrUuid);
   List<VirtualRouterVipVO> refs = q.list();
   if (!refs.isEmpty()) {
     dbf.removeCollection(refs, VirtualRouterVipVO.class);
   }
   trigger.next();
 }
Пример #6
0
  private List<VmInstanceInventory> vmFromDeleteAction(CascadeAction action) {
    List<VmInstanceInventory> ret = null;
    if (HostVO.class.getSimpleName().equals(action.getParentIssuer())) {
      List<HostInventory> hosts = action.getParentIssuerContext();
      List<String> huuids =
          CollectionUtils.transformToList(
              hosts,
              new Function<String, HostInventory>() {
                @Override
                public String call(HostInventory arg) {
                  return arg.getUuid();
                }
              });

      Map<String, VmInstanceVO> vmvos = new HashMap<String, VmInstanceVO>();
      SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
      q.add(VmInstanceVO_.hostUuid, SimpleQuery.Op.IN, huuids);
      q.add(VmInstanceVO_.type, Op.EQ, VmInstanceConstant.USER_VM_TYPE);
      List<VmInstanceVO> lst = q.list();
      for (VmInstanceVO vo : lst) {
        vmvos.put(vo.getUuid(), vo);
      }

      if (ClusterVO.class.getSimpleName().equals(action.getRootIssuer())) {
        List<ClusterInventory> clusters = action.getRootIssuerContext();
        List<String> clusterUuids =
            CollectionUtils.transformToList(
                clusters,
                new Function<String, ClusterInventory>() {
                  @Override
                  public String call(ClusterInventory arg) {
                    return arg.getUuid();
                  }
                });
        q = dbf.createQuery(VmInstanceVO.class);
        q.add(VmInstanceVO_.clusterUuid, Op.IN, clusterUuids);
        q.add(VmInstanceVO_.type, Op.EQ, VmInstanceConstant.USER_VM_TYPE);
        lst = q.list();
        for (VmInstanceVO vo : lst) {
          vmvos.put(vo.getUuid(), vo);
        }
      } else if (ZoneVO.class.getSimpleName().equals(action.getRootIssuer())) {
        List<ZoneInventory> zones = action.getRootIssuerContext();
        List<String> zoneUuids =
            CollectionUtils.transformToList(
                zones,
                new Function<String, ZoneInventory>() {
                  @Override
                  public String call(ZoneInventory arg) {
                    return arg.getUuid();
                  }
                });
        q = dbf.createQuery(VmInstanceVO.class);
        q.add(VmInstanceVO_.zoneUuid, Op.IN, zoneUuids);
        q.add(VmInstanceVO_.type, Op.EQ, VmInstanceConstant.USER_VM_TYPE);
        lst = q.list();
        for (VmInstanceVO vo : lst) {
          vmvos.put(vo.getUuid(), vo);
        }
      }

      if (!vmvos.isEmpty()) {
        ret = VmInstanceInventory.valueOf(vmvos.values());
      }
    } else if (NAME.equals(action.getParentIssuer())) {
      return action.getParentIssuerContext();
    } else if (PrimaryStorageVO.class.getSimpleName().equals(action.getParentIssuer())) {
      final List<String> pruuids =
          CollectionUtils.transformToList(
              (List<PrimaryStorageInventory>) action.getParentIssuerContext(),
              new Function<String, PrimaryStorageInventory>() {
                @Override
                public String call(PrimaryStorageInventory arg) {
                  return arg.getUuid();
                }
              });

      List<VmInstanceVO> vmvos =
          new Callable<List<VmInstanceVO>>() {
            @Override
            @Transactional(readOnly = true)
            public List<VmInstanceVO> call() {
              String sql =
                  "select vm from VmInstanceVO vm, VolumeVO vol, PrimaryStorageVO pr where vm.type = :vmType and vm.uuid = vol.vmInstanceUuid"
                      + " and vol.primaryStorageUuid = pr.uuid and vol.type = :volType and pr.uuid in (:uuids) group by vm.uuid";
              TypedQuery<VmInstanceVO> q =
                  dbf.getEntityManager().createQuery(sql, VmInstanceVO.class);
              q.setParameter("vmType", VmInstanceConstant.USER_VM_TYPE);
              q.setParameter("uuids", pruuids);
              q.setParameter("volType", VolumeType.Root);
              return q.getResultList();
            }
          }.call();

      if (!vmvos.isEmpty()) {
        ret = VmInstanceInventory.valueOf(vmvos);
      }
    } else if (L3NetworkVO.class.getSimpleName().equals(action.getParentIssuer())) {
      final List<String> l3uuids =
          CollectionUtils.transformToList(
              (List<L3NetworkInventory>) action.getParentIssuerContext(),
              new Function<String, L3NetworkInventory>() {
                @Override
                public String call(L3NetworkInventory arg) {
                  return arg.getUuid();
                }
              });

      List<VmInstanceVO> vmvos =
          new Callable<List<VmInstanceVO>>() {
            @Override
            @Transactional(readOnly = true)
            public List<VmInstanceVO> call() {
              String sql =
                  "select vm from VmInstanceVO vm, L3NetworkVO l3, VmNicVO nic where vm.type = :vmType and vm.uuid = nic.vmInstanceUuid and vm.state not in (:vmStates)"
                      + " and nic.l3NetworkUuid = l3.uuid and l3.uuid in (:uuids) group by vm.uuid";
              TypedQuery<VmInstanceVO> q =
                  dbf.getEntityManager().createQuery(sql, VmInstanceVO.class);
              q.setParameter("vmType", VmInstanceConstant.USER_VM_TYPE);
              q.setParameter(
                  "vmStates", Arrays.asList(VmInstanceState.Stopped, VmInstanceState.Stopping));
              q.setParameter("uuids", l3uuids);
              return q.getResultList();
            }
          }.call();

      if (!vmvos.isEmpty()) {
        ret = VmInstanceInventory.valueOf(vmvos);
      }
    } else if (IpRangeVO.class.getSimpleName().equals(action.getParentIssuer())) {
      final List<String> ipruuids =
          CollectionUtils.transformToList(
              (List<IpRangeInventory>) action.getParentIssuerContext(),
              new Function<String, IpRangeInventory>() {
                @Override
                public String call(IpRangeInventory arg) {
                  return arg.getUuid();
                }
              });

      List<VmInstanceVO> vmvos =
          new Callable<List<VmInstanceVO>>() {
            @Override
            @Transactional(readOnly = true)
            public List<VmInstanceVO> call() {
              String sql =
                  "select vm from VmInstanceVO vm, VmNicVO nic, UsedIpVO ip, IpRangeVO ipr where vm.type = :vmType and vm.uuid = nic.vmInstanceUuid and vm.state not in (:vmStates)"
                      + " and nic.usedIpUuid = ip.uuid and ip.ipRangeUuid = ipr.uuid and ipr.uuid in (:uuids) group by vm.uuid";
              TypedQuery<VmInstanceVO> q =
                  dbf.getEntityManager().createQuery(sql, VmInstanceVO.class);
              q.setParameter("vmType", VmInstanceConstant.USER_VM_TYPE);
              q.setParameter(
                  "vmStates", Arrays.asList(VmInstanceState.Stopped, VmInstanceState.Stopping));
              q.setParameter("uuids", ipruuids);
              return q.getResultList();
            }
          }.call();

      if (!vmvos.isEmpty()) {
        ret = VmInstanceInventory.valueOf(vmvos);
      }
    } else if (AccountVO.class.getSimpleName().equals(action.getParentIssuer())) {
      final List<String> auuids =
          CollectionUtils.transformToList(
              (List<AccountInventory>) action.getParentIssuerContext(),
              new Function<String, AccountInventory>() {
                @Override
                public String call(AccountInventory arg) {
                  return arg.getUuid();
                }
              });

      List<VmInstanceVO> vmvos =
          new Callable<List<VmInstanceVO>>() {
            @Override
            @Transactional(readOnly = true)
            public List<VmInstanceVO> call() {
              String sql =
                  "select d from VmInstanceVO d, AccountResourceRefVO r where d.uuid = r.resourceUuid and"
                      + " r.resourceType = :rtype and r.accountUuid in (:auuids) group by d.uuid";
              TypedQuery<VmInstanceVO> q =
                  dbf.getEntityManager().createQuery(sql, VmInstanceVO.class);
              q.setParameter("rtype", VmInstanceVO.class.getSimpleName());
              q.setParameter("auuids", auuids);
              return q.getResultList();
            }
          }.call();

      if (!vmvos.isEmpty()) {
        ret = VmInstanceInventory.valueOf(vmvos);
      }
    }

    return ret;
  }
Пример #7
0
  @Override
  protected void startVmFromNewCreate(
      final StartNewCreatedVmInstanceMsg msg, final SyncTaskChain taskChain) {
    boolean callNext = true;
    try {
      refreshVO();
      ErrorCode allowed = validateOperationByState(msg, self.getState(), null);
      if (allowed != null) {
        bus.replyErrorByMessageType(msg, allowed);
        return;
      }
      ErrorCode preCreated = extEmitter.preStartNewCreatedVm(msg.getVmInstanceInventory());
      if (preCreated != null) {
        bus.replyErrorByMessageType(msg, preCreated);
        return;
      }

      StartNewCreatedApplianceVmMsg smsg = (StartNewCreatedApplianceVmMsg) msg;
      ApplianceVmSpec aspec = smsg.getApplianceVmSpec();

      final VmInstanceSpec spec = new VmInstanceSpec();
      spec.setVmInventory(msg.getVmInstanceInventory());
      if (msg.getL3NetworkUuids() != null && !msg.getL3NetworkUuids().isEmpty()) {
        SimpleQuery<L3NetworkVO> nwquery = dbf.createQuery(L3NetworkVO.class);
        nwquery.add(L3NetworkVO_.uuid, SimpleQuery.Op.IN, msg.getL3NetworkUuids());
        List<L3NetworkVO> vos = nwquery.list();
        List<L3NetworkInventory> nws = L3NetworkInventory.valueOf(vos);
        spec.setL3Networks(nws);
      } else {
        spec.setL3Networks(new ArrayList<L3NetworkInventory>(0));
      }

      if (msg.getDataDiskOfferingUuids() != null && !msg.getDataDiskOfferingUuids().isEmpty()) {
        SimpleQuery<DiskOfferingVO> dquery = dbf.createQuery(DiskOfferingVO.class);
        dquery.add(DiskOfferingVO_.uuid, SimpleQuery.Op.IN, msg.getDataDiskOfferingUuids());
        List<DiskOfferingVO> vos = dquery.list();

        // allow create multiple data volume from the same disk offering
        List<DiskOfferingInventory> disks = new ArrayList<DiskOfferingInventory>();
        for (final String duuid : msg.getDataDiskOfferingUuids()) {
          DiskOfferingVO dvo =
              CollectionUtils.find(
                  vos,
                  new Function<DiskOfferingVO, DiskOfferingVO>() {
                    @Override
                    public DiskOfferingVO call(DiskOfferingVO arg) {
                      if (duuid.equals(arg.getUuid())) {
                        return arg;
                      }
                      return null;
                    }
                  });
          disks.add(DiskOfferingInventory.valueOf(dvo));
        }
        spec.setDataDiskOfferings(disks);
      } else {
        spec.setDataDiskOfferings(new ArrayList<DiskOfferingInventory>(0));
      }

      ImageVO imvo = dbf.findByUuid(spec.getVmInventory().getImageUuid(), ImageVO.class);
      spec.getImageSpec().setInventory(ImageInventory.valueOf(imvo));

      spec.putExtensionData(ApplianceVmConstant.Params.applianceVmSpec.toString(), aspec);
      spec.setCurrentVmOperation(VmInstanceConstant.VmOperation.NewCreate);
      spec.putExtensionData(
          ApplianceVmConstant.Params.applianceVmSubType.toString(), getSelf().getApplianceVmType());

      changeVmStateInDb(VmInstanceStateEvent.starting);

      extEmitter.beforeStartNewCreatedVm(VmInstanceInventory.valueOf(self));
      FlowChain chain = apvmf.getCreateApplianceVmWorkFlowBuilder().build();
      chain.setName(String.format("create-appliancevm-%s", msg.getVmInstanceUuid()));
      chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec);
      chain
          .getData()
          .put(
              ApplianceVmConstant.Params.applianceVmFirewallRules.toString(),
              aspec.getFirewallRules());

      addBootstrapFlows(
          chain, VolumeFormat.getMasterHypervisorTypeByVolumeFormat(imvo.getFormat()));

      List<Flow> subCreateFlows = getPostCreateFlows();
      if (subCreateFlows != null) {
        for (Flow f : subCreateFlows) {
          chain.then(f);
        }
      }

      chain.then(
          new NoRollbackFlow() {
            String __name__ = "change-appliancevm-status-to-connected";

            @Override
            public void run(FlowTrigger trigger, Map data) {
              // must reload here, otherwise it will override changes created by previous flows
              self = dbf.reload(self);
              getSelf().setStatus(ApplianceVmStatus.Connected);
              dbf.update(self);
              trigger.next();
            }
          });

      boolean noRollbackOnFailure = ApplianceVmGlobalProperty.NO_ROLLBACK_ON_POST_FAILURE;
      chain.noRollback(noRollbackOnFailure);
      chain
          .done(
              new FlowDoneHandler(msg, taskChain) {
                @Override
                public void handle(Map data) {
                  VmInstanceSpec spec =
                      (VmInstanceSpec)
                          data.get(VmInstanceConstant.Params.VmInstanceSpec.toString());
                  self = dbf.reload(self);
                  self.setLastHostUuid(spec.getDestHost().getUuid());
                  self.setHostUuid(spec.getDestHost().getUuid());
                  self.setClusterUuid(spec.getDestHost().getClusterUuid());
                  self.setZoneUuid(spec.getDestHost().getZoneUuid());
                  self.setHypervisorType(spec.getDestHost().getHypervisorType());
                  self.setRootVolumeUuid(spec.getDestRootVolume().getUuid());
                  changeVmStateInDb(VmInstanceStateEvent.running);
                  logger.debug(
                      String.format(
                          "appliance vm[uuid:%s, name: %s, type:%s] is running ..",
                          self.getUuid(), self.getName(), getSelf().getApplianceVmType()));
                  VmInstanceInventory inv = VmInstanceInventory.valueOf(self);
                  extEmitter.afterStartNewCreatedVm(inv);
                  StartNewCreatedVmInstanceReply reply = new StartNewCreatedVmInstanceReply();
                  reply.setVmInventory(inv);
                  bus.reply(msg, reply);
                  taskChain.next();
                }
              })
          .error(
              new FlowErrorHandler(msg, taskChain) {
                @Override
                public void handle(ErrorCode errCode, Map data) {
                  extEmitter.failedToStartNewCreatedVm(VmInstanceInventory.valueOf(self), errCode);
                  dbf.remove(self);
                  StartNewCreatedVmInstanceReply reply = new StartNewCreatedVmInstanceReply();
                  reply.setError(errCode);
                  reply.setSuccess(false);
                  bus.reply(msg, reply);
                  taskChain.next();
                }
              })
          .start();

      callNext = false;
    } finally {
      if (callNext) {
        taskChain.next();
      }
    }
  }