World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#2251] feat(PyClient): Add Metalake APIs in Gravitino Python client (#2842)
Xun Liu1a74d6b4990d
diff --git a/clients/client-python/README.md b/clients/client-python/README.mdindex 2fdbeef492..7912065ec9 100644--- a/clients/client-python/README.md+++ b/clients/client-python/README.md@@ -14,7 +14,7 @@1. Install dependency```bash- pip install -e .[dev]+ pip install -e '.[dev]'```2. Run testsdiff --git a/clients/client-python/build.gradle.kts b/clients/client-python/build.gradle.ktsindex 00b376878d..21b89367a1 100644--- a/clients/client-python/build.gradle.kts+++ b/clients/client-python/build.gradle.kts@@ -21,6 +21,17 @@ fun deleteCacheDir(targetDir: String) {}}+fun gravitinoServer(operation: String) {+ val process = ProcessBuilder("${project.rootDir.path}/distribution/package/bin/gravitino.sh", operation).start()+ val exitCode = process.waitFor()+ if (exitCode == 0) {+ val currentContext = process.inputStream.bufferedReader().readText()+ println("Current docker context is: $currentContext")+ } else {+ println("checkOrbStackStatus Command execution failed with exit code $exitCode")+ }+}+tasks {val pipInstall by registering(VenvTask::class) {venvExec = "pip"@@ -35,12 +46,20 @@ tasks {}val integrationTest by registering(VenvTask::class) {+ doFirst() {+ gravitinoServer("start")+ }+dependsOn(pipInstall)venvExec = "python"- args = listOf("-m", "unittest", "tests/test_integration_gravitino_client.py")+ args = listOf("-m", "unittest")workingDir = projectDir.resolve(".")environment = mapOf("PROJECT_VERSION" to project.version,- "GRAVITINO_HOME" to project.rootDir.path + "/distribution/package")+ "GRADLE_START_GRAVITINO" to "True")++ doLast {+ gravitinoServer("stop")+ }}val build by registering(VenvTask::class) {diff --git a/clients/client-python/gravitino/client/__init__.py b/clients/client-python/gravitino/client/__init__.pynew file mode 100644index 0000000000..5779a3ad25--- /dev/null+++ b/clients/client-python/gravitino/client/__init__.py@@ -0,0 +1,4 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""diff --git a/clients/client-python/gravitino/client/gravitino_admin_client.py b/clients/client-python/gravitino/client/gravitino_admin_client.pynew file mode 100644index 0000000000..ba54f32bc3--- /dev/null+++ b/clients/client-python/gravitino/client/gravitino_admin_client.py@@ -0,0 +1,107 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+import logging+from typing import List, Dict++from gravitino.client.gravitino_client_base import GravitinoClientBase+from gravitino.client.gravitino_metalake import GravitinoMetalake+from gravitino.dto.dto_converters import DTOConverters+from gravitino.dto.requests.metalake_create_request import MetalakeCreateRequest+from gravitino.dto.requests.metalake_updates_request import MetalakeUpdatesRequest+from gravitino.dto.responses.drop_response import DropResponse+from gravitino.dto.responses.metalake_list_response import MetalakeListResponse+from gravitino.dto.responses.metalake_response import MetalakeResponse+from gravitino.meta_change import MetalakeChange+from gravitino.name_identifier import NameIdentifier++logger = logging.getLogger(__name__)+++class GravitinoAdminClient(GravitinoClientBase):+ """+ Gravitino Client for the administrator to interact with the Gravitino API, allowing the client to list, load, create, and alter Metalakes.+ Normal users should use {@link GravitinoClient} to connect with the Gravitino server.+ """++ def __init__(self, uri): # TODO: AuthDataProvider authDataProvider+ super().__init__(uri)++ def list_metalakes(self) -> List[GravitinoMetalake]:+ """+ Retrieves a list of Metalakes from the Gravitino API.+ Return:+ An array of GravitinoMetalake objects representing the Metalakes.+ """+ resp = self.rest_client.get(self.API_METALAKES_LIST_PATH)+ metalake_list_resp = MetalakeListResponse.from_json(resp.body, infer_missing=True)+ metalake_list_resp.validate()++ return [GravitinoMetalake.build(o, self.rest_client) for o in metalake_list_resp.metalakes]++ def create_metalake(self, ident: NameIdentifier, comment: str, properties: Dict[str, str]) -> GravitinoMetalake:+ """+ Creates a new Metalake using the Gravitino API.+ Args:+ ident: The identifier of the new Metalake.+ comment: The comment for the new Metalake.+ properties: The properties of the new Metalake.+ Return:+ A GravitinoMetalake instance representing the newly created Metalake.+ TODO: @throws MetalakeAlreadyExistsException If a Metalake with the specified identifier already exists.+ """+ NameIdentifier.check_metalake(ident)++ req = MetalakeCreateRequest(ident.name, comment, properties)+ req.validate()++ resp = self.rest_client.post(self.API_METALAKES_LIST_PATH, req)+ metalake_response = MetalakeResponse.from_json(resp.body, infer_missing=True)+ metalake_response.validate()++ return GravitinoMetalake.build(metalake_response.metalake, self.rest_client)++ def alter_metalake(self, ident: NameIdentifier, *changes: MetalakeChange) -> GravitinoMetalake:+ """+ Alters a specific Metalake using the Gravitino API.+ Args:+ ident: The identifier of the Metalake to be altered.+ changes: The changes to be applied to the Metalake.+ Return:+ A GravitinoMetalake instance representing the updated Metalake.+ TODO: @throws NoSuchMetalakeException If the specified Metalake does not exist.+ TODO: @throws IllegalArgumentException If the provided changes are invalid or not applicable.+ """+ NameIdentifier.check_metalake(ident)++ reqs = [DTOConverters.to_metalake_update_request(change) for change in changes]+ updates_request = MetalakeUpdatesRequest(reqs)+ updates_request.validate()++ resp = self.rest_client.put(self.API_METALAKES_IDENTIFIER_PATH + ident.name,+ updates_request) # , MetalakeResponse, {}, ErrorHandlers.metalake_error_handler())+ metalake_response = MetalakeResponse.from_json(resp.body)+ metalake_response.validate()++ return GravitinoMetalake.build(metalake_response.metalake, self.rest_client)++ def drop_metalake(self, ident: NameIdentifier) -> bool:+ """+ Drops a specific Metalake using the Gravitino API.+ Args:+ ident: The identifier of the Metalake to be dropped.+ Return:+ True if the Metalake was successfully dropped, false otherwise.+ """+ NameIdentifier.check_metalake(ident)++ try:+ resp = self.rest_client.delete(self.API_METALAKES_IDENTIFIER_PATH + ident.name)+ dropResponse = DropResponse.from_json(resp.body)++ return dropResponse.dropped()++ except Exception as e:+ logger.warning(f"Failed to drop metadata ", e)+ return Falsediff --git a/clients/client-python/gravitino/client/gravitino_client_base.py b/clients/client-python/gravitino/client/gravitino_client_base.pynew file mode 100644index 0000000000..a1f640709c--- /dev/null+++ b/clients/client-python/gravitino/client/gravitino_client_base.py@@ -0,0 +1,64 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+import logging++from gravitino.client.gravitino_metalake import GravitinoMetalake+from gravitino.client.gravitino_version import GravitinoVersion+from gravitino.dto.responses.metalake_response import MetalakeResponse+from gravitino.name_identifier import NameIdentifier+from gravitino.utils import HTTPClient++logger = logging.getLogger(__name__)++class GravitinoClientBase:+ """+ Base class for Gravitino Java client;+ It uses an underlying {@link RESTClient} to send HTTP requests and receive responses from the API.+ """+ rest_client: HTTPClient # The REST client to communicate with the REST server+ API_METALAKES_LIST_PATH = "api/metalakes" # The REST API path for listing metalakes+ API_METALAKES_IDENTIFIER_PATH = f"{API_METALAKES_LIST_PATH}/" # The REST API path prefix for load a specific metalake++ def __init__(self, uri: str):+ self.rest_client = HTTPClient(uri)++ def load_metalake(self, ident: NameIdentifier) -> GravitinoMetalake:+ """Loads a specific Metalake from the Gravitino API.++ Args:+ ident The identifier of the Metalake to be loaded.++ Return:+ A GravitinoMetalake instance representing the loaded Metalake.++ Raises:+ NoSuchMetalakeException If the specified Metalake does not exist.+ """+ NameIdentifier.check_metalake(ident)++ resp = self.rest_client.get(GravitinoClientBase.API_METALAKES_IDENTIFIER_PATH + ident.name)+ metalake_response = MetalakeResponse.from_json(resp.body)+ metalake_response.validate()++ return GravitinoMetalake.build(metalake_response.metalake, self.rest_client)++ def get_version(self) -> GravitinoVersion:+ """Retrieves the version of the Gravitino API.++ Return:+ A GravitinoVersion instance representing the version of the Gravitino API.+ """+ resp = self.rest_client.get("api/version")+ resp.validate()++ return GravitinoVersion(resp.get_version())++ def close(self):+ """Closes the GravitinoClient and releases any underlying resources."""+ if self.rest_client is not None:+ try:+ self.rest_client.close()+ except Exception as e:+ logger.warning("Failed to close the HTTP REST client", e)diff --git a/clients/client-python/gravitino/client/gravitino_metalake.py b/clients/client-python/gravitino/client/gravitino_metalake.pynew file mode 100644index 0000000000..aef7e565d2--- /dev/null+++ b/clients/client-python/gravitino/client/gravitino_metalake.py@@ -0,0 +1,28 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from typing import Dict++from gravitino.dto.audit_dto import AuditDTO+from gravitino.dto.metalake_dto import MetalakeDTO+from gravitino.utils import HTTPClient+++class GravitinoMetalake(MetalakeDTO):+ """+ Gravitino Metalake is the top-level metadata repository for users. It contains a list of catalogs+ as sub-level metadata collections. With {@link GravitinoMetalake}, users can list, create, load,+ alter and drop a catalog with specified identifier.+ """+ restClient: HTTPClient++ def __init__(self, name: str = None, comment: str = None, properties: Dict[str, str] = None, audit: AuditDTO = None,+ rest_client: HTTPClient = None):+ super().__init__(name=name, comment=comment, properties=properties, audit=audit)+ self.restClient = rest_client++ @classmethod+ def build(cls, metalake: MetalakeDTO = None, client: HTTPClient = None):+ return cls(name=metalake.name, comment=metalake.comment, properties=metalake.properties,+ audit=metalake.audit, rest_client=client)diff --git a/clients/client-python/gravitino/client/gravitino_version.py b/clients/client-python/gravitino/client/gravitino_version.pynew file mode 100644index 0000000000..9ae39c3e70--- /dev/null+++ b/clients/client-python/gravitino/client/gravitino_version.py@@ -0,0 +1,14 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from dataclasses import dataclass++from gravitino.dto.version_dto import VersionDTO+++@dataclass+class GravitinoVersion(VersionDTO):+ """Gravitino version information."""+ def __init__(self, versionDTO):+ super().__init__(versionDTO.version, versionDTO.compile_date, versionDTO.git_commit)diff --git a/clients/client-python/gravitino/dto/__init__.py b/clients/client-python/gravitino/dto/__init__.pynew file mode 100644index 0000000000..5779a3ad25--- /dev/null+++ b/clients/client-python/gravitino/dto/__init__.py@@ -0,0 +1,4 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""diff --git a/clients/client-python/gravitino/dto/audit_dto.py b/clients/client-python/gravitino/dto/audit_dto.pynew file mode 100644index 0000000000..b1d2a8ba94--- /dev/null+++ b/clients/client-python/gravitino/dto/audit_dto.py@@ -0,0 +1,33 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from dataclasses import dataclass, field+from typing import Optional++from dataclasses_json import DataClassJsonMixin, config+++@dataclass+class AuditDTO(DataClassJsonMixin):+ """Data transfer object representing audit information."""++ creator: Optional[str]+ """The creator of the audit."""++ create_time: Optional[str] = field(metadata=config(field_name='createTime')) # TODO: Can't deserialized datetime from JSON+ """The create time of the audit."""++ last_modifier: Optional[str] = field(metadata=config(field_name='lastModifier'))+ """The last modifier of the audit."""++ last_modified_time: Optional[str] = field(+ metadata=config(field_name='lastModifiedTime')) # TODO: Can't deserialized datetime from JSON+ """The last modified time of the audit."""++ def __init__(self, creator: str = None, create_time: str = None, last_modifier: str = None,+ last_modified_time: str = None):+ self.creator: str = creator+ self.create_time: str = create_time+ self.last_modifier: str = last_modifier+ self.last_modified_time: str = last_modified_timediff --git a/clients/client-python/gravitino/dto/dto_converters.py b/clients/client-python/gravitino/dto/dto_converters.pynew file mode 100644index 0000000000..67c745239e--- /dev/null+++ b/clients/client-python/gravitino/dto/dto_converters.py@@ -0,0 +1,24 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from gravitino.dto.requests.metalake_update_request import MetalakeUpdateRequest+from gravitino.meta_change import MetalakeChange+++class DTOConverters:+ """Utility class for converting between DTOs and domain objects."""++ @staticmethod+ def to_metalake_update_request(change: MetalakeChange) -> object:+ # Assuming MetalakeUpdateRequest has similar nested class structure for requests+ if isinstance(change, MetalakeChange.RenameMetalake):+ return MetalakeUpdateRequest.RenameMetalakeRequest(change.newName)+ elif isinstance(change, MetalakeChange.UpdateMetalakeComment):+ return MetalakeUpdateRequest.UpdateMetalakeCommentRequest(change.newComment)+ elif isinstance(change, MetalakeChange.SetProperty):+ return MetalakeUpdateRequest.SetMetalakePropertyRequest(change.property, change.value)+ elif isinstance(change, MetalakeChange.RemoveProperty):+ return MetalakeUpdateRequest.RemoveMetalakePropertyRequest(change.property)+ else:+ raise ValueError(f"Unknown change type: {type(change).__name__}")diff --git a/clients/client-python/gravitino/dto/metalake_dto.py b/clients/client-python/gravitino/dto/metalake_dto.pynew file mode 100644index 0000000000..e8c00b2834--- /dev/null+++ b/clients/client-python/gravitino/dto/metalake_dto.py@@ -0,0 +1,51 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from dataclasses import dataclass+from typing import Optional, Dict++from dataclasses_json import DataClassJsonMixin++from gravitino.dto.audit_dto import AuditDTO+++@dataclass+class MetalakeDTO(DataClassJsonMixin):+ """Represents a Metalake Data Transfer Object (DTO) that implements the Metalake interface."""++ name: str+ """The name of the Metalake DTO."""++ comment: Optional[str]+ """The comment of the Metalake DTO."""++ properties: Optional[Dict[str, str]] = None+ """The properties of the Metalake DTO."""++ audit: AuditDTO = None+ """The audit information of the Metalake DTO."""++ def __init__(self, name: str = None, comment: str = None, properties: Dict[str, str] = None,+ audit: AuditDTO = None):+ self.name = name+ self.comment = comment+ self.properties = properties+ self.audit = audit++ def equals(self, other):+ if self == other:+ return True+ if not isinstance(other, MetalakeDTO):+ return False+ return self.name == other.name and self.comment == other.comment and \+ self.property_equal(self.properties, other.properties) and self.audit == other.audit++ def property_equal(self, p1, p2):+ if p1 is None and p2 is None:+ return True+ if p1 is not None and not p1 and p2 is None:+ return True+ if p2 is not None and not p2 and p1 is None:+ return True+ return p1 == p2diff --git a/clients/client-python/gravitino/dto/requests/__init__.py b/clients/client-python/gravitino/dto/requests/__init__.pynew file mode 100644index 0000000000..5779a3ad25--- /dev/null+++ b/clients/client-python/gravitino/dto/requests/__init__.py@@ -0,0 +1,4 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""diff --git a/clients/client-python/gravitino/dto/requests/metalake_create_request.py b/clients/client-python/gravitino/dto/requests/metalake_create_request.pynew file mode 100644index 0000000000..080cdc8d0f--- /dev/null+++ b/clients/client-python/gravitino/dto/requests/metalake_create_request.py@@ -0,0 +1,28 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from typing import Optional, Dict++from dataclasses import dataclass++from dataclasses_json import DataClassJsonMixin+++@dataclass+class MetalakeCreateRequest(DataClassJsonMixin):+ """"Represents a request to create a Metalake."""+ name: str+ comment: Optional[str]+ properties: Optional[Dict[str, str]]++ def __init__(self, name: str = None, comment: str = None, properties: Dict[str, str] = None):+ super().__init__()++ self.name = name.strip() if name else None+ self.comment = comment.strip() if comment else None+ self.properties = properties++ def validate(self):+ if not self.name:+ raise ValueError("\"name\" field is required and cannot be empty")diff --git a/clients/client-python/gravitino/dto/requests/metalake_update_request.py b/clients/client-python/gravitino/dto/requests/metalake_update_request.pynew file mode 100644index 0000000000..d2e3c455b0--- /dev/null+++ b/clients/client-python/gravitino/dto/requests/metalake_update_request.py@@ -0,0 +1,128 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from abc import abstractmethod, ABC+from dataclasses import dataclass, field++from dataclasses_json import config, DataClassJsonMixin++from gravitino.meta_change import MetalakeChange+++@dataclass+class MetalakeUpdateRequestType(DataClassJsonMixin):+ type: str = field(metadata=config(field_name='@type'))++ def __init__(self, type: str):+ self.type = type+++class MetalakeUpdateRequest:+ """Represents an interface for Metalake update requests."""++ @abstractmethod+ def validate(self):+ pass++ @abstractmethod+ def metalake_change(self):+ pass++ @dataclass+ class RenameMetalakeRequest(MetalakeUpdateRequestType):+ """Represents a request to rename a Metalake."""++ newName: str = None+ """The new name for the Metalake."""++ def __init__(self, newName: str):+ super().__init__("rename")+ self.newName = newName++ def validate(self):+ """Validates the fields of the request.++ Raises:+ IllegalArgumentException if the new name is not set.+ """+ if not self.newName:+ raise ValueError('"newName" field is required and cannot be empty')++ def metalake_change(self):+ return MetalakeChange.rename(self.newName)++ @dataclass+ class UpdateMetalakeCommentRequest(MetalakeUpdateRequestType):+ """Represents a request to update the comment on a Metalake."""++ newComment: str = None+ """The new comment for the Metalake."""++ def __init__(self, newComment: str):+ super().__init__("updateComment")+ self.newComment = newComment++ def validate(self):+ """Validates the fields of the request.++ Raises:+ IllegalArgumentException if the new comment is not set.+ """+ if not self.newComment:+ raise ValueError('"newComment" field is required and cannot be empty')++ def metalake_change(self):+ return MetalakeChange.update_comment(self.newComment)++ @dataclass+ class SetMetalakePropertyRequest(MetalakeUpdateRequestType):+ """Represents a request to set a property on a Metalake."""++ property: str = None+ """The property to set."""++ value: str = None+ """The value of the property."""++ def __init__(self, property: str, value: str):+ super().__init__("setProperty")+ self.property = property+ self.value = value++ def validate(self):+ """Validates the fields of the request.++ Raises:+ IllegalArgumentException if property or value are not set.+ """+ if not self.property:+ raise ValueError('"property" field is required and cannot be empty')+ if not self.value:+ raise ValueError('"value" field is required and cannot be empty')++ def metalake_change(self):+ return MetalakeChange.set_property(self.property, self.value)++ @dataclass+ class RemoveMetalakePropertyRequest(MetalakeUpdateRequestType):+ """Represents a request to remove a property from a Metalake."""++ property: str = None+ """The property to remove."""++ def __init__(self, property: str):+ super().__init__("removeProperty")+ self.property = property++ def validate(self):+ """Validates the fields of the request.++ Raises:+ IllegalArgumentException if property is not set.+ """+ if not self.property:+ raise ValueError('"property" field is required and cannot be empty')++ def metalake_change(self):+ return MetalakeChange.remove_property(self.property)diff --git a/clients/client-python/gravitino/dto/requests/metalake_updates_request.py b/clients/client-python/gravitino/dto/requests/metalake_updates_request.pynew file mode 100644index 0000000000..11ef2e1e8f--- /dev/null+++ b/clients/client-python/gravitino/dto/requests/metalake_updates_request.py@@ -0,0 +1,34 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from dataclasses import dataclass+from typing import List++from dataclasses_json import DataClassJsonMixin++from gravitino.dto.requests.metalake_update_request import MetalakeUpdateRequest+++@dataclass+class MetalakeUpdatesRequest(DataClassJsonMixin):+ """Represents a request containing multiple Metalake updates."""++ updates: List[MetalakeUpdateRequest]++ def __init__(self, updates: List[MetalakeUpdateRequest]):+ """Constructor for MetalakeUpdatesRequest.++ Args:+ updates: The list of Metalake update requests.+ """+ self.updates = updates++ def validate(self):+ """Validates each request in the list.++ Raises:+ IllegalArgumentException if validation of any request fails.+ """+ for update in self.updates:+ update.validate()diff --git a/clients/client-python/gravitino/dto/responses/__init__.py b/clients/client-python/gravitino/dto/responses/__init__.pynew file mode 100644index 0000000000..5779a3ad25--- /dev/null+++ b/clients/client-python/gravitino/dto/responses/__init__.py@@ -0,0 +1,4 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""diff --git a/clients/client-python/gravitino/dto/responses/base_response.py b/clients/client-python/gravitino/dto/responses/base_response.pynew file mode 100644index 0000000000..dca8f36b8d--- /dev/null+++ b/clients/client-python/gravitino/dto/responses/base_response.py@@ -0,0 +1,25 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from dataclasses import dataclass++from dataclasses_json import DataClassJsonMixin+++@dataclass+class BaseResponse(DataClassJsonMixin):+ """Represents a base response for REST API calls."""++ code: int++ @classmethod+ def default(cls):+ return cls(code=0)++ def validate(self):+ """Validates the response code.+ TODO: @throws IllegalArgumentException if code value is negative.+ """+ if self.code < 0:+ raise ValueError("code must be >= 0")diff --git a/clients/client-python/gravitino/dto/responses/drop_response.py b/clients/client-python/gravitino/dto/responses/drop_response.pynew file mode 100644index 0000000000..de1a6908bf--- /dev/null+++ b/clients/client-python/gravitino/dto/responses/drop_response.py@@ -0,0 +1,14 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from gravitino.dto.responses.base_response import BaseResponse+++class DropResponse(BaseResponse):+ """Represents a response for a drop operation."""++ dropped : bool++ def dropped(self) -> bool:+ return self.droppeddiff --git a/clients/client-python/gravitino/dto/responses/metalake_list_response.py b/clients/client-python/gravitino/dto/responses/metalake_list_response.pynew file mode 100644index 0000000000..a7bfcddaa4--- /dev/null+++ b/clients/client-python/gravitino/dto/responses/metalake_list_response.py@@ -0,0 +1,28 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from dataclasses import dataclass+from typing import List++from gravitino.dto.metalake_dto import MetalakeDTO+from gravitino.dto.responses.base_response import BaseResponse+++@dataclass+class MetalakeListResponse(BaseResponse):+ """Represents a response containing a list of metalakes."""++ metalakes: List[MetalakeDTO]++ def validate(self):+ super().validate()++ if self.metalakes is None:+ raise ValueError("metalakes must be non-null")++ for metalake in self.metalakes:+ if not metalake.name:+ raise ValueError("metalake 'name' must not be null and empty")+ if not metalake.audit:+ raise ValueError("metalake 'audit' must not be null")diff --git a/clients/client-python/gravitino/dto/responses/metalake_response.py b/clients/client-python/gravitino/dto/responses/metalake_response.pynew file mode 100644index 0000000000..0c23804878--- /dev/null+++ b/clients/client-python/gravitino/dto/responses/metalake_response.py@@ -0,0 +1,26 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from dataclasses import dataclass+from typing import Optional++from gravitino.dto.metalake_dto import MetalakeDTO+from gravitino.dto.responses.base_response import BaseResponse+++@dataclass+class MetalakeResponse(BaseResponse):+ """Represents a response containing metalake information."""++ metalake: Optional[MetalakeDTO]++ def validate(self):+ """Validates the response data.+ TODO: @throws IllegalArgumentException if the metalake, name or audit information is not set.+ """+ super().validate()++ assert self.metalake is not None, "metalake must not be null"+ assert self.metalake.name is not None, "metalake 'name' must not be null and empty"+ assert self.metalake.audit is not None, "metalake 'audit' must not be null"diff --git a/clients/client-python/gravitino/dto/version_dto.py b/clients/client-python/gravitino/dto/version_dto.pynew file mode 100644index 0000000000..881d1563f2--- /dev/null+++ b/clients/client-python/gravitino/dto/version_dto.py@@ -0,0 +1,19 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from dataclasses import dataclass+++@dataclass+class VersionDTO:+ """Represents a Version Data Transfer Object (DTO)."""++ version: str = ""+ """The version of the software."""++ compileDate: str = ""+ """The date the software was compiled."""++ gitCommit: str = ""+ """The git commit of the software."""diff --git a/clients/client-python/gravitino/exceptions/__init__.py b/clients/client-python/gravitino/exceptions/__init__.pynew file mode 100644index 0000000000..5779a3ad25--- /dev/null+++ b/clients/client-python/gravitino/exceptions/__init__.py@@ -0,0 +1,4 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""diff --git a/clients/client-python/gravitino/exceptions/gravitino_runtime_exception.py b/clients/client-python/gravitino/exceptions/gravitino_runtime_exception.pynew file mode 100644index 0000000000..8469535d82--- /dev/null+++ b/clients/client-python/gravitino/exceptions/gravitino_runtime_exception.py@@ -0,0 +1,12 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+++class GravitinoRuntimeException(RuntimeError):+ """Base class for all Gravitino runtime exceptions."""++ def __init__(self, message, *args):+ super().__init__(message.format(*args))+diff --git a/clients/client-python/gravitino/exceptions/illegal_name_identifier_exception.py b/clients/client-python/gravitino/exceptions/illegal_name_identifier_exception.pynew file mode 100644index 0000000000..fff6e5715d--- /dev/null+++ b/clients/client-python/gravitino/exceptions/illegal_name_identifier_exception.py@@ -0,0 +1,14 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+++class IllegalNameIdentifierException(Exception):+ """An exception thrown when a name identifier is invalid."""++ def __init__(self, message=None, *args):+ if message:+ super().__init__(message.format(*args))+ else:+ super().__init__()diff --git a/clients/client-python/gravitino/exceptions/illegal_namespace_exception.py b/clients/client-python/gravitino/exceptions/illegal_namespace_exception.pynew file mode 100644index 0000000000..b3ec0c2699--- /dev/null+++ b/clients/client-python/gravitino/exceptions/illegal_namespace_exception.py@@ -0,0 +1,14 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+++class IllegalNamespaceException(Exception):+ """An exception thrown when a namespace is invalid."""++ def __init__(self, message=None, *args):+ if message:+ super().__init__(message.format(*args))+ else:+ super().__init__()diff --git a/clients/client-python/gravitino/exceptions/no_such_metalake_exception.py b/clients/client-python/gravitino/exceptions/no_such_metalake_exception.pynew file mode 100644index 0000000000..ed3dc53627--- /dev/null+++ b/clients/client-python/gravitino/exceptions/no_such_metalake_exception.py@@ -0,0 +1,12 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from gravitino.exceptions.not_found_exception import NotFoundException+++class NoSuchMetalakeException(NotFoundException):+ """An exception thrown when a metalake is not found."""++ def __init__(self, message, *args):+ super().__init__(message, *args)diff --git a/clients/client-python/gravitino/exceptions/not_found_exception.py b/clients/client-python/gravitino/exceptions/not_found_exception.pynew file mode 100644index 0000000000..87f3caca52--- /dev/null+++ b/clients/client-python/gravitino/exceptions/not_found_exception.py@@ -0,0 +1,12 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from gravitino.exceptions.gravitino_runtime_exception import GravitinoRuntimeException+++class NotFoundException(GravitinoRuntimeException):+ """Base class for all exceptions thrown when a resource is not found."""++ def __init__(self, message, *args):+ super().__init__(message, *args)diff --git a/clients/client-python/gravitino/meta_change.py b/clients/client-python/gravitino/meta_change.pynew file mode 100644index 0000000000..809c87427f--- /dev/null+++ b/clients/client-python/gravitino/meta_change.py@@ -0,0 +1,94 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from dataclasses import dataclass+++class MetalakeChange:+ """A metalake change is a change to a metalake. It can be used to rename a metalake, update the+ comment of a metalake, set a property and value pair for a metalake, or remove a property from a+ metalake.+ """++ @staticmethod+ def rename(new_name: str) -> 'MetalakeChange.RenameMetalake':+ """Creates a new metalake change to rename the metalake.++ Args:+ new_name: The New name of the metalake.++ Returns:+ The metalake change.+ """+ return MetalakeChange.RenameMetalake(new_name)++ @staticmethod+ def update_comment(new_comment: str) -> 'MetalakeChange.UpdateMetalakeComment':+ """Creates a new metalake change to update the metalake comment.++ Args:+ new_comment: The new comment of the metalake.++ Return:+ The metalake change.+ """+ return MetalakeChange.UpdateMetalakeComment(new_comment)++ @staticmethod+ def set_property(property: str, value: str) -> 'SetProperty':+ """Creates a new metalake change to set a property and value pair for the metalake.++ Args:+ property: The property name to set.+ value: The value to set the property to.++ Return:+ The metalake change.+ """+ return MetalakeChange.SetProperty(property, value)++ @staticmethod+ def remove_property(property: str) -> 'RemoveProperty':+ """Creates a new metalake change to remove a property from the metalake.++ Args:+ property: The property name to remove.++ Return:+ The metalake change.+ """+ return MetalakeChange.RemoveProperty(property)++ @dataclass(frozen=True)+ class RenameMetalake:+ """A metalake change to rename the metalake."""+ newName: str++ def __str__(self):+ return f"RENAMEMETALAKE {self.newName}"++ @dataclass(frozen=True)+ class UpdateMetalakeComment:+ """A metalake change to update the metalake comment"""+ newComment: str++ def __str__(self):+ return f"UPDATEMETALAKECOMMENT {self.newComment}"++ @dataclass(frozen=True)+ class SetProperty:+ """A metalake change to set a property and value pair for the metalake"""+ property: str+ value: str++ def __str__(self):+ return f"SETPROPERTY {self.property} {self.value}"++ @dataclass(frozen=True)+ class RemoveProperty:+ """A metalake change to remove a property from the metalake"""+ property: str++ def __str__(self):+ return f"REMOVEPROPERTY {self.property}"diff --git a/clients/client-python/gravitino/name_identifier.py b/clients/client-python/gravitino/name_identifier.pynew file mode 100644index 0000000000..8c0c93b606--- /dev/null+++ b/clients/client-python/gravitino/name_identifier.py@@ -0,0 +1,263 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from gravitino.exceptions.illegal_name_identifier_exception import IllegalNameIdentifierException+from gravitino.namespace import Namespace+++class NameIdentifier:+ """A name identifier is a sequence of names separated by dots. It's used to identify a metalake, a+ catalog, a schema or a table. For example, "metalake1" can represent a metalake,+ "metalake1.catalog1" can represent a catalog, "metalake1.catalog1.schema1" can represent a+ schema.+ """++ DOT = '.'++ def __init__(self, namespace: Namespace, name: str):+ self.namespace = namespace+ self.name = name++ def NameIdentifier(self, namespace, name):+ self.check(namespace is not None, "Cannot create a NameIdentifier with null namespace")+ self.check(name is not None and name != "", "Cannot create a NameIdentifier with null or empty name")++ self.namespace = namespace+ self.name = name++ @staticmethod+ def of(*names: str) -> 'NameIdentifier':+ """Create the NameIdentifier with the given {@link Namespace} and name.++ Args:+ namespace: The namespace of the identifier+ name: The name of the identifier++ Return:+ The created NameIdentifier+ """+ NameIdentifier.check(names is not None, "Cannot create a NameIdentifier with null names")+ NameIdentifier.check(len(names) != 0, "Cannot create a NameIdentifier with no names")++ return NameIdentifier(Namespace.of(names[:-1]), names[-1])++ @staticmethod+ def of_namespace(namespace: Namespace, name: str) -> 'NameIdentifier':+ """Create the metalake NameIdentifier with the given name.++ Args:+ metalake: The metalake name++ Return:+ The created metalake NameIdentifier+ """+ return NameIdentifier(namespace, name)++ @staticmethod+ def of_metalake(metalake: str) -> 'NameIdentifier':+ """Create the catalog NameIdentifier with the given metalake and catalog name.++ Args:+ metalake: The metalake name+ catalog: The catalog name++ Return:+ The created catalog NameIdentifier+ """+ return NameIdentifier.of(metalake)++ @staticmethod+ def of_catalog(metalake: str, catalog: str) -> 'NameIdentifier':+ return NameIdentifier.of(metalake, catalog)++ @staticmethod+ def of_schema(metalake: str, catalog: str, schema: str) -> 'NameIdentifier':+ """Create the schema NameIdentifier with the given metalake, catalog and schema name.++ Args:+ metalake: The metalake name+ catalog: The catalog name+ schema: The schema name++ Return:+ The created schema NameIdentifier+ """+ return NameIdentifier.of(metalake, catalog, schema)++ @staticmethod+ def of_table(metalake: str, catalog: str, schema: str, table: str) -> 'NameIdentifier':+ """Create the table NameIdentifier with the given metalake, catalog, schema and table name.++ Args:+ metalake: The metalake name+ catalog: The catalog name+ schema: The schema name+ table: The table name++ Return:+ The created table NameIdentifier+ """+ return NameIdentifier.of(metalake, catalog, schema, table)++ @staticmethod+ def of_fileset(metalake: str, catalog: str, schema: str, fileset: str) -> 'NameIdentifier':+ """Create the fileset NameIdentifier with the given metalake, catalog, schema and fileset name.++ Args:+ metalake: The metalake name+ catalog: The catalog name+ schema: The schema name+ fileset: The fileset name++ Return:+ The created fileset NameIdentifier+ """+ return NameIdentifier.of(metalake, catalog, schema, fileset)++ @staticmethod+ def of_topic(metalake: str, catalog: str, schema: str, topic: str) -> 'NameIdentifier':+ """Create the topic NameIdentifier with the given metalake, catalog, schema and topic+ name.++ Args:+ metalake: The metalake name+ catalog: The catalog name+ schema: The schema name+ topic: The topic name++ Return:+ The created topic NameIdentifier+ """+ return NameIdentifier.of(metalake, catalog, schema, topic)++ @staticmethod+ def check_metalake(ident: 'NameIdentifier') -> None:+ """Check the given NameIdentifier is a metalake identifier. Throw an {@link+ IllegalNameIdentifierException} if it's not.++ Args:+ ident: The metalake NameIdentifier to check.+ """+ NameIdentifier.check(ident is not None, "Metalake identifier must not be null")+ Namespace.check_metalake(ident.namespace)++ @staticmethod+ def check_catalog(ident: 'NameIdentifier') -> None:+ """Check the given NameIdentifier is a catalog identifier. Throw an {@link+ IllegalNameIdentifierException} if it's not.++ Args:+ ident: The catalog NameIdentifier to check.+ """+ NameIdentifier.check(ident is None, "Catalog identifier must not be null")+ Namespace.check_catalog(ident.namespace)++ @staticmethod+ def check_schema(ident: 'NameIdentifier') -> None:+ """Check the given NameIdentifier is a schema identifier. Throw an {@link+ IllegalNameIdentifierException} if it's not.++ Args:+ ident: The schema NameIdentifier to check.+ """+ NameIdentifier.check(ident is not None, "Schema identifier must not be null")+ Namespace.check_schema(ident.namespace)++ @staticmethod+ def check_table(ident: 'NameIdentifier') -> None:+ """Check the given NameIdentifier is a table identifier. Throw an {@link+ IllegalNameIdentifierException} if it's not.++ Args:+ ident: The table NameIdentifier to check.+ """+ NameIdentifier.check(ident is not None, "Table identifier must not be null")+ Namespace.check_table(ident.namespace)++ @staticmethod+ def check_fileset(ident: 'NameIdentifier') -> None:+ """Check the given NameIdentifier is a fileset identifier. Throw an {@link+ IllegalNameIdentifierException} if it's not.++ Args:+ ident: The fileset NameIdentifier to check.+ """+ NameIdentifier.check(ident is not None, "Fileset identifier must not be null")+ Namespace.check_fileset(ident.namespace)++ @staticmethod+ def check_topic(ident: 'NameIdentifier') -> None:+ """Check the given NameIdentifier is a topic identifier. Throw an {@link+ IllegalNameIdentifierException} if it's not.++ Args:+ ident: The topic NameIdentifier to check.+ """+ NameIdentifier.check(ident is not None, "Topic identifier must not be null")+ Namespace.check_topic(ident.namespace)++ @staticmethod+ def parse(identifier: str) -> 'NameIdentifier':+ """Create a NameIdentifier from the given identifier string.++ Args:+ identifier: The identifier string++ Return:+ The created NameIdentifier+ """+ NameIdentifier.check(identifier is not None and identifier != '', "Cannot parse a null or empty identifier")++ parts = identifier.split(NameIdentifier.DOT)+ return NameIdentifier.of(*parts)++ def has_namespace(self):+ """Check if the NameIdentifier has a namespace.++ Return:+ True if the NameIdentifier has a namespace, false otherwise.+ """+ return not self.namespace.is_empty()++ def get_namespace(self):+ """Get the namespace of the NameIdentifier.++ Return:+ The namespace of the NameIdentifier.+ """+ return self.namespace++ def get_name(self):+ """Get the name of the NameIdentifier.++ Return:+ The name of the NameIdentifier.+ """+ return self.name++ def __eq__(self, other):+ if not isinstance(other, NameIdentifier):+ return False+ return self.namespace == other.namespace and self.name == other.name++ def __hash__(self):+ return hash((self.namespace, self.name))++ def __str__(self):+ if self.has_namespace():+ return str(self.namespace) + "." + self.name+ else:+ return self.name++ @staticmethod+ def check(condition, message, *args):+ """Check the given condition is true. Throw an {@link IllegalNameIdentifierException} if it's not.++ Args:+ condition: The condition to check.+ message: The message to throw.+ args: The arguments to the message.+ """+ if not condition:+ raise IllegalNameIdentifierException(message.format(*args))diff --git a/clients/client-python/gravitino/namespace.py b/clients/client-python/gravitino/namespace.pynew file mode 100644index 0000000000..f3f0396bb1--- /dev/null+++ b/clients/client-python/gravitino/namespace.py@@ -0,0 +1,251 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+from typing import List+++class Namespace:+ """A namespace is a sequence of levels separated by dots. It's used to identify a metalake, a+ catalog or a schema. For example, "metalake1", "metalake1.catalog1" and+ "metalake1.catalog1.schema1" are all valid namespaces.+ """++ EMPTY = None+ DOT = "."++ def __init__(self, levels: List[str]):+ self.levels = levels++ @staticmethod+ def empty() -> 'Namespace':+ """Get an empty namespace.++ Returns:+ An empty namespace+ """+ return Namespace([])++ @staticmethod+ def of(*levels: str) -> 'Namespace':+ """Create a namespace with the given levels.++ Args:+ levels The levels of the namespace++ Returns:+ A namespace with the given levels+ """+ if levels is None:+ raise ValueError("Cannot create a namespace with null levels")+ if len(levels) == 0:+ return Namespace.empty()++ for level in levels:+ if level is None or level == "":+ raise ValueError("Cannot create a namespace with null or empty level")++ return Namespace(list(levels))++ @staticmethod+ def of_metalake() -> 'Namespace':+ """Create a namespace for metalake.++ Returns:+ A namespace for metalake+ """+ return Namespace.empty()++ @staticmethod+ def of_catalog(metalake: str) -> 'Namespace':+ """Create a namespace for catalog.++ Args:+ metalake: The metalake name++ Returns:+ A namespace for catalog+ """+ return Namespace.of(metalake)++ @staticmethod+ def of_schema(metalake: str, catalog: str) -> 'Namespace':+ """Create a namespace for schema.++ Args:+ metalake: The metalake name+ catalog: The catalog name++ Returns:+ A namespace for schema+ """+ return Namespace.of(metalake, catalog)++ @staticmethod+ def of_table(metalake: str, catalog: str, schema: str) -> 'Namespace':+ """Create a namespace for table.++ Args:+ metalake: The metalake name+ catalog: The catalog name+ schema: The schema name++ Return:+ A namespace for table+ """+ return Namespace.of(metalake, catalog, schema)++ @staticmethod+ def of_fileset(metalake: str, catalog: str, schema: str) -> 'Namespace':+ """Create a namespace for fileset.++ Args:+ metalake: The metalake name+ catalog: The catalog name+ schema: The schema name++ Return:+ A namespace for fileset+ """+ return Namespace.of(metalake, catalog, schema)++ @staticmethod+ def of_topic(metalake: str, catalog: str, schema: str) -> 'Namespace':+ """Create a namespace for topic.++ Args:+ metalake: The metalake name+ catalog: The catalog name+ schema: The schema name++ Return:+ A namespace for topic+ """+ return Namespace.of(metalake, catalog, schema)++ @staticmethod+ def check_metalake(namespace: 'Namespace') -> None:+ """Check if the given metalake namespace is legal, throw an IllegalNamespaceException if+ it's illegal.++ Args:+ namespace: The metalake namespace+ """+ if not namespace and not namespace.is_empty():+ raise ValueError(f"Metalake namespace must be non-null and empty, the input namespace is {namespace}")++ @staticmethod+ def check_catalog(namespace: 'Namespace') -> None:+ """Check if the given catalog namespace is legal, throw an IllegalNamespaceException if+ it's illegal.++ Args:+ namespace: The catalog namespace+ """+ if not namespace and namespace.length() != 1:+ raise ValueError(f"Catalog namespace must be non-null and have 1 level, the input namespace is {namespace}")++ @staticmethod+ def check_schema(namespace: 'Namespace') -> None:+ """Check if the given schema namespace is legal, throw an IllegalNamespaceException if+ it's illegal.++ Args:+ namespace: The schema namespace+ """+ if not namespace and namespace.length() != 2:+ raise ValueError(f"Schema namespace must be non-null and have 2 levels, the input namespace is {namespace}")++ @staticmethod+ def check_table(namespace: 'Namespace') -> None:+ """Check if the given table namespace is legal, throw an IllegalNamespaceException if it's+ illegal.++ Args:+ namespace: The table namespace+ """+ if not namespace and namespace.length() != 3:+ raise ValueError(f"Table namespace must be non-null and have 3 levels, the input namespace is {namespace}")++ @staticmethod+ def check_fileset(namespace: 'Namespace') -> None:+ """Check if the given fileset namespace is legal, throw an IllegalNamespaceException if+ it's illegal.++ Args:+ namespace: The fileset namespace+ """+ if not namespace and namespace.length() != 3:+ raise ValueError(+ f"Fileset namespace must be non-null and have 3 levels, the input namespace is {namespace}")++ @staticmethod+ def check_topic(namespace: 'Namespace') -> None:+ """Check if the given topic namespace is legal, throw an IllegalNamespaceException if it's+ illegal.++ Args:+ namespace: The topic namespace+ """+ if not namespace and namespace.length() != 3:+ raise ValueError(f"Topic namespace must be non-null and have 3 levels, the input namespace is {namespace}")++ def levels(self) -> List[str]:+ """Get the levels of the namespace.++ Return:+ The levels of the namespace+ """+ return self.levels++ def level(self, pos: int) -> str:+ """Get the level at the given position.++ Args:+ pos: The position of the level++ Return:+ The level at the given position+ """+ if pos < 0 or pos >= len(self.levels):+ raise ValueError("Invalid level position")+ return self.levels[pos]++ def length(self) -> int:+ """Get the length of the namespace.++ Return:+ The length of the namespace.+ """+ return len(self.levels)++ def is_empty(self) -> bool:+ """Check if the namespace is empty.++ Return:+ True if the namespace is empty, false otherwise.+ """+ return len(self.levels) == 0++ def __eq__(self, other: 'Namespace') -> bool:+ if not isinstance(other, Namespace):+ return False+ return self.levels == other.levels++ def __hash__(self) -> int:+ return hash(tuple(self.levels))++ def __str__(self) -> str:+ return Namespace.DOT.join(self.levels)++ @staticmethod+ def check(expression: bool, message: str, *args) -> None:+ """Check the given condition is true. Throw an IllegalNamespaceException if it's not.++ Args:+ expression: The expression to check.+ message: The message to throw.+ args: The arguments to the message.+ """+ if not expression:+ raise ValueError(message.format(*args))diff --git a/clients/client-python/gravitino/utils/http_client.py b/clients/client-python/gravitino/utils/http_client.pyindex 870d2c2bc3..998f82b8e3 100644--- a/clients/client-python/gravitino/utils/http_client.py+++ b/clients/client-python/gravitino/utils/http_client.py@@ -2,7 +2,7 @@Copyright 2024 Datastrato Pvt Ltd.This software is licensed under the Apache License version 2."""-+import loggingfrom urllib.request import Request, build_openerfrom urllib.parse import urlencodefrom urllib.error import HTTPError@@ -12,6 +12,7 @@ from gravitino.typing import JSON_rofrom gravitino.utils.exceptions import handle_errorfrom gravitino.constants import TIMEOUT+logger = logging.getLogger(__name__)class Response:def __init__(self, response):@@ -20,6 +21,11 @@ class Response:self._headers = response.info()self._url = response.url+ logging.basicConfig(level=logging.DEBUG)+ console_handler = logging.StreamHandler()+ console_handler.setLevel(logging.DEBUG)+ logger.addHandler(console_handler)+@propertydef status_code(self):return self._status_code@@ -102,8 +108,12 @@ class HTTPClient:if headers:self._update_headers(headers)+ else:+ headers = {'Content-Type': 'application/json', 'Accept': 'application/vnd.gravitino.v1+json'}+ self._update_headers(headers)+if json:- request_data = _json.dumps(json).encode("utf-8")+ request_data = json.to_json().encode("utf-8")opener = build_opener()request = Request(self._build_url(endpoint, params), data=request_data)@@ -128,6 +138,9 @@ class HTTPClient:def put(self, endpoint, json=None, **kwargs):return self._request("put", endpoint, json=json, **kwargs)+ def close(self):+ self._request("close")+def unpack(path: str):def decorator(func):diff --git a/clients/client-python/requirements-dev.txt b/clients/client-python/requirements-dev.txtindex b0cc392c34..16f503518f 100644--- a/clients/client-python/requirements-dev.txt+++ b/clients/client-python/requirements-dev.txt@@ -1,3 +1,4 @@# Copyright 2024 Datastrato Pvt Ltd.# This software is licensed under the Apache License version 2.-requests\ No newline at end of file+requests+dataclasses-json\ No newline at end of filediff --git a/clients/client-python/tests/integration_test_env.py b/clients/client-python/tests/integration_test_env.pyindex 5670aa5ffa..7036b6f047 100644--- a/clients/client-python/tests/integration_test_env.py+++ b/clients/client-python/tests/integration_test_env.py@@ -9,13 +9,10 @@ import subprocessimport timeimport requests-from gravitino import GravitinoClient-from gravitino.constants import TIMEOUT-logger = logging.getLogger(__name__)-def check_gravitino_server_status():+def get_gravitino_server_version():try:response = requests.get("http://localhost:8090/api/version")response.raise_for_status() # raise an exception for bad status codes@@ -26,6 +23,20 @@ def check_gravitino_server_status():return False+def check_gravitino_server_status():+ gravitino_server_running = False+ for i in range(5):+ logger.info("Monitoring Gravitino server status. Attempt %s", i + 1)+ if get_gravitino_server_version():+ logger.debug("Gravitino Server is running")+ gravitino_server_running = True+ break+ else:+ logger.debug("Gravitino Server is not running")+ time.sleep(1)+ return gravitino_server_running++def _init_logging():logging.basicConfig(level=logging.DEBUG)console_handler = logging.StreamHandler()@@ -35,52 +46,50 @@ def _init_logging():# Provide real test environment for the Gravitino Serverclass IntegrationTestEnv(unittest.TestCase):- GravitinoHome = None+ gravitino_startup_script = None@classmethoddef setUpClass(cls):_init_logging()- logger.info("Starting integration test environment...")- cls.GravitinoHome = os.environ.get('GRAVITINO_HOME')- if cls.GravitinoHome is None:- logger.warning('WARN: Currently, Python Client integration test only runs in the Gradle build environment, '- 'Please execute `./gradlew :clients:client-python:test` in the gravitino project root directory.')++ if os.environ.get('GRADLE_START_GRAVITINO') is not None:+ logger.info('Manual start gravitino server [%s].', check_gravitino_server_status())+ return++ current_path = os.getcwd()+ cls.gravitino_startup_script = os.path.join(current_path, '../../../distribution/package/bin/gravitino.sh')+ if not os.path.exists(cls.gravitino_startup_script):+ logger.error("Can't find Gravitino startup script: %s, "+ "Please execute `./gradlew compileDistribution -x test` in the gravitino project root "+ "directory.", cls.gravitino_startup_script)quit(0)+ logger.info("Starting integration test environment...")+# Start Gravitino Server- result = subprocess.run([cls.GravitinoHome + '/bin/gravitino.sh', 'start'], capture_output=True, text=True)+ result = subprocess.run([cls.gravitino_startup_script, 'start'], capture_output=True, text=True)if result.stdout:logger.info("stdout: %s", result.stdout)if result.stderr:logger.info("stderr: %s", result.stderr)- gravitinoServerRunning = False- for i in range(5):- logger.info("Monitoring Gravitino server status. Attempt %s", i + 1)- if check_gravitino_server_status():- logger.debug("Gravitino Server is running")- gravitinoServerRunning = True- break- else:- logger.debug("Gravitino Server is not running")- time.sleep(1)-- if not gravitinoServerRunning:+ if not check_gravitino_server_status():logger.error("ERROR: Can't start Gravitino server!")quit(0)- cls.client = GravitinoClient("http://localhost:8090", timeout=TIMEOUT)-@classmethoddef tearDownClass(cls):+ if os.environ.get('GRADLE_START_GRAVITINO') is not None:+ return+logger.info("Stop integration test environment...")- result = subprocess.run([cls.GravitinoHome + '/bin/gravitino.sh', 'stop'], capture_output=True, text=True)+ result = subprocess.run([cls.gravitino_startup_script, 'stop'], capture_output=True, text=True)if result.stdout:logger.info("stdout: %s", result.stdout)if result.stderr:logger.info("stderr: %s", result.stderr)- gravitinoServerRunning = True+ gravitino_server_running = Truefor i in range(5):logger.debug("Monitoring Gravitino server status. Attempt %s", i + 1)if check_gravitino_server_status():@@ -88,14 +97,8 @@ class IntegrationTestEnv(unittest.TestCase):time.sleep(1)else:logger.debug("Stop Gravitino server successes!")- gravitinoServerRunning = False+ gravitino_server_running = Falsebreak- if gravitinoServerRunning:- logger.error("ERROR: Can't stop Gravitino server!")-- # Determine whether to run from Gradle base on environment variables- # integrated test environment (ITE)- @staticmethod- def not_in_ITE():- return os.environ.get('GRAVITINO_HOME') is None and os.environ.get('PROJECT_VERSION') is None+ if gravitino_server_running:+ logger.error("Can't stop Gravitino server!")diff --git a/clients/client-python/tests/test_gravitino_admin_client.py b/clients/client-python/tests/test_gravitino_admin_client.pynew file mode 100644index 0000000000..0490e16ab5--- /dev/null+++ b/clients/client-python/tests/test_gravitino_admin_client.py@@ -0,0 +1,116 @@+"""+Copyright 2024 Datastrato Pvt Ltd.+This software is licensed under the Apache License version 2.+"""+import gravitino+from gravitino.client.gravitino_admin_client import GravitinoAdminClient+from gravitino.dto.dto_converters import DTOConverters+from gravitino.dto.requests.metalake_updates_request import MetalakeUpdatesRequest+from gravitino.dto.responses.metalake_response import MetalakeResponse+from gravitino.meta_change import MetalakeChange+from gravitino.name_identifier import NameIdentifier+from gravitino.utils.exceptions import NotFoundError+from tests.integration_test_env import IntegrationTestEnv+++class TestGravitinoClient(IntegrationTestEnv):+ def setUp(self):+ self._gravitino_admin_client = GravitinoAdminClient(uri="http://localhost:8090")++ def test_create_metalake(self):+ metalake_name = "metalake00"+ try:+ self.create_metalake(metalake_name)+ except gravitino.utils.exceptions.HTTPError:+ self.drop_metalake(metalake_name)++ # Clean test data+ self.drop_metalake(metalake_name)++ def create_metalake(self, metalake_name):+ comment = "This is a sample comment"+ ident = NameIdentifier.of(metalake_name)+ properties = {"key1": "value1", "key2": "value2"}++ gravitinoMetalake = self._gravitino_admin_client.create_metalake(ident, comment, properties)++ self.assertEqual(gravitinoMetalake.name, metalake_name)+ self.assertEqual(gravitinoMetalake.comment, comment)+ self.assertEqual(gravitinoMetalake.properties.get("key1"), "value1")+ self.assertEqual(gravitinoMetalake.audit.creator, "anonymous")++ def test_alter_metalake(self):+ metalake_name = "metalake02"+ metalake_new_name = metalake_name + "_new"+ try:+ self.create_metalake(metalake_name)+ except gravitino.utils.exceptions.HTTPError:+ self.drop_metalake(metalake_name)++ changes = (+ MetalakeChange.rename(metalake_new_name),+ MetalakeChange.update_comment("new metalake comment"),+ )++ metalake = self._gravitino_admin_client.alter_metalake(NameIdentifier.of(metalake_name), *changes)+ self.assertEqual(metalake_new_name, metalake.name)+ self.assertEqual("new metalake comment", metalake.comment)+ self.assertEqual("anonymous", metalake.audit.creator) # Assuming a constant or similar attribute++ # Reload metadata via new name to check if the changes are applied+ new_metalake = self._gravitino_admin_client.load_metalake(NameIdentifier.of(metalake_new_name))+ self.assertEqual(metalake_new_name, new_metalake.name)+ self.assertEqual("new metalake comment", new_metalake.comment)++ # Old name does not exist+ old = NameIdentifier.of(metalake_name)+ with self.assertRaises(NotFoundError): # TODO: NoSuchMetalakeException+ self._gravitino_admin_client.load_metalake(old)++ # Clean test data+ self.drop_metalake(metalake_name)+ self.drop_metalake(metalake_new_name)++ def drop_metalake(self, metalake_name):+ ident = NameIdentifier.of(metalake_name)+ self.assertTrue(self._gravitino_admin_client.drop_metalake(ident))++ def test_drop_metalake(self):+ metalake_name = "metalake03"+ try:+ self.create_metalake(metalake_name)+ except gravitino.utils.exceptions.HTTPError:+ self.drop_metalake(metalake_name)++ self.drop_metalake(metalake_name)++ def test_metalake_update_request_to_json(self):+ changes = (+ MetalakeChange.rename("my_metalake_new"),+ MetalakeChange.update_comment("new metalake comment"),+ )+ reqs = [DTOConverters.to_metalake_update_request(change) for change in changes]+ updates_request = MetalakeUpdatesRequest(reqs)+ valid_json = (f'{{"updates": [{{"@type": "rename", "newName": "my_metalake_new"}}, '+ f'{{"@type": "updateComment", "newComment": "new metalake comment"}}]}}')+ self.assertEqual(updates_request.to_json(), valid_json)++ def test_from_json_metalake_response(self):+ str = (b'{"code":0,"metalake":{"name":"example_name18","comment":"This is a sample comment",'+ b'"properties":{"key1":"value1","key2":"value2"},'+ b'"audit":{"creator":"anonymous","createTime":"2024-04-05T10:10:35.218Z"}}}')+ metalake_response = MetalakeResponse.from_json(str, infer_missing=True)+ self.assertEqual(metalake_response.code, 0)+ self.assertIsNotNone(metalake_response.metalake)+ self.assertEqual(metalake_response.metalake.name, "example_name18")+ self.assertEqual(metalake_response.metalake.audit.creator, "anonymous")++ def test_list_metalakes(self):+ metalake_name = "metalake05"+ self.create_metalake(metalake_name)+ object = self._gravitino_admin_client.list_metalakes()+ assert len(object) > 0++ # Clean test data+ self.drop_metalake(metalake_name)+diff --git a/clients/client-python/tests/test_integration_gravitino_client.py b/clients/client-python/tests/test_integration_gravitino_client.pydeleted file mode 100644index 1c0830b727..0000000000--- a/clients/client-python/tests/test_integration_gravitino_client.py+++ /dev/null@@ -1,23 +0,0 @@-"""-Copyright 2024 Datastrato Pvt Ltd.-This software is licensed under the Apache License version 2.-"""--import os-import unittest-from tests.integration_test_env import IntegrationTestEnv--[email protected](IntegrationTestEnv.not_in_ITE(),- "Currently, Python Client integration test only runs in the Gradle build environment")-class IntegrationTestGravitinoClient(IntegrationTestEnv):- def test_version(self):- versionDTO = self.client.version- assert versionDTO['version'] is not None-- # Get project version from environment (Setting by Gradle build script `build.gradle.kts`),- # But if you directly execute this test in IDEA, maybe can not get it.- projectVersion = os.environ.get('PROJECT_VERSION', '')-- if projectVersion != '':- assert versionDTO['version'] == projectVersion