-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodolist_service.py
83 lines (57 loc) · 2.43 KB
/
todolist_service.py
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
import logging
import sys
import uuid
from concurrent import futures
import grpc
from grpc_health.v1 import health
from grpc_health.v1 import health_pb2
from grpc_health.v1 import health_pb2_grpc
import todolist_pb2
import todolist_pb2_grpc
port = 50051
health_check_servicer = None
class TodoListServicer(todolist_pb2_grpc.TodoListServicer):
def __init__(self):
self.items = []
def AddItem(self, request, context):
name = request.name
id = str(uuid.uuid4())
logging.info('Add item ({}, {})'.format(name, id))
self.items.append({
'name': name,
'id': id
})
return todolist_pb2.Id(id=id)
def GetItems(self, request, context):
logging.info('Get items: {}'.format(self.items))
return todolist_pb2.Items(items=map(lambda item: todolist_pb2.Item(name=todolist_pb2.Name(name=item['name']),
id=todolist_pb2.Id(id=item['id'])),
self.items))
def RemoveItem(self, request, context):
logging.info('Remove item ({})'.format(request.id))
self.items = list(filter(lambda item: item['id'] != request.id, self.items))
return todolist_pb2.Stub()
HealthCheckStatus = health_pb2.HealthCheckResponse
def set_health_check_status(status):
health_check_servicer.set('', status)
def serve():
logging.info('Starting configuration...')
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
todolist_pb2_grpc.add_TodoListServicer_to_server(
TodoListServicer(), server)
set_health_check_status(HealthCheckStatus.UNKNOWN)
health_pb2_grpc.add_HealthServicer_to_server(health_check_servicer, server)
server.add_insecure_port('[::]:{}'.format(port))
server.start()
logging.info('Started listening on port {}'.format(port))
set_health_check_status(HealthCheckStatus.SERVING)
server.wait_for_termination()
set_health_check_status(HealthCheckStatus.NOT_SERVING)
if __name__ == '__main__':
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
# Implementation of gRPC health checking
# https://github.com/grpc/grpc/blob/master/doc/health-checking.md
# Consul can be configured to execute this check to track the service's health status
# https://www.consul.io/docs/agent/checks.html
health_check_servicer = health.HealthServicer()
serve()