Skip to content

Commit

Permalink
Merge pull request #1 from capcom6/dev
Browse files Browse the repository at this point in the history
Fixes
  • Loading branch information
capcom6 authored Feb 9, 2023
2 parents d44ac55 + a072639 commit 496174b
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 47 deletions.
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Changelog

## v1.0.1

### Added
- changelog

### Fixed
- fake notifications in pending state
- service name escaping

## v1.0.0

### Added or Changed
- TCP probe
- HTTP probe
- Telegram notification
62 changes: 31 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
<h3 align="center">Service Monitor Telegram Bot</h3>

<p align="center">
Телеграм-бот для мониторинга доступности сетевых сервисов.
Telegram bot for monitoring the availability of network services.
<br />
<!-- <a href="https://github.com/capcom6/service-monitor-tgbot"><strong>Explore the docs »</strong></a>
<br />
Expand All @@ -57,8 +57,8 @@
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Usage](#usage)
- [Пример мониторинга HTTP-сервиса](#пример-мониторинга-http-сервиса)
- [Пример мониторинга TCP-сервиса](#пример-мониторинга-tcp-сервиса)
- [HTTP service monitoring example](#http-service-monitoring-example)
- [TCP service monitoring example](#tcp-service-monitoring-example)
- [Roadmap](#roadmap)
- [Contributing](#contributing)
- [License](#license)
Expand All @@ -69,11 +69,11 @@

<!-- [![Product Name Screen Shot][product-screenshot]](https://example.com) -->

Мониторинг доступности сетевых сервисов - важная задача для любого проекта. При этом не всегда есть необходимость разворачивать универсальные решения типа Prometheus, а достаточно простого решения. Именно для таких случаев и был создан данный бот.
Monitoring the availability of network services is an important task for any project. At the same time, it is not always necessary to deploy universal solutions like Prometheus, a fairly simple solution. It is for such cases that this bot was created.

Бот позволит мониторить доступность HTTP(S) и TCP сервисов и уведомлять об изменении их состояния в Telegram.
The bot will allow you to monitor the availability of HTTP(S) and TCP services and notify Telegram about changes in their status.

Проект находится в стадии MVP.
The project is in the MVP stage.

<p align="right">(<a href="#readme-top">back to top</a>)</p>

Expand All @@ -90,23 +90,23 @@
<!-- GETTING STARTED -->
## Getting Started

Для запуска бота с использованием Docker следуйте инструкциям ниже.
Follow the instructions below to run a bot using Docker.

### Prerequisites

Для запуска бота достаточно наличия Docker или иного окружения для запуска контейнеров.
To run a bot, it is enough to have Docker or another environment for running containers.

### Installation

1. Зарегистрируйте нового бота и получите токен для него: https://core.telegram.org/bots/features#creating-a-new-bot
2. Создайте [канал](https://telegram.org/tour/channels) или [группу](https://telegram.org/tour/groups) в которую будут отправляться уведомления
3. Добавьте бота в канал/группу в качестве администратора с возможностью отправки сообщений
3. Скопируйте конфигурационный файл [config.example.yml](configs/config.example.yml) в рабочую директорию под именем `config.yml`.
4. Внесите изменения в конфигурационный файл:
- укажите токен бота;
- укажите ИД канала/группы, узнать ИД можно, например, перейдя по ссылке вида [https://api.telegram.org/bot<token>/getUpdates?allowed_updates=[]](https://api.telegram.org/bot<token>/getUpdates?allowed_updates=[]) после добавления бота в канал/группу и найдя значение `my_chat_member.chat.id`;
- перечислите сервисы для мониторинга.
5. Запустите docker-контейнер: `docker run -d -v "$(pwd)/config.yml:/app/config.yml:ro" --name tgbot capcom6/service-monitor-tgbot:latest`
1. Register a new bot and get a token for it: https://core.telegram.org/bots/features#creating-a-new-bot
2. Create a [channel](https://telegram.org/tour/channels) or [group](https://telegram.org/tour/groups) to which notifications will be sent
3. Add the bot to the channel/group as an administrator with the ability to send messages
4. Copy the configuration file [config.example.yml](configs/config.example.yml) to your working directory as `config.yml`
5. Make changes to the configuration file:
- specify the bot token;
- specify the channel/group ID, you can find out the ID, for example, by following the link like [https://api.telegram.org/bot<token>/getUpdates?allowed_updates=[]](https://api.telegram.org/bot<token>/getUpdates?allowed_updates=[]) after adding the bot to a channel/group and finding the value of `my_chat_member.chat.id`;
- list the services to monitor.
6. Run the docker container: `docker run -d -v "$(pwd)/config.yml:/app/config.yml:ro" --name tgbot capcom6/service-monitor-tgbot:latest`

<p align="right">(<a href="#readme-top">back to top</a>)</p>

Expand All @@ -115,7 +115,7 @@
<!-- USAGE EXAMPLES -->
## Usage

### Пример мониторинга HTTP-сервиса
### HTTP service monitoring example

```yaml
services:
Expand All @@ -137,7 +137,7 @@ services:
![HTTP Alert][http-alert]
### Пример мониторинга TCP-сервиса
### TCP service monitoring example
```yaml
services:
Expand All @@ -163,18 +163,18 @@ services:
<!-- ROADMAP -->
## Roadmap
- [ ] Добавить Changelog
- [ ] Добавить возможность изменять текст сообщений
- [ ] Отправка уведомлений в несколько каналов/групп
- [ ] Отражение времени события в уведомлениях
- [ ] Подсчет времени онлайн/оффлайн
- [ ] Активный режим бота
- [ ] Запрос текущего состояния сервисов
- [ ] Отчет по SLA
- [ ] Журнал событий
- [ ] Разделение бота и сервиса мониторинга
- [ ] Динамический список сервисов
- [ ] Auto-discovery (в первую очередь через Docker)
- [x] Add Changelog
- [ ] Add the ability to change the text of messages
- [ ] Send notifications to multiple channels/groups
- [ ] Display event time in notifications
- [ ] Online/offline time count
- [ ] Active bot mode
- [ ] Request current state of services
- [ ] SLA report
- [ ] The event log
- [ ] Separation of bot and monitoring service
- [ ] Dynamic list of services
- [ ] Service discovery
See the [open issues](https://github.com/capcom6/service-monitor-tgbot/issues) for a full list of proposed features (and known issues).
Expand Down
4 changes: 2 additions & 2 deletions internal/bot/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ func Run() error {
msg := tgbotapi.NewMessage(cfg.Telegram.ChatID, "")
msg.ParseMode = tgbotapi.ModeMarkdownV2
if v.State == monitor.ServiceOffline {
msg.Text = "❌ " + v.Name + " is *offline*: " + tgbotapi.EscapeText(msg.ParseMode, v.Error.Error())
msg.Text = "❌ " + tgbotapi.EscapeText(msg.ParseMode, v.Name) + " is *offline*: " + tgbotapi.EscapeText(msg.ParseMode, v.Error.Error())
} else {
msg.Text = "✅ " + v.Name + " is *online*"
msg.Text = "✅ " + tgbotapi.EscapeText(msg.ParseMode, v.Name) + " is *online*"
}

if _, err := tgapi.Send(msg); err != nil {
Expand Down
26 changes: 12 additions & 14 deletions internal/monitor/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type MonitorModule struct {
Services []config.Service

probes []ProbesChannel
states []int
states []state
}

func NewMonitorModule(services []config.Service) *MonitorModule {
Expand All @@ -24,7 +24,7 @@ func NewMonitorModule(services []config.Service) *MonitorModule {

func (m *MonitorModule) Monitor(ctx context.Context) (UpdatesChannel, error) {
m.probes = make([]ProbesChannel, len(m.Services))
m.states = make([]int, len(m.Services))
m.states = make([]state, len(m.Services))

for i, s := range m.Services {
cfg, err := s.ApplyDefaultsAndValidate()
Expand Down Expand Up @@ -65,6 +65,7 @@ func (m *MonitorModule) Monitor(ctx context.Context) (UpdatesChannel, error) {

for i, ch := range m.probes {
go func(i int, ch ProbesChannel) {
log.Println("Probe", i, "started")
defer wg.Done()
for {
select {
Expand Down Expand Up @@ -101,28 +102,25 @@ func (m *MonitorModule) updateState(id int, probe error) *ServiceStatus {
delta = -1
}

if current > 0 && delta > 0 {
// защита от переполнения
if current <= service.SuccessThreshold {
current += delta
}
} else if current < 0 && delta < 0 {
if current >= -service.FailureThreshold {
current += delta
}
if (current.Probes > 0 && delta > 0) ||
(current.Probes < 0 && delta < 0) {
// если знак совпадает, то продолжаем
current.Probes += delta
} else {
current = delta
current.Probes = delta
}

var upd *ServiceStatus
if current == service.SuccessThreshold {
if !current.Online && current.Probes == service.SuccessThreshold {
current.Online = true
upd = &ServiceStatus{
Id: service.Id,
Name: service.Name,
State: ServiceOnline,
Error: nil,
}
} else if current == -service.FailureThreshold {
} else if current.Online && current.Probes == -service.FailureThreshold {
current.Online = false
upd = &ServiceStatus{
Id: service.Id,
Name: service.Name,
Expand Down
5 changes: 5 additions & 0 deletions internal/monitor/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,10 @@ type ServiceStatus struct {
Error error
}

type state struct {
Probes int
Online bool
}

type ProbesChannel chan error
type UpdatesChannel chan ServiceStatus

0 comments on commit 496174b

Please sign in to comment.