-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
41 changed files
with
1,195 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
_build |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
version: 2 | ||
|
||
sphinx: | ||
builder: html | ||
configuration: conf.py | ||
fail_on_warning: true | ||
python: | ||
version: 3.7 | ||
install: | ||
- requirements: requirements.txt | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
# Бонус-коды | ||
|
||
|
||
## Пример | ||
~~~python | ||
|
||
BONUS_CODES = [ | ||
|
||
# This code could be published somewhere in advertising | ||
# Could be applied only once | ||
# Grants group for 1 year | ||
{ | ||
'name': 'ReleasePromo2019', | ||
'prefix': 'ReleasePromo2019', | ||
'group': 'AlcorPromo', | ||
'days': 365, | ||
'expires': "2020-12-31", | ||
# 'repeat': 10 # Repeat period in days | ||
}, | ||
|
||
# This code is internal (started with underscore). It will not be applied if entered in profile | ||
# Grants group AlcorPromo forever | ||
{ | ||
'name': '_forever', | ||
'prefix': '_forever', | ||
'group': 'AlcorPromo', | ||
}, | ||
|
||
# This code is internal (started with underscore). It will not be applied if entered in profile | ||
# Grants 1mo of HIGHEST already applied group (by weight/_price/maxindicators) | ||
# Could be repeated every day (but only by admin) | ||
{ | ||
'name': '_1mo', | ||
'prefix': '_1mo', | ||
'days': 31, | ||
'repeat': 1, | ||
}, | ||
|
||
# This code is provider-specific | ||
# provider can generate codes on his side | ||
# okerr can verify codes based on pre-shared secret | ||
{ | ||
'name': 'provider1', | ||
'prefix': 'provider1:', | ||
'group': 'AlcorPromo', | ||
'days': 31, | ||
'verification': 'hmac:sha256', | ||
'secret': '1234567890abcdef' | ||
}, | ||
|
||
# This code is provider-specific | ||
# provider can generate codes on his side | ||
# okerr can verify codes based on pre-shared secret | ||
{ | ||
'name': 'provider2', | ||
'prefix': 'provider2:', | ||
'group': 'AlcorPromo', | ||
'days': 31, | ||
'discard_if_failed': 31, | ||
'reactivation': 2, | ||
'verification': 'url:200', | ||
'verify_url': 'http://test.sysattack.com/codes/{CODE}', | ||
}, | ||
|
||
] | ||
|
||
~~~ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
# Общее описание схемы конфигурации okerr | ||
Почти все программы okerr, которые работают с базой данных (Okerr UI, okerr-process, okerr-smtpd, okerr-telebot, okerr-mqsender, но не okerr-poster и okerr-sensor) используют эту схему конфигурации. Все конфигурационные файлы - модули python (если не указано обратное). | ||
|
||
|
||
|
||
Главный конфигурационный файл `okerr/settings.py` в каталоге okerr. (Все прочие файлы конфигурации подгружаются (импортируются) из этого файла). Далее, `okerr/settings_defaults.py` загружается, чтобы установить значения по умолчанию. | ||
|
||
|
||
Наиболее важные директивы в нем: | ||
- `MAIN_CONF_DIR='/etc/okerr'`, | ||
- `SITE_PRECONF_FILES = MAIN_CONF_DIR/okerr.conf`, | ||
- `SITE_CONF_DIRS` - subdirectories of `MAIN_CONF_DIR` ending with '.d' (alphabetically sorted). Including symlinks to directories. | ||
- `SITE_POSTCONF_FILES = MAIN_CONF_DIR/post.conf` | ||
- `SITE_JSON_DIRS = '/etc/okerr/json/'` (files here are in JSON format) | ||
|
||
Файлы, перечисленные выше не должны редактироваться пользователем/администратором. | ||
|
||
Далее импортируются: | ||
- Файлы preconf (предварительной конфигурации) | ||
- Все файлы '*.conf' из SITE_CONF_DIRS | ||
- Файлы postconf (пост-конфигурация) | ||
|
||
Любые конфигурационные значения, которые нужно изменить - [пере]устанавливаются в этих файлах. | ||
|
||
JKEYS_TPL загражается из `SITE_JSON_DIRS/keys-template.json`. | ||
|
||
## Условный импорт | ||
Есть возможность импортировать файлы конфигурации по условиям. Когда okerr импортирует файл, он проверяет переменные вида: `__IF_VARIABLE = VALUE`. Если хотя бы одна такая проверка не выполняется - файл не импортируется. | ||
|
||
Пример: | ||
/etc/okerr/okerr.conf: | ||
~~~ | ||
CLUSTER_NAME = 'MY' | ||
~~~ | ||
|
||
/etc/okerr/local.d/local.conf: | ||
~~~ | ||
__IF_CLUSTER_NAME = 'LOCAL' | ||
~~~ | ||
|
||
/etc/okerr/local.d/my.conf: | ||
~~~ | ||
__IF_CLUSTER_NAME = 'MY' | ||
~~~ | ||
|
||
В этом примере local.conf не будет загружен, а my.conf будет. | ||
|
||
|
||
## Отладка импорта | ||
Переменная `IMPORT_VERBOSITY` (по-умолчанию: 0) устанавливается в `settings.conf` и определяется, насколько подробной должна быть процедура импорта. Новое значение для этой переменной можно установить в `MAIN_CONF_DIR/okerr.conf`. Файлы `settings.py`, `settings_default.py` and `MAIN_CONF_DIR/okerr.conf` обрабатываются до обработки этого файла, и будут всегда импортированы с `IMPORT_VERBOSITY=0`. Но все последующие файлы будут загружаться с новым значением. | ||
|
||
При IMPORT_VERBOSITY=0, все символы из файла импортируются полностью тихо. | ||
|
||
При IMPORT_VERBOSITY>=1, пишутся имена загружаемых (или отвергнутых) файлов конфигурации. Пример: | ||
~~~ | ||
Load /etc/okerr/conf.d/admin.conf | ||
Load /etc/okerr/conf.d/cluster_first.conf | ||
Skip loading /etc/okerr/conf.d/cluster_local.conf ( __IF_CLUSTER_NAME = 'LOCAL' != 'FIRST') | ||
Skip loading /etc/okerr/conf.d/cluster_test.conf ( __IF_CLUSTER_NAME = 'TEST' != 'FIRST') | ||
Load /etc/okerr/conf.d/demo.conf | ||
~~~ | ||
|
||
При IMPORT_VERBOSITY>=2, так же пишется каждый импортируемый символ: | ||
~~~ | ||
Load /etc/okerr/conf.d/admin.conf | ||
ADMINS | ||
ADMINUSER | ||
LOGMAIL | ||
USUALUSER | ||
Load /etc/okerr/conf.d/cluster_first.conf | ||
MACHINES | ||
SYNC_MAP | ||
UP_MAP | ||
... | ||
~~~ | ||
|
||
При IMPORT_VERBOSITY>=3 так же пишется и значение каждого символа (иногда это может быть длинным текстом): | ||
~~~ | ||
Load /etc/okerr/local.d/local.conf | ||
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'localhost.okerr.com', 'dev.okerr.com'] | ||
MYIP = '1.2.3.4' | ||
SITEURL = 'http://localhost/' | ||
~~~ | ||
|
||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
# Коды ошибок | ||
|
||
Сервер okerr может выдавать особые соообщения об ошибках по HTTP. Ошибки выдаются через HTTP ответы с кодом статуса 400 (Bad request) и сообщением об ошибке. Сообщения об ошибках могут начинаться с 'ERROR:*code* *details*', где код - одно из следующих: | ||
|
||
**BAD_METHOD** - Индикатор с таким именем уже есть в проете и он использует не пассивный метод проверки. Таким образом, HTTP апдейт с клиента не ожидается для этого типа индикаторов. Например, такая ошибка будет при попытке создать идикатор типа sslcert. | ||
|
||
|
||
**LIMIT_MAXINDICATORS** - В проекте уже есть максимально допустимое количество индикаторов. Чтобы посмотреть, сколько индикаторов допускается, посмотрите страницу профиля, на ней - параметр maxindicators. Чтобы решить проблему: | ||
- Удалить индикаторы, которые вы не используете | ||
- Отключить индикаторы (они останутся в проекте, но не будут "считаться" при подсчете) | ||
- Переключиться на более высокий план. Если вы новый пользователь на плане 'Space' - вы автоматически получите план 'Alcor' после прохождения тренинга. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
# Установка собственного сервера okerr | ||
## Физический сервер или виртуальный? | ||
Okerr - достаточно большой и сложный проект: веб-приложение (apache/uwsgi), база данный, почтовый сервер, брокер сообщений, несколько systemd демонов okerr. Если вы используете любое другое ПО на сервер, нужно осторожно совмещать их. Так что, мы **настоятельно рекомендуем** использовать выделенный (физический или виртуальный) сервер для сервера okerr. По крайней мере, когда вы устанавливаете его первый раз | ||
|
||
`okerr-install.py` - рекомендуемый способ установки, и он будет описан здесь. Так же есть чеклист для [manual install](ru/Manual install), но он не рекомендуется, если вы не очень хорошо знакомы с okerr. | ||
|
||
## Шаг 1: создание LXC контейнера | ||
~~~ | ||
# host | ||
lxc-create -n okerr -t download -- --dist=debian --release=buster --arch=amd64 | ||
~~~ | ||
|
||
## Шаг 2a (рекомендуемый путь. делайте так) | ||
~~~ | ||
# host: start and attach | ||
lxc-start -n okerr | ||
lxc-attach -n okerr | ||
# VM | ||
apt install git python3 | ||
git clone https://gitlab.com/yaroslaff/okerr-dev.git /opt/okerr | ||
~~~ | ||
|
||
### Шаг 2b (альтернативный путь (исходные коды okerr на хостовой машине). НЕ делайте так, если вам это не нужно.) | ||
~~~ | ||
# host machine | ||
mkdir /var/lib/lxc/okerr/rootfs/opt/okerr | ||
~~~ | ||
|
||
Edit `/var/lib/lxc/okerr/config`, add mount option to config (replace path to okerr-dev repo): | ||
~~~ | ||
lxc.mount.entry = /home/USERNAME/repo/okerr-dev /var/lib/lxc/okerr/rootfs/opt/okerr none bind 0 0 | ||
~~~ | ||
|
||
Continue preparation: | ||
~~~ | ||
# start and attach | ||
lxc-start -n okerr | ||
lxc-attach -n okerr | ||
# VM | ||
mkdir /opt/okerr | ||
apt install git python3 | ||
~~~ | ||
|
||
## Шаг 3: Установка | ||
Замените email в команде и запустите: | ||
~~~ | ||
# inside VM | ||
cd /opt/okerr | ||
# All default values. user: okerr@example.com password: okerr_default_password | ||
./okerr-install.py --local --email USER@EMAIL.COM | ||
# Or explicitly | ||
./okerr-install.py --fix --apache --rmq --email USER@EMAIL.COM --pass MyPass | ||
~~~ | ||
Теперь можно расслабиться и откинуться на спинку кресла. Эта команда установит множество пакетов debian, модулей python, все настроет. На моем ноутбуке это занимает 11 минут. | ||
|
||
## Шаг 4: Послеустановочная конфигурация | ||
По умолчанию okerr настраивается чтобы обслуживать хост dev.okerr.com, так что вы можете установить его в /etc/hosts на вашей рабочей машине (чтобы он указывал на контейнет с okerr): | ||
~~~ | ||
192.168.122.219 dev.okerr.com | ||
~~~ | ||
Или установить/добавить другое имя хоста в файлах `/etc/okerr/local.d/local.conf` и `/etc/apache2/sites-available/okerr.conf` . | ||
|
||
Убедитесь, что вы можете отправлять почту с виртуального хоста. Если нужно - настройке postfix для этого (по умолчанию он использует имя хоста 'okerr'). | ||
|
||
|
||
~~~ | ||
myhostname = okerr #replace to your valid hostname | ||
# inet_protocols = all | ||
inet_protocols = ipv4 | ||
~~~ | ||
|
||
Так же вам нужно установить настройки FROM и SERVER_EMAIL в локальном конфиге (`/etc/okerr/okerr.conf`). Умолчания: | ||
~~~ | ||
SERVER_EMAIL = 'noreply@okerr.com' | ||
FROM = '"okerr robot" <noreply@okerr.com>' | ||
~~~ | ||
|
||
## Использование | ||
На этом этапе вы уже можете зайти на http://dev.okerr.com/ и получить полностью рабочую систему. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
# Ручная установка | ||
|
||
Это более сложный путь чтобы установить базовую часть okerr и предназначан только для опытных администраторов и программистов okerr, кто хочет работать с okerr "под капотом". Так же, это скорее подсказки и чек-листы, а не полное руководство и может быть немного устаревшим. | ||
|
||
Другими словами: лучше используйте рекомендуемую [Автоматическую установку](Install) :) | ||
|
||
## Install required debian packages | ||
~~~shell | ||
sudo apt install python3-dev python3-venv dialog gcc libmariadb-dev-compat libadns1-dev libffi-dev libssl-dev libsasl2-modules redis-server redis-tools libadns1-dev mariadb-server rsyslog postfix cron rabbitmq-server | ||
~~~ | ||
|
||
## Configure redis socket | ||
edit `/etc/redis/redis.conf` append: | ||
~~~ | ||
unixsocket /var/run/redis/redis.sock | ||
unixsocketperm 770 | ||
~~~ | ||
`sudo systemctl restart redis` | ||
|
||
`sudo usermod -a -G redis USER` | ||
|
||
Relogin now, or make sure you will work as user root (not secure) or user with group `redis`. | ||
|
||
## Configure RabbitMQ | ||
edit `/etc/rabbitmq/rabbitmq.config` | ||
~~~ | ||
[ | ||
{rabbit, [ | ||
{tcp_listeners, []}, | ||
{ssl_listeners, [{'0.0.0.0', 5671}]}, | ||
{ssl_options, [ | ||
{cacertfile, "/etc/okerr/ssl/ca.pem"}, | ||
{certfile, "/etc/okerr/ssl/rabbitmq.pem"}, | ||
{verify, verify_peer}, | ||
{fail_if_no_peer_cert, true} | ||
] | ||
} | ||
] | ||
} | ||
]. | ||
~~~ | ||
`systemctl restart rabbitmq-server` | ||
|
||
create vhost and user: | ||
~~~ | ||
sudo rabbitmqctl add_vhost okerr | ||
sudo rabbitmqctl add_user okerr okerr_default_password | ||
sudo rabbitmqctl set_permissions -p okerr okerr ".*" ".*" ".*" | ||
~~~ | ||
|
||
|
||
## Create db user | ||
`mysql -u root` | ||
|
||
~~~sql | ||
CREATE DATABASE okerr CHARACTER SET utf8 COLLATE utf8_general_ci; | ||
CREATE USER 'okerr'@'localhost' IDENTIFIED BY 'okerrpass'; | ||
GRANT ALL ON okerr.* TO 'okerr'@'localhost'; | ||
~~~ | ||
|
||
## Create and activate venv | ||
~~~shell | ||
sudo mkdir /opt/venv/okerr | ||
sudo chown USER /opt/venv/okerr | ||
python3 -m venv /opt/venv/okerr/ | ||
. /opt/venv/okerr/bin/activate | ||
~~~ | ||
|
||
## Install python packages | ||
~~~shell | ||
pip3 install -r requirements.txt | ||
~~~ | ||
|
||
## Create okerr certificates | ||
~~~shell | ||
sudo mkdir -p /etc/okerr/ssl | ||
cd ca | ||
sudo ./mkcert.sh ca | ||
sudo ./mkcert.sh client | ||
sudo ./mkcert.sh client rabbitmq | ||
~~~ | ||
|
||
## Initialize database | ||
~~~ | ||
./manage.py migrate | ||
./manage.py dbadmin --reinit --really | ||
./manage.py profile --create USER@EXAMPLE.COM --pass PASSWORD --textid okerr | ||
./manage.py group --assign Admin --user USER@EXAMPLE.COM --infinite | ||
~~~ | ||
|
||
## Create local config (optional) | ||
~~~ | ||
sudo mkdir /etc/okerr/conf.d | ||
sudo vim /etc/okerr/conf.d/local.conf | ||
~~~ | ||
enable DEBUG in `local.conf`: | ||
~~~ | ||
DEBUG=True | ||
~~~ | ||
|
||
## Start mqsender (task manager) | ||
~~~ | ||
./mqsender.py -v | ||
~~~ | ||
|
||
## Start sensor | ||
~~~ | ||
sensor.py -v | ||
~~~ | ||
|
||
## Start Okerr UI development UI | ||
~~~ | ||
./manage.py runserver | ||
~~~ |
Oops, something went wrong.