or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-management.mdconfig-secrets.mdcontainer-management.mdcontext-management.mderror-handling.mdimage-management.mdindex.mdnetwork-management.mdplugin-management.mdswarm-services.mdsystem-events.mdvolume-management.md

system-events.mddocs/

0

# System Information and Events

1

2

Docker daemon system information, resource usage monitoring, and real-time event streaming for comprehensive Docker environment observability.

3

4

## Capabilities

5

6

### System Information

7

8

```python { .api }

9

def df(self):

10

"""

11

Get Docker system disk usage information.

12

13

Returns:

14

dict: Disk usage data with the following structure:

15

- LayersSize (int): Total size of image layers in bytes

16

- Images (list): List of images with size information

17

- Containers (list): List of containers with size information

18

- Volumes (list): List of volumes with size information

19

- BuildCache (list): Build cache usage information

20

"""

21

22

def info(self):

23

"""

24

Get Docker system information.

25

26

Returns:

27

dict: System information including:

28

- ServerVersion (str): Docker server version

29

- Driver (str): Storage driver name

30

- KernelVersion (str): Host kernel version

31

- Architecture (str): Host architecture

32

- MemTotal (int): Total system memory

33

- NCPU (int): Number of CPUs

34

- DockerRootDir (str): Docker root directory

35

- Swarm (dict): Swarm configuration if enabled

36

"""

37

38

def ping(self):

39

"""

40

Ping the Docker daemon to verify connectivity.

41

42

Returns:

43

bool: True if daemon is reachable

44

45

Raises:

46

APIError: If daemon is unreachable

47

"""

48

49

def version(self, api_version=True):

50

"""

51

Get Docker version information.

52

53

Args:

54

api_version (bool): Include API version information

55

56

Returns:

57

dict: Version information including:

58

- Version (str): Docker version

59

- ApiVersion (str): API version

60

- MinAPIVersion (str): Minimum supported API version

61

- GitCommit (str): Git commit hash

62

- GoVersion (str): Go version used to build Docker

63

- Os (str): Operating system

64

- Arch (str): Architecture

65

- BuildTime (str): Build timestamp

66

"""

67

```

68

69

### Event Streaming

70

71

```python { .api }

72

def events(self, since=None, until=None, filters=None, decode=None):

73

"""

74

Stream Docker events from the daemon in real-time.

75

76

Args:

77

since (datetime, int, or str): Show events since this time

78

until (datetime, int, or str): Show events until this time

79

filters (dict): Filter events by type, container, image, etc.

80

decode (bool): Decode JSON events automatically (default: None)

81

82

Yields:

83

dict: Event objects with the following structure:

84

- Type (str): Event type ('container', 'image', 'network', 'volume', 'daemon')

85

- Action (str): Event action ('create', 'start', 'stop', 'destroy', etc.)

86

- Actor (dict): Object that generated the event

87

- ID (str): Object ID

88

- Attributes (dict): Object attributes

89

- time (int): Event timestamp

90

- timeNano (int): Event timestamp in nanoseconds

91

92

Common filter keys:

93

- type: Event type filter

94

- container: Container name or ID

95

- image: Image name or ID

96

- event: Specific event action

97

- label: Filter by labels

98

- network: Network name or ID

99

- volume: Volume name

100

- daemon: Daemon events

101

"""

102

```

103

104

## Usage Examples

105

106

### System Monitoring

107

108

```python

109

import docker

110

from datetime import datetime

111

112

client = docker.from_env()

113

114

# Get system information

115

info = client.info()

116

print(f"Docker Version: {info['ServerVersion']}")

117

print(f"Storage Driver: {info['Driver']}")

118

print(f"Total Memory: {info['MemTotal'] / (1024**3):.1f} GB")

119

print(f"CPUs: {info['NCPU']}")

120

121

# Check if Swarm is enabled

122

if info['Swarm']['LocalNodeState'] == 'active':

123

print("Swarm mode is active")

124

125

# Get resource usage

126

usage = client.df()

127

print(f"\\nDisk Usage:")

128

print(f"Images: {len(usage['Images'])} ({usage['LayersSize'] / (1024**2):.1f} MB)")

129

print(f"Containers: {len(usage['Containers'])}")

130

print(f"Volumes: {len(usage['Volumes'])}")

131

132

if 'BuildCache' in usage:

133

cache_size = sum(item.get('Size', 0) for item in usage['BuildCache'])

134

print(f"Build Cache: {cache_size / (1024**2):.1f} MB")

135

136

# Version information

137

version = client.version()

138

print(f"\\nVersion Details:")

139

print(f"API Version: {version['ApiVersion']}")

140

print(f"Git Commit: {version['GitCommit']}")

141

print(f"Go Version: {version['GoVersion']}")

142

```

143

144

### Real-time Event Monitoring

145

146

```python

147

import docker

148

from datetime import datetime, timedelta

149

150

client = docker.from_env()

151

152

# Monitor all events

153

print("Monitoring all Docker events (Ctrl+C to stop):")

154

try:

155

for event in client.events(decode=True):

156

timestamp = datetime.fromtimestamp(event['time'])

157

actor_name = event['Actor']['Attributes'].get('name', 'unknown')

158

print(f"[{timestamp}] {event['Type']}: {event['Action']} - {actor_name}")

159

except KeyboardInterrupt:

160

print("Event monitoring stopped")

161

162

# Monitor specific events with filters

163

print("\\nMonitoring container start/stop events:")

164

filters = {

165

'type': 'container',

166

'event': ['start', 'stop', 'create', 'destroy']

167

}

168

169

for event in client.events(filters=filters, decode=True):

170

container_name = event['Actor']['Attributes'].get('name', event['Actor']['ID'][:12])

171

action = event['Action']

172

timestamp = datetime.fromtimestamp(event['time'])

173

print(f"[{timestamp}] Container {container_name}: {action}")

174

175

# Historical events

176

since_time = datetime.now() - timedelta(hours=1)

177

print(f"\\nEvents from the last hour:")

178

179

for event in client.events(since=since_time, decode=True):

180

if event['Type'] == 'container':

181

container_name = event['Actor']['Attributes'].get('name', 'unknown')

182

print(f"{event['Action']}: {container_name} at {datetime.fromtimestamp(event['time'])}")

183

```

184

185

### Event Filtering and Processing

186

187

```python

188

import docker

189

import json

190

191

client = docker.from_env()

192

193

# Filter by specific container

194

container_filters = {

195

'container': ['my-app', 'nginx-proxy']

196

}

197

198

print("Monitoring specific containers:")

199

for event in client.events(filters=container_filters, decode=True):

200

container_name = event['Actor']['Attributes'].get('name')

201

print(f"Container {container_name}: {event['Action']}")

202

203

# Filter by labels

204

label_filters = {

205

'type': 'container',

206

'label': ['environment=production', 'service=web']

207

}

208

209

print("\\nMonitoring production web containers:")

210

for event in client.events(filters=label_filters, decode=True):

211

attrs = event['Actor']['Attributes']

212

container_name = attrs.get('name', 'unknown')

213

environment = attrs.get('environment', 'unknown')

214

service = attrs.get('service', 'unknown')

215

print(f"[{environment}/{service}] {container_name}: {event['Action']}")

216

217

# Process image events

218

image_filters = {'type': 'image'}

219

220

print("\\nMonitoring image events:")

221

for event in client.events(filters=image_filters, decode=True):

222

image_name = event['Actor']['Attributes'].get('name', event['Actor']['ID'][:12])

223

print(f"Image {image_name}: {event['Action']}")

224

225

# Log detailed info for pull events

226

if event['Action'] == 'pull':

227

print(f" Full event data: {json.dumps(event, indent=2)}")

228

229

# Custom event processor

230

def process_events():

231

\"\"\"Custom event processor with statistics.\"\"\"

232

event_counts = {}

233

234

try:

235

for event in client.events(decode=True):

236

event_type = f"{event['Type']}.{event['Action']}"

237

event_counts[event_type] = event_counts.get(event_type, 0) + 1

238

239

# Print summary every 10 events

240

total_events = sum(event_counts.values())

241

if total_events % 10 == 0:

242

print(f"\\nEvent Summary (last {total_events} events):")

243

for event_type, count in sorted(event_counts.items()):

244

print(f" {event_type}: {count}")

245

246

except KeyboardInterrupt:

247

print(f"\\nFinal Event Summary:")

248

for event_type, count in sorted(event_counts.items()):

249

print(f" {event_type}: {count}")

250

251

# Run custom processor

252

# process_events()

253

```

254

255

### System Health Monitoring

256

257

```python

258

import docker

259

import time

260

261

client = docker.from_env()

262

263

def monitor_system_health():

264

\"\"\"Monitor Docker system health metrics.\"\"\"

265

while True:

266

try:

267

# Test connectivity

268

client.ping()

269

270

# Get system stats

271

info = client.info()

272

usage = client.df()

273

274

# Calculate metrics

275

total_containers = len(usage['Containers'])

276

running_containers = len([c for c in client.containers.list()])

277

total_images = len(usage['Images'])

278

layer_size_gb = usage['LayersSize'] / (1024**3)

279

280

print(f"[{datetime.now()}] System Health:")

281

print(f" Containers: {running_containers}/{total_containers} running")

282

print(f" Images: {total_images} ({layer_size_gb:.2f} GB)")

283

print(f" Memory: {info['MemTotal'] / (1024**3):.1f} GB total")

284

print(f" Storage Driver: {info['Driver']}")

285

print(" Status: Healthy\\n")

286

287

except Exception as e:

288

print(f"[{datetime.now()}] System Health: ERROR - {e}\\n")

289

290

time.sleep(30) # Check every 30 seconds

291

292

# monitor_system_health()

293

```