a tomato

トマトが大好きです

ansibleを使うためのssh周りの設定

ansibleを使う時に必要なsshの設定です。

SSH用の公開/秘密鍵生成

兎にも角にもまずは、鍵認証によるログインが必要ですので、 公開鍵と秘密鍵を作成します。

% ssh-keygen -t rsa -b 4096                        
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/kzdev/.ssh/id_rsa): /Users/kzdev/.ssh/iscdhcp/id_rsa
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/kzdev/.ssh/iscdhcp/id_rsa.
Your public key has been saved in /Users/kzdev/.ssh/iscdhcp/id_rsa.pub.
The key fingerprint is:
SHA256:mQUfAGwyCJ68bFD9gQvkozUTZNiPZyhiTknP5+Wgr4s kzdev@MacBook-Pro
The key's randomart image is:
+---[RSA 4096]----+
|.**o o..o..      |
|+==.= +  o .     |
|o+X= * .  o      |
|=*+*=o.. +       |
|*= o+ + S        |
|.. . . .         |
|    .            |
|  .  .           |
| E oo            |
+----[SHA256]-----+
公開鍵を構築対象サーバに登録

作成した公開鍵を構築対象となるサーバに登録します。

% ssh-copy-id -i  /Users/kzdev/.ssh/iscdhcp/id_rsa.pub  root@10.211.55.6          
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/kzdev/.ssh/iscdhcp/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@10.211.55.6's password: 

Number of key(s) added:        1

Now try logging into the machine, with:   "ssh 'root@10.211.55.6'"
and check to make sure that only the key(s) you wanted were added.
SSH接続確認

パスワード入力無しでSSH接続が可能となることを確認します。

% ssh -i /Users/kzdev/.ssh/iscdhcp/id_rsa root@10.211.55.6            
Last login: Sat Aug  4 01:34:38 2018 from 10.211.55.2
[root@localhost ~]# 
構築対象側のSSH設定

これで最低限の準備は整いましたが、基本は鍵認証でログインするのでパスワード認証をOFFにします。セキュリティ観点においても、パスワード認証は様々な脆弱性に晒されるので、やはりオフにしておいた方が良いと思います。

[root@localhost ~]# sed -i -e 's/^PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
[root@localhost ~]# sed -i -e 's/^ChallengeResponseAuthentication yes/ChallengeResponseAuthentication no/' /etc/ssh/sshd_config

iptablesでアクティブモードFTPが通るように設定する

ftpクライアント側でiptablesを利用するケースが発生し、ftp通信を許可する設定(tcp:20, tcp:21)をしたところ、ls等のデータコネクションで通信を行うコマンドがエラーになってしまいました。

ftp 192.168.10.1
Connected to 192.168.10.1 (192.168.10.1).
220 (vsFTPd 2.2.2)
Name (192.168.10.1:kzdev): xxxxx
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls
425 Failed to establish connection.

これは、クライアント側からデータコネクションを確立にいくため、ランダムポート(1024〜65535)から動的に選択されてしまいます。そのため、tcp:20, tcp:21を開いてもランダムポートでの通信が通らないのです。

これだと、通信を行うには、iptablesを無効にしてしまうか、ランダムポートを全て許可しなければならず、ファイアウォールの意味をなさなくなってしまいます。 こんな時に使えるのが、ip_conntrack_ftpです。

このモジュールは、制御ポートを通してクライアントから通知されるデータコネクションやパッシブモードで利用するポート番号を自動的に開閉してくれる便利なモジュールです。

まずは、モジュールが存在しているか確認を行います。

$ lsmod | grep ftp

ない場合は、以下を実行してカーネルモジュールをロードする

$ modprobe ip_conntrack_ftp 
$ lsmod | grep ftp
nf_conntrack_ftp       11953  1 nf_nat_ftp
nf_conntrack           79206  4 nf_nat_ftp,nf_nat,nf_conntrack_ipv4,nf_conntrack_ftp

参考

Linuxコマンド集 - 【 modprobe 】カーネルモジュールをロードまたはアンロードする:ITpro

iptablesの起動スクリプトである/etc/sysconfig/iptables-configに以下の行を記述する。

IPTABLES_MODULES="ip_conntrack_ftp"

iptablesにモジュールをロードさせるため、サービスを再起動させる。

$ service iptables restart

これで、iptablesが有効な状態でFTP接続とデータコネクションの通信が無事に通るようになりました。

macOSX Hish sierraにアップデート後にvimが起動しない件について

f:id:kzdev:20171015232735p:plain

先日、macOSXにアップデートした後にvimを起動した所、以下のエラーで起動不能となっていました。

dyld: Library not loaded: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/libruby.2.0.0.dylib
  Referenced from: /usr/local/bin/vim
  Reason: image not found
Abort trap: 6

どうも、homebrewでinstallしている場合は、macvimをアップデートする必要があるとのことなのでアップデートするとまたもエラーが、、

$brew upgrade macvim

** BUILD FAILED **


The following build commands failed:
        StripNIB English.lproj/MainMenu.nib
(1 failure)
make[1]: *** [macvim] Error 65
make: *** [first] Error 2

READ THIS: https://docs.brew.sh/Troubleshooting.html

Error: GitHub
The GitHub credentials in the macOS keychain may be invalid.
Clear them with:
  printf "protocol=https\nhost=github.com\n" | git credential-osxkeychain erase
Or create a personal access token:
  https://github.com/settings/tokens/new?scopes=gist,public_repo&description=Homebrew
and then set the token as: export HOMEBREW_GITHUB_API_TOKEN="your_new_token"

メッセージの通り、キーチェイン内のgitに関する認証が無効になっているようなので、以下の操作で一度削除してからgit configにkeychainの情報を設定します。

$ printf "protocol=https\nhost=github.com\n" | git credential-osxkeychain erase 

これで、リトライするとまたエラーが・・

$ brew upgrade macvim                                                                                                                                                                                                                                                                                                +[master]
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> Updated Formulae
solr                                                                                                                                                            solr@5.5
==> Deleted Formulae
solr@5.4

==> Upgrading 1 outdated package, with result:
macvim 8.0-138
==> Upgrading macvim --with-lua
==> Downloading https://github.com/macvim-dev/macvim/archive/snapshot-138.tar.gz
Already downloaded: /Users/k-goto/Library/Caches/Homebrew/macvim-8.0-138.tar.gz
==> ./configure --with-features=huge --enable-multibyte --with-macarchs=x86_64 --enable-perlinterp --enable-rubyinterp --enable-tclinterp --enable-terminal --with-tlib=ncurses --with-compiledby=Homebrew --with-local-dir=/usr/local --enable-cscope --enable-luainterp --with-lua-prefix=/usr/local/opt/lua --enable-python
==> make
Last 15 lines from /Users/k-goto/Library/Logs/Homebrew/macvim/02.make:
    cd /tmp/macvim-20171016-46768-q6ljo1/macvim-snapshot-138/src/MacVim
    builtin-copy -exclude .DS_Store -exclude CVS -exclude .svn -exclude .git -exclude .hg -strip-debug-symbols -strip-tool /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/strip -resolve-src-symlinks /tmp/macvim-20171016-46768-q6ljo1/macvim-snapshot-138/src/MacVim/icons/MacVim.icns /tmp/macvim-20171016-46768-q6ljo1/macvim-snapshot-138/src/MacVim/build/Release/MacVim.app/Contents/Resources

CopyPlistFile build/Release/MacVim.app/Contents/Resources/KeyBinding.plist KeyBinding.plist
    cd /tmp/macvim-20171016-46768-q6ljo1/macvim-snapshot-138/src/MacVim
    builtin-copyPlist --outdir /tmp/macvim-20171016-46768-q6ljo1/macvim-snapshot-138/src/MacVim/build/Release/MacVim.app/Contents/Resources -- KeyBinding.plist

** BUILD FAILED **


The following build commands failed:
        StripNIB English.lproj/Preferences.nib
(1 failure)
make[1]: *** [macvim] Error 65
make: *** [first] Error 2

xcodeが更新されていなかったので、更新してリトライしたところ、以下の通り正常にインストールできました。

Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> Updated Formulae
faac                                                                            imagemagick@6                                                                   menhir                                                                          snort

==> Upgrading 1 outdated package, with result:
macvim 8.0-138
==> Upgrading macvim --with-lua
==> Downloading https://github.com/macvim-dev/macvim/archive/snapshot-138.tar.gz
Already downloaded: /Users/k-goto/Library/Caches/Homebrew/macvim-8.0-138.tar.gz
==> ./configure --with-features=huge --enable-multibyte --with-macarchs=x86_64 --enable-perlinterp --enable-rubyinterp --enable-tclinterp --enable-terminal --with-tlib=ncurses --with-compiledby=Homebrew --with-local-dir=/usr/local --enable-cscope --enable-luainterp --with-lua-prefix=/usr/local/opt/lua --enable-python
==> make
 /usr/local/Cellar/macvim/8.0-138: 2,139 files, 34.1MB, built in 3 minutes 1 second

MacはOSの更新が入る度に色々と動かないものが出るので、時間のある時にアップデートするようにしないといけないですね。

データベースに接続中のセッションを強制切断する方法

データベースに関する設定を行う時に、接続中のユーザがいると操作が正常に行えない場合があります。 そんな場合の対処です。

f:id:kzdev:20170921125812p:plain

前提

Software Version
PostgreSQL 9.6.1

手順

postgres=# alter database xxxxdb rename to xxxxdb_org;
ERROR:  database "xxxxdb" is being accessed by other users
DETAIL:  There are 2 other sessions using the database.

この場合、接続中のユーザセッションを強制的に切断後に再実行します。
まずは、接続中のユーザのpidを以下のコマンドで求めます。

postgres=# SELECT pid FROM pg_stat_activity where pid <> pg_backend_pid();
  pid  
-------
 15725
 16586
(2 rows)

参考 PostgreSQL: Documentation: 9.6: System Administration Functions

上記のように2ユーザいるので、それぞれのpidを強制切断します。

SELECT pg_terminate_backend(15725);
 pg_terminate_backend 
----------------------
 t
(1 row)

SELECT pg_terminate_backend(16586);
 pg_terminate_backend 
----------------------
 t
(1 row)

これで再実行します。

postgres=# alter database xxxxdb rename to xxxxdb_org;
postgres=#

dockerコンテナの日本語対応(centos)

dockerで公式centosイメージからコンテナを起動すると、時間とエンコードが日本語に対応していないので困った時の対策です。

f:id:kzdev:20170913005837p:plain

公式 www.docker.com

前提

Software Version
Docker 17.06.2-ce

手順

まずはcentosイメージをダウンロードします。

docker pull centos:latest
% docker images                                                                                                                                                                                          REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos              latest              328edcd84f1b        5 weeks ago         193MB
centos              6.8                 0cd976dc0a98        12 months ago       195MB

続いて、ダウンロードしたイメージでコンテナを起動します。

% docker run -i -t centos /bin/bash
[root@7f86c5aa58d6 /]#

無事にコンテナに入ったら、時間が正しいか確認してみます。

[root@7f86c5aa58d6 /]# date
Tue Sep 12 15:40:21 UTC 2017

はい。UTC(協定世界時)になっているので、JST-9時間ですね。
もう時刻やらタイマーを乱用するプログラムの試験などする場合は、この上なく困ります。

更に、localeなんかも日本語等の無駄なものはイメージ作成時に軽量化のため削除されてしまっているわけです。

[root@d8e528556ee7 /]# locale
LANG=
LC_CTYPE="POSIX"
LC_NUMERIC="POSIX"
LC_TIME="POSIX"
LC_COLLATE="POSIX"
LC_MONETARY="POSIX"
LC_MESSAGES="POSIX"
LC_PAPER="POSIX"
LC_NAME="POSIX"
LC_ADDRESS="POSIX"
LC_TELEPHONE="POSIX"
LC_MEASUREMENT="POSIX"
LC_IDENTIFICATION="POSIX"
LC_ALL=

ですので、日本語化したcentosのイメージを新たに用意します。
イメージ生成用のDockerfileはこちら。

FROM centos:6.8 
MAINTAINER "kzdev" <xxxx@gmail.com>  

RUN yum -y update
RUN yum -y install epel-release 
RUN yum reinstall -y glibc-common
ENV LANG ja_JP.UTF-8 
ENV LANGUAGE ja_JP:ja
ENV LANGUAGE ja_JP:ja
RUN yum clean all

RUN echo 'ZONE="Asia/Tokyo"' > /etc/sysconfig/clock 
RUN rm -f /etc/localtime
RUN ln -fs /usr/share/zoneinfo/Asia/Tokyo /etc/localtime

yum reinstall -y glibc-common で削除されたlocale達を復活させます。

続いて時刻設定を行います。
RUN echo 'ZONE="Asia/Tokyo"' > /etc/sysconfig/clockで、ハードウェアクロックのタイムゾーンASIAに変更します。

次にシステムクロックの変更を以下で行います。 既に配置されている/etc/localtimeを削除して、同名でASIAタイムゾーンファイルのシンボリックリンクを作成しています。

これでdocker imageをビルドします。

% docker build ./ -t centosj
...
Removing intermediate container dcb5ad3e340f
Step 12/12 : RUN ln -fs /usr/share/zoneinfo/Asia/Tokyo /etc/localtime
 ---> Running in 6c66749583f5
 ---> 967ab0235536
Removing intermediate container 6c66749583f5
Successfully built 967ab0235536
Successfully tagged testdev:latest

と出たら成功です。

稼働確認

無事にイメージを作成できたので、コンテナを起動してきちんと日本語になっているか確認してみます。

% docker run -i -t centosj /bin/bash
[root@65d95e00003c /]# date
2017913日 水曜日 01:11:32 JST
[root@65d95e00003c /]# locale
LANG=ja_JP.UTF-8
LC_CTYPE="ja_JP.UTF-8"
LC_NUMERIC="ja_JP.UTF-8"
LC_TIME="ja_JP.UTF-8"
LC_COLLATE="ja_JP.UTF-8"
LC_MONETARY="ja_JP.UTF-8"
LC_MESSAGES="ja_JP.UTF-8"
LC_PAPER="ja_JP.UTF-8"
LC_NAME="ja_JP.UTF-8"
LC_ADDRESS="ja_JP.UTF-8"
LC_TELEPHONE="ja_JP.UTF-8"
LC_MEASUREMENT="ja_JP.UTF-8"
LC_IDENTIFICATION="ja_JP.UTF-8"
LC_ALL=

日本時間と日本語化が無事に確認できました。

まとめ

必要な環境や機能が出てきたら、Dockerfileに追記してイメージを作ってコンテナを上げて使うという繰り返しになります。 一度イメージを作ってしまえば、生成や破棄はすぐに出来るので、試験やちょっとした動作確認にはもってこいです。

必要な機能を搭載したイメージに関しては、ほとんどがdocker-hubに既に上がっているので、探してなかったら作るとかの方が時短にはなると思います。

https://hub.docker.com

golang1.9 ReuseRecordでCSVのREADパフォーマンスが向上するかも!?

golangを1.9にアップデートしてみました。

Go 1.9 Release Notes - The Go Programming Language

f:id:kzdev:20170908010918p:plainf:id:kzdev:20170908010918p:plain

release noteを見ると機能の追加からパフォーマンスの向上まで色々ありますが、
今回は、CSVのREAD性能が向上したというので、ベンチマークを取ってどのくらい改善されたのか確認します。

続きを読む