session.py 6.54 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Internal GPU Memory Service client session."""

from __future__ import annotations

import logging
from typing import List, Optional, Tuple

from gpu_memory_service.client.rpc import _GMSRPCTransport
from gpu_memory_service.common.protocol.messages import (
    AllocateRequest,
    AllocateResponse,
    CommitRequest,
    CommitResponse,
    ExportAllocationRequest,
    ExportAllocationResponse,
    FreeAllocationRequest,
    FreeAllocationResponse,
    GetAllocationRequest,
    GetAllocationResponse,
    GetAllocationStateRequest,
    GetAllocationStateResponse,
    GetLockStateRequest,
    GetLockStateResponse,
    GetStateHashRequest,
    GetStateHashResponse,
    HandshakeResponse,
    ListAllocationsRequest,
    ListAllocationsResponse,
    MetadataDeleteRequest,
    MetadataDeleteResponse,
    MetadataGetRequest,
    MetadataGetResponse,
    MetadataListRequest,
    MetadataListResponse,
    MetadataPutRequest,
    MetadataPutResponse,
)
from gpu_memory_service.common.types import GrantedLockType, RequestedLockType

logger = logging.getLogger(__name__)


class _GMSClientSession:
    """Connected GMS client session with granted lock state."""

    def __init__(
        self,
        socket_path: str,
        lock_type: RequestedLockType,
        timeout_ms: Optional[int],
    ):
        self._requested_lock_type = lock_type
        self._transport = _GMSRPCTransport(socket_path)
        self._transport.connect()
        try:
            response = self._transport.handshake(lock_type, timeout_ms)
        except Exception:
            try:
                self._transport.close()
            except Exception:
                pass
            raise
        self._initialize_from_handshake(response)

    def _initialize_from_handshake(self, response: HandshakeResponse) -> None:
        if not response.success:
            self._transport.close()
            raise TimeoutError("Timeout waiting for lock")

        self._committed = response.committed
        if response.granted_lock_type is None:
            self._transport.close()
            raise RuntimeError("HandshakeResponse omitted granted_lock_type")
        self._granted_lock_type = response.granted_lock_type

        logger.info(
            "Connected with %s lock (granted=%s), committed=%s",
            self._requested_lock_type.value,
            self._granted_lock_type.value,
            self._committed,
        )

    @property
    def committed(self) -> bool:
        return self._committed

    @property
    def lock_type(self) -> GrantedLockType:
        return self._granted_lock_type

    @property
    def is_connected(self) -> bool:
        return self._transport.is_connected

    def get_lock_state(self) -> GetLockStateResponse:
        return self._transport.request(GetLockStateRequest(), GetLockStateResponse)

    def get_allocation_state(self) -> GetAllocationStateResponse:
        return self._transport.request(
            GetAllocationStateRequest(), GetAllocationStateResponse
        )

    def is_ready(self) -> bool:
        return self.committed

    def commit(self) -> bool:
        response = self._transport.request(CommitRequest(), CommitResponse)
        if not response.success:
            raise RuntimeError("GMS commit returned failure")
        self._committed = True
        try:
            self.close()
        except ConnectionError as exc:
            logger.warning("Commit succeeded but closing transport failed: %s", exc)
        logger.info("Committed weights and released RW connection")
        return True

    def allocate_info(self, size: int, tag: str = "default") -> AllocateResponse:
        return self._transport.request(
            AllocateRequest(size=size, tag=tag), AllocateResponse
        )

    def allocate(self, size: int, tag: str = "default") -> Tuple[str, int]:
        response = self.allocate_info(size=size, tag=tag)
        return response.allocation_id, response.aligned_size

    def export(self, allocation_id: str) -> int:
        response, fd = self._transport.request_with_fd(
            ExportAllocationRequest(allocation_id=allocation_id),
            ExportAllocationResponse,
        )
        if fd < 0:
            raise RuntimeError(
                f"GMS export returned no FD for allocation_id={allocation_id}"
            )
        return fd

    def get_allocation(self, allocation_id: str) -> GetAllocationResponse:
        return self._transport.request(
            GetAllocationRequest(allocation_id=allocation_id),
            GetAllocationResponse,
        )

    def list_allocations(
        self, tag: Optional[str] = None
    ) -> List[GetAllocationResponse]:
        return self._transport.request(
            ListAllocationsRequest(tag=tag),
            ListAllocationsResponse,
        ).allocations

    def free(self, allocation_id: str) -> bool:
        return self._transport.request(
            FreeAllocationRequest(allocation_id=allocation_id),
            FreeAllocationResponse,
        ).success

    def metadata_put(
        self, key: str, allocation_id: str, offset_bytes: int, value: bytes
    ) -> bool:
        return self._transport.request(
            MetadataPutRequest(
                key=key,
                allocation_id=allocation_id,
                offset_bytes=offset_bytes,
                value=value,
            ),
            MetadataPutResponse,
        ).success

    def metadata_get(self, key: str) -> Optional[tuple[str, int, bytes]]:
        response = self._transport.request(
            MetadataGetRequest(key=key), MetadataGetResponse
        )
        if not response.found:
            return None
        return response.allocation_id, response.offset_bytes, response.value

    def metadata_delete(self, key: str) -> bool:
        return self._transport.request(
            MetadataDeleteRequest(key=key), MetadataDeleteResponse
        ).deleted

    def metadata_list(self, prefix: str = "") -> List[str]:
        return self._transport.request(
            MetadataListRequest(prefix=prefix), MetadataListResponse
        ).keys

    def get_memory_layout_hash(self) -> str:
        return self._transport.request(
            GetStateHashRequest(), GetStateHashResponse
        ).memory_layout_hash

    def close(self) -> None:
        self._transport.close()
        logger.info("Closed %s connection", self._granted_lock_type.value)

    def __enter__(self) -> "_GMSClientSession":
        return self

    def __exit__(self, exc_type, exc_val, exc_tb) -> None:
        self.close()