Skip to main content

Service Management

Service management - bu Linux tizimlarida daemon va service'larni boshqarish uchun muhim skill. Zamonaviy Linux distributionlarda asosan systemd ishlatiladi, lekin eski tizimlar uchun SysV init ham bilish kerak.

Service Management Asoslari

Init System Turlari

# systemd (zamonaviy distributionlar)
# - Ubuntu 15.04+, Debian 8+, CentOS 7+, RHEL 7+, Fedora 15+

# SysV init (eski tizimlar)
# - Ubuntu 14.04 va oldingi, CentOS 6 va oldingi

# Upstart (o'rta davr)
# - Ubuntu 6.10-14.10

# Init system aniqlash
ps --no-headers -o comm 1 # PID 1 process nomi
systemctl --version 2>/dev/null # systemd versiyasi
initctl --version 2>/dev/null # Upstart versiyasi

Service vs Daemon

# Service - tizim tomonidan boshqariladigan process
# Daemon - backgroundda ishlaydigan process
# Unit - systemd'da service, timer, mount va boshqalar

systemd va systemctl

Service Status va Ma'lumot

# Service status
systemctl status service_name # Batafsil status
systemctl is-active service_name # Active/inactive
systemctl is-enabled service_name # Enabled/disabled
systemctl is-failed service_name # Failed/not-failed

# Barcha service'lar
systemctl list-units --type=service # Faol service'lar
systemctl list-units --type=service --all # Barcha service'lar
systemctl list-unit-files --type=service # Unit file'lar

# Service ma'lumotlari
systemctl show service_name # Batafsil ma'lumot
systemctl cat service_name # Unit file mazmuni
systemctl list-dependencies service_name # Dependencies

Service Boshqaruvi

# Service boshlash/to'xtatish
sudo systemctl start service_name # Service boshlash
sudo systemctl stop service_name # Service to'xtatish
sudo systemctl restart service_name # Service qayta ishga tushirish
sudo systemctl reload service_name # Configuration reload
sudo systemctl reload-or-restart service_name # Reload yoki restart

# Service enable/disable
sudo systemctl enable service_name # Boot'da avtomatik boshlash
sudo systemctl disable service_name # Boot'da boshlashni o'chirish
sudo systemctl enable --now service_name # Enable va start
sudo systemctl disable --now service_name # Stop va disable

# Service mask/unmask
sudo systemctl mask service_name # Service'ni butunlay disable qilish
sudo systemctl unmask service_name # Mask'ni olib tashlash

Service Monitoring

# Real-time monitoring
journalctl -u service_name -f # Service log'larini real-time kuzatish
systemctl status service_name # Current status
watch systemctl status service_name # Status'ni doimiy kuzatish

# Service logs
journalctl -u service_name # Service log'lari
journalctl -u service_name --since today # Bugungi log'lar
journalctl -u service_name --since "2023-01-01" # Ma'lum sanadan
journalctl -u service_name -n 50 # Oxirgi 50 qator
journalctl -u service_name --no-pager # Pager'siz ko'rsatish

System State Management

# System state
systemctl get-default # Default target
sudo systemctl set-default target # Default target o'rnatish

# System targets (runlevel'lar)
systemctl list-units --type=target # Available targets
systemctl isolate multi-user.target # Multi-user mode'ga o'tish
systemctl isolate graphical.target # Graphical mode'ga o'tish

# System control
sudo systemctl reboot # Tizimni qayta ishga tushirish
sudo systemctl poweroff # Tizimni o'chirish
sudo systemctl suspend # Sleep mode
sudo systemctl hibernate # Hibernate
sudo systemctl emergency # Emergency mode
sudo systemctl rescue # Rescue mode

Custom Service Yaratish

Service Unit File

# Service unit file yaratish
sudo vim /etc/systemd/system/myapp.service

# Service unit file structure:
[Unit]
Description=My Application Service
Documentation=https://myapp.example.com/docs
After=network.target mysql.service
Wants=mysql.service
Requires=network.target

[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/myapp
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp

# Security settings
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/myapp/data /var/log/myapp

# Resource limits
LimitNOFILE=65536
MemoryLimit=1G
CPUQuota=200%

[Install]
WantedBy=multi-user.target

Service Types

# Service Type'lar
Type=simple # Default, process foreground'da ishlaydi
Type=exec # systemd process'ni execute qilishni kutadi
Type=forking # Process fork qilib background'ga o'tadi
Type=oneshot # Bir marta ishlaydi va tugaydi
Type=dbus # D-Bus name'ni olishni kutadi
Type=notify # systemd'ga ready signal yuboradi
Type=idle # Boshqa job'lar tugashini kutadi

Service Template'lar

# Template service yaratish
sudo vim /etc/systemd/system/myapp@.service

[Unit]
Description=My Application Service for %i
After=network.target

[Service]
Type=simple
User=myapp
ExecStart=/opt/myapp/bin/myapp --instance=%i
Restart=always

[Install]
WantedBy=multi-user.target

# Template'dan instance yaratish
sudo systemctl enable myapp@instance1.service
sudo systemctl start myapp@instance1.service
sudo systemctl start myapp@instance2.service

Service Management Script

#!/bin/bash
# service-creator.sh - Custom service yaratish uchun script

create_service() {
local service_name=$1
local exec_path=$2
local user=$3
local description=$4

if [[ -z "$service_name" || -z "$exec_path" ]]; then
echo "Usage: create_service <service_name> <exec_path> [user] [description]"
return 1
fi

user=${user:-root}
description=${description:-"Custom service: $service_name"}

# Create service file
cat << EOF | sudo tee "/etc/systemd/system/$service_name.service"
[Unit]
Description=$description
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
User=$user
ExecStart=$exec_path
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd va enable service
sudo systemctl daemon-reload
sudo systemctl enable "$service_name.service"

echo "Service $service_name created and enabled"
echo "Start with: sudo systemctl start $service_name"
}

# Usage example:
# create_service "myapp" "/opt/myapp/bin/myapp" "myapp" "My Application Service"

Timer Units (Cron alternative)

Timer yaratish

# Timer unit file
sudo vim /etc/systemd/system/backup.timer

[Unit]
Description=Run backup daily
Requires=backup.service

[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=300

[Install]
WantedBy=timers.target

# Service unit file
sudo vim /etc/systemd/system/backup.service

[Unit]
Description=Backup service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
User=backup

Timer Management

# Timer'larni boshqarish
sudo systemctl enable backup.timer # Timer enable
sudo systemctl start backup.timer # Timer start
systemctl list-timers # Active timer'lar
systemctl list-timers --all # Barcha timer'lar

# Timer status
systemctl status backup.timer # Timer status
journalctl -u backup.timer # Timer logs

SysV Init (Legacy Systems)

SysV Service Management

# Service commands (CentOS 6, Ubuntu 14.04 va oldingi)
sudo service service_name start # Service boshlash
sudo service service_name stop # Service to'xtatish
sudo service service_name restart # Service qayta ishga tushirish
sudo service service_name reload # Configuration reload
sudo service service_name status # Service status

service --status-all # Barcha service'lar status

# chkconfig (Red Hat oilasi)
chkconfig --list # Service'lar va runlevel'lar
sudo chkconfig service_name on # Service enable
sudo chkconfig service_name off # Service disable
sudo chkconfig --level 35 service_name on # Specific runlevel

# update-rc.d (Debian oilasi)
sudo update-rc.d service_name enable # Service enable
sudo update-rc.d service_name disable # Service disable
sudo update-rc.d service_name remove # Service remove

Runlevel'lar

# Runlevel ma'lumotlari
runlevel # Current runlevel
who -r # Current runlevel (alternative)

# Runlevel'lar:
# 0 - Halt
# 1 - Single user mode
# 2 - Multi-user without networking
# 3 - Multi-user with networking
# 4 - Unused
# 5 - Graphical mode
# 6 - Reboot

# Runlevel o'zgartirish
sudo init 3 # Runlevel 3'ga o'tish
sudo telinit 5 # Runlevel 5'ga o'tish

Service Troubleshooting

Common Issues

# Service start qila olmaydi
sudo systemctl status service_name # Error details
journalctl -u service_name -n 50 # Recent logs
sudo systemctl reset-failed service_name # Failed state reset

# Port conflicts
sudo netstat -tulpn | grep :80 # Port ishlatilayotganini tekshirish
sudo ss -tulpn | grep :80 # Modern alternative

# Permission issues
sudo systemctl edit service_name # Service override yaratish
# [Service]
# User=newuser
# Group=newgroup

# Dependency issues
systemctl list-dependencies service_name # Dependencies ko'rish
systemctl list-dependencies service_name --reverse # Reverse dependencies

Service Debug

#!/bin/bash
# service-debug.sh - Service debug script

debug_service() {
local service_name=$1

if [[ -z "$service_name" ]]; then
echo "Usage: debug_service <service_name>"
return 1
fi

echo "=== Service Debug Report for $service_name ==="
echo "Date: $(date)"
echo

echo "=== Service Status ==="
systemctl status "$service_name"
echo

echo "=== Service Configuration ==="
systemctl cat "$service_name" 2>/dev/null || echo "Unit file not found"
echo

echo "=== Service Dependencies ==="
systemctl list-dependencies "$service_name" 2>/dev/null
echo

echo "=== Recent Logs (last 20 lines) ==="
journalctl -u "$service_name" -n 20 --no-pager
echo

echo "=== Service Properties ==="
systemctl show "$service_name" | grep -E "(ActiveState|LoadState|SubState|Result|ExecStart|User|Group)"
echo

echo "=== Port Check ==="
# Try to extract port from service
port=$(systemctl cat "$service_name" 2>/dev/null | grep -oE ":[0-9]+" | head -1 | tr -d ':')
if [[ -n "$port" ]]; then
echo "Checking port $port:"
sudo ss -tulpn | grep ":$port"
else
echo "No port found in service configuration"
fi
echo

echo "=== Process Check ==="
service_pid=$(systemctl show "$service_name" -p MainPID | cut -d= -f2)
if [[ "$service_pid" != "0" && -n "$service_pid" ]]; then
echo "Main PID: $service_pid"
ps aux | grep "$service_pid" | grep -v grep
echo "Process tree:"
pstree "$service_pid" 2>/dev/null || echo "pstree not available"
else
echo "Service not running or PID not available"
fi
}

# Usage: debug_service nginx

Advanced Service Management

Service Monitoring Script

#!/bin/bash
# service-monitor.sh - Service monitoring va alerting

CRITICAL_SERVICES=("nginx" "mysql" "ssh" "network")
NOTIFICATION_EMAIL="admin@example.com"
LOG_FILE="/var/log/service-monitor.log"

log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

check_service() {
local service_name=$1
local status

if systemctl is-active "$service_name" >/dev/null 2>&1; then
status="RUNNING"
else
status="DOWN"
fi

echo "$status"
}

restart_service() {
local service_name=$1

log_message "Attempting to restart $service_name"

if sudo systemctl restart "$service_name"; then
log_message "Successfully restarted $service_name"
return 0
else
log_message "Failed to restart $service_name"
return 1
fi
}

send_alert() {
local service_name=$1
local action=$2

if command -v mail >/dev/null 2>&1; then
echo "Service Alert: $service_name is $action on $(hostname) at $(date)" | \
mail -s "Service Alert: $service_name $action" "$NOTIFICATION_EMAIL"
fi

log_message "ALERT: $service_name is $action"
}

monitor_services() {
local failed_services=()

log_message "Starting service monitoring check"

for service in "${CRITICAL_SERVICES[@]}"; do
status=$(check_service "$service")

if [[ "$status" == "DOWN" ]]; then
log_message "WARNING: $service is down"
failed_services+=("$service")

# Try to restart
if restart_service "$service"; then
send_alert "$service" "restarted automatically"
else
send_alert "$service" "failed to restart"
fi
else
log_message "OK: $service is running"
fi
done

if [[ ${#failed_services[@]} -eq 0 ]]; then
log_message "All critical services are running"
else
log_message "Failed services: ${failed_services[*]}"
fi
}

# Crontab entry uchun:
# */5 * * * * /usr/local/bin/service-monitor.sh

monitor_services

Service Backup va Restore

#!/bin/bash
# service-backup.sh - Service configuration backup

backup_service_configs() {
local backup_dir="/backup/services/$(date +%Y%m%d_%H%M%S)"

mkdir -p "$backup_dir"

echo "=== Service Configuration Backup ==="
echo "Backup directory: $backup_dir"

# systemd services
if [[ -d "/etc/systemd/system" ]]; then
echo "Backing up systemd services..."
cp -r /etc/systemd/system "$backup_dir/"
fi

# Service-specific configs
services_to_backup=(
"/etc/nginx"
"/etc/apache2"
"/etc/mysql"
"/etc/postgresql"
"/etc/ssh"
"/etc/redis"
)

for config_dir in "${services_to_backup[@]}"; do
if [[ -d "$config_dir" ]]; then
service_name=$(basename "$config_dir")
echo "Backing up $service_name configuration..."
cp -r "$config_dir" "$backup_dir/"
fi
done

# Create services list
systemctl list-unit-files --type=service | grep enabled > "$backup_dir/enabled-services.txt"

# Compress backup
tar -czf "$backup_dir.tar.gz" -C "$(dirname "$backup_dir")" "$(basename "$backup_dir")"
rm -rf "$backup_dir"

echo "Backup completed: $backup_dir.tar.gz"
}

restore_service_configs() {
local backup_file=$1

if [[ ! -f "$backup_file" ]]; then
echo "Backup file not found: $backup_file"
return 1
fi

local restore_dir="/tmp/service-restore-$$"
mkdir -p "$restore_dir"

echo "Restoring from: $backup_file"
tar -xzf "$backup_file" -C "$restore_dir"

# Find the backup directory
backup_content=$(find "$restore_dir" -type d -name "*_*" | head -1)

if [[ -z "$backup_content" ]]; then
echo "Invalid backup format"
rm -rf "$restore_dir"
return 1
fi

# Restore systemd services
if [[ -d "$backup_content/system" ]]; then
echo "Restoring systemd services..."
sudo cp -r "$backup_content/system"/* /etc/systemd/system/
sudo systemctl daemon-reload
fi

# Restore other configurations (with confirmation)
for config_backup in "$backup_content"/*; do
if [[ -d "$config_backup" && "$(basename "$config_backup")" != "system" ]]; then
service_name=$(basename "$config_backup")
target_dir="/etc/$service_name"

if [[ -d "$target_dir" ]]; then
read -p "Restore $service_name configuration? [y/N] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
sudo cp -r "$config_backup"/* "$target_dir/"
echo "Restored $service_name configuration"
fi
fi
fi
done

# Restore enabled services
if [[ -f "$backup_content/enabled-services.txt" ]]; then
echo "Restoring enabled services..."
while read -r line; do
service_name=$(echo "$line" | awk '{print $1}')
if [[ "$service_name" != "UNIT" && -n "$service_name" ]]; then
sudo systemctl enable "$service_name" 2>/dev/null
fi
done < "$backup_content/enabled-services.txt"
fi

rm -rf "$restore_dir"
echo "Restore completed"
}

# Usage:
# backup_service_configs
# restore_service_configs "/backup/services/backup.tar.gz"

Bu tutorial service management bo'yicha zamonaviy systemd dan tortib legacy SysV init sistemalarigacha barcha asosiy ma'lumotlarni qamrab oladi. Real production environment'larda service'larni professional darajada boshqarish uchun zarur bo'lgan barcha skill'larni o'rgatadi.