プログラミングとかLinuxとかの備忘録

プログラミング、Linuxでハマった箇所や環境構築のメモ

Ubuntu18.04でnvidia-dockerを動かす

Ubuntu16.04でnvidia-dockerを動かすのUbuntu18.04版。

構成

初期設定

インストール時に
- IPの固定 - SSHサーバの自動起動 は設定済みなのでアップデートのみ行う。

$ sudo apt update
$ sudo apt -y upgrade

CUDA

確認

以下のコマンドで,何も出てこないことを確認する

$ sudo dpkg -l | grep nvidia
$ sudo dpkg -l | grep cuda

Nvidiaドライバのインストール

リポジトリ(Proprietary GPU Drivers : “Graphics Drivers” team)
を登録して,ドライバをインストールする
途中で,secure bootを無効にするかを聞かれたが,無効にせずに続行した

$ sudo add-apt-repository ppa:graphics-drivers/ppa
$ sudo apt update

$ sudo apt search nvidia | egrep '^nvidia-[0-9]+/'
nvidia-304/bionic 304.137-0ubuntu2 amd64
nvidia-331/bionic-updates 340.107-0ubuntu0.18.04.2 amd64
nvidia-340/bionic-updates 340.107-0ubuntu0.18.04.2 amd64
nvidia-346/bionic 352.63-0ubuntu3 amd64
nvidia-352/bionic 361.45.11-0ubuntu4 amd64
nvidia-361/bionic 367.57-0ubuntu5 amd64
nvidia-367/bionic 375.82-0ubuntu3 amd64
nvidia-375/bionic 384.111-0ubuntu1 amd64
nvidia-384/bionic 390.87-0ubuntu0~gpu18.04.2 amd64
nvidia-387/bionic 390.87-0ubuntu0~gpu18.04.2 amd64
nvidia-390/bionic 390.87-0ubuntu0~gpu18.04.2 amd64

$ sudo apt -y install nvidia-390

再起動し,GPUが認識されているかを確認

$ sudo reboot

$ nvidia-smi
Fri Feb 22 04:36:58 2019
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 390.87                 Driver Version: 390.87                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 00000000:41:00.0 Off |                  N/A |
|  0%   38C    P5    27W / 250W |      0MiB / 11156MiB |      3%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

dockerのインストール

docker-engine, docker-ce, docker-eeのいずれかのパッケージが依存関係として必要なので、Ubuntu公式リポジトリdocker.ioではnvidia-dockerを実行できない。
Get Docker CE for Ubuntu | Docker Documentation の通りにインストールする

$ sudo apt -y remove docker docker-engine docker.io containerd runc

$ sudo apt -y install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
$ sudo apt-key fingerprint 0EBFCD88
$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
$ sudo apt update

$ sudo apt -y install docker-ce docker-ce-cli containerd.io
$ sudo gpasswd -a <ユーザ名> docker

$ sudo systemctl start docker
$ sudo systemctl enable docker

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

nvidia-dockerのインストール

GitHub - NVIDIA/nvidia-docker: Build and run Docker containers leveraging NVIDIA GPUsの通りにインストールする

$ curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
$ curl -s -L https://nvidia.github.io/nvidia-docker/ubuntu18.04/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list
$ sudo apt update

$ sudo apt -y install nvidia-docker2
$ sudo pkill -SIGHUP dockerd

テスト

$ docker run --runtime=nvidia --rm nvidia/cuda:9.0-base nvidia-smi
Fri Feb 22 04:42:24 2019
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 390.87                 Driver Version: 390.87                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 00000000:41:00.0 Off |                  N/A |
|  0%   37C    P5    34W / 250W |      0MiB / 11156MiB |      3%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

Ubuntuで不要になったリポジトリを削除する

sudo apt updateするといろいろとエラーが出るようになったので、使っていないnvidia-dockerのリポジトリを削除する。
ついでに、Nvidiaのグラフィックドライバのリポジトリも削除する

nvidia-dockerの削除

まずnvidia-docker2自体を削除する

$ sudo apt remove --purge nvidia-docker2
$ sudo apt -y autoremove

リポジトリリストを削除する

$ cd /etc/apt/sources.list.d
$ ls 
graphics-drivers-ubuntu-ppa-xenial.list       nvidia-docker.list
graphics-drivers-ubuntu-ppa-xenial.list.save  nvidia-docker.list.save

$ sudo rm nvidia-docker.list nvidia-docker.list.save

GPGキーを削除する

$ sudo apt-key list
/etc/apt/trusted.gpg
--------------------
...
pub   4096R/F796ECB0 2017-09-28
uid                  NVIDIA CORPORATION (Open Source Projects) <cudatools@nvidia.com>
...

$ sudo apt-key del F796ECB0
OK

これでapt-key listNvidiaのキーが表示されなくなる

updateしてみてもエラーが出なくなるはず

$ sudo apt update
Hit:1 http://jp.archive.ubuntu.com/ubuntu xenial InRelease
Get:2 http://jp.archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB]                            
Get:3 http://jp.archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB]                                                
Get:4 http://security.ubuntu.com/ubuntu xenial-security InRelease [109 kB]                                                   
Hit:5 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu xenial InRelease       
Get:6 https://download.docker.com/linux/ubuntu xenial InRelease [66.2 kB]         
Get:7 http://security.ubuntu.com/ubuntu xenial-security/main amd64 DEP-11 Metadata [67.9 kB]
Get:8 http://security.ubuntu.com/ubuntu xenial-security/main DEP-11 64x64 Icons [67.1 kB]
Get:9 http://security.ubuntu.com/ubuntu xenial-security/universe amd64 DEP-11 Metadata [116 kB]
Get:10 http://security.ubuntu.com/ubuntu xenial-security/universe DEP-11 64x64 Icons [173 kB]
Get:11 http://security.ubuntu.com/ubuntu xenial-security/multiverse amd64 DEP-11 Metadata [2,464 B]
Fetched 818 kB in 2s (312 kB/s)     
Reading package lists... Done
Building dependency tree       
Reading state information... Done

graphics-driversの削除

追加時にコマンド

$ sudo add-apt-repository ppa:graphics-drivers/ppa

でppaを使って追加したので

$ sudo add-apt-repository --remove ppa:graphics-drivers/ppa

だけで削除できる。

updateしてもちゃんと消えている

$ sudo apt update
Hit:1 http://jp.archive.ubuntu.com/ubuntu xenial InRelease
Get:2 http://jp.archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB]                           
Get:3 http://jp.archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB]                                   
Hit:4 https://download.docker.com/linux/ubuntu xenial InRelease                                                  
Hit:5 http://security.ubuntu.com/ubuntu xenial-security InRelease                                                
Fetched 216 kB in 0s (274 kB/s)
Reading package lists... Done
Building dependency tree       
Reading state information... Done

OpenVPNの"No server certificate verification method has been enabled"を解決する

DockerでOpenVPNサーバを動かす で構築したOpenVPNサーバに接続する時に接続はできるが下の警告が出るので、出ないように設定したい。

警告内容

WARNING: No server certificate verification method has been enabled.
See http://openvpn.net/howto.html#mitm for more info.

解決方法

メッセージに出ていたURLのページ(2x HOW TO | OpenVPN)を見てみる

  • remote-cert-tls server
    • OpenVPN 2.0以下の場合はこの設定をクライアントファイルに追加する?
  • ns-cert-type server
    • それ以外のバージョン?ではこの設定をクライアントファイルに追加する?

特にサーバ側の設定は必要なさそう。

ns-cert-type server

OpenVPNサーバのバージョンが2.4.6なのでこっちを試してみる。

クライアントの*.ovpnファイルの適当な位置にns-cert-type serverを追加

client
dev tun
proto udp
ns-cert-type server
...省略

接続してみると

WARNING: -ns-cert-type is DEPRECATED. Use --remote-cert-tls instead.

が表示されて接続できなくなった。

remote-cert-tls server

*.ovpnファイルの

ns-cert-type server

remote-cert-tls server

に書き換えて接続すると警告がなくなって接続できるようになった。

DockerでOpenVPNサーバを動かす

ホスト環境

$ cat /etc/redhat-release
CentOS Linux release 7.5.1804 (Core)

$ docker --version
Docker version 1.13.1, build 8633870/1.13.1
$ docker-compose --version
docker-compose version 1.18.0, build 8dd22a9

Dockerfile

公式のalpine3.9のイメージにopenvpnとeasyrsaをインストールするぐらい

FROM alpine:3.9

RUN apk --update --no-cache --no-progress add \
        openvpn \
        easy-rsa \
        && \
    rm -rf /var/cache/apk/*

COPY run.sh /
CMD [ "/run.sh" ]

サービス起動用のスクリプトrun.shを作成

下記のスクリプトrun.shとして作成する。
--push "route 192.168.1.0 255.255.255.0"OpenVPNサーバのネットワークに応じて変更する。

#!/bin/sh

# ERROR: Cannot open TUN/TAP dev /dev/net/tun: No such file or directory (errno=2)が出ないようにするため
mkdir -p /dev/net
if [ ! -c /dev/net/tun ]; then
    mknod /dev/net/tun c 10 200
fi

# クライアント用のネットワーク
OVPN_SERVER=${OVPN_SERVER:-10.8.0.0}

# `ip addr`コマンドの結果からネットワークデバイス名を抽出する
OVPN_NATDEVICE=$(ip addr | awk 'match($0, /global [[:alnum:]]+/) {print substr($0, RSTART+7, RLENGTH)}')
if [ -z "${OVPN_NATDEVICE}" ]; then
    ip addr
    echo "Failed to extract OVPN_NATDEVICE."
    exit 1
fi

# iptablesの設定
iptables -t nat -C POSTROUTING -s ${OVPN_SERVER}/24 -o ${OVPN_NATDEVICE} -j MASQUERADE || {
    iptables -t nat -A POSTROUTING -s ${OVPN_SERVER}/24 -o ${OVPN_NATDEVICE} -j MASQUERADE
}

# OpenVPNサーバの起動
/usr/sbin/openvpn \
    --cd ${OVPN_DIR:-/etc/openvpn} \
    \
    --port  ${OVPN_PORT:-1194} \
    --proto ${OVPN_PROTO:-udp4} \
    --dev   ${OVPN_DEV:-tun} \
    \
    --ca    ${OVPN_CA:-"/opt/easy-rsa/pki/ca.crt"} \
    --cert  ${OVPN_CERT:-"/opt/easy-rsa/pki/issued/server.crt"} \
    --key   ${OVPN_KEY:-"/opt/easy-rsa/pki/private/server.key"} \
    --dh    ${OVPN_DH:-"/opt/easy-rsa/pki/dh.pem"} \
    --tls-auth /opt/easy-rsa/pki/ta.key 0 \
    \
    --server ${OVPN_SERVER} ${OVPN_SERVER_MASK:-255.255.255.0} \
    --ifconfig-pool-persist ipp.txt \
    --push "redirect-gateway def1" \
    --push "route ${OVPN_SERVER} 255.255.0.0" \
    --push "route 192.168.1.0 255.255.255.0" \
    --push "dhcp-option DNS 8.8.8.8" \
    \
    --keepalive 10 120 \
    --user nobody \
    --group nobody \
    --persist-key \
    --persist-tun \
    \
    --status openvpn-status.log \
    --verb ${OVPN_VERB:-3} \
    \
    --compress lz4 \
    --tun-mtu 1500 \
    --mssfix 1460

docker-compose.ymlの作成

  • WANには1194番ポートはさらさずに54321番ポートでアクセスするようにする
    • WAN → ルータ54321 → Dockerホスト54321 → Dockerコンテナ1194
  • ホスト再起動時に自動起動するようにする(restart: unless-stopped
version: '3.2'
services:
  openvpn:
    build: .
    image: openvpn
    cap_add:
      - NET_ADMIN
    ports:
      - "54321:1194/udp"
    volumes:
      - ./easy-rsa:/opt/easy-rsa
    working_dir: /opt/easy-rsa
    environment:
      - OVPN_PORT=1194
    restart: unless-stopped

OpenVPNサーバの設定

$ docker-compose build
$ docker-compose up -d

でコンテナを起動した状態で、マウントしている/opt/easy-rsa内でeasyrsaで証明書とかを生成する。

コンテナ内に入り、/opt/easy-rsa内に入り作業する。

$ docker-compose exec openvpn sh

# cd /opt/easy-rsa

PKIの初期化

# /usr/share/easy-rsa/easyrsa init-pki

Using SSL: openssl OpenSSL 1.1.1a  20 Nov 2018

init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /opt/easy-rsa/pki

CA(認証局)構築

# /usr/share/easy-rsa/easyrsa build-ca nopass

Using SSL: openssl OpenSSL 1.1.1a  20 Nov 2018
Generating RSA private key, 2048 bit long modulus (2 primes)
...............+++++
.........................+++++
e is 65537 (0x010001)
Can't load /opt/easy-rsa/pki/.rnd into RNG
140591198460776:error:2406F079:random number generator:RAND_load_file:Cannot open file:crypto/rand/randfile.c:98:Filename=/opt/easy-rsa/pki/.rnd
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]: .

CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/opt/easy-rsa/pki/ca.crt

Diffie-Helllmanパラメータの生成

# /usr/share/easy-rsa/easyrsa gen-dh

Using SSL: openssl OpenSSL 1.1.1a  20 Nov 2018
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
.............+.......
.....................
..........+..........
+....................
.....................
.......+.......+.....
DH parameters of size 2048 created at /opt/easy-rsa/pki/dh.pem

サーバー鍵の生成

# /usr/share/easy-rsa/easyrsa build-server-full server nopass

Using SSL: openssl OpenSSL 1.1.1a  20 Nov 2018
Generating a RSA private key
...+++++
....+++++
writing new private key to '/opt/easy-rsa/pki/private/server.key.XXXXjcFHin'
-----
Using configuration from /usr/share/easy-rsa//safessl-easyrsa.cnf
Can't open /opt/easy-rsa/pki/index.txt.attr for reading, No such file or directory
140106217700200:error:02001002:system library:fopen:No such file or directory:crypto/bio/bss_file.c:72:fopen('/opt/easy-rsa/pki/index.txt.attr','r')
140106217700200:error:2006D080:BIO routines:BIO_new_file:no such file:crypto/bio/bss_file.c:79:
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'server'
Certificate is to be certified until Jan 29 14:12:50 2022 GMT (1080 days)

Write out database with 1 new entries
Data Base Updated

tls-auth用の鍵の生成

# openvpn --genkey --secret pki/ta.key

CRLファイルの生成

# /usr/share/easy-rsa/easyrsa gen-crl

Using SSL: openssl OpenSSL 1.1.1a  20 Nov 2018
Using configuration from /usr/share/easy-rsa//safessl-easyrsa.cnf

An updated CRL has been created.
CRL file: /opt/easy-rsa/pki/crl.pem

クライアント鍵・設定ファイルを生成

<CLIENT-NAME>の部分にクライアント名に入れて実行する。

$ /usr/share/easy-rsa/easyrsa build-client-full <CLIENT-NAME> nopass

Using SSL: openssl OpenSSL 1.1.1a  20 Nov 2018
Generating a RSA private key
.................................................................................................+++++
..............................................................................+++++
writing new private key to '/opt/easy-rsa/pki/private/<CLIENT-NAME>.key.XXXXeDaKmJ'
-----
Using configuration from /usr/share/easy-rsa//safessl-easyrsa.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'<CLIENT-NAME>'
Certificate is to be certified until Jan 29 14:20:40 2022 GMT (1080 days)

Write out database with 1 new entries
Data Base Updated

下記の内容で<CLIENT-NAME>.ovpnを作成する。
<SERVER-IP>にはOpenVPNサーバのグローバルIPかホスト名を入れる。

client
dev tun
proto udp
remote <SERVER-IP> 54321
resolv-retry infinite
nobind
persist-key
persist-tun
auth-nocache
verb 3
key-direction 1
compress lz4
tun-mtu 1500
mssfix 1460
<ca>
  pki/ca.crtの内容をコピペ
</ca>
<cert>
  pki/issued/<CLIENT-NAME>.crtの内容をコピペ
</cert>
<key>
  pki/private/<CLIENT-NAME>.keyの内容をコピペ
</key>
<tls-auth>
  pki/ta.keyの内容をコピペ
</tls-auth>

作成したovpnをクライアントにインポートすれば接続できた。

CentOS7にdocker-ce、docker-composeをインストールする

CentOSのデフォルトのDockerが1.13.1でFROM前のARGが使えなかったので、新しいのDockerを入れる。

$ sudo yum list docker
docker.x86_64    2:1.13.1-88.git07f3374.el7.centos    extras

ホスト環境

$ uname -sr
Linux 3.10.0-957.1.3.el7.x86_64

$ cat /etc/redhat-release
CentOS Linux release 7.6.1810 (Core)

Dockerの削除

yumでDockerを入れていた場合は削除する

$ sudo yum -y remove docker docker-common

Dockerのインストール

リポジトリを追加

$ sudo yum -y install yum-utils
$ sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

docker-ceをインストール

$ sudo yum -y install docker-ce

おそらくdockerグループが自動作成されているはずなので、ユーザをdockerグループに追加する

$ cat /etc/group | grep docker
dockerroot:x:983:
docker:x:979:

$ sudo gpasswd -a <USER> docker
$ id
uid=1000(<USER>) gid=1000(<USER>) groups=1000(<USER>),10(wheel),979(docker)

デーモンを起動

$ sudo systemctl start docker
$ sudo systemctl enable docker

ログインし直せば使える

$ docker --version
Docker version 18.09.1, build 4c52b90

docker-composeのインストール

リポジトリがなさそうだったので公式(Install Docker Compose | Docker Documentation)の通りに下記コマンドでインストールする。

$ sudo curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
$ sudo chmod a+x /usr/local/bin/docker-compose

$ docker-compose --version
docker-compose version 1.23.2, build 1110ad01

KerasがGPUを認識できなくなった

2018年12月時点ではGPUで動いていたコードが2019年1月になるとGPUを認識できずにCPUで動くようになっていた。
Ubuntu自体のアップデート、Pythonパッケージのアップデートをしていた気がするのでそれが原因か?
記事執筆時点(2019年1月21日)での各バージョンは下記の通り。

  • Ubuntu 18.04.1 LTS
  • Docker
    • docker-ce/bionic,now 18.06.1~ce~3-0~ubuntu amd64
    • nvidia-docker2/now 2.0.3+docker18.06.1-1 all
  • pip
    • Keras==2.0.4
    • tensorflow-gpu==1.12.0

学習を開始すると

failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected

が出て学習自体は動くが、GPUを使っていないため遅い。

GPUドライバの再インストール

最終的にはGPUドライバの再インストールはおそらく不要?

nvidia-396/now 396.54-0ubuntu0~gpu16.04.1 amd64

gpu16.04.1部分がUbuntuのバージョンを16.04からdist-upgradeしたときの残骸?のような感じで怪しいのでGPUドライバを再インストールしてみる。

削除後、一応再起動。

$ sudo apt remove nvidia-396
$ sudo apt autoremove

$ sudo reboot

アップデート後、最新版を確認してみる

$ sudo apt update
$ sudo apt search nvidia
nvidia-396/now 396.54-0ubuntu0~gpu16.04.1 amd64 [設定が残存]
  (none)

[設定が残存]になっているので

$ sudo apt purge nvidia-396
$ sudo reboot

完全に消えたのでppaを追加してインストールする。
nvidia-396はリポジトリにはなかったので、代わりにnvidia-390をインストールする。

$ sudo add-apt-repository ppa:graphics-drivers/ppa
$ sudo apt update
$ sudo apt install nvidia-390

CUDA_VISIBLE_DEVICESが原因

コードのはじめの方でGPUが一枚しかないのに

os.environ["CUDA_VISIBLE_DEVICES"] = "1"

としていたことが原因。

os.environ["CUDA_VISIBLE_DEVICES"] = "0"

やCUDA_VISIBLE_DEVICESを設定しなければ問題なくGPUで動いた。

Raspberry Piとウェブカメラでmotionを使う

motionをインストール

$ sudo apt-get -y install motion

motionの設定

stream_localhost on
webcontrol_localhost on

stream_localhost off
webcontrol_localhost off

に変更する。

動作確認

USBカメラの確認

$ lsusb 
Bus 001 Device 005: ID 046d:082c Logitech, Inc. 

起動する

$ sudo motion -n
[0:motion] [NTC] [ALL] conf_load: Processing thread 0 - config file /etc/motion/motion.conf
[0:motion] [NTC] [ALL] motion_startup: Motion 4.0 Started
[0:motion] [NTC] [ALL] create_path: creating directory /var/log/motion
[0:motion] [NTC] [ALL] motion_startup: Logging to file (/var/log/motion/motion.log)

Ctrl+Cで止めて、 /var/lib/motionに画像が保存るはずなのでsftp等で確認する。