io.grpc.protobuf.StatusProto Java Examples

The following examples show how to use io.grpc.protobuf.StatusProto. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExperimentRunDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public String getProjectIdByExperimentRunId(String experimentRunId) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    ExperimentRunEntity experimentRunObj =
        session.get(ExperimentRunEntity.class, experimentRunId);
    if (experimentRunObj != null) {
      LOGGER.debug("Got ProjectId by ExperimentRunId ");
      return experimentRunObj.getProject_id();
    } else {
      String errorMessage = "ExperimentRun not found for given ID : " + experimentRunId;
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder().setCode(Code.NOT_FOUND_VALUE).setMessage(errorMessage).build();
      throw StatusProto.toStatusRuntimeException(status);
    }
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getProjectIdByExperimentRunId(experimentRunId);
    } else {
      throw ex;
    }
  }
}
 
Example #2
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public Project getProjectByID(String id) throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query query = session.createQuery(GET_PROJECT_BY_ID_HQL);
    query.setParameter("id", id);
    ProjectEntity projectEntity = (ProjectEntity) query.uniqueResult();
    if (projectEntity == null) {
      String errorMessage = ModelDBMessages.PROJECT_NOT_FOUND_FOR_ID;
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder().setCode(Code.NOT_FOUND_VALUE).setMessage(errorMessage).build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    LOGGER.debug(ModelDBMessages.GETTING_PROJECT_BY_ID_MSG_STR);
    return projectEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getProjectByID(id);
    } else {
      throw ex;
    }
  }
}
 
Example #3
Source File: ModelDBUtils.java    From modeldb with Apache License 2.0 6 votes vote down vote up
/**
 * If so throws an error if the workspace type is USER and the workspaceId and userID do not
 * match. Is a NO-OP if userinfo is null.
 */
public static void checkPersonalWorkspace(
    UserInfo userInfo,
    WorkspaceType workspaceType,
    String workspaceId,
    String resourceNameString) {
  if (userInfo != null
      && workspaceType == WorkspaceType.USER
      && !workspaceId.equals(userInfo.getVertaInfo().getUserId())) {
    Status status =
        Status.newBuilder()
            .setCode(Code.PERMISSION_DENIED_VALUE)
            .setMessage(
                "Creation of "
                    + resourceNameString
                    + " in other user's workspace is not permitted")
            .addDetails(Any.pack(UpdateProjectName.Response.getDefaultInstance()))
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }
}
 
Example #4
Source File: AuthServiceChannel.java    From modeldb with Apache License 2.0 6 votes vote down vote up
public AuthServiceChannel() {
  App app = App.getInstance();
  String host = app.getAuthServerHost();
  Integer port = app.getAuthServerPort();
  LOGGER.trace(ModelDBMessages.HOST_PORT_INFO_STR, host, port);
  if (host != null && port != null) { // AuthService not available.
    authServiceChannel =
        ManagedChannelBuilder.forTarget(host + ModelDBConstants.STRING_COLON + port)
            .usePlaintext()
            .build();

    this.serviceUserEmail = app.getServiceUserEmail();
    this.serviceUserDevKey = app.getServiceUserDevKey();
  } else {
    Status status =
        Status.newBuilder()
            .setCode(Code.UNAVAILABLE_VALUE)
            .setMessage("Host OR Port not found for contacting authentication service")
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }
}
 
Example #5
Source File: AuthServiceUtils.java    From modeldb with Apache License 2.0 6 votes vote down vote up
private UserInfo getUnsignedUser(boolean retry) {
  try (AuthServiceChannel authServiceChannel = new AuthServiceChannel()) {
    LOGGER.info(ModelDBMessages.AUTH_SERVICE_REQ_SENT_MSG);
    GetUser getUserRequest =
        GetUser.newBuilder().setUsername(ModelDBConstants.UNSIGNED_USER).build();
    // Get the user info by vertaId form the AuthService
    UserInfo userInfo = authServiceChannel.getUacServiceBlockingStub().getUser(getUserRequest);
    LOGGER.info(ModelDBMessages.AUTH_SERVICE_RES_RECEIVED_MSG);

    if (userInfo == null || userInfo.getVertaInfo() == null) {
      LOGGER.warn("unsigned user not found {}", userInfo);
      Status status =
          Status.newBuilder()
              .setCode(Code.NOT_FOUND_VALUE)
              .setMessage("Unsigned user not found with the provided metadata")
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    } else {
      return userInfo;
    }
  } catch (StatusRuntimeException ex) {
    return (UserInfo)
        ModelDBUtils.retryOrThrowException(
            ex, retry, (ModelDBUtils.RetryCallInterface<UserInfo>) this::getUnsignedUser);
  }
}
 
Example #6
Source File: AuthServiceUtils.java    From modeldb with Apache License 2.0 6 votes vote down vote up
private UserInfo getCurrentLoginUserInfo(boolean retry) {
  try (AuthServiceChannel authServiceChannel = new AuthServiceChannel()) {
    LOGGER.info(ModelDBMessages.AUTH_SERVICE_REQ_SENT_MSG);
    UserInfo userInfo =
        authServiceChannel.getUacServiceBlockingStub().getCurrentUser(Empty.newBuilder().build());
    LOGGER.info(ModelDBMessages.AUTH_SERVICE_RES_RECEIVED_MSG);

    if (userInfo == null || userInfo.getVertaInfo() == null) {
      LOGGER.info("user not found {}", userInfo);
      Status status =
          Status.newBuilder()
              .setCode(Code.NOT_FOUND_VALUE)
              .setMessage("Current user could not be resolved.")
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    } else {
      return userInfo;
    }
  } catch (StatusRuntimeException ex) {
    return (UserInfo)
        ModelDBUtils.retryOrThrowException(
            ex, retry, (ModelDBUtils.RetryCallInterface<UserInfo>) this::getCurrentLoginUserInfo);
  }
}
 
Example #7
Source File: DatasetServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/** Deletes dataset corresponding to the id. Required input parameter : id */
@Override
public void deleteDataset(
    DeleteDataset request, StreamObserver<DeleteDataset.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    // Request Parameter Validation
    if (request.getId().isEmpty()) {
      LOGGER.info(ModelDBMessages.DATASET_ID_NOT_FOUND_IN_REQUEST);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(ModelDBMessages.DATASET_ID_NOT_FOUND_IN_REQUEST)
              .addDetails(Any.pack(DeleteDataset.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    boolean deleteStatus = datasetDAO.deleteDatasets(Collections.singletonList(request.getId()));
    responseObserver.onNext(DeleteDataset.Response.newBuilder().setStatus(deleteStatus).build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(responseObserver, e, DeleteDataset.Response.getDefaultInstance());
  }
}
 
Example #8
Source File: ExperimentRunDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public List<Observation> getObservationByKey(String experimentRunId, String observationKey)
    throws InvalidProtocolBufferException {

  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    ExperimentRunEntity experimentRunEntityObj =
        session.get(ExperimentRunEntity.class, experimentRunId);
    if (experimentRunEntityObj == null) {
      LOGGER.info(ModelDBMessages.EXP_RUN_NOT_FOUND_ERROR_MSG);
      Status status =
          Status.newBuilder()
              .setCode(Code.NOT_FOUND_VALUE)
              .setMessage(ModelDBMessages.EXP_RUN_NOT_FOUND_ERROR_MSG)
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    ExperimentRun experimentRun = experimentRunEntityObj.getProtoObject();
    List<Observation> observationEntities = new ArrayList<>();
    for (Observation observation : experimentRun.getObservationsList()) {
      if ((observation.hasArtifact() && observation.getArtifact().getKey().equals(observationKey))
          || (observation.hasAttribute()
              && observation.getAttribute().getKey().equals(observationKey))) {
        observationEntities.add(observation);
      }
    }
    return observationEntities;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getObservationByKey(experimentRunId, observationKey);
    } else {
      throw ex;
    }
  }
}
 
Example #9
Source File: ModelDBUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/**
 * This is the common method for all to throw an exception to the UI
 *
 * @param errorMessage : error message throws by any service
 * @param errorCode : error code like Code.NOT_FOUND, Code.INTERNAL etc.
 * @param defaultResponse : Method reference to identify the error block
 */
public static void logAndThrowError(String errorMessage, int errorCode, Any defaultResponse) {
  LOGGER.warn(errorMessage);
  Status status =
      Status.newBuilder()
          .setCode(errorCode)
          .setMessage(errorMessage)
          .addDetails(defaultResponse)
          .build();
  throw StatusProto.toStatusRuntimeException(status);
}
 
Example #10
Source File: ProjectServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void deepCopyProject(
    DeepCopyProject request, StreamObserver<DeepCopyProject.Response> responseObserver) {
  QPSCountResource.inc();

  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    // Request Parameter Validation
    if (request.getId() == null) {
      String errorMessage = "Project ID not found in DeepCopyProject request";
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(GetProjectByName.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    // Get the user info from the Context
    UserInfo userInfo = authService.getCurrentLoginUserInfo();

    Project project = projectDAO.deepCopyProjectForUser(request.getId(), userInfo);

    responseObserver.onNext(DeepCopyProject.Response.newBuilder().setProject(project).build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(responseObserver, e, DeepCopyProject.Response.getDefaultInstance());
  }
}
 
Example #11
Source File: ProjectServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void getProjectReadme(
    GetProjectReadme request, StreamObserver<GetProjectReadme.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    // Request Parameter Validation
    if (request.getId().isEmpty()) {
      String errorMessage = "Project ID not found in GetProjectReadme request";
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(GetProjectReadme.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    // Validate if current user has access to the entity or not
    roleService.validateEntityUserWithUserInfo(
        ModelDBServiceResourceTypes.PROJECT, request.getId(), ModelDBServiceActions.READ);

    Project project = projectDAO.getProjectByID(request.getId());
    responseObserver.onNext(
        GetProjectReadme.Response.newBuilder().setReadmeText(project.getReadmeText()).build());
    responseObserver.onCompleted();
  } catch (Exception e) {
    ModelDBUtils.observeError(
        responseObserver, e, GetProjectReadme.Response.getDefaultInstance());
  }
}
 
Example #12
Source File: ProjectServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void getProjectShortName(
    GetProjectShortName request, StreamObserver<GetProjectShortName.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    // Request Parameter Validation
    if (request.getId().isEmpty()) {
      String errorMessage = "Project ID not found in GetProjectShortName request";
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(GetProjectShortName.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    // Validate if current user has access to the entity or not
    roleService.validateEntityUserWithUserInfo(
        ModelDBServiceResourceTypes.PROJECT, request.getId(), ModelDBServiceActions.READ);

    Project project = projectDAO.getProjectByID(request.getId());
    responseObserver.onNext(
        GetProjectShortName.Response.newBuilder().setShortName(project.getShortName()).build());
    responseObserver.onCompleted();
  } catch (Exception e) {
    ModelDBUtils.observeError(
        responseObserver, e, GetProjectShortName.Response.getDefaultInstance());
  }
}
 
Example #13
Source File: ExperimentDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Experiment addExperimentAttributes(String experimentId, List<KeyValue> attributes)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    ExperimentEntity experimentObj = session.get(ExperimentEntity.class, experimentId);
    if (experimentObj == null) {
      String errorMessage = ModelDBMessages.EXPERIMENT_NOT_FOUND_ERROR_MSG + experimentId;
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder().setCode(Code.NOT_FOUND_VALUE).setMessage(errorMessage).build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    experimentObj.setAttributeMapping(
        RdbmsUtils.convertAttributesFromAttributeEntityList(
            experimentObj, ModelDBConstants.ATTRIBUTES, attributes));
    long currentTimestamp = Calendar.getInstance().getTimeInMillis();
    experimentObj.setDate_updated(currentTimestamp);
    Transaction transaction = session.beginTransaction();
    session.saveOrUpdate(experimentObj);
    transaction.commit();
    LOGGER.debug("Experiment attributes added successfully");
    return experimentObj.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return addExperimentAttributes(experimentId, attributes);
    } else {
      throw ex;
    }
  }
}
 
Example #14
Source File: RemoteSpawnRunner.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static boolean retriableExecErrors(Exception e) {
  if (e instanceof BulkTransferException) {
    BulkTransferException bulkTransferException = (BulkTransferException) e;
    return bulkTransferException.onlyCausedByCacheNotFoundException();
  }
  if (!RemoteRetrierUtils.causedByStatus(e, Code.FAILED_PRECONDITION)) {
    return false;
  }
  com.google.rpc.Status status = StatusProto.fromThrowable(e);
  if (status == null || status.getDetailsCount() == 0) {
    return false;
  }
  for (Any details : status.getDetailsList()) {
    PreconditionFailure f;
    try {
      f = details.unpack(PreconditionFailure.class);
    } catch (InvalidProtocolBufferException protoEx) {
      return false;
    }
    if (f.getViolationsCount() == 0) {
      return false; // Generally shouldn't happen
    }
    for (Violation v : f.getViolationsList()) {
      if (!v.getType().equals(VIOLATION_TYPE_MISSING)) {
        return false;
      }
    }
  }
  return true; // if *all* > 0 violations have type MISSING
}
 
Example #15
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Project setProjectShortName(String projectId, String projectShortName, UserInfo userInfo)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query query = session.createQuery(GET_PROJECT_BY_SHORT_NAME_AND_OWNER_HQL);
    query.setParameter("projectShortName", projectShortName);
    query.setParameter("vertaId", authService.getVertaIdFromUserInfo(userInfo));
    ProjectEntity projectEntity = (ProjectEntity) query.uniqueResult();
    if (projectEntity != null) {
      Status status =
          Status.newBuilder()
              .setCode(Code.ALREADY_EXISTS_VALUE)
              .setMessage("Project already exist with given short name")
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    query = session.createQuery(GET_PROJECT_BY_ID_HQL);
    query.setParameter("id", projectId);
    projectEntity = (ProjectEntity) query.uniqueResult();
    projectEntity.setShort_name(projectShortName);
    projectEntity.setDate_updated(Calendar.getInstance().getTimeInMillis());
    Transaction transaction = session.beginTransaction();
    session.update(projectEntity);
    transaction.commit();
    LOGGER.debug(ModelDBMessages.GETTING_PROJECT_BY_ID_MSG_STR);
    return projectEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return setProjectShortName(projectId, projectShortName, userInfo);
    } else {
      throw ex;
    }
  }
}
 
Example #16
Source File: CommentServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/**
 * Convert AddComment request to Comment object. This method generates the Comment Id using UUID
 * and puts it in the Comment object.
 *
 * @param request : AddComment
 * @param userInfo : UserInfo
 * @return Comment comment
 */
private Comment getCommentFromRequest(AddComment request, UserInfo userInfo) {

  String errorMessage = null;
  if (request.getEntityId().isEmpty() && request.getMessage().isEmpty()) {
    errorMessage = "Entity ID and comment message not found in AddComment request";
  } else if (request.getEntityId().isEmpty()) {
    errorMessage = "Entity ID not found in AddComment request";
  } else if (request.getMessage().isEmpty()) {
    errorMessage = "Comment message not found in AddComment request";
  }

  if (errorMessage != null) {
    LOGGER.info(errorMessage);
    Status status =
        Status.newBuilder()
            .setCode(Code.INVALID_ARGUMENT_VALUE)
            .setMessage(errorMessage)
            .addDetails(Any.pack(AddComment.Response.getDefaultInstance()))
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }

  return Comment.newBuilder()
      .setId(UUID.randomUUID().toString())
      .setUserId(userInfo != null ? userInfo.getUserId() : "")
      .setVertaId(authService.getVertaIdFromUserInfo(userInfo))
      .setDateTime(Calendar.getInstance().getTimeInMillis())
      .setMessage(request.getMessage())
      .build();
}
 
Example #17
Source File: DatasetDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean deleteDatasets(List<String> datasetIds) {
  // Get self allowed resources id where user has delete permission
  List<String> allowedDatasetIds =
      roleService.getAccessibleResourceIdsByActions(
          ModelDBServiceResourceTypes.DATASET,
          ModelDBActionEnum.ModelDBServiceActions.DELETE,
          datasetIds);
  if (allowedDatasetIds.isEmpty()) {
    Status status =
        Status.newBuilder()
            .setCode(Code.PERMISSION_DENIED_VALUE)
            .setMessage("Access Denied for given dataset Ids : " + datasetIds)
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }

  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Transaction transaction = session.beginTransaction();
    Query deletedDatasetsQuery = session.createQuery(DELETED_STATUS_DATASET_QUERY_STRING);
    deletedDatasetsQuery.setParameter("deleted", true);
    deletedDatasetsQuery.setParameter("datasetIds", allowedDatasetIds);
    int updatedCount = deletedDatasetsQuery.executeUpdate();
    LOGGER.debug("Mark Datasets as deleted : {}, count : {}", allowedDatasetIds, updatedCount);
    transaction.commit();
    LOGGER.debug("Dataset deleted successfully");
    return true;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return deleteDatasets(datasetIds);
    } else {
      throw ex;
    }
  }
}
 
Example #18
Source File: ExperimentRunServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void logMetrics(LogMetrics request, StreamObserver<LogMetrics.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    String errorMessage = null;
    if (request.getId().isEmpty() && request.getMetricsList().isEmpty()) {
      errorMessage = "ExperimentRun ID and New Metrics not found in LogMetrics request";
    } else if (request.getId().isEmpty()) {
      errorMessage = "ExperimentRun ID not found in LogMetrics request";
    } else if (request.getMetricsList().isEmpty()) {
      errorMessage = "New Metrics not found in LogMetrics request";
    }

    if (errorMessage != null) {
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(LogMetrics.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    String projectId = experimentRunDAO.getProjectIdByExperimentRunId(request.getId());
    // Validate if current user has access to the entity or not
    roleService.validateEntityUserWithUserInfo(
        ModelDBServiceResourceTypes.PROJECT, projectId, ModelDBServiceActions.UPDATE);

    experimentRunDAO.logMetrics(request.getId(), request.getMetricsList());
    responseObserver.onNext(LogMetrics.Response.newBuilder().build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(responseObserver, e, LogMetrics.Response.getDefaultInstance());
  }
}
 
Example #19
Source File: ExperimentRunServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private void logAndThrowError(String errorMessage, int errorCode, Any defaultResponse) {
  LOGGER.warn(errorMessage);
  Status status =
      Status.newBuilder()
          .setCode(errorCode)
          .setMessage(errorMessage)
          .addDetails(defaultResponse)
          .build();
  throw StatusProto.toStatusRuntimeException(status);
}
 
Example #20
Source File: DatasetVersionServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void setDatasetVersionVisibility(
    SetDatasetVersionVisibilty request,
    StreamObserver<SetDatasetVersionVisibilty.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    // Request Parameter Validation
    if (request.getId().isEmpty()) {
      LOGGER.info(ModelDBMessages.DATASET_VERSION_ID_NOT_FOUND_IN_REQUEST);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(ModelDBMessages.DATASET_VERSION_ID_NOT_FOUND_IN_REQUEST)
              .addDetails(Any.pack(SetDatasetVersionVisibilty.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    DatasetVersion datasetVersion = datasetVersionDAO.getDatasetVersion(request.getId());
    // Validate if current user has access to the entity or not
    roleService.validateEntityUserWithUserInfo(
        ModelDBServiceResourceTypes.DATASET,
        datasetVersion.getDatasetId(),
        ModelDBServiceActions.READ);

    datasetVersion =
        datasetVersionDAO.setDatasetVersionVisibility(
            request.getId(), request.getDatasetVersionVisibility());
    responseObserver.onNext(
        SetDatasetVersionVisibilty.Response.newBuilder()
            .setDatasetVersion(datasetVersion)
            .build());
    responseObserver.onCompleted();
  } catch (Exception e) {
    ModelDBUtils.observeError(
        responseObserver, e, SetDatasetVersionVisibilty.Response.getDefaultInstance());
  }
}
 
Example #21
Source File: ModelDBUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
public static String checkEntityNameLength(String entityName) {
  if (entityName != null && entityName.length() > ModelDBConstants.NAME_LENGTH) {
    String errorMessage =
        "Entity name can not be more than " + ModelDBConstants.NAME_LENGTH + " characters";
    LOGGER.info(errorMessage);
    Status status =
        Status.newBuilder().setCode(Code.INVALID_ARGUMENT_VALUE).setMessage(errorMessage).build();
    throw StatusProto.toStatusRuntimeException(status);
  }
  return entityName;
}
 
Example #22
Source File: AdvancedServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void getHydratedProjectById(
    GetHydratedProjectById request,
    StreamObserver<GetHydratedProjectById.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    if (request.getId().isEmpty()) {
      String errorMessage = "Project ID not found in GetHydratedProjectById request";
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(GetHydratedProjectById.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    // Validate if current user has access to the entity or not
    roleService.validateEntityUserWithUserInfo(
        ModelDBServiceResourceTypes.PROJECT, request.getId(), ModelDBServiceActions.READ);

    Project project = projectDAO.getProjectByID(request.getId());
    responseObserver.onNext(
        GetHydratedProjectById.Response.newBuilder()
            .setHydratedProject(getHydratedProjects(Collections.singletonList(project)).get(0))
            .build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(
        responseObserver, e, GetHydratedProjectById.Response.getDefaultInstance());
  }
}
 
Example #23
Source File: MetadataDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public boolean addLabels(IdentificationType id, List<String> labels) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Transaction transaction = session.beginTransaction();
    for (String label : labels) {
      LabelsMappingEntity labelsMappingEntity = new LabelsMappingEntity(id, label);
      LabelsMappingEntity existingLabelsMappingEntity =
          session.get(LabelsMappingEntity.class, labelsMappingEntity.getId());
      if (existingLabelsMappingEntity == null) {
        session.save(labelsMappingEntity);
      } else {
        Status status =
            Status.newBuilder()
                .setCode(Code.ALREADY_EXISTS_VALUE)
                .setMessage("Label '" + label + "' already exists with given ID")
                .build();
        throw StatusProto.toStatusRuntimeException(status);
      }
    }
    transaction.commit();
    return true;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return addLabels(id, labels);
    } else {
      throw ex;
    }
  }
}
 
Example #24
Source File: AuthServiceUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public String getUsernameFromUserInfo(UserInfo userInfo) {
  if (userInfo != null
      && userInfo.getVertaInfo() != null
      && !userInfo.getVertaInfo().getUsername().isEmpty()) {
    return userInfo.getVertaInfo().getUsername();
  }
  Status status =
      Status.newBuilder()
          .setCode(Code.NOT_FOUND_VALUE)
          .setMessage("Username not found in userInfo")
          .build();
  throw StatusProto.toStatusRuntimeException(status);
}
 
Example #25
Source File: ExperimentRunServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void logAttribute(
    LogAttribute request, StreamObserver<LogAttribute.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    String errorMessage = null;
    if (request.getId().isEmpty() && request.getAttribute().getKey().isEmpty()) {
      errorMessage = "ExperimentRun ID and New Attribute not found in LogAttribute request";
    } else if (request.getId().isEmpty()) {
      errorMessage = "ExperimentRun ID not found in LogAttribute request";
    } else if (request.getAttribute().getKey().isEmpty()) {
      errorMessage = "Attribute not found in LogAttribute request";
    }

    if (errorMessage != null) {
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(LogAttribute.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    String projectId = experimentRunDAO.getProjectIdByExperimentRunId(request.getId());
    // Validate if current user has access to the entity or not
    roleService.validateEntityUserWithUserInfo(
        ModelDBServiceResourceTypes.PROJECT, projectId, ModelDBServiceActions.UPDATE);

    experimentRunDAO.logAttributes(
        request.getId(), Collections.singletonList(request.getAttribute()));
    responseObserver.onNext(LogAttribute.Response.newBuilder().build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(responseObserver, e, LogAttribute.Response.getDefaultInstance());
  }
}
 
Example #26
Source File: ExperimentRunDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public List<KeyValue> getExperimentRunAttributes(
    String experimentRunId, List<String> attributeKeyList, Boolean getAll)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    ExperimentRunEntity experimentRunObj =
        session.get(ExperimentRunEntity.class, experimentRunId);
    if (experimentRunObj == null) {
      String errorMessage = "Invalid ExperimentRun ID found";
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder().setCode(Code.NOT_FOUND_VALUE).setMessage(errorMessage).build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    if (getAll) {
      return experimentRunObj.getProtoObject().getAttributesList();
    } else {
      Query query = session.createQuery(GET_EXP_RUN_ATTRIBUTE_BY_KEYS_HQL);
      query.setParameterList("keys", attributeKeyList);
      query.setParameter(ModelDBConstants.EXPERIMENT_RUN_ID_STR, experimentRunId);
      query.setParameter(ModelDBConstants.FIELD_TYPE_STR, ModelDBConstants.ATTRIBUTES);
      List<AttributeEntity> attributeEntities = query.list();
      return RdbmsUtils.convertAttributeEntityListFromAttributes(attributeEntities);
    }
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getExperimentRunAttributes(experimentRunId, attributeKeyList, getAll);
    } else {
      throw ex;
    }
  }
}
 
Example #27
Source File: CommentDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Comment updateComment(String entityType, String entityId, Comment updatedComment) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    UserCommentEntity userCommentEntity =
        session.load(UserCommentEntity.class, updatedComment.getId());
    if (userCommentEntity == null) {
      Status status =
          Status.newBuilder()
              .setCode(Code.NOT_FOUND_VALUE)
              .setMessage("Comment does not exist in database")
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    userCommentEntity.setUser_id(updatedComment.getUserId());
    userCommentEntity.setOwner(updatedComment.getVertaId());
    userCommentEntity.setMessage(updatedComment.getMessage());
    userCommentEntity.setDate_time(updatedComment.getDateTime());
    Transaction transaction = session.beginTransaction();
    session.update(userCommentEntity);
    transaction.commit();
    LOGGER.debug("Comment updated successfully");
    return userCommentEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return updateComment(entityType, entityId, updatedComment);
    } else {
      throw ex;
    }
  }
}
 
Example #28
Source File: ExperimentDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public List<KeyValue> getExperimentAttributes(
    String experimentId, List<String> attributeKeyList, Boolean getAll)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    ExperimentEntity experimentObj = session.get(ExperimentEntity.class, experimentId);
    if (experimentObj == null) {
      String errorMessage = ModelDBMessages.EXPERIMENT_NOT_FOUND_ERROR_MSG + experimentId;
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder().setCode(Code.NOT_FOUND_VALUE).setMessage(errorMessage).build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    if (getAll) {
      return experimentObj.getProtoObject().getAttributesList();
    } else {
      Query query = session.createQuery(GET_KEY_VALUE_EXPERIMENT_QUERY);
      query.setParameterList("keys", attributeKeyList);
      query.setParameter(ModelDBConstants.EXPERIMENT_ID_STR, experimentId);
      query.setParameter(ModelDBConstants.FIELD_TYPE_STR, ModelDBConstants.ATTRIBUTES);
      List<AttributeEntity> attributeEntities = query.list();
      return RdbmsUtils.convertAttributeEntityListFromAttributes(attributeEntities);
    }
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getExperimentAttributes(experimentId, attributeKeyList, getAll);
    } else {
      throw ex;
    }
  }
}
 
Example #29
Source File: DatasetVersionServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/**
 * internal utility function to reduce lines of code
 *
 * @param errorMessage
 * @param errorCode
 * @param defaultResponse
 */
// TODO: check if this could be bumped up to utils so it can be used across files
private void logAndThrowError(String errorMessage, int errorCode, Any defaultResponse) {
  LOGGER.warn(errorMessage);
  Status status =
      Status.newBuilder()
          .setCode(errorCode)
          .setMessage(errorMessage)
          .addDetails(defaultResponse)
          .build();
  throw StatusProto.toStatusRuntimeException(status);
}
 
Example #30
Source File: DatasetVersionServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void getDatasetVersionTags(
    GetTags request, StreamObserver<GetTags.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    // Request Parameter Validation
    if (request.getId().isEmpty()) {
      LOGGER.info(ModelDBMessages.DATASET_VERSION_ID_NOT_FOUND_IN_REQUEST);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(ModelDBMessages.DATASET_VERSION_ID_NOT_FOUND_IN_REQUEST)
              .addDetails(Any.pack(GetTags.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    DatasetVersion datasetVersion = datasetVersionDAO.getDatasetVersion(request.getId());
    // Validate if current user has access to the entity or not
    roleService.validateEntityUserWithUserInfo(
        ModelDBServiceResourceTypes.DATASET,
        datasetVersion.getDatasetId(),
        ModelDBServiceActions.READ);

    List<String> tags = datasetVersionDAO.getDatasetVersionTags(request.getId());
    responseObserver.onNext(GetTags.Response.newBuilder().addAllTags(tags).build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(responseObserver, e, GetTags.Response.getDefaultInstance());
  }
}