Esempio n. 1
0
  public VirtualMachineProxyImpl(
      DebugProcessImpl debugProcess, @NotNull VirtualMachine virtualMachine) {
    myVirtualMachine = virtualMachine;
    myDebugProcess = debugProcess;

    myVersionHigher_15 = versionHigher("1.5");
    myVersionHigher_14 = myVersionHigher_15 || versionHigher("1.4");

    // avoid lazy-init for some properties: the following will pre-calculate values
    canRedefineClasses();
    canWatchFieldModification();
    canPopFrames();

    try {
      // this will cache classes inside JDI and enable faster search of classes later
      virtualMachine.allClasses();
    } catch (Throwable e) {
      // catch all exceptions in order not to break vm attach process
      // Example:
      // java.lang.IllegalArgumentException: Invalid JNI signature character ';'
      //  caused by some bytecode "optimizers" which break type signatures as a side effect.
      //  solution if you are using JAX-WS: add
      // -Dcom.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize=true to JVM args
      LOG.info(e);
    }

    virtualMachine.topLevelThreadGroups().forEach(this::threadGroupCreated);
  }
Esempio n. 2
0
  synchronized VirtualMachine open() {
    if (connector instanceof LaunchingConnector) {
      vm = launchTarget();
    } else if (connector instanceof AttachingConnector) {
      vm = attachTarget();
    } else if (connector instanceof ListeningConnector) {
      vm = listenTarget();
    } else {
      throw new InternalError(MessageOutput.format("Invalid connect type"));
    }
    vm.setDebugTraceMode(traceFlags);
    if (vm.canBeModified()) {
      setEventRequests(vm);
      resolveEventRequests();
    }
    /*
     * Now that the vm connection is open, fetch the debugee
     * classpath and set up a default sourcepath.
     * (Unless user supplied a sourcepath on the command line)
     * (Bug ID 4186582)
     */
    if (Env.getSourcePath().length() == 0) {
      if (vm instanceof PathSearchingVirtualMachine) {
        PathSearchingVirtualMachine psvm = (PathSearchingVirtualMachine) vm;
        Env.setSourcePath(psvm.classPath());
      } else {
        Env.setSourcePath(".");
      }
    }

    return vm;
  }
Esempio n. 3
0
 @Override
 public void migrateVM(final VirtualMachine vm, final PhysicalMachine target)
     throws VMManagementException, NetworkNode.NetworkException {
   if (vms.contains(vm)) {
     vm.migrate(
         target.allocateResources(vm.getResourceAllocation().allocated, true, migrationAllocLen));
   }
 }
  @Override
  public void execute(VirtualMachine vm, List<String> parameters) {
    Variable variable1 = vm.getVariable(parameters.get(1));
    Variable variable2 = vm.getVariable(parameters.get(2));

    vm.setReturnValue(
        (Integer.parseInt(variable1.getValue()) > Integer.parseInt(variable2.getValue())) + "");
  }
  @Override
  public Long getIdPublicAddressOfVM(VirtualMachine vm) {
    if (vm.publicIpAddress() != null) {
      return vm.publicIpAddress().get().getId();
    }

    return null;
  }
Esempio n. 6
0
  private static ExecutionContext buildInitializedContext(
      VirtualMachine vm, String methodSignature, VMState state) {
    VirtualMethod method = vm.getClassManager().getMethod(methodSignature);
    ExecutionContext context = vm.spawnRootContext(method);
    int registerCount = context.getMethodState().getRegisterCount();
    setupMethodState(context, state.getRegisters(), registerCount);
    setupClassStates(context, vm, state.getFields());

    return context;
  }
  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || !(o instanceof VirtualMachine)) {
      return false;
    }

    VirtualMachine that = (VirtualMachine) o;
    return name.equals(that.getName());
  }
  public boolean isInstanceOf(Instance instance, List<VirtualMachine> vms, long cloudId) {
    boolean result = false;

    for (VirtualMachine vm : vms) {
      Long vmId = vm.getId();

      if (vm.cloud().getId().equals(cloudId) && instance.getVirtualMachine().getId().equals(vmId)) {
        result = true;
      }
    }

    return result;
  }
 private void assertVirtualMachine(VirtualMachine virtualMachine) {
   assertEquals(
       "getVirtualMachine doesn't return correct result", VM_1_NAME, virtualMachine.getName());
   assertEquals(
       "getVirtualMachine doesn't return correct result",
       VmState.RUNNING,
       virtualMachine.getCurrentState());
   assertEquals(
       "getVirtualMachine doesn't return correct result", HWP_1_ID, virtualMachine.getProductId());
   assertEquals(
       "getVirtualMachine doesn't return correct result",
       REGION,
       virtualMachine.getProviderRegionId());
   assertEquals(
       "getVirtualMachine doesn't return correct result",
       DATACENTER_ID,
       virtualMachine.getProviderDataCenterId());
   assertEquals(
       "getVirtualMachine doesn't return correct result",
       VM_1_OWNER,
       virtualMachine.getProviderOwnerId());
   assertEquals(
       "getVirtualMachine doesn't return correct result",
       VM_1_NETWORK_ID,
       virtualMachine.getProviderVlanId());
   assertEquals(
       "getVirtualMachine doesn't return correct result",
       VM_1_NETWORK_IP_ADDRESSES.get(0),
       virtualMachine.getPublicAddresses()[0].getIpAddress());
 }
  /** Second part of debugger start procedure. */
  private void startDebugger() {
    threadManager = new ThreadManager(this);

    setBreakpoints();
    updateWatches();
    println(bundle.getString("CTL_Debugger_running"), STL_OUT);
    setDebuggerState(DEBUGGER_RUNNING);

    virtualMachine.resume();

    // start refresh thread .................................................
    if (debuggerThread != null) debuggerThread.stop();
    debuggerThread =
        new Thread(
            new Runnable() {
              public void run() {
                for (; ; ) {
                  try {
                    Thread.sleep(5000);
                  } catch (InterruptedException ex) {
                  }
                  if (getState() == DEBUGGER_RUNNING) threadGroup.refresh();
                }
              }
            },
            "Debugger refresh thread"); // NOI18N
    debuggerThread.setPriority(Thread.MIN_PRIORITY);
    debuggerThread.start();
  }
Esempio n. 11
0
 public void deployVM(
     final VirtualMachine vm, final ResourceAllocation ra, final Repository vaSource)
     throws VMManagementException, NetworkNode.NetworkException {
   if (checkAllocationsPresence(ra)) {
     final VirtualAppliance va = vm.getVa();
     final StorageObject foundLocal = localDisk.lookup(va.id);
     final StorageObject foundRemote = vaSource == null ? null : vaSource.lookup(va.id);
     if (foundLocal != null || foundRemote != null) {
       vm.switchOn(ra, vaSource);
     } else {
       throw new VMManagementException("No VA available!");
     }
   } else {
     throw new VMManagementException("Tried to deploy VM with an expired resource allocation");
   }
 }
Esempio n. 12
0
 public List<ReferenceType> allClasses() {
   List<ReferenceType> allClasses = myAllClasses;
   if (allClasses == null) {
     myAllClasses = allClasses = myVirtualMachine.allClasses();
   }
   return allClasses;
 }
Esempio n. 13
0
 public void redefineClasses(Map<ReferenceType, byte[]> map) {
   DebuggerManagerThreadImpl.assertIsManagerThread();
   try {
     myVirtualMachine.redefineClasses(map);
   } finally {
     clearCaches();
   }
 }
 /** Go. */
 public synchronized void go() throws DebuggerException {
   if (virtualMachine == null) return;
   setLastAction(ACTION_GO);
   removeStepRequest();
   virtualMachine.resume();
   threadGroup.refresh();
   super.go();
 }
Esempio n. 15
0
 @Override
 public void terminateVM(final VirtualMachine vm, final boolean killTasks)
     throws NoSuchVMException, VMManagementException {
   if (!vms.contains(vm)) {
     throw new NoSuchVMException("Termination request was received for an unknown VM");
   }
   vm.switchoff(killTasks);
 }
Esempio n. 16
0
  public void dispose() {
    try {
      myVirtualMachine.dispose();
    } catch (UnsupportedOperationException e) {
      LOG.info(e);
    }

    // Memory leak workaround, see IDEA-163334
    TargetVM target =
        ReflectionUtil.getField(
            myVirtualMachine.getClass(), myVirtualMachine, TargetVM.class, "target");
    if (target != null) {
      Thread controller =
          ReflectionUtil.getField(target.getClass(), target, Thread.class, "eventController");
      if (controller != null) {
        controller.stop();
      }
    }
  }
Esempio n. 17
0
  private Configuration makeConfiguration() {
    Configuration cfg = new SimpleConfiguration();
    for (int i = 1; i <= 20; i++) {
      VirtualMachine vm = new SimpleVirtualMachine("vappHA.VM" + i);
      cfg.addWaiting(vm);
      if (i % 2 == 0) {
        vm.setTemplate("foo");
      } else {
        vm.setTemplate("bar");
      }
    }
    VirtualMachine vmX = new SimpleVirtualMachine("vappHA.top");
    vmX.setTemplate("foo");
    cfg.addWaiting(vmX);
    VirtualMachine vmY = new SimpleVirtualMachine("vappHA.middle");
    vmX.setTemplate("ttt");
    cfg.addWaiting(vmY);

    for (int i = 1; i <= 20; i++) {
      Node n = new SimpleNode("node-" + i);
      cfg.addOnline(n);
    }
    cfg.addOnline(new SimpleNode("node-frontend"));
    return cfg;
  }
Esempio n. 18
0
  public static ExecutionGraph execute(
      VirtualMachine vm, String className, String methodDescriptor, VMState state) {
    String methodSignature = className + "->" + methodDescriptor;
    ExecutionContext context = buildInitializedContext(vm, methodSignature, state);
    ExecutionGraph graph = null;
    try {
      graph = vm.execute(methodSignature, context);
    } catch (VirtualMachineException e) {
      e.printStackTrace();
    }

    return graph;
  }
Esempio n. 19
0
 /* launch child target vm */
 private VirtualMachine launchTarget() {
   LaunchingConnector launcher = (LaunchingConnector) connector;
   try {
     VirtualMachine vm = launcher.launch(connectorArgs);
     process = vm.process();
     displayRemoteOutput(process.getErrorStream());
     displayRemoteOutput(process.getInputStream());
     return vm;
   } catch (IOException ioe) {
     ioe.printStackTrace();
     MessageOutput.fatalError("Unable to launch target VM.");
   } catch (IllegalConnectorArgumentsException icae) {
     icae.printStackTrace();
     MessageOutput.fatalError("Internal debugger error.");
   } catch (VMStartException vmse) {
     MessageOutput.println("vmstartexception", vmse.getMessage());
     MessageOutput.println();
     dumpFailedLaunchInfo(vmse.process());
     MessageOutput.fatalError("Target VM failed to initialize.");
   }
   return null; // Shuts up the compiler
 }
Esempio n. 20
0
 void release() {
   if (user != null) {
     vms.remove(user);
     user.unsubscribeStateChange(this);
     completedVMs++;
     internalAvailableCaps.singleAdd(realAllocated);
     internalReallyFreeCaps.singleAdd(realAllocated);
     increasingFreeCapacityListenerManager.notifyListeners(
         Collections.singletonList(realAllocated));
     user = null;
     swept = true;
   }
 }
Esempio n. 21
0
  @Test(enabled = true)
  public void testCreateTemplate() throws Exception {
    Zone zone = Iterables.getFirst(client.getZoneClient().listZones(), null);
    assertNotNull(zone);
    Iterable<Network> networks =
        client
            .getNetworkClient()
            .listNetworks(ListNetworksOptions.Builder.zoneId(zone.getId()).isDefault(true));
    networks =
        Iterables.filter(
            networks,
            new Predicate<Network>() {
              @Override
              public boolean apply(@Nullable Network network) {
                return network != null && network.getState().equals("Implemented");
              }
            });
    assertEquals(Iterables.size(networks), 1);
    Network network = Iterables.getOnlyElement(networks, null);
    assertNotNull(network);

    // Create a VM and stop it
    Long templateId = (imageId != null && !"".equals(imageId)) ? new Long(imageId) : null;
    vmForCreation =
        VirtualMachineClientLiveTest.createVirtualMachineInNetwork(
            network, templateId, client, jobComplete, virtualMachineRunning);
    assertTrue(
        jobComplete.apply(
            client.getVirtualMachineClient().stopVirtualMachine(vmForCreation.getId())),
        vmForCreation.toString());

    // Work out the VM's volume
    Set<Volume> volumes =
        client
            .getVolumeClient()
            .listVolumes(ListVolumesOptions.Builder.virtualMachineId(vmForCreation.getId()));
    assertEquals(volumes.size(), 1);
    Volume volume = Iterables.getOnlyElement(volumes);

    // Create a template
    CreateTemplateOptions options = CreateTemplateOptions.Builder.volumeId(volume.getId());
    AsyncCreateResponse response =
        client
            .getTemplateClient()
            .createTemplate(
                TemplateMetadata.builder()
                    .name(prefix + "-createTemplate")
                    .osTypeId(vmForCreation.getGuestOSId())
                    .displayText("jclouds live testCreateTemplate")
                    .build(),
                options);
    assertTrue(jobComplete.apply(response.getJobId()), vmForCreation.toString());
    createdTemplate =
        client.getTemplateClient().getTemplateInZone(response.getId(), vmForCreation.getZoneId());

    // Assertions
    assertNotNull(createdTemplate);
  }
 /** Test serialization/unserialization */
 public void test() {
   Configuration cfg = new SimpleConfiguration();
   for (int i = 1; i <= 10; i++) {
     Node n = new SimpleNode("N" + i, i, i + 1, i + 2);
     if (i % 3 == 0) {
       cfg.addOffline(n);
     } else {
       cfg.addOnline(n);
     }
   }
   Random rnd = new Random();
   for (int i = 1; i <= 20; i++) {
     VirtualMachine vm = new SimpleVirtualMachine("VM" + i, i, i + 1, i + 2);
     vm.setCPUDemand(i + 3);
     vm.setCPUMax(i + 7);
     Node n = cfg.getOnlines().get(rnd.nextInt(cfg.getOnlines().size()));
     if (i % 3 == 0) {
       cfg.setSleepOn(vm, n);
     } else if (i % 5 == 0) {
       cfg.addWaiting(vm);
     } else {
       cfg.setRunOn(vm, n);
     }
   }
   FileConfigurationSerializer s = PlainTextConfigurationSerializer.getInstance();
   File tmpF;
   try {
     tmpF = File.createTempFile("out", "out");
     tmpF.deleteOnExit();
     s.write(cfg, tmpF.getAbsolutePath());
     Configuration r = s.read(tmpF.getAbsolutePath());
     Assert.assertEquals(r, cfg);
   } catch (IOException e) {
     Assert.fail(e.getMessage(), e);
   } catch (ConfigurationSerializerException e) {
     Assert.fail(e.getMessage(), e);
   }
 }
Esempio n. 23
0
 public void disposeVM() {
   try {
     if (vm != null) {
       vm.dispose();
       vm = null;
     }
   } finally {
     if (process != null) {
       process.destroy();
       process = null;
     }
     waitOutputComplete();
   }
 }
Esempio n. 24
0
 void use(final VirtualMachine vm) throws VMManagementException {
   if (swept) {
     throw new VMManagementException("Tried to use an already expired allocation");
   }
   if (user == null) {
     user = vm;
     internalAvailableCaps.subtract(realAllocated);
     vms.add(vm);
     vm.subscribeStateChange(this);
     cancel();
   } else {
     throw new VMManagementException("Tried to use a resource allocation more than once!");
   }
 }
Esempio n. 25
0
  public void close() {
    // TODO make sure stop() has already been called to exit the sketch

    // TODO actually kill off the vm here
    if (vm != null) {
      try {
        vm.exit(0);

      } catch (com.sun.jdi.VMDisconnectedException vmde) {
        // if the vm has disconnected on its own, ignore message
        // System.out.println("harmless disconnect " + vmde.getMessage());
        // TODO shouldn't need to do this, need to do more cleanup
      }
      vm = null;
    }
  }
 /** Disconnects from running debugged process. */
 public void disconnect() throws DebuggerException {
   if (breakpointMain != null) {
     for (int x = 0; x < breakpointMain.length; x++) breakpointMain[x].remove();
     breakpointMain = null;
   }
   try {
     if (virtualMachine != null) virtualMachine.dispose();
   } catch (VMDisconnectedException e) {
   }
   if (threadManager != null) threadManager.finish();
   if (debuggerThread != null) {
     debuggerThread.interrupt();
     debuggerThread.stop();
   }
   super.finishDebugger();
 }
Esempio n. 27
0
 public void resume() {
   DebuggerManagerThreadImpl.assertIsManagerThread();
   if (myPausePressedCount > 0) {
     myPausePressedCount--;
   }
   clearCaches();
   LOG.debug("before resume VM");
   try {
     myVirtualMachine.resume();
   } catch (InternalException e) {
     // ok to ignore. Although documentation says it is safe to invoke resume() on running VM,
     // sometimes this leads to com.sun.jdi.InternalException: Unexpected JDWP Error: 13
     // (THREAD_NOT_SUSPENDED)
     LOG.info(e);
   }
   LOG.debug("VM resumed");
   // logThreads();
 }
 /** Step out. */
 public synchronized void stepOut() throws DebuggerException {
   if (virtualMachine == null) return;
   removeStepRequest();
   try {
     setLastAction(ACTION_STEP_OUT);
     stepRequest =
         requestManager.createStepRequest(
             currentThread.getThreadReference(), StepRequest.STEP_LINE, StepRequest.STEP_OUT);
     stepRequest.addCountFilter(1);
     stepRequest.setSuspendPolicy(EventRequest.SUSPEND_ALL);
     operator.register(stepRequest, this);
     stepRequest.enable();
     virtualMachine.resume();
     super.stepOut();
   } catch (DuplicateRequestException e) {
     e.printStackTrace();
   }
 }
Esempio n. 29
0
  private void setEventRequests(VirtualMachine vm) {
    EventRequestManager erm = vm.eventRequestManager();

    // Normally, we want all uncaught exceptions.  We request them
    // via the same mechanism as Commands.commandCatchException()
    // so the user can ignore them later if they are not
    // interested.
    // FIXME: this works but generates spurious messages on stdout
    //        during startup:
    //          Set uncaught j86.java.lang.Throwable
    //          Set deferred uncaught j86.java.lang.Throwable
    Commands evaluator = new Commands();
    evaluator.commandCatchException(new StringTokenizer("uncaught j86.java.lang.Throwable"));

    ThreadStartRequest tsr = erm.createThreadStartRequest();
    tsr.enable();
    ThreadDeathRequest tdr = erm.createThreadDeathRequest();
    tdr.enable();
  }
Esempio n. 30
0
 private static void setupClassStates(
     ExecutionContext context,
     VirtualMachine vm,
     Map<String, Map<String, HeapItem>> classNameToFieldDescriptorToItem) {
   ClassManager classManager = vm.getClassManager();
   for (Entry<String, Map<String, HeapItem>> entry : classNameToFieldDescriptorToItem.entrySet()) {
     String className = entry.getKey();
     VirtualClass virtualClass = classManager.getVirtualClass(className);
     Map<String, HeapItem> fieldDescriptorToItem = entry.getValue();
     ClassState cState = context.peekClassState(virtualClass);
     for (Entry<String, HeapItem> fieldNameAndTypeToItem : fieldDescriptorToItem.entrySet()) {
       String fieldNameAndType = fieldNameAndTypeToItem.getKey();
       String fieldName = fieldNameAndType.split(":")[0];
       VirtualField field = virtualClass.getField(fieldName);
       HeapItem item = fieldNameAndTypeToItem.getValue();
       cState.pokeField(field, item);
     }
     context.initializeClass(cState, SideEffect.Level.NONE);
   }
 }