Java 类com.vmware.vim25.mo.Datacenter 实例源码

项目:teamcity-vmware-plugin    文件:VmwarePooledUpdateInstanceTaskTest.java   
@BeforeMethod
@Override
protected void setUp() throws Exception {
  super.setUp();
  myIdxStorage = createTempDir();
  FakeModel.instance().addDatacenter("dc");
  FakeModel.instance().addFolder("cf").setParent("dc", Datacenter.class);
  FakeModel.instance().addResourcePool("rp").setParentFolder("cf");
  FakeModel.instance().addVM("image1").setParentFolder("cf");
  FakeModel.instance().addVM("image2").setParentFolder("cf");
  FakeModel.instance().addVM("image_template").setParentFolder("cf");
  FakeModel.instance().addVMSnapshot("image2", "snap");
  FakeModel.instance().getCustomizationSpecs().put("someCustomization", new CustomizationSpec());
  FakeModel.instance().getCustomizationSpecs().put("linux", new CustomizationSpec());
  myFakeApiConnector = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null);
  setInternalProperty("teamcity.vsphere.instance.status.update.delay.ms", "250");
  myTaskManager = new MyExposingVmwareUpdateTaskManager();
}
项目:teamcity-vmware-plugin    文件:VmwareCloudIntegrationTest.java   
public void check_same_datacenter() throws InterruptedException {
  FakeModel.instance().addDatacenter("dc2");
  FakeModel.instance().addFolder("cf2").setParent("dc2", Datacenter.class);
  FakeModel.instance().addResourcePool("rp2").setParentFolder("cf2");
  FakeModel.instance().addVM("image3").setParentFolder("cf");
  updateClientParameters(CloudProfileUtil.collectionFromJson(
    "[{sourceVmName:'image1', behaviour:'START_STOP'}," +
      "{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp',maxInstances:3,behaviour:'ON_DEMAND_CLONE'}," +
      "{sourceVmName:'image_template', snapshot:'" + VmwareConstants.CURRENT_STATE + "',folder:'cf',pool:'rp',maxInstances:3,behaviour:'FRESH_CLONE'}, " +
      "{sourceVmName:'image3',snapshot:'" + VmwareConstants.CURRENT_STATE + "'," + "folder:'cf2',pool:'rp2',maxInstances:3,behaviour:'ON_DEMAND_CLONE'}]", PROJECT_ID));
  recreateClient();

  final CloudInstanceUserData userData = createUserData("image3_agent");
  final VmwareCloudInstance vmwareCloudInstance = myClient.startNewInstance(getImageByName("image3"), userData);
  new WaitFor(10 * 1000) {
    @Override
    protected boolean condition() {
      return vmwareCloudInstance.getStatus() == InstanceStatus.ERROR && vmwareCloudInstance.getErrorInfo() != null;
    }
  }.assertCompleted();

  final String msg = vmwareCloudInstance.getErrorInfo().getMessage();
  assertContains(msg, "Unable to find folder cf2 in datacenter dc");
}
项目:contrail-vcenter-plugin    文件:VCenterDB.java   
public VCenterDB(String vcenterUrl, String vcenterUsername,
                 String vcenterPassword, String contrailDcName, String contrailClusterName,
                 String contrailDvsName, String ipFabricPgName, Mode mode) {
    this.vcenterUrl             = vcenterUrl;
    this.vcenterUsername        = vcenterUsername;
    this.vcenterPassword        = vcenterPassword;
    this.contrailDataCenterName = contrailDcName;
    this.contrailClusterName = contrailClusterName;
    this.contrailDvSwitchName   = contrailDvsName;
    this.contrailIpFabricPgName = ipFabricPgName;
    this.mode                   = mode;

    s_logger.info("VCenterDB(" + contrailDvsName + ", " + ipFabricPgName + ")");
    datacenters = new ConcurrentHashMap<String, Datacenter>();
    dvswitches = new ConcurrentHashMap<String, VmwareDistributedVirtualSwitch>();
    dvsPvlanMap = new ConcurrentHashMap<String, VMwareDVSPvlanMapEntry[]>();

    // Create ESXi host to vRouterVM Ip address map
    buildEsxiToVRouterIpMap();
}
项目:contrail-vcenter-plugin    文件:VCenterDB.java   
public IpPool getIpPoolById(Integer poolid,  String nwName, Datacenter dc, String dcName)
        throws RemoteException {

    if (ipPools == null) {
        ipPools = ipPoolManager.queryIpPools(dc);
        if (ipPools == null || ipPools.length == 0) {
            s_logger.debug(" Datacenter: " + dcName + " IP Pools NOT configured");
            return null;
        }
    }

    // refresh cached pools and try again
    ipPools = ipPoolManager.queryIpPools(dc);
    if (ipPools == null || ipPools.length == 0) {
        s_logger.debug(" Datacenter: " + dcName + " IP Pools NOT configured");
        return null;
    }

    return getIpPool(poolid, nwName);
}
项目:contrail-vcenter-plugin    文件:VCenterPluginResp.java   
private void populateVCenterServerInfo() {
    VCenterServerInfo vCenterServerInfo = vCenterPluginInfo.getVCenterServerInfo();

    if (VCenterNotify.getVcenterDB() != null) {
        vCenterServerInfo.setUrl(VCenterNotify.getVcenterDB().getVcenterUrl() );

        vCenterServerInfo.setConnected(VCenterNotify.getVCenterConnected());

        vCenterServerInfo.setOperationalStatus(VCenterNotify.getVcenterDB().getOperationalStatus());
        Datacenter dc = VCenterNotify.getVcenterDB().getDatacenter();
        if (dc != null && dc.getMOR() != null) {
            vCenterServerInfo.setDatacenterMor(dc.getMOR().getVal());
        }
        VmwareDistributedVirtualSwitch dvs = VCenterNotify.getVcenterDB().getDvs();
        if (dvs != null && dvs.getMOR() != null) {
            vCenterServerInfo.setDvsMor(dvs.getMOR().getVal());
        }
    }
}
项目:teamcity-vmware-plugin    文件:VmwareCloudImageTest.java   
@BeforeMethod
public void setUp() throws Exception {
  super.setUp();
  FakeModel.instance().clear();
  myTaskExecutor = new CloudAsyncTaskExecutor("Test-vmware");
  myApiConnector = new FakeApiConnector(VmwareCloudIntegrationTest.TEST_SERVER_UUID, VmwareCloudIntegrationTest.PROFILE_ID);
  myIdxStorage = createTempDir();
  Map<String, String> params = new HashMap<>();
  params.put("nickname", "imageNickname");
  params.put("sourceVmName", "srcVM");
  params.put("snapshot", "srcVMSnap");
  params.put("folder", "folderId");
  params.put("pool", "rpId");
  params.put("behaviour", CloneBehaviour.FRESH_CLONE.toString());
  params.put("maxInstances", "5");
  CloudImageParameters imageParameters = new CloudImageParametersImpl(params, VmwareCloudIntegrationTest.PROJECT_ID);

  myImageDetails = new VmwareCloudImageDetails(imageParameters);

  FakeModel.instance().addDatacenter("dc2");
  FakeModel.instance().addFolder("folderId").setParent("dc2", Datacenter.class);
  FakeModel.instance().addVM("srcVM").setParentFolder("folderId");
  FakeModel.instance().addResourcePool("rpId").setParentFolder("folderId");

  FakeModel.instance().addVMSnapshot("srcVM", "srcVMSnap");

  myProfile = VmwareTestUtils.createProfileFromProps(new CloudClientParametersImpl(Collections.emptyMap(), Collections.emptyList()));
  myImage = new VmwareCloudImage(myApiConnector, myImageDetails, myTaskExecutor, myIdxStorage, myProfile);

  myCloudClient = new VMWareCloudClient(myProfile, myApiConnector, new VmwareUpdateTaskManager(), createTempDir());
  myCloudClient.populateImagesData(Collections.singletonList(myImageDetails));
  myUpdateTask = new UpdateInstancesTask<VmwareCloudInstance, VmwareCloudImage, VMWareCloudClient>(myApiConnector, myCloudClient, 10*1000, false);
}
项目:primecloud-controller    文件:VmwareProcessClient.java   
public void deleteDisk(String datastoreName, String fileName) {
    // Datacenter
    ManagedEntity datacenter = vmwareClient.getRootEntity();

    // Datastore
    Datastore datastore = vmwareClient.search(Datastore.class, datastoreName);
    if (datastore == null) {
        // データストアが見つからない場合
        throw new AutoException("EPROCESS-000505", datastoreName);
    }

    // ディスクの削除
    FileManager fileManager = vmwareClient.getServiceInstance().getFileManager();
    if (fileManager == null) {
        // fileManagerが利用できない場合
        throw new AutoException("EPROCESS-000533");
    }

    try {
        // ディスク削除
        fileManager.deleteDatastoreFile_Task(fileName, (Datacenter) datacenter);
        // ディスク削除後にごみができ、再度アタッチするとエラーになるので削除
        String flatname;
        flatname = fileName.substring(0, fileName.length() - 5) + "-flat.vmdk";
        fileManager.deleteDatastoreFile_Task(flatname, (Datacenter) datacenter);
    } catch (RemoteException e) {
        throw new AutoException("EPROCESS-000522", e, fileName);
    }

    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100455", fileName));
    }
}
项目:contrail-vcenter-plugin    文件:VCenterDB.java   
public VmwareDistributedVirtualSwitch getVmwareDvs(String name,
        Datacenter dc, String dcName)
                throws RemoteException {
    if (dvswitches.containsKey(name)) {
        return dvswitches.get(name);
    }

    String description = "<dvs " + name + ", datacenter " + dcName
            + ", vCenter " + vcenterUrl + ">.";

    InventoryNavigator inventoryNavigator = new InventoryNavigator(dc);

    VmwareDistributedVirtualSwitch dvs = null;
    try {
        dvs = (VmwareDistributedVirtualSwitch)inventoryNavigator.searchManagedEntity(
                "VmwareDistributedVirtualSwitch", name);
    } catch (RemoteException e ) {
        operationalStatus = "Failed to retrieve " + description;
        s_logger.error(operationalStatus);
        throw new RemoteException(operationalStatus, e);
    }

    if (dvs == null) {
        operationalStatus = "Failed to retrieve " + description;
        s_logger.error(operationalStatus);
        throw new RemoteException(operationalStatus);
    }

    s_logger.info("Found " + description);
    dvswitches.put(name, dvs);
    return dvs;
}
项目:contrail-vcenter-plugin    文件:VCenterDB.java   
public VMwareDVSPvlanMapEntry[] getDvsPvlanMap(String dvsName, Datacenter dc, String dcName)
                throws RemoteException {
    if (dvsPvlanMap.containsKey(dvsName)) {
        return dvsPvlanMap.get(dvsName);
    }

    VmwareDistributedVirtualSwitch dvs = getVmwareDvs(dvsName, dc, dcName);

    // Extract private vlan entries for the virtual switch
    VMwareDVSConfigInfo dvsConfigInfo = (VMwareDVSConfigInfo) dvs.getConfig();
    if (dvsConfigInfo == null) {
        s_logger.error("dvSwitch: " + dvsName
                + " Datacenter: " + dcName + " ConfigInfo is empty");
    }

    if (!(dvsConfigInfo instanceof VMwareDVSConfigInfo)) {
        s_logger.error("dvSwitch: " + dvsName +
                " Datacenter: " + dcName + " ConfigInfo " +
                "isn't instanceof VMwareDVSConfigInfo");
    }

    VMwareDVSPvlanMapEntry[] pvlanMapArray = dvsConfigInfo.getPvlanConfig();
    if (pvlanMapArray != null) {
        dvsPvlanMap.put(dvsName, pvlanMapArray);
        s_logger.info("Found private vlan map array on dvSwitch: " + dvsName +
                " Datacenter: " + dcName);
        return pvlanMapArray;
    }

    s_logger.error("dvSwitch: " + dvsName +
            " Datacenter: " + dcName + " Private VLAN NOT" +
            "configured");
    return null;
}
项目:contrail-vcenter-plugin    文件:VCenterDB.java   
public boolean isVmEventOnMonitoredCluster(Event event, String hostName)
    throws RemoteException {
    String dcName;
    Datacenter dc;

    // If contrailClusterName is null, all clusters under datacenter 
    // are monitored by vcenter plugin.
    if (contrailClusterName == null)
        return true;

    if (event.getHost() != null) {
        hostName = event.getHost().getName();
        HostSystem host = getVmwareHost(hostName, contrailDC, contrailDataCenterName);

        if (host != null) {
            ClusterComputeResource cluster = (ClusterComputeResource) host.getParent();
            if (cluster != null) {
                String clstrName = cluster.getName();
                if (clstrName != null && clstrName.equals(contrailClusterName)) {
                    return true;
                }
            }
        }
    }

    return false;
}
项目:contrail-vcenter-plugin    文件:VCenterNotify.java   
private void createDatacenterEventFilter(Datacenter dc) throws RemoteException {

        if (dc == null) {
            s_logger.error("Cannot register for events on null datacenter  ");
            return;
        }
        s_logger.info("Register for events on datacenter ");

        String[] eventNames = {
            // Host events
            "HostConnectionLostEvent",
            "HostConnectedEvent",
            "EnteredMaintenanceModeEvent",
            "ExitMaintenanceModeEvent",

            // VM events
            // VM create events
             "VmCreatedEvent",
            "VmClonedEvent",
            "VmDeployedEvent",
            // VM modify events
            "VmPoweredOnEvent",
            "DrsVmPoweredOnEvent",
            "VmPoweredOffEvent",
            "VmSuspendedEvent",
            "VmRenamedEvent",
            "VmMacChangedEvent",
            "VmMacAssignedEvent",
            "VmReconfiguredEvent",
            // VM Migration events
            "DrsVmMigratedEvent",
            "VmMigratedEvent",
            // VM delete events
            "VmRemovedEvent"
        };

        watchManagedObjectEvents(dc, eventNames);
    }
项目:jcloud-vsphere    文件:VirtualDiskManagerApi.java   
Task copyVirtualDiskTask(String sourceName, Datacenter sourceDatacenter, String destName,
Datacenter destDatacenter, VirtualDiskSpec destSpec, Boolean force) throws FileFault, RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:VSphereFileManager.java   
@Override
public void changeOwner(String name, Datacenter datacenter, String owner) throws InvalidDatastore, FileFault, UserNotFound, RuntimeFault, RemoteException {
   //To change body of implemented methods use File | Settings | File Templates.
}
项目:jcloud-vsphere    文件:VSphereFileManager.java   
@Override
public Task copyDatastoreFileTask(String sourceName, Datacenter sourceDatacenter, String destinationName, Datacenter destinationDatacenter, boolean force) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException {
   return null;  //To change body of implemented methods use File | Settings | File Templates.
}
项目:jcloud-vsphere    文件:VSphereFileManager.java   
@Override
public Task deleteDatastoreFileTask(String name, Datacenter datacenter) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException {
   return null;  //To change body of implemented methods use File | Settings | File Templates.
}
项目:jcloud-vsphere    文件:VSphereFileManager.java   
@Override
public void makeDirectory(String name, Datacenter datacenter, boolean createParentDirectories) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException {
   //To change body of implemented methods use File | Settings | File Templates.
}
项目:jcloud-vsphere    文件:VSphereFileManager.java   
@Override
public Task moveDatastoreFileTask(String sourceName, Datacenter sourceDatacenter, String destinationName, Datacenter destinationDatacenter, boolean force) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException {
   return null;  //To change body of implemented methods use File | Settings | File Templates.
}
项目:teamcity-vmware-plugin    文件:VmwarePooledUpdateInstanceTaskTest.java   
public void check_called_once() throws MalformedURLException {
  final AtomicBoolean listAllCanBeCalled = new AtomicBoolean();
  final AtomicBoolean listAllCalledOnce = new AtomicBoolean();

  final AtomicBoolean getByNameCanBeCalled = new AtomicBoolean();
  final AtomicBoolean getByNameCalledOnce = new AtomicBoolean();

  myFakeApiConnector = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null) {

    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      if (!listAllCanBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertFalse(listAllCalledOnce.get());
      listAllCalledOnce.set(true);
      return super.findAllEntitiesAsMapOld(instanceType);
    }

    @Override
    protected Map<String, VirtualMachine> searchVMsByNames(@NotNull final Collection<String> names, @Nullable final Datacenter dc) throws VmwareCheckedCloudException {
      if (!getByNameCanBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertFalse(getByNameCalledOnce.get());
      getByNameCalledOnce.set(true);
      return super.searchVMsByNames(names, dc);
    }
  };

  final CloudClientParameters clientParameters1 = new CloudClientParametersImpl(
    Collections.emptyMap(), CloudProfileUtil.collectionFromJson("[{sourceVmName:'image1', behaviour:'START_STOP'}]", PROJECT_ID));
  final VMWareCloudClient client1 = new MyClient(clientParameters1, null);


  final CloudClientParameters clientParameters2 = new CloudClientParametersImpl(
    Collections.emptyMap(), CloudProfileUtil.collectionFromJson(
    "[{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp'," +
    "maxInstances:3,behaviour:'ON_DEMAND_CLONE',customizationSpec:'someCustomization'}]", PROJECT_ID));
  final VMWareCloudClient client2 = new MyClient(clientParameters2, null);

  final CloudClientParameters clientParameters3 = new CloudClientParametersImpl(
    Collections.emptyMap(), CloudProfileUtil.collectionFromJson(
    "[{'source-id':'image_template',sourceVmName:'image_template', snapshot:'" + VmwareConstants.CURRENT_STATE +
    "',folder:'cf',pool:'rp',maxInstances:3,behaviour:'FRESH_CLONE', customizationSpec: 'linux'}]",
    PROJECT_ID));
  final VMWareCloudClient client3 = new MyClient(clientParameters3, null);

  final VmwareUpdateInstanceTask task1 = myTaskManager.createUpdateTask(myFakeApiConnector, client1);
  final VmwareUpdateInstanceTask task2 = myTaskManager.createUpdateTask(myFakeApiConnector, client2);
  final VmwareUpdateInstanceTask task3 = myTaskManager.createUpdateTask(myFakeApiConnector, client3);

  listAllCanBeCalled.set(true);
  listAllCalledOnce.set(false);
  getByNameCalledOnce.set(false);
  getByNameCanBeCalled.set(true);
  task1.run();
  task2.run();
  task3.run();
  assertTrue(listAllCalledOnce.get());
  assertTrue(getByNameCalledOnce.get());
}
项目:teamcity-vmware-plugin    文件:VmwarePooledUpdateInstanceTaskTest.java   
public void check_cleared_after_dispose_2() throws MalformedURLException {
  final AtomicBoolean canBeCalled = new AtomicBoolean();
  final AtomicInteger callsCount = new AtomicInteger();

  myFakeApiConnector = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null) {
    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      processChecks();
      return Collections.emptyMap();
    }

    private void processChecks() {
      if (!canBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertTrue(callsCount.get() < 2);
      callsCount.incrementAndGet();
    }

    @Override
    protected Map<String, VirtualMachine> searchVMsByNames(@NotNull final Collection<String> names, @Nullable final Datacenter dc) throws VmwareCheckedCloudException {
      processChecks();
      return Collections.emptyMap();
    }
  };

  final CloudClientParameters clientParameters1 = new CloudClientParametersImpl(
    Collections.emptyMap(), CloudProfileUtil.collectionFromJson("[{sourceVmName:'image1', behaviour:'START_STOP'}]", PROJECT_ID));
  final VMWareCloudClient client1 = new MyClient(clientParameters1, null);


  final CloudClientParameters clientParameters2 = new CloudClientParametersImpl(
    Collections.emptyMap(), CloudProfileUtil.collectionFromJson(
    "[{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp'," +
    "maxInstances:3,behaviour:'ON_DEMAND_CLONE',customizationSpec:'someCustomization'}]", PROJECT_ID));

  final VMWareCloudClient client2 = new MyClient(clientParameters2, null);
  final VmwareUpdateInstanceTask task1 = myTaskManager.createUpdateTask(myFakeApiConnector, client1);


  canBeCalled.set(true);
  callsCount.set(0);
  task1.run();
  assertTrue(callsCount.get() > 0);

  client1.dispose();
  final VmwareUpdateInstanceTask task2 = myTaskManager.createUpdateTask(myFakeApiConnector, client2);
  canBeCalled.set(true);
  callsCount.set(0);
  task2.run();
  assertTrue(callsCount.get() > 0);


}
项目:teamcity-vmware-plugin    文件:VmwareCloudIntegrationTest.java   
@BeforeMethod
public void setUp() throws Exception {
  super.setUp();
  //org.apache.log4j.Logger.getLogger("jetbrains.buildServer").setLevel(Level.DEBUG);
  //org.apache.log4j.Logger.getRootLogger().addAppender(new ConsoleAppender());

  myIdxStorage = createTempDir();

  setInternalProperty("teamcity.vsphere.instance.status.update.delay.ms", "50");
  myClientParameters = new CloudClientParametersImpl(
    Collections.emptyMap(),
                                                     CloudProfileUtil.collectionFromJson("[{sourceVmName:'image1', behaviour:'START_STOP'}," +
                                                                                         "{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp',maxInstances:3,behaviour:'ON_DEMAND_CLONE', " +
                                                                                         "customizationSpec:'someCustomization'}," +
                                                                                         "{sourceVmName:'image_template', snapshot:'" + VmwareConstants.CURRENT_STATE +
                                                                                         "',folder:'cf',pool:'rp',maxInstances:3,behaviour:'FRESH_CLONE', customizationSpec: 'linux'}]",
                                                                                         PROJECT_ID));

  myFakeApi = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null);
  FakeModel.instance().addDatacenter("dc");
  FakeModel.instance().addFolder("cf").setParent("dc", Datacenter.class);
  FakeModel.instance().addResourcePool("rp").setParentFolder("cf");
  FakeModel.instance().addVM("image1").setParentFolder("cf");
  FakeModel.instance().addVM("image2").setParentFolder("cf");
  FakeModel.instance().addVM("image_template").setParentFolder("cf");
  FakeModel.instance().addVMSnapshot("image2", "snap");
  FakeModel.instance().getCustomizationSpecs().put("someCustomization", new CustomizationSpec());
  FakeModel.instance().getCustomizationSpecs().put("linux", new CustomizationSpec());
  myLastRunTime = new AtomicLong(0);
  myStuckTime = new AtomicLong(2*60*1000);

  myTaskManager = new VmwareUpdateTaskManager(){
    @Override
    protected VmwarePooledUpdateInstanceTask createNewPooledTask(@NotNull final VMWareApiConnector connector, @NotNull final VMWareCloudClient client) {
      return new VmwarePooledUpdateInstanceTask(connector, client, myStuckTime.get(), false){
        @Override
        public void run() {
          super.run();
          myLastRunTime.set(System.currentTimeMillis());
        }
      };
    }
  };

  recreateClient();
  assertNull(myClient.getErrorInfo());
}
项目:teamcity-vmware-plugin    文件:VmwareCloudIntegrationTest.java   
public void do_not_clear_image_instances_list_on_error() throws ExecutionException, InterruptedException, MalformedURLException {
  final AtomicBoolean failure = new AtomicBoolean(false);
  final AtomicLong lastApiCallTime = new AtomicLong(0);
  myFakeApi = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID){
    @Override
    protected <T extends ManagedEntity> Collection<T> findAllEntitiesOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findAllEntitiesOld(instanceType);
    }

    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findAllEntitiesAsMapOld(instanceType);
    }

    @Override
    protected <T extends ManagedEntity> Pair<T,Datacenter> findEntityByIdNameOld(final String name, final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findEntityByIdNameOld(name, instanceType);
    }
  };
  recreateClient(250);
  startNewInstanceAndWait("image2");
  startNewInstanceAndWait("image2");
  startNewInstanceAndWait("image2");
  Thread.sleep(5*1000);
  failure.set(true);
  final long problemStart = System.currentTimeMillis();
  new WaitFor(5*1000){

    @Override
    protected boolean condition() {
      return myLastRunTime.get() > problemStart;
    }
  }.assertCompleted("Should have been checked at least once - delay set to 2 sec");

  assertEquals(3, getImageByName("image2").getInstances().size());
}
项目:teamcity-vmware-plugin    文件:VmwareCloudIntegrationTest.java   
public void start_instance_should_not_block_ui() throws MalformedURLException, InterruptedException, CheckedCloudException {
  final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  final Lock lock = new ReentrantLock();
  final AtomicBoolean shouldLock = new AtomicBoolean(false);
  try {
    myFakeApi = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID) {

      @Override
      protected <T extends ManagedEntity> T findEntityByIdNameNullableOld(final String name, final Class<T> instanceType, final Datacenter dc) throws VmwareCheckedCloudException {
        try {
          if (shouldLock.get()) {
            lock.lock(); // will stuck here
          }
          return super.findEntityByIdNameNullableOld(name, instanceType, dc);
        } finally {
          if (shouldLock.get())
            lock.unlock();
        }
      }

      @Override
      protected <T extends ManagedEntity> Collection<T> findAllEntitiesOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
        try {
          if (shouldLock.get()) {
            lock.lock(); // will stuck here
          }
          return super.findAllEntitiesOld(instanceType);
        } finally {
          if (shouldLock.get())
          lock.unlock();
        }
      }

      @Override
      protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
        try {
          if (shouldLock.get()) {
            lock.lock(); // will stuck here
          }
          return super.findAllEntitiesAsMapOld(instanceType);
        } finally {
          if (shouldLock.get())
          lock.unlock();
        }
      }

    };

    recreateClient();
    final VmwareCloudInstance startedInstance = startNewInstanceAndWait("image2");
    terminateAndDeleteIfNecessary(false, startedInstance);

    shouldLock.set(true);
    lock.lock();
    executor.execute(new Runnable() {
      public void run() {
        // start already existing clone
        myClient.startNewInstance(getImageByName("image2"), createUserData("image2_agent"));
        // start-stop instance
        myClient.startNewInstance(getImageByName("image1"), createUserData("image1_agent"));
        // clone a new one
        myClient.startNewInstance(getImageByName("image_template"), createUserData("image_template_agent"));
      }
    });
    executor.shutdown();
    assertTrue("canStart method blocks the thread!", executor.awaitTermination(100000, TimeUnit.MILLISECONDS));
  } finally {
    lock.unlock();
    executor.shutdownNow();
  }

}
项目:contrail-vcenter-plugin    文件:VCenterDB.java   
public Datacenter getDatacenter() {
  return contrailDC;
}
项目:contrail-vcenter-plugin    文件:VCenterDB.java   
public void setDatacenter(Datacenter _dc) {
  contrailDC = _dc;
}
项目:vijava    文件:VMClone.java   
public static void main(String[] args) throws Exception
  {
   CommandLineParser clp = new CommandLineParser(constructOptions(), args);

   String urlStr = clp.get_option("url");
   String username = clp.get_option("username");
   String password = clp.get_option("password");
   String cloneName = clp.get_option("CloneName");
   String vmPath = clp.get_option("vmPath");
   String datacenterName= clp.get_option("DatacenterName");

   try
   {
       ServiceInstance si = new ServiceInstance(new URL(urlStr), username, password, true);
       VirtualMachine vm = (VirtualMachine) si.getSearchIndex().findByInventoryPath(vmPath);
       Datacenter dc = (Datacenter) si.getSearchIndex().findByInventoryPath(datacenterName);

       if(vm==null || dc ==null)
       {
           System.out.println("VirtualMachine or Datacenter path is NOT correct. Pls double check. ");
           return;
       }
       Folder vmFolder = dc.getVmFolder();

       VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
       cloneSpec.setLocation(new VirtualMachineRelocateSpec());
       cloneSpec.setPowerOn(false);
       cloneSpec.setTemplate(false);

       Task task = vm.cloneVM_Task(vmFolder, cloneName, cloneSpec);
       System.out.println("Launching the VM clone task. It might take a while. Please wait for the result ...");

       String status =  task.waitForMe();
       if(status==Task.SUCCESS)
       {
            System.out.println("Virtual Machine got cloned successfully.");
       }
       else
       {
           System.out.println("Failure -: Virtual Machine cannot be cloned");
       }
   }
   catch(RemoteException re)
   {
       re.printStackTrace();
   }
   catch(MalformedURLException mue)
   {
       mue.printStackTrace();
   }
}
项目:vijava    文件:CreateVM.java   
public static void main(String[] args) throws Exception 
{  
  if(args.length!=3)
  {
    System.out.println("Usage: java CreateVM <url> " +
          "<username> <password>");
    System.exit(0);
  }

  String dcName = "ha-datacenter";
  String vmName = "vimasterVM";
  long memorySizeMB = 500;
  int cupCount = 1;
  String guestOsId = "sles10Guest";
  long diskSizeKB = 1000000;
  // mode: persistent|independent_persistent,
  // independent_nonpersistent
  String diskMode = "persistent";
  String datastoreName = "storage1 (2)";
  String netName = "VM Network";
  String nicName = "Network Adapter 1";

  ServiceInstance si = new ServiceInstance(
      new URL(args[0]), args[1], args[2], true);

  Folder rootFolder = si.getRootFolder();

  Datacenter dc = (Datacenter) new InventoryNavigator(
      rootFolder).searchManagedEntity("Datacenter", dcName);
  ResourcePool rp = (ResourcePool) new InventoryNavigator(
      dc).searchManagedEntities("ResourcePool")[0];

  Folder vmFolder = dc.getVmFolder();

  // create vm config spec
  VirtualMachineConfigSpec vmSpec = 
    new VirtualMachineConfigSpec();
  vmSpec.setName(vmName);
  vmSpec.setAnnotation("VirtualMachine Annotation");
  vmSpec.setMemoryMB(memorySizeMB);
  vmSpec.setNumCPUs(cupCount);
  vmSpec.setGuestId(guestOsId);

  // create virtual devices
  int cKey = 1000;
  VirtualDeviceConfigSpec scsiSpec = createScsiSpec(cKey);
  VirtualDeviceConfigSpec diskSpec = createDiskSpec(
      datastoreName, cKey, diskSizeKB, diskMode);
  VirtualDeviceConfigSpec nicSpec = createNicSpec(
      netName, nicName);

  vmSpec.setDeviceChange(new VirtualDeviceConfigSpec[] 
      {scsiSpec, diskSpec, nicSpec});

  // create vm file info for the vmx file
  VirtualMachineFileInfo vmfi = new VirtualMachineFileInfo();
  vmfi.setVmPathName("["+ datastoreName +"]");
  vmSpec.setFiles(vmfi);

  // call the createVM_Task method on the vm folder
  Task task = vmFolder.createVM_Task(vmSpec, rp, null);
  String result = task.waitForMe();       
  if(result == Task.SUCCESS) 
  {
    System.out.println("VM Created Sucessfully");
  }
  else 
  {
    System.out.println("VM could not be created. ");
  }
}
项目:vijava    文件:CopyFile.java   
public static void main(String[] args) throws Exception
{
  if(args.length != 3)
  {
    System.out.println("Usage: java CopyFile " 
      + "<url> <username> <password>");
    return;
  }

  ServiceInstance si = new ServiceInstance(
    new URL(args[0]), args[1], args[2], true);

  Datacenter dc = (Datacenter)new InventoryNavigator(
      si.getRootFolder()).searchManagedEntity(
          "Datacenter", "ha-datacenter");
  FileManager fileMgr = si.getFileManager();
  if(fileMgr==null)
  {
    System.out.println("FileManager not available.");
    si.getServerConnection().logout();
    return;
  }

  String basePath = "[storage1 (2)] Nostalgia011";
  String dirPath = basePath + "/" + "testDir";
  // create parent directories if needed - true
  fileMgr.makeDirectory(dirPath, dc, true);

  String srcPath = basePath + "/Nostalgia011.vmdk";
  String dstPath = dirPath + "/copy of Nostalgia011.vmdk";
  Task cTask = fileMgr.copyDatastoreFile_Task(srcPath, dc, 
      dstPath, dc, true);

  if(cTask.waitForMe()==Task.SUCCESS)
  {
    System.out.println("File copied successfully!");
  }
  else
  {
    System.out.println("File copy failed!");
    return;
  }
  Thread.sleep(30*1000);

  fileMgr.deleteDatastoreFile_Task(dstPath, dc);
  fileMgr.deleteDatastoreFile_Task(dirPath, dc);
  si.getServerConnection().logout();
}
项目:roboconf-platform    文件:VmwareIaasHandler.java   
@Override
public String createMachine( TargetHandlerParameters parameters ) throws TargetException {

    this.logger.fine( "Creating a new VM @ VMware." );

    // For IaaS, we only expect root instance names to be passed
    if( InstanceHelpers.countInstances( parameters.getScopedInstancePath()) > 1 )
        throw new TargetException( "Only root instances can be passed in arguments." );

    String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath());

    // Deal with the creation
    try {
        System.setProperty("org.xml.sax.driver","org.apache.xerces.parsers.SAXParser");
        Map<String,String> targetProperties = parameters.getTargetProperties();
        final String machineImageId = targetProperties.get( TEMPLATE );
        final ServiceInstance vmwareServiceInstance = getServiceInstance( targetProperties );

        final ComputeResource vmwareComputeResource = (ComputeResource)(
                new InventoryNavigator( vmwareServiceInstance.getRootFolder())
                .searchManagedEntity("ComputeResource", targetProperties.get( CLUSTER )));

        // Generate the user data first, so that nothing has been done on the IaaS if it fails
        String userData = UserDataHelpers.writeUserDataAsString(
                parameters.getMessagingProperties(),
                parameters.getDomain(),
                parameters.getApplicationName(),
                rootInstanceName );

        VirtualMachine vm = getVirtualMachine( vmwareServiceInstance, machineImageId );
        String vmwareDataCenter = targetProperties.get( DATA_CENTER );
        Folder vmFolder =
                ((Datacenter)(new InventoryNavigator( vmwareServiceInstance.getRootFolder())
                .searchManagedEntity("Datacenter", vmwareDataCenter)))
                .getVmFolder();

        this.logger.fine("machineImageId=" + machineImageId);
        if (vm == null || vmFolder == null)
            throw new TargetException("VirtualMachine (= " + vm + " ) or Datacenter path (= " + vmFolder + " ) is NOT correct. Please, double check.");

        VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
        cloneSpec.setLocation(new VirtualMachineRelocateSpec());
        cloneSpec.setPowerOn(false);
        cloneSpec.setTemplate(true);

        VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec();
        vmSpec.setAnnotation( userData );
        cloneSpec.setConfig(vmSpec);

        Task task = vm.cloneVM_Task( vmFolder, rootInstanceName, cloneSpec );
        this.logger.fine("Cloning the template: "+ machineImageId +" ...");
        String status = task.waitForTask();
        if (!status.equals(Task.SUCCESS))
            throw new TargetException("Failure: Virtual Machine cannot be cloned." );

        VirtualMachine vm2 = getVirtualMachine( vmwareServiceInstance, rootInstanceName );
        this.logger.fine("Transforming the clone template to Virtual machine ...");
        vm2.markAsVirtualMachine( vmwareComputeResource.getResourcePool(), null);

        DynamicProperty dprop = new DynamicProperty();
        dprop.setName("guestinfo.userdata");
        dprop.setVal(userData);
        vm2.getGuest().setDynamicProperty(new DynamicProperty[]{dprop});

        task = vm2.powerOnVM_Task(null);
        this.logger.fine("Starting the virtual machine: "+ rootInstanceName +" ...");
        status = task.waitForTask();
        if( ! status.equals( Task.SUCCESS ))
            throw new TargetException("Failure: Virtual Machine cannot be started." );

        return vm2.getName();

    } catch( Exception e ) {
        throw new TargetException( e );
    }
}
项目:jcloud-vsphere    文件:FileManagerApi.java   
/**
 * Change oner of one file on datastore.
 *
 * @param name
 * @param datacenter
 * @param owner
 * @throws InvalidDatastore
 * @throws FileFault
 * @throws UserNotFound
 * @throws RuntimeFault
 * @throws RemoteException
 */
void changeOwner(String name, Datacenter datacenter, String owner) throws InvalidDatastore, FileFault, UserNotFound, RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:VirtualDiskManagerApi.java   
/**
 * SDK2.5 signature for back compatibility
 */
Task extendVirtualDiskTask(String name, Datacenter datacenter, long newCapacityKb) throws FileFault, RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:VirtualDiskManagerApi.java   
/**
 * SDK4.0 signature
 */
Task extendVirtualDiskTask(String name, Datacenter datacenter, long newCapacityKb, Boolean eagerZero) throws FileFault, RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:VirtualDiskManagerApi.java   
/**
 * @since SDK4.0
 */
Task eagerZeroVirtualDiskTask(String name, Datacenter datacenter) throws FileFault, RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:IpPoolManagerApi.java   
/**
 * @since SDK5.1
 */
String allocateIpv4Address(Datacenter dc, int poolId, String allocationId) throws RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:IpPoolManagerApi.java   
/**
 * @since SDK5.1
 */
String allocateIpv6Address(Datacenter dc, int poolId, String allocationId) throws RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:IpPoolManagerApi.java   
/**
 * @since SDK5.1
 */
List<IpPoolManagerIpAllocation> queryIPAllocations(Datacenter dc, int poolId, String extensionKey) throws RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:IpPoolManagerApi.java   
/**
 * @since SDK5.1
 */
void releaseIpAllocation(Datacenter dc, int poolId, String allocationId) throws RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:FileManagerApi.java   
Task copyDatastoreFileTask(String sourceName, Datacenter sourceDatacenter, String destinationName, Datacenter destinationDatacenter, boolean force) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:FileManagerApi.java   
Task deleteDatastoreFileTask(String name, Datacenter datacenter) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException;
项目:jcloud-vsphere    文件:FileManagerApi.java   
void makeDirectory(String name, Datacenter datacenter, boolean createParentDirectories) throws FileFault, InvalidDatastore, RuntimeFault, java.rmi.RemoteException;
项目:jcloud-vsphere    文件:FileManagerApi.java   
Task moveDatastoreFileTask(String sourceName, Datacenter sourceDatacenter, String destinationName, Datacenter destinationDatacenter, boolean force) throws FileFault, InvalidDatastore, RuntimeFault, RemoteException;