Coverage for /builds/BuildGrid/buildgrid/buildgrid/server/client/logstream.py: 46.67%

30 statements  

« prev     ^ index     » next       coverage.py v7.4.1, created at 2024-10-04 17:48 +0000

1# Copyright (C) 2020 Bloomberg LP 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# <http://www.apache.org/licenses/LICENSE-2.0> 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14 

15 

16from contextlib import contextmanager 

17from typing import Iterator, Optional 

18 

19import grpc 

20from grpc import RpcError 

21 

22from buildgrid._protos.build.bazel.remote.logstream.v1.remote_logstream_pb2 import CreateLogStreamRequest, LogStream 

23from buildgrid._protos.build.bazel.remote.logstream.v1.remote_logstream_pb2_grpc import LogStreamServiceStub 

24from buildgrid.server.logging import buildgrid_logger 

25 

26LOGGER = buildgrid_logger(__name__) 

27 

28 

29class LogStreamClient: 

30 def __init__(self, channel: grpc.Channel, instance_name: str = "") -> None: 

31 self._channel = channel 

32 self._instance_name = instance_name 

33 self._logstream_stub: Optional[LogStreamServiceStub] = LogStreamServiceStub(self._channel) 

34 

35 def create(self, parent: str) -> LogStream: 

36 assert self._logstream_stub, "LogStreamClient used after close" 

37 

38 parent = f"{self._instance_name}/{parent}" 

39 request = CreateLogStreamRequest(parent=parent) 

40 try: 

41 return self._logstream_stub.CreateLogStream(request) 

42 except RpcError as e: 

43 LOGGER.exception(f"Error creating a LogStream: {e.details()}") 

44 raise ConnectionError(e.details()) 

45 

46 def close(self) -> None: 

47 self._logstream_stub = None 

48 

49 

50@contextmanager 

51def logstream_client(channel: grpc.Channel, instance_name: str) -> Iterator[LogStreamClient]: 

52 client = LogStreamClient(channel, instance_name) 

53 try: 

54 yield client 

55 finally: 

56 client.close()