CentOS7のファイルディスクリプタの設定

確認方法

cat /proc/`pgrep -f サービス名`/limits

Limit                     Soft Limit           Hard Limit           Units     
Max cpu time              unlimited            unlimited            seconds   
Max file size             unlimited            unlimited            bytes     
Max data size             unlimited            unlimited            bytes     
Max stack size            8388608              unlimited            bytes     
Max core file size        0                    unlimited            bytes     
Max resident set          unlimited            unlimited            bytes     
Max processes             29222                29222                processes 
Max open files            1024                1024                files     
Max locked memory         65536                65536                bytes     
Max address space         unlimited            unlimited            bytes     
Max file locks            unlimited            unlimited            locks     
Max pending signals       29222                29222                signals   
Max msgqueue size         819200               819200               bytes     
Max nice priority         0                    0                    
Max realtime priority     0                    0                    
Max realtime timeout      unlimited            unlimited            us        

変更方法

/usr/lib/systemd/system/サービス管理ファイル に、

LimitNOFILE=65536

を追加する。

追加した跡は、

systemctl daemon-reload
systemctl restart daemon

として、サービスを再起動する。

pecoで遊んでみる

Twitterでやり取りさせて貰っているShu1さんの記事が面白かったので、GCEで再現してみた
http://blog.jicoman.info/2018/04/ec2-ssh-using-peco/

※ gcloudの設定が終わっている事前提

pecoインストール

wget https://github.com/peco/peco/releases/download/v0.5.3/peco_linux_amd64.tar.gz

tar zxvf peco_linux_amd64.tar.gz
mv peco_linux_amd64/peco /usr/local/bin/
rm -rf peco_linux_amd64*

関数設定

vim ~/.bash_profile

# ssh簡単にするやつ
function ssh-gce() {
  local user="root"
  local host=$(gcloud compute instances list | grep stg | awk '{print $1,$3,$4}' | column -t -s" " | /usr/local/bin/peco | awk '{print $3}')
  ssh "$user@$host"
}

修正後に、

source ~/.bash_profile

出来たー!

ドメイン移管のエラー対応

他サービスで取得したドメインを、お名前.comに移管する際、一筋縄ではいかない。

まず拒否理由の内容

審査による拒否
詳細は下記内容をご確認ください。
拒否理由:[Whois情報に正確な情報の記載がございませんため、弊社審査において不受理とさせていただきました。  現ドメイン管理会社にて、Whois情報を正確な情報へご変更のうえ、再度お手続きをお願いいたします。]

正しい情報を住所をローマ字読みで入力しているのに、なんで!?

と、なる事が多いのでまとめておく。
先に言うと、『日本語の解釈と違う内容を求められる』事が最大の原因だと思う。

例として、東京都港区の区役所の住所「〒105-8511 東京都港区芝公園1丁目5番25号」を展開してみる。

項目 日本語 英語 説明
国(Country) 日本 JP ここは迷わない
郵便番号(ZIP/Postal code) 105-8511 105-8511 ハイフンあり、なしはどちらでもいい
都道府県(state) 東京都 Tokyo ここも迷わない
市区町村(city) 港区 Minato-ku 「市区町村」なので、「Minato-ku Shibakouen」と描きたいが、ここは英語でcityの場所の為、「Minato-ku」まで
番地(street) 芝公園1丁目5番25号 1-5-25, Shibakouen 番地って「1-5-25」だけじゃないの?と思うが、書き方は「番地 ,(カンマ) 町名」になる

他に電話番号やメールアドレスも登録する必要があるが、
それは迷わないと思うから省略。

これを適切に理解していれば、一発でドメイン移管が行える!

pop2imapを使ってメールデータを移行する

お客さんの環境(さくらレンタルサーバー)から、自前で構築したIMAPSの環境にメールデータを移行したいと話があった。

色々探して、perlのpop2imapってツールを見つけた。
これならサーバーにSSHログイン出来ない環境でも、IMAPかPOP3が動いていればデータの移行が簡単に出来る。

wget http://www.linux-france.org/prj/pop2imap/dist/pop2imap-1.27.tgz

tar zxvf pop2imap-1.27.tgz

cd pop2imap-1.27/

INSTALLを見ると、必要がモジュールが書かれている。

You need : 
- Perl 
  try : perl -v
  try : perl -c pop2imap

- Mail::IMAPClient module 
  try : perl -mMail::IMAPClient -e ''

- Mail::POP3Client module 
  try : perl -mMail::POP3Client -e ''

- Email::Simple module
  try : perl -mEmail::Simple -e ''

- Date::Manip module 
  try : perl -mDate::Manip -e ''

- IO::Socket::SSL  module (optional needed with --ssl1 or --ssl2)
  try : perl -mIO::Socket::SSL -e ''

Any software packager should add all the perl modules dependencies by default
since users can use any option (--ssl*).

これらは入っていなければyumなりCPAMなりでインストールする。
yumの場合は

yum -y install \
perl-Mail-POP3Client.noarch \
perl-Mail-IMAPClient.noarch \
perl-Mail-POP3Client.noarch \
perl-Date-Manip.noarch \
perl-IO-Socket-SSL.noarch

モジュールを入れたら、makeする。

make
make install  # /usr/bin/pop2imap にインストールされる

オプションは直感的に分かるけど、パスワードを平文で打つので、作業後はhistory消しておいた方が良さそう。

pop2imap --help

usage: /usr/bin/pop2imap [options]

Several options are mandatory. See the example below.

--from        <string> : parsed as <user1>@<host1>[:<port1>]
--host1       <string> : "from" POP server. Mandatory.
--port1       <int>    : port to connect. Default is 110 (ssl:995).
--user1       <string> : user to login.   Mandatory.
--password1   <string> : password for the user1. Dangerous, use --passfile1
--passfile1   <string> : password file for the user1. Contains the password.
--ssl1                 : enable ssl on POP connect
--to          <string> : parsed as <user2>@<host2>[:<port2>][/<folder>]
--host2       <string> : "destination" IMAP server. Mandatory.
--port2       <int>    : port to connect. Default is 143 (ssl:993).
--user2       <string> : user to login.   Mandatory.
--password2   <string> : password for the user2. Dangerous, use --passfile2
--passfile2   <string> : password file for the user2. Contains the password.
--ssl2                 : enable ssl on IMAP connect
--starttls2            : use starttls on IMAP connect instead of SSL
--timeout2    <int>    : Connections timeout in seconds. Default is 240.
--folder      <string> : sync to this IMAP folder.
--delete               : delete messages in "from" POP server after
                         a successful transfer. useful in case you
                         want to migrate from one server to another one.
                         They are really deleted when a QUIT command
                         is send.
--idatefromheader      : sets the internal dates on host2 same as the 
                         "Date:" headers from host1. Turned on by default.
--dry                  : do nothing, just print what would be done.
--debug                : debug mode.
--debugimap            : IMAP debug mode.
--debugpop             : POP debug mode.
--tests                : Run non-regression tests
--quiet                : Only print error messages
--version              : print sotfware version.
--help                 : print this message.

Example: to synchronise pop  account "foo" on "pop3.truc.org"
                     to imap account "bar" on "imap.trac.org"

/usr/bin/pop2imap \
   --host1 pop3.troc.org --user1 foo --passfile1 /etc/secret1 \
   --host2 imap.trac.org --user2 bar --passfile2 /etc/secret2


Branched by Phil Carmody <phil.carmody@partner.samsung.com> from:
 $Id: pop2imap,v 1.27 2015/11/03 23:34:02 gilles Exp gilles $ 
      pop2imap copyleft is the GNU General Public License.

使い方

pop2imap --host1 移行元サーバー --user1 移行元ユーザー名 --password1 移行元パスワード --host2 移行先サーバー --user2 移行先ユーザー名 --password2 移行先パスワード -ssl2(IMAPSで接続)

おまけ
historyを削除する

history -c

EC2にswapを増やす

訳あってEC2のt2.nano(メモリ 0.5GB)でCPAMを使いたいけど、CPAMだけで300MB近くメモリを食うので、isntall処理がAbortしてしまう。

#  perl -MCPAN -e shell
Terminal does not support AddHistory.

cpan shell -- CPAN exploration and modules installation (v2.16)
Enter 'h' for help.

cpan[1]> install Mail::IMAPClient
Reading '/root/.cpan/sources/authors/01mailrc.txt.gz'
............................................................................DONE
Reading '/root/.cpan/sources/modules/02packages.details.txt.gz'
  Database was generated on Tue, 10 Apr 2018 14:54:48 GMT
....................................................Killed

遅くてもinstallが出来ればいいので、SWAP付けて逃げる。

# free -m
              total        used        free      shared  buff/cache   available
Mem:            483         174         222          32          86         245
Swap:             0           0           0  ← SWAPがない

/var/swapfileを作成して、SWAPに当てる

# dd if=/dev/zero of=/var/swapfile bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 15.0153 s, 71.5 MB/s

# mkswap /var/swapfile
mkswap: /var/swapfile: insecure permissions 0644, 0600 suggested.
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=2311e423-13a4-4451-b081-05ac4074c8bf

# swapon /var/swapfile
swapon: /var/swapfile: insecure permissions 0644, 0600 suggested.

# free -m
              total        used        free      shared  buff/cache   available
Mem:            483         175           5          32         302         244
Swap:          1023           0        1023  ← SWAP増えた!

Google Cloud Storageを公開する

ACLの確認

gsutil acl get gs://バケット名

レスポンス
[
  {
    "entity": "project-owners-xxxxxxxxxxx",
    "projectTeam": {
      "projectNumber": "xxxxxxxxxxx",
      "team": "owners"
    },
    "role": "OWNER"
  },
  {
    "entity": "project-editors-xxxxxxxxxxx",
    "projectTeam": {
      "projectNumber": "xxxxxxxxxxx",
      "team": "editors"
    },
    "role": "OWNER"
  },
  {
    "entity": "project-viewers-xxxxxxxxxxx",
    "projectTeam": {
      "projectNumber": "xxxxxxxxxxx",
      "team": "viewers"
    },
    "role": "READER"
  },
  {
    "entity": "allUsers",
    "role": "READ"
  }
]

全ユーザーにデータ書き込みを許可する

gsutil acl ch -u AllUsers:R gs://バケット名

レスポンス
Updated ACL on gs://バケット名/

全ユーザーにデータ読み込みを許可する

gsutil acl ch -u AllUsers:W gs://バケット名

レスポンス
Updated ACL on gs://バケット名/

nginxでのリダイレクト

nginxが.htaccess使えないの忘れていたので、HTTPで来たアクセスをHTTPSにリダイレクトする設定を今更書いた

server {
    listen       80;
    server_name  www.jhhk-family.net;
    return 301 http://www.jhhk-family.net/$request_uri;
}

SMTPSとIMAPSで安全なセキュアなメールサーバーを作る

AWSにメールサーバーを移設した際に、STARTSSLからSMTPSとIMAPSの環境に変更したので、そのメモ


環境:
AWS EC2 (Amazon Linux AMI 2017.09.1 (HVM), SSD Volume Type)

セキュリティグループ:
22/tcp , 25/tcp, 80/tcp(Let’s Encryptの認証用に一時的に開ける), 465/tcp, 993/tcp を開けておく。


必要なパッケージをインストール

yum install postfix dovecot cyrus-sasl cyrus-sasl-plain

LetsEncryptでメールサーバー用の証明書を発行
wordpress をELB+EC2でHTTPS通信させる
を参照


(SMTPSに必要な箇所のみ記載)
/etc/postfix/postfix.cf

smtpd_sasl_auth_enable = yes
smtpd_recipient_restrictions =
    permit_mynetworks
    permit_sasl_authenticated
    reject_unauth_destination

smtp_tls_security_level = may
smtpd_tls_security_level = may
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.jhhk-family.net/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.jhhk-family.net/privkey.pem
smtpd_tls_session_cache_database = btree:/var/lib/postfix/smtpd_scache
tls_high_cipherlist = kEECDH:+kEECDH+SHA:kEDH:+kEDH+SHA:+kEDH+CAMELLIA:kECDH:+kECDH+SHA:kRSA:+kRSA+SHA:+kRSA+CAMELLIA:!aNULL:!eNULL:!SSLv2:!RC4:!MD5:!DES:!EXP:!SEED:!IDEA:!3DES
smtp_tls_ciphers = high
smtpd_tls_ciphers = high
smtpd_tls_mandatory_ciphers = high

/etc/postfix/master.cf

smtps     inet  n       -       n       -       -       smtpd
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING

smtpd_client_restrictionsは未設定。必要に応じて。

/etc/dovecot/conf.d/10-auth.conf

auth_mechanisms = plain
!include auth-system.conf.ext

/etc/dovecot/conf.d/10-ssl.conf

ssl = yes
ssl_cert = </etc/letsencrypt/live/mail.jhhk-family.net/fullchain.pem
ssl_key = </etc/letsencrypt/live/mail.jhhk-family.net/privkey.pem
ssl_protocols = !SSLv2 !SSLv3 !TLSv1
ssl_cipher_list = HIGH:MEDIUM:!aNULL:!MD5:!SEED:!IDEA:!RC4:!3DES:!RSA

/etc/dovecot/conf.d/10-master.conf

service imap-login {
#  inet_listener imap {
#    port = 143
#  }
  inet_listener imaps {
    port = 993
    ssl = yes
  }

最後にpostfix、dovecot、saslを起動する。

service saslauthd start
service postfix start
service dovecot start

randomモジュールを使う

pythonのramdomモジュールを使って、20人を超える飲み会の座席を固めてみる。

ramdomモジュールは、loop内で使っても、n個 – 1とかには出来ないらしく、10枚のカードから1枚選んで、また10枚の中に戻す。と言った動きになる。

member.yml

※氏名は平成21年生まれの名前ランキングから抜粋

[code]
member:
– "佐藤 優衣"
– "田中 美羽"
– "佐藤 花音"
– "鈴木 大翔"
– "吉田 悠人"
– "田中 優衣"
– "高橋 美結"
– "佐藤 愛莉"
– "鈴木 杏奈"
– "吉田 百花"
– "佐藤 翔太"
– "山口 結愛"
– "田中 大翔"
– "伊藤 悠真"
– "加藤 颯真"
– "佐藤 優成"
– "森 悠真"
– "中村 優希"
– "田中 悠翔"
– "鈴木 悠真"

table:
– A-1
– A-2
– A-3
– A-4
– A-5
– A-6
– B-1
– B-2
– B-3
– B-4
– B-5
– B-6
– C-1
– C-2
– C-3
– C-4
– C-5
– C-6
– C-7
– C-8
[/code]

lottery.py
[code]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import yaml
import random

base = os.path.dirname(os.path.abspath(__file__))
input = (os.path.join(base,’member.yml’))

f = open(imput, ‘r’)
result = yaml.load(f)
f.close()

members= (random.sample(source[‘member’],len(source[‘member’])))
tables = (source[‘table’])

for (t,m) in zip(tables,members):
print(t + ‘\t’ + m)

[/code]

[code]
(random.sample(source[‘member’],len(source[‘member’])))
[/code]

がramdomモジュールを使っている箇所で、
random.sample(配列,何個取るか?)と使う。

全メンバーを1度のみ抽出するので、len(source[‘member’])としている。