Giter Club home page Giter Club logo

devops-netology's Introduction

SERVICES DOCUMENTS TYPE go_memstats_gc_cpu_fraction gauge.md PREVIEW AS EXPORT AS SAVE TO IMPORT FROM DOCUMENT NAME TYPE go_memstats_gc_cpu_fraction gauge.md MARKDOWNPREVIEWToggle Mode 



На лекции мы познакомились с node_exporter. В демонстрации его исполняемый файл запускался в background. Этого достаточно для демо, но не для настоящей production-системы, где процессы должны находиться под внешним управлением. Используя знания из лекции по systemd, создайте самостоятельно простой unit-файл для node_exporter:

поместите его в автозагрузку,
предусмотрите возможность добавления опций к запускаемому процессу через внешний файл (посмотрите, например, на systemctl cat cron),
удостоверьтесь, что с помощью systemctl процесс корректно стартует, завершается, а после перезагрузки автоматически поднимается.

sudo wget https://github.com/prometheus/node_exporter/releases/download/v1.1.2/node_exporter-1.1.2.linux-amd64.tar.gz
tar -xvf node_exporter*
sudo cp node_exporter*/node_exporter /usr/local/bin
sudo useradd -rs /bin/false node_exporter
sudo vim /etc/systemd/system/node_exporter.service

///
[Unit]
Description=Node Exporter

[Service]
User=node_exporter
EnvironmentFile=/etc/node_exporter
ExecStart=/usr/local/bin/node_exporter $OPTIONS

[Install]
WantedBy=multi-user.target
///

sudo vim /etc/node_exporter
///
OPTIONS="–collector.textfile.directory /var/lib/node_exporter/textfile_collector"
///

sudo systemctl daemon-reload
sudo systemctl restart node_exporter
sudo systemctl status node_exporter

После перезгрузки

vagrant@vagrant:~$ sudo systemctl status node_exporter
● node_exporter.service - Node Exporter
Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Mon 2021-06-14 18:59:56 UTC; 2min 23s ago
Process: 580 ExecStart=/usr/local/bin/node_exporter $OPTIONS (code=exited, status=1/FAILURE)
Main PID: 580 (code=exited, status=1/FAILURE)

Jun 14 18:59:56 vagrant node_exporter[580]: level=info ts=2021-06-14T18:59:56.842Z caller=node_exporter.go:113 collecto>
Jun 14 18:59:56 vagrant node_exporter[580]: level=info ts=2021-06-14T18:59:56.842Z caller=node_exporter.go:113 collecto>
Jun 14 18:59:56 vagrant node_exporter[580]: level=info ts=2021-06-14T18:59:56.842Z caller=node_exporter.go:113 collecto>
Jun 14 18:59:56 vagrant node_exporter[580]: level=info ts=2021-06-14T18:59:56.842Z caller=node_exporter.go:113 collecto>
Jun 14 18:59:56 vagrant node_exporter[580]: level=info ts=2021-06-14T18:59:56.842Z caller=node_exporter.go:113 collecto>
Jun 14 18:59:56 vagrant node_exporter[580]: level=info ts=2021-06-14T18:59:56.842Z caller=node_exporter.go:113 collecto>
Jun 14 18:59:56 vagrant node_exporter[580]: level=info ts=2021-06-14T18:59:56.842Z caller=node_exporter.go:195 msg="Lis>
Jun 14 18:59:56 vagrant node_exporter[580]: level=error ts=2021-06-14T18:59:56.860Z caller=node_exporter.go:198 err="li>
Jun 14 18:59:56 vagrant systemd[1]: node_exporter.service: Main process exited, code=exited, status=1/FAILURE
Jun 14 18:59:56 vagrant systemd[1]: node_exporter.service: Failed with result ‘exit-code’.

Ознакомьтесь с опциями node_exporter и выводом /metrics по-умолчанию. Приведите несколько опций, которые вы бы выбрали для базового мониторинга хоста по CPU, памяти, диску и сети.
Добавляем для примера node_exporter --collector.cpu
collector=filesystem
collector=netstat
collector=meminfo

vagrant@vagrant:~$ curl http://localhost:9100/metrics |grep cpu
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:–:-- --:–:-- --:–:-- 0# HELP go_memstats_gc_cpu_fraction The fraction of this program’s available CPU time used by the GC since the program started.

TYPE go_memstats_gc_cpu_fraction gauge

go_memstats_gc_cpu_fraction 7.693596084437705e-06

HELP node_cpu_guest_seconds_total Seconds the cpus spent in guests (VMs) for each mode.

TYPE node_cpu_guest_seconds_total counter

node_cpu_guest_seconds_total{cpu=“0”,mode=“nice”} 0
node_cpu_guest_seconds_total{cpu=“0”,mode=“user”} 0

HELP node_cpu_seconds_total Seconds the cpus spent in each mode.

TYPE node_cpu_seconds_total counter

node_cpu_seconds_total{cpu=“0”,mode=“idle”} 1130.53
node_cpu_seconds_total{cpu=“0”,mode=“iowait”} 2.67
node_cpu_seconds_total{cpu=“0”,mode=“irq”} 0
node_cpu_seconds_total{cpu=“0”,mode=“nice”} 0
node_cpu_seconds_total{cpu=“0”,mode=“softirq”} 6.12
node_cpu_seconds_total{cpu=“0”,mode=“steal”} 0
node_cpu_seconds_total{cpu=“0”,mode=“system”} 15.58
node_cpu_seconds_total{cpu=“0”,mode=“user”} 3.03

HELP node_memory_Percpu_bytes Memory information field Percpu_bytes.

TYPE node_memory_Percpu_bytes gauge

node_memory_Percpu_bytes 552960

HELP node_pressure_cpu_waiting_seconds_total Total time in seconds that processes have waited for CPU time

TYPE node_pressure_cpu_waiting_seconds_total counter

node_pressure_cpu_waiting_seconds_total 15.843631
node_scrape_collector_duration_seconds{collector=“cpu”} 0.00027576
node_scrape_collector_duration_seconds{collector=“cpufreq”} 4.9318e-05
node_scrape_collector_success{collector=“cpu”} 1
node_scrape_collector_success{collector=“cpufreq”} 1
100 122k 0 122k 0 0 1151k 0 --:–:-- --:–:-- --:–:-- 1151k

HELP process_cpu_seconds_total Total user and system CPU time spent in seconds.

TYPE process_cpu_seconds_total counter

process_cpu_seconds_total 0.45

Установите в свою виртуальную машину Netdata. Воспользуйтесь готовыми пакетами для установки (sudo apt install -y netdata). После успешной установки:

в конфигурационном файле /etc/netdata/netdata.conf в секции [web] замените значение с localhost на bind to = 0.0.0.0,
добавьте в Vagrantfile проброс порта Netdata на свой локальный компьютер и сделайте vagrant reload:
config.vm.network “forwarded_port”, guest: 19999, host: 19999
После успешной перезагрузки в браузере на своем ПК (не в виртуальной машине) вы должны суметь зайти на localhost:19999. Ознакомьтесь с метриками, которые по умолчанию собираются Netdata и с комментариями, которые даны к этим метрикам.

sudo systemctl restart netdata
vagrant@vagrant:~$ sudo systemctl status netdata
● netdata.service - netdata - Real-time performance monitoring
Loaded: loaded (/lib/systemd/system/netdata.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2021-06-14 19:50:17 UTC; 3s ago
Docs: man:netdata
file:///usr/share/doc/netdata/html/index.html
https://github.com/netdata/netdata
Main PID: 2604 (netdata)
Tasks: 18 (limit: 1074)
Memory: 18.3M
CGroup: /system.slice/netdata.service
├─2604 /usr/sbin/netdata -D
├─2647 bash /usr/lib/netdata/plugins.d/tc-qos-helper.sh 1
├─2654 /usr/lib/netdata/plugins.d/apps.plugin 1
└─2657 /usr/lib/netdata/plugins.d/nfacct.plugin 1

Jun 14 19:50:17 vagrant systemd[1]: Started netdata - Real-time performance monitoring.
Jun 14 19:50:17 vagrant netdata[2604]: SIGNAL: Not enabling reaper
Jun 14 19:50:17 vagrant netdata[2604]: 2021-06-14 19:50:17: netdata INFO : MAIN : SIGNAL: Not enabling reaper

Можно ли по выводу dmesg понять, осознает ли ОС, что загружена не на настоящем оборудовании, а на системе виртуализации?

vagrant@vagrant:~$ sudo dmesg |grep virt
[ 0.004514] CPU MTRRs all blank - virtualized system.
[ 0.049572] Booting paravirtualized kernel on KVM
[ 5.722493] systemd[1]: Detected virtualization oracle.
vagrant@vagrant:~$

Как настроен sysctl fs.nr_open на системе по-умолчанию? Узнайте, что означает этот параметр. Какой другой существующий лимит не позволит достичь такого числа (ulimit --help)?
https://access.redhat.com/solutions/1479623
The default value fs.nr_open is 1024*1024 = 1048576.
The maximum value of fs.nr_open is limited to sysctl_nr_open_max in kernel, which is 2147483584 on x86_64.

ulimit -n 2147483584

-bash: ulimit: open files: cannot modify limit: Operation not permitted

sysctl fs.nr_open

fs.nr_open = 1048576

sysctl -w fs.nr_open=2147483584

fs.nr_open = 2147483584

ulimit -n 2147483584

ulimit -n

2147483584

sysctl -w fs.nr_open=2147483585

sysctl: setting key “fs.nr_open”: Invalid argument
fs.nr_open = 2147483585

Найдите информацию о том, что такое :(){ :|:& };:. Запустите эту команду в своей виртуальной машине Vagrant с Ubuntu 20.04 (это важно, поведение в других ОС не проверялось). Некоторое время все будет “плохо”, после чего (минуты) – ОС должна стабилизироваться. Вызов dmesg расскажет, какой механизм помог автоматической стабилизации. Как настроен этот механизм по-умолчанию, и как изменить число процессов, которое можно создать в сессии?

Эта функция fork bomb, заменим : на функцию netolog функция порождает саму себя.
netolog{
netolog | netolog &
}; netolog

Результат самовостановления системы по ограничению количества сесий на пользователя.
[ 1595.454419] cgroup: fork rejected by pids controller in /user.slice/user-1000.slice/session-3.scope

devops-netology's People

Contributors

komarovma avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.