Skip to main content

4 posts tagged with "Linux"

View all tags

cPanel Crash Loop? mycpanel.pem Needs Cert + Key in One File

Β· 6 min read

After a deploy script replaced the cPanel service certificate, cpanel.service fell into a crash loop: nothing listening on 2083/2087, and both WHM and cPanel were unreachable.

Encountered this while running managed hosting for a leading manufacturer's China site β€” an ongoing engagement covering monitoring, backups, and certificate deployment on a production cPanel/WHM server.

TL;DR​

One cause: /var/cpanel/ssl/cpanel/mycpanel.pem must be a single PEM combining the leaf certificate and the private key (the same shape as the pure-ftpd bundle), with the chain in mycpanel.cabundle; the split crt/key formats used by dovecot/exim are not interchangeable, and writing a fullchain into the pem is exactly the crashing form. A second trap sits in verification: restartsrv_cpsrvd exit 0 and an active unit mean nothing β€” SSL setup fails 1-6 seconds after start, so recovery is proven on port 2083.

Symptoms: panel down, service crash loop​

Right after writing the new certificate and restarting, the panel hostname stopped responding and both 2083/2087 had no listener. The journal and error_log show two faces of the same failure:

cpanel.service: Main process exited, status=25
cpsrvd: Failed to load SSL libraries or certificate from
/var/cpanel/ssl/cpanel/ at cpsrvd.pl line 724

The standard recovery path came first: restartsrv_cpsrvd returned 0 and systemctl is-active cpanel reported active β€” it looked recovered. Seconds later 2083 was still silent and the panel still unreachable, crash loop intact. Those two green lights that aren't green are the second topic of this post.

Root cause: mycpanel.pem is cert + key combined, not the chain​

cPanel's format requirement for cpsrvd (the panel service) differs from most services: mycpanel.pem holds the leaf certificate and private key combined, while the chain lives separately in mycpanel.cabundle. That matches the pure-ftpd bundle shape; dovecot/exim use split crt/key files β€” the three formats are not interchangeable:

ServiceCertificate file shape
cpsrvd (cPanel/WHM panel)mycpanel.pem combined (leaf+key) + mycpanel.cabundle (chain)
pure-ftpdcombined bundle (same shape as cpsrvd)
dovecot / eximsplit crt/key

The failing script wrote a fullchain β€” chain only, no private key β€” into mycpanel.pem. At startup cpsrvd loads SSL, finds no private key, and fails at cpsrvd.pl line 724; systemd starts the unit, the process exits immediately, status 25, and the cycle repeats. The certificate itself was fine; only the file shape was wrong.

One distinction worth making: this is the cPanel service certificate (hostname-level, serving the panel ports). Site domain certificates go through AutoSSL β€” a separate track; when issuance stalls there, check the exclusion list first, see cPanel AutoSSL Not Issuing? Self-Signed Certificate Fix.

The false-success detour: restartsrv exit 0 β‰  cpsrvd alive​

Timing is what makes this misleading. SSL setup fails 1-6 seconds after systemd starts the unit, while restartsrv_cpsrvd returned its 0 at start-up time and is-active sampled the pre-crash window β€” both signals landed before the crash, so both were green.

That pair of green lights is exactly what the triage trusted first: recovery declared on restartsrv 0 + active, then the panel still down, and only a direct curl against 2083 exposed the SSL load failure. Since then, liveness for cpsrvd on this server is judged only by port probes: curl -sv https://hostname:2083 or openssl s_client -connect hostname:2083, requiring a completed handshake with certificate details.

"State signal disconnected from actual usability" is not an one-off β€” the reverse variant, systemctl showing inactive while the process runs, is covered in systemctl Shows inactive But the Process Is Running? Bare-Process Health Check False Negative. The shared conclusion: probe the service through its own port/protocol, not through the process manager's word.

Fix: write per-service formats, verify on the port​

The repair is three steps: combined PEM in place, chain separated, acceptance on the port.

# leaf.pem = server certificate (leaf), privkey.pem = private key, cabundle.pem = chain
cat leaf.pem privkey.pem > /var/cpanel/ssl/cpanel/mycpanel.pem
cp cabundle.pem /var/cpanel/ssl/cpanel/mycpanel.cabundle
chown cpanel:cpanel /var/cpanel/ssl/cpanel/mycpanel*
chmod 660 /var/cpanel/ssl/cpanel/mycpanel*
systemctl restart cpanel

Acceptance ignores status signals and reads the port only:

curl -sv https://<hostname>:2083 -o /dev/null 2>&1 | grep -E 'subject|expire'
curl -sv https://<hostname>:2087 -o /dev/null 2>&1 | grep -E 'subject|expire'

Both commands must print the certificate subject and expiry before the panel ports count as recovered. After this incident the deploy script fixed the combined format in place and gained an end-to-end check: the hook prints DEPLOY-OK with all four service ports green.

For the other services, match the table above: dovecot/exim get split crt/key, pure-ftpd and cpsrvd get combined bundles. One certificate, three file shapes, none interchangeable.

Notes

  • Content order in mycpanel.pem: leaf certificate first, private key after; the chain goes into mycpanel.cabundle, never into the pem.
  • Permissions cpanel:cpanel 660 β€” too wide or too narrow, cpsrvd may refuse to load.
  • Acceptance is port probes only; restartsrv's exit code and is-active are not liveness evidence.
  • More AlmaLinux 10 + cPanel close-out pitfalls (TFA, missing resources, domain mounting): AlmaLinux 10 + cPanel: New-Server Pitfalls from TFA to DNS.

FAQ​

What goes in mycpanel.pem vs mycpanel.cabundle?​

mycpanel.pem is one PEM holding the leaf certificate followed by the private key, owned cpanel:cpanel with 660 permissions; the intermediate chain goes separately into mycpanel.cabundle. Writing a fullchain into mycpanel.pem produces exactly this crash β€” no private key in the file, cpsrvd fails SSL loading, and systemd reports status=25 in a loop.

Can the dovecot/exim certificate files be reused for cpsrvd?​

Not directly. cpsrvd expects a combined PEM (the same shape as the pure-ftpd bundle), while dovecot/exim use separate crt/key files β€” the formats are not interchangeable across the services. The same certificate must be written out in each service's own format.

restartsrv returned 0 and systemctl says active β€” is cpsrvd really alive?​

Neither signal is a liveness proof: SSL setup failed 1-6 seconds after systemd started the unit, long after restartsrv printed its exit 0, and is-active still showed active in that window. Probe port 2083 instead (curl -sv or openssl s_client); a completed TLS handshake is the only evidence that counts.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Does rsync -a Preserve Timestamps? Why Fresh Backups Vanish

Β· 8 min read

In a cron-driven rsync-plus-find backup pipeline that keeps 7 days of upload snapshots by directory name, the pull script ran fine by hand but, once scheduled, three consecutive snapshot directories showed files = 0 β€” the files landed, then vanished.

TL;DR​

The a in rsync -a (archive) propagates the source's mtimes to the target, directories included β€” the target directory's mtime means "when the source last changed", never "when this pull finished". If the source's top-level directory is frozen (new files only land in deep subdirectories), that value stays in the past, and a trailing find -mtime +7 cleanup judges the just-pulled snapshot "7 days old" and deletes the whole directory. "Manual runs always work, cron always fails" is a false correlation: manual testing only ever runs the rsync line, never the cleanup. Fix: judge retention by directory-name dates, and record pull completion in a marker file's mtime.

Symptoms: fresh snapshots vanish​

The scheduled pipeline's signature is "pulled, then deleted": the snapshot directory exists with no transport errors in the logs, yet files = 0; run the same script by hand and every file is there. Three runs in a row.

The usual suspects were eliminated one by one: CRLF line endings, fd handling around flock, disk space, cron-vs-terminal environment differences, execution shape (an inline heredoc one-liner vs the script file) β€” all negative. Along the way a strong false correlation formed: "the script always fails, the inline version always works", and the investigation chased execution shapes for two loops.

The turn came from strace: in the failing runs the transfer was complete β€” the directory tree's mkdir calls and the jpg bytes landing were all on record. In other words rsync finished its job and the files disappeared afterwards. Moving attention from "the transfer" to "which line runs after the transfer" surfaced the cleanup line at the bottom of the script.

The database side of this same pipeline has a sibling pitfall: pg_dump backups with no data? FORCE RLS binds owners too β€” the same "command exits normally, content is empty" shape.

Root cause: rsync -a resets the target's mtimes​

The cleanup didn't delete "files that never arrived" β€” it deleted "directories judged old", because the retention check read the wrong clock. Three links chained; remove any one and nothing happens:

Link 1: -a preserves the source's timestamps, directories included. -a equals -rlptgoD; -t preserves mtimes and -r recurses. After the sync, the target tree's mtime = the source's directory mtime, and the moment "this pull finished" is recorded nowhere in the synced paths.

Link 2: the source's top-level directory mtime is frozen. New attachments all land in deep subdirectories, so uploads/ itself hasn't changed since Oct 30. Every snapshot inherits that same stale value at its top level.

Link 3: the retention check find -mtime +7. Today is Nov 23; the snapshot's top-level mtime is Oct 30 β€” 24 days apart, beyond the 7-day retention. -mtime +7 matches, and the directory is deleted. Every run: pulled, then deleted.

Root-cause chain: rsync -a carries the source&#39;s frozen mtime to the target, and find -mtime +7 judges the fresh snapshot stale

"Inline always works" falls out of the same chain: inline testing only ever runs the transfer lines and never the cleanup, so it cannot fail β€” the real difference from the script is not execution shape but whether the find line runs.

A minimal reproduction shows who decides the mtime:

mkdir -p /tmp/demo/src/uploads/2026-11-23
echo x > /tmp/demo/src/uploads/2026-11-23/a.jpg
touch -d '2026-10-30' /tmp/demo/src/uploads # freeze the top level

mkdir -p /tmp/demo/dst
rsync -a /tmp/demo/src/uploads /tmp/demo/dst/snap

stat -c '%y %n' /tmp/demo/dst/snap # 2026-10-30 ← inherited
find /tmp/demo/dst -maxdepth 1 -type d -mtime +7 -print
# β†’ /tmp/demo/dst/snap ← exactly what the cleanup deletes

Fix: judge retention by directory names, mark completion with a file​

The fix replaces the clock the retention check reads β€” not mtime but the date in the directory name; and "when this pull finished" gets its own record in a marker file the sync never touches.

# Retention: compare directory-name dates (ISO order == lexicographic order)
cutoff=$(date -d '7 days ago' +%Y-%m-%d)
for d in /data/snapshots/20*-*-*; do
name=$(basename "$d")
[[ "$name" < "$cutoff" ]] && rm -rf "$d"
done

# Completion time: touch a marker after the pull; later checks read its mtime
rsync -a "$SRC_HOST:uploads/" "$SNAP_DIR/"
touch "$SNAP_DIR/.pull-complete"
# How long since completion: stat -c %Y "$SNAP_DIR/.pull-complete"

The two clocks have separate jobs: directory-name dates answer "should this snapshot be kept", the marker's mtime answers "how long has this pull been running, is it stuck". Both avoid the mtime that rsync writes, because that field means "when the source changed", not "when I pulled".

After the fix landed in those two places, the cron runs stopped showing files = 0.

Scenario 2: root gets Permission denied on /tmp lock files? fs.protected_regular​

Even root gets rejected: on the same box, root opening an existing lock file with open(O_CREAT) in /tmp β€” a file owned by someone else β€” fails with EACCES. Ubuntu's fs.protected_regular applies to sticky directories and root has no exemption. Put lock and swap files in /run, not /tmp.

Scenario 3: can't find the rsync read-only restriction? It's on the dedicated transfer user​

Nothing shows up on the usual login account because the restriction lives in the command= option of authorized_keys for a dedicated transfer user (rrsync). When auditing ssh restrictions, first work out which user a key belongs to, then read that user's authorized_keys.

On rsync 3.2.7, a --link-dest pointing at a nonexistent path only prints a warning and still exits 0 β€” not fatal, but the hard-link space saving silently disappears for that run. Check the link-dest target exists before running, or alert on the warning.

Scenario 5: grep $'\r' always matches over ssh? A false positive from nested quoting​

Detecting CRLF remotely with grep -c $'\r' fails under nested quoting: by the time it reaches the remote shell, $'\r' is treated as a plain pattern and matches everything. Detect CR with awk '/\r/' instead.

Before you ship

  • For any retention / cleanup / cooldown check, avoid fields the transfer tool rewrites: -a resets directory mtimes β€” judge by directory-name dates or a completion marker.
  • Dry-run handwritten cleanups with -print for a few rounds before switching to -delete.
  • The --link-dest target must exist; 3.2.7 only warns and exits 0 on a dangling path.
  • Put lock and swap files in /run to stay clear of /tmp's fs.protected_regular.

FAQs​

Does rsync -a preserve timestamps?​

Yes. -a equals -rlptgoD: -t preserves mtimes and -r recurses, so directory mtimes are carried over from the source as well. The target's mtime means "when the source last changed", not "when this pull happened" β€” record the pull time in a marker file instead.

How do I delete files older than 7 days with find safely?​

find /dir -mtime +7 is the usual one-liner, but never key a retention policy on mtimes that rsync controls β€” a pull with -a rewrites them. Compare zero-padded directory-name dates or a completion marker's timestamp, and verify the hit set with -print before switching to -delete.

Why does my cron rsync job produce empty backup directories?​

In this failure the transfer itself completed every run (strace showed the full tree and jpgs landing), but a trailing find -mtime +7 cleanup deleted the just-pulled snapshot β€” three consecutive runs showed files = 0. Separate the transfer from the cleanup and log the cleanup decision.

What should I use instead of mtime for backup retention?​

Directory-name dates (ISO format compares lexicographically) or a .pull-complete marker touched after each pull, read back with stat. Neither is rewritten by rsync -a; the same rule applies to row-count style checks β€” don't rely on fields the transfer tool overwrites.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Aliyun Assistant Kills nohup Jobs? Escape with setsid

Β· 6 min read

While using Aliyun Cloud Assistant RunCommand to start an strace sampler, a watch loop and a periodic sampler on a server, the background jobs were silently reaped the moment the call returned β€” the output was an empty file, or a half file with exactly one sample, and nothing ever logged an error.

Ran into this while providing managed hosting for a WordPress site in China β€” full-site migration, image CDN offload, daily backups and automated patrols.

TL;DR​

When a Cloud Assistant invocation ends, the agent cleans up the background processes derived from it, and nohup does not save them β€” it only ignores SIGHUP and redirects output, leaving the process in the original session, right inside the cleanup's reach. A new session via setsid is what escapes: setsid nohup cmd < /dev/null &. And before reading results back, verify the output file's line count and mtime β€” do not read an empty file as "the command never ran".

Symptoms: the call returns, the background jobs vanish​

Background jobs started with nohup cmd & inside one RunCommand invocation died in three different shapes:

JobHow it died
strace samplerOutput file never created at all
Periodic sampler v1Wrote exactly one sample, then nothing
cpdavd watcher, first versionReaped; process gone

All three share two traits: the invocation itself returned Success, and the server logged no error anywhere. Searching "nohup process disappeared" mostly points at SIGHUP β€” but nohup was already in place.

Root cause: nohup never changes the session, and cleanup sweeps by session​

nohup's contract is two lines long: ignore SIGHUP, redirect output to nohup.out. What it does not do is change the session β€” the process stays inside the session the Cloud Assistant agent created for this invocation. When the invocation finishes, the agent cleans up the processes derived from it, grouped by session, and nohup jobs fall squarely inside.

setsid is the semantics that actually addresses this: it puts the new process into a brand-new session, detached from the invocation's. Detached, the end-of-invocation sweep never reaches it β€” verified across all three job types, all of which survived once setsid went in.

One honest boundary: whether the agent sweeps by process group or by session was not verified at source level. But "leave the original session and you survive" held as a sufficient condition on every job tested, and that is enough.

Fix: the setsid three-piece form, plus output verification​

Detaching from session, terminal and foreground in one line:

# Long-running job started from inside a Cloud Assistant script (sampler example)
setsid nohup /usr/local/bin/sampler --interval 60 -o /tmp/samples.csv </dev/null >/tmp/sampler.log 2>&1 &

Do not drop </dev/null β€” a background job whose stdin still hangs on the invocation's terminal semantics can survive the cleanup and still stall.

Cloud Assistant is asynchronous in three steps (CreateCommand β†’ InvokeCommand β†’ DescribeInvocationResults); fetch results about 10 seconds after invoking, and let the script exit normally after spawning the background job β€” no waiting required.

Before reading results back, verify the job actually lived:

# Line count should match the expected sample count; mtime should keep advancing
wc -l /tmp/samples.csv
stat -c %Y /tmp/samples.csv

An empty file or a single sample means the job died β€” go check the setsid form, not the business command. This "spawn remotely, read back later, verify output first" loop, combined with Cloud Assistant's ActionTrail audit trail, is a complete emergency-diagnostics workflow.

The lesson also explains the architecture behind CCLee Server Sentinel, a Linux server monitoring service: collection runs through a resident agent and local cron on each machine, and backup scripts run locally without depending on a central server β€” a long-lived job's lifecycle should never be bound to the tail end of a single remote invocation.

Note

The verified form is setsid nohup cmd < /dev/null &, and each piece does one job: setsid changes the session, nohup covers SIGHUP and output, stdin redirection cuts terminal semantics. Put output verification before the read-back β€” the invocation's Success only means the script finished, not that the background job is alive. And since a setsid job has left the invocation's session, later invocations cannot manage it directly; leave a PID file or locate it by process name.

Untrustworthy signals come in sets on Cloud Assistant: CLI errors go to stderr with exit 0, and a jq fallback default launders the failure into an empty result β€” see Aliyun CLI Exit 0 but Failed? jq Default Values Hide Errors.

FAQ​

Why did my nohup process disappear anyway?​

nohup does exactly two things: ignore SIGHUP and redirect output. The process stays in the original session, and Cloud Assistant cleans up the invocation's derived processes by session when the call ends β€” in one verified case strace, a sampler and a watcher all died while the invocation itself returned success with no error. A new session via setsid is what escapes the cleanup.

A nohup job quits after running for a while β€” what's going on?​

Three usual causes: the launcher's session being torn down, stdin still attached to a closed terminal, or a vanished redirect target. Check the timing: the sampler in this case stopped after exactly one sample, in sync with the invocation returning β€” that pinned the cause to invocation cleanup, not a crash.

How do I keep a script running in the background of a Cloud Assistant RunCommand?​

Use the three-piece form: setsid nohup cmd < /dev/null &. The new session is outside the end-of-invocation cleanup, so the job survives across calls. Before reading results, check the output file's line count and mtime β€” an empty or half-filled file means the job died, not that the command never ran.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

systemctl Shows inactive But the Process Is Running? Bare-Process Health Check False Negative

Β· 5 min read

While building a server health-check endpoint, systemctl is-active redis-server returned inactive β€” yet Redis was happily serving requests.

Encountered this while building AI Analytics β€” LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operations strategy. The monitoring dashboard needs to reflect the real status of every infrastructure component, and Redis was reporting a false negative from the start.

TL;DR​

systemctl is-active only works for services that systemd manages through unit files. If Redis (or any service) runs as a bare process with no .service unit, systemctl can never see its true state and returns inactive (exit code 3). Reliable probing has to bypass systemctl and ask the process (pgrep) or the port (ss) directly.

Symptoms​

The probe called systemctl is-active for both Nginx and Redis:

$ systemctl is-active nginx
active # βœ… fine

$ systemctl is-active redis-server
inactive # ❌ looks like Redis is down
$ echo $?
3 # exit code 3 = inactive

But every business endpoint was reading and writing Redis fine β€” only /api/v1/server-monitor/status reported Redis as down.

Root Cause​

systemd is a process manager, and it only knows about units it started and owns. When you run systemctl start redis-server (or let systemd read redis-server.service), systemd records that unit's state and is-active can return active.

On this server, Redis was started as a bare process β€” a direct redis-server invocation, or launched via nohup / a custom script, never registered as a systemd service. So:

  • There is no redis-server.service in systemd's unit list at all;
  • systemctl is-active redis-server can't find the unit, treats it as inactive, and returns exit 3;
  • Nginx, by contrast, is a standard systemd service, so is-active correctly reports active.

In one line: is-active reflects systemd's view, not the system process view. "The process is running" and "systemd knows it's running" are two different things.

Solution​

Switch the probe to a "systemctl first β†’ process/port fallback" chain. If systemctl hits, use it; otherwise confirm the process is actually alive with pgrep or ss. Use execFileSync (no shell, args passed as an array) to avoid command injection:

import { execFileSync } from "node:child_process";

/** Run a single command safely (no shell); unify non-zero exit to null */
function sh(cmd: string, args: string[]): string | null {
try {
return execFileSync(cmd, args, {
stdio: ["ignore", "pipe", "ignore"],
timeout: 2000,
})
.toString()
.trim();
} catch {
return null; // inactive / process missing / timeout all land here
}
}

/**
* Probe whether a service is up: systemctl first, bare-process fallback.
* @param unit systemd unit name (e.g. "nginx")
* @param proc process name (e.g. "redis") for the pgrep fallback
* @param port listening port (e.g. 6379) for the ss fallback
*/
function isServiceUp(unit: string, proc?: string, port?: number): boolean {
// 1. Try systemctl first (standard systemd services)
const st = sh("systemctl", ["is-active", unit]);
if (st && st !== "inactive" && st !== "unknown") {
return true; // active, or activating/reloading etc.
}

// 2. Fallback A: find a PID by process name
if (proc && sh("pgrep", ["-f", proc])) return true;

// 3. Fallback B: confirm a listening port
if (port) {
const listening = sh("ss", ["-lnt"]);
if (listening && listening.includes(`:${port} `)) return true;
}

return false;
}

// Nginx: standard systemd service, systemctl hits directly
const nginxUp = isServiceUp("nginx");

// Redis: may be a bare process β€” pass process name + port as fallback
const redisUp = isServiceUp("redis-server", "redis", 6379);

The most robust final check at the application layer is to let the service answer for itself β€” Redis's PING, PostgreSQL's SELECT 1, an HTTP health endpoint. A listening port only proves "the process started", not "the service is ready", so on critical paths add one more application-level probe:

$ redis-cli ping
PONG # process alive + responsive = truly up

FAQ​

Why does systemctl is-active show inactive when the process is actually running?​

systemctl only queries services that systemd manages through unit files. If the process was started directly or with nohup as a bare process with no .service unit, systemd neither knows about it nor tracks it, so is-active can only return inactive (exit 3). That's a blind spot in systemd's view, not the process being down.

How do you reliably check whether a process is running?​

Don't rely on systemctl alone. Use pgrep <name> to find the PID, or ss -lntp | grep <port> to confirm a listening port β€” these inspect the system process table / network stack, independent of systemd management. For critical services, add an application-level probe (e.g. redis-cli ping) to verify both that the process exists and that it responds.

Caveats

  • Unit name β‰  process name: the redis-server in systemctl is-active redis-server is the unit name, which may differ from the actual process name (redis-server or redis). Don't conflate them.
  • Set a timeout in production: probe commands should have a short timeout (2s in the example above) and catch errors, so one stuck command doesn't drag down the whole monitoring endpoint.
  • Containerized services differ: services running in Docker aren't visible to the host's systemctl β€” use docker inspect or the container healthcheck API instead of the pgrep fallback here.
  • The real fix: migrate the bare process into a systemd unit (with Type=, Restart=always). Then is-active becomes accurate and you get systemd's auto-restart for free.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me