Mohammed Naser | 1220717 | 2024-02-05 18:49:35 -0500 | [diff] [blame] | 1 | #!/bin/bash -x |
| 2 | |
| 3 | # Check if an argument was provided |
| 4 | if [ "$#" -ne 1 ]; then |
| 5 | echo "Usage: $0 <path_to_save_logs>" |
| 6 | exit 1 |
| 7 | fi |
| 8 | |
| 9 | # Define the base directory where you want to save the logs |
| 10 | BASE_DIR="$1" |
| 11 | |
| 12 | # Create the base directory if it doesn't exist |
| 13 | mkdir -p "$BASE_DIR" |
| 14 | |
| 15 | # Function to fetch logs for a pod and container |
| 16 | fetch_logs() { |
| 17 | local ns="$1" |
| 18 | local pod="$2" |
| 19 | local container="$3" |
| 20 | local pod_dir="$BASE_DIR/$ns/$pod" |
| 21 | local log_file="$pod_dir/$container.log" |
| 22 | local prev_log_file="$pod_dir/${container}-previous.log" |
| 23 | |
| 24 | # Ensure the pod directory exists |
| 25 | mkdir -p "$pod_dir" |
| 26 | |
| 27 | # Fetch current logs |
| 28 | kubectl logs "$pod" -n "$ns" -c "$container" > "$log_file" 2>/dev/null |
| 29 | |
| 30 | # Fetch previous logs if they exist |
| 31 | if kubectl logs "$pod" -n "$ns" -c "$container" --previous &>/dev/null; then |
| 32 | kubectl logs "$pod" -n "$ns" -c "$container" --previous > "$prev_log_file" 2>/dev/null |
| 33 | fi |
| 34 | } |
| 35 | |
| 36 | export -f fetch_logs |
| 37 | export BASE_DIR |
| 38 | |
| 39 | # Get all namespaces |
| 40 | namespaces=$(kubectl get ns -o jsonpath='{.items[*].metadata.name}') |
| 41 | |
| 42 | # Loop through each namespace |
| 43 | for ns in $namespaces; do |
| 44 | ( |
| 45 | # Create a directory for the namespace |
| 46 | mkdir -p "$BASE_DIR/$ns" |
| 47 | |
| 48 | # Get all pods in the namespace |
| 49 | pods=$(kubectl get pods -n "$ns" -o jsonpath='{.items[*].metadata.name}') |
| 50 | |
| 51 | # Loop through each pod |
| 52 | for pod in $pods; do |
| 53 | ( |
| 54 | # Create a directory for the pod |
| 55 | mkdir -p "$BASE_DIR/$ns/$pod" |
| 56 | |
| 57 | # Get all containers in the pod |
| 58 | containers=$(kubectl get pod "$pod" -n "$ns" -o jsonpath='{.spec.containers[*].name}') |
| 59 | |
| 60 | # Loop through each container |
| 61 | for container in $containers; do |
| 62 | # Fetch logs in parallel |
| 63 | fetch_logs "$ns" "$pod" "$container" & |
| 64 | done |
| 65 | |
| 66 | # Wait for all background log fetches to complete before moving to the next pod |
| 67 | wait |
| 68 | ) & |
| 69 | done |
| 70 | # Wait for all background pods processing to complete before moving to the next namespace |
| 71 | wait |
| 72 | ) & |
| 73 | done |
| 74 | |
| 75 | # Wait for all background namespaces processing to complete |
| 76 | wait |
| 77 | |
| 78 | echo "Logs have been saved to $BASE_DIR" |