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

2024年2月14日水曜日

VSCodeServer(code-server)

VSCodeをエディタとして使うことが多くなった。
MarkdownやMindmapや解像度を上げる作業に便利。

PCならVSCodeをインストールすればよいのだけれど、持っているChomebookではlinuxの仮想環境の上に動かすため、どうしてももっさりしてしまう。

以下のようなサービスもあるけど、経験として自宅サーバーで構築したかった。
https://vscode.dev/

code-server

これを自宅サーバーで動かして、SSHトンネリングでアクセスする

公式
https://github.com/coder/code-server
インストール方法
https://coder.com/docs/code-server/latest/install#debian-ubuntu

参考
https://qiita.com/plumchang/items/2229bda056d0f1ef3434
https://zenn.dev/kato_k/articles/6301d35b3d8d3c

インストール

curl -fsSL https://code-server.dev/install.sh | sh

設定ファイル

$ cat ~/.config/code-server/config.yaml
bind-addr: 127.0.0.1:8282
auth: none
cert: false

nextcloudで自動同期

code-serverではリモート先のファイルを編集するため、ローカルや他のPCとの同期が難しい。
そこで、nextcloudで同期させようと思った。

クライアントソフト

GUIは以下で、自動同期される
https://nextcloud.stylez.co.jp/nextcloud-desktop-client

CLIは以下で、自動同期されない
https://docs.nextcloud.com/desktop/3.11/advancedusage.html#nextcloud-command-line-client

参考
https://ritaiz.com/articles/steps-to-install-nextcloud-cli-client-on-ubuntu

CLI

nextcloudcmd -u username -p password --path /Documents/path $HOME/ドキュメント/ https://****.mydns.jp:port/

systemdを使った自動同期

linuxでcronの変わりにsysemd timerでスクリプトを実行したい。

Serviceファイルの作成

systemdが実行するサービスファイルを作成する。
このファイルは、どのスクリプトを、どのユーザーとして実行するかを指定する。

$ cat /etc/systemd/system/adeno-sync-nextcloud.service 
[Unit]
Description=Sync nextcloud script

[Service]
Type=simple
User=adeno
ExecStart=/home/adeno/ドキュメント/nextcloud_sync.sh

[Install]
WantedBy=multi-user.target

Timerファイルの作成

次に、いつサービスを実行するかを指定するtimerファイルを作成する
1分毎に同期を実施する

$ cat /etc/systemd/system/adeno-sync-nextcloud.timer 
[Unit]
Description=Runs my custom script

[Timer]
OnCalendar=*:*:00

Persistent=true
Unit=adeno-sync-nextcloud.service

systemdのリロード

systemdが新しいファイルを認識するように、systemdの設定をリロードする。

sudo systemctl daemon-reload

Timerの有効化と起動

有効化し、起動する

sudo systemctl enable adeno-sync-nextcloud.timer 
sudo systemctl start adeno-sync-nextcloud.timer 

nextcloudのmarkdownビューアー

Markdown Editor
Notes

2023年10月23日月曜日

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

外部からのアクセス設定

人生何があるかわからない。
素敵なことも、望まないことも、同時にやってきた。情緒どうすんのさ。

設定

  • 外部用のIPv4ルーターにて内部IP静的付与
  • メトリック設定
  • ポートフォアード設定
  • mydns.jpの更新設定
  • nextcloud側の設定

外部用のIPv4ルーターにて内部IP静的付与

特に備忘録なし

メトリック設定

https://pcvogel.sarakura.net/2021/01/15/32107

$ adeno@blackcore:~$ route -n
カーネルIP経路テーブル
受信先サイト    ゲートウェイ    ネットマスク   フラグ Metric Ref 使用数 インタフェース
0.0.0.0         192.168.1.1     0.0.0.0         UG    102    0        0 enp1s0
0.0.0.0         192.168.2.1     0.0.0.0         UG    103    0        0 enp4s0
192.168.1.0     0.0.0.0         255.255.255.0   U     102    0        0 enp1s0
192.168.2.0     0.0.0.0         255.255.255.0   U     103    0        0 enp4s0

enp4s0が外部用
enp1s0が内部用

デフォルトゲートウェイの変更
192.168.2.0/24をデフォルトになるように変更したい。

このあたりを思い出して
https://continue-to-challenge.blogspot.com/2019/06/ipoe.html

adeno@blackcore:~$ nmcli 
enp4s0: 接続済み から 有線接続 1
        "Realtek RTL8111/8168/8411"
        ethernet (r8169), A8:A1:59:**:**:**, hw, mtu 1500
        ip4 デフォルト
        inet4 192.168.2.21/24
        route4 192.168.2.0/24 metric 101
        route4 default via 192.168.2.1 metric 101

enp1s0: 接続済み から 有線接続 2.5G
        "Realtek RTL8125 2.5GbE"
        ethernet (r8169), 88:C9:B3:**:**:**, hw, mtu 1500
        ip6 デフォルト
        inet4 192.168.1.21/24
        route4 192.168.1.0/24 metric 102
        route4 169.254.0.0/16 metric 1000
        route4 default via 192.168.1.1 metric 102

wlp5s0: 切断済み
        "Intel Wireless-AC 3168NGW"
        wifi (iwlwifi), F0:57:A6:0E:53:99, hw, mtu 1500

adeno@blackcore:~$ sudo nmcli connection modify "有線接続 1" ipv4.never-default no
adeno@blackcore:~$ sudo nmcli connection modify "有線接続 1" ipv4.ignore-auto-routes no
adeno@blackcore:~$ sudo nmcli connection modify "有線接続 2.5G" ipv4.never-default yes
adeno@blackcore:~$ sudo nmcli connection modify "有線接続 2.5G" ipv4.ignore-auto-routes yes
adeno@blackcore:~$ sudo nmcli con up 有線接続\ 1
adeno@blackcore:~$ sudo nmcli con up 有線接続\ 2.5G 

ポートフォアード設定

外部22ポートを内部のサーバーIPの22へ転送

などなど

やっぱりいろいろ忘れるね。。。

ポート制限

サービス名 ポート
certbot 80/tcp,443/tcp
nextcloud 20443/tcp
ssh 22/tcp
samba

mydns.jpの更新設定

定期的に実行するのと、グローバルIPが変わったタイミングで実行したい。

定期実行

前回覚えたsystemd.timerで定期的に実行する

$ cat mydns_update.sh 
#!/bin/bash
#****.mydns.jp
wget -O - --http-user=****** --http-password=***** https://ipv4.mydns.jp/login.html

$ sudo cat /etc/systemd/system/mydns.renew.service 
[Unit]
Description=MyDNS.jp Renew
RefuseManualStart=no
RefuseManualStop=yes

[Service]
Type=oneshot
ExecStart=/home/adeno/BlackCoreEnv/mydns_update.sh
$ sudo cat /etc/systemd/system/mydns.renew.timer 
[Unit]
Description=MyDNS.jp Renew

[Timer]
OnBootSec=5min
OnUnitActiveSec=1d

[Install]
WantedBy=timers.target

グローバルIPの変更時に実行

グローバルIPを調べるサービスglobalip.meを使わせてもらう

$ cat chk_gip.sh 
#!/bin/bash

#------------------------------------------------------
workpath=/home/adeno/BlackCoreEnv
logname=chkgip.log
mydns_update=$workpath/mydns_update.sh

#------------------------------------------------------
oldip_path=$workpath/gip_old.txt
log_path=$workpath/$logname

echo "Glocal IP 更新チェック" | tee $log_path
date | tee -a $log_path

touch $oldip_path
oldip=`cat $oldip_path`

newip=`curl -s globalip.me | sed '1!d'`


if [ "$newip" != "$oldip" ] ; then
        #echo "$newip" | tee -a $oldip_path
        echo "Global IP の変更検出:"$oldip" → "$newip | tee -a  $log_path
        echo "mydns.jpに通知" | tee -a $log_path
        $mydns_update | tee -a $log_path
        echo $newip > $oldip_path

else
        echo "Global IP に変更なし:"$newip | tee -a $log_path
fi

echo "終了" | tee -a $log_path

$ sudo cat /etc/systemd/system/globalip.renew_check.service 
[Unit]
Description=Global IP Renew Check
RefuseManualStart=no
RefuseManualStop=yes

[Service]
Type=oneshot
ExecStart=/home/adeno/BlackCoreEnv/chk_gip.sh
$ sudo cat /etc/systemd/system/globalip.renew_check.timer 
Global IP Renew Check

$ cat /etc/systemd/system/docker-nextcloud.cert.renew.timer 
[Unit]
Description=Docker NextCloud Cert Renew

[Timer]
OnBootSec=3min
OnUnitActiveSec=5m

[Install]
WantedBy=timers.target

Written with StackEdit.

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回整理したい。

2022年12月30日金曜日

メディアサーバー構築2

メディアサーバー構築2

書こう書こうと思っていたら、9ヶ月近く経過していた。
時間が経つのはおそろしい。

メディアサーバーとして、ミニPCを入手した。もろもろ準備を行う。

wifi有効化

システム > ドライバーマネージャー


インストール

  • kodi
  • nextcloud clinet
  • ssh server

nextcloud クライアント

kodiのソース設定でwebdavを選ぶことが出来たが、webdavはちょっと遅かったので、nextcloud clientで同期した。
nextcloudのクライアントアプリで、同期するフォルダやファイルサイズの制限ができる。

これで、勝手に同期してくれる。

kodi

kodi自動起動

[設定マネージャー]→[セッションと起動]→kodiとnextcloudを指定する

ソース設定

nextcloudのディレクトリを指定する

ssh server

ホスト名でアクセスしたい

mDNSでホスト名でアクセスしたい。
avahiを使用しない方法があるのか
https://wiki.archlinux.jp/index.php/Systemd-resolved#mDNS
https://qiita.com/slug/items/4c7121af229b9a6c92c4
https://0e39bf7b.blog/posts/mdns-on-ubuntu-server/

が、ホスト名.localでアクセスすることが出来なかった。

仕方がないので、avahiをインストール
https://wiki.archlinux.jp/index.php/Avahi

sudo apt-get install avahi-daemon libnss-mdns
adeno@nipogi:~$ sudo systemctl status avahi-daemon.service 
● avahi-daemon.service - Avahi mDNS/DNS-SD Stack
     Loaded: loaded (/lib/systemd/system/avahi-daemon.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2022-12-30 10:50:04 JST; 10min ago
TriggeredBy: ● avahi-daemon.socket
   Main PID: 7685 (avahi-daemon)
     Status: "avahi-daemon 0.7 starting up."
      Tasks: 2 (limit: 14065)
     Memory: 1.4M
     CGroup: /system.slice/avahi-daemon.service
             ├─7685 avahi-daemon: running [nipogi.local]
             └─7687 avahi-daemon: chroot helper

sshサーバー

一応、公開鍵暗号認証方式にして、パスワード認証を切っておく
https://wiki.archlinux.jp/index.php/SSH_鍵
https://blog.htkyama.org/ssh_ed25519

リモコンが欲しい

wiiリモコンを中古でゲット
https://wiki.archlinux.jp/index.php/XWiimote
https://github.com/xwiimote/xwiimote
https://manpages.ubuntu.com/manpages/jammy/en/man4/xorg-xwiimote.4.html

キーのマッピングは以下を参考
https://ja.gadget-info.com/46371-20-kodi-keyboard-shortcuts-every-kodi-user-should-know
http://hide817.blog.fc2.com/blog-entry-6.html?sp
https://kodi.wiki/view/Keymap#Keyboards

変更無しで動いたもの

- +:音量アップ
- -:音量ダウン
- A:決定(リターン)
- B:なし
- HOME:なし
- 1:なし
- 2:なし
- 十字キー:操作

変更する

- B:BackSpace(戻る)
- HOME:ESC(取消)
- 1:スペース(スライドショー)
- 2:なし

sudo apt-get install xwiimote libxwiimote xserver-xorg-input-xwiimote
sudo usermod -aG input kodi

sudo xwiishow 1
xwiikeymap
/usr/share/X11/xorg.conf.d/50-xorg-fix-xwiimote.conf

adeno@nipogi:~$ cat /usr/share/X11/xorg.conf.d/50-xorg-fix-xwiimote.conf 
# X11 xorg Wii Remote raw input config
# XWiimote reports accelerometer and IR data as absolute axes. Disable them to
# avoid weird mouse behaviour. To use IR data as mouse input, use the xwiimote
# tools or xf86-input-xwiimote which overwrites this.
# This only disables the raw input from the kernel devices. If you use the
# xwiimote tools to emulate mouses/keyboards, then they are not affected by
# this.

Section "InputClass"
	Identifier "Nintendo Wii Remote Raw Input Blacklist"
	MatchProduct "Nintendo Wii Remote"
	Option "Ignore" "on"
	Option "MapB" "KEY_BACKSPACE"
    Option "MapHome" "KEY_Escape"
    Option "MapOne" "KEY_Space"
    Option "MapTwo" "KEY_I"
EndSection

これでとりあえずはいいか?

2022年3月21日月曜日

タブレットPCをフォトフレームにする

ASUS TransBook T90chiがある
Windowsが入った、機動力のあるPCだったが、最近は使っていない。
子供用のPCにしようかと思ったけど、まだ早いしスペックもこそまでなので、何か使い道がないかと悩んでいた。
お家の情報共有機器としてなにか使えないか

  • 予定の表示
  • 天気
  • 電車・バスの運行状況
  • フォトフレーム

この中で、すぐに出来そうな「フォトフレーム」をやってみたいと思う。

Linux Mintをインストール

たまたまLinuxインストールを紹介しているサイトを見つけて刺激を受けた
やってみよう
https://nomux2.net/asus-transbook-t90chi-xubuntu/
http://www.drvlabo.jp/wp/archives/1749
http://kapper1224.sblo.jp/article/186209546.html
https://nomux2.net/t09chi-linux-mint/

基本的には一番最後のサイトのままかも
ハマりポイントや変更点は以下の通り。

使用するディストリビューション

adeno@T90CHI:~$ lsb_release -a
No LSB modules are available.
Distributor ID:	Linuxmint
Description:	Linux Mint 20.2
Release:	20.2
Codename:	uma

adeno@T90CHI:~$ uname -a
Linux T90CHI 5.1.0-050100-generic #201905052130 SMP Mon May 6 01:32:59 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

bootia32.efi

ブータブルUSBメモリを作成するときに、Etcherを使ったら、空き容量が無くてbootia32.efiの書き込みが出来なかった。
なので、上の方と同じようにrufasを使って対応した。

画面の回転

lotate.shとして以下を作成した。
横向き固定。自動回転はいらなかったので。

xrandr -o right
xinput set-prop 'pointer:SYNA****:** ****:****' 'Coordinate Transformation Matrix' 0 1 0 -1 0 1 0 0 1

サウンド出力

特に何もせずとも対応されていた。

Bluetooth

カーネル5.1で確認した。

カーネル5.1の自動起動

cat /boot/grub/grub.conf

menuentry 'Linux Mint 20.2 Xfce, with Linux 5.1.0-050100-generic' --class linuxmint --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-5.1.0-050100-generic-advanced-823a8bf2-b59f-4214-ad18-69bd640496f8' {

上記をgrubに設定する。

#GRUB_DEFAULT=0
GRUB_DEFAULT='Advanced options for Linux Mint 20.2 Xfce>Linux Mint 20.2 Xfce, with Linux 5.1.0-050100-generic'

最初書き方がわからなくて、試行錯誤した。

NextCloudクライアント導入

特にハマるところはなし

簡易フォトフレーム

まずはfehで確認

cat ~pf/ph.sh 
#!/bin/bash
feh -F -Z --recursive --randomize /home/pf/Nextcloud/ -D 5

これで5秒毎にランダムに表示される

マウスカーソルを消す

cat ~pf/hide_pointer.sh 
#!/bin/bash
unclutter -idle 1 -root &

https://qiita.com/naohikowatanabe/items/73b093399deb0ebf496e
https://wiki.archlinux.jp/index.php/Unclutter

自動起動・自動終了

/sys/class/rtc/rtc0/wakealarm
が無いから出来ないー
さて困ったものだ。

画面のバックライトOFF/ONで代用するか?
https://wiki.archlinux.jp/index.php/バックライト

adeno@T90CHI:~$ cat /sys/class/backlight/intel_backlight/brightness 
20
adeno@T90CHI:~$ cat /sys/class/backlight/intel_backlight/brightness 
59
adeno@T90CHI:~$ cat /sys/class/backlight/intel_backlight/max_brightness 
100
chmod 777 /sys/class/backlight/intel_backlight/brightness
echo 50 > /sys/class/backlight/intel_backlight/brightness
sleep 1 && xset dpms force off

時間で消灯・時間で点灯

xset dpms force off
xset q
Keyboard Control:
  auto repeat:  on    key click percent:  0    LED mask:  00000000
  XKB indicators:
    00: Caps Lock:   off    01: Num Lock:    off    02: Scroll Lock: off
    03: Compose:     off    04: Kana:        off    05: Sleep:       off
    06: Suspend:     off    07: Mute:        off    08: Misc:        off
    09: Mail:        off    10: Charging:    off    11: Shift Lock:  off
    12: Group 2:     off    13: Mouse Keys:  off
  auto repeat delay:  500    repeat rate:  20
  auto repeating keys:  00ffffffdffffbbf
                        fedfffefffedffff
                        9fffffffffffffff
                        fff7ffffffffffff
  bell percent:  50    bell pitch:  400    bell duration:  100
Pointer Control:
  acceleration:  2/1    threshold:  4
Screen Saver:
  prefer blanking:  yes    allow exposures:  yes
  timeout:  600    cycle:  600
Colors:
  default colormap:  0x20    BlackPixel:  0x0    WhitePixel:  0xffffff
Font Path:
  /usr/share/fonts/X11/misc,/usr/share/fonts/X11/Type1,built-ins
DPMS (Energy Star):
  Standby: 300    Suspend: 0    Off: 600
  DPMS is Enabled
  Monitor is Off

5分周期でチェックスクリプトを実行する
これをcronとかで呼び出す

#!/bin/bash

# display on time
on_time="7:00"

# display off time
off_time="23:50"

# feh option
feh_dir="/home/pf/Nextcloud/"
feh_timer=10

###########################################################
function chk_feh() {
    # PIDを取得する
    feh_exist=`ps aux | grep "feh" | grep "$feh_dir" | awk '{print $2}'`
    echo $feh_exist
}
function display_off () {
    echo 消灯
    feh_pid=`chk_feh`
    echo $feh_pid
    if [[ -n $feh_pid ]]; then
        # プロセス実行中→終了する
        echo プロセス実行中→終了する
        kill $feh_pid
        sleep 1
    fi
    DISPLAY=:0.0 xset dpms force off
}

function display_on () {
    echo 点灯
    feh_pid=`chk_feh`
    echo $feh_pid
    if [[ -z $feh_pid ]]; then
        # プロセスが無い→起動する
        echo プロセスが無い→起動する
        # feh_run=`feh $feh_option`
        # DISPLAY=:0.0 feh -F -Z --recursive --randomize /home/pf/Nextcloud/ -D 5 &
        feh_run=`DISPLAY=:0.0 feh -F -Z --recursive --randomize $feh_dir -D $feh_timer &`
    fi
    DISPLAY=:0.0 xset dpms force on
}


nowdate=`date "+%Y/%m/%d %H:%M:%S"`
chk_base_date=`date +%Y/%m/%d`

echo $nowdate
echo "ON Time= "$chk_base_date" "$on_time
echo "OFF Time= "$chk_base_date" "$off_time

now_time_unix=`date --date "$nowdate" +%s`
on_time_unix=`date --date "$chk_base_date $on_time" +%s`
off_time_unix=`date --date "$chk_base_date $off_time" +%s`
echo $now_time_unix
echo $on_time_unix
echo $off_time_unix

if [ $now_time_unix -lt $on_time_unix ]; then
    display_off
else
    if [ $now_time_unix -lt $off_time_unix ]; then
        display_on
    else
        display_off
    fi
fi

crontabにて

/5 * * * * /home/pf/chk_date.sh > /tmp/chk_date.log

なんだか欲が出てきた。
人感センサーで、動きが無いときは消灯とか・・・。

2022年3月5日土曜日

メディアサーバー構築1

NextCloudに写真とか動画とかを保存している。
ちょっとした共有に便利、スマホで気軽にできるのが良い。
ちょっと欲が出てきて、TVで見てみたいと思い、どのような方法があるのか考えた。
スマホだど画面小さいし、TVの4Kで見てみたいじゃんというのが動機だ。

欲しいスペック

  • DLNAとかwebdav、NextCloudアプリ
  • 4Kで見たい
  • できるだけ安価
  • いろいろな使い方ができる

で、探してみた

No 1 2 3 4
品名 Amazon Fire TV Stick 4K Max Chromecast with Google TV Apple TV 4K ミニPC
価格 @6,980 @7,600 @21,800 @20,000〜@30,000
CPU クアッドコア 1.8GHz ? 64ビットアーキテクチャ搭載A12 Bionicチップ Celeron
メモリ 2GB ? ? 8〜32GB
ストレージ 8GB ? 32GB 64〜128GB
リモコン あり あり あり なし
DLNA VLC for Fire、kodi 多分○ 多分○? ○
webdav kodi 多分○ 多分○? ○
NextCloudアプリ たぶん× 多分○ たぶん× ○

なんとかTV系の3種は、安いし、それぞれのプラットフォームのサービスをもっているので、心惹かれるものがある。
でもそれらのサービスを使うと沼なので、今はあえて使いたくない。
それと自宅なんちゃってサーバーのリプレースを行う時期なので、今回は茨の道でミニPCを導入してみることにした。

ミニPC

Bmax、CHIWI、NiPoGi、MINISFORUMなどいろいろな種類がある。
自作・BTOも含めるともっとある。

価格や拡張性から、この3機種を候補にした。

No 1 2 3
品名 NiPoGi Bmax E3950 CHIWI HeroBox
CPU Celeron J4125 2GHz 4core Celeron E3950 2GHz 2core Celeron N4100 1.1GHz 4core
メモリ 12GB 8GB 8GB
ストレージ 128GB 128GB 256GB
その他 ファンあり 2.5inchSSD拡張可能 ファンあり 2.5inchSSD拡張可能 ファンレス 拡張は不可
価格 @24,225 @18,691 @21,500

ということで、少々高いが、No1のNiPoGiにすることにした。

NiPoGiとご対面

NiPoGiってなんて読むのかな?にぽぎ?


内臓ストレージにはwin10がインストールされているみたい
今回は、お試しで2.5inchSSDを別で用意して、そっちにLinuxMintをインストールしてみた

以下もろもろのメモ

BIOSは?

DEL長押し

USBブートは?

BIOSでブート順序変更が必要だけど出来た
USB2.0のほうのポートを使った

LinuxMintのインストール

USBブートからのSSDへインストール

TVにつながる?

もちOKだった

TVからリモコン操作できる?

HDMI-CECは出来ないと思う
TVにつないでリモコン操作したくらいでは反応なし
どうやって操作しようか
Bluetoothのリモコン探すか

やりたいことのメモ

入れたいもの

  • kodi
  • nextcloud clinet
  • sshserver

2021年5月8日土曜日

Lichee Pi Zeroで母艦PCとファイル同期させる

あまり手をつけていないが、少しずつやっている
母艦PCとのファイル同期に、開発中はsftpとかで良いんだろうが
例えば、何か作った後に、データを更新させたいといった時
sshはなんか心理的にやだった(何が

フォトフレームとした場合も、写真の更新取得先はdropboxやnextcloudなどクラウドストレージかもしれないし。何かしら同期させる手段が欲しい。

でも個別にサービスに対応させるのはしんどい。
davfs2を最初考えたけど、うまいことマウント出来ずに挫折した。
webdav以外にもつながりたいかもしれないし。
そんなことを悩んでいたら、rcloneというソフトに出会った。

rcloneはすごそう

  • Rclone syncs your files to cloud storage

すごいたくさん対応してるー!
https://rclone.org/#providers

Dropboxもあるし、Google Photos、Nextcloud、webdavなんかもある!
これを導入できれば、スッキリできるかもしれない。

お試し導入してみる

まずはどんなものかを味わうために、ビルド済みのやつを持ってきてみる。
https://rclone.org/downloads/
の[ARMv6 - 32 Bit][linux]というやつ

rclone-v1.54.0-linux-arm.zip

これを展開して、LicheePiに転送。

# ./rclone version
rclone v1.54.0
- os/arch: linux/arm
- go version: go1.15.7

さすが golang すんなり起動するのがすごいね。

対向サーバーは?

さてさて、対向となるサーバーはどうしようかと、あまり手間かけたくないし。
簡易的なwebサーバーで良いんだけど。
なんとなくwebdav使ってみたくて、あれこれ探していたら、wsgidavというソフトに出会った。

https://wsgidav.readthedocs.io/en/latest/index.html
https://qiita.com/Brad-55/items/5b596b76ef7dc1be9a39

インストールはとっても簡単

pip install --upgrade wsgidav

これでOK!
起動もとても簡単!

wsgidav --host=0.0.0.0 --port=8888 --root=/home/adeno/develop/wsgidav --auth=anonymous

これで、とりあえず、認証なしのwebdavサービスが出来上がる。すてき。


 

さて、やってみよう

これもとても簡単
https://rclone.org/webdav/

に従いやっていくだけ

# ./rclone ls chihiro:
1970/01/02 08:10:10 NOTICE: Time may be set wrong - time from "192.168.100.10:8888" is -448164h47m5.409855313s different from this computer
   476690 Screenshot from 2020-04-17 15-46-39.png
   540108 Screenshot from 2020-04-17 15-48-22.png
   272475 chihiro001.jpg
   376802 chihiro002.jpg
   441756 chihiro003.jpg
   297234 chihiro004.jpg
   160027 chihiro005.jpg
   224296 chihiro006.jpg
   276833 chihiro007.jpg
   296495 chihiro008.jpg

おっと、日時設定してなかった。

日時設定

とりあえず手動で

# date --set "2021-02-17 6:00:00"
Wed Feb 17 06:00:00 UTC 2021

あれ、UTCだ。

    BR2_TARGET_TZ_INFO=y
    BR2_TARGET_TZ_ZONELIST="default"
    BR2_TARGET_LOCALTIME="Asia/Tokyo" 

これで、再度ビルドして

# date --set "2021-02-20 19:38:00"
Sat Feb 20 19:38:00 JST 2021

これでOK

NTP導入

手動でうまく行くことがわかったので、今度は自動で調時させたい。

クライアント側

chronyというのを使ってみる。

    BR2_PACKAGE_CHRONY=y

サーバー側

特に何も考えずに、以下を参考に
https://tecadmin.net/setup-time-synchronisation-ntp-server-on-ubuntu-linuxmint/

$ sudo apt install ntp

/etc/ntp.confに追記

restrict 192.168.100.0 mask 255.255.255.0 nomodify notrap

あとはリロード

sudo service ntp reload

ファイアウォールも忘れてはいけない
123/tcpを許可する

実行

# cat /etc/chrony.conf 
server 192.168.100.10
leapsecmode slew
makestep 1.0 3

# /etc/init.d/S49chrony restart
# chronyc sources
210 Number of sources = 1
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^? 192.168.100.10                3   6     1    30  -18678d[-18678d] +/-  134ms
# chronyc makestep
200 OK
<3分くらい後に>
# date
Mon Feb 22 06:18:51 JST 2021

makestep 1.0 3

により、サービス起動時に1.0秒以上のズレがあった場合には即時調時されるっぽい。

buildrootと連携(rcloneパッケージの作成)

今後も見据えてmenuconfigから選択できるようにしたい。
このあたりを参考に

https://buildroot.org/downloads/manual/manual.html#outside-br-custom
https://buildroot.org/downloads/manual/manual.html#adding-packages

パッケージの追加

構成を考える
br2-externalにて指定している外部ツリー

ex_licheepizerodock

の下にpackageディレクトリを作成してもろもろ置いていく。
今回は思考停止して「rclone」とした。

tabが重要なので、エディタのtab→スペース変換はoffにしないとハマる。

ex_licheepizerodock$ tree
.
├── Config.in
<>
├── external.desc
├── external.mk
├── package
│   └── rclone
│       ├── Config.in
│       └── rclone.mk

Config.inとexternal.mkの変更

Config.inの変更

source "$BR2_EXTERNAL_LICHEEPI_ZERO_DOCK_EX_PATH/package/rclone/Config.in"

external.mkの変更

include $(sort $(wildcard $(BR2_EXTERNAL_LICHEEPI_ZERO_DOCK_EX_PATH)/package/*/*.mk))

package内のConfig.inと.mkの作成

Config.inの作成

config BR2_PACKAGE_RCLONE
    bool "rclone sync"
    help
        Rclone syncs your files to cloud storage

rclone.mkの作成

超絶シンプル。zip展開して、バイナリをコピーするだけ。

################################################################################
#
# Rclone syncs.
#
################################################################################

RCLONE_SOURCE = rclone-current-linux-arm.zip
RCLONE_SITE = https://downloads.rclone.org
RCLONE_LICENSE = MIT
RCLONE_SOURCE_BASENAME = rclone
RCLONE_BIN_NAME = rclone

define RCLONE_EXTRACT_CMDS
	unzip -j $(DL_DIR)/$(RCLONE_SOURCE_BASENAME)/$(RCLONE_SOURCE) -d $(@D)
endef

define RCLONE_INSTALL_TARGET_CMDS
	@echo BR2_PACKAGE_RCLONE_INSTALL_TARGET_CMDS
	$(INSTALL) -D -m 0755 $(@D)/$(RCLONE_BIN_NAME) $(TARGET_DIR)/usr/bin
endef

$(eval $(generic-package))

これでOK!


 

2020年1月31日金曜日

Nextcloudで動画のサムネイルを表示させる

Nextcloudを愛用しているのだけど、動画が三角アイコン表示になるのが悲しくて、どうにかしたいと思っていた。


ファイル名をちゃんとつけるほどのマメな管理はできないしー。
スキマ時間にやり方を探して試してみたけど、しっかり調べてなかったからすごく時間がかかってしまった。

調査

以下の手順が参考になった。NextCloud用の「Preview Generator」というプラグインがあるんだね。
https://www.allerstorfer.at/nextcloud-install-preview-generator/
でも、、、一生懸命海外のページを検索していたのだが、日本でちゃんとやっている方がいたOrz
https://bucci.bp7.org/archives/41840/
どうして、見つけられなかったんだろうね。

インストール

Preview Generatorのインストール

自分のNextcloud管理画面からインストールするのが簡単
https://apps.nextcloud.com/apps/previewgenerator

サムネイルを作成するために必要なソフトの導入

今回は動画のサムネイルがほしいので
apt-get  install ffmpeg imagemagick ghostscript
もしかしたらffmpegだけでも良かったかも

Nextcloudの設定ファイル

config.phpに追記を行う
'enable_previews' => true,
'enabledPreviewProviders' =>
 array (
    0 => 'OC\\Preview\\Image',
    1 => 'OC\\Preview\\Movie',
    2 => 'OC\\Preview\\MKV',
    3 => 'OC\\Preview\\MP4',
    4 => 'OC\\Preview\\AVI',
 ),
みたいな感じで

サムネイル作成

Nextcloud(Owncloud)の管理コマンドOCCを使うみたい

初回の全体スキャン

初回の全体スキャンは手動でやってみる
sudo -u www-data php /var/www/nextcloud/occ preview:generate-all -vvv
かなり時間がかかった。 とりあえず一晩放置し、アクセスしてみる。

できたー嬉しい!

自動更新のための設定

cronに登録しちゃうみたい。便利だね
crontab -u www-data -e
*/10 * * * * php /var/www/nextcloud/occ preview:pre-generate -vvv
この時のパラメータは「pre-generate」なので注意。
最初間違えてallにしてしまい大変な思いをした。
細かい使い方はちゃんと公式を参照しよう
https://github.com/rullzer/previewgenerator

スペック問題があるのか?リソース確認

AMD E-350 1.6GHz 2コア 64bit メモリ:8GBというかなりの老体なので、果たしてスペック大丈夫か!?
そろそろ後継考えないとね。
小型PCってなかなかニッチな気がするから、もしかしたらNASのほうが良いのかもしれん。
ちょっとCPU負荷を知りたいので、以下を参考にsarを実行してみた
https://every-rating.com/vps/sar.html
あれ?
$ sar
/var/log/sysstat/sa31 を開けません: そのようなファイルやディレクトリはありません
データ収集が有効になっているかを確認してください
設定を有効にしないといけないみたい…
https://www.skyarch.net/blog/?p=9777
$ cat /etc/default/sysstat
#
# Default settings for /etc/init.d/sysstat, /etc/cron.d/sysstat
# and /etc/cron.daily/sysstat files
#

# Should sadc collect system activity informations? Valid values
# are "true" and "false". Please do not put other values, they
# will be overwritten by debconf!
ENABLED="false"
をENABLED="true"に変更する
これでしばらく待ってからsarを実行してみる
sar -q
09時45分01秒   runq-sz  plist-sz   ldavg-1   ldavg-5  ldavg-15   blocked
09時55分01秒         4       334      0.13      0.12      0.09         0
平均値:          4       334      0.13      0.12      0.09         0
これとか
sar -u
09時45分01秒     CPU     %user     %nice   %system   %iowait    %steal     %idle
09時55分01秒     all      2.23      0.64      1.48      0.57      0.00     95.07
平均値:      all      2.23      0.64      1.48      0.57      0.00     95.07
これでしばらく様子を見てみようかね
使い方
https://qiita.com/kidach1/items/07637a5baa0da7d52e6a