Перейти к основному содержанию

Seafile 9.0.2 — установка на Debian 11

Seafile

Seafile — это личное облачное хранилище для хранения данных в стиле Dropbox.

https://www.seafile.com

Сегодня мы установим Seafile 9.0.2 на Debian 11.

  • Имеется сервер с операционной системой Debian 11. Где-то в облаке.
  • Seafile для безопасности запустим под отдельным пользователем как службы.
  • В качестве БД используем MySQL 8 на том же сервере.
  • Дополнительно поднимем и настроим Nginx.

Доступна версия 9.0.2 64bit.

https://www.seafile.com/en/download/

Ссылки

Ранее я уже публиковал статью про установку Seafile на Ubuntu:

Seafile 7.1.1 — установка на Ubuntu 18.04 LTS

В новой статье будет несколько отличий.

  1. Ранее я устанавливал Seafile 7.1.1, теперь установим более новую версию Seafile 9.0.2.
  2. Ранее была операционная система Ubuntu 18.04, сейчас Debian 11.

https://www.seafile.com

Мануал:

https://manual.seafile.com/

База данных MySQL 8 для Seafile

Установка MySQL 8 на Debian 11 у меня уже есть в отдельной статье:

Debian 11 — установка MySQL 8

Точно так же устанавливаем и перемещаем базу в директорию /opt.

Создаём три базы:

  • seafile-ccnet
  • seafile-db
  • seafile-seahub

и пользователя MySQL: seafile:

mysql -u root -p
CREATE SCHEMA `seafile-ccnet` DEFAULT CHARACTER SET utf8 ;
CREATE SCHEMA `seafile-db` DEFAULT CHARACTER SET utf8 ;
CREATE SCHEMA `seafile-seahub` DEFAULT CHARACTER SET utf8 ;
CREATE USER 'seafile'@'localhost' identified by 'ПАРОЛЬ';
GRANT ALL PRIVILEGES ON `seafile-ccnet`.* to `seafile`@localhost;
GRANT ALL PRIVILEGES ON `seafile-db`.* to `seafile`@localhost;
GRANT ALL PRIVILEGES ON `seafile-seahub`.* to `seafile`@localhost;

seafile

Меняем настройки безопасности пользователю:

ALTER USER 'seafile'@'localhost' IDENTIFIED WITH mysql_native_password BY 'ПАРОЛЬ';

Установка пакетов

Устанавливаем пакеты, хочу обратить внимание на пакет python3-dev, который в официальном мануале не указан (работаем под ROOT):

apt-get update
apt-get install -y python3 python3-dev python3-setuptools python3-pip libmysqlclient-dev
apt-get install -y memcached libmemcached-dev 
pip3 install --timeout=3600 django==3.2.* Pillow pylibmc captcha jinja2 sqlalchemy==1.4.3 \
django-pylibmc django-simple-captcha python3-ldap mysqlclient pycryptodome==3.12.0 cffi==1.14.0

Создание директории и пользователя

Для Seafile создадим директорию /opt/seafile:

mkdir /opt/seafile
cd /opt/seafile

seafile

Создаём пользователя, под которым будет работать seafile (я назвал его sf) и назначаем права:

useradd -m -s /bin/bash sf
cd /
chown -R sf\: ./opt/seafile/
cd /opt
ls -fla | grep seafile

seafile

Установка Seafile Server

Работаем под пользователем sf:

su - sf

Скачиваем и распаковываем дистрибутив:

cd /opt/seafile
wget https://download.seadrive.org/seafile-server_9.0.2_x86-64.tar.gz
tar -xf seafile-server_9.0.2_x86-64.tar.gz
ls -Fla

seafile

Устанавливаем Seafile:

cd /opt/seafile/seafile-server-9.0.2/
./setup-seafile-mysql.sh

Запускается мастер установки. В процессе установки нам зададут вопросы, отвечаем на них, у вас будут собственные ответы:

  1. What is the name of the server? It will be displayed on the client. Пишу — seafile.
  2. What is the ip or domain of the server? Домена пока нет, пишу прямой IP — 46.39.246.23.
  3. Which port do you want to use for the seafile fileserver? Порт по умолчанию 8082 — устраивает.
  4. Please choose a way to initialize seafile databases:
    [1] Create new ccnet/seafile/seahub databases
    [2] Use existing ccnet/seafile/seahub databases
    Я уже создал все БД, указываю 2.
  5. What is the host of mysql server? По умолчанию сервер БД localhost — localhost.
  6. What is the port of mysql server? Порт по умолчанию 3306, меня устраивает.
  7. Which mysql user to use for seafile? Указываем имя пользователя MySQL. Я пишу — seafile.
  8. What is the password for mysql user "seafile"? Указываем пароль от пользователя MySQL.
  9. Enter the existing database name for ccnet: Пишу — seafile-ccnet.
  10. Enter the existing database name for seafile: Пишу — seafile-db.
  11. Enter the existing database name for seahub: Пишу — seafile-seahub.

seafile

Проверяем настройки. Нажимаем Enter. Устанавливается Seafile Server.

seafile

Пробуем запустить seafile:

cd /opt/seafile/seafile-server-latest/
./seafile.sh start

seafile

Пробуем запустить seahub:

./seahub.sh start

При первом запуске нас попросят создать админа для seafile, укажите email и пароль.

seafile

Проверим, что сервисы seafile и seahub работают и используют порты 8000 и 8082:

netstat -plntu

seafile

Останавливаем службы для дальнейшей настройки:

./seahub.sh stop
./seafile.sh stop

Настройка автозапуска Seafile в качестве сервисов

Работаем под рутом. Создаём сервис seafile:

cd /etc/systemd/system/
vim seafile.service

Содержимое:

[Unit]
Description=Seafile
After=network.target
[Service]
Type=forking
ExecStart=/opt/seafile/seafile-server-latest/seafile.sh start
ExecStop=/opt/seafile/seafile-server-latest/seafile.sh stop
LimitNOFILE=infinity
User=sf
Group=sf
[Install]
WantedBy=multi-user.target

Создаём сервис seahub:

vim seahub.service

Содержимое:

[Unit]
Description=Seafile hub
After=network.target seafile.service
[Service]
Type=forking
ExecStart=/opt/seafile/seafile-server-latest/seahub.sh start
ExecStop=/opt/seafile/seafile-server-latest/seahub.sh stop
User=sf
Group=sf
[Install]
WantedBy=multi-user.target

Запускаем сервисы и настраиваем автозагрузку:

systemctl daemon-reload
systemctl start seafile
systemctl start seahub
systemctl enable seafile
systemctl enable seahub

Проверяем:

systemctl status seafile

seafile

systemctl status seahub

seafile

Службы настроены.

Установка и настройка Nginx

Выполним установку Nginx и первоначальную настройку Seafile.

Установим nginx:

apt-get install nginx -y

Проверим что настроен автозапуск:

systemctl is-enabled nginx

Если автозапуск не настроен, то можно включить:

systemctl enable nginx

Проверим:

systemctl status nginx

seafile

Создаём конфигурационный файл для Seafile:

cd /etc/nginx/
vim sites-available/seafile

Содержимое:

server {
        listen 80;
        server_name _;

        server_tokens off;
        proxy_set_header X-Forwarded-For $remote_addr;

        location / {
            proxy_pass         http://127.0.0.1:8000;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
            proxy_read_timeout  1200s;

            # used for view/edit office file via Office Online Server
            client_max_body_size 0;

            access_log      /var/log/nginx/seahub.access.log;
            error_log       /var/log/nginx/seahub.error.log;
        }

        location /seafhttp {
            rewrite ^/seafhttp(.*)$ $1 break;
            proxy_pass http://127.0.0.1:8082;
            client_max_body_size 0;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_connect_timeout  36000s;
            proxy_read_timeout  36000s;
            proxy_send_timeout  36000s;
            send_timeout  36000s;
        }
        location /media {
            root /opt/seafile/seafile-server-latest/seahub;
        }
}

seafile

Применяем конфигурацию:

rm -f /etc/nginx/sites-enabled/default
ln -s /etc/nginx/sites-available/seafile /etc/nginx/sites-enabled/
nginx -t
systemctl restart nginx

seafile

Начальная настройка Seafile Server

Работаем под пользователем sf:

su - sf

Переходим в директорию с файлами конфигурации:

cd /opt/seafile/conf/

ccnet.conf

Настраиваем ccnet.conf, указываем SERVICE_URL:

vim scnet.conf

Содержимое:

[General]
SERVICE_URL = http://46.39.246.23
[Database]
ENGINE = mysql
HOST = 127.0.0.1
PORT = 3306
USER = seafile
PASSWD = ПАРОЛЬ
DB = seafile-ccnet
CONNECTION_CHARSET = utf8

seafile.conf

Настраиваем seafile.conf, указываем host и keep_days:

vim seafile.conf

Содержимое:

[fileserver]
host = 0.0.0.0
port = 8082
[database]
type = mysql
host = 127.0.0.1
port = 3306
user = seafile
password = ПАРОЛЬ
db_name = seafile-db
connection_charset = utf8
[history]
keep_days = 30

seahub_settings.py

Настраиваем seahub_settings.py:

mkdir /opt/seafile/seahub-data/thumbnail/
mkdir /opt/seafile/seahub-data/thumbnail/thumb/
vim seahub_settings.py

Содержимое:

# -*- coding: utf-8 -*-
SECRET_KEY = "СОЛЬ"
FILE_SERVER_ROOT = 'http://46.39.246.23/seafhttp'
# For security consideration, please set to match the host/domain of your site, e.g.,
ALLOWED_HOSTS = ['.example.com'].
# Please refer https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts for details.
ALLOWED_HOSTS = ['46.39.246.23']
# Enalbe or disalbe registration on web. Default is `False`.
ENABLE_SIGNUP = False
DATABASES = {
'default': { 'ENGINE': 'django.db.backends.mysql',
'NAME': 'seafile-seahub',
'USER': 'seafile',
'PASSWORD': 'ПАРОЛЬ',
'HOST': '127.0.0.1',
'PORT': '3306',
'OPTIONS': {'charset': 'utf8mb4'},
}
}
ENABLE_SETTINGS_VIA_WEB = False
TIME_ZONE = 'Europe/Moscow'
LANGUAGE_CODE = 'ru'
LANGUAGES = (
('en', 'English'),
('ru', 'Русский'),
)
SITE_NAME = 'Seafile'
# Absolute filesystem path to the directory that will hold thumbnail files.
THUMBNAIL_ROOT = '/opt/seafile/seahub-data/thumbnail/thumb/'
SERVICE_URL = 'http://46.39.246.23'

Первый запуск

Проверяем что сайт заработал на HTTP протоколе.

http://46.39.246.23

seafile

Проверяем, что выполняется вход под созданным e-mail и паролем админа.

Настройка HTTPS и сертификата SSL

Правим конфигурационный файл для Seafile:

vim sites-available/seafile

В "server_name _;" указываем домен:

server_name internet-lab.ru;

Перезапускаем Nginx:

service nginx restart

Переходим в директорию с файлами конфигурации:

cd /opt/seafile/conf/

Правим ccnet.conf:

vim scnet.conf

В "SERVICE_URL" указываем домен и HTTPS:

SERVICE_URL = https://internet-lab.ru

Правим seahub_settings.py:

vim seahub_settings.py

В "SERVICE_URL" указываем домен и HTTPS. В "FILE_SERVER_ROOT" указываем домен и HTTPS. В "ALLOWED_HOSTS" добавляем домен.

SERVICE_URL = https://internet-lab.ru
FILE_SERVER_ROOT = 'https://internet-lab.ru/seafhttp
ALLOWED_HOSTS = ['46.39.246.23','internet-lab.ru']

Перезапускаем Seafile:

service seafile restart
service seahub restart

Устанавливаем certbot:

Let's Encrypt — настройка certbot в Debian

Проверяем работу сайта по HTTPS:

ssl

Сайт работает.

Конфигурация Seafile

Переходим в директорию с файлами конфигурации:

cd /opt/seafile/conf/

Настраиваем seahub_settings.py согласно своим потребностям:

  • # -*- coding: utf-8 -*-
    SECRET_KEY = "b'xxxxdr^83)(xxx(yxxxwr)1t#k#7mi-!q^mzh_xxxxp4=xxx)n'"
    SERVICE_URL = 'https://internet-lab.ru'
    FILE_SERVER_ROOT = 'https://internet-lab.ru/seafhttp'
    
    # For security consideration, please set to match the host/domain of your site, e.g.,
    ALLOWED_HOSTS = ['.example.com'].
    # Please refer https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts for details.
    ALLOWED_HOSTS = ['46.39.246.23','internet-lab.ru']
    
    # Enable or disable registration on web. Default is `False`.
    ENABLE_SIGNUP = False
    
    # Activate or deactivate user when registration complete. Default is `True`.
    # If set to `False`, new users need to be activated by admin in admin panel.
    ACTIVATE_AFTER_REGISTRATION = False
    
    # Whether to send email when a system admin adding a new member. Default is `True`.
    SEND_EMAIL_ON_ADDING_SYSTEM_MEMBER = True
    
    # Whether to send email when a system admin resetting a user's password. Default is `True`.
    SEND_EMAIL_ON_RESETTING_USER_PASSWD = True
    
    # Send system admin notify email when user registration is complete. Default is `False`.
    NOTIFY_ADMIN_AFTER_REGISTRATION = True
    
    # Remember days for login. Default is 7
    LOGIN_REMEMBER_DAYS = 14
    
    # Attempt limit before showing a captcha when login.
    LOGIN_ATTEMPT_LIMIT = 3
    
    # deactivate user account when login attempts exceed limit
    # Since version 5.1.2 or pro 5.1.3
    FREEZE_USER_ON_LOGIN_FAILED = False
    
    # mininum length for user's password
    USER_PASSWORD_MIN_LENGTH = 6
    
    # LEVEL based on four types of input:
    # num, upper letter, lower letter, other symbols
    # '3' means password must have at least 3 types of the above.
    USER_PASSWORD_STRENGTH_LEVEL = 3
    
    # default False, only check USER_PASSWORD_MIN_LENGTH
    # when True, check password strength level, STRONG(or above) is allowed
    USER_STRONG_PASSWORD_REQUIRED = False
    
    # Force user to change password when admin add/reset a user.
    # Added in 5.1.1, deafults to True.
    FORCE_PASSWORD_CHANGE = True
    
    # Age of cookie, in seconds (default: 2 weeks).
    SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
    
    # Whether a user's session cookie expires when the Web browser is closed.
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False
    
    # Whether to save the session data on every request. Default is `False`
    SESSION_SAVE_EVERY_REQUEST = False
    
    # Whether enable personal wiki and group wiki. Default is `False`
    # Since 6.1.0 CE
    ENABLE_WIKI = True
    
    # In old version, if you use Single Sign On, the password is not saved in Seafile.
    # Users can't use WebDAV because Seafile can't check whether the password is correct.
    # Since version 6.3.8, you can enable this option to let user's to specific a password for WebDAV login.
    # Users login via SSO can use this password to login in WebDAV.
    # Enable the feature. pycryptodome should be installed first.
    # sudo pip install pycryptodome==3.7.2
    ENABLE_WEBDAV_SECRET = True
    
    # Turn on this option to let users to add a label to a library snapshot. Default is `False`
    ENABLE_REPO_SNAPSHOT_LABEL = False
    
    # mininum length for password of encrypted library
    REPO_PASSWORD_MIN_LENGTH = 8
    
    # mininum length for password for share link (since version 4.4)
    SHARE_LINK_PASSWORD_MIN_LENGTH = 8
    
    # minimum expire days for share link (since version 6.3.6)
    SHARE_LINK_EXPIRE_DAYS_MIN = 0 # default is 0, no limit.
    
    # maximum expire days for share link (since version 6.3.6)
    SHARE_LINK_EXPIRE_DAYS_MAX = 0 # default is 0, no limit.
    
    # default expire days for share link (since version 6.3.8)
    # only valid when SHARE_LINK_EXPIRE_DAYS_MIN and SHARE_LINK_EXPIRE_DAYS_MAX is configured
    # should be greater than or equal to MIN and less than or equal to MAX
    SHARE_LINK_EXPIRE_DAYS_DEFAULT = 0
    
    # force user login when view file/folder share link (since version 6.3.6)
    SHARE_LINK_LOGIN_REQUIRED = False
    
    # enable water mark when view(not edit) file in web browser (since version 6.3.6)
    ENABLE_WATERMARK = False
    
    # Disable sync with any folder. Default is `False`
    # NOTE: since version 4.2.4
    DISABLE_SYNC_WITH_ANY_FOLDER = True
    
    # Enable or disable library history setting
    ENABLE_REPO_HISTORY_SETTING = True
    
    # Enable or disable normal user to create organization libraries
    # Since version 5.0.5
    ENABLE_USER_CREATE_ORG_REPO = True
    
    # Enable or disable user share library to any group
    # Since version 6.2.0
    ENABLE_SHARE_TO_ALL_GROUPS = True
    
    # Enable or disable user to clean trash (default is True)
    # Since version 6.3.6
    ENABLE_USER_CLEAN_TRASH = True
    
    # Whether to use pdf.js to view pdf files online. Default is `True`, you can turn it off.
    # NOTE: since version 1.4.
    USE_PDFJS = True
    
    # Online preview maximum file size, defaults to 30M.
    FILE_PREVIEW_MAX_SIZE = 30 * 1024 * 1024
    
    # Extensions of previewed text files.
    # NOTE: since version 6.1.1
    TEXT_PREVIEW_EXT = """ac, am, bat, c, cc, cmake, cpp, cs, css, diff, el, h, html, htm, java, js, json, less, make, org, php, pl, properties, py, rb, scala, script, sh, sql, txt, text, tex, vi, vim, xhtml, xml, log, csv, groovy, rst, patch, go"""
    
    # Enable or disable thumbnails
    # NOTE: since version 4.0.2
    ENABLE_THUMBNAIL = True
    
    # Seafile only generates thumbnails for images smaller than the following size.
    # Since version 6.3.8 pro, suport the psd online preview.
    THUMBNAIL_IMAGE_SIZE_LIMIT = 30 # MB
    
    # Enable or disable thumbnail for video. ffmpeg and moviepy should be installed first.
    # For details, please refer to https://manual.seafile.com/deploy/video_thumbnails.html
    # NOTE: since version 6.1
    ENABLE_VIDEO_THUMBNAIL = True
    
    # Use the frame at 5 second as thumbnail
    THUMBNAIL_VIDEO_FRAME_TIME = 1
    
    # Absolute filesystem path to the directory that will hold thumbnail files.
    THUMBNAIL_ROOT = '/opt/seafile/seahub-data/thumbnail/thumb/'
    
    # Default size for picture preview. Enlarge this size can improve the preview quality.
    # NOTE: since version 6.1.1
    THUMBNAIL_SIZE_FOR_ORIGINAL = 1024
    
    # Enable cloude mode and hide `Organization` tab.
    # CLOUD_MODE = True
    
    # Disable global address book
    # ENABLE_GLOBAL_ADDRESSBOOK = False
    
    # Enable authentication with ADFS
    # Default is False
    # Since 6.0.9
    # ENABLE_ADFS_LOGIN = True
    
    # Enable authentication wit Kerberos
    # Default is False
    # ENABLE_KRB5_LOGIN = True
    
    # Enable authentication with Shibboleth
    # Default is False
    # ENABLE_SHIBBOLETH_LOGIN = True
    
    # Disable settings via Web interface in system admin->settings
    # Default is True
    # Since 5.1.3
    ENABLE_SETTINGS_VIA_WEB = False
    
    # Choices can be found here:
    # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
    # although not all choices may be available on all operating systems.
    # If running in a Windows environment this must be set to the same as your
    # system time zone.
    TIME_ZONE = 'Europe/Moscow'
    
    # Language code for this installation. All choices can be found here:
    # http://www.i18nguy.com/unicode/language-identifiers.html
    # Default language for sending emails.
    LANGUAGE_CODE = 'ru'
    
    # Custom language code choice.
    LANGUAGES = (
    ('en', 'English'),
    ('ru', 'Русский'),
    )
    
    # Set this to your website/company's name. This is contained in email notifications and
    welcome message when user login for the first time.
    SITE_NAME = 'Seafile'
    
    # Browser tab's title
    SITE_TITLE = 'Seafile internet-lab.ru'
    
    # If you don't want to run seahub website on your site's root path, set this option to your preferred path.
    # e.g. setting it to '/seahub/' would run seahub on http://example.com/seahub/.
    # SITE_ROOT = '/'
    
    # Max number of files when user upload file/folder.
    # Since version 6.0.4
    MAX_NUMBER_OF_FILES_FOR_FILEUPLOAD = 500
    
    # Control the language that send email. Default to user's current language.
    # Since version 6.1.1
    # SHARE_LINK_EMAIL_LANGUAGE = ''
    # Interval for browser requests unread notifications
    # Since PRO 6.1.4 or CE 6.1.2
    UNREAD_NOTIFICATIONS_REQUEST_INTERVAL = 3 * 60 # seconds
    
    # Whether to allow user to delete account, change login password or update basic user
    # info on profile page.
    # Since PRO 6.3.10
    ENABLE_DELETE_ACCOUNT = False
    ENABLE_UPDATE_USER_INFO = True
    ENABLE_CHANGE_PASSWORD = True
    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'seafile-seahub',
    'USER': 'seafile',
    'PASSWORD': 'ПАРОЛЬ',
    'HOST': '127.0.0.1',
    'PORT': '3306',
    'OPTIONS': {'charset': 'utf8mb4'},
    }
    }
    
    #LOGGING = {
    # 'version': 1,
    # 'disable_existing_loggers': False,
    # 'formatters': {
    # 'verbose': {
    # 'format': '%(process)-5d %(thread)d %(name)-50s %(levelname)-8s %(message)s'
    # },
    # 'standard': {
    # 'format': '%(asctime)s [%(levelname)s] %(name)s:%(lineno)s %(funcName)s %(message)s'
    # },
    # 'simple': {
    # 'format': '[%(asctime)s] %(name)s %(levelname)s %(message)s',
    # 'datefmt': '%d/%b/%Y %H:%M:%S'
    # },
    # },
    # 'filters': {
    # 'require_debug_false': {
    # '()': 'django.utils.log.RequireDebugFalse',
    # },
    # 'require_debug_true': {
    # '()': 'django.utils.log.RequireDebugTrue',
    # },
    # },
    # 'handlers': {
    # 'console': {
    # 'filters': ['require_debug_true'],
    # 'class': 'logging.StreamHandler',
    # 'formatter': 'simple'
    # },
    # 'syslog': {
    # 'class': 'logging.handlers.SysLogHandler',
    # 'address': '/dev/log',
    # 'formatter': 'standard'
    # },
    # },
    #
    # 'loggers': {
    # # root logger
    # # All logs printed by Seahub and any third party libraries will be handled by this logger.
    # '': {
    # 'handlers': ['console', 'syslog'],
    # 'level': 'DEBUG', # Logs when log level is higher than info. Level can be any one of DEBUG, INFO, WARNING, ERROR, CRITICAL.
    # 'disabled': False
    # },
    # # This logger recorded logs printed by Django Framework. For example, when you see 5xx page error, you should check the logs recorded by this logger.
    # 'django.request': {
    # 'handlers': ['console', 'syslog'],
    # 'level': 'DEBUG',
    # 'propagate': False,
    #
    # },
    #
    # },
    #
    #}
    

Это не все настройки, больше смотрите в документации.

 

Похожие материалы

Seafile — установка на Ubuntu 18.04 LTS

Seafile — это личное облачное хранилище для хранения данных в стиле Dropbox. Сегодня мы развернём это хранилище на виртуальном сервере. В качестве гипервизора у нас ESXi 6.7 Update 1.

Seafile сервер для Linux версия 7.0.4

26 июля 2019 года вышла новая версия сервера Seafile для Linux — 7.0.4. Релиз доступен для скачивания. До этого был успешный релиз 7.0.3. На этот раз попробую обновиться дальше до версии 7.0.4.