List Resources Related to Postgres Cluster acid-minimal-cluster in Namespace postgres-database¶
What does it do?
This command retrieves all resources with specific labels in a particular namespace, and then provides detailed information about a specific object within that namespace using a specific context.
Command
kubectl get all -l cluster-name=acid-minimal-cluster -n postgres-database --context gke_runwhen-nonprod-sandbox_us-central1_sandbox-cluster-1-cluster && kubectl describe postgresql.acid.zalan.do acid-minimal-cluster -n postgres-database --context gke_runwhen-nonprod-sandbox_us-central1_sandbox-cluster-1-cluster
This multi-line content is auto-generated and used for educational purposes. Copying and pasting the multi-line text might not function as expected.
# First, we want to list all resources with specific labels in a certain namespace and contextkubectlgetall-l${RESOURCE_LABELS}-n${NAMESPACE}--context${CONTEXT}# Then, we want to describe a specific object of a certain kind and name in the same namespace and contextkubectldescribe${OBJECT_KIND}${OBJECT_NAME}-n${NAMESPACE}--context${CONTEXT}Inthecomments,replace`${RESOURCE_LABELS}`,`${NAMESPACE}`,`${CONTEXT}`,`${OBJECT_KIND}`,and`${OBJECT_NAME}`withtheactualvaluesorvariablesyouareusing.Thiswillmakethecommandmorereadableandunderstandablefornewerorlessexperienceddevopsengineers.
Get Postgres Pod Logs & Events for Cluster acid-minimal-cluster in Namespace postgres-database¶
What does it do?
This command retrieves the names of all pods in a specific namespace and context that have certain resource labels and are currently running. It outputs only the names of the pods as a result.
This multi-line content is auto-generated and used for educational purposes. Copying and pasting the multi-line text might not function as expected.
# The following command retrieves the names of all pods with specific labels and running in a particular namespace, using a specific context.kubectlgetpods\# Uses the kubectl command-line tool to interact with Kubernetes-l${RESOURCE_LABELS}\# Specifies the resource labels to filter the pods-n${NAMESPACE}\# Specifies the namespace where the pods are located--context${CONTEXT}\# Specifies the context for accessing the Kubernetes cluster-o=name\# Formats the output to only display the names of the pods--field-selector=status.phase=Running# Filters the pods based on their running status
Get Postgres Pod Resource Utilization for Cluster acid-minimal-cluster in Namespace postgres-database¶
What does it do?
This command uses kubectl to show resource usage of pods with specific labels, including individual container resource usage, in the specified namespace and context.
Command
kubectl top pods -l cluster-name=acid-minimal-cluster --containers -n postgres-database --context gke_runwhen-nonprod-sandbox_us-central1_sandbox-cluster-1-cluster
Get Running Postgres Configuration for Cluster acid-minimal-cluster in Namespace postgres-database¶
What does it do?
This script is a bash script that performs configuration checks on two different types of PostgreSQL Operators: Crunchy and Zalando. It collects reports and issues related to the configurations and outputs them in a JSON format.
#!/bin/bash# Arrays to collect reports and issuesCONFIG_REPORTS=()ISSUES=()# Function to generate an issue in JSON format and add to ISSUES array
generate_issue(){issue=$(cat<<EOF{ "title": "Configuration issue for Postgres Cluster \`$OBJECT_NAME\` in \`$NAMESPACE\`", "description": "$1", "parameter": "$2", "current_value": "$3", "expected_value": "$4"}EOF)ISSUES+=("$issue")}# Function to display configuration and perform sanity checks for CrunchyDB PostgreSQL Operator
display_crunchy_config(){POD_NAME=$(${KUBERNETES_DISTRIBUTION_BINARY}getpods-n"$NAMESPACE"--context"$CONTEXT"-lpostgres-operator.crunchydata.com/role=master-ojsonpath="{.items[0].metadata.name}")CONFIG=$(${KUBERNETES_DISTRIBUTION_BINARY}exec-n"$NAMESPACE""$POD_NAME"--context"$CONTEXT"-c"$DATABASE_CONTAINER"--psql-Upostgres-c"SHOW ALL")echo"CrunchyDB PostgreSQL Configuration:"echo"$CONFIG"CONFIG_REPORTS+=("CrunchyDB PostgreSQL Configuration:\n$CONFIG")# Sanity Checksecho"Performing sanity checks..."if[["$CONFIG"==*"shared_buffers"*]];thenecho"shared_buffers setting is present."elsegenerate_issue"Missing critical configuration parameter""shared_buffers""None""Expected to be present"fiif[["$CONFIG"==*"max_connections"*]];thenecho"max_connections setting is present."elsegenerate_issue"Missing critical configuration parameter""max_connections""None""Expected to be present"fi# Example additional sanity check for max_connectionsMAX_CONNECTIONS=$(echo"$CONFIG"|grep-imax_connections|awk'{print $3}')if((MAX_CONNECTIONS<100));thengenerate_issue"max_connections is set to less than 100""max_connections""$MAX_CONNECTIONS"">= 100"elseecho"max_connections setting is adequate."fi# Check if PgBouncer is deployed in the statusPGB_READY=$(${KUBERNETES_DISTRIBUTION_BINARY}getpostgresclusters.postgres-operator.crunchydata.com"$OBJECT_NAME"-n"$NAMESPACE"--context"$CONTEXT"-ojsonpath="{.status.proxy.pgBouncer.readyReplicas}")if[["$PGB_READY"-gt0]];thenPGB_CONFIGMAP_NAME=$(${KUBERNETES_DISTRIBUTION_BINARY}getconfigmap-lpostgres-operator.crunchydata.com/role=pgbouncer-n"$NAMESPACE"--context"$CONTEXT"-ojsonpath="{.items[0].metadata.name}")display_pgbouncer_config"$PGB_CONFIGMAP_NAME"else{echo"PgBouncer is not deployed for CrunchyDB in the namespace $NAMESPACE."}fi}# Function to display configuration and perform sanity checks for Zalando PostgreSQL Operator
display_zalando_config(){POD_NAME=$(${KUBERNETES_DISTRIBUTION_BINARY}getpods-n"$NAMESPACE"--context"$CONTEXT"-lapplication=spilo-ojsonpath="{.items[0].metadata.name}")CONFIG=$(${KUBERNETES_DISTRIBUTION_BINARY}exec-n"$NAMESPACE""$POD_NAME"--context"$CONTEXT"-c"$DATABASE_CONTAINER"--psql-Upostgres-c"SHOW ALL")echo"Zalando PostgreSQL Configuration:"echo"$CONFIG"CONFIG_REPORTS+=("Zalando PostgreSQL Configuration:\n$CONFIG")# Sanity Checksecho"Performing sanity checks..."if[["$CONFIG"==*"shared_buffers"*]];thenecho"shared_buffers setting is present."elsegenerate_issue"Missing critical configuration parameter""shared_buffers""None""Expected to be present"fiif[["$CONFIG"==*"max_connections"*]];thenecho"max_connections setting is present."elsegenerate_issue"Missing critical configuration parameter""max_connections""None""Expected to be present"fi# Example additional sanity check for max_connectionsMAX_CONNECTIONS=$(echo"$CONFIG"|grep-imax_connections|awk'{print $3}')if((MAX_CONNECTIONS<100));thengenerate_issue"max_connections is set to less than 100""max_connections""$MAX_CONNECTIONS"">= 100"elseecho"max_connections setting is adequate."fi# Check for PgBouncerPGB_LABEL="application=pgbouncer"display_pgbouncer_config"$PGB_LABEL"}# Function to display configuration and perform sanity checks for PgBouncer
display_pgbouncer_config(){CONFIGMAP_NAME=$1if[-z"$CONFIGMAP_NAME"];thenecho"PgBouncer ConfigMap is not found in the namespace $NAMESPACE."returnfiCONFIG=$(${KUBERNETES_DISTRIBUTION_BINARY}getconfigmap"$CONFIGMAP_NAME"-n"$NAMESPACE"--context"$CONTEXT"-ojsonpath='{.data.pgbouncer\.ini}')echo"PgBouncer Configuration:"echo"$CONFIG"CONFIG_REPORTS+=("PgBouncer Configuration:\n$CONFIG")# Sanity Checksecho"Performing sanity checks..."ifgrep-q"max_client_conn"<<<"$CONFIG";thenecho"max_client_conn setting is present."elsegenerate_issue"Missing critical configuration parameter""max_client_conn""None""Expected to be present"fi# Example additional sanity check for max_client_connMAX_CLIENT_CONN=$(grep-imax_client_conn<<<"$CONFIG"|awk-F'=''{print $2}'|tr-d' ')if((MAX_CLIENT_CONN<100));thengenerate_issue"max_client_conn is set to less than 100""max_client_conn""$MAX_CLIENT_CONN"">= 100"elseecho"max_client_conn setting is adequate."fi}if[["$OBJECT_API_VERSION"==*"crunchydata.com"*]];thendisplay_crunchy_config
elif[["$OBJECT_API_VERSION"==*"zalan.do"*]];thendisplay_zalando_config
elseecho"Unsupported API version. Please specify a valid API version containing 'crunchydata.com' or 'zalan.do'."fi# Print the configuration reports and issuesOUTPUT_FILE="../config_report.out"echo"Configuration Report:">"$OUTPUT_FILE"forreportin"${CONFIG_REPORTS[@]}";doecho-e"$report">>"$OUTPUT_FILE"doneecho"">>"$OUTPUT_FILE"echo"Issues:">>"$OUTPUT_FILE"echo"[">>"$OUTPUT_FILE"forissuein"${ISSUES[@]}";doecho"$issue,">>"$OUTPUT_FILE"done# Remove the last comma and close the JSON array
sed-i'$ s/,$//'"$OUTPUT_FILE"echo"]">>"$OUTPUT_FILE"echo"Configuration report and issues have been written to $OUTPUT_FILE."
Thesecommentsprovideexplanations,contexts,examples,andclarificationsthatwouldhelpnewerorlessexperienceddevopsengineersunderstandthepurposeandfunctionalityofeachpartofthescript.
Get Patroni Output and Add to Report for Cluster acid-minimal-cluster in Namespace postgres-database¶
What does it do?
This command uses kubectl to execute a patronictl command in the specified namespace and context, targeting a specific database container within a workload. It is often used for troubleshooting or managing database clusters in Kubernetes.
This multi-line content is auto-generated and used for educational purposes. Copying and pasting the multi-line text might not function as expected.
# Retrieve the name of the pod associated with the specified workload in the given namespace and contextPOD_NAME=$(kubectlgetpods${WORKLOAD_NAME}-n${NAMESPACE}--context${CONTEXT}-ojsonpath='{.items[0].metadata.name}')# Execute a command inside the specified pod, namespace, and context, targeting a specific containerkubectlexec$POD_NAME-n${NAMESPACE}--context${CONTEXT}-c${DATABASE_CONTAINER}--patronictllistInthefirstline,weuse`kubectlgetpods`toretrieveinformationaboutthepodsassociatedwiththespecifiedworkload,namespace,andcontext.Wethenuse`jsonpath`toextractthenameofthepodandstoreitinthevariable`POD_NAME`.Inthesecondline,weuse`kubectlexec`toexecuteacommandinsidethespecifiedpod,namespace,andcontext.Wealsospecifythetargetcontainerusingthe`-c`flag,andthenrunthecommand`patronictllist`withinthatcontainer.
Fetch Patroni Database Lag for Cluster acid-minimal-cluster in Namespace postgres-database¶
What does it do?
This command is using kubectl to execute a patronictl list command in a specific pod and container within a Kubernetes cluster. It's pulling information about the pods and containers from the specified namespace and context.
This multi-line content is auto-generated and used for educational purposes. Copying and pasting the multi-line text might not function as expected.
# Set variables for better readability and reusabilityWORKLOAD_NAME="your-workload-name"NAMESPACE="your-namespace"CONTEXT="your-context"DATABASE_CONTAINER="your-database-container"# Get the pod name of the specified workload in the specified namespace and contextPOD_NAME=$(kubectlgetpods${WORKLOAD_NAME}-n${NAMESPACE}--context${CONTEXT}-ojsonpath='{.items[0].metadata.name}')# Execute a command inside the specified pod, namespace, and context, targeting the specified database containerkubectlexec$POD_NAME-n${NAMESPACE}--context${CONTEXT}-c${DATABASE_CONTAINER}--patronictllist-fjson
Check Database Backup Status for Cluster acid-minimal-cluster in Namespace postgres-database¶
What does it do?
This script is a Bash shell script that checks the health of backups for Postgres clusters managed by two different Kubernetes operators - CrunchyDB and Zalando PostgreSQL. It generates a report on the status of the backups and any issues encountered, based on the maximum acceptable age for the backup.
#!/bin/bash# Set the maximum acceptable age of the backup (in seconds) based on BACKUP_MAX_AGE environment variableMAX_AGE=$((BACKUP_MAX_AGE*3600))# Arrays to store backup reports and issuesBACKUP_REPORTS=()ISSUES=()# Function to generate an issue in JSON format
generate_issue(){cat<<EOF{ "title": "Backup health issue for Postgres Cluster \`$OBJECT_NAME\` in \`$NAMESPACE\`", "description": "$1", "backup_completion_time": "$2", "backup_age_hours": "$3"}EOF}# Function to check CrunchyDB PostgreSQL Operator backup
check_crunchy_backup(){POSTGRES_CLUSTER_JSON=$(${KUBERNETES_DISTRIBUTION_BINARY}getpostgresclusters.postgres-operator.crunchydata.com$OBJECT_NAME-n"$NAMESPACE"--context"$CONTEXT"-ojson)LATEST_BACKUP_TIME=$(echo"$POSTGRES_CLUSTER_JSON"|jq-r'.status.pgbackrest.scheduledBackups | max_by(.completionTime) | .completionTime')LATEST_BACKUP_TIMESTAMP=$(date-d"$LATEST_BACKUP_TIME"+%s)CURRENT_TIMESTAMP=$(date+%s)BACKUP_AGE=$((CURRENT_TIMESTAMP-LATEST_BACKUP_TIMESTAMP))BACKUP_AGE_HOURS=$(awk"BEGIN {print $BACKUP_AGE/3600}")BACKUP_REPORTS+=("CrunchyDB Backup completed at $LATEST_BACKUP_TIME with age $BACKUP_AGE_HOURS hours.")if["$BACKUP_AGE"-gt"$MAX_AGE"];thenISSUES+=("$(generate_issue"The latest backup for the CrunchyDB PostgreSQL cluster \`$OBJECT_NAME\` is older than the acceptable limit of $BACKUP_MAX_AGE hour(s).""$LATEST_BACKUP_TIME""$BACKUP_AGE_HOURS")")elseBACKUP_REPORTS+=("CrunchyDB Backup is healthy. Latest backup completed at $LATEST_BACKUP_TIME.")fi}# Function to check Zalando PostgreSQL Operator backup
check_zalando_backup(){# Assuming that we need to log in to the database to check backup statusPOD_NAME=$(${KUBERNETES_DISTRIBUTION_BINARY}getpods-n"$NAMESPACE"--context"$CONTEXT"-lapplication=spilo-ojsonpath="{.items[0].metadata.name}")LATEST_BACKUP_TIME=$(${KUBERNETES_DISTRIBUTION_BINARY}exec-n"$NAMESPACE""$POD_NAME"--context"$CONTEXT"-c"$DATABASE_CONTAINER"--bash-c'psql -U postgres -t -c "SELECT MAX(backup_time) FROM pg_stat_archiver;"')LATEST_BACKUP_TIMESTAMP=$(date-d"$LATEST_BACKUP_TIME"+%s)CURRENT_TIMESTAMP=$(date+%s)BACKUP_AGE=$((CURRENT_TIMESTAMP-LATEST_BACKUP_TIMESTAMP))BACKUP_AGE_HOURS=$(awk"BEGIN {print $BACKUP_AGE/3600}")BACKUP_REPORTS+=("Zalando Backup completed at $LATEST_BACKUP_TIME with age $BACKUP_AGE_HOURS hours.")if["$BACKUP_AGE"-gt"$MAX_AGE"];thenISSUES+=("$(generate_issue"The latest backup for the Zalando PostgreSQL cluster is older than the acceptable limit of $BACKUP_MAX_AGE hour(s).""$LATEST_BACKUP_TIME""$BACKUP_AGE_HOURS")")elseBACKUP_REPORTS+=("Zalando Backup is healthy. Latest backup completed at $LATEST_BACKUP_TIME.")fi}# Check the backup based on API versionif[["$OBJECT_API_VERSION"==*"crunchydata.com"*]];thencheck_crunchy_backup
elif[["$OBJECT_API_VERSION"==*"zalan.do"*]];thencheck_zalando_backup
elseecho"Unsupported API version: $OBJECT_API_VERSION. Please specify a valid API version containing 'postgres-operator.crunchydata.com' or 'acid.zalan.do'."fiOUTPUT_FILE="../backup_report.out"
rm-f$OUTPUT_FILE# Print the backup reports and issuesecho"Backup Report:">"$OUTPUT_FILE"echo"Maximum age for last backup is set to: $BACKUP_MAX_AGE hour(s)">>"$OUTPUT_FILE"forreportin"${BACKUP_REPORTS[@]}";doecho"$report">>"$OUTPUT_FILE"doneecho"">>"$OUTPUT_FILE"echo"Issues:">>"$OUTPUT_FILE"echo"[">>"$OUTPUT_FILE"forissuein"${ISSUES[@]}";doecho"$issue,">>"$OUTPUT_FILE"done# Remove the last comma and close the JSON array
sed-i'$ s/,$//'"$OUTPUT_FILE"echo"]">>"$OUTPUT_FILE"
Run DB Queries for Cluster acid-minimal-cluster in Namespace postgres-database¶
What does it do?
This script is designed to execute health queries for different versions of PostgreSQL operators in a Kubernetes environment. It generates a report of query results and any issues encountered during execution, and then writes the report to an output file in JSON format.
#!/bin/bash# Arrays to collect reports and issuesQUERY_REPORTS=()ISSUES=()# Function to sanitize a string for JSON compatibility
sanitize_string(){echo"$1"|sed's/["]/ /g'|tr'\n'' '|tr'\r'' '}# Function to generate an issue in JSON format and add to ISSUES array
generate_issue(){localdescription=$(sanitize_string"$1")localquery=$(sanitize_string"$2")localerror=$(sanitize_string"$3")issue=$(cat<<EOF{ "title": "Health Query Issue", "description": "$1", "description": "$description", "query": "$query", "error": "$error"}EOF)ISSUES+=("$issue")}# Function to execute health queries for CrunchyDB PostgreSQL Operator
execute_crunchy_queries(){# Getting the name of the podPOD_NAME=$(${KUBERNETES_DISTRIBUTION_BINARY}getpods-n"$NAMESPACE"--context"$CONTEXT"-lpostgres-operator.crunchydata.com/role=master-ojsonpath="{.items[0].metadata.name}")# Iterating through each health query and executing itwhileIFS=read-rquery;doecho"Executing query: $query"result=$(${KUBERNETES_DISTRIBUTION_BINARY}exec-n"$NAMESPACE""$POD_NAME"--context"$CONTEXT"--container"$DATABASE_CONTAINER"--bash-c"psql -U postgres -c \"$query\""2>&1)if[$?-eq0];thenecho"Query executed successfully."QUERY_REPORTS+=("Query: $query\nResult:\n$result\n")elseecho"Query execution failed."generate_issue"Failed to execute health query""$query""$result"fidone<<<"$HEALTH_QUERIES"}# Function to execute health queries for Zalando PostgreSQL Operator
execute_zalando_queries(){# Getting the name of the podPOD_NAME=$(${KUBERNETES_DISTRIBUTION_BINARY}getpods-n"$NAMESPACE"--context"$CONTEXT"-lapplication=spilo-ojsonpath="{.items[0].metadata.name}")# Iterating through each health query and executing itwhileIFS=read-rquery;doecho"Executing query: $query"result=$(${KUBERNETES_DISTRIBUTION_BINARY}exec-n"$NAMESPACE""$POD_NAME"--context"$CONTEXT"--container"$DATABASE_CONTAINER"--bash-c"psql -U postgres -c \"$query\""2>&1)if[$?-eq0];thenecho"Query executed successfully."QUERY_REPORTS+=("Query: $query\nResult:\n$result\n")elseecho"Query execution failed."generate_issue"Failed to execute health query""$query""$result"fidone<<<"$HEALTH_QUERIES"}# Setting up health queries based on the OBJECT_API_VERSIONHEALTH_QUERIES=$QUERYif[["$OBJECT_API_VERSION"==*"crunchydata.com"*]];thenexecute_crunchy_queries
elif[["$OBJECT_API_VERSION"==*"zalan.do"*]];thenexecute_zalando_queries
elseecho"Unsupported API version. Please specify a valid API version containing 'crunchydata.com' or 'zalan.do'."fi# Print the query reports and issuesOUTPUT_FILE="../health_query_report.out"echo"Health Query Report:">"$OUTPUT_FILE"forreportin"${QUERY_REPORTS[@]}";doecho-e"$report">>"$OUTPUT_FILE"doneecho"">>"$OUTPUT_FILE"echo"Issues:">>"$OUTPUT_FILE"echo"[">>"$OUTPUT_FILE"forissuein"${ISSUES[@]}";doecho"$issue,">>"$OUTPUT_FILE"done# Remove the last comma and close the JSON array
sed-i'$ s/,$//'"$OUTPUT_FILE"echo"]">>"$OUTPUT_FILE"echo"Health query report and issues have been written to $OUTPUT_FILE."