@Test
  public void test() throws ApiSenderException {
    VmInstanceInventory vm = deployer.vms.get("TestVm");
    api.stopVmInstance(vm.getUuid());
    PrimaryStorageInventory local = deployer.primaryStorages.get("local");

    VolumeSnapshotInventory sp = api.createSnapshot(vm.getRootVolumeUuid());
    Assert.assertFalse(kconfig.snapshotCmds.isEmpty());
    LocalStorageResourceRefVO ref = dbf.findByUuid(sp.getUuid(), LocalStorageResourceRefVO.class);
    Assert.assertNotNull(ref);
    Assert.assertEquals(vm.getHostUuid(), ref.getHostUuid());

    sp = api.createSnapshot(vm.getRootVolumeUuid());
    ref = dbf.findByUuid(sp.getUuid(), LocalStorageResourceRefVO.class);
    Assert.assertNotNull(ref);
    Assert.assertEquals(vm.getHostUuid(), ref.getHostUuid());

    sp = api.createSnapshot(vm.getRootVolumeUuid());
    ref = dbf.findByUuid(sp.getUuid(), LocalStorageResourceRefVO.class);
    Assert.assertNotNull(ref);
    Assert.assertEquals(vm.getHostUuid(), ref.getHostUuid());

    PrimaryStorageVO localvo = dbf.findByUuid(local.getUuid(), PrimaryStorageVO.class);
    long avail = localvo.getCapacity().getAvailableCapacity();

    ImageInventory img = api.createTemplateFromSnapshot(sp.getUuid());
    Assert.assertTrue(img.getSize() != 0);

    localvo = dbf.findByUuid(local.getUuid(), PrimaryStorageVO.class);
    Assert.assertEquals(avail, localvo.getCapacity().getAvailableCapacity());
  }
  @Test
  public void test() throws ApiSenderException, InterruptedException {
    long requiredSize = SizeUnit.GIGABYTE.toByte(10);
    SimulatorPrimaryStorageDetails sp = new SimulatorPrimaryStorageDetails();
    sp.setTotalCapacity(SizeUnit.TERABYTE.toByte(10));
    sp.setAvailableCapacity(sp.getTotalCapacity());
    sp.setUrl("nfs://simulator/primary/");
    PrimaryStorageInventory pinv = api.createSimulatoPrimaryStorage(1, sp).get(0);
    ZoneInventory zone = api.createZones(1).get(0);
    ClusterInventory cluster = api.createClusters(1, zone.getUuid()).get(0);
    HostInventory host = api.createHost(1, cluster.getUuid()).get(0);
    api.attachPrimaryStorage(cluster.getUuid(), pinv.getUuid());

    AllocatePrimaryStorageMsg msg = new AllocatePrimaryStorageMsg();
    msg.setRequiredHostUuid(host.getUuid());
    msg.setSize(requiredSize);
    msg.setServiceId(bus.makeLocalServiceId(PrimaryStorageConstant.SERVICE_ID));
    MessageReply reply = bus.call(msg);
    Assert.assertEquals(AllocatePrimaryStorageReply.class, reply.getClass());
    AllocatePrimaryStorageReply ar = (AllocatePrimaryStorageReply) reply;
    Assert.assertEquals(pinv.getUuid(), ar.getPrimaryStorageInventory().getUuid());

    ReturnPrimaryStorageCapacityMsg rmsg = new ReturnPrimaryStorageCapacityMsg();
    rmsg.setDiskSize(requiredSize);
    rmsg.setPrimaryStorageUuid(pinv.getUuid());
    rmsg.setServiceId(bus.makeLocalServiceId(PrimaryStorageConstant.SERVICE_ID));
    bus.send(rmsg);
    Thread.sleep(2000);
    PrimaryStorageVO pvo = dbf.findByUuid(pinv.getUuid(), PrimaryStorageVO.class);
    Assert.assertEquals(
        pvo.getCapacity().getTotalCapacity(), pvo.getCapacity().getAvailableCapacity());
  }
 @Override
 public PrimaryStorageInventory createPrimaryStorage(
     PrimaryStorageVO vo, APIAddPrimaryStorageMsg msg) {
   vo.setMountPath(msg.getUrl());
   vo = dbf.persistAndRefresh(vo);
   return PrimaryStorageInventory.valueOf(vo);
 }
  @Override
  public void rollback(FlowRollback trigger, Map data) {
    Long size = (Long) data.get(LocalStorageAllocateCapacityForAttachingVolumeFlow.class);
    if (size != null) {
      PrimaryStorageInventory pri =
          (PrimaryStorageInventory)
              data.get(
                  VmInstanceConstant.Params.DestPrimaryStorageInventoryForAttachingVolume
                      .toString());
      ReturnPrimaryStorageCapacityMsg rmsg = new ReturnPrimaryStorageCapacityMsg();
      rmsg.setPrimaryStorageUuid(pri.getUuid());
      rmsg.setDiskSize(size);
      bus.makeTargetServiceIdByResourceUuid(rmsg, PrimaryStorageConstant.SERVICE_ID, pri.getUuid());
      bus.send(rmsg);
    }

    trigger.rollback();
  }
  private void handle(PrimaryStorageDeletionMsg msg) {
    PrimaryStorageInventory inv = PrimaryStorageInventory.valueOf(self);
    extpEmitter.beforeDelete(inv);
    deleteHook();
    extpEmitter.afterDelete(inv);

    PrimaryStorageDeletionReply reply = new PrimaryStorageDeletionReply();
    bus.reply(msg, reply);
  }
Exemple #6
0
  @Test
  public void test() throws ApiSenderException {
    VmInstanceInventory vm = deployer.vms.get("TestVm");
    ImageInventory iso = deployer.images.get("TestIso");
    PrimaryStorageInventory ps = deployer.primaryStorages.get("ceph-pri");

    restf.installBeforeAsyncJsonPostInterceptor(
        new BeforeAsyncJsonPostInterceptor() {
          @Override
          public void beforeAsyncJsonPost(String url, Object body, TimeUnit unit, long timeout) {
            if (body instanceof AttachIsoCmd) {
              AttachIsoCmd cmd = (AttachIsoCmd) body;
              isoto = (KvmCephIsoTO) cmd.iso;
            }
          }

          @Override
          public void beforeAsyncJsonPost(String url, String body, TimeUnit unit, long timeout) {}
        });

    api.attachIso(vm.getUuid(), iso.getUuid(), null);
    Assert.assertNotNull(isoto);
    Assert.assertFalse(isoto.getMonInfo().isEmpty());

    CephPrimaryStorageVO ceph = dbf.findByUuid(ps.getUuid(), CephPrimaryStorageVO.class);
    Assert.assertEquals(ceph.getMons().size(), isoto.getMonInfo().size());

    for (final CephPrimaryStorageMonVO mon : ceph.getMons()) {
      MonInfo info =
          CollectionUtils.find(
              isoto.getMonInfo(),
              new Function<MonInfo, MonInfo>() {
                @Override
                public MonInfo call(MonInfo arg) {
                  return arg.getHostname().equals(mon.getHostname()) ? arg : null;
                }
              });

      Assert.assertNotNull(info);
    }
  }
  protected void handle(APIChangePrimaryStorageStateMsg msg) {
    APIChangePrimaryStorageStateEvent evt = new APIChangePrimaryStorageStateEvent(msg.getId());

    PrimaryStorageState currState = self.getState();
    PrimaryStorageStateEvent event = PrimaryStorageStateEvent.valueOf(msg.getStateEvent());
    PrimaryStorageState nextState = AbstractPrimaryStorage.getNextState(currState, event);

    try {
      extpEmitter.preChange(self, event);
    } catch (PrimaryStorageException e) {
      evt.setErrorCode(
          errf.instantiateErrorCode(SysErrors.CHANGE_RESOURCE_STATE_ERROR, e.getMessage()));
      bus.publish(evt);
      return;
    }

    extpEmitter.beforeChange(self, event);
    changeStateHook(event, nextState);
    self.setState(nextState);
    self = dbf.updateAndRefresh(self);
    extpEmitter.afterChange(self, event, currState);
    evt.setInventory(PrimaryStorageInventory.valueOf(self));
    bus.publish(evt);
  }
  @Test
  public void test() throws ApiSenderException, InterruptedException {
    HostInventory host2 = deployer.hosts.get("host2");
    HostInventory host1 = deployer.hosts.get("host1");
    VmInstanceInventory vm = deployer.vms.get("TestVm");
    PrimaryStorageInventory local = deployer.primaryStorages.get("local");

    List<VolumeVO> vols = dbf.listAll(VolumeVO.class);
    List<VolumeVO> volumesOnLocal = new ArrayList<VolumeVO>();

    ImageCacheVO cacheVO = dbf.listAll(ImageCacheVO.class).get(0);
    long imageSize = cacheVO.getSize();
    long usedVolumeSize = 0;
    for (VolumeVO vol : vols) {
      if (vol.getPrimaryStorageUuid().equals(local.getUuid())) {
        volumesOnLocal.add(vol);
        usedVolumeSize += ratioMgr.calculateByRatio(vol.getPrimaryStorageUuid(), vol.getSize());
      }
    }

    config.createEmptyVolumeCmds.clear();
    config.deleteBitsCmds.clear();
    vm = api.migrateVmInstance(vm.getUuid(), host2.getUuid());
    TimeUnit.SECONDS.sleep(5);
    LocalStorageHostRefVO ref1 = dbf.findByUuid(host1.getUuid(), LocalStorageHostRefVO.class);
    Assert.assertEquals(ref1.getTotalCapacity() - imageSize, ref1.getAvailableCapacity());
    LocalStorageHostRefVO ref2 = dbf.findByUuid(host2.getUuid(), LocalStorageHostRefVO.class);
    Assert.assertEquals(
        ref2.getTotalCapacity() - imageSize - usedVolumeSize, ref2.getAvailableCapacity());

    Assert.assertEquals(volumesOnLocal.size(), config.createEmptyVolumeCmds.size());
    for (final VolumeVO vol : volumesOnLocal) {
      // volumes are created on dst host
      CreateEmptyVolumeCmd cmd =
          CollectionUtils.find(
              config.createEmptyVolumeCmds,
              new Function<CreateEmptyVolumeCmd, CreateEmptyVolumeCmd>() {
                @Override
                public CreateEmptyVolumeCmd call(CreateEmptyVolumeCmd arg) {
                  return arg.getVolumeUuid().equals(vol.getUuid()) ? arg : null;
                }
              });
      Assert.assertNotNull(cmd);
      Assert.assertEquals(vol.getInstallPath(), cmd.getInstallUrl());

      LocalStorageResourceRefVO r = dbf.findByUuid(vol.getUuid(), LocalStorageResourceRefVO.class);
      Assert.assertEquals(host2.getUuid(), r.getHostUuid());

      // volumes are deleted on src host
      DeleteBitsCmd dcmd =
          CollectionUtils.find(
              config.deleteBitsCmds,
              new Function<DeleteBitsCmd, DeleteBitsCmd>() {
                @Override
                public DeleteBitsCmd call(DeleteBitsCmd arg) {
                  return arg.getPath().equals(vol.getInstallPath()) ? arg : null;
                }
              });
      Assert.assertNotNull(
          String.format(
              "no delete command for volume[uuid:%s, path:%s]",
              vol.getUuid(), vol.getInstallPath()),
          dcmd);
    }

    Assert.assertFalse(kconfig.migrateVmCmds.isEmpty());
    MigrateVmCmd mcmd = kconfig.migrateVmCmds.get(0);
    Assert.assertEquals(host2.getManagementIp(), mcmd.getDestHostIp());
    Assert.assertEquals(vm.getUuid(), mcmd.getVmUuid());
    Assert.assertEquals(
        StorageMigrationPolicy.IncCopy.toString(), mcmd.getStorageMigrationPolicy());
  }
 @Override
 public PrimaryStorageInventory getInventory(String uuid) {
   return PrimaryStorageInventory.valueOf(dbf.findByUuid(uuid, PrimaryStorageVO.class));
 }
  protected void handle(APIDeletePrimaryStorageMsg msg) {
    final APIDeletePrimaryStorageEvent evt = new APIDeletePrimaryStorageEvent(msg.getId());
    final String issuer = PrimaryStorageVO.class.getSimpleName();
    final List<PrimaryStorageInventory> ctx = PrimaryStorageInventory.valueOf(Arrays.asList(self));
    FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
    chain.setName(String.format("delete-primary-storage-%s", msg.getUuid()));
    if (msg.getDeletionMode() == APIDeleteMessage.DeletionMode.Permissive) {
      chain
          .then(
              new NoRollbackFlow() {
                @Override
                public void run(final FlowTrigger trigger, Map data) {
                  casf.asyncCascade(
                      CascadeConstant.DELETION_CHECK_CODE,
                      issuer,
                      ctx,
                      new Completion(trigger) {
                        @Override
                        public void success() {
                          trigger.next();
                        }

                        @Override
                        public void fail(ErrorCode errorCode) {
                          trigger.fail(errorCode);
                        }
                      });
                }
              })
          .then(
              new NoRollbackFlow() {
                @Override
                public void run(final FlowTrigger trigger, Map data) {
                  casf.asyncCascade(
                      CascadeConstant.DELETION_DELETE_CODE,
                      issuer,
                      ctx,
                      new Completion(trigger) {
                        @Override
                        public void success() {
                          trigger.next();
                        }

                        @Override
                        public void fail(ErrorCode errorCode) {
                          trigger.fail(errorCode);
                        }
                      });
                }
              });
    } else {
      chain.then(
          new NoRollbackFlow() {
            @Override
            public void run(final FlowTrigger trigger, Map data) {
              casf.asyncCascade(
                  CascadeConstant.DELETION_FORCE_DELETE_CODE,
                  issuer,
                  ctx,
                  new Completion(trigger) {
                    @Override
                    public void success() {
                      trigger.next();
                    }

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

    chain
        .done(
            new FlowDoneHandler(msg) {
              @Override
              public void handle(Map data) {
                casf.asyncCascadeFull(
                    CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion());
                bus.publish(evt);

                PrimaryStorageDeletedData d = new PrimaryStorageDeletedData();
                d.setPrimaryStorageUuid(self.getUuid());
                d.setInventory(PrimaryStorageInventory.valueOf(self));
                evtf.fire(PrimaryStorageCanonicalEvent.PRIMARY_STORAGE_DELETED_PATH, d);
              }
            })
        .error(
            new FlowErrorHandler(msg) {
              @Override
              public void handle(ErrorCode errCode, Map data) {
                evt.setErrorCode(
                    errf.instantiateErrorCode(SysErrors.DELETE_RESOURCE_ERROR, errCode));
                bus.publish(evt);
              }
            })
        .start();
  }
 protected PrimaryStorageInventory getSelfInventory() {
   return PrimaryStorageInventory.valueOf(self);
 }