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

259

260

261

262

263

264

265

266

267

268

269

270

271

# 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. 

 

 

import asyncio 

import ctypes 

from enum import Enum 

import sys 

import socket 

 

from google.protobuf import json_format 

 

from buildgrid._exceptions import InvalidArgumentError 

from buildgrid._protos.buildgrid.v2 import monitoring_pb2 

 

 

class MonitoringOutputType(Enum): 

# Standard output stream. 

STDOUT = 'stdout' 

# On-disk file. 

FILE = 'file' 

# UNIX domain socket. 

SOCKET = 'socket' 

# UDP IP:port 

UDP = 'udp' 

 

 

class MonitoringOutputFormat(Enum): 

# Protobuf binary format. 

BINARY = 'binary' 

# JSON format. 

JSON = 'json' 

# StatsD format. Only metrics are kept - logs are dropped. 

STATSD = 'statsd' 

 

 

class UdpWrapper: 

""" Wraps socket sendto() in write() so it can be used polymorphically """ 

 

def __init__(self, endpoint_location): 

try: 

self._addr, self._port = endpoint_location.split(":") 

self._port = int(self._port) 

except ValueError as e: 

error_msg = "udp endpoint-location {} does not have the form address:port".format( 

endpoint_location) 

raise ValueError(error_msg) from e 

self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 

 

def write(self, message): 

self._socket.sendto(message, (self._addr, self._port)) 

 

 

class MonitoringBus: 

 

def __init__(self, event_loop, 

endpoint_type=MonitoringOutputType.SOCKET, endpoint_location=None, 

metric_prefix="", 

serialisation_format=MonitoringOutputFormat.BINARY): 

self.__event_loop = event_loop 

self.__streaming_task = None 

 

self.__message_queue = asyncio.Queue(loop=self.__event_loop) 

self.__sequence_number = 1 

 

self.__output_location = None 

self.__async_output = False 

self.__json_output = False 

self.__statsd_output = False 

self.__print_output = False 

self.__udp_output = False 

 

if endpoint_type == MonitoringOutputType.FILE: 

self.__output_location = endpoint_location 

 

elif endpoint_type == MonitoringOutputType.SOCKET: 

self.__output_location = endpoint_location 

self.__async_output = True 

 

elif endpoint_type == MonitoringOutputType.STDOUT: 

self.__print_output = True 

 

elif endpoint_type == MonitoringOutputType.UDP: 

self.__output_location = endpoint_location 

self.__udp_output = True 

 

else: 

raise InvalidArgumentError("Invalid endpoint output type: [{}]" 

.format(endpoint_type)) 

 

self.__metric_prefix = metric_prefix 

 

if serialisation_format == MonitoringOutputFormat.JSON: 

self.__json_output = True 

elif serialisation_format == MonitoringOutputFormat.STATSD: 

self.__statsd_output = True 

 

# --- Public API --- 

 

@property 

def prints_records(self): 

"""Whether or not messages are printed to standard output.""" 

return self.__print_output 

 

def start(self): 

"""Starts the monitoring bus worker task.""" 

if self.__streaming_task is not None: 

return 

 

self.__streaming_task = asyncio.ensure_future( 

self._streaming_worker(), loop=self.__event_loop) 

 

def stop(self): 

"""Cancels the monitoring bus worker task.""" 

if self.__streaming_task is None: 

return 

 

self.__streaming_task.cancel() 

 

async def prefix_record(self, record): 

instance_name = record.metadata.get('instance-name') 

if instance_name is not None: 

# This is an instance metric, so we'll add the instance name 

# to the prefix if it isn't empty 

if instance_name: 

instance_name = instance_name + "." 

 

# Prefix the metric with "instance_name.instance." if the instance 

# name isn't empty, otherwise just "instance." 

record.name = "{}{}instance.{}".format( 

self.__metric_prefix, instance_name, record.name) 

 

else: 

# Not an instance metric 

record.name = "{}{}".format(self.__metric_prefix, record.name) 

 

return record 

 

async def send_record(self, record): 

"""Publishes a record onto the bus asynchronously. 

 

Args: 

record (Message): The 

""" 

if record.DESCRIPTOR is monitoring_pb2.MetricRecord.DESCRIPTOR: 

record = await self.prefix_record(record) 

 

await self.__message_queue.put(record) 

 

# --- Private API --- 

 

@staticmethod 

def _convert_metric_to_statsd(record): 

if record.type == monitoring_pb2.MetricRecord.COUNTER: 

if record.count is None: 

raise ValueError( 

"COUNTER record {} is missing a count".format(record.name)) 

return "{}:{}|c\n".format(record.name, record.count) 

elif record.type is monitoring_pb2.MetricRecord.TIMER: 

if record.duration is None: 

raise ValueError( 

"TIMER record {} is missing a duration".format(record.name)) 

return "{}:{}|ms\n".format(record.name, record.duration.ToMilliseconds()) 

elif record.type is monitoring_pb2.MetricRecord.GAUGE: 

if record.value is None: 

raise ValueError( 

"GAUGE record {} is missing a value".format(record.name)) 

return "{}:{}|g\n".format(record.name, record.value) 

raise ValueError("Unknown record type.") 

 

async def _streaming_worker(self): 

"""Handles bus messages streaming work.""" 

async def __streaming_worker(end_points): 

record = await self.__message_queue.get() 

 

message = monitoring_pb2.BusMessage() 

message.sequence_number = self.__sequence_number 

 

if record.DESCRIPTOR is monitoring_pb2.LogRecord.DESCRIPTOR: 

message.log_record.CopyFrom(record) 

 

elif record.DESCRIPTOR is monitoring_pb2.MetricRecord.DESCRIPTOR: 

message.metric_record.CopyFrom(record) 

 

else: 

return False 

 

if self.__json_output: 

blob_message = json_format.MessageToJson(message).encode() 

 

for end_point in end_points: 

end_point.write(blob_message) 

 

elif self.__statsd_output: 

if record.DESCRIPTOR is monitoring_pb2.MetricRecord.DESCRIPTOR: 

statsd_message = MonitoringBus._convert_metric_to_statsd( 

record) 

for end_point in end_points: 

end_point.write(statsd_message.encode()) 

 

else: 

blob_size = ctypes.c_uint32(message.ByteSize()) 

blob_message = message.SerializeToString() 

 

for end_point in end_points: 

end_point.write(bytes(blob_size)) 

end_point.write(blob_message) 

 

return True 

 

output_writers, output_file = [], None 

 

async def __client_connected_callback(reader, writer): 

output_writers.append(writer) 

 

try: 

if self.__async_output and self.__output_location: 

await asyncio.start_unix_server( 

__client_connected_callback, path=self.__output_location, 

loop=self.__event_loop) 

 

while True: 

if await __streaming_worker(output_writers): 

self.__sequence_number += 1 

 

for writer in output_writers: 

await writer.drain() 

 

elif self.__udp_output and self.__output_location: 

output_writers.append(UdpWrapper(self.__output_location)) 

while True: 

if await __streaming_worker(output_writers): 

self.__sequence_number += 1 

 

elif self.__output_location: 

output_file = open(self.__output_location, mode='wb') 

 

output_writers.append(output_file) 

 

while True: 

if await __streaming_worker([output_file]): 

self.__sequence_number += 1 

 

output_file.flush() 

 

elif self.__print_output: 

output_writers.append(sys.stdout.buffer) 

 

while True: 

if await __streaming_worker(output_writers): 

self.__sequence_number += 1 

 

except asyncio.CancelledError: 

if output_file is not None: 

output_file.close() 

 

elif output_writers: 

for writer in output_writers: 

writer.close() 

await writer.wait_closed()