or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

api-groups.mdclient-configuration.mdcore-resources.mdcustom-resources.mdexception-handling.mdindex.mdpod-operations.mdutilities.mdwatch-informers.md

pod-operations.mddocs/

0

# Pod Operations

1

2

The Fabric8 Kubernetes Client provides specialized operations for Pods beyond basic CRUD, including log streaming, command execution, port forwarding, and file operations. These advanced capabilities enable comprehensive Pod management and debugging.

3

4

## PodResource Interface

5

6

Specialized interface for Pod-specific operations.

7

8

```java { .api }

9

public interface PodResource extends Resource<Pod> {

10

// Log operations

11

String log();

12

String log(PodLogOptions options);

13

InputStream logInputStream();

14

InputStream logInputStream(PodLogOptions options);

15

LogWatch watchLog();

16

LogWatch watchLog(PodLogOptions options);

17

18

// Execution operations

19

ExecWatch exec(String... command);

20

ExecWatch exec(ExecOptions options);

21

22

// Port forwarding

23

LocalPortForward portForward(int port);

24

LocalPortForward portForward(int port, int localPort);

25

26

// File operations

27

Boolean upload(Path pathToUpload);

28

Boolean copy(Path source, Path destination);

29

30

// Attach operations

31

Pod attach();

32

ExecWatch attach(AttachOptions options);

33

}

34

```

35

36

## Log Operations

37

38

### Basic Log Retrieval

39

40

```java { .api }

41

public interface PodResource {

42

String log();

43

String log(PodLogOptions options);

44

InputStream logInputStream();

45

InputStream logInputStream(PodLogOptions options);

46

}

47

48

public class PodLogOptions {

49

public String getContainer();

50

public void setContainer(String container);

51

public Boolean getFollow();

52

public void setFollow(Boolean follow);

53

public Integer getTailLines();

54

public void setTailLines(Integer tailLines);

55

public String getSinceTime();

56

public void setSinceTime(String sinceTime);

57

public Integer getSinceSeconds();

58

public void setSinceSeconds(Integer sinceSeconds);

59

public Boolean getTimestamps();

60

public void setTimestamps(Boolean timestamps);

61

public Boolean getPrevious();

62

public void setPrevious(Boolean previous);

63

}

64

```

65

66

### Log Watching

67

68

```java { .api }

69

public interface LogWatch extends Closeable {

70

OutputStream getOutput();

71

void close();

72

}

73

```

74

75

## Execution Operations

76

77

### ExecWatch Interface

78

79

Interface for executing commands in Pod containers.

80

81

```java { .api }

82

public interface ExecWatch extends Closeable {

83

OutputStream getInput();

84

InputStream getOutput();

85

InputStream getError();

86

void resize(int cols, int rows);

87

void close();

88

}

89

90

public class ExecOptions {

91

public String getContainer();

92

public void setContainer(String container);

93

public String[] getCommand();

94

public void setCommand(String[] command);

95

public Boolean getStdin();

96

public void setStdin(Boolean stdin);

97

public Boolean getStdout();

98

public void setStdout(Boolean stdout);

99

public Boolean getStderr();

100

public void setStderr(Boolean stderr);

101

public Boolean getTty();

102

public void setTty(Boolean tty);

103

}

104

```

105

106

## Port Forwarding

107

108

### LocalPortForward Interface

109

110

Interface for managing port forwarding sessions.

111

112

```java { .api }

113

public interface LocalPortForward extends Closeable {

114

int getLocalPort();

115

boolean isAlive();

116

void close();

117

}

118

```

119

120

## Usage Examples

121

122

### Reading Pod Logs

123

124

```java

125

// Get logs from default container

126

String logs = client.pods().withName("my-pod").log();

127

System.out.println("Pod logs:\n" + logs);

128

129

// Get logs from specific container

130

String containerLogs = client.pods().withName("my-pod").log(new PodLogOptionsBuilder()

131

.withContainer("app-container")

132

.withTailLines(100)

133

.withTimestamps(true)

134

.build());

135

136

// Get logs since specific time

137

String recentLogs = client.pods().withName("my-pod").log(new PodLogOptionsBuilder()

138

.withSinceSeconds(3600) // Last hour

139

.withFollow(false)

140

.build());

141

142

// Get previous container logs (useful after restarts)

143

String previousLogs = client.pods().withName("crashed-pod").log(new PodLogOptionsBuilder()

144

.withPrevious(true)

145

.build());

146

```

147

148

### Streaming Logs

149

150

```java

151

// Stream logs in real-time

152

LogWatch logWatch = client.pods().withName("my-pod").watchLog(new PodLogOptionsBuilder()

153

.withFollow(true)

154

.withTailLines(10)

155

.build());

156

157

// Read streaming logs

158

try (BufferedReader reader = new BufferedReader(new InputStreamReader(logWatch.getOutput()))) {

159

String line;

160

while ((line = reader.readLine()) != null) {

161

System.out.println("Log: " + line);

162

163

// Break on some condition

164

if (line.contains("Application started")) {

165

break;

166

}

167

}

168

} finally {

169

logWatch.close();

170

}

171

172

// Stream logs with InputStream

173

try (InputStream logStream = client.pods().withName("my-pod").logInputStream(new PodLogOptionsBuilder()

174

.withFollow(true)

175

.withContainer("web-server")

176

.build())) {

177

178

byte[] buffer = new byte[1024];

179

int bytesRead;

180

while ((bytesRead = logStream.read(buffer)) != -1) {

181

String logChunk = new String(buffer, 0, bytesRead);

182

System.out.print(logChunk);

183

}

184

}

185

```

186

187

### Executing Commands

188

189

```java

190

// Execute simple command

191

ExecWatch execWatch = client.pods().withName("my-pod").exec("ls", "-la", "/app");

192

193

// Read command output

194

try (BufferedReader reader = new BufferedReader(new InputStreamReader(execWatch.getOutput()))) {

195

String line;

196

while ((line = reader.readLine()) != null) {

197

System.out.println("Output: " + line);

198

}

199

}

200

201

// Read any errors

202

try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(execWatch.getError()))) {

203

String line;

204

while ((line = errorReader.readLine()) != null) {

205

System.err.println("Error: " + line);

206

}

207

}

208

209

execWatch.close();

210

211

// Execute interactive command with input

212

ExecWatch interactiveExec = client.pods().withName("my-pod").exec("sh");

213

214

// Send commands to the shell

215

try (PrintWriter writer = new PrintWriter(interactiveExec.getInput())) {

216

writer.println("echo 'Hello from pod'");

217

writer.println("pwd");

218

writer.println("exit");

219

writer.flush();

220

}

221

222

// Read output

223

try (BufferedReader reader = new BufferedReader(new InputStreamReader(interactiveExec.getOutput()))) {

224

String line;

225

while ((line = reader.readLine()) != null) {

226

System.out.println("Shell output: " + line);

227

}

228

}

229

230

interactiveExec.close();

231

```

232

233

### Advanced Execution with Options

234

235

```java

236

// Execute in specific container with TTY

237

ExecOptions execOptions = new ExecOptionsBuilder()

238

.withContainer("sidecar")

239

.withCommand("bash", "-c", "cat /proc/meminfo | head -5")

240

.withStdin(false)

241

.withStdout(true)

242

.withStderr(true)

243

.withTty(false)

244

.build();

245

246

ExecWatch execWatch = client.pods().withName("my-pod").exec(execOptions);

247

248

// Process output and errors

249

CompletableFuture<String> outputFuture = CompletableFuture.supplyAsync(() -> {

250

try (BufferedReader reader = new BufferedReader(new InputStreamReader(execWatch.getOutput()))) {

251

return reader.lines().collect(Collectors.joining("\n"));

252

} catch (IOException e) {

253

throw new RuntimeException(e);

254

}

255

});

256

257

CompletableFuture<String> errorFuture = CompletableFuture.supplyAsync(() -> {

258

try (BufferedReader reader = new BufferedReader(new InputStreamReader(execWatch.getError()))) {

259

return reader.lines().collect(Collectors.joining("\n"));

260

} catch (IOException e) {

261

throw new RuntimeException(e);

262

}

263

});

264

265

try {

266

String output = outputFuture.get(30, TimeUnit.SECONDS);

267

String errors = errorFuture.get(30, TimeUnit.SECONDS);

268

269

System.out.println("Command output:\n" + output);

270

if (!errors.isEmpty()) {

271

System.err.println("Command errors:\n" + errors);

272

}

273

} finally {

274

execWatch.close();

275

}

276

```

277

278

### Port Forwarding

279

280

```java

281

// Forward pod port to local port

282

LocalPortForward portForward = client.pods().withName("web-pod").portForward(8080);

283

284

try {

285

System.out.println("Port forwarding active on localhost:" + portForward.getLocalPort());

286

System.out.println("Access the service at: http://localhost:" + portForward.getLocalPort());

287

288

// Keep port forward alive

289

while (portForward.isAlive()) {

290

Thread.sleep(1000);

291

}

292

} finally {

293

portForward.close();

294

}

295

296

// Forward to specific local port

297

LocalPortForward specificPortForward = client.pods().withName("database-pod")

298

.portForward(5432, 15432); // Forward pod:5432 to localhost:15432

299

300

System.out.println("Database accessible at localhost:15432");

301

302

// Use in try-with-resources

303

try (LocalPortForward pf = client.pods().withName("api-pod").portForward(3000)) {

304

// Make HTTP requests to localhost:pf.getLocalPort()

305

// Port forward automatically closed when leaving try block

306

307

// Example HTTP request (requires HTTP client library)

308

// HttpClient httpClient = HttpClient.newHttpClient();

309

// HttpRequest request = HttpRequest.newBuilder()

310

// .uri(URI.create("http://localhost:" + pf.getLocalPort() + "/health"))

311

// .build();

312

// HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

313

}

314

```

315

316

### File Operations

317

318

```java

319

// Upload file to pod

320

Path localFile = Paths.get("/local/path/config.yaml");

321

Boolean uploadSuccess = client.pods().withName("my-pod").upload(localFile);

322

323

if (uploadSuccess) {

324

System.out.println("File uploaded successfully");

325

} else {

326

System.out.println("File upload failed");

327

}

328

329

// Copy files between local and pod

330

Path source = Paths.get("/local/source/data.txt");

331

Path destination = Paths.get("/pod/destination/data.txt");

332

333

Boolean copySuccess = client.pods().withName("my-pod").copy(source, destination);

334

335

if (copySuccess) {

336

System.out.println("File copied successfully");

337

} else {

338

System.out.println("File copy failed");

339

}

340

341

// Copy directory

342

Path sourceDir = Paths.get("/local/config/");

343

Path destDir = Paths.get("/pod/app/config/");

344

345

Boolean dirCopySuccess = client.pods().withName("my-pod").copy(sourceDir, destDir);

346

```

347

348

### Attach Operations

349

350

```java

351

// Attach to pod (similar to kubectl attach)

352

Pod attachedPod = client.pods().withName("interactive-pod").attach();

353

354

// Attach with options

355

AttachOptions attachOptions = new AttachOptionsBuilder()

356

.withContainer("main")

357

.withStdin(true)

358

.withStdout(true)

359

.withStderr(true)

360

.withTty(true)

361

.build();

362

363

ExecWatch attachWatch = client.pods().withName("interactive-pod").attach(attachOptions);

364

365

// Send input to attached process

366

try (PrintWriter writer = new PrintWriter(attachWatch.getInput())) {

367

writer.println("Hello from attached session");

368

}

369

370

// Read output

371

try (BufferedReader reader = new BufferedReader(new InputStreamReader(attachWatch.getOutput()))) {

372

String line;

373

while ((line = reader.readLine()) != null) {

374

System.out.println("Attached output: " + line);

375

}

376

}

377

378

attachWatch.close();

379

```

380

381

### Multi-Container Pod Operations

382

383

```java

384

// Get pod with multiple containers

385

Pod multiContainerPod = client.pods().withName("multi-container-pod").get();

386

387

if (multiContainerPod != null) {

388

List<Container> containers = multiContainerPod.getSpec().getContainers();

389

390

for (Container container : containers) {

391

String containerName = container.getName();

392

System.out.println("Processing container: " + containerName);

393

394

// Get logs from each container

395

String containerLogs = client.pods().withName("multi-container-pod")

396

.log(new PodLogOptionsBuilder()

397

.withContainer(containerName)

398

.withTailLines(50)

399

.build());

400

401

System.out.println("Logs from " + containerName + ":\n" + containerLogs);

402

403

// Execute command in each container

404

ExecWatch exec = client.pods().withName("multi-container-pod")

405

.exec(new ExecOptionsBuilder()

406

.withContainer(containerName)

407

.withCommand("ps", "aux")

408

.build());

409

410

// Process exec output

411

try (BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getOutput()))) {

412

System.out.println("Processes in " + containerName + ":");

413

reader.lines().forEach(line -> System.out.println(" " + line));

414

} finally {

415

exec.close();

416

}

417

}

418

}

419

```

420

421

### Error Handling

422

423

```java

424

try {

425

// Try to get logs from a pod that might not exist

426

String logs = client.pods().withName("non-existent-pod").log();

427

} catch (KubernetesClientException e) {

428

if (e.getCode() == 404) {

429

System.out.println("Pod not found");

430

} else {

431

System.out.println("Error getting logs: " + e.getMessage());

432

}

433

}

434

435

try {

436

// Try to execute command with timeout

437

ExecWatch exec = client.pods().withName("slow-pod").exec("sleep", "300");

438

439

// Set up timeout

440

CompletableFuture<Void> execFuture = CompletableFuture.runAsync(() -> {

441

try (BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getOutput()))) {

442

reader.lines().forEach(System.out::println);

443

} catch (IOException e) {

444

throw new RuntimeException(e);

445

}

446

});

447

448

try {

449

execFuture.get(10, TimeUnit.SECONDS); // 10 second timeout

450

} catch (TimeoutException e) {

451

System.out.println("Command execution timed out");

452

exec.close(); // Force close

453

}

454

455

} catch (KubernetesClientException e) {

456

System.out.println("Execution failed: " + e.getMessage());

457

}

458

459

// Handle port forwarding errors

460

try {

461

LocalPortForward pf = client.pods().withName("my-pod").portForward(8080);

462

463

if (!pf.isAlive()) {

464

System.out.println("Port forwarding failed to start");

465

}

466

467

// Monitor port forward health

468

Timer timer = new Timer();

469

timer.schedule(new TimerTask() {

470

@Override

471

public void run() {

472

if (!pf.isAlive()) {

473

System.out.println("Port forwarding died, cleaning up");

474

timer.cancel();

475

}

476

}

477

}, 0, 5000); // Check every 5 seconds

478

479

} catch (KubernetesClientException e) {

480

System.out.println("Port forwarding failed: " + e.getMessage());

481

}

482

```