Skip to main content


Ok so recently I ran into a hiccup with an issue that effects how my jetstream and daemons run on my #friendica instance, as I am still working on the what I created a workaround that makes sure that they run as they should, I made one more semi useful script for a resource control hack, that helps throttle lsphp to reduce server loads on limited resources without compromising flow of feeds, then I have made some cron adjustments that may or may not help your #friendica instance; I am sharing my little scripts and hacks for those who may have resource issues where their daemon and jetstream keep getting killed, or where they are on a limited server environment, I offer no promise nor support, but for me it is working nicely;
Again I make no claims of actual usability or benefit, as of posting this it seems to be working well on my #friendica instance;


Crons

# --- Friendica Automation Suite ---
MAILTO="your-email@domain.com"
SHELL="/bin/bash"

# Core background tasks
0 */1 * * * /home/USER/friendica_cron.sh >/dev/null 2>&1
*/15 * * * * /usr/bin/flock -n /tmp/fc_worker.lock -c cd /home/USER/public_html && bin/console worker >/dev/null 2>&1

# Maintenance: Monthly Smarty purge (1st of the month)
0 0 1 * * /usr/bin/rm -rf /home/USER/public_html/view/smarty/compile/* >/dev/null 2>&1

# Maintenance: Weekly Storage & Cache clearing (Sundays)
0 1 * * 0 cd /home/USER/public_html; bin/console storage clear >/dev/null 2>&1
30 1 * * 0 cd /home/USER/public_html; bin/console cache clear >/dev/null 2>&1

# Watchdogs: StayAlive & Bouncer
@reboot /bin/bash /home/USER/scripts/StayAlive.sh > /dev/null 2>&1 &
0 * * * * pgrep -f StayAlive.sh > /dev/null || /bin/bash /home/USER/scripts/StayAlive.sh > /dev/null 2>&1 &

@reboot /bin/bash /home/USER/scripts/bouncer.sh > /dev/null 2>&1 &
* * * * * pgrep -f bouncer.sh > /dev/null || /bin/bash /home/USER/scripts/bouncer.sh > /dev/null 2>&1 &


README

⚙️ The Friendica Automation Suite (Crontab)
Scheduled Maintenance & Self-Healing Guards
This configuration file acts as the "Brain" of your Friendica instance. It manages the scheduling for background tasks, periodic cache cleaning, and—most importantly—ensures your custom stability scripts (Bouncer and StayAlive) never stop running.

⚠️ Implementation Note: Replace YOUR_HOME, YOUR_USER, and YOUR_INSTANCE_ROOT with your actual server paths.

These Crons are provided "as-is" for educational and personal use.

They will not be maintained or updated.

No support or bug fixes will be provided.

Use at your own risk..

🛠 What This Schedule Manages
1. Core Background Tasks
Hourly Maintenance: Runs friendica_cron.sh to handle general background cleanup.

Frequent Worker: Executes the Friendica worker every 15 minutes to keep the federation queue moving.

2. Housekeeping & Performance
To prevent disk bloat and keep the interface snappy, the following cleanup tasks are automated:

Monthly Smarty Purge: Clears compiled template files on the 1st of every month to refresh the UI engine.

Weekly Storage Cleanup: Clears the avatar and storage cache every Sunday at 1:00 AM.

Weekly Node Cache: Flushes the node cache every Sunday at 1:30 AM to keep remote directory info fresh.

3. The "Immortal" Guard System
The most critical part of this setup is the Watchdog for the Watchdogs.

Boot Persistence: Both the StayAlive.sh (Service Guard) and bouncer.sh (Resource Throttle) are set to trigger immediately upon a server reboot (@reboot).

The Safety Check: Every hour (for StayAlive) and every minute (for the Bouncer), the system checks if the scripts are still running. If they’ve been killed by the system, it automatically restarts them.

📋 Installation
To apply these rules to your server:

Open your crontab editor:

Bash
crontab -e
Paste the configuration, ensuring your paths are correct.

Save and exit.

🔍 Pro-Tip: Monitoring
You have MAILTO set at the top. If your server is configured for mail, any errors from these tasks will be sent directly to your inbox. If you prefer to log to a file instead, you can change the >/dev/null 2>&1 at the end of the lines to >> ~/cron_log.txt 2>&1.


Bouncer

#!/bin/bash

# These are the Bouncer's Rules
MAX_KIDS=3        # Only 3 people in the kitchen at once
MAX_HEAT=2        # Only 2% energy allowed
CHECK_TIME=5      # Wait 5 seconds before checking again

while true
do
  # 1. Count how many 'lsphp' workers are busy with your site
  CURRENT_KIDS=$(pgrep -f "lsphp.*YOUR_INSTANCE_ROOT" | wc -l)

 # Lower priority for all lsphp processes to keep the server cool
    pgrep -u *YOUR_USER lsphp | xargs -r renice -n 15 > /dev/null 2>&1

  # 2. If there are more than 3...
  if [ "$CURRENT_KIDS" -gt "$MAX_KIDS" ]; then
    echo "Bouncer: Too many kids! Making the extras wait in the hallway."
    
    # This finds the newest workers and tells them to 'STOP' (Pause)
    # They stay in line, but they don't use any CPU while paused.
    pgrep -f "lsphp.*YOUR_INSTANCE_ROOT" | tail -n +$((MAX_KIDS+1)) | xargs kill -STOP
    
    # Wait for things to cool down
    sleep $CHECK_TIME
    
    # Tell them they can 'CONT' (Continue) ONE BY ONE
        echo "$EXTRAS" | while read -r kid_pid; do
            if [ ! -z "$kid_pid" ]; then
                kill -CONT "$kid_pid"
                echo "Bouncer: Letting kid $kid_pid back in."
                sleep 1 
            fi
        done
  fi

  # Take a small breath so the Bouncer doesn't get tired
  sleep 1
done


README

🚪 The LSPHP Bouncer
Resource Throttle & Process Queue for Shared Hosting
The LSPHP Bouncer is a lightweight Bash watchdog designed for users on LiteSpeed-based hosting. It prevents your account from hitting "Resource Limit Reached" errors (508 errors) by pausing excess PHP processes (lsphp) instead of letting them crash the site or trigger a provider-level kill.

⚠️ Maintenance Notice
This project is provided "as-is" for educational and personal use.

It will not be maintained or updated.

No support or bug fixes will be provided.

Use at your own risk..

🧐 How It Works
LiteSpeed servers often spawn many lsphp workers to handle incoming traffic. If too many start at once, your host might lock your account for exceeding CPU or process limits.

The Headcount: Every second, the Bouncer counts how many PHP workers are active for your specific site.

The Velvet Rope: If the count exceeds your MAX_KIDS limit, the Bouncer sends a SIGSTOP signal to the extra processes. This pauses them—they stay in the queue but stop consuming CPU cycles.

The Entry: After a short cooldown (CHECK_TIME), the Bouncer sends a SIGCONT signal, letting those processes finish their work one by one.

🛠 Configuration
Open the script and adjust these "House Rules" to match your hosting plan:

MAX_KIDS: The maximum number of PHP processes you are allowed (e.g., 3).

CHECK_TIME: How many seconds to pause the "extras" before letting them work again.

Process Filter: The script looks for "lsphp.*your.domain". Ensure the string matches what shows up in your process monitor (usually top or htop).

🚀 Setup & Execution
1. Make it Executable
Bash
chmod +x bouncer.sh
2. Run the Bouncer
To keep the Bouncer running even after you log out of SSH:

Bash
nohup ./bouncer.sh > /dev/null 2>&1 &
📈 Why use this?
Avoids 508 Errors: Instead of the server showing a "Limit Reached" page, the site just feels a tiny bit slower while the Bouncer staggers the load.

CPU Friendly: Paused processes (kill -STOP) consume zero CPU, helping you stay under the "Energy" or "Heat" limits of your host.

Specific Targeting: Using pgrep -f, it only targets your specific site's workers, leaving other processes alone.


Persistent Service Guard

#!/bin/bash

# --- CONFIGURATION (Users change these) ---
# The absolute path to your application root
SITE_ROOT="/path/to/your/app"

# The path to the PHP binary (usually 'php' or a specific version)
PHP_CLI="/usr/bin/php"

# Name of the console executable
CONSOLE_APP="bin/console.php"

# Where to save the logs
LOG_FILE="./guard_log.txt"

# List of services to monitor
SERVICES=("daemon" "jetstream")

# --- CORE LOGIC (Do not edit below) ---
CONSOLE_PHP="$SITE_ROOT/$CONSOLE_APP"

echo "$(date): Persistent Guard started for services: ${SERVICES[*]}" >> "$LOG_FILE"

while true; do
    for SERVICE in "${SERVICES[@]}"; do
        # Check status
        STATUS=$($PHP_CLI $CONSOLE_PHP $SERVICE status 2>&1)

        if [[ "$STATUS" != *"is running"* ]]; then
            echo "$(date): $SERVICE is DOWN. Attempting start..." >> "$LOG_FILE"
            $PHP_CLI $CONSOLE_PHP $SERVICE start >> "$LOG_FILE" 2>&1
        fi
    done
    sleep 60
done


README

Persistent Service Guard
A robust, lightweight Bash-based watchdog script designed to monitor and automatically restart background services (such as Friendica daemons or Jetstream workers) for PHP-based applications.

⚠️ Maintenance Notice
This project is provided "as-is" for educational and personal use.

It will not be maintained or updated.

No support or bug fixes will be provided.

Use at your own risk.

🚀 What It Does
The Service Guard addresses the common issue where background processes or daemons on shared or private hosting may crash or be killed by the system.

Active Monitoring: It loops indefinitely, checking the status of defined services every 60 seconds.

Automatic Recovery: If a service is reported as "not running," the script immediately attempts to restart it.

Logging: Every check, failure, and restart attempt is timestamped and recorded for auditing.

🛠 Setup & Usage
1. Configuration
Before running, ensure the following variables in guard.sh match your environment:

SITE_ROOT: The absolute path to your application root.

PHP_CLI: The path to the PHP binary (e.g., /usr/bin/php).

SERVICES: The names of the services to monitor (e.g., "daemon" "jetstream").

2. Permissions
Grant execution rights to the script:

Bash
chmod +x guard.sh
3. Execution
Run the script in the background to ensure it persists after your session ends:

Bash
nohup ./guard.sh > /dev/null 2>&1 &
📊 Managing Logs
The script appends data to guard_log.txt. To prevent this file from consuming excessive disk space, use one of the following methods:

Manual Truncation
Clear the log without stopping the script:

Bash
> guard_log.txt
Automatic Log Rotation (Improvement Example)
To automate log management, add this logic inside the while loop of the script:

Bash
# Improvement: Simple Log Rotation
MAX_SIZE=1048576 # 1MB in bytes
FILE_SIZE=$(stat -c%s "$LOG_FILE")

if [ "$FILE_SIZE" -gt "$MAX_SIZE" ]; then
echo "$(date): Log rotated (size limit reached)" > "$LOG_FILE"
fi
📈 Potential Improvements
Users wishing to extend the script's functionality can implement the following:

1. Auto-Discovery
Replace the hardcoded PHP_CLI path with dynamic discovery:

Bash
PHP_CLI=$(which php)
2. Failure Notifications
Integrate curl to send alerts to Discord or Telegram when a service fails:

Bash
# Discord Notification Example
curl -H "Content-Type: application/json" -X POST -d "{\"content\": \"⚠️ Alert: $SERVICE has crashed. Restarting...\"}" YOUR_WEBHOOK_URL
3. Dependency Validation
Add a check to verify the application exists before the loop starts:

Bash
if [ ! -f "$CONSOLE_PHP" ]; then
echo "Error: Console application not found at $CONSOLE_PHP"
exit 1
fi


⚖️ License (MIT)
Copyright (c) 2026 pasjrwoctx👽 (Philip A. Swiderski Jr.)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

@Friendica Support @Friendica Developers @Friendica Admins

You can encourage my continued useless ideas, and by doing so your helping to feed, house and clothe a #disabled man living in #poverty, $5-10-15 It All Helps, via #cashapp at $woctxphotog or via #paypal at https://www.paypal.com/donate?campaign_id=5BN5MB5BVQL22