or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

agent-inspection.mdapi-integration.mdconfiguration.mdindex.mdinstallation.mdprocess-management.mdtunnel-management.md

process-management.mddocs/

0

# Process Management

1

2

Complete ngrok process lifecycle management including startup, monitoring, health checking, and cleanup with support for custom configurations and log monitoring.

3

4

## Capabilities

5

6

### Process Container

7

8

The NgrokProcess class provides comprehensive process information and control.

9

10

```python { .api }

11

class NgrokProcess:

12

"""

13

Container for ngrok process information and operations.

14

"""

15

proc: subprocess.Popen # The child process running ngrok

16

pyngrok_config: PyngrokConfig # Configuration used with ngrok

17

api_url: str # API URL for ngrok web interface

18

logs: list # Recent logs from ngrok (limited by max_logs)

19

startup_error: str # Error message if startup failed

20

21

def healthy(self):

22

"""

23

Check if ngrok process is running and healthy.

24

25

Returns:

26

bool: True if process is started, running, and healthy

27

28

Raises:

29

PyngrokSecurityError: When API URL is not supported

30

"""

31

32

def start_monitor_thread(self):

33

"""

34

Start a thread to monitor the ngrok process and its logs.

35

Does nothing if monitor thread is already running.

36

"""

37

38

def stop_monitor_thread(self):

39

"""

40

Stop the monitor thread after the next log event.

41

Sets a flag for the thread to terminate when it wakes up.

42

"""

43

```

44

45

**Usage Examples:**

46

47

```python

48

from pyngrok import ngrok

49

50

# Get the current ngrok process

51

process = ngrok.get_ngrok_process()

52

53

print(f"Process ID: {process.proc.pid}")

54

print(f"API URL: {process.api_url}")

55

print(f"Is healthy: {process.healthy()}")

56

57

# Access recent logs

58

for log in process.logs[-5:]: # Last 5 logs

59

print(f"{log.t} [{log.lvl}] {log.msg}")

60

61

# Control monitoring

62

process.start_monitor_thread()

63

process.stop_monitor_thread()

64

```

65

66

### Getting Process Instance

67

68

Retrieve or start the ngrok process with automatic installation and startup.

69

70

```python { .api }

71

def get_process(pyngrok_config):

72

"""

73

Get the current ngrok process for the given config's ngrok_path.

74

If ngrok is not running, starts a new process.

75

76

Parameters:

77

- pyngrok_config (PyngrokConfig): Configuration for ngrok interaction

78

79

Returns:

80

NgrokProcess: The ngrok process instance

81

"""

82

```

83

84

**Usage Examples:**

85

86

```python

87

from pyngrok import process, conf

88

89

# Get process with default configuration

90

default_config = conf.get_default()

91

ngrok_process = process.get_process(default_config)

92

93

# Get process with custom configuration

94

custom_config = conf.PyngrokConfig(

95

startup_timeout=30,

96

monitor_thread=True

97

)

98

custom_process = process.get_process(custom_config)

99

100

print(f"Process API URL: {custom_process.api_url}")

101

```

102

103

### High-Level Process Access

104

105

Get the current ngrok process with automatic installation and startup.

106

107

```python { .api }

108

def get_ngrok_process(pyngrok_config=None):

109

"""

110

Get the current ngrok process for the given configuration.

111

Installs ngrok if not present and starts the process if not running.

112

113

Parameters:

114

- pyngrok_config (PyngrokConfig, optional): Configuration override

115

116

Returns:

117

NgrokProcess: The running ngrok process instance

118

119

Raises:

120

PyngrokError: When process startup fails

121

"""

122

```

123

124

**Usage Examples:**

125

126

```python

127

from pyngrok import ngrok, conf

128

129

# Get process with default configuration (installs and starts if needed)

130

process = ngrok.get_ngrok_process()

131

print(f"Process API URL: {process.api_url}")

132

print(f"Process healthy: {process.healthy()}")

133

134

# Get process with custom configuration

135

custom_config = conf.PyngrokConfig(

136

startup_timeout=30,

137

monitor_thread=True

138

)

139

custom_process = ngrok.get_ngrok_process(custom_config)

140

print(f"Custom process logs: {len(custom_process.logs)}")

141

142

# Access process details

143

print(f"Process PID: {process.proc.pid}")

144

print(f"Config path: {process.pyngrok_config.config_path}")

145

```

146

147

### Process Status Checking

148

149

Check if ngrok is currently running without starting it.

150

151

```python { .api }

152

def is_process_running(ngrok_path):

153

"""

154

Check if ngrok process is currently running for the given path.

155

156

Parameters:

157

- ngrok_path (str): Path to the ngrok binary

158

159

Returns:

160

bool: True if ngrok is running from the given path

161

"""

162

```

163

164

**Usage Examples:**

165

166

```python

167

from pyngrok import process, conf

168

169

# Check if default ngrok is running

170

default_config = conf.get_default()

171

is_running = process.is_process_running(default_config.ngrok_path)

172

print(f"ngrok running: {is_running}")

173

174

# Check custom path

175

custom_path = "/usr/local/bin/ngrok"

176

is_custom_running = process.is_process_running(custom_path)

177

print(f"Custom ngrok running: {is_custom_running}")

178

```

179

180

### Process Termination

181

182

Kill running ngrok processes with cleanup.

183

184

```python { .api }

185

def kill_process(ngrok_path):

186

"""

187

Terminate the ngrok process for the given path.

188

This method issues a kill request and does not block.

189

190

Parameters:

191

- ngrok_path (str): Path to the ngrok binary

192

"""

193

```

194

195

**Usage Examples:**

196

197

```python

198

from pyngrok import process, conf

199

200

# Kill default ngrok process

201

default_config = conf.get_default()

202

process.kill_process(default_config.ngrok_path)

203

204

# Kill custom ngrok process

205

process.kill_process("/usr/local/bin/ngrok")

206

207

# Verify process is stopped

208

is_running = process.is_process_running(default_config.ngrok_path)

209

print(f"Process still running: {is_running}") # Should be False

210

```

211

212

### Direct Process Execution

213

214

Run ngrok directly with custom arguments for command-line style usage.

215

216

```python { .api }

217

def run_process(ngrok_path, args):

218

"""

219

Start a blocking ngrok process with the given path and arguments.

220

This method is for direct ngrok invocation and blocks until completion.

221

222

Parameters:

223

- ngrok_path (str): Path to the ngrok binary

224

- args (list): Arguments to pass to ngrok

225

226

Note: Not compatible with non-blocking API methods

227

"""

228

229

def capture_run_process(ngrok_path, args):

230

"""

231

Run ngrok process and capture its output.

232

Blocks until process completes and returns captured output.

233

234

Parameters:

235

- ngrok_path (str): Path to the ngrok binary

236

- args (list): Arguments to pass to ngrok

237

238

Returns:

239

str: Captured output from the ngrok process

240

241

Raises:

242

PyngrokNgrokError: When ngrok exits with non-zero code

243

CalledProcessError: When process execution fails

244

"""

245

```

246

247

**Usage Examples:**

248

249

```python

250

from pyngrok import process, conf

251

252

config = conf.get_default()

253

254

# Run ngrok with custom arguments (blocking)

255

# This is equivalent to running "ngrok version" from command line

256

try:

257

process.run_process(config.ngrok_path, ["version"])

258

except Exception as e:

259

print(f"Error running ngrok: {e}")

260

261

# Capture output from ngrok command

262

try:

263

version_output = process.capture_run_process(config.ngrok_path, ["--version"])

264

print(f"ngrok version: {version_output}")

265

except Exception as e:

266

print(f"Error getting version: {e}")

267

268

# Run help command and capture output

269

help_output = process.capture_run_process(config.ngrok_path, ["--help"])

270

print(help_output)

271

```

272

273

### Authentication Setup

274

275

Configure authentication tokens and API keys through the process management layer.

276

277

```python { .api }

278

def set_auth_token(pyngrok_config, token):

279

"""

280

Set the ngrok auth token in the config file.

281

282

Parameters:

283

- pyngrok_config (PyngrokConfig): Configuration for ngrok interaction

284

- token (str): The auth token to set

285

286

Raises:

287

PyngrokError: When ngrok_version is not supported

288

PyngrokNgrokError: When ngrok could not start or save the token

289

"""

290

291

def set_api_key(pyngrok_config, key):

292

"""

293

Set the ngrok API key in the config file (v3 only).

294

295

Parameters:

296

- pyngrok_config (PyngrokConfig): Configuration for ngrok interaction

297

- key (str): The API key to set

298

299

Raises:

300

PyngrokError: When ngrok_version is not supported

301

PyngrokNgrokError: When ngrok could not start or save the key

302

"""

303

```

304

305

**Usage Examples:**

306

307

```python

308

from pyngrok import process, conf

309

310

config = conf.get_default()

311

312

# Set auth token

313

try:

314

process.set_auth_token(config, "your_authtoken_here")

315

print("Auth token saved successfully")

316

except Exception as e:

317

print(f"Error setting auth token: {e}")

318

319

# Set API key (ngrok v3 only)

320

if config.ngrok_version == "v3":

321

try:

322

process.set_api_key(config, "your_api_key_here")

323

print("API key saved successfully")

324

except Exception as e:

325

print(f"Error setting API key: {e}")

326

```

327

328

### Process Monitoring and Logging

329

330

Monitor ngrok process health and capture log events.

331

332

**Usage Examples:**

333

334

```python

335

from pyngrok import process, conf

336

import time

337

338

def log_callback(log):

339

print(f"[{log.t}] {log.lvl}: {log.msg}")

340

if log.err:

341

print(f" Error: {log.err}")

342

343

# Configuration with logging

344

config = conf.PyngrokConfig(

345

log_event_callback=log_callback,

346

monitor_thread=True,

347

max_logs=50

348

)

349

350

# Get process with monitoring

351

ngrok_process = process.get_process(config)

352

353

# Check process health periodically

354

for i in range(5):

355

time.sleep(2)

356

if ngrok_process.healthy():

357

print(f"Process healthy at check {i+1}")

358

else:

359

print(f"Process unhealthy at check {i+1}")

360

if ngrok_process.startup_error:

361

print(f"Startup error: {ngrok_process.startup_error}")

362

363

# Access accumulated logs

364

print(f"\nTotal logs captured: {len(ngrok_process.logs)}")

365

for log in ngrok_process.logs[-3:]: # Last 3 logs

366

print(f" {log.lvl}: {log.msg}")

367

```

368

369

### Advanced Process Configuration

370

371

Examples of advanced process management scenarios.

372

373

**Usage Examples:**

374

375

```python

376

from pyngrok import process, conf

377

378

# Configuration for production environment

379

production_config = conf.PyngrokConfig(

380

startup_timeout=60, # Longer timeout for slow systems

381

monitor_thread=True, # Monitor for stability

382

max_logs=500, # Keep more logs

383

request_timeout=15.0, # Longer API timeouts

384

start_new_session=True # Isolate process on POSIX

385

)

386

387

# High-availability setup with health checking

388

def health_monitor(ngrok_process):

389

"""Monitor ngrok process health and restart if needed"""

390

if not ngrok_process.healthy():

391

print("Process unhealthy, restarting...")

392

process.kill_process(ngrok_process.pyngrok_config.ngrok_path)

393

time.sleep(1)

394

return process.get_process(ngrok_process.pyngrok_config)

395

return ngrok_process

396

397

# Start monitored process

398

monitored_process = process.get_process(production_config)

399

400

# Periodic health checks (in real application, use threading)

401

import time

402

for _ in range(10):

403

monitored_process = health_monitor(monitored_process)

404

time.sleep(5)

405

```