Skip to content

Commit b846d2f

Browse files
authored
Merge pull request #2 from DanLinX2004X/feature/ci-pipeline
Fix system-monitor.sh warnings & add CI
2 parents 1ccb038 + 33fd28f commit b846d2f

File tree

4 files changed

+105
-22
lines changed

4 files changed

+105
-22
lines changed

.github/workflows/ci.yml

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
name: Bash CI
2+
3+
on:
4+
push:
5+
branches: [main, feature/ci-pipeline]
6+
paths-ignore:
7+
- '**.md'
8+
pull_request:
9+
branches: [main]
10+
paths-ignore:
11+
- '**.md'
12+
workflow_dispatch:
13+
14+
jobs:
15+
bash-checks:
16+
runs-on: ubuntu-latest
17+
18+
steps:
19+
- name: Checkout code
20+
uses: actions/checkout@v4
21+
22+
- name: Syntax check
23+
run: bash -n system-monitor.sh
24+
25+
- name: Run Shellcheck
26+
uses: ludeeus/action-shellcheck@master
27+
continue-on-error: true
28+
29+
- name: Verify dependencies
30+
run: |
31+
for cmd in awk grep free df ps bc ip; do
32+
if ! command -v $cmd &>/dev/null; then
33+
echo "Missing dependency: $cmd"
34+
exit 1
35+
fi
36+
done
37+
38+
- name: Help/version flags test
39+
run: |
40+
chmod +x system-monitor.sh
41+
./system-monitor.sh --help | grep "Usage"
42+
./system-monitor.sh --version | grep "version"
43+
44+
- name: Smoke test
45+
run: |
46+
./system-monitor.sh --brief | grep "cpu_load"

README.md

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ Add a line for hourly monitoring (runs at the beginning of each hour):**
227227

228228
- Cron runs with a minimal environment - test thoroughly
229229

230-
### 🐳 **Docker Container Monitoring**
230+
### 🐳 Docker Container Monitoring
231231

232232
You can use this script to monitor resources inside Docker containers.
233233

@@ -283,7 +283,7 @@ docker exec postgres-container /tmp/system-monitor.sh --brief
283283
- Some **system metrics** may not be available in containers
284284

285285

286-
### 🔄 **Alternative: Run from host system**
286+
### 🔄 *lternative: Run from host system
287287

288288
You can also monitor containers from the host system:
289289

@@ -297,18 +297,33 @@ docker exec container_name cat /proc/loadavg
297297
docker exec container_name free -h
298298
```
299299

300+
## ⚙️ CI Integration & ShellCheck Fixes
301+
302+
- Continuous Integration (CI): Added GitHub Actions workflow to automatically check the script on every push and pull request.
303+
- Syntax check (bash -n)
304+
- ShellCheck validation
305+
- Dependency verification (awk, grep, free, df, ps, bc, ip)
306+
- Smoke tests & basic flag tests (--help, --version, --brief)
307+
- ShellCheck Warnings: Fixed all warnings in system-monitor.sh to ensure clean, maintainable code.
308+
- Quotes around variables
309+
- Separate declaration and assignment for local variables
310+
- Word splitting issues resolved
311+
312+
> ✅ CI ensures that every future change maintains script correctness and readability.
313+
314+
300315
## 🤝 Contributing
301316

302317
If you'd like to suggest improvements or report issues:
303318

304-
### 📝 **Easiest Way (Recommended):**
319+
### 📝 Easiest Way (Recommended):
305320

306321
1. **Create an Issue** on GitHub - describe your idea or problem
307322

308323
2. **I'll implement the changes** myself and credit you in the commits
309324

310325

311-
### 💻 **For Advanced Users (if familiar with Git):**
326+
### 💻 For Advanced Users (if familiar with Git):
312327

313328
1. **Fork the repository** (click "Fork" in the top-right corner)
314329

@@ -317,7 +332,7 @@ If you'd like to suggest improvements or report issues:
317332
3. **Create a Pull Request** - I'll review and merge your changes
318333

319334

320-
### 🐛 **Reporting Bugs:**
335+
### 🐛 Reporting Bugs:
321336

322337
In your Issue, please include:
323338

@@ -330,7 +345,7 @@ In your Issue, please include:
330345
- What you expected to see
331346

332347

333-
### 💡 **Improvement Ideas:**
348+
### 💡 Improvement Ideas:
334349

335350
- Add CPU temperature monitoring
336351

README.ru.md

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ docker exec postgres-container /tmp/system-monitor.sh --brief
277277

278278
- Некоторые **системные метрики** могут быть недоступны в контейнерах
279279

280-
### 🔄 **Альтернатива: Запуск с хостовой системы**
280+
### 🔄 Альтернатива: Запуск с хостовой системы
281281

282282
Вы также можете мониторить контейнеры с хостовой системы:
283283

@@ -290,18 +290,33 @@ docker exec имя_контейнера cat /proc/loadavg
290290
docker exec имя_контейнера free -h
291291
```
292292

293+
## ⚙️ Интеграция CI и исправления ShellCheck
294+
295+
- Непрерывная интеграция (CI): Добавлен workflow GitHub Actions для автоматической проверки скрипта при каждом push и pull request:
296+
- Проверка синтаксиса (bash -n)
297+
- Валидация через ShellCheck
298+
- Проверка зависимостей (awk, grep, free, df, ps, bc, ip)
299+
- Smoke-тесты и базовая проверка флагов (--help, --version, --brief)
300+
- Предупреждения ShellCheck: Исправлены все предупреждения в system-monitor.sh для чистого и поддерживаемого кода:
301+
- Кавычки вокруг переменных
302+
- Раздельное объявление и присвоение локальных переменных
303+
- Решены проблемы с разбиением слов
304+
305+
> ✅ CI гарантирует, что будущие изменения будут поддерживать корректность и читаемость скрипта.
306+
307+
293308
## 🤝 Участие в разработке
294309

295310
Если вы хотите предложить улучшение или сообщить об ошибке:
296311

297-
### 📝 **Самый простой способ (рекомендуется):**
312+
### 📝 Самый простой способ (рекомендуется):
298313

299314
1. **Напишите Issue** на GitHub - опишите идею или проблему
300315

301316
2. **Я сам внесу изменения** и упомяну вас в коммитах
302317

303318

304-
### 💻 **Для продвинутых (если знакомы с Git):**
319+
### 💻 Для продвинутых (если знакомы с Git):
305320

306321
1. **Сделайте Fork** репозитория (кнопка "Fork" в правом верхнем углу)
307322

@@ -310,7 +325,7 @@ docker exec имя_контейнера free -h
310325
3. **Создайте Pull Request** - я проверю и добавлю ваши изменения
311326

312327

313-
### 🐛 **Сообщение об ошибках:**
328+
### 🐛 Сообщение об ошибках:
314329

315330
В Issue укажите:
316331

@@ -323,7 +338,7 @@ docker exec имя_контейнера free -h
323338
- Что вы ожидали увидеть
324339

325340

326-
### 💡 **Идеи для улучшений:**
341+
### 💡 Идеи для улучшений:
327342

328343
- Добавление мониторинга температуры CPU
329344

system-monitor.sh

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -135,15 +135,17 @@ colorize() {
135135

136136
# --- CPU Metrics Collection ---
137137
get_cpu_metrics() {
138-
local loadavg=$(cat /proc/loadavg 2>/dev/null)
138+
local loadavg
139+
loadavg=$(cat /proc/loadavg 2>/dev/null)
139140
if [ -n "$loadavg" ]; then
140141
CPU_LOAD_1MIN=$(echo "$loadavg" | awk '{print $1}')
141142
CPU_LOAD_5MIN=$(echo "$loadavg" | awk '{print $2}')
142143
CPU_LOAD_15MIN=$(echo "$loadavg" | awk '{print $3}')
143144
CPU_CORES=$(nproc 2>/dev/null || echo "1")
144145

145146
# Calculate load as percentage of CPU cores
146-
local load_percent=$(echo "scale=0; ($CPU_LOAD_1MIN * 100) / $CPU_CORES" | bc 2>/dev/null)
147+
local load_percent
148+
load_percent=$(echo "scale=0; ($CPU_LOAD_1MIN * 100) / $CPU_CORES" | bc 2>/dev/null)
147149
CPU_LOAD_PERCENT=${load_percent:-0}
148150
else
149151
CPU_LOAD_1MIN="N/A"
@@ -156,7 +158,8 @@ get_cpu_metrics() {
156158

157159
# --- Memory Metrics Collection ---
158160
get_memory_metrics() {
159-
local mem_info=$(free -b 2>/dev/null | grep Mem)
161+
local mem_info
162+
mem_info=$(free -b 2>/dev/null | grep Mem)
160163
if [ -n "$mem_info" ]; then
161164
MEM_TOTAL=$(echo "$mem_info" | awk '{printf "%.2f", $2/1024/1024/1024}')
162165
MEM_USED=$(echo "$mem_info" | awk '{printf "%.2f", $3/1024/1024/1024}')
@@ -172,7 +175,8 @@ get_memory_metrics() {
172175

173176
# --- Disk Metrics Collection ---
174177
get_disk_metrics() {
175-
local disk_info=$(df -B1 / 2>/dev/null | awk 'NR==2')
178+
local disk_info
179+
disk_info=$(df -B1 / 2>/dev/null | awk 'NR==2')
176180
if [ -n "$disk_info" ]; then
177181
DISK_USED=$(echo "$disk_info" | awk '{printf "%.1f", $3/1024/1024/1024}')
178182
DISK_AVAILABLE=$(echo "$disk_info" | awk '{printf "%.1f", $4/1024/1024/1024}')
@@ -191,11 +195,14 @@ get_disk_metrics() {
191195
# --- Network Metrics Collection ---
192196
get_network_metrics() {
193197
# Get primary network interface (route to Google DNS)
194-
local interface=$(ip route get 8.8.8.8 2>/dev/null | awk '{print $5}' | head -1)
198+
local interface
199+
interface=$(ip route get 8.8.8.8 2>/dev/null | awk '{print $5}' | head -1)
195200
if [ -n "$interface" ] && [ "$interface" != "dev" ]; then
196201
NET_INTERFACE="$interface"
197-
local rx_bytes=$(cat "/sys/class/net/$interface/statistics/rx_bytes" 2>/dev/null)
198-
local tx_bytes=$(cat "/sys/class/net/$interface/statistics/tx_bytes" 2>/dev/null)
202+
local rx_bytes
203+
rx_bytes=$(cat "/sys/class/net/$interface/statistics/rx_bytes" 2>/dev/null)
204+
local tx_bytes
205+
tx_bytes=$(cat "/sys/class/net/$interface/statistics/tx_bytes" 2>/dev/null)
199206

200207
NET_RX_MB=$(echo "scale=2; ${rx_bytes:-0} / 1024 / 1024" | bc 2>/dev/null)
201208
NET_TX_MB=$(echo "scale=2; ${tx_bytes:-0} / 1024 / 1024" | bc 2>/dev/null)
@@ -259,14 +266,14 @@ print_detailed_stats() {
259266
# CPU Information
260267
echo -e "${BLUE}==== CPU LOAD ====${NC}"
261268
echo -e "CPU Cores: $CPU_CORES"
262-
echo -e "Load Average: 1min: $(colorize $CPU_LOAD_1MIN 1 2) | 5min: $(colorize $CPU_LOAD_5MIN 1 2) | 15min: $(colorize $CPU_LOAD_15MIN 1 2)"
263-
echo -e "System Load: $(colorize ${CPU_LOAD_PERCENT}% 70 90)"
269+
echo -e "Load Average: 1min: $(colorize "$CPU_LOAD_1MIN" 1 2) | 5min: $(colorize "$CPU_LOAD_5MIN" 1 2) | 15min: $(colorize "$CPU_LOAD_15MIN" 1 2)"
270+
echo -e "System Load: $(colorize "${CPU_LOAD_PERCENT}"% 70 90)"
264271
echo
265272

266273
# Memory Information
267274
echo -e "${BLUE}==== MEMORY USAGE ====${NC}"
268275
echo -e "Total: ${MEM_TOTAL} GB"
269-
echo -e "Used: $(colorize "${MEM_USED} GB" $(echo "scale=0; $MEM_TOTAL * 0.7" | bc 2>/dev/null) $(echo "scale=0; $MEM_TOTAL * 0.9" | bc 2>/dev/null))"
276+
echo -e "Used: $(colorize "${MEM_USED} GB" "$(echo "scale=0; $MEM_TOTAL * 0.7" | bc 2>/dev/null)" "$(echo "scale=0; $MEM_TOTAL * 0.9" | bc 2>/dev/null)")"
270277
echo -e "Available: ${MEM_AVAILABLE} GB"
271278
echo -e "Usage: $(colorize "${MEM_PERCENT}%" 70 90)"
272279
echo
@@ -341,7 +348,7 @@ main() {
341348
echo
342349

343350
# Sleep with interrupt checking
344-
for ((i=0; i<INTERVAL && EXIT_SIGNAL==false; i++)); do
351+
while [ "$EXIT_SIGNAL" = false ]; do
345352
sleep 1
346353
done
347354
done

0 commit comments

Comments
 (0)