Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

# Copyright (C) 2018 Bloomberg LP 

# 

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

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

# You may obtain a copy of the License at 

# 

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

# 

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

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

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

# See the License for the specific language governing permissions and 

# limitations under the License. 

 

 

""" 

ExecutionService 

================ 

 

Serves remote execution requests. 

""" 

 

import logging 

import queue 

from functools import partial 

 

import grpc 

 

from buildgrid._exceptions import FailedPreconditionError, InvalidArgumentError, CancelledError 

from buildgrid._protos.build.bazel.remote.execution.v2 import remote_execution_pb2_grpc 

from buildgrid._protos.google.longrunning import operations_pb2 

from buildgrid.server._authentication import AuthContext, authorize 

from buildgrid.server.peer import Peer 

from buildgrid.server._resources import ExecContext, limit 

 

 

class ExecutionService(remote_execution_pb2_grpc.ExecutionServicer): 

 

def __init__(self, server, monitor=False): 

self.__logger = logging.getLogger(__name__) 

 

self.__peers_by_instance = None 

self.__peers = None 

 

self._instances = {} 

 

remote_execution_pb2_grpc.add_ExecutionServicer_to_server(self, server) 

 

self._is_instrumented = monitor 

 

if self._is_instrumented: 

self.__peers_by_instance = {} 

self.__peers = {} 

 

# --- Public API --- 

 

def add_instance(self, instance_name, instance): 

"""Registers a new servicer instance. 

 

Args: 

instance_name (str): The new instance's name. 

instance (ExecutionInstance): The new instance itself. 

""" 

self._instances[instance_name] = instance 

 

if self._is_instrumented: 

self.__peers_by_instance[instance_name] = set() 

 

def get_scheduler(self, instance_name): 

"""Retrieves a reference to the scheduler for an instance. 

 

Args: 

instance_name (str): The name of the instance to query. 

 

Returns: 

Scheduler: A reference to the scheduler for `instance_name`. 

 

Raises: 

InvalidArgumentError: If no instance named `instance_name` exists. 

""" 

instance = self._get_instance(instance_name) 

 

return instance.scheduler 

 

# --- Public API: Servicer --- 

 

@authorize(AuthContext) 

@limit(ExecContext) 

def Execute(self, request, context): 

"""Handles ExecuteRequest messages. 

 

Args: 

request (ExecuteRequest): The incoming RPC request. 

context (grpc.ServicerContext): Context for the RPC call. 

""" 

self.__logger.debug("Execute request from [%s]", context.peer()) 

 

instance_name = request.instance_name 

message_queue = queue.Queue() 

peer_uid = context.peer() 

 

Peer.register_peer(uid=peer_uid, context=context) 

 

try: 

instance = self._get_instance(instance_name) 

 

job_name = instance.execute(request.action_digest, 

request.skip_cache_lookup) 

 

operation_name = instance.register_job_peer(job_name, 

peer_uid, message_queue) 

 

context.add_callback(partial(self._rpc_termination_callback, 

peer_uid, instance_name, operation_name)) 

 

if self._is_instrumented: 

if peer_uid not in self.__peers: 

self.__peers_by_instance[instance_name].add(peer_uid) 

self.__peers[peer_uid] = 1 

else: 

self.__peers[peer_uid] += 1 

 

operation_full_name = "{}/{}".format(instance_name, operation_name) 

 

self.__logger.info("Operation [%s] created for job [%s]", 

operation_full_name, job_name) 

 

for operation in instance.stream_operation_updates_while_context_is_active(message_queue, context): 

operation.name = operation_full_name 

yield operation 

 

if not context.is_active(): 

self.__logger.info("Peer peer_uid=[%s] was holding up a thread for " 

" `stream_operation_updates()` for instance_name=[%s]," 

" operation_name=[%s], but the rpc context is not active anymore;" 

" releasing thread.", 

peer_uid, instance_name, operation_name) 

 

except InvalidArgumentError as e: 

self.__logger.error(e) 

context.set_details(str(e)) 

context.set_code(grpc.StatusCode.INVALID_ARGUMENT) 

yield operations_pb2.Operation() 

 

except FailedPreconditionError as e: 

self.__logger.error(e) 

context.set_details(str(e)) 

context.set_code(grpc.StatusCode.FAILED_PRECONDITION) 

yield operations_pb2.Operation() 

 

except CancelledError as e: 

self.__logger.info("Operation cancelled [%s]", operation_full_name) 

context.set_details(str(e)) 

context.set_code(grpc.StatusCode.CANCELLED) 

yield e.last_response 

 

@authorize(AuthContext) 

@limit(ExecContext) 

def WaitExecution(self, request, context): 

"""Handles WaitExecutionRequest messages. 

 

Args: 

request (WaitExecutionRequest): The incoming RPC request. 

context (grpc.ServicerContext): Context for the RPC call. 

""" 

self.__logger.debug("WaitExecution request from [%s]", context.peer()) 

 

names = request.name.split('/') 

instance_name = '/'.join(names[:-1]) 

operation_name = names[-1] 

message_queue = queue.Queue() 

peer = context.peer() 

 

try: 

instance = self._get_instance(instance_name) 

 

instance.register_operation_peer(operation_name, 

peer, message_queue) 

 

context.add_callback(partial(self._rpc_termination_callback, 

peer, instance_name, operation_name)) 

 

if self._is_instrumented: 

if peer not in self.__peers: 

self.__peers_by_instance[instance_name].add(peer) 

self.__peers[peer] = 1 

else: 

self.__peers[peer] += 1 

 

operation_full_name = "{}/{}".format(instance_name, operation_name) 

 

for operation in instance.stream_operation_updates_while_context_is_active(message_queue, context): 

operation.name = operation_full_name 

yield operation 

 

if not context.is_active(): 

self.__logger.info("Peer peer_uid=[%s] was holding up a thread for " 

" `stream_operation_updates()` for instance_name=[%s]," 

" operation_name=[%s], but the rpc context is not active anymore;" 

" releasing thread.", 

peer, instance_name, operation_name) 

 

except InvalidArgumentError as e: 

self.__logger.error(e) 

context.set_details(str(e)) 

context.set_code(grpc.StatusCode.INVALID_ARGUMENT) 

yield operations_pb2.Operation() 

 

except CancelledError as e: 

self.__logger.info("Operation cancelled [%s]", operation_full_name) 

context.set_details(str(e)) 

context.set_code(grpc.StatusCode.CANCELLED) 

yield e.last_response 

 

# --- Public API: Monitoring --- 

 

@property 

def is_instrumented(self): 

return self._is_instrumented 

 

def query_n_clients(self): 

if self.__peers is not None: 

return len(self.__peers) 

return 0 

 

def query_n_clients_for_instance(self, instance_name): 

try: 

if self.__peers_by_instance is not None: 

return len(self.__peers_by_instance[instance_name]) 

except KeyError: 

pass 

return 0 

 

# --- Private API --- 

 

def _rpc_termination_callback(self, peer_uid, instance_name, operation_name): 

self.__logger.debug("RPC terminated for peer_uid=[%s], instance_name=[%s], operation_name=[%s]", 

peer_uid, instance_name, operation_name) 

 

instance = self._get_instance(instance_name) 

 

instance.unregister_operation_peer(operation_name, peer_uid) 

 

if self._is_instrumented: 

if self.__peers[peer_uid] > 1: 

self.__peers[peer_uid] -= 1 

else: 

self.__peers_by_instance[instance_name].remove(peer_uid) 

del self.__peers[peer_uid] 

 

Peer.deregister_peer(peer_uid) 

 

def _get_instance(self, name): 

try: 

return self._instances[name] 

 

except KeyError: 

raise InvalidArgumentError("Instance doesn't exist on server: [{}]".format(name))