private static VdcQueryReturnValue createGetDeviceListReturnValue(List<LUNs> luns) {
    VdcQueryReturnValue returnValue = new VdcQueryReturnValue();
    returnValue.setSucceeded(true);
    returnValue.setReturnValue(luns);

    return returnValue;
  }
  @Override
  public ExternalHostGroup get() {
    // Convert the resource identifier to the host group name:
    String name = hex2string(id);

    // The backend query that retrieves the list of hosts groups needs a complete provider instance,
    // the id isn't
    // enough:
    Provider provider = BackendExternalProviderHelper.getProvider(this, providerId);

    // The backend doesn't have a way to retrieve a host by ide, so we have to iterate them:
    ProviderQueryParameters parameters = new ProviderQueryParameters();
    parameters.setProvider(provider);
    VdcQueryReturnValue result =
        runQuery(VdcQueryType.GetHostGroupsFromExternalProvider, parameters);
    List<org.ovirt.engine.core.common.businessentities.ExternalHostGroup> entities =
        result.getReturnValue();
    if (entities != null) {
      for (org.ovirt.engine.core.common.businessentities.ExternalHostGroup entity : entities) {
        if (name.equals(entity.getName())) {
          return addLinks(populate(map(entity), entity));
        }
      }
    }

    // No luck:
    return notFound();
  }
Example #3
0
  private boolean runQuery(HttpServletResponse response, String sessionID) {
    boolean returnValue = false;

    log.debug("Calling ValidateSession query");

    VdcQueryReturnValue queryReturnValue =
        backend.runInternalQuery(
            VdcQueryType.ValidateSession, new VdcQueryParametersBase(sessionID));

    if (queryReturnValue != null) {
      returnValue = queryReturnValue.getSucceeded();

      if (returnValue) {
        DbUser user = queryReturnValue.getReturnValue();

        // We get the user name only in case the validation succeeded, and the user is an
        // administrator
        if (user.isAdmin()) {
          log.debug("Getting user name");
          printUPNToResponse(response, getUPN(user));
        } else {
          log.error("User '{}' is not authorized to perform operation", user.getLoginName());
          returnValue = false;
        }
      }
    } else {
      log.error("Got NULL from backend.RunQuery");
    }

    return returnValue;
  }
 private VdcQueryReturnValue createVmQueryResult() {
   final VdcQueryReturnValue v = new VdcQueryReturnValue();
   List<VM> list = new ArrayList<VM>();
   list.add(createVM());
   v.setReturnValue(list);
   v.setSucceeded(true);
   return v;
 }
Example #5
0
  public void setCertificateInfo(VM model) {
    VdcQueryReturnValue result =
        runQuery(
            VdcQueryType.GetVdsCertificateSubjectByVmId,
            new IdQueryParameters(asGuid(model.getId())));

    if (result != null && result.getSucceeded() && result.getReturnValue() != null) {
      if (!model.isSetDisplay()) {
        model.setDisplay(new Display());
      }
      model.getDisplay().setCertificate(new Certificate());
      model.getDisplay().getCertificate().setSubject(result.getReturnValue().toString());
    }
  }
 /**
  * Run the following test case.
  *
  * <ol>
  *   <li>Run a search query, with *win* as the parameter, searching for VMs
  *   <li>The callback is NOT marked to handle failures
  *   <li>The failure is a not logged in failure
  *   <li>Return success, but the success status is !succeeded (business logic failure/not logged
  *       in)
  *   <li>Check to make sure the appropriate query start and query complete events are fired
  * </ol>
  */
 @Test
 public void testRunQuery_success_not_succeeded_eventshandler_nocallbackhandler() {
   VdcQueryParametersBase testParameters =
       new SearchParameters("*win*", SearchType.VM); // $NON-NLS-1$
   frontend.runQuery(VdcQueryType.Search, testParameters, mockAsyncQuery, false);
   verify(mockService).RunQuery(eq(VdcQueryType.Search), eq(testParameters), callback.capture());
   VdcQueryReturnValue mockReturnValue = new VdcQueryReturnValue();
   mockReturnValue.setExceptionString("USER_IS_NOT_LOGGED_IN"); // $NON-NLS-1$
   // Return value set to failure
   mockReturnValue.setSucceeded(false);
   callback.getValue().onSuccess(mockReturnValue);
   // Make sure the not logged in event is called
   verify(mockFrontendNotLoggedInEvent).raise(Frontend.class, EventArgs.EMPTY);
 }
 /**
  * Run the following test case.
  *
  * <ol>
  *   <li>Run a search query, with *win* as the parameter, searching for VMs
  *   <li>Return success, the success status is succeeded
  *   <li>No success converter defined
  *   <li>Check to make sure the appropriate query start and query complete events are fired
  * </ol>
  */
 @Test
 public void testRunQuery_success_succeeded_eventshandler_noconverter() {
   Object mockModel = new Object();
   when(mockAsyncQuery.getModel()).thenReturn(mockModel);
   VdcQueryParametersBase testParameters =
       new SearchParameters("*win*", SearchType.VM); // $NON-NLS-1$
   frontend.runQuery(VdcQueryType.Search, testParameters, mockAsyncQuery, false);
   verify(mockService).RunQuery(eq(VdcQueryType.Search), eq(testParameters), callback.capture());
   VdcQueryReturnValue mockReturnValue = new VdcQueryReturnValue();
   mockReturnValue.setSucceeded(true);
   callback.getValue().onSuccess(mockReturnValue);
   verify(mockAsyncQuery).setOriginalReturnValue(mockReturnValue);
   verify(mockAsyncCallback).onSuccess(mockModel, mockReturnValue);
 }
 /**
  * Run the following test case.
  *
  * <ol>
  *   <li>Run a search query, with *win* as the parameter, searching for VMs
  *   <li>Immediately, before returning a result, call the same run query again
  *   <li>Return success, the success status is succeeded
  *   <li>No success converter defined
  *   <li>Make sure that the result callback is called only once
  *   <li>Check to make sure the appropriate query start and query complete events are fired
  * </ol>
  */
 @Test
 public void testRunQuery_success_succeeded_multiple_same_eventshandler_noconverter() {
   Object mockModel = new Object();
   when(mockAsyncQuery.getModel()).thenReturn(mockModel);
   VdcQueryParametersBase testParameters =
       new SearchParameters("*win*", SearchType.VM); // $NON-NLS-1$
   frontend.runQuery(VdcQueryType.Search, testParameters, mockAsyncQuery, false);
   frontend.runQuery(VdcQueryType.Search, testParameters, mockAsyncQuery, false);
   verify(mockService).RunQuery(eq(VdcQueryType.Search), eq(testParameters), callback.capture());
   VdcQueryReturnValue mockReturnValue = new VdcQueryReturnValue();
   mockReturnValue.setExceptionString("USER_IS_NOT_LOGGED_IN"); // $NON-NLS-1$
   // Return value set to success
   mockReturnValue.setSucceeded(true);
   callback.getValue().onSuccess(mockReturnValue);
   verify(mockAsyncCallback).onSuccess(mockModel, mockReturnValue);
 }
Example #9
0
  private boolean isRepoImageExists(
      String repoImagePath, Guid storageDomainId, ImageFileType imageFileType) {
    VdcQueryReturnValue ret =
        getBackend()
            .runInternalQuery(
                VdcQueryType.GetImagesList,
                new GetImagesListParameters(storageDomainId, imageFileType));

    if (ret != null && ret.getReturnValue() != null && ret.getSucceeded()) {
      for (RepoImage isoFileMetaData : ret.<List<RepoImage>>getReturnValue()) {
        if (repoImagePath.equals(isoFileMetaData.getRepoImageId())) {
          return true;
        }
      }
    }
    return false;
  }
 /** @return true if all parameters class and its inner members passed validation */
 protected boolean validateInputs() {
   Set<ConstraintViolation<P>> violations = validator.validate(getParameters());
   if (!violations.isEmpty()) {
     returnValue.setExceptionString(violations.toString());
     return false;
   }
   return true;
 }
 @Override
 protected void executeCommand() {
   if (validatePermissions()) {
     if (validateInputs()) {
       try {
         returnValue.setSucceeded(true);
         executeQueryCommand();
       } catch (RuntimeException ex) {
         returnValue.setSucceeded(false);
         Throwable th = ex instanceof EngineException ? ex : ex.getCause();
         if (th instanceof EngineException) {
           EngineException vdcExc = (EngineException) th;
           if (vdcExc.getErrorCode() != null) {
             returnValue.setExceptionString(vdcExc.getErrorCode().toString());
           } else {
             returnValue.setExceptionString(vdcExc.getMessage());
           }
           log.error("Query '{}' failed: {}", getClass().getSimpleName(), vdcExc.getMessage());
           log.error("Exception", vdcExc);
         } else {
           returnValue.setExceptionString(ex.getMessage());
           log.error("Query '{}' failed: {}", getClass().getSimpleName(), ex.getMessage());
           log.error("Exception", ex);
         }
       }
     } else {
       log.error(
           "Query execution failed due to invalid inputs: {}", returnValue.getExceptionString());
     }
   } else {
     String errMessage = "Query execution failed due to insufficient permissions.";
     log.error(errMessage);
     returnValue.setExceptionString(errMessage);
   }
 }
  // TODO: REVISIT when backend expose CertificateSubject in vds
  public Host addCertificateInfo(Host host) {
    VdcQueryReturnValue result =
        runQuery(
            VdcQueryType.GetVdsCertificateSubjectByVdsId,
            new GetVdsByVdsIdParameters(asGuid(host.getId())));

    if (result != null && result.getSucceeded() && result.getReturnValue() != null) {
      String subject = result.getReturnValue().toString();
      if (subject != null) {
        host.setCertificate(new Certificate());
        host.getCertificate().setSubject(subject);
        host.getCertificate().setOrganization(subject.split(",")[0].replace("O=", ""));
      }
    } else {
      LOG.error("Could not fetch certificate info for host " + host.getId());
    }
    return host;
  }
  /**
   * Get devices (LUNs) that are visible by the host.
   *
   * @return the list of LUNs.
   */
  protected List<LUNs> getDeviceList() {
    List<LUNs> luns = new ArrayList<>();
    VdcQueryReturnValue returnValue =
        executeGetDeviceList(
            new GetDeviceListQueryParameters(
                getParameters().getVdsId(), getParameters().getStorageType(), false, null));

    if (returnValue.getSucceeded()) {
      luns.addAll(returnValue.<List<LUNs>>getReturnValue());
    } else {
      throw new RuntimeException(
          String.format(
              "GetDeviceList execution failed. Exception message: %1$s",
              returnValue.getExceptionString()));
    }

    return luns;
  }
  @Test
  public void failWhenCertEnforcedAndCANotFound() {
    when(getQueryParameters().getOptions()).thenReturn(getValidOptions(GraphicsType.SPICE));
    mockSessionDataContainer();
    mockGetVdsCertificateSubjectByVmId();
    doReturn(mockVm(GraphicsType.SPICE)).when(getQuery()).getCachedVm();

    mockSpiceRelatedConfig();

    VdcQueryReturnValue caResult = new VdcQueryReturnValue();
    caResult.setSucceeded(false);
    doReturn(caResult)
        .when(backend)
        .runInternalQuery(eq(VdcQueryType.GetCACertificate), any(VdcQueryParametersBase.class));

    getQuery().getQueryReturnValue().setSucceeded(true);
    getQuery().executeQueryCommand();
    assertFalse(getQuery().getQueryReturnValue().getSucceeded());
  }
  protected void updateRngDevice(Guid templateId) {
    // do not update if this flag is not set
    if (getParameters().isUpdateRngDevice()) {
      VdcQueryReturnValue query =
          runInternalQuery(VdcQueryType.GetRngDevice, new IdQueryParameters(templateId));

      List<VmRngDevice> rngDevs = query.getReturnValue();

      if (getParameters().getRngDevice() != null) {
        getParameters().getRngDevice().setVmId(templateId);
      }

      VdcReturnValueBase rngCommandResult = null;
      if (rngDevs.isEmpty()) {
        if (getParameters().getRngDevice() != null) {
          RngDeviceParameters params =
              new RngDeviceParameters(getParameters().getRngDevice(), false);
          rngCommandResult =
              runInternalAction(
                  VdcActionType.AddRngDevice, params, cloneContextAndDetachFromParent());
        }
      } else {
        if (getParameters().getRngDevice() == null) {
          RngDeviceParameters params = new RngDeviceParameters(rngDevs.get(0), false);
          rngCommandResult =
              runInternalAction(
                  VdcActionType.RemoveRngDevice, params, cloneContextAndDetachFromParent());
        } else {
          RngDeviceParameters params =
              new RngDeviceParameters(getParameters().getRngDevice(), false);
          params.getRngDevice().setDeviceId(rngDevs.get(0).getDeviceId());
          rngCommandResult =
              runInternalAction(
                  VdcActionType.UpdateRngDevice, params, cloneContextAndDetachFromParent());
        }
      }

      if (rngCommandResult != null && !rngCommandResult.getSucceeded()) {
        getReturnValue().setSucceeded(false);
      }
    }
  }
  protected void updateWatchdog(Guid templateId) {
    // do not update if this flag is not set
    if (getParameters().isUpdateWatchdog()) {
      VdcQueryReturnValue query =
          runInternalQuery(VdcQueryType.GetWatchdog, new IdQueryParameters(templateId));
      List<VmWatchdog> watchdogs = query.getReturnValue();
      if (watchdogs.isEmpty()) {
        if (getParameters().getWatchdog() != null) {
          WatchdogParameters parameters = new WatchdogParameters();
          parameters.setVm(false);
          parameters.setClusterIndependent(
              getVmTemplate().getTemplateType() == VmEntityType.INSTANCE_TYPE || isBlankTemplate());

          parameters.setId(templateId);
          parameters.setAction(getParameters().getWatchdog().getAction());
          parameters.setModel(getParameters().getWatchdog().getModel());
          runInternalAction(
              VdcActionType.AddWatchdog, parameters, cloneContextAndDetachFromParent());
        }
      } else {
        WatchdogParameters watchdogParameters = new WatchdogParameters();
        watchdogParameters.setVm(false);
        watchdogParameters.setClusterIndependent(
            getVmTemplate().getTemplateType() == VmEntityType.INSTANCE_TYPE || isBlankTemplate());

        watchdogParameters.setId(templateId);
        if (getParameters().getWatchdog() == null) {
          // there is a watchdog in the vm, there should not be any, so let's delete
          runInternalAction(
              VdcActionType.RemoveWatchdog, watchdogParameters, cloneContextAndDetachFromParent());
        } else {
          // there is a watchdog in the vm, we have to update.
          watchdogParameters.setAction(getParameters().getWatchdog().getAction());
          watchdogParameters.setModel(getParameters().getWatchdog().getModel());
          runInternalAction(
              VdcActionType.UpdateWatchdog, watchdogParameters, cloneContextAndDetachFromParent());
        }
      }
    }
  }
 @Override
 protected void addUsersToModel(VdcQueryReturnValue returnValue, Set<String> excludeUsers) {
   Iterable<DbUser> filteredUsers =
       Linq.where(
           (ArrayList<DbUser>) returnValue.getReturnValue(),
           new Linq.DbUserPredicate(getTargetDbUser()));
   for (DbUser dbUser : filteredUsers) {
     if (!excludeUsers.contains(dbUser.getExternalId())) {
       EntityModel tempVar2 = new EntityModel();
       tempVar2.setEntity(dbUser);
       getusers().add(tempVar2);
     }
   }
 }
  @Override
  protected void addGroupsToModel(VdcQueryReturnValue returnValue, Set<String> excludeUsers) {
    Iterable<DbGroup> filteredGroups =
        Linq.where(
            (ArrayList<DbGroup>) returnValue.getReturnValue(),
            new Linq.DbGroupPredicate(getTargetDbGroup()));

    for (DbGroup group : filteredGroups) {
      if (!excludeUsers.contains(group.getId().toString())) {
        DbUser dbUser = new DbUser();
        dbUser.setExternalId(group.getExternalId());
        dbUser.setFirstName(group.getName());
        dbUser.setLastName(""); // $NON-NLS-1$
        dbUser.setLoginName(""); // $NON-NLS-1$
        dbUser.setDomain(group.getDomain());
        dbUser.setNamespace(group.getNamespace());

        EntityModel entity = new EntityModel();
        entity.setEntity(dbUser);
        getgroups().add(entity);
      }
    }
  }
 private VdcQueryReturnValue getVdcReturnValue() {
   VdcQueryReturnValue retValue = new VdcQueryReturnValue();
   retValue.setSucceeded(true);
   retValue.setReturnValue(serverKeyFingerprint);
   return retValue;
 }
  public void SetDefaultNames(VDS host, RefObject<String> message) {
    message.argvalue = null;
    setCommonName(StringFormat.format("%1$s-Local", host.getvds_name().replace('.', '-')));
    storage_pool candidate = null;

    // selecet all possible DCs
    VdcQueryReturnValue returnValue =
        Frontend.RunQuery(
            VdcQueryType.Search,
            new SearchParameters(
                StringFormat.format("DataCenter: name=%1$s", getCommonName() + "*"),
                SearchType.StoragePool));

    java.util.ArrayList<storage_pool> dataCenterList = new java.util.ArrayList<storage_pool>();
    java.util.ArrayList<VDSGroup> clusterList = null;
    if (returnValue != null && returnValue.getSucceeded() && returnValue.getReturnValue() != null) {
      dataCenterList =
          Linq.<storage_pool>Cast(
              (java.util.ArrayList<IVdcQueryable>) returnValue.getReturnValue());
    }
    // check if current settings suitable for local setup (in case just SD creation failed -
    // re-using the same setup)
    boolean useCurrentSettings = false;
    if (host.getstorage_pool_id() != null) {
      storage_pool tempCandidate = DataProvider.GetDataCenterById(host.getstorage_pool_id());
      if (IsLocalDataCenterEmpty(tempCandidate)) {
        candidate = tempCandidate;
        useCurrentSettings = true;
      } else {
        if (tempCandidate != null && tempCandidate.getstorage_pool_type() == StorageType.LOCALFS) {
          message.argvalue =
              "Note: Local Storage is already configured for this Host. The Host belongs to "
                  + host.getstorage_pool_name()
                  + " with local Storage Domain. If OK is clicked - this Host will be moved to a new Data Center, and a new Local Storage Domain will be created. Hit Cancel to abort the operation.";
        }
      }
    }
    // check if there is other DC suitable for re-use
    if (candidate == null) {
      for (storage_pool dataCenter : dataCenterList) {
        // need to check if the new DC is without host.
        if (IsLocalDataCenterEmpty(dataCenter)
            && DataProvider.GetLocalStorageHost(dataCenter.getname()) == null) {
          candidate = dataCenter;
          break;
        }
      }
    }
    java.util.ArrayList<String> listNames = new java.util.ArrayList<String>();
    // in case we found a suitable candidte for re-use:
    if (candidate != null) {
      getDataCenter().setDataCenterId(candidate.getId());
      getDataCenter().getName().setEntity(candidate.getname());
      getDataCenter().getDescription().setEntity(candidate.getdescription());
      Version compVersion = candidate.getcompatibility_version();
      getDataCenter().getVersion().setSelectedItem(compVersion);
      getCluster().getVersion().setSelectedItem(compVersion);
      setDontCreateDataCenter(true);
      // if we use current settings there is no need to create cluster.
      if (useCurrentSettings) {
        getCluster().setClusterId(host.getvds_group_id().getValue());
        getCluster().getName().setEntity(host.getvds_group_name());
        VDSGroup cluster = DataProvider.GetClusterById(host.getvds_group_id().getValue());
        if (cluster != null) {
          getCluster().getDescription().setEntity(cluster.getdescription());
          ServerCpu tempVar = new ServerCpu();
          tempVar.setCpuName(cluster.getcpu_name());
          getCluster().getCPU().setSelectedItem(tempVar);
        }
        setDontCreateCluster(true);
        setDontChangeHostCluster(true);
      }
      // use differnt cluster
      else {
        // check the DC cluster list (for re-use)
        clusterList = DataProvider.GetClusterList(candidate.getId());
        // no clusters avilable - pick up new name.
        if (clusterList.isEmpty()) {
          java.util.ArrayList<VDSGroup> listClusters = DataProvider.GetClusterList();
          listNames = new java.util.ArrayList<String>();
          for (VDSGroup cluster : listClusters) {
            listNames.add(cluster.getname());
          }
          getCluster().getName().setEntity(AvailableName(listNames));
        } else {
          // use the DC cluster.
          getCluster().setClusterId(clusterList.get(0).getId());
          getCluster().getName().setEntity(clusterList.get(0).getname());
          getCluster().getDescription().setEntity(clusterList.get(0).getdescription());
          VDSGroup cluster = DataProvider.GetClusterById(getCluster().getClusterId().getValue());
          if (cluster != null) {
            ServerCpu tempVar2 = new ServerCpu();
            tempVar2.setCpuName(cluster.getcpu_name());
            getCluster().getCPU().setSelectedItem(tempVar2);
          }
          setDontCreateCluster(true);
          if (host.getvds_group_id().getValue().equals(getCluster().getClusterId())) {
            setDontChangeHostCluster(true);
          }
        }
      }
    } else {
      // didn't found DC to re-use, so we select new names:
      listNames = new java.util.ArrayList<String>();
      for (storage_pool storagePool : dataCenterList) {
        listNames.add(storagePool.getname());
      }
      getDataCenter().getName().setEntity(AvailableName(listNames));

      // Choose a Data Center version corresponding to the host.
      if (!StringHelper.isNullOrEmpty(host.getsupported_cluster_levels())) {
        // the supported_cluster_levels are sorted.
        String[] array = host.getsupported_cluster_levels().split("[,]", -1);
        Version maxCombindVersion = null;

        for (int i = 0; i < array.length; i++) {
          Version vdsVersion = new Version(array[i]);
          for (Version version :
              (java.util.List<Version>) getDataCenter().getVersion().getItems()) {
            if (version.equals(vdsVersion) && version.compareTo(maxCombindVersion) > 0) {
              maxCombindVersion = version;
            }
          }
        }
        if (maxCombindVersion != null) {
          getDataCenter().getVersion().setSelectedItem(maxCombindVersion);
          getCluster().getVersion().setSelectedItem(maxCombindVersion);
        }
      }

      listNames = new java.util.ArrayList<String>();
      if (clusterList == null) {
        clusterList = DataProvider.GetClusterList();
      }

      for (VDSGroup cluster : clusterList) {
        listNames.add(cluster.getname());
      }
      getCluster().getName().setEntity(AvailableName(listNames));
    }

    // Choose default CPU name to match host.
    if (host.getCpuName() != null && getCluster().getCPU().getSelectedItem() != null) {
      getCluster()
          .getCPU()
          .setSelectedItem(
              Linq.FirstOrDefault(
                  (java.util.List<ServerCpu>) getCluster().getCPU().getItems(),
                  new Linq.ServerCpuPredicate(host.getCpuName().getCpuName())));
    }
    // always choose a avialable storage name.
    java.util.ArrayList<storage_domains> listStorageDomains = DataProvider.GetStorageDomainList();
    listNames = new java.util.ArrayList<String>();
    for (storage_domains storageDomain : listStorageDomains) {
      listNames.add(storageDomain.getstorage_name());
    }
    getFormattedStorageName().setEntity(AvailableName(listNames));
  }
 @Override
 public void setReturnValue(Object value) {
   returnValue.setReturnValue(value);
 }
 private VdcQueryReturnValue createDuplicateResult() {
   final VdcQueryReturnValue v = new VdcQueryReturnValue();
   v.setReturnValue(Boolean.FALSE);
   v.setSucceeded(true);
   return v;
 }