hagetak's blog

どうも、はげたかです。

python3 で Google Cloud SDK(gcloud)をインストールする

環境

$ python -V
Python 2.7.16

$ python3 -V
Python 3.7.5

結論

環境変数が用意されているので、いれてあげる

export CLOUDSDK_PYTHON=$(which python3)

インストール(失敗編)

$ curl https://sdk.cloud.google.com | bash
...省略
Welcome to the Google Cloud SDK!
ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
    globals()[__func_name] = __get_hash(__func_name)
  File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
    raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512
Traceback (most recent call last):
  File "/Users/your-user/google-cloud-sdk/bin/bootstrapping/install.py", line 12, in <module>
    import bootstrapping
  File "/Users/your-user/google-cloud-sdk/bin/bootstrapping/bootstrapping.py", line 39, in <module>
    from googlecloudsdk.core import config
  File "/Users/your-user/google-cloud-sdk/lib/googlecloudsdk/core/config.py", line 29, in <module>
    from googlecloudsdk.core.util import files as file_utils
  File "/Users/your-user/google-cloud-sdk/lib/googlecloudsdk/core/util/files.py", line 596, in <module>
    class Checksum(object):
  File "/Users/your-user/google-cloud-sdk/lib/googlecloudsdk/core/util/files.py", line 599, in Checksum
    def __init__(self, algorithm=hashlib.sha256):
AttributeError: 'module' object has no attribute 'sha256'

python3 が利用されず、python 2.7 でインストーラーが走っている。

python3 でインストール

環境変数 CLOUDSDK_PYTHON をみてくれているので、この環境変数python3のPATHを与えてあげるとインストールできる。

$ export CLOUDSDK_PYTHON=$(which python3)
$ curl https://sdk.cloud.google.com | bash

$ gcloud --version
zsh: command not found: gcloud

# インストール時に`.zshrc`に変更が加われ、gcloudのPATHが追加されたためシェルを再度呼び出す
$ exec -l $SHELL

$ gcloud --version
Google Cloud SDK 276.0.0
bq 2.0.52
core 2020.01.10
gsutil 4.47

退職後、1ヶ月休んで次の会社に行くときの準備

概要

5月末に会社を退職し、1ヶ月ニート(3万円のお給料もらえたので、フリーランス)して、 次の会社に転職した。

会社から会社まで1ヶ月空いてしまうと、少し面倒な手続きが必要となる。

  • 国民保険に加入(健康保険の任意継続)
  • 国民年金への加入
  • 健康診断(転職先で求められたら)

※ 僕は専門家ではないので、間違えていたら申し訳ございません!困ったら関係窓口に相談するのがベストです!

国民保険に加入(健康保険の任意継続)

国民保険

国民保険の場合は、14日以内に申請しないといけない。 その際に、前職から、「健康保険資格喪失証明書」をもらわないといけない。

今回は、「健康保険資格喪失証明書」がなかったので、下記任意継続とした。

### 任意継続

僕が加入していた健康保険は、「[ITS]関東ITソフトウェア健康保険組合」であった

ITSの場合、20日以内に任意継続の申請を行わなければいけない。

僕は、大久保にある受付にて30分ほどで任意継続の申請が終わった。

国民年金への加入

1ヶ月空いてしまうと、国民年金に一度加入しなければいけない。

年金事務所にて申請しなければいけない。期限としては、早めがりそうだが、月末に評価(国民年金であるか、厚生年金であるか)されるため月末までに行えば良いとのこと。

健康診断

近くの病院に電話して予約 => 健康診断。 ちなみに、健康診断は健康保険の対象とならないため、保健証なくても良い。(僕がいったところはそうであった。)

さいごに

諸々手続きが面倒であったため、次は休み期間あけたくないが...休みたいよね。。。 ということで、今回やったことをログとして残す。次回、転職する際にこれを参考にし幸せなニート生活を得る。 

世界一やさしい フリーランスの教科書 1年生

世界一やさしい フリーランスの教科書 1年生

hubot のスクリプトを開発するローカル開発環境をgithubにあげました

何かと便利なhubot、これらのscriptを開発する環境を作るのって面倒ですよね。

そのため、docker化して誰でも楽ちんに使えるようにしました

https://github.com/hagetak/hubot-local

あとはこれをフォークしてオリジナルなdockerファイルにしてください!

Slack入門 [ChatOpsによるチーム開発の効率化]

Slack入門 [ChatOpsによるチーム開発の効率化]

vagrant ゲストOSで「Temporary failure in name resolution」が出るときの対処法

vagrant ゲストOSで「Temporary failure in name resolution」が出るときの対処法

vagrantを利用していて、外部URLに通信したときに、「Temporary failure in name resolution」「名前解決に一時的に失敗しました」というエラーが出たときの対処法です。

エラー内容再現

$ ping example.com
ping: example.com: Temporary failure in name resolution

解決法

エラー内容を見る限り、名前解決に失敗していることがわかる。ということで、Google が提供しているDNSサーバ に変更する。(https://securitysoft.asia/sougou/column/publicdns.php

sudo su - 
cp /etc/resolv.conf{,.org}
vim /etc/resolv.conf
diff /etc/resolv.conf{,.org}
3c3
< nameserver 8.8.8.8
---
> nameserver 10.0.2.3


cat /etc/resolv.conf
# Generated by NetworkManager
search search-mitty.com
nameserver 8.8.8.8
options single-request-reopen

ちなみに、10.0.2.3 とは

下記URLを見る限り、virtualboxが設定する、デフォルトのDNSサーバであり、

ホスト OS が参照している DNS キャッシュサーバー

であるとのこと。

https://fumiyas.github.io/vagrant/network.html

ping は通るようだが、なぜ名前解決に失敗したのかは不明。

ping 10.0.2.3
PING 10.0.2.3 (10.0.2.3) 56(84) bytes of data.
64 bytes from 10.0.2.3: icmp_seq=1 ttl=64 time=0.019 ms
64 bytes from 10.0.2.3: icmp_seq=2 ttl=64 time=0.277 ms

本解決法は、一時的であり、virtualbox, vagrantを利用している場合は、Vagrantfileを書き換えてあげるのが正しいと思う。

https://serverfault.com/questions/453185/vagrant-virtualbox-dns-10-0-2-3-not-working/506206

実践 Vagrant

実践 Vagrant

munin を導入し、8080ポートで公開/メールが送信できない問題

概要

日頃からメンテナンスできていないサーバ(絶賛稼働中:ユーザも存在する)がある。(ユーザは身内)

何か起きたときの初動が遅れてしまうのは、嫌なので munin で監視することにする。

ある程度の知識があれば簡単にできるが、調べてもでてこないことを実施したので、記録として残す。

条件

  • さくらVPSIPアドレス xxx.xxx.xxx.xxx) で稼働中。
    • IPアドレス(port 80)にアクセスすると、プロジェクト画面
      • /munin でアクセスできない
    # こんな感じで設定
    <VirtualHost *:80>
        <Directory /var/www/project_name>
            ServerName xxx.xxx.xxx.xxx
        </Directory>
    </VirtualHost>

やったこと

  • 通常のインストール
  • /munin以外でアクセスするようにした
    • ポートを変えて回避
  • 閾値を超えたらメール通知をさせる
    • ココでハマッた

munin インストール

yum install munin
service munin-node start

# basic 認証設定
htpasswd -m /etc/munin/munin-htpasswd munin

# port を変更して、munin を確認できるように変更する
vi /etc/httpd/conf.d/munin.conf
Listen 8080
NameVirtualHost xxx.xxx.xxx.xxx:8080

<VirtualHost xxx.xxx.xxx.xxx:8080>
ServerName xxx.xxx.xxx.xxx:8080
# munin install 時に発行された内容
# ...
# ...
</VirtualHost>

設定するための準備

# ディスク関係
$ munin-run df             
_dev_vda3.value 19.8722218428188
_dev_vda1.value 30.4904706457799

# CPU関係
$ munin-run cpu
user.value 73024010
nice.value 12247
system.value 4216490
idle.value 7275145677
iowait.value 526483
irq.value 1414
softirq.value 298340
steal.value 3071780
guest.value 0

muninの設定ファイルを変更

vim /etc/munin/munin.conf

閾値は適当。追々調整していく。

# For those with Nagios, the following might come in handy. In addition,
# the services must be defined in the Nagios server as well.
#contact.nagios.command /usr/bin/send_nsca nagios.host.comm -c /etc/nsca.conf
 
contact.email.command mail -s "Munin-notification for ${var:group}::${var:host}" "your-mail@address.com"
contact.email.always_send warning critical

# a simple host tree
[your-service-name]
    address 127.0.0.1
    use_node_name yes

    # For disk
    df._dev_vda1.warning 50
    df._dev_vda1.critical 80

    df._dev_vda3.warning 50
    df._dev_vda3.critical 80

    # For CPU
    cpu.user.warning 40
    cpu.user.critical 80
    contacts email

テスト送信

sudo -u munin sh -c "/usr/share/munin/munin-limits --contact email --force"

メールが飛んだら、munin の設定は以上。

munin でメールが送信できない

上記のテスト送信を実行時、下記のエラーが発生した。

$ sudo -u munin sh -c "/usr/share/munin/munin-limits --contact email --force"
sh: -c: line 0: unexpected EOF while looking for matching `"'
sh: -c: line 1: シンタックス エラー: 期待してないファイルの終了

対策

原因は分からず、下記のように変更したら回避した。(そもそも別の問題が合ったのかもしれない)

# your-mail@address.com => "your-mail@address.com"
# 上の例では既に`"`付きで対応済み
contact.email.command mail -s "Munin-notification for ${var:group}::${var:host}" "your-mail@address.com"

歌詞を検索するruby製簡易スクリプトを作成しました

ブログで報告するようなことでもないですが、ruby製のかんたんなスクリプトを作成しました。

用途としては、業務時間中にちらっと歌詞をみたいときとかに使ってください。 ターミナル内で完結するので一目が気にならないというメリットがあります。

https://github.com/hagetak/fetch_lyric

とりあえず検索できれば良いというスタンスなので直近メンテする予定はないです。

たのしいRuby 第5版

たのしいRuby 第5版

CakePHP のプロジェクトでコーディング規約に沿っているか自動チェックをする

CakePHP のプロジェクトでコーディング規約に沿っているか自動チェックをする

概要

よくプルリクエストで、コーディング規約に沿っていない箇所をご指摘頂く。コーディング規約はあらかじめ決まっているため、事前に気づくことができる。

プルリク => レビュー => 修正(コーディング規約に沿っていない箇所) => レビュー => ・・・

1サイクル(レビュー => 修正)が増えるので、当然、自分やレビュー者にも負担がかかり、時間も無駄にしてしまう。(そしてコミットログを汚すことにもなる)

ということで、コーディング規約チェッカー(PHP_CodeSniffer 2.0.0)を導入してみては?と提案いただいたので導入してみる。

ココで得られること

  • PHP_CodeSniffer のインストール
  • CakePHP 用のルールをセット
  • 簡単なカスタマイズができる(インデントに Tabを許可する)
    • Tabs must be used to indent lines; spaces are not allowed

コーディング規約一覧

PSR-0

http://www.infiniteloop.co.jp/docs/psr/psr-0.html

PSR-1

http://www.infiniteloop.co.jp/docs/psr/psr-1-basic-coding-standard.html

PSR-2

http://www.infiniteloop.co.jp/docs/psr/psr-2-coding-style-guide.html

CakePHP2

https://book.cakephp.org/2.0/ja/contributing/cakephp-coding-conventions.html

PHP_CodeSniffer 2.0.0

Composer のインストール

Composer とは、PHPのパッケージ管理ツールである。詳しくは、以下を参照すること。

http://qiita.com/atwata/items/d6f1cf95ce96ebe58010

# composer のインストール ※ 既にインストール済みの場合はSKIPすること
curl http://getcomposer.org/installer | php 

# 利用している shell の設定ファイルに環境設定を書き込み
vim ~/.zshrc

################ 以下を記述 #####################

# For Composer, Uses vendor's bin.
export PATH="$PATH:$HOME/.composer/vendor/bin"

################ ここまで #######################

# 変更した設定ファイルを読みこむ
source ~/.zshrc

CodeSniffer をインストール

composer global require "squizlabs/php_codesniffer"
composer global show --installed | grep php_codesniffer

Changed current directory to /Users/{{USER_NAME}_/.composer
You are using the deprecated option "installed". Only installed packages are shown by default now. The --all option can be used to show all packages.
squizlabs/php_codesniffer    2.8.0   PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined s...

# 使えるかチェック
phpcbf --version
PHP_CodeSniffer version 2.6.1 (stable) by Squiz (http://www.squiz.net)

CakePHP2 用のルールを取得

上記のインストールの他に、CakePHP用のコーディング規約ルールを取得しなければいけない。

https://github.com/cakephp/cakephp-codesniffer/

CakePHP2 のルールを取得するには、 update-fxer-2 を取得する。

master は CakePHP3用でPSR-2 を準拠しているため全く異なる

# 好みの場所にインストールする
# 僕の場合は、 ~/.sniffs/{{Intalled Coding Rules}}
cd ~/
curl -LO https://github.com/cakephp/cakephp-codesniffer/archive/update-fxer-2.zip
unzip update-fxer-2.zip -d sniffs
cd ~/.sniffs/

# ~/.sniffs/{{NAME}} になるので正しい名前を命名する
# ※ ここでバージョン指定{{CakePHP2}} したいが、エラーになる.><;
mv cakephp-codesniffer-update-fxer-2 CakePHP

# 削除忘れずに
rm ~/update-fxer-2.zip

取得したルールを反映させる

# 取得したルールセットを反映させる
phpcs --config-set installed_paths ~/.sniffs/                           

# 反映を確認する
phpcs -i
The installed coding standards are MySource, PEAR, PHPCS, PSR1, PSR2, Squiz, Zend and CakePHP2

phpcbf -i
The installed coding standards are MySource, PEAR, PHPCS, PSR1, PSR2, Squiz, Zend and CakePHP2

実際に使ってみよう。

phpcs --standard=CakePHP /PATH/TO/CAKEPHP_APP/app/Controller/AppController.php

----------------------------------------------------------------------
FOUND 7 ERRORS AND 1 WARNING AFFECTING 5 LINES
----------------------------------------------------------------------
 33 | ERROR   | [ ] Expected 1 space before curly opening bracket
 36 | ERROR   | [x] Tabs must be used to indent lines; spaces are not
    |         |     allowed
 36 | WARNING | [ ] Possible useless method overriding detected
 36 | ERROR   | [ ] Missing function doc comment
 37 | ERROR   | [x] Tabs must be used to indent lines; spaces are not
    |         |     allowed
 37 | ERROR   | [x] Opening brace should be on the same line as the
    |         |     declaration
 38 | ERROR   | [x] Tabs must be used to indent lines; spaces are not
    |         |     allowed
 39 | ERROR   | [x] Tabs must be used to indent lines; spaces are not
    |         |     allowed
----------------------------------------------------------------------
PHPCBF CAN FIX THE 5 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

インデントのタブの指摘が多すぎる。うあああああ。

インデントにタブ利用を許可するカスタマイズする

cd ~/.sniffs/CakePHP 
cp ruleset.xml ruleset.xml.org                                                      

# 62行目の'<rule ref="Generic.WhiteSpace.DisallowSpaceIndent"/>'をコメントアウト
vim ruleset.xml

### こうする
 <!-- <rule ref="Generic.WhiteSpace.DisallowSpaceIndent"/> -->

diff ruleset.xml ruleset.xml.org 
62c62
<  <!-- <rule ref="Generic.WhiteSpace.DisallowSpaceIndent"/> -->
---
>  <rule ref="Generic.WhiteSpace.DisallowSpaceIndent"/>
phpcs --standard=CakePHP /PATH/TO/CAKEPHP_APP/app/Controller/AppController.php

----------------------------------------------------------------------
FOUND 3 ERRORS AND 1 WARNING AFFECTING 3 LINES
----------------------------------------------------------------------
 33 | ERROR   | [ ] Expected 1 space before curly opening bracket
 36 | WARNING | [ ] Possible useless method overriding detected
 36 | ERROR   | [ ] Missing function doc comment
 37 | ERROR   | [x] Opening brace should be on the same line as the
    |         |     declaration
----------------------------------------------------------------------
PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

これで、インデントのエラーが消え、本質的なコーディング規約を見ることができる。

CakePHP2 実践入門 (WEB+DB PRESS plus)

CakePHP2 実践入門 (WEB+DB PRESS plus)

CakePHPで学ぶ継続的インテグレーション

CakePHPで学ぶ継続的インテグレーション

PHPフレームワーク CakePHP 3入門

PHPフレームワーク CakePHP 3入門