or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

api-interface.mdindex.mdmetric-sending.md

metric-sending.mddocs/

0

# Metric Sending

1

2

Send monitoring metrics to Zabbix server via trapper protocol with batch processing, configurable connection parameters, and comprehensive response handling. This functionality allows external applications to push metrics data directly to Zabbix for monitoring and alerting.

3

4

## Capabilities

5

6

### ZabbixSender Class

7

8

Client for sending metrics to Zabbix server using the trapper protocol with batch processing and configurable connection settings.

9

10

```python { .api }

11

class ZabbixSender:

12

def __init__(self, zabbix_server='127.0.0.1', zabbix_port=10051, use_config=None, chunk_size=250, socket_wrapper=None, timeout=10):

13

"""

14

Initialize ZabbixSender client.

15

16

Parameters:

17

- zabbix_server (str): Zabbix server IP address (default: '127.0.0.1')

18

- zabbix_port (int): Zabbix server port (default: 10051)

19

- use_config (str/bool, optional): Path to zabbix_agentd.conf file or True for default location

20

- chunk_size (int): Number of metrics to send per batch (default: 250)

21

- socket_wrapper (function, optional): Socket wrapper function for SSL/encryption

22

- timeout (int): Connection timeout in seconds (default: 10)

23

"""

24

```

25

26

#### Sending Metrics

27

28

```python { .api }

29

def send(self, metrics):

30

"""

31

Send list of metrics to Zabbix server.

32

33

Parameters:

34

- metrics (list): List of ZabbixMetric objects to send

35

36

Returns:

37

ZabbixResponse: Response object with send results

38

39

Raises:

40

socket.error: If connection fails

41

ValueError: If invalid metric data

42

"""

43

```

44

45

### ZabbixMetric Class

46

47

Container class representing a single metric to send to Zabbix with host, key, value, and optional timestamp.

48

49

```python { .api }

50

class ZabbixMetric:

51

def __init__(self, host, key, value, clock=None):

52

"""

53

Create a single metric for sending to Zabbix.

54

55

Parameters:

56

- host (str): Hostname as displayed in Zabbix frontend

57

- key (str): Item key identifier (must match Zabbix item configuration)

58

- value (str/int/float): Metric value to send

59

- clock (int, optional): Unix timestamp (default: current time)

60

61

Attributes:

62

- host (str): Metric hostname

63

- key (str): Metric key

64

- value (str): Metric value (converted to string)

65

- clock (int): Unix timestamp

66

"""

67

```

68

69

### ZabbixResponse Class

70

71

Response parser that processes server responses and provides access to send operation statistics.

72

73

```python { .api }

74

class ZabbixResponse:

75

def __init__(self):

76

"""Initialize response tracking counters."""

77

78

def parse(self, response):

79

"""

80

Parse server response and update counters.

81

82

Parameters:

83

- response (str): JSON response from Zabbix server

84

"""

85

86

@property

87

def processed(self):

88

"""

89

Number of successfully processed metrics.

90

91

Returns:

92

int: Count of processed metrics

93

"""

94

95

@property

96

def failed(self):

97

"""

98

Number of failed metrics.

99

100

Returns:

101

int: Count of failed metrics

102

"""

103

104

@property

105

def total(self):

106

"""

107

Total number of metrics sent.

108

109

Returns:

110

int: Total metric count

111

"""

112

113

@property

114

def time(self):

115

"""

116

Total processing time on server.

117

118

Returns:

119

Decimal: Processing time in seconds

120

"""

121

122

@property

123

def chunk(self):

124

"""

125

Number of chunks/batches sent.

126

127

Returns:

128

int: Chunk count

129

"""

130

```

131

132

## Usage Examples

133

134

### Basic Metric Sending

135

136

```python

137

from pyzabbix import ZabbixMetric, ZabbixSender

138

139

# Create individual metrics

140

metrics = [

141

ZabbixMetric('webserver01', 'cpu.usage', 85.2),

142

ZabbixMetric('webserver01', 'memory.usage[percent]', 67.5),

143

ZabbixMetric('webserver01', 'disk.free[/]', 1024000000),

144

ZabbixMetric('database01', 'mysql.queries', 1500),

145

]

146

147

# Send to Zabbix server

148

sender = ZabbixSender(zabbix_server='192.168.1.100', zabbix_port=10051)

149

result = sender.send(metrics)

150

151

print(f"Processed: {result.processed}")

152

print(f"Failed: {result.failed}")

153

print(f"Total: {result.total}")

154

print(f"Time: {result.time} seconds")

155

```

156

157

### Using Configuration File

158

159

```python

160

from pyzabbix import ZabbixMetric, ZabbixSender

161

162

# Use default zabbix_agentd.conf location

163

sender = ZabbixSender(use_config=True)

164

165

# Or specify custom config file path

166

sender = ZabbixSender(use_config='/etc/zabbix/zabbix_agentd.conf')

167

168

metrics = [

169

ZabbixMetric('server01', 'custom.metric', 42),

170

]

171

172

result = sender.send(metrics)

173

```

174

175

### Batch Processing with Custom Chunk Size

176

177

```python

178

from pyzabbix import ZabbixMetric, ZabbixSender

179

180

# Create large number of metrics

181

metrics = []

182

for i in range(1000):

183

metrics.append(ZabbixMetric('server01', f'metric.{i}', i * 10))

184

185

# Send in smaller chunks

186

sender = ZabbixSender(

187

zabbix_server='zabbix.example.com',

188

chunk_size=100, # Send 100 metrics at a time

189

timeout=30 # 30 second timeout

190

)

191

192

result = sender.send(metrics)

193

print(f"Sent {result.total} metrics in {result.chunk} chunks")

194

```

195

196

### Using Timestamps

197

198

```python

199

import time

200

from pyzabbix import ZabbixMetric, ZabbixSender

201

202

# Current timestamp

203

current_time = int(time.time())

204

205

# Historical timestamp (1 hour ago)

206

historical_time = current_time - 3600

207

208

metrics = [

209

ZabbixMetric('server01', 'current.value', 100, current_time),

210

ZabbixMetric('server01', 'historical.value', 90, historical_time),

211

ZabbixMetric('server01', 'auto.timestamp', 110), # Uses current time

212

]

213

214

sender = ZabbixSender()

215

result = sender.send(metrics)

216

```

217

218

### SSL/TLS Connection

219

220

```python

221

import ssl

222

from pyzabbix import ZabbixMetric, ZabbixSender

223

224

def ssl_wrapper(sock):

225

"""Custom SSL wrapper function."""

226

context = ssl.create_default_context()

227

return context.wrap_socket(sock)

228

229

sender = ZabbixSender(

230

zabbix_server='secure-zabbix.example.com',

231

zabbix_port=10051,

232

socket_wrapper=ssl_wrapper

233

)

234

235

metrics = [ZabbixMetric('server01', 'secure.metric', 42)]

236

result = sender.send(metrics)

237

```

238

239

### Error Handling

240

241

```python

242

import socket

243

from pyzabbix import ZabbixMetric, ZabbixSender

244

245

sender = ZabbixSender(zabbix_server='192.168.1.100', timeout=5)

246

metrics = [ZabbixMetric('server01', 'test.metric', 100)]

247

248

try:

249

result = sender.send(metrics)

250

251

if result.failed > 0:

252

print(f"Warning: {result.failed} metrics failed to process")

253

254

print(f"Successfully sent {result.processed} metrics")

255

256

except socket.timeout:

257

print("Connection timeout - Zabbix server may be unreachable")

258

except socket.error as e:

259

print(f"Network error: {e}")

260

except ValueError as e:

261

print(f"Invalid metric data: {e}")

262

```

263

264

### Monitoring Script Integration

265

266

```python

267

import psutil

268

import time

269

from pyzabbix import ZabbixMetric, ZabbixSender

270

271

def collect_system_metrics(hostname):

272

"""Collect system metrics and send to Zabbix."""

273

metrics = []

274

275

# CPU usage

276

cpu_percent = psutil.cpu_percent(interval=1)

277

metrics.append(ZabbixMetric(hostname, 'system.cpu.util', cpu_percent))

278

279

# Memory usage

280

memory = psutil.virtual_memory()

281

metrics.append(ZabbixMetric(hostname, 'vm.memory.util[pused]', memory.percent))

282

283

# Disk usage

284

disk = psutil.disk_usage('/')

285

disk_percent = (disk.used / disk.total) * 100

286

metrics.append(ZabbixMetric(hostname, 'vfs.fs.size[/,pused]', disk_percent))

287

288

# Load average (Unix systems)

289

try:

290

load1, load5, load15 = psutil.getloadavg()

291

metrics.append(ZabbixMetric(hostname, 'system.cpu.load[all,avg1]', load1))

292

except AttributeError:

293

pass # Not available on Windows

294

295

return metrics

296

297

# Send metrics

298

hostname = 'server01'

299

sender = ZabbixSender(zabbix_server='monitoring.example.com')

300

301

while True:

302

try:

303

metrics = collect_system_metrics(hostname)

304

result = sender.send(metrics)

305

print(f"Sent {result.processed} metrics, {result.failed} failed")

306

307

except Exception as e:

308

print(f"Error collecting/sending metrics: {e}")

309

310

time.sleep(60) # Send every minute

311

```

312

313

## Configuration File Format

314

315

When using `use_config=True` or specifying a config file path, ZabbixSender reads server connection details from zabbix_agentd.conf format:

316

317

```ini

318

# Server configuration

319

Server=192.168.1.100

320

ServerPort=10051

321

322

# Optional settings

323

Timeout=10

324

```

325

326

The following parameters are read from the configuration file:

327

- `Server` or `ServerActive`: Zabbix server IP address

328

- `ServerPort`: Zabbix server port (default: 10051)