> For the complete documentation index, see [llms.txt](https://agrat.gitbook.io/admin/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://agrat.gitbook.io/admin/utility/lsyncd.md).

# lsyncd

{% embed url="<https://axkibe.github.io/lsyncd/>" %}

## Установка

{% tabs %}
{% tab title="Bash" %}

```bash
apt instal lsyncd
```

{% endtab %}
{% endtabs %}

## Папки

{% tabs %}
{% tab title="Bash" %}

```bash
mkdir -p /etc/lsyncd && mkdir -p /var/log/lsyncd && mkdir -p /etc/lsyncd/conf.d/
```

{% endtab %}
{% endtabs %}

## Конфиг

{% tabs %}
{% tab title="Bash" %}

```bash
vi /etc/lsyncd/lsyncd.conf.lua
```

{% endtab %}
{% endtabs %}

Для синка в обе стороны, обязательный параметр "**temp\_dir**"

**ssh** - указывать не обязательно, если настройки стандартны

{% tabs %}
{% tab title="Lua" %}

```lua
settings {
      logfile    = "/var/log/lsyncd/lsyncd.log",
      statusFile = "/var/log/lsyncd/lsyncd_status.log",
      statusInterval = 20,
      nodaemon   = false
}
sync {
      default.rsyncssh,
      source="/path/to/dir",
      host="new_server",
      targetdir="/path/to/dir/new_server",
      excludeFrom="/etc/lsyncd/linux_notes.exclude",
      delay=10,
      delete = true,
      rsync = {
               archive = true,
               compress = false,
               whole_file = false,
               sparse = true,
               update = true,
               temp_dir="/tmp/",
               links = true,
               times = true,
               protect_args = false,
               acls = true,
               verbose = true
              },
      ssh = {
        port = 22,
        _extra = {"/usr/bin/ssh -l user -p 22 -i /home/user/.ssh/id_rsa -o StrictHostKeyChecking=no"}
    } 
}
```

{% endtab %}
{% endtabs %}

### Синк одного файла

{% tabs %}
{% tab title="Lua" %}

```lua
sync {
      default.rsyncssh,
      source="/etc/security",
      host="new_server",
      targetdir="/etc/security",
      delay=10,
      delete=false,
      rsync = {
               archive = true,
               compress = false,
               whole_file = false,
               sparse = true,
               update = true,
               temp_dir="/tmp/",
               links = true,
               times = true,
               protect_args = false,
               acls = true,
               verbose = true,
               _extra = {
                    "--include=limits.conf",
                    "--exclude=*"
               }
      },
      ssh = {
        port = 22
      }
}
```

{% endtab %}
{% endtabs %}

## Исключения

{% tabs %}
{% tab title="Bash" %}

```bash
vi /etc/lsyncd/linux_notes.exclude
```

{% endtab %}
{% endtabs %}

```
.git/*
.*
```

## **Настройки ядра**

У **inotify** есть три параметра (см. ls /proc/sys/fs/inotify/):&#x20;

**max\_queued\_events** — максимальное число событий в очереди; **default** = 16384;&#x20;

**max\_user\_instances** — сколько инстансов inotify может запустить один пользоваетль; **default** = 128;&#x20;

**max\_user\_watches** — сколько файлов может отслеживать один пользоваль; **default** = 8192.

{% tabs %}
{% tab title="Bash" %}

```bash
echo "
fs.inotify.max_user_watches = 16777216
fs.inotify.max_queued_events = 65536
" >> /etc/sysctl.conf
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Bash" %}

```bash
sysctl -p
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Bash" %}

```bash
echo 16777216 > /proc/sys/fs/inotify/max_user_watches
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Bash" %}

```bash
echo 65536 > /proc/sys/fs/inotify/max_queued_events
```

{% endtab %}
{% endtabs %}

## Example

### Синк на несколько серверов

{% tabs %}
{% tab title="Lua" %}

```lua
settings = {
   delay        = 1,
   maxProcesses = 3,
   logfile = "/var/log/lsyncd/lsyncd.log",
   statusFile = "/var/log/lsyncd/lsyncd.stat",
}

targetlist = {
 "1.0.0.2:/var/www/html", 
 "1.0.0.3:/var/www/html"
}

for _, server in ipairs(targetlist) do
  sync{ default.rsync,
    source="/var/www/html",
	rsyncOps="-rltvupgo"
    target=server
  }
end
```

{% endtab %}
{% endtabs %}

### Отдельный файл для каждого sync

{% tabs %}
{% tab title="Lua" %}

```lua
local confdir = '/etc/lsyncd/conf.d/'
local entries = readdir( confdir )

for name, isdir in pairs( entries ) do
    if not isdir then
        dofile( confdir .. name )
    end
end
```

{% endtab %}
{% endtabs %}

<https://github.com/axkibe/lsyncd/issues/441#issuecomment-293287126>

## Start/stop

```
systemctl restart lsyncd
systemctl enable lsyncd
```

## Errors

### ssh\_exchange\_identification: read: Connection reset by peer

при большом количестве файлов для синхронизации, правим в файле **/etc/ssh/sshd\_config** на сервере приемнике правим:

```bash
MaxSessions 100
MaxStartups 100:30:1000
```

**MaxSessions** Задает максимальное количество открытых сеансов, разрешенных для одного сетевого подключения. По умолчанию 10.

**MaxStartups**. Запись параметра имеет форму "**start:rate:full**". В нашем случае она означает отключение с вероятностью 30% при наличии 100 неаутентифицированных связей, с линейным ростом вероятности до 100% при достижении 1000.
