Nextcloud を 15 にアップグレードしようとしてコケる

20181212_05:12:42-18746

Nextcloud 15 がリリースされました.

14.0.4 からアップグレードしようとしましたが失敗しました.そのメモです.

$ sudo -u www-data php7.0 ./occ upgrade
Nextcloud or one of the apps require upgrade - only a limited number of commands are available
You may use your browser or the occ upgrade command to do the upgrade
Set log level to debug
Updating database schema
Updated database
UnexpectedValueException: The files of the app "user_external" were not correctly replaced before running the update
Update failed
Maintenance mode is kept active
Reset log level

整合性が保たれていないようなので手動でアーカイブを入手して比較すると同じに見える

$ wget https://download.nextcloud.com/server/releases/nextcloud-15.0.0.tar.bz2 https://download.nextcloud.com/server/releases/nextcloud-15.0.0.tar.bz2.asc
$ gpg --verify ./nextcloud-15.0.0.tar.bz2.asc
gpg: 署名されたデータが'./nextcloud-15.0.0.tar.bz2'にあると想定します 
gpg: 2018年12月10日 19時27分11秒 JSTにRSA鍵ID A724937Aで施された署名
gpg: "Nextcloud Security <security@nextcloud.com>"からの正しい署名
gpg: *警告*: この鍵は信用できる署名で証明されていません!
gpg:          この署名が所有者のものかどうかの検証手段がありません。 
主鍵フィンガー・プリント: 2880 6A87 8AE4 23A2 8372  792E D758 99B9 A724 937A
$ tar tvf ./nextcloud-15.0.0.tar.bz2 | lv
$ tar xf ./nextcloud-15.0.0.tar.bz2
$ sudo -u www-data rsync -acvvn ./nextcloud/apps/user_external /var/www/home.matoken.org/nextcloud/apps/
sending incremental file list
delta-transmission disabled for local transfer or --whole-file
user_external/
user_external/appinfo/app.php is uptodate
user_external/appinfo/database.xml is uptodate
user_external/appinfo/info.xml is uptodate
user_external/appinfo/signature.json is uptodate
user_external/img/app.svg is uptodate
user_external/lib/base.php is uptodate
user_external/lib/ftp.php is uptodate
user_external/lib/imap.php is uptodate
user_external/lib/smb.php is uptodate
user_external/lib/webdavauth.php is uptodate
total: matches=0  hash_hits=0  false_alarms=0 data=0

sent 515 bytes  received 587 bytes  2,204.00 bytes/sec
total size is 19,690  speedup is 17.87 (DRY RUN)

このあたりのバグぽい

ちなみに user_external はFTP, IMAP, SMB の認証周りのよう.

Authenticate user login against FTP, IMAP or SMB.

とりあえず該当の user_external を無効にしてアップグレードは通った

$ sudo -u www-data php7.0 ./occ app:disable user_external
$ sudo -u www-data php7.0 ./occ upgrade

通ったけど無効にしていても怒られる

Some files have not passed the integrity check. Further information on how to resolve this issue can be found in the documentation. (List of invalid files… / Rescan…)

Technical information
=====================
The following list covers which files have failed the integrity check. Please read
the previous linked documentation to learn more about the errors and how to fix
them.

Results
=======
- user_external
    - EXTRA_FILE
        - user_external/appinfo/signature.json

Raw output
==========
Array
(
    [user_external] => Array
        (
            [EXTRA_FILE] => Array
                (
                    [user_external/appinfo/signature.json] => Array
                        (
                            [expected] => 
                            [current] => 37efcee67605ab01a595df9b8e37a63f0260a8d795cb4af9b1b40e137ace928193747445954b22455fcbfd1758ea9b663153afc73438f5370725682e344c8723
                        )

                )

        )

)

まだ非対応アプリも多いしメイン環境は暫く待ったほうが良さそうな感じです.

環境

$ sudo -u www-data php7.0 ./occ status -v
  - installed: true
  - version: 15.0.0.10
  - versionstring: 15.0.0
  - edition: 
$ lsb_release -d
Description:    Ubuntu 16.04.5 LTS
$ uname -m
x86_64

pdfファイルから画像を抜き出し( pdfimages or LibreOffice )

ここ2,3日で数回使ったのでメモしておきます.

poppler-utilsのpdfimagesを使う

概要
$ apt show poppler-utils | grep Description: -A99

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

Description: PDF 向けユーティリティ (Poppler ベース)
 Poppler は xpdf PDF ビューアを基に作られた PDF 描画ライブラリです。
 .
 本パッケージには (Poppler ベースの) コマンドラインユーティリティが含まれ、
 PDF 文書の情報の取得、他の形式への変換、編集ができます。
  * pdfdetach -- 埋め込みファイル (添付ファイル) の一覧出力または抽出
  * pdffonts -- フォント分析ツール
  * pdfimages -- 画像抽出ツール
  * pdfinfo -- 文書情報
  * pdfseparate -- ページ抽出ツール
  * pdfsig -- デジタル署名の検証
  * pdftocairo -- PDF から PNG/JPEG/PDF/PS/EPS/SVG への Cairo を使った変換ツール
  * pdftohtml -- PDF から HTML への変換ツール
  * pdftoppm -- PDF から PPM/PNG/JPEG 画像への変換ツール
  * pdftops -- PDF から PostScript (PS) への変換ツール
  * pdftotext -- テキストの抽出
  * pdfunite -- 文書の併合ツール
導入
$ sudo apt install poppler-utils
usage
$ pdfimages
pdfimages version 0.69.0
Copyright 2005-2018 The Poppler Developers - http://poppler.freedesktop.org
Copyright 1996-2011 Glyph & Cog, LLC
Usage: pdfimages [options] <PDF-file> <image-root>
  -f <int>       : first page to convert
  -l <int>       : last page to convert
  -png           : change the default output format to PNG
  -tiff          : change the default output format to TIFF
  -j             : write JPEG images as JPEG files
  -jp2           : write JPEG2000 images as JP2 files
  -jbig2         : write JBIG2 images as JBIG2 files
  -ccitt         : write CCITT images as CCITT files
  -all           : equivalent to -png -tiff -j -jp2 -jbig2 -ccitt
  -list          : print list of images instead of saving
  -opw <string>  : owner password (for encrypted files)
  -upw <string>  : user password (for encrypted files)
  -p             : include page numbers in output file names
  -q             : don't print any messages or errors
  -v             : print copyright and version info
  -h             : print usage information
  -help          : print usage information
  --help         : print usage information
  -?             : print usage information
pdfファイル内の画像リスト確認
$ pdfimages ./bicycle_parking.pdf -list
page   num  type   width height color comp bpc  enc interp  object ID x-ppi y-ppi size ratio
--------------------------------------------------------------------------------------------
   1     0 image     340   120  rgb     3   8  image  no         5  0   221   221 9576B 7.8%
   1     1 image     960   720  rgb     3   8  jpeg   yes       14  0   170   170 64.2K 3.2%
pdfファイルから画像抜き出し既定値では.ppm形式
$ pdfimages ./bicycle_parking.pdf ./bicycle_parking-images
$ ls -l ./bicycle_parking-images*
-rw-r--r-- 1 matoken matoken  122415 11月 12 21:40 ./bicycle_parking-images-000.ppm
-rw-r--r-- 1 matoken matoken 2073615 11月 12 21:40 ./bicycle_parking-images-001.ppm
$ identify ./bicycle_parking-images-000.ppm
./bicycle_parking-images-000.ppm PPM 340x120 340x120+0+0 8-bit sRGB 122415B 0.000u 0:00.000
png形式に変換して保存
$ pdfimages ./bicycle_parking.pdf ./bicycle_parking-images -png
$ ls -l ./bicycle_parking-images*
-rw-r--r-- 1 matoken matoken  10274 11月 12 21:46 ./bicycle_parking-images-000.png
-rw-r--r-- 1 matoken matoken 321115 11月 12 21:46 ./bicycle_parking-images-001.png
$ identify ./bicycle_parking-images-000.png
./bicycle_parking-images-000.png PNG 340x120 340x120+0+0 8-bit sRGB 10274B 0.000u 0:00.000
jpegファイルはjpegとして保存(それ以外はppm)
$ pdfimages ./bicycle_parking.pdf ./bicycle_parking-images -j
$ ls -l ./bicycle_parking-images*
-rw-r--r-- 1 matoken matoken 122415 11月 12 21:48 ./bicycle_parking-images-000.ppm
-rw-r--r-- 1 matoken matoken  65695 11月 12 21:48 ./bicycle_parking-images-001.jpg

LibreOfficeでOpenDocumentFormatに変換して画像だけ抜き出し

OpenDocumentFormatはzip形式で圧縮されてその中に画像ファイルも含まれるのでDraw形式に変換して画像ディレクトリの格納されている Pictures だけ展開すると画像が取り出せる.

導入はディストリビューションのほかFlatpack, snapなども公式で配布されているのでお好みで.今回は Debian sid amd64 でapt installしたもの.

$ libreoffice --headless --nologo --nofirststartwizard --convert-to odg ./bicycle_parking.pdf
convert /home/matoken/Downloads/bicycle_parking.pdf -> /home/matoken/Downloads/bicycle_parking.odg using filter : draw8
$ unzip ./bicycle_parking.odg Pictures/*
Archive:  ./bicycle_parking.odg
 extracting: Pictures/10000000000003C0000002D0136E1A08DF8E2B28.jpg
 extracting: Pictures/100000000000015400000078BA7345C344D8D008.png
$ ls -lA Pictures/
合計 80
-rw-r--r-- 1 matoken matoken 10812 11月 12 12:56 100000000000015400000078BA7345C344D8D008.png
-rw-r--r-- 1 matoken matoken 65695 11月 12 12:56 10000000000003C0000002D0136E1A08DF8E2B28.jpg
$ identify Pictures/*
Pictures/100000000000015400000078BA7345C344D8D008.png PNG 340x120 340x120+0+0 8-bit sRGB 10812B 0.000u 0:00.000
Pictures/10000000000003C0000002D0136E1A08DF8E2B28.jpg JPEG 960x720 960x720+0+0 8-bit sRGB 65695B 0.000u 0:00.000

環境

$ dpkg-query -W poppler-utils unzip libreoffice imagemagick
imagemagick     8:6.9.10.14+dfsg-7
libreoffice     1:6.1.3-1
poppler-utils   0.69.0-2
unzip   6.0-21
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

Googleの社名変更で apt update エラー

パッケージ情報更新のために apt update 中にエラーが発生しました.Googleのアプリケーション(Google Chrome等)を導入ししたときに入るGoogleのリポジトリで Google, Inc.Google LLC に変わったためのようです.

E: Repository 'http://dl.google.com/linux/chrome/deb stable Release' changed its 'Origin' value from 'Google, Inc.' to 'Google LLC'
N: This must be accepted explicitly before updates for this repository can be applied. See apt-secure(8) manpage for details.
Do you want to accept these changes and continue updating from this repository? [y/N]

Google LCCには去年変わっていてこのリポジトリにもやっと修正が入ったということのようです.(Androidアプリなどはもっと早かったですね)

ここで y で受け入れると次からこのエラーは現れません.

ヒット:4 http://dl.google.com/linux/chrome/deb stable Release
環境1
$ dpkg-query -W apt
apt     1.7.0
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64
環境2
$ dpkg-query -W apt
apt     1.7.0
$ lsb_release -d
Description:    Parrot 4.3
$ uname -m
x86_64

壊れたzipファイルからデータを復旧する

Flickrからダウンロードしたアーカイブがダウンロードに失敗したのか内容が見られないです.
アーカイブが壊れている場合 -F でどうにかなりそう?

$ zip -l data-download-1.zip
		zip warning: missing end signature--probably not a zip file (did you
		zip warning: remember to use binary mode when you transferred it?)
		zip warning: (if you are trying to read a damaged archive try -F)

zip error: Zip file structure invalid (data-download-1.zip)

-F では駄目で -FF を試してみる

$ zip -F data-download-1.zip --out data-download-1_fix.zip
Fix archive (-F) - assume mostly intact archive
		zip warning: bad archive - missing end signature
		zip warning: (If downloaded, was binary mode used?  If not, the
		zip warning:  archive may be scrambled and not recoverable)
		zip warning: Can't use -F to fix (try -FF)

zip error: Zip file structure invalid (data-download-1.zip)

-FF である程度救える感じ

$ zip -FF data-download-1.zip --out data-download-1_fix.zip
Fix archive (-FF) - salvage what can
		zip warning: Missing end (EOCDR) signature - either this archive
					 is not readable or the end is damaged
Is this a single-disk archive?  (y/n): y
  Assuming single-disk archive
Scanning for entries...
 copying: img_20140426_180357_13952989767_o.jpg  (1935629 bytes)
 copying: img_20140723_180327_14575993850_o.jpg  (2639807 bytes)
 copying: img_20140723_180323_14576035839_o.jpg  (3302817 bytes)
 copying: img_20140723_180400_14576043890_o.jpg  (3611376 bytes)
   :
 copying: imgp1491_15854514735_o.jpg
		zip warning: no end of stream entry found: imgp1491_15854514735_o.jpg
		zip warning: rewinding and scanning for later entries

こういう耐障害性は非圧縮tarやafioとかのほうが強いでしょうがWindowsなんかでは多分標準で扱えないしダウンロードに失敗した場合は再度試みることが出来るのでやっぱzipでいいのかな.

ちなみに今回はFlickrから同じファイルを3回ダウンロードしても全部同じ内容で壊れていたので恐らくFlickr側で壊れているなてことでデータを再リクエストしました…….

環境
$ dpkg-query -W zip tar afio
afio    2.5.1.20160103+gitc8e4317-1
tar     1.30+dfsg-2
zip     3.0-11+b1
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

Googleドライブにコマンドラインでアクセスするskickaを試す

Googleドライブにコマンドラインでアクセスできる skicka を少し試してみました.

GOPATHを設定していない場合設定
$ GOPATH=~/go
$ PATH=${PATH}:~/go/bin
skickaの導入
$ go get github.com/google/skicka

skickaの設定を行います.
init コマンドで設定ファイルを生成します.
設定ファイルは ~/.skicka.config として作れれます.
次にlsコマンドを発行します.初回実行時にはウェブブラウザが起動して認証処理が走ります.許可すると自動的に認証が完了してls処理が走ります.
認証情報は`~/.skicka.tokencache.json` に保存されます.
ls実行時に次回以降のためにメタデータを作成します.ファイルが多いと時間がかかります.プログレスが表示されるのでしばらく待ちましょう.
メタデータは ~/.skicka.metadata.cache に保存されます.

skickaの初期設定
$ skicka init
$ skicka ls

サーバなどでウェブブラウザを起動するのが難しい場合は -no-browser-authls コマンドの に付けて起動すると認証URLが表示されるのでそれを操作PCなどで開いて認証を行い,表示された認証コードをコマンドラインに貼り付けます.

$ skicka -no-browser-auth ls
Go to the following link in your browser:
https://accounts.google.com/o/oauth2/auth?client_id=952283912845-sjotrejbktpinel08hrnspl33d8gho1e.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&state=st1541320926479298710
Enter verification code: 4/iwBrjQFEvm2p0nQGXJuRQgTZFZZ6BmXkT7Up7Wl3UYS7NWEyiltTc6E
Usage
$ ~/go/bin/skicka
usage: skicka [skicka options] <command> [command options]

Supported commands are:
  cat       Print the contents of the given file
  download  Download a file or folder hierarchy from Drive to the local disk
  df        Display free space on Drive
  du        Report disk usage for a folder hierarchy on Drive
  fsck      Check consistency of files in Drive and local metadata cache
  genkey    Generate a new encryption key
  init      Create an initial skicka configuration file
  ls        List the contents of a folder on Google Drive
  mkdir     Create a new folder or folder hierarchy on Drive
  rm        Remove a file or folder on Google Drive
  upload    Upload a local file or directory hierarchy to Drive

'skicka help' prints more detailed documentation.
help
$ ~/go/bin/skicka help                                                                                                             [45/2151]
skicka is a tool for working with files and folders on Google Drive.
See http://github.com/google/skicka/README.md for information about getting started.

usage: skicka [common options] <command> [command options]

Commands and their options are:
  cat        Print the contents of the Google Drive file to standard output.
             Arguments: drive_path ...

  download   Recursively download either a single file, or all files from a
             Google Drive folder to a local directory. If the corresponding
             local file already exists and has the same contents as the its
             Google Drive file, the download is skipped.
             Arguments: [-ignore-times] [-download-google-apps-files]
                        drive_path local_path

  df         Prints the total space used and amount of available space on
             Google Drive.

  du         Print the space used by the Google Drive folder and its children.
             Arguments: [drive_path ...]

  fsck       [EXPERIMENTAL/NEW] Use at your own risk.
             Perform a number of consistency checks on files stored in Google
             Drive, including verifying metadata and removing duplicate files
             with the same name.
             Arguments: [--trash-duplicates] [drive_path]

  help       Print this help text.

  genkey     Generate a new key for encrypting files.

  init       Create an initial ~/.skicka.config configuration file. (You
             will need to edit it before using skicka; see comments in the
             configuration file for details.)

  ls         List the files and directories in the given Google Drive folder.                                                                          [8/2151]
             Arguments: [-d, -l, -ll, -r] [drive_path ...],
             where -l and -ll specify long (including sizes and update
             times) and really long output (also including MD5 checksums),
             respectively.  The -r argument causes ls to recursively list
             all files in the hierarchy rooted at the base directory, and
             -d causes directories specified on the command line to be
             listed as files (i.e., their contents aren't listed.)

  mkdir      Create a new directory (folder) at the given Google Drive path.
             Arguments: [-p] drive_path ...,
             where intermediate directories in the path are created if -p is
             specified.

  rm         Remove a file or directory at the given Google Drive path.
             Arguments: [-r, -s] drive_path ...,
             where files and directories are recursively removed if -r is
             specified and the google drive trash is skipped if -s is
             specified. The default behavior is to fail if the drive path
             specified is a directory and -r is not specified, and to send
             files to the trash instead of permanently deleting them.

  upload     Uploads all files in the local directory and its children to the
             given Google Drive path. Skips files that have already been
             uploaded.
             Arguments: [-ignore-times] [-encrypt] [-follow-symlinks <maxdepth>]
                        local_path drive_path

Options valid for both "upload" and "download":
  -dry-run         Don't actually upload or download, but print the paths of
                   all files that would be transferred.
  -ignore-times    Normally, skicka assumes that if the timestamp of a local
                   file matches the timestamp of the file on Drive and the
                   files have the same size, then it isn't necessary to
                   confirm that the file contents match. The -ignore-times
                   flag can be used to force checking file contents in this
                   case.

General options valid for all commands:
  -config <filename>     General skicka configuration file. Default: ~/.skicka.config.
  -debug                 Enable debugging output.
  -dump-http             Dump http traffic.
  -metadata-cache-file <filename>
                         File to store metadata about Google Drive contents.
                         Default: ~/.skicka.metadata.cache
  -no-browser-auth       Disables attempting to open the authorization URL in a web
                         browser when initially authorizing skicka to access Google Drive.
  -quiet                 Suppress non-error messages.
  -tokencache <filename> OAuth2 token cache file. Default: ~/.skicka.tokencache.json.
  -verbose               Enable verbose output.
ファイルのアップロード
$ skicka upload ~/Pictures/$(ls -tr1 ~/Pictures/|tail -1) /
Files:  14.41 KiB / 14.41 KiB [====================================================================================================================] 100.00% 3s
2018/11/04 17:45:32 Preparation time 1s, sync time 3s
2018/11/04 17:45:32 Updated 1 Drive files, 0 local files
2018/11/04 17:45:32 14.41 kiB read from disk, 0 B written to disk
2018/11/04 17:45:32 14.41 kiB uploaded (3.98 kiB/s), 0 B downloaded (0 B/s)
2018/11/04 17:45:32 52.08 MiB peak memory used
ファイルを確認
$ skicka ls|grep jpg
20180307_23:03:21-10889.jpg
20180307_23:03:21-10889.jpg
20181104_17:11:45-30082.jpg
ファイルのダウンロード
$ skicka rm 20181104_17:11:45-30082.jpg
$ diff ~/Pictures/20181104_17:11:45-30082.jpg /tmp/20181104_17:11:45-30082.jpg
$ ls -l ~/Pictures/20181104_17:11:45-30082.jpg /tmp/20181104_17:11:45-30082.jpg
-rw-r--r-- 1 matoken matoken 14760 11月  4 17:41 /home/matoken/Pictures/20181104_17:11:45-30082.jpg
-rw-r--r-- 1 matoken matoken 14760 11月  4 17:41 /tmp/20181104_17:11:45-30082.jpg
ファイルの削除
$ skicka rm /20181104_17:11:45-30082.jpg

skickaには暗号化機能があります.upload時に -encrypt オプションを付与することによりファイルを暗号化してGoogleドライブに保存できます.そのためには準備が必要です.
SKICKA_PASSPHRASE という環境変数にパスフレーズを設定した状態で,skicka genkey を実行して生成された情報を設定ファイルの ~/.skicka.config に書き込みます.

暗号化のためのkey等を生成する(環境変数はexportしないと認識しなかった)
$ read -sp "skicka pass: " SKICKA_PASSPHRASE && export SKICKA_PASSPHRASE && skicka genkey
skicka pass: ; Add the following lines to the [encryption] section
; of your ~/.skicka.config file.
        salt=62cd4c08693c935f35c45be5261907127ef14055f197bb19bae36616fedecb54
        passphrase-hash=23f702efce4fe7bf775d3bc80f07e2a765589016b537bf322ed5e0c8f2f6ce90
        encrypted-key=463c9c75b3aa98e5401bb5fde6d681f8053d39d3e5ce49ef22bcc58977736162
        encrypted-key-iv=d2533e58f6c9bb976a66d499280ce8c2
設定ファイルに暗号化情報を書き込む(コメントを外すのを忘れずに)
$ vi ~/.skicka.config
$ grep -A5 encryption ~/.skicka.config
[encryption]
        ; Run 'skicka genkey' to generate an encyption key.
        salt=62cd4c08693c935f35c45be5261907127ef14055f197bb19bae36616fedecb54
        passphrase-hash=23f702efce4fe7bf775d3bc80f07e2a765589016b537bf322ed5e0c8f2f6ce90
        encrypted-key=463c9c75b3aa98e5401bb5fde6d681f8053d39d3e5ce49ef22bcc58977736162
        encrypted-key-iv=d2533e58f6c9bb976a66d499280ce8c2

upload時に -encrypt を指定すると暗号化され,.aes256 という拡張子付きで保存されます.

暗号化しながら保存する
$ skicka mkdir encryption
$ skicka upload -encrypt ~/Pictures/20181105_19\:11\:18-8911.jpg /encryption/
$ skicka ls /encryption/
20181105_19:11:18-8911.jpg.aes256

元のファイル名ではダウンロードできず,.aes256 拡張子付きのファイル名ではダウンロードできた.このファイルは .aes256 の拡張子付きのままだが,復号されている.

ダウンロード
$ skicka download /encryption/20181105_19:11:18-8911.jpg ./
skicka: /encryption/20181105_19:11:18-8911.jpg: not found on Drive
$ skicka download /encryption/20181105_19:11:18-8911.jpg.aes256 ./
$ file ./20181105_19\:11\:18-8911.jpg.aes256
./20181105_19:11:18-8911.jpg.aes256: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, baseline, precision 8, 933x600, frames
3
$ identify ./20181105_19\:11\:18-8911.jpg.aes256
./20181105_19:11:18-8911.jpg.aes256 JPEG 933x600 933x600+0+0 8-bit sRGB 92988B 0.000u 0:00.000
$ display ./20181105_19\:11\:18-8911.jpg.aes256

ウェブブラウザからダウンロードしたファイルは暗号化されている.データ量は少し増えている.

$ file 20181105_19_11_18-8911.jpg.aes256.jpg.aes256
20181105_19_11_18-8911.jpg.aes256.jpg.aes256: data
$ ls -la 201811*
-rw-r--r-- 1 matoken matoken 92988 11月  5 19:30 20181105_19:11:18-8911.jpg.aes256
-rw-r--r-- 1 matoken matoken 93004 11月  5 21:46 20181105_19_11_18-8911.jpg.aes256.jpg.aes256
環境
$ dpkg-query -W golang git bash
bash    4.4.18-3.1
git     1:2.19.1-1
golang  2:1.10~5
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

特定プロセスのcpu利用率を制限するcpulimitを試す

先日mysqldump + xz 圧縮の間に pv を挟んで帯域制限をして xz の負荷を下げました.

しかしこの方法ではそんなに負荷がない mysqldump もずっと動かしっぱなしで db にもよろしく無いです.mysqldump は先に済ませて xz だけを制限することにします.

before
umask 0266 && nice -n 19 ionice -c 3 /usr/bin/mysqldump --defaults-file=/mnt/backup/micro/.my-backup.cnf --single-transaction --quick --all-databases --events | pv -L 128k 2>/dev/null | nice -n 19 ionice -c 3 /usr/bin/xz -9 > /mnt/backup/micro/`date +\%F_\%T_$$`.sql.xz
after
DUMP="/mnt/backup/micro/`date +\%F_\%T_$$`.sql"; umask 0266 && nice -n 19 ionice -c 3 /usr/bin/mysqldump --defaults-file=/mnt/backup/micro/.my-backup.cnf --single-transaction --quick --all-databases --events > ${DUMP} && pv -L 128k nice -n 19 ionice -c 3 /usr/bin/xz -9 > ${DUMP}.xz && rm ${DUMP}

一応動くけどcrontabなので1行で書いてあって見にくいしあまりいけてないですね.
せめてファイルに分けたほうが良さそう.

LimitCPU

pvでもいいのですが,cpu利用率を制限できないかなと思いました.xzのオプションでは見当たらずLinux環境なので cgroups で制限しようかとも思ったのですが, LimitCPU というものを見つけました.これは SIGSTOPSIGCONT のPOSIXシグナルをプロセスに送信することにより実現しているので,POSIX環境ならどこでも動きそうなのでこちらを試してみました.

LimitCPUはメンテされなくなったCPUlimitのフォークでコマンドやパッケージ名は cpulimit です.(混乱する><)

導入
$ sudo apt install cpulimit
usage
$ cpulimit -h
CPUlimit version 2.1
Usage: cpulimit TARGET [OPTIONS...] [-- PROGRAM]
   TARGET must be exactly one of these:
      -p, --pid=N        pid of the process
      -e, --exe=FILE     name of the executable program file
                         The -e option only works when
                         cpulimit is run with admin rights.
      -P, --path=PATH    absolute path name of the
                         executable program file
   OPTIONS
      -b  --background   run in background
      -c  --cpu=N        override the detection of CPUs on the machine.
      -l, --limit=N      percentage of cpu allowed from 1 up.
                         Usually 1 - 200, but can be higher
                         on multi-core CPUs (mandatory)
      -q, --quiet        run in quiet mode (only print errors).
      -k, --kill         kill processes going over their limit
                         instead of just throttling them.
      -r, --restore      Restore processes after they have
                         been killed. Works with the -k flag.
      -s, --signal=SIG   Send this signal to the watched process when cpulimit exits.
                         Signal should be specificed as a number or
                         SIGTERM, SIGCONT, SIGSTOP, etc. SIGCONT is the default.
      -v, --verbose      show control statistics
      -z, --lazy         exit if there is no suitable target process,
                         or if it dies
          --             This is the final CPUlimit option. All following
                         options are for another program we will launch.
      -h, --help         display this help and exit

制限はプロセスIDでの制限,プログラム名での制限,指定したプログラムを制限することが可能です.
cpuが複数ある場合は -l の値はcpu 1つあたり100として,100 * cpu数 を元に指定します.cpu 2つで 50% 利用したい場合は -l 100 になると思います.

プロセスID 1234 のプログラムをcpuを2つ利用,cpuを50%(2コアなので実際は100%分)
$ cpulimit -c 2 -p 1234 -l 50
xzというプログラムをcpu利用率を25%に制限
$ cpulimit -c 2 -l 50 - xz

※xzの前の - はなくてもいいが cpulimit のオプションの最後を示す.

cpuを1つだけ利用.cpu利用率を25%に制限しつつxzを実行できます.
$ cpulimit -c 1 -l 25 -z -  xz -9 datafile
  • -c : 利用するcpu数

  • -p : 制限するプロセスID

  • -l : 制限するcpu利用率

  • -z : 指定したプロセスが完了したらcpulimitも終了する(通常は関しを続けて同じ条件に一致するプロセスが現れたら制限する)

今回はxzを制限したいのでこんな感じに.
あまり変わりませんね…….

DUMP="/mnt/backup/micro/`date +\%F_\%T_$$`.sql"; umask 0266 && nice -n 19 ionice -c 3 /usr/bin/mysqldump --defaults-file=/mnt/backup/micro/.my-backup.cnf --single-transaction --quick --all-databases --events > ${DUMP} && nice -n 19 ionice -c 3 cpulimit -c1 -l 25 - /usr/bin/xz -9 ${DUMP}

バックアップ専用ユーザとして分けてあるのでそのユーザで cpulimit -c 1 -l 25 - xz とかしてxzという名前のプロセスを全部制限してしまうのもありかもしれません.monit とかで監視させればいい感じかも?そうすると,

DUMP="/mnt/backup/micro/`date +\%F_\%T_$$`.sql"; umask 0266 && nice -n 19 ionice -c 3 /usr/bin/mysqldump --defaults-file=/mnt/backup/micro/.my-backup.cnf --single-transaction --quick --all-databases --events > ${DUMP} && /usr/bin/xz -9 ${DUMP}

あまり変わりませんね…….

環境
$ dpkg-query -W cpulimit xz-utils
cpulimit        2.2-1
$ lsb_release -d
Description:    Ubuntu 16.04.5 LTS
$ uname -m
x86_64

rsyncで同期したファイルの内容が間違っていて困る

最近外のサーバのffmpegで生成したファイルをrsyncコマンドで家にコピーしています.しかし,先日rsyncでコピーが正常終了したファイルなのに再生が出来ないファイルが現れました.
恐らくffmpegの処理が最後まで終わっていない状態でrsyncを開始して,ffmpegの -movflags faststart が最後のあたりでrsyncで転送が終わった領域を書き換えたのではないかと思います.
rsyncはチェックサムを確認していたのでは?と確認するとどうも明示的にチェックサムのオプションを付与しないと簡易的なチェックしかしていないようです.
少し確認してみました.

内容が違うけれどファイルサイズとタイムスタンプの同じファイルを用意する.

$ mkdir from to
$ echo '0123456789' > from/01
$ echo '0123456780' > to/01
$ touch -d0 from/01
$ touch -d0 to/01
$ ls -l from/01 to/01
-rw-r--r-- 1 matoken matoken 11 11月  2 00:00 from/01
-rw-r--r-- 1 matoken matoken 11 11月  2 00:00 to/01

rsync の --archive option でコピーすると同じファイルと認識されて同期されない.内容も異なったまま.

$ rsync -av from/ to/
sending incremental file list

sent 73 bytes  received 12 bytes  170.00 bytes/sec
total size is 11  speedup is 0.13
$ diff from/01 to/01
1c1
< 0123456789
---
> 0123456780

rsync の --checksum optionを付与すると別のファイルと認識されて同期されて内容も同一になる.

$ rsync -av --checksum from/ to/
sending incremental file list
01

sent 147 bytes  received 35 bytes  364.00 bytes/sec
total size is 11  speedup is 0.06
$ diff from/01 to/01

ということでこんな感じに変更した.

$ rsync -avAHXce ssh --partial --append user@server:from/ to/

#実際はよく回線切れるのでwhile loop に入れてある.

EDIT: 転送済み部分のチェックはこれではNGで --append(既存のファイルに追記)を削る必要があった.--append-verify で行けそうな気がしたがこれもNGだった.

環境
$ dpkg-query -W rsync
rsync   3.1.2-2.2
$ lsb_release -d
Description:    Ubuntu 18.10
$ uname -m
x86_64

Debian, Ubuntu で 上流のパッケージを借りてくる

以前以下のような記事を書きました.

今でもこのblogの中ではアクセスが多く,最近もトラックバックをもらいました.

この当時は arm64 の mozcパッケージがなくて自分でbuild したという話なのですが,現在はDebian では buster(testing), Ubuntu ではartful(17.10) 以降でパッケージが存在します.
なのでこの野良パッケージを使うよりも公式の上流パッケージを借りるほうが大抵の場合いいと思います.
ということで手順を書いておきます.

パッケージファイルだけが必要な場合はパッケージのページからダウンロード可能です.

野良パッケージは近日中に削除します.

Debian stretch arm64 に Debian buster arm64 の mozc を借りてくる

Debian stretch arm64 では mozc-data しかない
$ apt-cache search mozc
mozc-data - Mozc input method - data files

buster(testing) のmozc を借りてくることにする.

/etc/apt/preferences で buster の優先度を下げる

/etc/apt/preferences
Package: *
Pin: release n=buster
Pin-Priority: 100
/etc/apt/sources.list に buster(testing)追加 設定
deb http://deb.debian.org/debian buster main

sources.list の編集には apt edit-sources を使うと文法チェックをしてくれるのでおすすめ

パッケージ情報の更新
$ sudo apt update
mozcパッケージの確認
$ apt-cache search mozc
mozc-data - Mozc input method - data files
fcitx-dbus-status - Addon for Fcitx to set/get/monitor IM statuses via D-Bus
emacs-mozc - Mozc for Emacs
emacs-mozc-bin - Helper module for emacs-mozc
fcitx-mozc - Mozc engine for fcitx - Client of the Mozc input method
ibus-mozc - Mozc engine for IBus - Client of the Mozc input method
mozc-server - Server of the Mozc input method
mozc-utils-gui - GUI utilities of the Mozc input method
uim-mozc - Mozc engine for uim - Client of the Mozc input method
パッケージの導入
$ apt install fcitx-mozc -t buster

後は通常の apt update && apt upgrade で stretch で導入したパッケージは stretch で,buster で導入したパッケージはbuster で更新されるはず.

Ubuntu 16.04 LTS xenial arm64 に Ubuntu 18.04 LTS bionic arm64 の mozc を借りてくる

Debianの手順と同じでもokだと思うけど念の為以下の手順を真似してみる.

mozc は Ubuntu 17.10 artful から対応しているが,もうサポートされないのでUbuntu 18.04 bionic を使う.

標準のリリースを xenial に設定

/etc/apt/apt.conf.d/01ubuntu
APT::Default-Release "xenial";

mozc をpinningする

/etc/apt/preferences
Package: *mozc*
Pin: release n=xenial
Pin-Priority: -10

Package: *mozc*
Pin: release n=bionic
Pin-Priority: 900

/etc/apt/sources.list に buster(testing) を 追加 設定

/etc/apt/sources.list
deb http://ports.ubuntu.com/ bionic main universe

※sources.list の編集には apt edit-sources を使うと文法チェックをしてくれるのでおすすめ
※mirrorにより arm64 が置かれていないので注意

パッケージ情報の更新
$ sudo apt update
検索結果にmozcが出てくる
$ apt-cache search mozc
mozc-data - Mozc input method - data files
ibus-mozc - Mozc engine for IBus - Client of the Mozc input method
mozc-server - Server of the Mozc input method
mozc-utils-gui - GUI utilities of the Mozc input method
emacs-mozc - Mozc for Emacs
emacs-mozc-bin - Helper module for emacs-mozc
fcitx-mozc - Mozc engine for fcitx - Client of the Mozc input method
uim-mozc - Mozc engine for uim - Client of the Mozc input method
パッケージの導入
$ sudo apt install fcitx-mozc -t bionic

Redshift-gtk が位置情報を取得出来なくて困る

太陽の動きに合わせてモニタの色や明るさの調整をしてくれる f.LuxインスパイアなRedshiftというプログラムがあるのですが,新しい環境に導入しても動作しません.位置情報が取得できないようです.

44624259834 09ae5f8845

$ redshift
位置プロバイダ `geoclue2' を試行しています...
プロバイダ `geoclue2' を使用します。
方式 `randr' を使用します。
初期位置が取得可能になるのを待機しています...
Unable to start GeoClue client: GDBus.Error:org.freedesktop.DBus.Error.AccessDenied: 'redshift' disallowed, no agent for UID 1000.
Access to the current location was denied by GeoClue!
Make sure that location services are enabled and that Redshift is permitted
to use location services. See https://github.com/jonls/redshift#faq for more
information.
プロバイダから位置を取得できません。

geoclue2のdemoを試してみますがやはり動きません.agentを実行した状態だと動きます.

demoも動かない
$ sudo apt install geoclue-2-demo
$ /usr/lib/geoclue-2.0/demos/where-am-i

** (where-am-i:16681): CRITICAL **: 07:00:13.576: Failed to connect to GeoClue2 service: GDBus.Error:org.freedesktop.DBus.Error.AccessDenied: 'geoclue-where-am-i' disallowed, no agent for UID 1000
agentを実行してから試すと取得できるが確認メッセージが表示される
$ /usr/lib/geoclue-2.0/demos/agent &
$ /usr/lib/geoclue-2.0/demos/where-am-i
Geolocation service not in use
Geolocation service in use
Client object: /org/freedesktop/GeoClue2/Client/1

New location:
Latitude:    34.700000°
Longitude:   137.733300°
Accuracy:    25000.000000 meters
Timestamp:   2018年10月16日 07時01分35秒 (1539640895 seconds since the Epoch)
$ redshift
位置プロバイダ `geoclue2' を試行しています...
プロバイダ `geoclue2' を使用します。
方式 `randr' を使用します。
初期位置が取得可能になるのを待機しています...
Geolocation service not in use
Geolocation service in use
位置: 北緯 34.70°, 東経 137.73°

44434687985 2bbe2c44ec
44434688165 c1b5632101

GeoClueの設定で確認メッセージを表示しないように設定しておきます.

/etc/geoclue/geoclue.conf にredshiftの設定を追記
$ echo '[redshift]
allowed=true
system=false
users=' | sudo tee -a
/etc/geoclue/geoclue.conf
[redshift]
allowed=true
system=false
users=
agentを再起動して試す
$ kill %1
[1]+  Terminated              /usr/lib/geoclue-2.0/demos/agent
$ /usr/lib/geoclue-2.0/demos/agent &
[1] 32138
$ redshift
位置プロバイダ `geoclue2' を試行しています...
プロバイダ `geoclue2' を使用します。
方式 `randr' を使用します。
初期位置が取得可能になるのを待機しています...
Geolocation service not in use
Geolocation service in use
位置: 北緯 34.70°, 東経 137.73°
^CGeolocation service not in use

てことで,agentを実行しておけば動くようになりました.しかし,位置がかなりずれています.浜松あたりの座標が帰って来ていますが,実際は鹿児島です.
半時間はずれてそうです.

Redshift のhelpを確認すると手動で座標を指定できるようです.

redshift help
$ gtk-redshift --help
ヘルプを出力するには `redshift -h` を実行してください。
$ redshift -h
使い方: redshift -l 緯度:経度 -t 昼の色温度:夜の色温度 [オプション...]

時刻に従ってディスプレイの色温度を設定します。

  -h            このヘルプ メッセージを表示
  -v            詳細な出力
  -V            プログラムのバージョンを表示

  -b DAY:NIGHT  画面に適用する明るさ (0.1 から 1.0 の間)
  -c FILE       指定した設定ファイルから設定を読み込む
  -g R:G:B      追加で適用するガンマ補正
  -l LAT:LON    あなたの現在位置
  -l PROVIDER   自動で位置情報を更新するプロバイダを選択
                (`list' を指定すると利用可能なプロバイダの一覧が見られます)
  -m METHOD     色温度の設定方式
                (`list' を指定すると利用可能な方式の一覧が見られます)
  -o            ワン ショット モード (色温度の変更は継続して行いません)
  -O TEMP       ワン ショット 手動モード (色温度を設定します)
  -p            表示モード (パラメータの出力のみを行って終了します)
  -P            新しい色効果の適用前に既存のガンマ ランプをリセット
  -x            リセット モード (画面の調整を解除します)
  -r            色温度の緩やかな変更を無効にする
  -t DAY:NIGHT  昼間/夜間に設定する色温度

ニュートラルな温度は 6500K です。この値を用いると
ディスプレイの色温度は変更されません。これよりも高い値を設定すると
青い光が増え、低い値を設定すると赤い光が増えます。

既定値:

  昼間の温度: 6500K
  夜間の温度: 4500K

バグは <https://github.com/jonls/redshift/issues> に報告してください
$ redshift -l list
利用可能な位置プロバイダ:
  geoclue2
  manual

`-l プロバイダ名:オプション' でコロン区切りのオプションを指定します。
`-l プロバイダ名:help' でヘルプが参照できます。

OpenStreetMapなどで設定したい場所のURLで時計度の座標が確認出来ます.

座標を指定して実行してみます.小数点以下2桁しか見ないようです.

redshiftに手動で座標指定
$ redshift -l 35.69935:139.76957
方式 `randr' を使用します。
初期位置が取得可能になるのを待機しています...
位置: 北緯 35.70°, 東経 139.77°
^C
$ gtk-redshift -l 35.70:139.77 &

設定ファイルに位置情報設定しておきます.これでオプション無しでokになります.(秋葉原周辺の設定)

$ mkdir -p ~/.config/redshift
$ vi ~/.config/redshift/redshift.conf
~/.config/redshift/redshift.conf
[redshift]

location-provider=manual

[manual]
;秋葉原付近の差表
lat=35.70
lon=139.77
ADD 2020-12-28)

Debian sid amd64の redshift 1.12 ではPATHが ~/.config/redshift.conf に変わっていました.

$ redshift -V
redshift 1.12
$ dpkg-query -W redshift
redshift        1.12-4
$ man redshift | grep redshift.conf
       A  configuration  file  with  the name redshift.conf can optionally be placed in ~/.config/. The file has standard INI format. General

手動でとりあえず設定できましたが,移動するたびに設定するのは面倒なので別の位置情報取得データベースを試してみます.

GeoIPの導入とアップデート
$ sudo apt install geoip-bin geoip-database geoip-database-extra geoipupdate
$ sudo geoipupdate
$ geoiplookup $(curl -s ifconfig.me/ip)
GeoIP Country Edition: JP, Japan
GeoIP City Edition, Rev 1: JP, 13, Hyogo, Nishinomiya, 662-0934, 34.716702, 135.333298, 0, 0
GeoIP ASNum Edition: AS10013 FreeBit Co.,Ltd.

GeoIPは兵庫になりました.少し近づいたけどやはりかなりずれています.
これでうまく行ったらこんな感じで設定できるのですが.

GeoIPを使ったredshift利用例
$ gtk-redshift -l $( geoiplookup $(curl -s ifconfig.me/ip)|grep City | cut -f7-8 -d, | sed -e 's/,/:/' -e 's/\ //g' )

てことでagentを起動するのは面倒だし旅行の予定もないのでとりあえずマニュアル設定にしておきます.

環境
$ dpkg-query -W redshift redshift-gtk geoclue-2.0 geoclue-2-demo geoip-bin geoip-database geoip-database-extra geoipupdate
geoclue-2-demo  2.4.12-2
geoclue-2.0     2.4.12-2
geoip-bin       1.6.12-1
geoip-database  20180315-1
geoip-database-extra    20180315-1
geoipupdate     2.5.0-1
redshift        1.12-2
redshift-gtk    1.12-2
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

Raspbian stretch 2018-10-09

Raspberry Pi の Debian ベースのディストリビューションの最新版の Raspbian 2018-10-09 がリリースされたようです.

curl -sS -o – http://downloads.raspberrypi.org/raspbian/release_notes.txt | perl -e ‘$c=0;while(<STDIN>){if$c!=0 ) && ( $=~/^\ /{print $}elsif($c==0){print $_}else{exit} $c++}’
2018-10-09:
  * In startup wizard, assign keyboard to country as per Debian installer recommendations
  * In startup wizard, add option to use US keyboard in preference to country-specific option
  * In startup wizard, show IP address on first page
  * In startup wizard, check for existing wifi network connection and show it if there is one
  * In startup wizard, install language support packages for LibreOffice and other applications
  * In startup wizard, improve operation with keyboard only and no mouse
  * Password change in Raspberry Pi Configuration and startup wizard now works properly if passwords contain shell characters
  * Battery indicator plugin modified to cope with Pi-top hardware monitor crashing
  * Networking plugin hides wifi password characters by default
  * In Scratch 2 GPIO plugin, set pin from dropdown list rather than free text
  * In Scratch 2 SenseHAT plugin, swap x and y axis values for LED array
  * Include latest Adobe Flash player (31.0.0.108)
  * Include latest RealVNC Server (6.3.1)
  * Include libav-tools
  * Include ssh-import-id
  * Removed Mathematica
  * Merge in latest third-party code for Bluetooth ALSA interface
  * Add ability to prevent software update changing configuration files, by creating ~/.config/.lock file
  * Various other small bug fixes, tweaks and changes to text
  * Make dhcpcd work with 3G devices
  * Add hw acceleration to ffmpeg
  * Improved WiFi-BT coexistence parameters
  * Run fake-hwclock before systemd-fsck-root
  * Raspberry Pi PoE HAT support
  * Linux kernel 4.14.71
  * Raspberry Pi firmware 5b49caa17e91d0e64024380119ad739bb201c674

個人的には 「 Add hw acceleration to ffmpeg」 が嬉しいです.自分でbuildしなくてもよくなってそうです.

$ dpkg-query -W ffmpeg
ffmpeg  7:3.2.10-1~deb9u1+rpt2
$ ffmpeg 2>&1 | grep -o -E '\--enable-omx-rpi|\--enable-mmal'
--enable-omx-rpi
--enable-mmal

とりあえずダウンロードしておきます.

$ # ダウンロードURL確認
$ LANG=C wget --max-redirect=0 https://downloads.raspberrypi.org/raspbian_lite_latest 2>&1 | sed -En 's/Location: ([^ ]*).*$/\1/p'
https://downloads.raspberrypi.org/raspbian_lite/images/raspbian_lite-2018-10-11/2018-10-09-raspbian-stretch-lite.zip
$ # ファイル確認
$ w3m -dump https://downloads.raspberrypi.org/raspbian_lite/images/raspbian_lite-2018-10-11/
Index of /raspbian_lite/images/raspbian_lite-2018-10-11

   [ICO]                        Name                        Last    Size Description
                                                          modified
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
[PARENTDIR] Parent Directory                                           -
[ ]         2018-10-09-raspbian-stretch-lite.info        2018-10-09  54K
                                                              13:34
[ ]         2018-10-09-raspbian-stretch-lite.zip         2018-10-09 351M
                                                              13:34
[ ]         2018-10-09-raspbian-stretch-lite.zip.sha1    2018-10-11   79
                                                              11:38
[ ]         2018-10-09-raspbian-stretch-lite.zip.sha256  2018-10-11  103
                                                              11:38
[ ]         2018-10-09-raspbian-stretch-lite.zip.sig     2018-10-10  473
                                                              13:37
[ ]         2018-10-09-raspbian-stretch-lite.zip.torrent 2018-10-11  28K
                                                              11:38
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━


Apache/2.4.10 (Debian) Server at downloads.raspberrypi.org Port 80
$ # bitttorrent と 署名ファイルダウンロード
$ wget https://downloads.raspberrypi.org/raspbian_lite/images/raspbian_lite-2018-10-11/2018-10-09-raspbian-stretch-lite.zip.torrent https://downloads.raspberrypi.org/raspbian_lite/images/raspbian_lite-2018-10-11/2018-10-09-raspbian-stretch-lite.zip.sig
$ # Transmission で ダウンロード
$ transmission-cli ./2018-10-09-raspbian-stretch-lite.zip.torrent
   :
$ # 署名確認
$ gpg --verify 2018-10-09-raspbian-stretch-lite.zip.sig