ラベル nginx の投稿を表示しています。 すべての投稿を表示
ラベル nginx の投稿を表示しています。 すべての投稿を表示

2023年9月24日日曜日

ホームサーバーの環境移行(5)

前回nextcloudの移行で試行錯誤していたら、気づいたら数か月経っていた。経っていたに。

おさらい

事前準備

前回の記事参照

nextcloud用のdockerを作成

drwxr-xr-x 2 nextcloud_docker users  4096  6月 29 00:19 cert
drwxr-xr-x 4           200081 200081 4096  3月 25 10:26 data
-rw-r--r-- 1 nextcloud_docker users   107  2月 27 00:32 db.env
-rw-r--r-- 1 nextcloud_docker root   2106  6月 28 06:02 docker-compose.yml
-rw-r--r-- 1 nextcloud_docker users  7797  6月 29 00:21 nginx.conf
db.env 
---
MYSQL_ROOT_PASSWORD=********
MYSQL_PASSWORD=********
MYSQL_DATABASE=nextcloud
MYSQL_USER=nextcloud
docker-compose.yml 
---
version: '3'

services:
  db:
    image: mariadb:10.5
    command: --transaction-isolation=READ-COMMITTED --log-bin=binlog --binlog-format=ROW
    restart: always
    volumes:
      - ./data/db:/var/lib/mysql
    environment:
      - MARIADB_AUTO_UPGRADE=1
      - MARIADB_DISABLE_UPGRADE_BACKUP=1
    env_file:
      - db.env
    ports:
      - 23306:3306

  redis:
    image: redis:alpine
    restart: always

  app:
    image: nextcloud:fpm-alpine
    restart: always
    volumes:
      - ./data/nextcloud:/var/www/html
    environment:
      - MYSQL_HOST=db
      - REDIS_HOST=redis
      - PHP_MEMORY_LIMIT=4096M
      - PHP_UPLOAD_LIMIT=4096M
    env_file:
      - db.env
    depends_on:
      - db
      - redis

  web:
    image: nginx
    restart: always
    ports:
      - 28080:80
      - 20443:443
    volumes:
      - ./data/nextcloud:/var/www/html:ro
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./cert:/etc/letsencrypt/live/******.jp:ro
    depends_on:
      - app

  cron:
    image: nextcloud:fpm-alpine
    restart: always
    volumes:
      - ./data/nextcloud:/var/www/html
    entrypoint: /cron.sh
    depends_on:
      - db
      - redis

volumes:
  db:
  nextcloud:
nginx.conf 
---
worker_processes auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    # Prevent nginx HTTP Server Detection
    server_tokens   off;

    keepalive_timeout  65;

    upstream php-handler {
        server app:9000;
    }

    server {
        listen 80;

	# SSL configuration
	#
	listen 443 ssl default_server;
	#listen [::]:443 ssl default_server;
 	#ssl_certificate /etc/nginx/server.crt;
	#ssl_certificate_key /etc/nginx/server.key;
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
	ssl_ciphers HIGH:!aNULL:!MD5;
	ssl_certificate     /etc/letsencrypt/live/******.jp/nginx.pem;
	ssl_certificate_key /etc/letsencrypt/live/******.jp/nginx.key;
	
	server_name ******.jp;


        # set max upload size
        client_max_body_size 512M;
        fastcgi_buffers 64 4K;

        # Enable gzip but do not remove ETag headers
        gzip on;
        gzip_vary on;
        gzip_comp_level 4;
        gzip_min_length 256;
        gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
        gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

        # Pagespeed is not supported by Nextcloud, so if your server is built
        # with the `ngx_pagespeed` module, uncomment this line to disable it.
        #pagespeed off;

        # HTTP response headers borrowed from Nextcloud `.htaccess`
        add_header Referrer-Policy                      "no-referrer"   always;
        add_header X-Content-Type-Options               "nosniff"       always;
        add_header X-Download-Options                   "noopen"        always;
        add_header X-Frame-Options                      "SAMEORIGIN"    always;
        add_header X-Permitted-Cross-Domain-Policies    "none"          always;
        add_header X-Robots-Tag                         "none"          always;
        add_header X-XSS-Protection                     "1; mode=block" always;

        # Remove X-Powered-By, which is an information leak
        fastcgi_hide_header X-Powered-By;

        # Path to the root of your installation
        root /var/www/html;

        # Specify how to handle directories -- specifying `/index.php$request_uri`
        # here as the fallback means that Nginx always exhibits the desired behaviour
        # when a client requests a path that corresponds to a directory that exists
        # on the server. In particular, if that directory contains an index.php file,
        # that file is correctly served; if it doesn't, then the request is passed to
        # the front-end controller. This consistent behaviour means that we don't need
        # to specify custom rules for certain paths (e.g. images and other assets,
        # `/updater`, `/ocm-provider`, `/ocs-provider`), and thus
        # `try_files $uri $uri/ /index.php$request_uri`
        # always provides the desired behaviour.
        index index.php index.html /index.php$request_uri;

        # Rule borrowed from `.htaccess` to handle Microsoft DAV clients
        location = / {
            if ( $http_user_agent ~ ^DavClnt ) {
                return 302 /remote.php/webdav/$is_args$args;
            }
        }

        location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
        }

        # Make a regex exception for `/.well-known` so that clients can still
        # access it despite the existence of the regex rule
        # `location ~ /(\.|autotest|...)` which would otherwise handle requests
        # for `/.well-known`.
        location ^~ /.well-known {
            # The rules in this block are an adaptation of the rules
            # in `.htaccess` that concern `/.well-known`.

            location = /.well-known/carddav { return 301 /remote.php/dav/; }
            location = /.well-known/caldav  { return 301 /remote.php/dav/; }

            location /.well-known/acme-challenge    { try_files $uri $uri/ =404; }
            location /.well-known/pki-validation    { try_files $uri $uri/ =404; }

            # Let Nextcloud's API for `/.well-known` URIs handle all other
            # requests by passing them to the front-end controller.
            return 301 /index.php$request_uri;
        }

        # Rules borrowed from `.htaccess` to hide certain paths from clients
        location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/)  { return 404; }
        location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console)                { return 404; }

        # Ensure this block, which passes PHP files to the PHP process, is above the blocks
        # which handle static assets (as seen below). If this block is not declared first,
        # then Nginx will encounter an infinite rewriting loop when it prepends `/index.php`
        # to the URI, resulting in a HTTP 500 error response.
        location ~ \.php(?:$|/) {
            # Required for legacy support
            rewrite ^/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+|.+\/richdocumentscode\/proxy) /index.php$request_uri;

            fastcgi_split_path_info ^(.+?\.php)(/.*)$;
            set $path_info $fastcgi_path_info;

            try_files $fastcgi_script_name =404;

            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $path_info;
            #fastcgi_param HTTPS on;

            fastcgi_param modHeadersAvailable true;         # Avoid sending the security headers twice
            fastcgi_param front_controller_active true;     # Enable pretty urls
            fastcgi_pass php-handler;

            fastcgi_intercept_errors on;
            fastcgi_request_buffering off;
        }

        location ~ \.(?:css|js|svg|gif)$ {
            try_files $uri /index.php$request_uri;
            expires 6M;         # Cache-Control policy borrowed from `.htaccess`
            access_log off;     # Optional: Don't log access to assets
        }

        location ~ \.woff2?$ {
            try_files $uri /index.php$request_uri;
            expires 7d;         # Cache-Control policy borrowed from `.htaccess`
            access_log off;     # Optional: Don't log access to assets
        }

        # Rule borrowed from `.htaccess`
        location /remote {
            return 301 /remote.php$request_uri;
        }

        location / {
            try_files $uri $uri/ /index.php$request_uri;
        }
    }
}

動作確認

docker-compose -H unix:///run/user/1004/docker.sock up

これで初期状態までは行けた

現行nextcloudからデータ引き継ぎ

現行サーバーからバックアップ作成

dbデータ

  • mysqldump
mysqldump --single-transaction -h localhost -u nextcloud -p nextcloud > nextcloud-sqlbkp.bak

dataファイル

sudo tar zcvf /mnt/4Traid1/nextcloud_data_20230713.tar.gz /mnt/4Traid1/nextcloud/data

バックアップデータを復元してみる

https://docs.nextcloud.com/server/latest/admin_manual/maintenance/index.html
https://docs.nextcloud.com/server/latest/admin_manual/maintenance/migrating.html#

dbデータ

  • import
mysql -h localhost --port=23306 -u root -p nextcloud < nextcloud-sqlbkp.bak 
  • oc_storagesの変更

dataファイル

tar.gzを展開すると

sudo ls -l  /mnt/backuparea/mnt/4Traid1/nextcloud/data/
合計 136064
drwxr-xr-x  7 www-data root          4096  2月 17  2019 admin
-rw-r--r--  1 www-data root             0  2月 12  2022 index.html
drwxr-xr-x  4 www-data www-data      4096  2月 13  2022 kodi
-rw-r-----  1 www-data www-data  14385806  6月 18 19:18 nextcloud.log
-rw-r-----  1 www-data www-data 124743392  2月  7  2020 nextcloud.log.1
drwxr-xr-x  5 www-data www-data      4096  3月  9  2022 pf

のような感じ。 これを/mnt/backuparea/に上書きする

ls -l /mnt/backuparea/nextcloud_test/data/nextcloud/data/
合計 8
-rw-r--r-- 1 200081 200081    0  7月 13 10:36 index.html
-rw-r----- 1 200081 200081 5563  7月 13 10:36 nextcloud.log
sudo mv /mnt/backuparea/nextcloud_test/data/nextcloud/data /mnt/backuparea/nextcloud_test/data/nextcloud/data.org
/mnt/backuparea/mnt/4Traid1/nextcloud$ sudo mv data /mnt/backuparea/nextcloud_test/data/nextcloud/
$ sudo chown 200081 -R /mnt/backuparea/nextcloud_test/data/nextcloud/data
$ sudo chgrp 200081 -R /mnt/backuparea/nextcloud_test/data/nextcloud/data

起動

インストールウィザード

adminはadmin2にした



アップデートが動くのでしばらく待つ



ダッシュボード



セキュリティ&セットアップ警告

一見動いていそうだけど、チェックかけるとたくさん出てきたOrz



occ db:add-missing-indices
nextcloud_docker@blackcore:/mnt/backuparea/nextcloud_test$ docker -H unix:///run/user/1004/docker.sock exec -it nextcloud_test_app_1 sudo -u www-data /bin/php occ db:add-missing-indices
OCI runtime exec failed: exec failed: unable to start container process: exec: "sudo": executable file not found in $PATH: unknown
nextcloud_docker@blackcore:/mnt/backuparea/nextcloud_test$ docker -H unix:///run/user/1004/docker.sock exec -it nextcloud_test_app_1 php occ db:add-missing-indices
Console has to be executed with the user that owns the file config/config.php
Current user id: 0
Owner id of config.php: 82
Try adding 'sudo -u #82' to the beginning of the command (without the single quotes)
If running with 'docker exec' try adding the option '-u 82' to the docker command (without the single quotes)

sudoコマンドが使えない
こちらを参考にして実行するユーザーを選択した
https://qiita.com/tabimoba/items/c5467432d1a635f9ce5b

nextcloud_docker@blackcore:/mnt/backuparea/nextcloud_test$ docker -H unix:///run/user/1004/docker.sock exec -it -u 82 nextcloud_test_app_1 php occ db:add-missing-indices
Check indices of the share table.
Check indices of the filecache table.
Adding additional size index to the filecache table, this can take some time...
Filecache table updated successfully.
Adding additional size index to the filecache table, this can take some time...
Filecache table updated successfully.
Adding additional path index to the filecache table, this can take some time...
Filecache table updated successfully.
Check indices of the twofactor_providers table.
Check indices of the login_flow_v2 table.
Check indices of the whats_new table.
Check indices of the cards table.
Adding cards_abiduri index to the cards table, this can take some time...
cards table updated successfully.
Check indices of the cards_properties table.
Check indices of the calendarobjects_props table.
Adding calendarobject_calid_index index to the calendarobjects_props table, this can take some time...
calendarobjects_props table updated successfully.
Check indices of the schedulingobjects table.
Adding schedulobj_principuri_index index to the schedulingobjects table, this can take some time...
schedulingobjects table updated successfully.
Check indices of the oc_properties table.
Adding properties_path_index index to the oc_properties table, this can take some time...
Adding properties_pathonly_index index to the oc_properties table, this can take some time...
oc_properties table updated successfully.
Check indices of the oc_jobs table.
Adding job_lastcheck_reserved index to the oc_jobs table, this can take some time...
oc_properties table updated successfully.
Check indices of the oc_direct_edit table.
Adding direct_edit_timestamp index to the oc_direct_edit table, this can take some time...
oc_direct_edit table updated successfully.
Check indices of the oc_preferences table.
Adding preferences_app_key index to the oc_preferences table, this can take some time...
oc_properties table updated successfully.
Check indices of the oc_mounts table.
occ db:add-missing-primary-keys
nextcloud_docker@blackcore:/mnt/backuparea/nextcloud_test$ docker -H unix:///run/user/1004/docker.sock exec -it -u 82 nextcloud_test_app_1 php occ db:add-missing-primary-keys
Check primary keys.
Adding primary key to the federated_reshares table, this can take some time...
federated_reshares table updated successfully.
Adding primary key to the systemtag_object_mapping table, this can take some time...
systemtag_object_mapping table updated successfully.
Adding primary key to the comments_read_markers table, this can take some time...
comments_read_markers table updated successfully.
Adding primary key to the collres_resources table, this can take some time...
collres_resources table updated successfully.
Adding primary key to the collres_accesscache table, this can take some time...
collres_accesscache table updated successfully.
Adding primary key to the filecache_extended table, this can take some time...
filecache_extended table updated successfully.
occ db:add-missing-columns
nextcloud_docker@blackcore:/mnt/backuparea/nextcloud_test$ docker -H unix:///run/user/1004/docker.sock exec -it -u 82 nextcloud_test_app_1 php occ db:add-missing-columns
Check columns of the comments table.
Adding additional reference_id column to the comments table, this can take some time...
Comments table updated successfully.
occ db:convert-filecache-bigint
nextcloud_docker@blackcore:/mnt/backuparea/nextcloud_test$ docker -H unix:///run/user/1004/docker.sock exec -it -u 82 nextcloud_test_app_1 php occ db:convert-filecache-bigint
Following columns will be updated:

* federated_reshares.share_id
* filecache.mtime
* filecache.storage_mtime
* filecache_extended.fileid
* files_trash.auto_id
* mounts.storage_id
* mounts.root_id
* mounts.mount_id
* share_external.id
* share_external.parent

This can take up to hours, depending on the number of files in your instance!
Continue with the conversion (y/n)? [n] y

オレオレ証明書からLet’s Encryptへ

今までと同じように、Let’s Encryptを使用させていただく。ありがたや。
80と443を使用するのか・・・。ポート変換もだめ?

https://letsencrypt.org/ja/docs/challenge-types/

https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal&tab=standard

https://snapcraft.io/docs/installing-snap-on-linux-mint

nginxインストール

ここを参考に
https://zenn.dev/hitoshiro/articles/b8170ec36d1f01

sudo apt install nginx
sudo cat /etc/nginx/conf.d/conf.conf

server{

  listen  80;
  server_name ****.mydns.jp;
  root  /var/www/html;

}

これで、とりあえずのnginxは用意した。

certbotのインストール

https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal&tab=standard

インストールは上記サイトの通り

sudo certbot --nginx

で、cretbotさんがconfigに追記してくれた

sudo cat /etc/nginx/conf.d/conf.conf

server{
  server_name ****.mydns.jp;
  root  /var/www/html;

  listen 443 ssl; # managed by Certbot
  ssl_certificate /etc/letsencrypt/live/****.mydns.jp/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/****.mydns.jp/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server{
    if ($host = ****.mydns.jp) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

  listen  80;
  server_name ****.mydns.jp;
  return 404; # managed by Certbot
}

証明書の取得

deno@blackcore:~$ sudo certbot --nginx
Saving debug log to /var/log/letsencrypt/letsencrypt.log

Which names would you like to activate HTTPS for?
We recommend selecting either all domains, or all domains in a VirtualHost/server block.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: ****.mydns.jp
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 1
Requesting a certificate for ****.mydns.jp

Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/****.mydns.jp/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/****.mydns.jp/privkey.pem
This certificate expires on 2023-12-22.
These files will be updated when the certificate renews.
Certbot has set up a scheduled task to automatically renew this certificate in the background.

Deploying certificate
Successfully deployed certificate for ****.mydns.jp to /etc/nginx/conf.d/conf.conf
Congratulations! You have successfully enabled HTTPS on https://****.mydns.jp

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
 * Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
 * Donating to EFF:                    https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

自動更新のテスト

sudo certbot renew --dry-run
Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/****.mydns.jp.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Account registered.
Simulating renewal of an existing certificate for ****.mydns.jp

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations, all simulated renewals succeeded: 
  /etc/letsencrypt/live/****.mydns.jp/fullchain.pem (success)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

次回更新も自動でやってくれるらしい

deno@blackcore:~$ sudo systemctl list-timers
NEXT                        LEFT               LAST                        PASSED             UNIT                         ACTIVATES                     
<略>
Sun 2023-09-24 09:54:00 JST 11h left           n/a                         n/a                snap.certbot.renew.timer     snap.certbot.renew.service

へー便利。

証明書をdocker上のnginxから参照する

良いやり方が思いつかなかったので、単純に変更があったらコピーして所有者変更・コンテナ再起動を実施

cat chk_cert.sh 
#!/bin/bash

#-----------------------------------------------------------------
# certbotが保存するcertの保存先
source_dir="/etc/letsencrypt/live/****.mydns.jp/"

# docker上のnginxの参照先
target_dir="/mnt/backuparea/nextcloud_test/cert/"

# コピー先を参照するユーザー名
target_username="nextcloud_docker"

#-----------------------------------------------------------------


# 更新フラグ
update_required=false

# ファイルの比較と更新
for file in "$source_dir"/*
do
    # echo "$file"
    # ファイル名を抽出
    filename=$(basename "$file")

    # 対応するファイルパスをターゲットディレクトリから取得
    target_file="$target_dir/$filename"

    # ファイルが存在しないか、差分がある場合に更新
    if [ ! -e "$target_file" ] || ! cmp -s "$file" "$target_file"
    then
        cp "$file" "$target_file"
        chown "$target_username" "$target_file"
        # echo "ファイル $filename を更新しました。"
        update_required=true
    fi
done

# 更新がある場合にnginxを再起動する
if [ "$update_required" = true ]
then
    /mnt/backuparea/nextcloud_test/chk_cert_restart.sh
    echo "更新によるリスタートしました。"
else
    echo "更新なし"
fi


cat chk_cert_restart.sh 
#!/bin/bash

#dockerコンテナの再起動
sudo -u nextcloud_docker /bin/bash -c "cd /mnt/backuparea/nextcloud_test && docker-compose -H unix:///run/user/1004/docker.sock restart"

自動更新(コピー)する

今までcronしか使ったことがなかったので、systemdのtimerを使ってみる
https://gamingpc.one/dev/systemd-timer-cheat/
https://wiki.archlinux.jp/index.php/Systemd/タイマー

$ cat /etc/systemd/system/docker-nextcloud.cert.renew.service 
[Unit]
Description=Docker NextCloud Cert Renew
RefuseManualStart=no
RefuseManualStop=yes

[Service]
Type=oneshot
ExecStart=/mnt/backuparea/nextcloud_test/chk_cert.sh
$ cat /etc/systemd/system/docker-nextcloud.cert.renew.timer 
[Unit]
Description=Docker NextCloud Cert Renew

[Timer]
OnBootSec=5min
OnUnitActiveSec=1d

[Install]
WantedBy=timers.target

有効にするには

sudo systemctl daemon-reload
sudo systemctl enable docker-nextcloud.cert.renew.timer
sudo systemctl start docker-nextcloud.cert.renew.timer
sudo systemctl list-timers
NEXT                        LEFT               LAST                        PASSED             UNIT                              ACTIVATES                          
(略)
Mon 2023-09-25 08:49:01 JST 23h left           Sun 2023-09-24 08:49:01 JST 2min 7s ago        docker-nextcloud.cert.renew.timer docker-nextcloud.cert.renew.service

これでOKなはず!

2023年7月26日水曜日

ホームサーバーの環境移行(4)

気が付いたら5か月経っていた。早くね。
2月にやったことをちゃんとまとめていなかった報いか。

現状

済

  1. samba
  2. gogs
  3. MariaDB
  4. webmin

未

今回の対象

  • nextcolud

nextcloudの引っ越し

ここを参考にする
https://docs.nextcloud.com/server/latest/admin_manual/maintenance/index.html
https://hub.docker.com/_/nextcloud
https://blog.seigo2016.com/blog/h-blxsnew_s

事前準備

ユーザー作成

  • ユーザー:nextcloud_docker 1004
  • グループ:nextcloud-rtls-docker 200999

サブ UID/サブ GIDの設定

$ cat /etc/subuid
nextcloud_docker:200000:65536

$ cat /etc/subgid
nextcloud_docker:200000:65536

インストール

nextcloud_docker@blackcore:~$ dockerd-rootless-setuptool.sh install
[INFO] systemd not detected, dockerd-rootless.sh needs to be started manually:

PATH=/usr/bin:/sbin:/usr/sbin:$PATH dockerd-rootless.sh 

[INFO] CLI context "rootless" already exists
[INFO] Use CLI context "rootless"
Current context is now "rootless"

[INFO] Make sure the following environment variables are set (or add them to ~/.bashrc):

# WARNING: systemd not found. You have to remove XDG_RUNTIME_DIR manually on every logout.
export XDG_RUNTIME_DIR=/home/nextcloud_docker/.docker/run
export PATH=/usr/bin:$PATH
Some applications may require the following environment variable too:
export DOCKER_HOST=unix:///home/nextcloud_docker/.docker/run/docker.sock
nextcloud_docker@blackcore:~$ cat .config/systemd/user/docker.service 
[Unit]
Description=Docker Application Container Engine (Rootless)
Documentation=https://docs.docker.com/go/rootless/

[Service]
Environment=PATH=/home/nextcloud_docker/bin:/sbin:/usr/sbin:/home/nextcloud_docker/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
ExecStart=/bin/dockerd-rootless.sh
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always
StartLimitBurst=3
StartLimitInterval=60s
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
Delegate=yes
Type=notify
NotifyAccess=all
KillMode=mixed

[Install]
WantedBy=default.target

設定

loginctl enable-linger nextcloud_docker
nextcloud_docker@blackcore:~$ XDG_RUNTIME_DIR=/run/user/$(id -u nextcloud_docker) systemctl --user daemon-reload
nextcloud_docker@blackcore:~$ XDG_RUNTIME_DIR=/run/user/$(id -u nextcloud_docker) systemctl --user start docker
nextcloud_docker@blackcore:~$ XDG_RUNTIME_DIR=/run/user/$(id -u nextcloud_docker) systemctl --user status docker
● docker.service - Docker Application Container Engine (Rootless)
     Loaded: loaded (/home/nextcloud_docker/.config/systemd/user/docker.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2023-02-22 06:07:22 JST; 3s ago
       Docs: https://docs.docker.com/go/rootless/
   Main PID: 912102 (rootlesskit)
      Tasks: 54
     Memory: 45.7M
        CPU: 205ms
     CGroup: /user.slice/user-1004.slice/user@1004.service/app.slice/docker.service
             ├─912102 rootlesskit --net=slirp4netns --mtu=65520 --slirp4netns-sandbox=auto --slirp4netns-seccomp=auto --disable-host-loopback --port-driver=builtin --copy-up=/etc --copy-up=/run --propagation=rslave /bin/dockerd-rootless.sh
             ├─912113 /proc/self/exe --net=slirp4netns --mtu=65520 --slirp4netns-sandbox=auto --slirp4netns-seccomp=auto --disable-host-loopback --port-driver=builtin --copy-up=/etc --copy-up=/run --propagation=rslave /bin/dockerd-rootless.sh
             ├─912132 slirp4netns --mtu 65520 -r 3 --disable-host-loopback --enable-sandbox --enable-seccomp 912113 tap0
             ├─912140 dockerd
             └─912166 containerd --config /run/user/1004/docker/containerd/containerd.toml --log-level info

 2月 22 06:07:22 blackcore dockerd-rootless.sh[912140]: time="2023-02-22T06:07:22.095812655+09:00" level=warning msg="WARNING: No io.max (wbps) support"
 2月 22 06:07:22 blackcore dockerd-rootless.sh[912140]: time="2023-02-22T06:07:22.095815109+09:00" level=warning msg="WARNING: No io.max (riops) support"
 2月 22 06:07:22 blackcore dockerd-rootless.sh[912140]: time="2023-02-22T06:07:22.095817634+09:00" level=warning msg="WARNING: No io.max (wiops) support"
 2月 22 06:07:22 blackcore dockerd-rootless.sh[912140]: time="2023-02-22T06:07:22.095820449+09:00" level=warning msg="WARNING: bridge-nf-call-iptables is disabled"
 2月 22 06:07:22 blackcore dockerd-rootless.sh[912140]: time="2023-02-22T06:07:22.095823155+09:00" level=warning msg="WARNING: bridge-nf-call-ip6tables is disabled"
 2月 22 06:07:22 blackcore dockerd-rootless.sh[912140]: time="2023-02-22T06:07:22.095831981+09:00" level=info msg="Docker daemon" commit=bc3805a graphdriver=overlay2 version=23.0.1
 2月 22 06:07:22 blackcore dockerd-rootless.sh[912140]: time="2023-02-22T06:07:22.095857399+09:00" level=info msg="Daemon has completed initialization"
 2月 22 06:07:22 blackcore dockerd-rootless.sh[912140]: time="2023-02-22T06:07:22.104160647+09:00" level=info msg="[core] [Server #10] Server created" module=grpc
 2月 22 06:07:22 blackcore systemd[892130]: Started Docker Application Container Engine (Rootless).
 2月 22 06:07:22 blackcore dockerd-rootless.sh[912140]: time="2023-02-22T06:07:22.110857925+09:00" level=info msg="API listen on /run/user/1004/docker.sock"

XDG_RUNTIME_DIR=/run/user/$(id -u nextcloud_docker) systemctl --user enable docker

動作確認

hello-worldが動くかでテスト

nextcloud_docker@blackcore:~$ docker -H unix:///run/user/1004/docker.sock run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete 
Digest: sha256:6e8b6f026e0b9c419ea0fd02d3905dd0952ad1feea67543f525c73a0a790fefb
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

nextcloud用のdocker-composeを作成

nextcloud_docker@blackcore:/mnt/backuparea/nextcloud$ cat db.env
MYSQL_ROOT_PASSWORD=****************
MYSQL_PASSWORD=****************
MYSQL_DATABASE=nextcloud
MYSQL_USER=nextcloud

nextcloud_docker@blackcore:/mnt/backuparea/nextcloud$ cat docker-compose.yml 
version: '3'

services:
  db:
    image: mariadb:10.5
    command: --transaction-isolation=READ-COMMITTED --log-bin=binlog --binlog-format=ROW
    restart: always
    volumes:
      - db:/var/lib/mysql
    environment:
      - MARIADB_AUTO_UPGRADE=1
      - MARIADB_DISABLE_UPGRADE_BACKUP=1
    env_file:
      - db.env
    ports:
      - 23306:3306

  redis:
    image: redis:alpine
    restart: always

  app:
    image: nextcloud:fpm-alpine
    restart: always
    volumes:
      - nextcloud:/var/www/html
    environment:
      - MYSQL_HOST=db
      - REDIS_HOST=redis
    env_file:
      - db.env
    depends_on:
      - db
      - redis

  web:
    image: nginx
    restart: always
    ports:
      - 28080:80
    volumes:
      - nextcloud:/var/www/html:ro
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - app

  cron:
    image: nextcloud:fpm-alpine
    restart: always
    volumes:
      - nextcloud:/var/www/html
    entrypoint: /cron.sh
    depends_on:
      - db
      - redis

volumes:
  db:
  nextcloud:

あとは

nextcloud_docker@blackcore:/mnt/backuparea/nextcloud$ cat nginx.conf 
worker_processes auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    # Prevent nginx HTTP Server Detection
    server_tokens   off;

    keepalive_timeout  65;

    #gzip  on;

    upstream php-handler {
        server app:9000;
    }

    server {
        listen 80;

        # HSTS settings
        # WARNING: Only add the preload option once you read about
        # the consequences in https://hstspreload.org/. This option
        # will add the domain to a hardcoded list that is shipped
        # in all major browsers and getting removed from this list
        # could take several months.
        #add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;" always;

        # set max upload size
        client_max_body_size 512M;
        fastcgi_buffers 64 4K;

        # Enable gzip but do not remove ETag headers
        gzip on;
        gzip_vary on;
        gzip_comp_level 4;
        gzip_min_length 256;
        gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
        gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

        # Pagespeed is not supported by Nextcloud, so if your server is built
        # with the `ngx_pagespeed` module, uncomment this line to disable it.
        #pagespeed off;

        # HTTP response headers borrowed from Nextcloud `.htaccess`
        add_header Referrer-Policy                      "no-referrer"   always;
        add_header X-Content-Type-Options               "nosniff"       always;
        add_header X-Download-Options                   "noopen"        always;
        add_header X-Frame-Options                      "SAMEORIGIN"    always;
        add_header X-Permitted-Cross-Domain-Policies    "none"          always;
        add_header X-Robots-Tag                         "none"          always;
        add_header X-XSS-Protection                     "1; mode=block" always;

        # Remove X-Powered-By, which is an information leak
        fastcgi_hide_header X-Powered-By;

        # Path to the root of your installation
        root /var/www/html;

        # Specify how to handle directories -- specifying `/index.php$request_uri`
        # here as the fallback means that Nginx always exhibits the desired behaviour
        # when a client requests a path that corresponds to a directory that exists
        # on the server. In particular, if that directory contains an index.php file,
        # that file is correctly served; if it doesn't, then the request is passed to
        # the front-end controller. This consistent behaviour means that we don't need
        # to specify custom rules for certain paths (e.g. images and other assets,
        # `/updater`, `/ocm-provider`, `/ocs-provider`), and thus
        # `try_files $uri $uri/ /index.php$request_uri`
        # always provides the desired behaviour.
        index index.php index.html /index.php$request_uri;

        # Rule borrowed from `.htaccess` to handle Microsoft DAV clients
        location = / {
            if ( $http_user_agent ~ ^DavClnt ) {
                return 302 /remote.php/webdav/$is_args$args;
            }
        }

        location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
        }

        # Make a regex exception for `/.well-known` so that clients can still
        # access it despite the existence of the regex rule
        # `location ~ /(\.|autotest|...)` which would otherwise handle requests
        # for `/.well-known`.
        location ^~ /.well-known {
            # The rules in this block are an adaptation of the rules
            # in `.htaccess` that concern `/.well-known`.

            location = /.well-known/carddav { return 301 /remote.php/dav/; }
            location = /.well-known/caldav  { return 301 /remote.php/dav/; }

            location /.well-known/acme-challenge    { try_files $uri $uri/ =404; }
            location /.well-known/pki-validation    { try_files $uri $uri/ =404; }

            # Let Nextcloud's API for `/.well-known` URIs handle all other
            # requests by passing them to the front-end controller.
            return 301 /index.php$request_uri;
        }

        # Rules borrowed from `.htaccess` to hide certain paths from clients
        location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/)  { return 404; }
        location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console)                { return 404; }

        # Ensure this block, which passes PHP files to the PHP process, is above the blocks
        # which handle static assets (as seen below). If this block is not declared first,
        # then Nginx will encounter an infinite rewriting loop when it prepends `/index.php`
        # to the URI, resulting in a HTTP 500 error response.
        location ~ \.php(?:$|/) {
            # Required for legacy support
            rewrite ^/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+|.+\/richdocumentscode\/proxy) /index.php$request_uri;

            fastcgi_split_path_info ^(.+?\.php)(/.*)$;
            set $path_info $fastcgi_path_info;

            try_files $fastcgi_script_name =404;

            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $path_info;
            #fastcgi_param HTTPS on;

            fastcgi_param modHeadersAvailable true;         # Avoid sending the security headers twice
            fastcgi_param front_controller_active true;     # Enable pretty urls
            fastcgi_pass php-handler;

            fastcgi_intercept_errors on;
            fastcgi_request_buffering off;
        }

        location ~ \.(?:css|js|svg|gif)$ {
            try_files $uri /index.php$request_uri;
            expires 6M;         # Cache-Control policy borrowed from `.htaccess`
            access_log off;     # Optional: Don't log access to assets
        }

        location ~ \.woff2?$ {
            try_files $uri /index.php$request_uri;
            expires 7d;         # Cache-Control policy borrowed from `.htaccess`
            access_log off;     # Optional: Don't log access to assets
        }

        # Rule borrowed from `.htaccess`
        location /remote {
            return 301 /remote.php$request_uri;
        }

        location / {
            try_files $uri $uri/ /index.php$request_uri;
        }
    }
}

実行してみる

nextcloud_docker@blackcore:/mnt/backuparea/nextcloud$ docker-compose -H unix:///run/user/1004/docker.sock up
Starting nextcloud_db_1    ... done
Starting nextcloud_redis_1 ... done
Starting nextcloud_cron_1  ... done
Starting nextcloud_app_1   ... done
Starting nextcloud_web_1   ... done
Attaching to nextcloud_db_1, nextcloud_redis_1, nextcloud_app_1, nextcloud_cron_1, nextcloud_web_1
db_1     | 2023-03-16 20:30:42+00:00 [Note] [Entrypoint]: Entrypoint script for MariaDB Server 1:10.5.19+maria~ubu2004 started.

動いた!


バックアップデータを復元してみる

https://docs.nextcloud.com/server/latest/admin_manual/maintenance/index.html
https://docs.nextcloud.com/server/latest/admin_manual/maintenance/migrating.html#

dbデータ

  • import
mysql -h localhost --port=23306 -u root -p nextcloud < nextcloud-sqlbkp.bak 
  • oc_storagesの変更

dataファイル

  • コピー
sudo cp -r nextcloud/ /mnt/backuparea/nextcloud/data/
sudo chown 200081 -R /mnt/backuparea/nextcloud/data/
sudo chgrp 200081 -R /mnt/backuparea/nextcloud/data/
  • パーミッション
adeno@blackcore:/mnt/backuparea/nextcloud$ ls -l data/nextcloud/data
合計 135988
drwxr-xr-x  7 200081 extcloud-rtls-docker      4096  2月 17  2019 admin
(略)
  • 備忘録
    最終手段でシンボリックリンクで対応したと思ったけど、何だっけ??

微調整

セキュリティ&セットアップ警告

HTTPSの対応

Traefikを試してみる?

https://coders-shelf.com/traefik-intro/
https://qiita.com/adwin/items/ccc34ef5f4c88d8fa02c#おまけ-https-化も楽勝

cat traefik.yml 
------------------------------------------------------------
api:
  insecure: true # WebUI にアクセスできるように設定
  dashboard: true

entryPoints:
  http:
    address: ":80"

  https:
    address: ":20443"

providers:
  docker:
#    network: sample_traefik
    exposedByDefault: false

cat docker-compose.yml 
------------------------------------------------------------
ersion: '3'

services:
  db:
    image: mariadb:10.5
    command: --transaction-isolation=READ-COMMITTED --log-bin=binlog --binlog-format=ROW
    restart: always
    volumes:
      - ./data/db:/var/lib/mysql
    environment:
      - MARIADB_AUTO_UPGRADE=1
      - MARIADB_DISABLE_UPGRADE_BACKUP=1
    env_file:
      - db.env
    ports:
      - 23306:3306

  redis:
    image: redis:alpine
    restart: always

  app:
    image: nextcloud:fpm-alpine
    restart: always
    volumes:
      - ./data/nextcloud:/var/www/html
    environment:
      - MYSQL_HOST=db
      - REDIS_HOST=redis
    env_file:
      - db.env
    depends_on:
      - db
      - redis

  web:
    image: nginx
    restart: always
    ports:
      - 28080:80
    volumes:
      - ./data/nextcloud:/var/www/html:ro
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - app
    labels:
      - traefik.enable=true
      - traefik.http.routers.servicename.rule=Host(`blackcore.local`)
      - traefik.http.routers.servicename.entrypoints=https
      - traefik.http.routers.servicename.tls=true

  cron:
    image: nextcloud:fpm-alpine
    restart: always
    volumes:
      - ./data/nextcloud:/var/www/html
    entrypoint: /cron.sh
    depends_on:
      - db
      - redis

  traefik:
    image: traefik
    ports:
      - 28081:8080
      - 28082:80
      - 20443:20443
    volumes:
      - /run/user/1004/docker.sock:/var/run/docker.sock:ro
      - ./traefik.yml:/etc/traefik/traefik.yml

volumes:
  db:
  nextcloud:

httpsでのアクセスで、404 not foundとなってしまう。

nginxでhttpsを

そもそもリバースプロキシではなくて、nginxでhttps対応ができればやりたいことはできる。
nginx.confに以下を追加

cat nginx.conf
---
	# SSL configuration
	#
	listen 443 ssl default_server;
	listen [::]:443 ssl default_server;
 	#ssl_certificate /etc/nginx/server.crt;
	#ssl_certificate_key /etc/nginx/server.key;
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
	ssl_ciphers HIGH:!aNULL:!MD5;
	ssl_certificate     /etc/letsencrypt/live/*****.jp/fullchain.pem;
	ssl_certificate_key /etc/letsencrypt/live/*****.jp/privkey.pem;

長くなってきたし、時間も空いてしまってよくわからなくなってきたので、1回整理したい。

2019年8月2日金曜日

バックアップについて

12月頃にHOMEサーバーの環境を移行してから、バックアップが手薄になっていた。
https://continue-to-challenge.blogspot.com/2018/10/nextcloud.html
https://continue-to-challenge.blogspot.com/2018/12/gogs.html
今回はせめて再構築が用意になるように外付けHDDにバックアップを行うことにした。
対象
  • nextcloud
  • gogs
  • redmine
nextcloudには、家族の写真とかがあるので特に大事。

バックアップ

nextcloud

ほぼ先人と同じ
https://docs.nextcloud.com/server/15/admin_manual/maintenance/backup.html
https://denor.jp/nextcloudサーバのデータ自動バックアップ設定-snap版
https://takuya-1st.hatenablog.jp/entry/2018/11/20/020000
#!/bin/bash
NCPATH="/mnt/***/www/html/nextcloud"
NCDATA_PATH="/mnt/***/nextcloud/data"
TARGET="/mnt/usbhdd/nextcloud_backup"

echo start at `date`

echo "(STEP1)HDD spin-up"
sdparm -r --command=start /dev/sdd

echo "(STEP2)Maintenance Mode [ ON ]"
sudo -u www-data php ${NCPATH}/occ maintenance:mode --on

echo "(STEP3)Backup Config"
rsync -vAax ${NCPATH} ${TARGET}

echo "(STEP4)Backup Data"
rsync -vAax ${NCDATA_PATH} ${TARGET}

echo "(STEP5)Backup Database"
mysqldump --single-transaction -h localhost -u nextcloud -p****** nextcloud > ${TARGET}/nextcloud-sqlbkp.bak

echo "(STEP6)Maintenance Mode [ OFF ]"
sudo -u www-data php ${NCPATH}/occ maintenance:mode --off

echo "(STEP7)HDD spin-down"
sdparm -r --command=stop /dev/sdd

echo end at `date`

省電力化のためにスピンダウン入れてみたけど、効果は未知数。
smartで起動しちゃうみたいだし・・・。

gogs

大体ここの内容と同じ
https://gogs.io/docs/upgrade/upgrade_from_binary
#!/bin/bash
GGSPATH="/***/git/gogs"
GGSRPPATH="/***/git/gogs-repositories"
TARGET="/mnt/usbhdd/gogs_backup"

echo start at `date`

echo "(STEP1)gogs [ STOP ]"
systemctl stop gogs

echo "(STEP2)Backup Custom"
rsync -vAax ${GGSPATH}/custom ${TARGET}

echo "(STEP3)Backup Data"
rsync -vAax ${GGSPATH}/data ${TARGET}

echo "(STEP4)Backup Log"
rsync -vAax ${GGSPATH}/log ${TARGET}

echo "(STEP5)Backup Database"
mysqldump --single-transaction -h localhost -u gogs -p****** gogs_git  > ${TARGET}/gogs-sqlbkp.bak

echo "(STEP6)Backup Repository"
rsync -vAax ${GGSRPPATH} ${TARGET}

echo "(STEP7)gogs [ START ]"
systemctl start gogs

#echo "(STEP7)HDD spin-down"
#sdparm -r --command=stop /dev/sdd
echo end at `date`

redmine

本体はdocker、データベースはローカルのMariaDBを使用している。
https://continue-to-challenge.blogspot.com/2019/07/redmine.html
バックアップの方法
https://qiita.com/mikoski01/items/7d71ef7d167a6b78219a
http://redmine.jp/faq/system_management/backup/
#!/bin/bash
RMPATH="/srv/docker/redmine/redmine/files"
TARGET="/mnt/usbhdd/redmine_backup"

echo start at `date`

echo "(STEP1)redmine [ STOP ]"
docker stop redmine

echo "(STEP2)Backup Data"
rsync -vAax ${RMPATH} ${TARGET}

echo "(STEP3)Backup Database"
mysqldump --single-transaction -h localhost -u redmine -p****** redmine  > ${TARGET}/redmine-sqlbkp.bak

echo "(STEP4)redmine [ START ]"
docker start redmine

リストア

gogsの復元

ほぼ、この前の環境構築と同じ
https://continue-to-challenge.blogspot.com/2018/12/gogs.html
今回はテストとしてNanoPiに環境構築してみた。
  1. gogsインストールして
  2. MariaDBにデータベース作成
  3. バックアップからデータリストア
  4. 起動
の簡単4ステップ

redmineの復元

環境構築は、この前の手順で
https://continue-to-challenge.blogspot.com/2019/07/redmine.html
復元手順は
http://redmine.jp/faq/system_management/backup/
すいすい行くと思いきや
standard_init_linux.go:211: exec user process caused "exec format error"
なんだと!
どうやらNanoPiではARM用のイメージを使わないといけないらしい。
https://matatsuna.hatenablog.com/entry/2017/08/16/223039
公式のものがARM64対応していたのでそれにしてみる。
https://hub.docker.com/_/redmine
docker run --name=redmine -it --rm \
-e REDMINE_DB_USERNAME=redmine -e REDMINE_DB_PASSWORD=****** \
-e REDMINE_DB_DATABASE=redmine \
-e REDMINE_DB_MYSQL=192.168.1.13 -e REDMINE_DB_PORT=3306 \
-p 3000:3000 \
-v /srv/docker/files:/usr/src/redmine/files \
library/redmine:4.0.4
初期状態で起動が確認できたら、
  1. /srv/docker/redmineにfilesの中身を展開する
  2. データベースの復元
を行う。
できた!

nextcloudの復元

nextcloudには30GBくらいのデータが保存されているため、NanoPIのSDカードでは到底復元の環境に出来ない。
そこで、NanoPIに外付けHDDを装着した。 段々とNASキットが欲しくなる。
http://wiki.friendlyarm.com/wiki/index.php/1-bay_NAS_Dock_v1.2_for_NanoPi_NEO/NEO2#Hardware_Spec
https://www.friendlyarm.com/index.php?route=product/product&path=93&product_id=222
http://akizukidenshi.com/catalog/g/gM-12591/
ま、我慢だけどね。
ルートを外付けHDDに変更するには
nand-sata-install
https://lubtech.geo.jp/2017-09-10/?p=3048
環境構築はこの前の手順で
https://continue-to-challenge.blogspot.com/2018/10/nextcloud.html
こちらは特にARM/X86_64で違いはなく、当時の方法を思い出して行けば大丈夫。
ただし、復旧までの暫定・データ取り出しを目的としているためSSLは除外した。
うーん。眠い。

2019年7月23日火曜日

Redmineインストール

いまさらだけど、やっぱりタスク管理をやってみたくて
超メジャーにすることにした。
https://propagandes.info/redmine-install/
動作環境
http://guide.redmine.jp/RedmineInstall/#Requirements
あれ、MariaDBだめなの??
じゃあ、新たにPostgreSQLを入れるか、Dcoker使って環境作るか・・・。
まずはお試しなので、Docker使ってみようかな。
https://qiita.com/bezeklik/items/b9d75ee74e0ae4c6d42c
悩む・・。
https://www.untrustedconnection.com/2018/01/redmine-passenger-and-nginx-on-ubuntu.html
悩んだ時は巨人の肩に乗る!
https://github.com/sameersbn/docker-redmine

MariaDBのデータディレクトリ移動

よくよく見たら、データがraid環境下に保管されていなかった。あちゃー
cat /etc/mysql/mariadb.conf.d/50-server.cnf
-------------------------------------------
(略)
#
# * Basic Settings
#
user  = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket  = /var/run/mysqld/mysqld.sock
port  = 3306
basedir  = /usr
datadir  = /var/lib/mysql
tmpdir  = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
(略)
のdatadirを"/mnt/4Traid1/dbdata"に変更したい
systemctl stop mariadb.service
50-server.cnfのdatadb書き換え
データ移動
systemctl start mariadb.service
これで少し安心。

いざRedmine

http://www.makcraft.com/blog/meditation/2019/01/19/running-redmine-on-docker-containers/

Dockerの準備

https://docs.docker.com/install/linux/docker-ce/ubuntu/
基本的にはこの手順。だけど、Ubuntuじゃないので、注意。
$ lsb_release -cs
tara
「tara」は「Ubuntu 18.04 LTS」をベースにしているらしい。
で、これのコードネームは「bionic」らしい。
https://ja.wikipedia.org/wiki/Linux_Mint
https://www.ubuntulinux.jp/News/ubuntu1804
なので、「$(lsb_release -cs)」の部分を書き換える。

まずはクイックスタートを試してみる

https://github.com/sameersbn/docker-redmine#installation
docker pull sameersbn/redmine:latest
docker run --name=postgresql-redmine -d --env='DB_NAME=redmine_production'   --env='DB_USER=redmine' --env='DB_PASS=password' --volume=/srv/docker/redmine/postgresql:/var/lib/postgresql sameersbn/postgresql:9.6-4
docker run --name=redmine -d --link=postgresql-redmine:postgresql --publish=5080:80 --publish=50443:443 --env='REDMINE_PORT=5080' --volume=/srv/docker/redmine/redmine:/home/redmine/data sameersbn/redmine:4.0.4
https://サーバー:5080にアクセスすると


おぉ!

外部SQLサーバーを使ってみる

せっかく母艦のほうにMariaDBがあるのでPostgreからこっちに切り替えてみる
Redmineのコンテナからアクセスできるようにする。振られたIPはなんだろうか?
https://qiita.com/miyatahirotaka/items/a44e2ae0bac53a4a5feb
https://qiita.com/suin/items/50033dc60bfba8553395
http://docs.docker.jp/engine/userguide/networking/dockernetworks.html
docker exec -i -t redmine bash
root@57a:/home/redmine/redmine# hostname -i
172.17.0.3

MariaDBの設定変更

外部からアクセス出来るようにする。
https://qiita.com/tocomi/items/0c009d7299584df49378
vi /etc/mysql/mariadb.conf.d/50-server.cnf
-----------
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
# bind-address            = 127.0.0.1
-----------
service mariadb restart

MariaDBにDBとユーザー作成

CREATE USER 'redmine'@'172.17.%' IDENTIFIED BY 'password';
CREATE DATABASE IF NOT EXISTS `redmine_production` DEFAULT CHARACTER SET `utf8` COLLATE `utf8_unicode_ci`;
GRANT ALL PRIVILEGES ON redmine.* TO 'redmine'@'172.17.%'
試しに、コンテナの中からアクセス出来るか確認してみる
docker exec -i -t redmine bash
root@57a:/home/redmine/redmine# mysql -u redmine -p --host==サーバーIP

起動中のRedmineとPostgreを停止する

プロセスの確認と停止
docker ps -a
CONTAINER ID        IMAGE                        COMMAND                  CREATED             STATUS                     PORTS               NAMES
57aee49d39b6        sameersbn/redmine:4.0.4      "/sbin/entrypoint.sh…"   5 days ago          Exited (0) 5 seconds ago                       redmine
78b9389d7745        sameersbn/postgresql:9.6-4   "/sbin/entrypoint.sh"    5 days ago          Up 5 days                  5432/tcp            postgresql-redmine

docker stop redmine
docker stop postgresql-redmine
コンテナの削除
docker rm redmine
docker rm postgresql-redmine
http://www.risewill.co.jp/blog/archives/6793

外部SQLサーバーを指定して起動してみる

docker run --name=redmine -it --rm \
--env='DB_ADAPTER=mysql2' \
--env='DB_HOST=192.168.1.25' --env='DB_NAME=redmine_production' \
--env='DB_USER=redmine' --env='DB_PASS=password' \
--env='REDMINE_HTTPS=false' \
--publish=5080:80 --publish=50443:443 --env='REDMINE_PORT=5080' \
--volume=/srv/docker/redmine/redmine:/home/redmine/data \
sameersbn/redmine::4.0.4
さぁ



わぉOrz
ログを確認してみる。
docker exec -i -t redmine bash
tail -f /var/log/redmine/redmine/production.log
----
Started GET "/" for 127.0.0.1 at 2019-07-09 22:40:27 +0000
Processing by WelcomeController#index as HTML
Completed 500 Internal Server Error in 8ms (ActiveRecord: 3.8ms)
  
ActiveRecord::StatementInvalid (Mysql2::Error: Table 'redmine.settings' doesn't exist: SHOW FULL FIELDS FROM `settings`):
  
app/models/setting.rb:235:in `check_cache'
app/controllers/application_controller.rb:90:in `user_setup'
----
DBを見てみると、空っぽだった。なぜ?
http://guide.redmine.jp/RedmineInstall/#step-6-
https://qiita.com/bezeklik/items/b9d75ee74e0ae4c6d42c
初期設定が必要なのか??
docker exec redmine bundle exec rake db:migrate RAILS_ENV=production
docker exec redmine bundle exec rake redmine:load_default_data RAILS_ENV=production REDMINE_LANG=ja
これで再度アクセスしてみると



やったー
admin/adminで入ろう
よしよし、良さそう!

スマホアプリを使ってみる

宅内では使えそうなので、外出先での使用を考えてスマホアプリを導入してみる。
http://redminepm.com/ja
あまり、外部からアクセスできるポートを何個も開けるのは気分的に嫌だったので、
さらに当面は自分しか使わないので、sshポートフォアードを使用した。
使う時だけlocalhost:5080とサーバーの5080をつなげる。



タスクを眺めるにはアプリが見やすいと思う



チケットを割り当てたり、ガントチャート見たりはブラウザと使い分けると幸せになれそう。
しばらくはこれでやってみようと思う。

2018年10月29日月曜日

Nextcloudを導入してみた

まとまった時間を確保するのは難しい。
でもスキマ時間を見つけて、いろいろやっている。続けることが大事。

家族からDropboxがいっぱいになってしまったとクレームが来た。
容量アップするか、他のクラウドサービスにするか、といろんな人が体験したような悩みに直面。
うちの使い方は
  1. 大事な写真・動画の保存
  2. 家族や親戚との共有
  3. ドキュメント類の同期
  4. LINEでは動画が何日かすると消えてしまう
のために使っている。
動画とか保存しだすと1Gとかあっという間なので、一杯になってしまうというのも、頷ける。。。

それぞれいろんなサービスを駆使したら解決できるのだろうけど、
勉強がてら、家サーバーで何かできないか調べてみた。
ちょうど、今のサーバー君が2010年くらいの代物なので、リプレースがてら環境構築してみた。

 メモ
現行 Atom N270 1.6GHz 1コア2スレッド 32bit メモリ:1GB
新規 AMD E-350 1.6GHz 2コア 64bit メモリ:8GB
あれ??あまりスペックアップしていないOrz

(まぁ64bit対応できているからいいか・・・)


ownCloudとNextcloud

歴史とかよくわからないけど、Nextcloudの方がダウンロードリンクが
分かりやすかったので、そっちにした。

インストール手順は以下にまとまっていた
https://docs.nextcloud.com/server/14/admin_manual/installation/source_installation.html#ubuntu-installation-label
0.前提条件
先述のAMD E-350という年代物・・・。これにMint 64bitをインストール。

1.必要なパッケージインストール 
apt-get install mariadb-server
apt-get install mariadb-client
apt-get install nginx
apt-get install php-fpm php-mysqlnd php-zip php-xml php-mbstring php-gd php-curl

2.mariaebのセットアップ
以下のセットアップを実行する
/usr/bin/mysql_secure_installation
rootユーザー設定
create user 'nextcloud'@'localhost' identified by 'パスワード';
create database nextcloud;
grant all on nextcloud.* to 'nextcloud'@'localhost';
これで、mariadbはOK
3.nginxのセットアップ
以下を変更し設定する
/etc/nginx/nginx.conf
/etc/nginx/sites-enabled/default
4.php-fpmのセットアップ
以下を変更し設定する
/etc/php/7.2/fpm/pool.d/www.conf
5.nextcloudのダウンロード
https://nextcloud.com/install/#instructions-server
https://download.nextcloud.com/server/releases/nextcloud-14.0.3.zip
以下のセットアップを実行するだけ
sudo -u www-data php occ  maintenance:install --database "mysql" \
--database-name "nextcloud"  --database-user "nextcloud" \
--database-pass "パスワード" \
--admin-user "admin" --admin-pass "あどみんパスワード"
これでおしまい。 こんな感じ

2017年8月20日日曜日

NanoPi NEOを監視カメラに(ZoneMinder+nginxで動体検出)

先日入手した「NanoPi NEO」で監視カメラ(動体検出)を構築してみた。

動体検出としてはmotion一番有名だと思っているが、
今回は外部トリガー(例えば、焦電センサーとかSlackからの要求とか)に対応したく
ZoneMinderを使用してみた。

・motion
 導入事例が多い、外部トリガーには対応していない?
・ ZoneMinder (github)
 導入事例がmotionに比べて少ない、設定項目が多く、プログラム自体も巨大?
 外部トリガーが出来るっぽい

ただし、ZoneMinderはwebサーバーにapacheが必要みたい。
なんとなく軽量にしてみたく、nginxを使用するように変更。

1.インストール
  sudo apt-get install zoneminder
  sudo apt-get install nginx-extras fcgiwrap php7.0-fpm
  sudo apt-get install mariadb-server

2.セットアップ
  (1) nginx
   /etc/nginx/sites-available/default の変更
    ・cgi-binとfastcgi_paramsのところ
  アクセス権付与し、再起動
  chown www-data:www-data /etc/zm/zm.conf
  systemctl restart nginx

 (2)mariadb
  ※ユーザー・パスワードは適宜変更、 /etc/zm/zm.confと合わせる
  create user 'zmuser'@'localhost' identified by 'zmpass';
  grant all on zm .* to zmuser;
  create database zm;
  mysql -u zmuser -p zm < /usr/share/zoneminder/db/zm_create.sql

 (3)php
  /etc/php/7.0/fpm/php.ini の変更
  「date.timezone = "Asia/Tokyo"」
  再起動
  /etc/init.d/php7.0-fpm restart

 (4)カメラへのアクセス権付与
  usermod -aG video www-data
  ※要再起動
  
 (5)その他
  /etc/sysctl.confを変更
  kernel.shmall = 268435456
  kernel.shmmax = 268435456
  sysctl -p
  ※本当に必要かわからない。 Orz
  8/30 追記
  ここに設定方法があった。
  使用しているNanoPi NEOは256MBだから半分の128MBにした
  
  kernel.shmall = 32768
  kernel.shmmax = 134217728


   ipcs -l 実行結果は以下の通り

------ Messages Limits --------
max queues system wide = 989
max size of message (bytes) = 8192
default max size of queue (bytes) = 16384

------ Shared Memory Limits --------
max number of segments = 4096
max seg size (kbytes) = 131072 = 128MB
max total shared memory (kbytes) = 131072 = 128MB
min seg size (bytes) = 1

------ Semaphore Limits --------
max number of arrays = 128
max semaphores per array = 250
max semaphores system wide = 32000
max ops per semop call = 32
semaphore max value = 32767

 (6)webページにアクセス
  http://[NanoPiNeoのIPアドレス]/zoneminder/index.php

  設定 > Paths > PATH_ZMSを変更
  /zoneminder/cgi-bin/nph-zms

3.映像確認
こんな感じ




手順まとめると大したことなかったけど、
もろもろ1週間位かかっているOrz

最後に自動起動するようにしておく
systemctl enable zoneminder
systemctl start zoneminder

あと、ディスク容量が逼迫した場合に古い記録から消す設定
How can I stop ZoneMinder filling up my disk?
http://zoneminder.readthedocs.io/en/latest/faq.html

次は検知時の映像をslackに投稿するぞー!

参考
 ・https://chiralsoftware.com/idea/nginx-ubuntu-and-zoneminder