Technology Engineering

178inaba の技術ブログ

【Raspberry Pi】バックアップ用のHDDをセットアップする。

inabaです。

GitLabのバックアップ用にとHDDを買っていました。
そのHDDのセットアップをします。

また、Swap領域も今までのHDDのファイルから新HDDのパーティションに変更します。

Swap領域の削除

今まで使っていたSwapファイル及びSwap起動サービスを削除します。

# Swap起動サービスの停止
$ sudo /etc/init.d/dphys-swapfile stop

# Swap起動サービスパッケージの削除
$ sudo apt-get purge dphys-swapfile 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following package was automatically installed and is no longer required:
  dc
Use 'apt-get autoremove' to remove it.
The following packages will be REMOVED:
  dphys-swapfile*
0 upgraded, 0 newly installed, 1 to remove and 5 not upgraded.
After this operation, 85.0 kB disk space will be freed.
Do you want to continue? [Y/n] Y
(Reading database ... 98423 files and directories currently installed.)
Removing dphys-swapfile (20100506-1) ...
Purging configuration files for dphys-swapfile (20100506-1) ...
Processing triggers for man-db (2.7.0.2-5) ...

# 不要になったと示されたdcパッケージの削除
$ sudo apt-get purge dc
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages will be REMOVED:
  dc*
0 upgraded, 0 newly installed, 1 to remove and 5 not upgraded.
After this operation, 111 kB disk space will be freed.
Do you want to continue? [Y/n] Y
(Reading database ... 98408 files and directories currently installed.)
Removing dc (1.06.95-9) ...
Purging configuration files for dc (1.06.95-9) ...
Processing triggers for install-info (5.2.0.dfsg.1-6) ...
Processing triggers for man-db (2.7.0.2-5) ...

# Swapファイルの削除
$ sudo rm -rf /var/swap 

フォーマット

フォーマットは以前Raspberry PiにHDDを追加した時とだいたい同じです。

# 対象ディスクの確認
$ sudo fdisk -l
# ...
Disk /dev/sdb: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

# フォーマット
$ sudo fdisk /dev/sdb

# Swap領域用のパーティション(16GiB)を切る。
Command (m for help): n
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): 

Using default response p.
Partition number (1-4, default 1): 
First sector (2048-1953525167, default 2048): 
Last sector, +sectors or +size{K,M,G,T,P} (2048-1953525167, default 1953525167): +16G # +16Gでサイズ指定(16GiB)のパーティションが切れる。

Created a new partition 1 of type 'Linux' and of size 16 GiB.

Command (m for help): p # パーティションができたことを確認。
Disk /dev/sdb: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
# ...

Device     Boot Start      End  Sectors Size Id Type
/dev/sdb1        2048 33556479 33554432  16G 83 Linux

# バックアップ用のパーティションを切る
Command (m for help): n
Partition type
   p   primary (1 primary, 0 extended, 3 free)
   e   extended (container for logical partitions)
Select (default p): 

Using default response p.
Partition number (2-4, default 2): 
First sector (33556480-1953525167, default 33556480): 
Last sector, +sectors or +size{K,M,G,T,P} (33556480-1953525167, default 1953525167): # デフォルトで最大のパーティションが作れるのでEnterを押すだけで良い。

Created a new partition 2 of type 'Linux' and of size 915.5 GiB.

Command (m for help): p # パーティションができたことを確認。
Disk /dev/sdb: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
# ...

Device     Boot    Start        End    Sectors   Size Id Type
/dev/sdb1           2048   33556479   33554432    16G 83 Linux
/dev/sdb2       33556480 1953525167 1919968688 915.5G 83 Linux

Command (m for help): t # Swap領域に使うパーティションのパーティションタイプIDを82(Linux swap)に設定。
Partition number (1,2, default 2): 1
Hex code (type L to list all codes): 82

Changed type of partition 'Linux' to 'Linux swap / Solaris'.

Command (m for help): p # パーティションタイプIDが変更された事を確認。
Disk /dev/sdb: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
# ...

Device     Boot    Start        End    Sectors   Size Id Type
/dev/sdb1           2048   33556479   33554432    16G 82 Linux swap / Solaris
/dev/sdb2       33556480 1953525167 1919968688 915.5G 83 Linux

Command (m for help): w # 保存して終了。

The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

Swap領域作成&Swap開始

# Swap領域作成
$ sudo mkswap -c /dev/sdb1 
0 bad pages
Setting up swapspace version 1, size = 16777212 KiB
no label, UUID=50945b0a-3c30-4de5-a95d-223bb0f6415a

# Swap開始
$ sudo swapon /dev/sdb1

# 再起動しても自動でSwap開始するように設定
$ sudo nano /etc/fstab
$ cat /etc/fstab 
# ...
/dev/sdb1       swap            swap    defaults          0       0

バックアップ領域をマウント

# バックアップ領域のファイルシステムをext4にする。
$ sudo mkfs.ext4 /dev/sdb2
mke2fs 1.42.12 (29-Aug-2014)
Creating filesystem with 239996086 4k blocks and 60006400 inodes
Filesystem UUID: 50945b0a-3c30-4de5-a95d-223bb0f6415a
Superblock backups stored on blocks: 
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 
    4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968, 
    102400000, 214990848

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

# 念のためディスクチェック
$ sudo e2fsck -f /dev/sdb2
e2fsck 1.42.12 (29-Aug-2014)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/sdb2: 11/60006400 files (0.0% non-contiguous), 3817299/239996086 blocks

# マウントポイントの作成
$ mkdir backups

# マウント
$ sudo mount -t ext4 -o defaults /dev/sdb2 /mnt/backups

# 確認
$ df -kh
Filesystem      Size  Used Avail Use% Mounted on
# ...
/dev/sdb2       902G   72M  856G   1% /mnt/backups

# 不要ファイル削除(後述)
$ sudo rm -rf  /mnt/backups/lost+found

# マウント永続化
$ sudo nano /etc/fstab 
$ cat /etc/fstab 
# ...
/dev/sdb2       /mnt/backups    ext4    defaults          0       0

マウントしたディスクにlost+foundというディレクトリがありますが、これはe2fsckコマンドでできたディレクトリのようです。
削除してもかまわないようです。

ja.stackoverflow.com

今日はここまで。

GitLab visibility設定とSign-up制限

inabaです。

引き続きGitLabの設定をします。

バージョン

バージョンは8.7.9です。

Raspbian Jessie向けのパッケージは多少古いようです。
これに関しては下記issueで議論されています。

gitlab.com

最新を入れる方法もあるようです。
自分はとりあえずそのままにしてあります。

設定

設定はWebからAdminでログインして行います。
設定画面は右上のレンチのアイコン -> 左のメニューの一番下のSettingsをクリックして行きます。

visibility設定

f:id:i178inaba:20161218171928p:plain

  • Default group visibilityはグループを作るときのデフォルトのvisibilityを設定します。

    • デフォルトでは設定されていないのでPrivateに設定します。
  • Restricted visibility levelsはユーザがプロジェクト等を作る時に設定できるvisibilityを制限します。

    • 自宅サーバでインターネットに公開しないので、念のためPrivateに制限しておきます。

Sign-up制限

Restricted visibility levelsと同様の理由で念のため制限しておきます。
Sign-upを制限すると新規ユーザを登録できなくなると思われるかもしれませんが、新規でユーザを追加するのはAdminでもできるので大丈夫です。

f:id:i178inaba:20161218171933p:plain

Sign-up enabledのチェックを外します。
これでログインページからSign-upフォームが消えます。

今日はここまで。

GitLabのメールを設定する

inabaです。

最近、GitLabをRaspberry Piにインストールしました。

inaba.hatenablog.com

メール来ない問題

GitLabに新しいユーザで登録するとメールが来るはずなのですが、来ません。

Postfixの設定めんどくさい説

Postfixの設定をサクッとすればいけるかなーと思っていろいろ調べたらGmailのアカウントとかパスワードとか必要そうでめんどくさそう。

d.hatena.ne.jp
d.hatena.ne.jp
kkv.hatenablog.com

調べた結果

  • Postfixがあるサーバまで正引きできるドメインが必要
  • 正引きできるドメインがない場合はGmailを経由する方法が使える
    • Gmailを経由する方法を仕様する場合はアカウントとパスワードを設定しないとならない。

という結果に。
Raspberry Pi自宅サーバなので固定IPではないし、PostfixGmailのアカウント書くなら下記の方法で行けるのでPostfixは諦めた。

GitLabのSMTP設定

GitLabにはPostfixを使う以外に、外部SMTPサーバを使う設定ができる。

gitlab.com

どうせパスワード設定するならこっちの設定をするほうがいい気がする。

・・・と思い、設定しようと思ったが、設定ファイルに平文でGmailのパスワード書くのは抵抗があるので、他のサービスを利用することにした。

Mailgun

www.mailgun.com

10000通/月まで無料なので良いと思います。
今回はこのSMTPサービスを使用します。
登録はそんなに難しくないので手順に従って登録していきます。

手順参考:
デベロッパーフレンドリーなAPIベースのメール配信システムMailgun | 三度の飯とエレクトロン

ドメイン

Mailgunを使うにはドメインが必要です。
多少お金はかかります(自分の場合、.comで1,382円/年)が、1個あるとこういう時に遊べるので買っておくと良いと思います。

設定

SMTP settingsのMailgunの項目を参考にGitLabにSMTPサーバの設定をします。

# 設定ファイルを編集
$ sudo nano /etc/gitlab/gitlab.rb

# GitLab再設定
$ sudo gitlab-ctl reconfigure

これでメールが来るようになります。

その他設定

external_url

メールは来るようになりますが、メールに書かれているURLがhttp://raspberrypiから始まっていて、このままではアクセスできません。

なので
external_url 'http://raspberrypi'

external_url 'http://raspberrypi.local'
に変えます。

メールに書かれているURLがhttp://raspberrypi.localで始まるようになり、アクセスができるようになります。

gitlab_email関連

送信元のメールアドレス等を設定します。
デフォルトでも支障はありませんが、せっかくなので自分のドメインのメールアドレス等に変えたほうが良いでしょう。
また、メールを受信したときに出る名前も変えられるので変えておきます。

gitlab_rails['gitlab_email_from'] = '<送信元アドレス>'
gitlab_rails['gitlab_email_display_name'] = 'GitLab From Raspberry Pi'
gitlab_rails['gitlab_email_reply_to'] = '<返信先アドレス>'

Postfixの削除

使わないのでPostfixは削除してしまって良いと思います。
設定等していないので、使うときはまたインストールすれば良いです。

# 設定ファイルも同時に削除できるpurgeで削除
$ sudo apt-get purge postfix 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages will be REMOVED:
  postfix*
0 upgraded, 0 newly installed, 1 to remove and 5 not upgraded.
After this operation, 3,095 kB disk space will be freed.
Do you want to continue? [Y/n] Y
(Reading database ... 98621 files and directories currently installed.)
Removing postfix (2.11.3-1) ...
Purging configuration files for postfix (2.11.3-1) ...
Processing triggers for man-db (2.7.0.2-5) ...
Processing triggers for libc-bin (2.19-18+deb8u6) ...

# もう一度削除しようとすると不要なパッケージが見られる。
$ sudo apt-get purge postfix 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Package 'postfix' is not installed, so not removed
The following package was automatically installed and is no longer required:
  ssl-cert
Use 'apt-get autoremove' to remove it.
0 upgraded, 0 newly installed, 0 to remove and 5 not upgraded.

# ssl-certも不要と出たので削除
$ sudo apt-get -y purge ssl-cert
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages will be REMOVED:
  ssl-cert*
0 upgraded, 0 newly installed, 1 to remove and 5 not upgraded.
After this operation, 104 kB disk space will be freed.
(Reading database ... 98432 files and directories currently installed.)
Removing ssl-cert (1.0.35) ...
Purging configuration files for ssl-cert (1.0.35) ...
Processing triggers for man-db (2.7.0.2-5) ...

# 不要なパッケージが無いかもう一度実行
$ sudo apt-get -y purge ssl-cert
Reading package lists... Done
Building dependency tree        
Reading state information... Done
Package 'ssl-cert' is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 5 not upgraded.

もう不要なパッケージはなさそうでした。

adminのメールアドレス設定

ついでに、adminのアドレスがadmin@example.comになっているので受信可能なメールアドレスに変更します。
Web画面からrootでログインして、左のメニューからProfile Settingsを選択してメールアドレスを変更します。

まとめ

これで登録時にメールが来てGitLabを使い始めることができます。

今日はここまで。

Raspberry Piでいろいろ。【その3 -> GitLabインストール】

inabaです。

前回

inaba.hatenablog.com

今日はGitLabをインストールしていきます。

やること

  • SSH接続 OK
  • 起動ドライブをHDDにする OK
  • 無線でつなぐ OK
  • Swap領域設定 OK
  • パスワード変更 OK
  • パッケージ更新 OK
  • GitLabインストール

GitLabインストール

基本的に下記を参考にインストールしていきます。

about.gitlab.com

1. Install and configure the necessary dependencies

必要なパッケージをインストールしていきます。

$ sudo apt-get install curl openssh-server ca-certificates postfix apt-transport-https
Reading package lists... Done
Building dependency tree       
Reading state information... Done
ca-certificates is already the newest version.
curl is already the newest version.
openssh-server is already the newest version.
openssh-server set to manually installed.
The following extra packages will be installed:
  libcurl3-gnutls ssl-cert
Suggested packages:
  procmail postfix-mysql postfix-pgsql postfix-ldap postfix-pcre sasl2-bin dovecot-common postfix-cdb mail-reader ufw postfix-doc openssl-blacklist
The following NEW packages will be installed:
  apt-transport-https libcurl3-gnutls postfix ssl-cert
0 upgraded, 4 newly installed, 0 to remove and 0 not upgraded.
Need to get 1,673 kB of archives.
After this operation, 3,845 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://mirrordirector.raspbian.org/raspbian/ jessie/main libcurl3-gnutls armhf 7.38.0-4+deb8u5 [225 kB]
Get:2 http://mirrordirector.raspbian.org/raspbian/ jessie/main apt-transport-https armhf 1.0.9.8.3 [134 kB]
Get:3 http://mirrordirector.raspbian.org/raspbian/ jessie/main ssl-cert all 1.0.35 [20.9 kB]
Get:4 http://mirrordirector.raspbian.org/raspbian/ jessie/main postfix armhf 2.11.3-1 [1,293 kB]                                                                                 
Fetched 1,673 kB in 9s (185 kB/s)                                                                                                                                                
Preconfiguring packages ...
Selecting previously unselected package libcurl3-gnutls:armhf.
(Reading database ... 31272 files and directories currently installed.)
Preparing to unpack .../libcurl3-gnutls_7.38.0-4+deb8u5_armhf.deb ...
Unpacking libcurl3-gnutls:armhf (7.38.0-4+deb8u5) ...
Selecting previously unselected package apt-transport-https.
Preparing to unpack .../apt-transport-https_1.0.9.8.3_armhf.deb ...
Unpacking apt-transport-https (1.0.9.8.3) ...
Selecting previously unselected package ssl-cert.
Preparing to unpack .../ssl-cert_1.0.35_all.deb ...
Unpacking ssl-cert (1.0.35) ...
Selecting previously unselected package postfix.
Preparing to unpack .../postfix_2.11.3-1_armhf.deb ...
Unpacking postfix (2.11.3-1) ...
Processing triggers for man-db (2.7.0.2-5) ...
Processing triggers for systemd (215-17+deb8u5) ...
Setting up libcurl3-gnutls:armhf (7.38.0-4+deb8u5) ...
Setting up apt-transport-https (1.0.9.8.3) ...
Setting up ssl-cert (1.0.35) ...
Setting up postfix (2.11.3-1) ...
Adding group `postfix' (GID 115) ...
Done.
Adding system user `postfix' (UID 109) ...
Adding new user `postfix' (UID 109) with group `postfix' ...
Not creating home directory `/var/spool/postfix'.
Creating /etc/postfix/dynamicmaps.cf
Adding tcp map entry to /etc/postfix/dynamicmaps.cf
Adding sqlite map entry to /etc/postfix/dynamicmaps.cf
Adding group `postdrop' (GID 116) ...
Done.
setting myhostname: raspberrypi
setting alias maps
setting alias database
changing /etc/mailname to gitlab.raspberrypi.local
setting myorigin
setting destinations: gitlab.raspberrypi.local, raspberrypi, localhost.localdomain, localhost
setting relayhost: 
setting mynetworks: 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
setting mailbox_size_limit: 0
setting recipient_delimiter: +
setting inet_interfaces: all
/etc/aliases does not exist, creating it.
WARNING: /etc/aliases exists, but does not have a root alias.

Postfix is now set up with a default configuration.  If you need to make 
changes, edit
/etc/postfix/main.cf (and others) as needed.  To view Postfix configuration
values, see postconf(1).

After modifying main.cf, be sure to run '/etc/init.d/postfix reload'.

Running newaliases
Processing triggers for libc-bin (2.19-18+deb8u6) ...
Processing triggers for systemd (215-17+deb8u5) ...

途中、Postfix設定のため、こんな画面が出てきます。

f:id:i178inaba:20161214004424p:plain

ここは下記を参考にSMTPを使用するInternet Siteを選択。

docs.gitlab.com

f:id:i178inaba:20161214004429p:plain

上記はドメイン名を設定する画面です。
適当にgitlab.raspberrypi.localと設定しました。
間違っても後で変えられると思います。

$ curl https://packages.gitlab.com/gpg.key | sudo apt-key add -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1703  100  1703    0     0   1850      0 --:--:-- --:--:-- --:--:--  1849
OK

2. Add the GitLab package server and install the package

GitLabのパッケージサーバを追加してGitLabをインストールします。

$ sudo curl -sS https://packages.gitlab.com/install/repositories/gitlab/raspberry-pi2/script.deb.sh | sudo bash
Detected operating system as raspbian/jessie.
Checking for curl...
Detected curl...
Running apt-get update... done.
Installing apt-transport-https... done.
Installing /etc/apt/sources.list.d/gitlab_raspberry-pi2.list...done.
Importing packagecloud gpg key... done.
Running apt-get update... done.

The repository is setup! You can now install packages.

$ sudo apt-get install gitlab-ce
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following NEW packages will be installed:
  gitlab-ce
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 263 MB of archives.
After this operation, 724 MB of additional disk space will be used.
Get:1 https://packages.gitlab.com/gitlab/raspberry-pi2/raspbian/ jessie/main gitlab-ce armhf 8.7.9+20160704103025-ce.1 [263 MB]
Fetched 263 MB in 2min 39s (1,653 kB/s)                                                                                                                                          
Selecting previously unselected package gitlab-ce.
(Reading database ... 31486 files and directories currently installed.)
Preparing to unpack .../gitlab-ce_8.7.9+20160704103025-ce.1_armhf.deb ...
Unpacking gitlab-ce (8.7.9+20160704103025-ce.1) ...
Setting up gitlab-ce (8.7.9+20160704103025-ce.1) ...
gitlab: Thank you for installing GitLab!
gitlab: To configure and start GitLab, RUN THE FOLLOWING COMMAND:

sudo gitlab-ctl reconfigure

gitlab: GitLab should be reachable at http://raspberrypi
gitlab: Otherwise configure GitLab for your system by editing /etc/gitlab/gitlab.rb file
gitlab: And running reconfigure again.
gitlab: 
gitlab: For a comprehensive list of configuration options please see the Omnibus GitLab readme
gitlab: https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md
gitlab: 
It looks like GitLab has not been configured yet; skipping the upgrade script.

3. Configure and start GitLab

GitLabのconfigureをします。

$ sudo gitlab-ctl reconfigure
# 長いので出力は割愛。

下記にアクセスするとGitLabの画面が出ます。

http://raspberrypi.local/

下記画面でrootのパスワードを設定します。

f:id:i178inaba:20161214012746p:plain f:id:i178inaba:20161214013437p:plain

  • Username: root
  • Password: 先程設定したパスワード

でログイン。

f:id:i178inaba:20161214013325p:plain

ログインできました!

細かい設定等はあるかもしれませんがとりあえずGitLabのインストールという目標は達成しました。
今後はバックアップ設定とかしたいですね。
お疲れ様でした。

Raspberry Piでいろいろ。【その2 -> Swap領域設定、パスワード変更、パッケージ更新】

inabaです。
昨日に引き続き、Raspberry Piの設定をしていきます。

やること

  • SSH接続 OK
  • 起動ドライブをHDDにする OK
  • 無線でつなぐ OK
  • Swap領域設定 New
  • パスワード変更
  • パッケージ更新
  • GitLabインストール

Swap領域設定

GitLabのRaspberry Piへのインストールについてのページに

We recommend adding at least 1GB of swap

とあります。
「1GBはスワップ領域作ったほうがいいよ。」という感じでしょうか。

about.gitlab.com

また、Requirementsには

1GB RAM + 3GB of swap is the absolute minimum but we strongly advise against this amount of memory. See the unicorn worker section below for more advice.

とあります。
「メモリが1GBなら3GBはスワップ領域あったほうがいいよ。」という感じでしょうか。

docs.gitlab.com

昨日起動ディスクにしたHDDは1TBあるので容量の心配はありません。
なので、どーんと16GB割り当ててみることにします。

Swap領域の割り当てにはパーティションを割り当てる方法とファイルを割り当てる方法があるが、調べたところパフォーマンスに差はなく、ディスクフォーマットをしなくてよいのでファイルを使うことにする。
ちなみにRaspberry PiはもともとファイルのSwap領域がある。

$ swapon -s
Filename                Type        Size    Used    Priority
/var/swap                               file        102396  0   -1

単位はkBだそうなので、だいたい100MBくらいだろうか。

それでは実際に設定していく。

# Swap領域管理サービスを停止。
$ service dphys-swapfile stop

# Swap領域設定ファイルを編集。
$ sudo nano /etc/dphys-swapfile
$ cat /etc/dphys-swapfile
...
CONF_SWAPSIZE=16384
...
# ↑元々は「CONF_SWAPSIZE=1024」

# Swap領域管理サービスを開始。
# (ちょい時間かかる。)
$ sudo service dphys-swapfile start

# 確認
$ swapon -s
Filename                Type        Size    Used    Priority
/var/swap                               file        2097148 0   -1

あれ?
2097148kbという事だから2GBくらいにしかなってない。

調べた。

a244.hateblo.jp

CONF_MAXSWAP=2048という行のコメントアウト外して、倍の4096にすると良いらしい。

上の行のコメントは

restrict size (computed and absolute!) to maximally this limit
can be set to empty for no limit, but beware of filled partitions!
this is/was a (outdated?) 32bit kernel limit (in MBytes), do not overrun it
but is also sensible on 64bit to prevent filling /var or even / partition

Google翻訳にかけると

最大限にこの制限にサイズ(計算されたと絶対!)を制限する
   制限なしで空にすることができますが、塗りつぶされたパーティションには注意してください!
   これは(古い?)32ビットカーネルの制限(MBytes)であり、それをオーバーランさせない
   しかし、/varやeven / partitionの埋め込みを防ぐために64ビットでも有効です

重要そうなのは

制限なしで空にすることができますが(can be set to empty for no limit)

ということはCONF_MAXSWAP=というように空を設定すれば制限無しにできるのかな?

再度設定

# Swap領域管理サービスを停止。
$ service dphys-swapfile stop

# Swap領域設定ファイルを編集。
$ cat /etc/dphys-swapfile
...
#CONF_MAXSWAP=2048
...
$ sudo nano /etc/dphys-swapfile
$ cat /etc/dphys-swapfile
...
CONF_MAXSWAP=
...

# Swap領域管理サービスを開始。
# (まぁまぁ時間かかる。)
$ sudo service dphys-swapfile start
Job for dphys-swapfile.service failed. See 'systemctl status dphys-swapfile.service' and 'journalctl -xn' for details.
# 失敗したようだ。

$ systemctl status dphys-swapfile.service
● dphys-swapfile.service - LSB: Autogenerate and use a swap file
   Loaded: loaded (/etc/init.d/dphys-swapfile)
   Active: failed (Result: timeout) since Mon 2016-12-12 16:49:03 UTC; 1min 20s ago # timeoutと出ている。
  Process: 15078 ExecStop=/etc/init.d/dphys-swapfile stop (code=exited, status=0/SUCCESS)
  Process: 15135 ExecStart=/etc/init.d/dphys-swapfile start (code=killed, signal=TERM)

試しにCONF_SWAPSIZEを1024に戻して開始してみる。

# 念のため停止コマンドを実行
$ sudo service dphys-swapfile stop
$ cat /etc/dphys-swapfile 
...
CONF_SWAPSIZE=16384
...
$ sudo nano /etc/dphys-swapfile
$ cat /etc/dphys-swapfile
...
CONF_SWAPSIZE=1024
...
$ sudo service dphys-swapfile start
$

成功した。

今度はCONF_SWAPSIZEとCONF_MAXSWAP両方に16384を設定してみる。

$ sudo service dphys-swapfile stop
$ cat /etc/dphys-swapfile 
...
CONF_SWAPSIZE=1024
...
CONF_MAXSWAP=
...
$ sudo nano /etc/dphys-swapfile
$ cat /etc/dphys-swapfile
...
CONF_SWAPSIZE=16384
...
CONF_MAXSWAP=16384
...
$ sudo service dphys-swapfile start
Job for dphys-swapfile.service failed. See 'systemctl status dphys-swapfile.service' and 'journalctl -xn' for details.
# 失敗した。

$ systemctl status dphys-swapfile.service
● dphys-swapfile.service - LSB: Autogenerate and use a swap file
   Loaded: loaded (/etc/init.d/dphys-swapfile)
   Active: failed (Result: timeout) since Mon 2016-12-12 17:07:04 UTC; 36s ago # 同じくtimeout
  Process: 15307 ExecStop=/etc/init.d/dphys-swapfile stop (code=exited, status=0/SUCCESS)
  Process: 15403 ExecStart=/etc/init.d/dphys-swapfile start (code=killed, signal=TERM)

では、8GBにする。

$ sudo service dphys-swapfile stop
$ cat /etc/dphys-swapfile 
...
CONF_SWAPSIZE=16384
...
CONF_MAXSWAP=16384
...
$ sudo nano /etc/dphys-swapfile 
$ cat /etc/dphys-swapfile 
...
CONF_SWAPSIZE=8192
...
CONF_MAXSWAP=
...
$ sudo service dphys-swapfile start
$

成功した。

結局スワップ領域は8GBに。

パスワード変更

デフォルトユーザpiでログインすると下記のメッセージが表示される。

SSH is enabled and the default password for the 'pi' user has not been changed.
This is a security risk - please login as the 'pi' user and type 'passwd' to set a new password.

ようは「パスワードがデフォルトだとセキュリティリスクがありますよ。」という話らしい。
なので変更する。

$ passwd
Changing password for pi.
(current) UNIX password:  # 現在のパスワード
Enter new UNIX password:  # 新しいパスワード
Retype new UNIX password: # 新しいパスワード確認
passwd: password updated successfully

念のため別コンソールでログインして反映されたか確認するとよい。

パッケージ更新

全てのパッケージを最新にする。

$ sudo apt-get clean && sudo apt-get update && sudo apt-get -y upgrade && sudo apt-get clean
Get:1 http://archive.raspberrypi.org jessie InRelease [13.2 kB]                     
Get:2 http://mirrordirector.raspbian.org jessie InRelease [14.9 kB]                 
Get:3 http://archive.raspberrypi.org jessie/main armhf Packages [128 kB]
Get:4 http://mirrordirector.raspbian.org jessie/main armhf Packages [8,981 kB]
Get:5 http://archive.raspberrypi.org jessie/ui armhf Packages [53.6 kB]        
Ign http://archive.raspberrypi.org jessie/main Translation-en_GB                                                                                                                 
Ign http://archive.raspberrypi.org jessie/main Translation-en                                                                                                                    
Ign http://archive.raspberrypi.org jessie/ui Translation-en_GB                                                                                                                   
Ign http://archive.raspberrypi.org jessie/ui Translation-en                                                                                                                      
Get:6 http://mirrordirector.raspbian.org jessie/contrib armhf Packages [37.5 kB]                                                                                                 
Get:7 http://mirrordirector.raspbian.org jessie/non-free armhf Packages [70.3 kB]                                                                                                
Get:8 http://mirrordirector.raspbian.org jessie/rpi armhf Packages [1,356 B]                                                                                                     
Ign http://mirrordirector.raspbian.org jessie/contrib Translation-en_GB                                                                                                          
Ign http://mirrordirector.raspbian.org jessie/contrib Translation-en
Ign http://mirrordirector.raspbian.org jessie/main Translation-en_GB
Ign http://mirrordirector.raspbian.org jessie/main Translation-en
Ign http://mirrordirector.raspbian.org jessie/non-free Translation-en_GB
Ign http://mirrordirector.raspbian.org jessie/non-free Translation-en
Ign http://mirrordirector.raspbian.org jessie/rpi Translation-en_GB
Ign http://mirrordirector.raspbian.org jessie/rpi Translation-en
Fetched 9,300 kB in 3min 18s (46.8 kB/s)
Reading package lists... Done
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
  libdrm2 libicu52 raspberrypi-sys-mods raspi-config
4 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 6,615 kB of archives.
After this operation, 60.4 kB of additional disk space will be used.
Get:1 http://archive.raspberrypi.org/debian/ jessie/main libdrm2 armhf 2.4.71-1+rpi1 [32.4 kB]
Get:2 http://mirrordirector.raspbian.org/raspbian/ jessie/main libicu52 armhf 52.1-8+deb8u4 [6,556 kB]
Get:3 http://archive.raspberrypi.org/debian/ jessie/main raspberrypi-sys-mods all 20161208+1 [8,412 B]
Get:4 http://archive.raspberrypi.org/debian/ jessie/main raspi-config all 20161207 [17.7 kB]
Fetched 6,615 kB in 5s (1,267 kB/s)                                   
Reading changelogs... Done
(Reading database ... 31272 files and directories currently installed.)
Preparing to unpack .../libdrm2_2.4.71-1+rpi1_armhf.deb ...
Unpacking libdrm2:armhf (2.4.71-1+rpi1) over (2.4.65-3~bpo8+1) ...
Preparing to unpack .../libicu52_52.1-8+deb8u4_armhf.deb ...
Unpacking libicu52:armhf (52.1-8+deb8u4) over (52.1-8+deb8u3) ...
Preparing to unpack .../raspberrypi-sys-mods_20161208+1_all.deb ...
Unpacking raspberrypi-sys-mods (20161208+1) over (20161124) ...
Preparing to unpack .../raspi-config_20161207_all.deb ...
Unpacking raspi-config (20161207) over (20161114) ...
Processing triggers for systemd (215-17+deb8u5) ...
Setting up libdrm2:armhf (2.4.71-1+rpi1) ...
Setting up libicu52:armhf (52.1-8+deb8u4) ...
Setting up raspberrypi-sys-mods (20161208+1) ...
Installing new version of config file /etc/profile.d/sshpasswd.sh ...
Setting up raspi-config (20161207) ...
Processing triggers for libc-bin (2.19-18+deb8u6) ...

こんな感じかな。

今日はここまで。

Raspberry Piでいろいろ。【その1 -> SSH接続、起動ドライブHDD化、無線LAN設定】

ご無沙汰しております。
inabaです。

Raspberry Pi 3を夏頃に入手してLチカさせてほったらかしにしていました。
もったいないのでRaspberry PiでGitLabサーバでも作りたいと思います。

備忘録としてブログにも記しておこうとおもいます。

やること

  • SSH接続
  • 起動ドライブをHDDにする
  • パスワード変える
  • 無線でつなぐ
  • パッケージ更新
  • GitLabインストール

ssh接続

推奨OSのraspbianは最初からsshdが立ち上がっているという話だったが、自分がインストールしたRASPBIAN JESSIE LITEでは立ち上がっていなかったのでsshdを立ち上げ。
これができないとRaspberry Piにキーボードを繋いで操作しなければならないので一番最初にやる。

  1. sudo raspi-configを実行。
  2. 5 Interfacing Optionsを選択。
  3. P2 SSHを選択。
  4. Yesを選択。
  5. Okを選択。
  6. Finishを選択。

追記(2017/04/03)
raspi-configが更新され、SSHの設定が7 Advanced Optionsから5 Interfacing Optionsに変更されました。

この後、同じネットワークにあるPCからssh pi@raspberrypi.localと打てば入れる。
再起動しても設定は生きているので大丈夫。
自分は面倒なのでsshの設定だけしたら、Raspberry Piのキーボードは外してmacから全部操作することにした。

起動ドライブをHDDに変更

初期状態から変更が少ない状態のままHDDに移行するほうが良いと思うので早めにやる。

理由としては、標準ではSDカードが起動ドライブになるのだが、SDカードは書き換えに弱く、壊れやすいと聞いたため。
ブートローダーはSDカードから変えられないそうなので、SD自体は必須となるのだが、書き込み回数自体は減るだろうと思う。

# ディスク名確認。
$ sudo fdisk -l
Disk /dev/sda: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors

# 買ったばかりでパーティションが無いので作る。
$ sudo fdisk /dev/sda # 対話式コマンド。
Command (m for help): m # コマンド一覧を見る。

Help:

  DOS (MBR)
   a   toggle a bootable flag
   b   edit nested BSD disklabel
   c   toggle the dos compatibility flag

  Generic
   d   delete a partition
   l   list known partition types
   n   add a new partition
   p   print the partition table
   t   change a partition type
   v   verify the partition table

  Misc
   m   print this menu
   u   change display/entry units
   x   extra functionality (experts only)

  Save & Exit
   w   write table to disk and exit
   q   quit without saving changes

  Create a new label
   g   create a new empty GPT partition table
   G   create a new empty SGI (IRIX) partition table
   o   create a new empty DOS partition table
   s   create a new empty Sun partition table

Command (m for help): n # 新しくパーティションを作る。
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): # プライマリパーティションなのでデフォルトのままエンター。
Partition number (1-4, default 1): # パーティションは1つだけ作るのでデフォルトのままエンター。
First sector (2048-1953525167, default 2048): # 最大サイズで作るのでデフォルトのままエンター。
Last sector, +sectors or +size{K,M,G,T,P} (2048-1953525167, default 1953525167): # 同じくデフォルトのままエンター。

Created a new partition 1 of type 'Linux' and of size 931.5 GiB. # パーティションが作られた。

Command (m for help): p # パーティションができたことを確認。

Disk /dev/sda: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
# ...

Device     Boot Start        End    Sectors   Size Id Type
/dev/sda1        2048 1953525167 1953523120 931.5G 83 Linux # パーティション。

Command (m for help): w # ディスクに書き込み。
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

# OSの非同期書き込みを考慮してSync
$ sync

# パーティションのファイルシステムをext4にする。
$ sudo mkfs.ext4 /dev/sda1
mke2fs 1.42.12 (29-Aug-2014)
/dev/sda1 contains a ext4 file system
    last mounted on Sun Dec 11 11:49:33 2016
Proceed anyway? (y,n) y # すでに作成されていると、実行するか確認されるのでy。
Creating filesystem with 244190390 4k blocks and 61054976 inodes
Filesystem UUID: 50945b0a-3c30-4de5-a95d-223bb0f6415a
Superblock backups stored on blocks: 
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 
    4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968, 
    102400000, 214990848

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done     

# SDカードの起動ドライブのデータをHDDにコピー。
$ sudo dd if=/dev/mmcblk0p2 of=/dev/sda1 bs=32M conv=noerror,sync
939+1 records in
940+0 records out
31541166080 bytes (32 GB) copied, 1740.37 s, 18.1 MB/s

# ディスクをチェック。
$ sudo e2fsck -f /dev/sda1
e2fsck 1.42.12 (29-Aug-2014)
/dev/sda1: recovering journal
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
Free blocks count wrong (7376566, counted=7351276). # ブロック数に差異が出ている。
Fix<y>? yes 修正するかと聞かれたのでy。
Free inodes count wrong (1859519, counted=1859633).
Fix<y>? yes # 同じくy。

/dev/sda1: ***** FILE SYSTEM WAS MODIFIED *****
/dev/sda1: 35407/1895040 files (0.2% non-contiguous), 342292/7693568 blocks

# SDをコピーしたためSDのサイズになっているらしい。パーティションを最大化するためリサイズ。
$ sudo resize2fs /dev/sda1
resize2fs 1.42.12 (29-Aug-2014)
Resizing the filesystem on /dev/sda1 to 244190390 (4k) blocks.
The filesystem on /dev/sda1 is now 244190390 (4k) blocks long.

# fstabを書き換えるためマウント。
$ sudo mount -t ext4 -o defaults /dev/sda1 /mnt

# fstabの/dev/mmcblk0p2を/dev/sda1へ書き換え。
$ cat fstab 
proc            /proc           proc    defaults          0       0
/dev/mmcblk0p1  /boot           vfat    defaults          0       2
/dev/mmcblk0p2  /               ext4    defaults,noatime  0       1 # 変更前。
# a swapfile is not a swap partition, no line here
#   use  dphys-swapfile swap[on|off]  for that
$ sudo nano /mnt/etc/fstab # nanoで書き換え。
$ cat fstab 
proc            /proc           proc    defaults          0       0
/dev/mmcblk0p1  /boot           vfat    defaults          0       2
/dev/sda1       /               ext4    defaults,noatime  0       1 # 変更後。
# a swapfile is not a swap partition, no line here
#   use  dphys-swapfile swap[on|off]  for that

# ブートローダーの起動ドライブの設定を書き換え
# root=/dev/mmcblk0p2 -> root=/dev/sda1
$ cat /boot/cmdline.txt
dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait
$ sudo nano /boot/cmdline.txt
$ cat /boot/cmdline.txt
dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=/dev/sda1 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait

# 再起動
$ sudo reboot

# 再起動後
$ df -kh
Filesystem      Size  Used Avail Use% Mounted on
/dev/root       918G  839M  879G   1% /

これでHDDを使うようになった。
ファイルシステムをCentOS7で使われているxfsにしようかとも思ったが、説明を読むと、メモリを大量に使うような仕様になっているようだったのでいつものext4にした。

Linux HDDフォーマット 参考サイト
Linux CentOS 外付けHDDのフォーマットとマウント

ファイルシステム 参考サイト
qiita.com

Raspberry Pi HDD起動 参考サイト
jyn.jp

無線で繋ぐ

$ sudo sh -c 'wpa_passphrase (SSID) (PASSPHRASE) >> /etc/wpa_supplicant/wpa_supplicant.conf'

上記を実行。
(SSID) (PASSPHRASE)は自分のSSIDとパスに変更して実行してください。

仮に

$ sudo sh -c 'wpa_passphrase foo bar >> /etc/wpa_supplicant/wpa_supplicant.conf'

を実行した場合の/etc/wpa_supplicant/wpa_supplicant.confが下記。

country=GB
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
    ssid="foo"
    #psk="bar"
    psk=baz
}

パスフレーズが平文でコメントアウトされているので、セキュリティ的に気になるのであれば削除しておいたほうがいい。
自分はテキストエディタnanoで削除した。

$ sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

無線接続が遅いと感じたときの対処方法もあるようだったが、現状不満が無いので設定しなかった。
今後、不満があれば設定する。
Raspberry Piで無線LANの反応が悪い時の対処法 | ものづくりエクスペリメント

今日はここまで〜。

【Go】kingpinをinit()でパースしていたらテストでエラーが出た話 #golang

kingpin

標準のflagパッケージでは、同時に長いオプションと短いオプション(shortオプション)を定義するのが面倒。

package main

import (
    "flag"
    "fmt"
)

var (
    dryRun = flag.Bool("dry-run", false, "dry run mode.")
)

func init() {
    flag.BoolVar(dryRun, "n", false, "dry run mode.")
    flag.Parse()
}

func main() {
    fmt.Printf("dry run mode: %v\n", *dryRun)
}

説明も二重に出てる。

$ go build -o flag
$ ./flag --help
Usage of ./flag:
  -dry-run
        dry run mode.
  -n    dry run mode.

※説明に関してはパッケージ変数Usageを上書きすることで変えられる。

上記のような理由でshortオプションの定義がいい感じのパッケージ無いかな〜と探してたらkingpinを見つけた!
kingpinだといい感じにshortオプションを宣言できる!!

package main

import (
    "fmt"

    "gopkg.in/alecthomas/kingpin.v2"
)

var (
    dryRun = kingpin.Flag("dry-run", "dry run mode.").Short('n').Bool()
)

func init() {
    kingpin.Parse()
}

func main() {
    fmt.Printf("dry run mode: %v\n", *dryRun)
}

Short('n')だけでshortオプションを定義できる。

説明もデフォルトでいい感じ。

$ go run main.go --help
usage: main [<flags>]

Flags:
      --help     Show context-sensitive help (also try --help-long and --help-man).
  -n, --dry-run  dry run mode.

exit status 1

error in test

便利に使っていたkingpinだけど、テスト時に問題が。。。
フラグを指定していなければ何も問題ない。

$ go test
PASS
ok      gist/kingpin    0.008s

が、フラグを指定するとエラーが。。。

$ go test -v
kingpin.test: error: unknown short flag '-t', try --help
exit status 1
FAIL    gist/kingpin    0.008s

何が起きているのだろうか

-tの正体を突き止めるために引数を表示するログを入れてみた。

func init() {
    fmt.Println(os.Args)
    kingpin.Parse()
}

結果

$ go test -v
[/tmp/kingpin.test -test.v=true]
kingpin.test: error: unknown short flag '-t', try --help
exit status 1
FAIL    gist/kingpin    0.008s

-test.v=true←これが原因らしい。

標準のflagパッケージではどうか?

func init() {
    flag.BoolVar(dryRun, "n", false, "dry run mode.")

    fmt.Println(os.Args)

    flag.Parse()
}

結果

$ go test -v
[/tmp/flag.test -test.v=true]
=== RUN   TestRun
--- PASS: TestRun (0.00s)
PASS
ok      gist/flag   0.006s

大丈夫っぽい。
ソースを追ったら、flagパッケージのパッケージ変数CommandLinego testコマンドとテストバイナリで共有しているから大丈夫だったみたい。
(go testでテストバイナリ作る時に、go test用のオプションも含めてバイナリを作っているっぽい。)
確認のため、別なFlagSetを定義してそちらを使ってみる。

package main

import (
    "flag"
    "fmt"
    "os"
)

var (
    tflg   = flag.NewFlagSet("test_flag", flag.ExitOnError)
    dryRun = tflg.Bool("dry-run", false, "dry run mode.")
)

func init() {
    tflg.BoolVar(dryRun, "n", false, "dry run mode.")

    fmt.Println(os.Args)

    tflg.Parse(os.Args[1:])
}

func main() {
    fmt.Printf("dry run mode: %v\n", *dryRun)

    result := run(*dryRun)
    fmt.Printf("result: %v\n", result)
}

func run(dryRun bool) bool {
    if dryRun {
        return false
    }

    return true
}

FlagSetNewFlagSet()で定義できる。
Parse()だけ通常と違い、引数を渡してやる必要がある。

結果

$ go test -v
[/tmp/flag.test -test.v=true]
flag provided but not defined: -test.v
Usage of test_flag:
  -dry-run
        dry run mode.
  -n    dry run mode.
exit status 2
FAIL    gist/flag   0.006s

やはり失敗した。

まとめ

  • kingpin特有のエラーではなく、flagパッケージでも出る。
  • エラーを出さないためにはmain()でパースする必要がある。

基本的な事だけど、init()はテスト時に呼ばれて、main()はテスト時に呼ばれないって事だよね。