@Override
  public NetworkServiceProviderType getTypeOfNetworkServiceProviderForService(
      String l3NetworkUuid, NetworkServiceType serviceType) {
    L3NetworkVO l3vo = dbf.findByUuid(l3NetworkUuid, L3NetworkVO.class);
    L3NetworkInventory l3inv = L3NetworkInventory.valueOf(l3vo);
    NetworkServiceL3NetworkRefInventory targetRef = null;
    for (NetworkServiceL3NetworkRefInventory ref : l3inv.getNetworkServices()) {
      if (ref.getNetworkServiceType().equals(serviceType.toString())) {
        targetRef = ref;
        break;
      }
    }

    if (targetRef == null) {
      throw new OperationFailureException(
          errf.stringToOperationError(
              String.format(
                  "L3Network[uuid:%s] doesn't have network service[type:%s] enabled or no provider provides this network service",
                  l3NetworkUuid, serviceType)));
    }

    SimpleQuery<NetworkServiceProviderVO> q = dbf.createQuery(NetworkServiceProviderVO.class);
    q.select(NetworkServiceProviderVO_.type);
    q.add(NetworkServiceProviderVO_.uuid, Op.EQ, targetRef.getNetworkServiceProviderUuid());
    String providerType = q.findValue();
    return NetworkServiceProviderType.valueOf(providerType);
  }
Exemplo n.º 2
0
 @Test
 public void test() throws ApiSenderException {
   ZoneInventory zone = api.createZones(1).get(0);
   L2NetworkInventory linv = api.createNoVlanL2Network(zone.getUuid(), "eth0");
   L3NetworkInventory l3inv = api.createL3BasicNetwork(linv.getUuid());
   l3inv.setName("1");
   l3inv.setDescription("xxx");
   l3inv = api.updateL3Network(l3inv);
   Assert.assertEquals("1", l3inv.getName());
   Assert.assertEquals("xxx", l3inv.getDescription());
 }
Exemplo n.º 3
0
  @Test
  public void test() throws ApiSenderException, InterruptedException {
    CoreGlobalProperty.VM_TRACER_ON = false;
    IdentityGlobalConfig.SESSION_TIMEOUT.updateValue(TimeUnit.HOURS.toSeconds(1000));
    api.prepare();
    InstanceOfferingInventory ioinv = api.listInstanceOffering(null).get(0);
    ImageInventory iminv = api.listImage(null).get(0);
    List<DiskOfferingInventory> dinvs = api.listDiskOffering(null);
    List<L3NetworkInventory> nwinvs = api.listL3Network(null);
    List<String> nws = new ArrayList<String>(nwinvs.size());
    for (L3NetworkInventory nwinv : nwinvs) {
      nws.add(nwinv.getUuid());
    }

    for (int i = 0; i < vmNum; i++) {
      VmInstanceInventory vm = new VmInstanceInventory();
      vm.setDescription("TestVm");
      vm.setName("TestVm");
      vm.setType(VmInstanceConstant.USER_VM_TYPE);
      vm.setInstanceOfferingUuid(ioinv.getUuid());
      vm.setImageUuid(iminv.getUuid());
      createVm(vm, dinvs.get(0).getUuid(), nws, new ArrayList<String>());
    }
    latch.await(600, TimeUnit.MINUTES);
    long totalTime = 0;
    long minTime = 0;
    long maxTime = 0;
    for (Long t : timeCost) {
      minTime = Math.min(minTime, t);
      maxTime = Math.max(maxTime, t);
      totalTime += t;
    }
    System.out.println(
        String.format(
            "total time: %s, min time: %s, max time: %s, avg  time: %s",
            TimeUnit.MILLISECONDS.toSeconds(totalTime),
            TimeUnit.MILLISECONDS.toSeconds(minTime),
            TimeUnit.MILLISECONDS.toSeconds(maxTime),
            TimeUnit.MILLISECONDS.toSeconds(totalTime / timeCost.size())));

    /*
    SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
    q.add(VmInstanceVO_.state, Op.EQ, VmInstanceState.Running);
    long count = q.count();
    Assert.assertEquals(vmNum, count);
    */
    TimeUnit.HOURS.sleep(1000);
  }
Exemplo n.º 4
0
 @Test
 public void test() throws ApiSenderException {
   ImageInventory iminv = deployer.images.get("TestImage");
   InstanceOfferingInventory ioinv = deployer.instanceOfferings.get("TestInstanceOffering");
   L3NetworkInventory l3inv = deployer.l3Networks.get("TestL3Network2");
   APICreateVmInstanceMsg msg = new APICreateVmInstanceMsg();
   msg.setImageUuid(iminv.getUuid());
   msg.setInstanceOfferingUuid(ioinv.getUuid());
   List<String> l3uuids = new ArrayList<String>();
   l3uuids.add(l3inv.getUuid());
   msg.setL3NetworkUuids(l3uuids);
   msg.setName("TestVm");
   msg.setSession(session);
   msg.setServiceId(ApiMediatorConstant.SERVICE_ID);
   msg.setType(VmInstanceConstant.USER_VM_TYPE);
   ApiSender sender = api.getApiSender();
   sender.send(msg, APICreateVmInstanceEvent.class);
 }
  @Test
  public void test() throws ApiSenderException {
    L3NetworkInventory l3 = deployer.l3Networks.get("l3Network1");
    InstanceOfferingInventory instanceOffering =
        deployer.instanceOfferings.get("instanceOffering512M512HZ");
    ImageInventory imageInventory = deployer.images.get("image1");
    ZoneInventory zone1 = deployer.zones.get("zone1");

    VmCreator creator = new VmCreator();
    creator.addL3Network(l3.getUuid());
    creator.imageUuid = imageInventory.getUuid();
    creator.instanceOfferingUuid = instanceOffering.getUuid();
    creator.zoneUuid = zone1.getUuid();
    VmInstanceInventory vm = creator.create();
    HostCapacityVO cvo = dbf.findByUuid(vm.getHostUuid(), HostCapacityVO.class);
    Assert.assertEquals(instanceOffering.getCpuNum(), cvo.getUsedCpu());
    Assert.assertEquals(instanceOffering.getMemorySize(), cvo.getUsedMemory());
    Assert.assertEquals(zone1.getUuid(), vm.getZoneUuid());
  }
Exemplo n.º 6
0
 @AsyncThread
 private void createVm(ImageInventory img, String bsUuid) throws ApiSenderException {
   img = api.addImage(img, bsUuid);
   InstanceOfferingInventory ioinv = deployer.instanceOfferings.get("small");
   L3NetworkInventory l3 = deployer.l3Networks.get("TestL3Network1");
   VmCreator creator = new VmCreator(api);
   creator.imageUuid = img.getUuid();
   creator.session = api.getAdminSession();
   creator.instanceOfferingUuid = ioinv.getUuid();
   creator.name = "vm";
   creator.addL3Network(l3.getUuid());
   try {
     synchronized (vms) {
       vms.add(creator.create());
     }
   } finally {
     latch.countDown();
   }
 }
  @Test
  public void test() throws ApiSenderException, InterruptedException {
    VmInstanceInventory vm = deployer.vms.get("TestVm");
    final L3NetworkInventory l31 = deployer.l3Networks.get("TestL3Network1");
    final L3NetworkInventory l32 = deployer.l3Networks.get("TestL3Network2");

    VmNicInventory nic1 =
        CollectionUtils.find(
            vm.getVmNics(),
            new Function<VmNicInventory, VmNicInventory>() {
              @Override
              public VmNicInventory call(VmNicInventory arg) {
                return arg.getL3NetworkUuid().equals(l31.getUuid()) ? arg : null;
              }
            });
    VmNicInventory nic2 =
        CollectionUtils.find(
            vm.getVmNics(),
            new Function<VmNicInventory, VmNicInventory>() {
              @Override
              public VmNicInventory call(VmNicInventory arg) {
                return arg.getL3NetworkUuid().equals(l32.getUuid()) ? arg : null;
              }
            });

    VmInstanceInventory update = new VmInstanceInventory();
    update.setUuid(vm.getUuid());
    update.setDefaultL3NetworkUuid(l32.getUuid());
    api.updateVm(update);
    TimeUnit.SECONDS.sleep(2);
    Assert.assertEquals(1, fconfig.resetDefaultGatewayCmds.size());
    ResetDefaultGatewayCmd cmd = fconfig.resetDefaultGatewayCmds.get(0);
    Assert.assertEquals(nic1.getMac(), cmd.macOfGatewayToRemove);
    Assert.assertEquals(nic1.getGateway(), cmd.gatewayToRemove);
    Assert.assertEquals(
        new BridgeNameFinder().findByL3Uuid(l31.getUuid()), cmd.bridgeNameOfGatewayToRemove);

    Assert.assertEquals(nic2.getMac(), cmd.macOfGatewayToAdd);
    Assert.assertEquals(nic2.getGateway(), cmd.gatewayToAdd);
    Assert.assertEquals(
        new BridgeNameFinder().findByL3Uuid(l32.getUuid()), cmd.bridgeNameOfGatewayToAdd);
  }
Exemplo n.º 8
0
 private void prepareLifeCycleInfo(FlowChain chain) {
   ApplianceVmPostLifeCycleInfo info = new ApplianceVmPostLifeCycleInfo();
   ApplianceVmInventory ainv = ApplianceVmInventory.valueOf(getSelf());
   L3NetworkVO defaultRouteL3VO =
       dbf.findByUuid(ainv.getDefaultRouteL3NetworkUuid(), L3NetworkVO.class);
   info.setDefaultRouteL3Network(L3NetworkInventory.valueOf(defaultRouteL3VO));
   info.setManagementNic(ainv.getManagementNic());
   chain
       .getData()
       .put(ApplianceVmConstant.Params.applianceVmInfoForPostLifeCycle.toString(), info);
 }
Exemplo n.º 9
0
  @Test
  public void test() throws ApiSenderException {
    final L3NetworkInventory l3 = deployer.l3Networks.get("TestL3Network4");
    VmInstanceInventory vm = deployer.vms.get("TestVm");
    vm = api.attachNic(vm.getUuid(), l3.getUuid());
    Assert.assertEquals(4, vm.getVmNics().size());

    VmNicInventory nic = vm.getVmNics().get(0);
    vm = api.detachNic(nic.getUuid());
    Assert.assertEquals(3, vm.getVmNics().size());
    Assert.assertFalse(config.detachNicCommands.isEmpty());

    String l3Uuid = nic.getL3NetworkUuid();
    nic = vm.findNic(l3Uuid);
    Assert.assertNull(nic);

    api.stopVmInstance(vm.getUuid());
    vm = api.startVmInstance(vm.getUuid());
    Assert.assertEquals(3, vm.getVmNics().size());
    nic = vm.findNic(l3Uuid);
    Assert.assertNull(nic);
  }
Exemplo n.º 10
0
  private void handleDeletion(final CascadeAction action, final Completion completion) {
    int op = toDeletionOpCode(action);
    if (op == OP_NOPE) {
      completion.success();
      return;
    }

    if (op == OP_REMOVE_INSTANCE_OFFERING) {
      if (VmGlobalConfig.UPDATE_INSTANCE_OFFERING_TO_NULL_WHEN_DELETING.value(Boolean.class)) {
        new Runnable() {
          @Override
          @Transactional
          public void run() {
            List<InstanceOfferingInventory> offerings = action.getParentIssuerContext();
            List<String> offeringUuids =
                CollectionUtils.transformToList(
                    offerings,
                    new Function<String, InstanceOfferingInventory>() {
                      @Override
                      public String call(InstanceOfferingInventory arg) {
                        return arg.getUuid();
                      }
                    });

            String sql =
                "update VmInstanceVO vm set vm.instanceOfferingUuid = null where vm.instanceOfferingUuid in (:offeringUuids)";
            Query q = dbf.getEntityManager().createQuery(sql);
            q.setParameter("offeringUuids", offeringUuids);
            q.executeUpdate();
          }
        }.run();
      }

      completion.success();
      return;
    }

    final List<VmInstanceInventory> vminvs = vmFromDeleteAction(action);
    if (vminvs == null) {
      completion.success();
      return;
    }

    if (op == OP_STOP) {
      List<StopVmInstanceMsg> msgs = new ArrayList<StopVmInstanceMsg>();
      for (VmInstanceInventory inv : vminvs) {
        StopVmInstanceMsg msg = new StopVmInstanceMsg();
        msg.setVmInstanceUuid(inv.getUuid());
        bus.makeTargetServiceIdByResourceUuid(msg, VmInstanceConstant.SERVICE_ID, inv.getUuid());
        msgs.add(msg);
      }

      bus.send(
          msgs,
          20,
          new CloudBusListCallBack(completion) {
            @Override
            public void run(List<MessageReply> replies) {
              if (!action.isActionCode(CascadeConstant.DELETION_FORCE_DELETE_CODE)) {
                for (MessageReply r : replies) {
                  if (!r.isSuccess()) {
                    completion.fail(r.getError());
                    return;
                  }
                }
              }

              completion.success();
            }
          });
    } else if (op == OP_DELETION) {
      List<VmInstanceDeletionMsg> msgs = new ArrayList<VmInstanceDeletionMsg>();
      for (VmInstanceInventory inv : vminvs) {
        VmInstanceDeletionMsg msg = new VmInstanceDeletionMsg();
        msg.setForceDelete(action.isActionCode(CascadeConstant.DELETION_FORCE_DELETE_CODE));
        msg.setVmInstanceUuid(inv.getUuid());
        bus.makeTargetServiceIdByResourceUuid(msg, VmInstanceConstant.SERVICE_ID, inv.getUuid());
        msgs.add(msg);
      }

      bus.send(
          msgs,
          20,
          new CloudBusListCallBack(completion) {
            @Override
            public void run(List<MessageReply> replies) {
              if (!action.isActionCode(CascadeConstant.DELETION_FORCE_DELETE_CODE)) {
                for (MessageReply r : replies) {
                  if (!r.isSuccess()) {
                    completion.fail(r.getError());
                    return;
                  }
                }
              }

              completion.success();
            }
          });
    } else if (op == OP_DETACH_NIC) {
      List<DetachNicFromVmMsg> msgs = new ArrayList<DetachNicFromVmMsg>();
      List<L3NetworkInventory> l3s = action.getParentIssuerContext();
      for (VmInstanceInventory vm : vminvs) {
        for (L3NetworkInventory l3 : l3s) {
          DetachNicFromVmMsg msg = new DetachNicFromVmMsg();
          msg.setVmInstanceUuid(vm.getUuid());
          msg.setVmNicUuid(vm.findNic(l3.getUuid()).getUuid());
          bus.makeTargetServiceIdByResourceUuid(msg, VmInstanceConstant.SERVICE_ID, vm.getUuid());
          msgs.add(msg);
        }
      }

      bus.send(
          msgs,
          new CloudBusListCallBack(completion) {
            @Override
            public void run(List<MessageReply> replies) {
              if (!action.isActionCode(CascadeConstant.DELETION_FORCE_DELETE_CODE)) {
                for (MessageReply r : replies) {
                  if (!r.isSuccess()) {
                    completion.fail(r.getError());
                    return;
                  }
                }
              }

              completion.success();
            }
          });
    }
  }
Exemplo n.º 11
0
  @Override
  public void applyEip(final EipStruct struct, final Completion completion) {
    L3NetworkVO l3vo = dbf.findByUuid(struct.getNic().getL3NetworkUuid(), L3NetworkVO.class);
    final L3NetworkInventory l3inv = L3NetworkInventory.valueOf(l3vo);
    vrMgr.acquireVirtualRouterVm(
        l3inv,
        new VirtualRouterOfferingValidator() {
          @Override
          public void validate(VirtualRouterOfferingInventory offering)
              throws OperationFailureException {
            if (!offering.getPublicNetworkUuid().equals(struct.getVip().getL3NetworkUuid())) {
              throw new OperationFailureException(
                  errf.stringToOperationError(
                      String.format(
                          "found a virtual router offering[uuid:%s] for L3Network[uuid:%s] in zone[uuid:%s]; however, the network's public network[uuid:%s] is not the same to EIP[uuid:%s]'s; you may need to use system tag"
                              + " guestL3Network::l3NetworkUuid to specify a particular virtual router offering for the L3Network",
                          offering.getUuid(),
                          l3inv.getUuid(),
                          l3inv.getZoneUuid(),
                          struct.getVip().getL3NetworkUuid(),
                          struct.getEip().getUuid())));
            }
          }
        },
        new ReturnValueCompletion<VirtualRouterVmInventory>(completion) {
          @Override
          public void success(final VirtualRouterVmInventory vr) {
            applyEip(
                vr,
                struct,
                new Completion() {
                  @Override
                  public void success() {
                    SimpleQuery<VirtualRouterEipRefVO> q =
                        dbf.createQuery(VirtualRouterEipRefVO.class);
                    q.add(VirtualRouterEipRefVO_.eipUuid, Op.EQ, struct.getEip().getUuid());
                    if (!q.isExists()) {
                      // if virtual router is stopped outside zstack (e.g. the host rebbot)
                      // database will still have VirtualRouterEipRefVO for this EIP.
                      // in this case, don't create the record again
                      VirtualRouterEipRefVO ref = new VirtualRouterEipRefVO();
                      ref.setEipUuid(struct.getEip().getUuid());
                      ref.setVirtualRouterVmUuid(vr.getUuid());
                      dbf.persist(ref);
                    }
                    completion.success();
                  }

                  @Override
                  public void fail(ErrorCode errorCode) {
                    completion.fail(errorCode);
                  }
                });
          }

          @Override
          public void fail(ErrorCode errorCode) {
            completion.fail(errorCode);
          }
        });
  }
Exemplo n.º 12
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();
      }
    }
  }