|
| 1 | +#!/bin/sh |
| 2 | + |
| 3 | +# Check if exactly two arguments are provided: <namespace> and <output_directory> |
| 4 | +if [ $# -ne 2 ]; then |
| 5 | + echo "Usage: $0 <namespace> <output_directory>" >&2 |
| 6 | + exit 1 |
| 7 | +fi |
| 8 | + |
| 9 | +NAMESPACE="$1" |
| 10 | +OUTPUT_DIR="$2" |
| 11 | + |
| 12 | +# Create the output directory if it does not exist |
| 13 | +mkdir -p "$OUTPUT_DIR" |
| 14 | +if [ ! $? ]; then |
| 15 | + echo "Failed to create output directory: $OUTPUT_DIR" >&2 |
| 16 | + exit 1 |
| 17 | +fi |
| 18 | + |
| 19 | +# Fetch all pod names in the specified namespace using kubectl |
| 20 | +PODS=$(kubectl get pods -n "$NAMESPACE" -o jsonpath='{.items[*].metadata.name}' 2>/dev/null) |
| 21 | +if [ ! $? ]; then |
| 22 | + echo "Error retrieving pods from namespace: $NAMESPACE" >&2 |
| 23 | + exit 1 |
| 24 | +fi |
| 25 | + |
| 26 | +# Exit if no pods found in the namespace |
| 27 | +if [ -z "$PODS" ]; then |
| 28 | + echo "No pods found in namespace: $NAMESPACE" |
| 29 | + exit 0 |
| 30 | +fi |
| 31 | + |
| 32 | +# Process each pod to collect logs from all containers (regular and init) |
| 33 | +for POD in $PODS; do |
| 34 | + echo "Processing pod: $POD" |
| 35 | + |
| 36 | + # Fetch init container names for the current pod first |
| 37 | + INIT_CONTAINERS=$(kubectl get pod "$POD" -n "$NAMESPACE" -o jsonpath='{.spec.initContainers[*].name}' 2>/dev/null) |
| 38 | + if [ ! $? ]; then |
| 39 | + echo "Failed to get init containers for pod: $POD" >&2 |
| 40 | + continue |
| 41 | + fi |
| 42 | + |
| 43 | + # Fetch regular container names for the current pod |
| 44 | + CONTAINERS=$(kubectl get pod "$POD" -n "$NAMESPACE" -o jsonpath='{.spec.containers[*].name}' 2>/dev/null) |
| 45 | + if [ ! $? ]; then |
| 46 | + echo "Failed to get containers for pod: $POD" >&2 |
| 47 | + continue |
| 48 | + fi |
| 49 | + |
| 50 | + # Combine init container and regular names into a single list for logs |
| 51 | + ALL_CONTAINERS="$INIT_CONTAINERS $CONTAINERS" |
| 52 | + |
| 53 | + # Skip if no containers are found for the pod |
| 54 | + if [ -z "$ALL_CONTAINERS" ]; then |
| 55 | + echo "No containers or init containers found for pod: $POD" |
| 56 | + continue |
| 57 | + fi |
| 58 | + |
| 59 | + # Save logs for each init container in the list |
| 60 | + for CONTAINER in $ALL_CONTAINERS; do |
| 61 | + echo "Fetching logs for container: $CONTAINER" |
| 62 | + kubectl logs "$POD" -n "$NAMESPACE" -c "$CONTAINER" >> "${OUTPUT_DIR}/${POD}.log" |
| 63 | + if [ ! $? ]; then |
| 64 | + echo "Failed to retrieve logs for pod $POD, container $CONTAINER" >&2 |
| 65 | + fi |
| 66 | + done |
| 67 | +done |
| 68 | + |
| 69 | + |
| 70 | +echo "Logs saved to directory: $OUTPUT_DIR" |
| 71 | + |
0 commit comments