2016年11月22日火曜日

rubyのaws-sdkでALBのターゲットグループに紐付いているEC2インスタンスのIPを取得してみた

ELBからALBにリプレイスを行うにあたって、ALB配下のインスタンスのIPを取得する必要があったので調べました。
ALBはターゲットグループを割り当てる形になるので、指定したターゲットグループに紐づくインスタンスを取得すればIP取れました。

require 'aws-sdk'

alb = Aws::ElasticLoadBalancingV2::Client.new(
  region: 'ap-northeast-1',
  access_key_id: 'xxx',
  secret_access_key: 'xxx'
)

ec2 = Aws::EC2::Client.new(
  region: 'ap-northeast-1',
  access_key_id: 'xxx',
  secret_access_key: 'xxx'
)

instance_healths = alb.describe_target_health({ target_group_arn: 'xxx' })
instance_ids = instance_healths.target_health_descriptions.map {|t| t.target.id }

ec2_instances = ec2.describe_instances({ instance_ids: instance_ids })
instance_ips = ec2_instances.reservations.map { |e| p e.instances[0].public_ip_address }

2016年11月9日水曜日

aws-sdk v2でS3操作するとエラー出た

rubyのaws-sdkでS3の操作しようとしたら、エラー出たのでその時の対応。
sdkのバージョンは以下で指定
gem 'aws-sdk', "~>2.1"

出たエラーは以下のようなもの
F, [2016-11-08T11:23:44.711503 #21962] FATAL -- : 
Aws::Errors::MissingRegionError (missing region; use :region option or export region name to ENV['AWS_REGION']):
  app/xxx:12:in `new'
  app/xxx:12:in `update_s3_bucket_acl'
  app/xxx.rb:338:in `update_s3_bucket_acl'
  app/xxx.rb:323:in `block in update'
  app/xxx.rb:306:in `update'
  config/initializers/quiet_assets.rb:6:in `call_with_quiet_assets'

そのときのコードの一部がこれ
require 'aws-sdk'

s3 = Aws::S3::Resource.new(
  access_key_id: #{access_key_id},
  secret_access_key: #{secret_access_key}
)

bucket = s3.bucket(bucket_name)

対応内容はエラーにまんま書いてあるように、regionを追加しました
s3 = Aws::S3::Resource.new(
  region: 'ap-northeast-1',
  access_key_id: #{access_key_id},
  secret_access_key: #{secret_access_key}
)

S3ってregion関係ないと思うので指定いらなそうなのになと思うのは勉強不足なのでしょう...


参考URL
http://qiita.com/rikitoro@github/items/45f9c85c218343e69014
http://stackoverflow.com/questions/28825047/aws-sdk-v2-for-s3

2016年10月24日月曜日

rubyのaws-sdkでELBに紐付いているEC2インスタンスのIPを取得しようとしたらバージョン2系で記法が変わってた件

ELBに紐付いているEC2インスタンスのIPを取得していたのですが、
aws-sdkのバージョンを1系から2系に変更したらけっこう記法が変わってたので調べました。

バージョン1系
require 'aws-sdk'

elb_name = 'aaa'

AWS.config({
  access_key_id: 'xxx',
  secret_access_key: 'xxx',
  ec2_endpoint: 'xxx',
  elb_endpoint: 'xxx'
})

elb = AWS::ELB.new
lb_instances = elb.load_balancers[elb_name].instances
instance_ips = lb_instances.map { |instance| instance.public_ip_address }

バージョン2系
require 'aws-sdk'

elb_name = 'aaa'

# ELBクライアント
elb = Aws::ElasticLoadBalancing::Client.new(
  region: 'xxx',
  access_key_id: 'xxx',
  secret_access_key: 'xxx'
)

# EC2クライアント
ec2 = Aws::EC2::Client.new(
  region: 'xxx',
  access_key_id: 'xxx',
  secret_access_key: 'xxx'
)

lb_instances = elb.describe_load_balancers({ load_balancer_names: [elb_name] })[:load_balancer_descriptions][0][:instances]
ec2_instances = ec2.describe_instances({ instance_ids: lb_instances.map { |instance| instance.instance_id } })
instance_ips = ec2_instances.reservations.map { |e| e.instances[0].public_ip_address }

2016年9月27日火曜日

rubyのバージョンをあげたらrails consoleが起動しなくなった件

rubyのバージョンを2.1.3から2.3.1にあげることになったので、バージョンアップをしたところ、
bundle exec rails cでエラーが出るようになりました。
$ bundle exec rails c
/Users/xxx/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- bundler/setup (LoadError)
 from /Users/xxx/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.1.3/lib/spring/commands.rb:33:in `'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.1.3/lib/spring/commands.rb:4:in `'
 from /Users/xxx/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /Users/xxx/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.1.3/lib/spring/application.rb:77:in `preload'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.1.3/lib/spring/xxx.rb:140:in `serve'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.1.3/lib/spring/application.rb:128:in `block in run'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.1.3/lib/spring/application.rb:122:in `loop'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.1.3/lib/spring/application.rb:122:in `run'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.1.3/lib/spring/application/boot.rb:18:in `'
 from /Users/xxx/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /Users/xxx/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from -e:1:in `
'

調べてみると、bundle installでvendor/bundle配下に入れた時に、
springがvendor/bundleのbundlerを読み込もうとしてないよってエラーになっているようです。

更に調べてみると、springの1.6.3で直っているようです。

元のspringのバージョンが以下
$ bundle exec gem list|grep spring
spring (1.1.3)
spring-commands-rspec (1.0.2)

springのバージョンを最新にする
$ bundle update spring
$ bundle exec gem list|grep spring
spring (1.7.2)
spring-commands-rspec (1.0.2)

springを停止してからrails cをしてみると、いろいろメッセージでるけど、ちゃんと起動しました
$ bundle exec bin/spring stop
Spring stopped.
$ bundle exec rails c
Resque::Helpers will be gone with no replacement in Resque 2.0.0.
Running via Spring preloader in process 8207
Loading development environment (Rails 4.1.6)
irb: warn: can't alias context from irb_context.
Cannot read termcap database;
using dumb terminal settings.
irb(main):001:0> 


参考URL
http://qiita.com/koshigoe/items/2304ec081a9f036e8941

2016年8月17日水曜日

apache httpd serverがバージョンアップで起動しなくなった

apacheのhttpd serverがバージョンアップしたら起動しなくなったので調べました。
バージョンアップは意図して行ったのではなく、AWSのautoscaleで起動したインスタンスが
セキュリティアップデートでhttpd serverがバージョンアップしてしまった感じです。

バージョンアップ前のバージョン : 2.4.16-1.63.amzn1
バージョンアップ後のバージョン : 2.4.23-1.66.amzn1

バージョンアップ後、apacheが起動しないのでerror_logには以下の内容が残っていました。
[Tue Aug 16 19:16:23.815996 2016] [suexec:notice] [pid 3157] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Tue Aug 16 19:16:23.816582 2016] [proxy_hcheck:crit] [pid 3157] AH03262: mod_watchdog is required
AH00016: Configuration Failed

いろいろ調べてみたところ、mod_watchdog.soをloadする必要がありそうです。
元々の設定では読み込んでませんでした。
$ grep watchdog /etc/httpd/conf.modules.d/00-base.conf
#LoadModule watchdog_module modules/mod_watchdog.so

rpmに含まれているるconfでは読み込まれているようです。
$ grep watchdog /etc/httpd/conf.modules.d/00-base.conf.rpmnew 
LoadModule watchdog_module modules/mod_watchdog.so

mod_watchdog.soをloadするようにすると、無事に起動しました。


参考URL
http://forums.fedoraforum.org/showthread.php?t=310826

2016年8月10日水曜日

nginxのせいでDisk Fullになってアクセス不能になった件

正直恥ずかしい話ですし、Disk監視ちゃんと入れておけば防げる話です。

AWSのEC2でnginx動かしていたら、Disk使用率が100%になってレスポンスが返せなくなりました。
原因はnginxが巨大なログファイルを出力していたためなのですが、
dfだとdiskが喰われているのに、/に移動してdu -sh *でディレクトリごとの使用量を見てみても、
どこがdiskを喰っているのかわかりませんでした。

そこで何かのプロセスがファイルをつかんでいるだろうと調べたところ、nginxが巨大なログファイルをつかんでいました。
なぜそれがduでわからなかったかというと、実際のファイルは存在していなかったからです。
nginxの起動ユーザーはec2-userになっていたのですが、nginxはyumでインストールしたものなので、
log出力先のディレクトリのオーナーがnginxユーザーになっており、
ログがローテーとするタイミングで実ファイルへの書き込みができなくなっていて、
その存在しないファイルにずっと出力が続けられていて、ディスクを喰っていた感じです。

まずnginxのプロセスを調べました。
$ps -ef|grep nginx
root      2258     1  0  2015 ?        00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
ec2-user  2259  2258  0  2015 ?        01:06:48 nginx: worker process
ec2-user  2260  2258  0  2015 ?        01:06:14 nginx: worker process
ec2-user  4949  4810  0 22:31 pts/0    00:00:00 grep nginx

プロセスIDが2259が開いているファイルを調べたところ、deletedな巨大なaccess.logが見つかりました。
$sudo lsof -p 2259
COMMAND  PID     USER   FD   TYPE             DEVICE   SIZE/OFF   NODE NAME
nginx   2259 ec2-user    2w   REG              202,1     175662 275456 /var/log/nginx/error.log-20150528 (deleted)
nginx   2259 ec2-user    4w   REG              202,1     175662 275456 /var/log/nginx/error.log-20150528 (deleted)
nginx   2259 ec2-user    5w   REG              202,1 5977988117 275453 /var/log/nginx/access.log-20150528 (deleted)
nginxを再起動すると、diskの空きが増えて、またレスポンスが返せるようになりました。

2016年7月19日火曜日

Recommendifyを入れてみたらちょっとはまった

今更なのですがRecommendifyを試してみて、普通にgem入れようとしたら入らなかったので調べました。
試した環境はMac OSX El Capitanです。

まずは以下の2つをインストール。
brew insert redis
brew insert hiredis

次にGemfileにhiredisとrecommendifyを追加。
gem install hiredis
gem install recommendify

そしてbundle installを実行。
すると、recommendifyが入らなくてエラーになりました。
Installing recommendify 0.3.8 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    /Users/xxx/.rbenv/versions/2.1.3/bin/ruby extconf.rb

make "DESTDIR=" clean
rm -f *.o

make "DESTDIR="
mkdir -p ../bin
gcc -Wall recommendify.c -lhiredis -o ../bin/recommendify
recommendify.c:4:10: fatal error: 'hiredis/hiredis.h' file not found
#include 
         ^
1 error generated.
make: *** [build] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/xxx/yyy/vendor/bundle/ruby/2.1.0/gems/recommendify-0.3.8 for inspection.
Results logged to /Users/xxx/yyy/vendor/bundle/ruby/2.1.0/extensions/x86_64-darwin-14/2.1.0-static/recommendify-0.3.8/gem_make.out
An error occurred while installing recommendify (0.3.8), and Bundler cannot continue.
Make sure that `gem install recommendify -v '0.3.8'` succeeds before bundling.

調べてみたところ、recommendifyをgitからnativeブランチで取得するとよさそうです。
gem install recommendify, git: "https://github.com/danmorin/recommendify.git", branch: "native"
これで無事に入りました。

参考URL
http://blog.naberon.jp/post/2013/09/09/site-recommend/
http://d.hatena.ne.jp/itmsc/20130812/1376289715
http://qiita.com/toyama0919/items/bef2e375e9ebde9a01ba
https://github.com/paulasmuth/recommendify/issues/6

2016年7月6日水曜日

nologinのユーザーをログインできるようにする

ログインできないユーザーをログインできるようにする必要があったので調べました。
usermodでログインシェルを変更できるようです。
cat /etc/passwd | grep test
test:x:501:501::/home/test:/sbin/nologin

usermod -s /bin/bash test

cat /etc/passwd | grep test
test:x:501:501::/home/test:/bin/bash

参考URL
http://server-setting.info/centos/login_user.html

2016年7月1日金曜日

Google Maps APIでMissingKeyMapError出たので調べた

ちょっとgoogle maps apiで出力してる地図を置き換えていたら、
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
でこれまで動かしていた地図は表示されていたのですが、
<script src=”https://maps.googleapis.com/maps/api/js”></script>
を使ったら地図が表示されず、MissingKeyMapErrorがコンソールに出ていました。

google maps apiで調べてみると、呼び出してるJSにはAPIキーがパラメーターで渡せるようですが、
使い方を説明しているページの多くが、APIキーはなくても大丈夫と書いてあったので、
面倒だし取得しないでやろうとしていたら地図が表示されてません。

そして更に調べたところ、2016/06/22からAPIキーは必須になったそうです。
渋々APIキーを取得してパラメーターに入れたところ、ちゃんと地図が表示されました。
現状ではこれが正しい形なようです。(sensor=true|falseはつけなくてよいようです。)
<script src=”https://maps.googleapis.com/maps/api/js?key={APIキー}”></script>

参考URL
http://blog.cloud9works.net/web/how-to-fix-google-map-api-key-error/
https://developers.google.com/maps/documentation/javascript/error-messages#deverrorcodes

2016年6月14日火曜日

hadoop止まらないので調べた

もう使われてないhadoopが動いていて、無駄にログ吐き続けてdiskを喰っていたので
止めようとしたら止まらなかったので調べました。

とりあえず止める系のコマンドをいくつか叩いてみましたが、プロセスは残ったままでした。
$ ./sbin/stop-all.sh 
This script is Deprecated. Instead use stop-dfs.sh and stop-yarn.sh
16/06/13 11:18:15 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Stopping namenodes on [ec2-xx-xx-xx-xx.ap-northeast-1.compute.amazonaws.com]
ec2-xx-xx-xx-xx.ap-northeast-1.compute.amazonaws.com: no namenode to stop
localhost: no datanode to stop
Stopping secondary namenodes [0.0.0.0]
0.0.0.0: no secondarynamenode to stop
16/06/13 11:18:19 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
stopping yarn daemons
no resourcemanager to stop
localhost: no nodemanager to stop
no proxyserver to stop

$ ./sbin/stop-dfs.sh 
16/06/13 11:17:41 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Stopping namenodes on [ec2-xx-xx-xx-xx.ap-northeast-1.compute.amazonaws.com]
ec2-xx-xx-xx-xx.ap-northeast-1.compute.amazonaws.com: no namenode to stop
localhost: no datanode to stop
Stopping secondary namenodes [0.0.0.0]
0.0.0.0: no secondarynamenode to stop
16/06/13 11:17:46 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable

$ ./sbin/stop-yarn.sh 
stopping yarn daemons
no resourcemanager to stop
localhost: no nodemanager to stop
no proxyserver to stop


 ./sbin/hadoop-daemon.sh stop tasktracker
no tasktracker to stop

$ ./sbin/hadoop-daemon.sh stop datanode
no datanode to stop

そこで調べてみたところ、どうやらPIDファイルがなくなってるのが原因っぽいです。
configファイルのPIDまわりの記述を調べてみました。
$ grep PID_DIR etc/hadoop/*
etc/hadoop/hadoop-env.cmd:set HADOOP_PID_DIR=%HADOOP_PID_DIR%
etc/hadoop/hadoop-env.cmd:set HADOOP_SECURE_DN_PID_DIR=%HADOOP_PID_DIR%
etc/hadoop/hadoop-env.sh:export HADOOP_PID_DIR=${HADOOP_PID_DIR}
etc/hadoop/hadoop-env.sh:export HADOOP_SECURE_DN_PID_DIR=${HADOOP_PID_DIR}
etc/hadoop/mapred-env.sh:#export HADOOP_MAPRED_PID_DIR= # The pid files are stored. /tmp by default.
PIDファイルの置き場はデフォルトの/tmpっぽくて、
すでに長期間運用したこのhadoopはtmpwatchですでにpidファイルが削除されているようで、
もうkillするしかなさそうです。ということでkillして停止しました。。。


参考URL
http://masa-cbl.hatenadiary.jp/entry/20121018/1350576124

2016年6月6日月曜日

rspecでFactoryGirlでCarrierWaveのデータを作成する

CarrierWaveのイメージを入れたFactoryGirlのデータを作りたかったので調べました。

テスト用の画像データを以下に置いた状態で、
spec/support/files/test.jpg
以下の形式で記述するとよさげです。

test_image { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'files', 'test.jpg'))



参考URL
http://kzy52.com/entry/2014/01/03/094308

2016年5月30日月曜日

active_adminのcsv出力でxxx_countというカラムが出てこない件

active_adminのデフォルトのcsv出力を使ってとあるテーブルをcsv出力していたら、
xxx_countのカラムが入っていないということで調べました。

とりあえずlocale設定してないからかなと思い、設定してみたもののだめでした。
https://github.com/activeadmin/activeadmin
でcountで何か除外処理とか入ってないかなと思い調べたものの、特に見つかりませんでした。


なので、activeadminのコードでデバッグしてみたところ、
https://github.com/activeadmin/activeadmin/blob/master/lib/active_admin/csv_builder.rb#L22-27
のresource.content_columnsでxxx_countが含まれていませんでした。
    def self.default_for_resource(resource)
      new resource: resource do
        column :id
        resource.content_columns.each { |c| column c.name.to_sym }
      end
    end


で、content_columnsはどこで実装されているのかを調べてくと、
railsのActiveRecordにある処理でした。
http://apidock.com/rails/ActiveRecord/ModelSchema/ClassMethods/content_columns
ここでばっちり_countを取り除いていました。
他に_idも取り除かれていて、csv見たら確かにxxx_idのカラムもありませんでした。

ちなみにcsvと同じ並びにあるxmlやjsonだとxxx_count普通に出てくるので、
activeadminがcsvのときだけcontent_columnsのメソッド使ったのは何でなんでしょうね。。。


参考URL
https://github.com/activeadmin/activeadmin/blob/master/lib/active_admin/csv_builder.rb
https://github.com/activeadmin/activeadmin/issues/4298
http://apidock.com/rails/ActiveRecord/ModelSchema/ClassMethods/content_columns

2016年5月25日水曜日

deviseでfacebookのgraph apiから日本語の名前を取得する

deviseを使ってfacebook認証を実装していて、初期の登録時に
facebookのgraph apiからユーザーの名前を取得していたのですが、
それがローマ字のものが取れていたので、
日本語名を取るにはどこかでlocaleを指定しないといけないのだろうと調べました。

初めにこの辺にたどり着いたので、それを元に実装してみましたが、日本語名は取れませんでした
https://github.com/plataformatec/devise/wiki/How-To:-OmniAuth-inside-localized-scope
https://gist.github.com/gurix/4ed589b5551661c1536a

次にたどり着いたのがこのあたりのページで、ここの内容を参考に
omniauthの設定にlocaleを設定したら、無事に日本語名が取れるようになりました。
http://qiita.com/eleven_2012/items/d8ef22a8928c65570b82
https://teratail.com/questions/25290

設定したのはこんな感じです
config.omniauth :facebook, '#{facebook ID}', '#{key}', locale: 'ja_JP', provider_ignores_state: true, scope: 'email, public_profile'

2016年5月20日金曜日

bundle exec rails sが起動しなかった

bundle exec rails sが突然起動しなくなったので調べました。

環境は以下です。
Mac 10.11.4
ruby 2.1.3
rails 4.1.6

bundle exec rails sすると微動だにしなくCtrl+Cをやっても返ってこない状態になりました。
プロセスは起動していたので、killして止めることはできました。

調べたところ、springがおかしいかもということで、
springを停止してみました。
$ bundle exec bin/spring status
Spring is running:

 3134 spring server | kidsline | started 15 hours ago  
 7517 spring app    | kidsline | started 8 secs ago | development mode
 
$ bundle exec bin/spring stop
Spring stopped.

$ bundle exec bin/spring status
Spring is not running.

springを止めた上でstartすると、無事に起動しました。
$ bundle exec rails s
Resque::Helpers will be gone with no replacement in Resque 2.0.0.
=> Booting WEBrick
=> Rails 4.1.6 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
=> Ctrl-C to shutdown server
[2016-05-18 11:32:31] INFO  WEBrick 1.3.1
[2016-05-18 11:32:31] INFO  ruby 2.1.3 (2014-09-19) [x86_64-darwin14.0]
[2016-05-18 11:32:31] INFO  WEBrick::HTTPServer#start: pid=12814 port=3000

参考URL
http://qiita.com/rojiuratech/items/759c2d62907a2a36e340

2016年4月26日火曜日

rubyのHashでeach_with_indexの使い方

rubyのHashでeach_with_index使う時に調べててなるほどと思ったので書きました。
まずはこういうHashがあるとします。
test = { english: 100, japanese: 90 }

普通にeach_with_indexを使うとこんな感じになるかと思います。
test.each_with_index do |obj, index|
 p obj
 p obj.class
 p index
end

[:english, 100]
Array
0
[:japanese, 90]
Array
1
この形だとせっかくHashなのにkeyとvalueを分けて取れないので以下のようにやるとよいようです。
test.each_with_index do |(key, val), index|
 p key
 p val
 p index
end

:english
100
0
:japanese
90
1
これは知らなかったのですごく便利。

参考URL
http://bismar.hatenablog.com/entry/2012/12/01/215111

2016年4月19日火曜日

rubyの日付をeachでまわす

rubyで特定の日付から数日分eachでループでまわしたいときがあって、
それをやるのに2度も同じところではまったので備忘メモです。

まずはダメなパターン
(Time.now..(Time.now + 6.days)).each do |day|
 p day
end

こっちはOKなパターン
(Date.today..(Date.today + 6.days)).each do |day|
  p day
end

Timeは数値ではないので、離散形式でテストされる。 しかしTimeを用いた範囲は離散範囲ではない。
ということで、Timeではだめなので、やるときにはDateでやるか、
eachじゃない回し方をするのがよさそうです。

参考URL
http://sekai.hateblo.jp/entry/2013/10/23/081950

2016年3月31日木曜日

active_adminのscopeに設定したものが表示されない

active_adminのscopeに設定したものが表示されないと隣の席の人が言ってたので調べました

元々こうなっていました。
scope 'aaa', :need_aaa, default: false
  scope 'いいい', :need_iii, default: false

そこに以下のものを追加してたのですが、元々あった'いいい'の部分が表示されなくなってしまいました。
scope 'ううう', :need_uuu, default: false
調べたところ、scopeに日本語使ってるため表示されなくなったようです。
日本語の部分をとりあえず英語に変えたらうまく表示されるようになりました。

参考URL
http://qiita.com/SpicyCoffee/items/7b7060b93811be389893

2016年3月18日金曜日

zabbix-agentを2.2から2.4にあげようとしたらはまった件

zabbix-agentを2.2から2.4にあげようとしたら、yumで2.4にできなくてはまったときの話

対象サーバー : ec2 AmazonLinux

まず元々入っていたバージョンが2.2系でした。
$sudo yum list installed|grep zabbix
zabbix.x86_64                         2.2.8-1.el6                  @zabbix      
zabbix-agent.x86_64                   2.2.8-1.el6                  @zabbix      
zabbix-release.noarch                 2.2-1.el6                    installed  

3つのRPMを削除
$sudo yum list installed|grep zabbix

レポジトリを2.4用に更新
$sudo rpm -ivh http://repo.zabbix.com/zabbix/2.4/rhel/6/x86_64/zabbix-release-2.4-1.el6.noarch.rpm
$sudo yum list installed|grep zabbix
zabbix-release.noarch                 2.4-1.el6                    installed 

yum installを実行してみるが2.2.11が対象としてあがってくる
$sudo yum install zabbix-agent
読み込んだプラグイン:priorities, update-motd, upgrade-helper
10 packages excluded due to repository priority protections
依存性の解決をしています
--> トランザクションの確認を実行しています。
---> パッケージ zabbix-agent.x86_64 0:2.2.11-1.el6 を インストール
--> 依存性の処理をしています: zabbix のパッケージ: zabbix-agent-2.2.11-1.el6.x86_64
--> トランザクションの確認を実行しています。
---> パッケージ zabbix.x86_64 0:2.2.11-1.el6 を インストール
--> 依存性解決を終了しました。

依存性を解決しました

==============================================================================================================================================================================================================
 Package                                             アーキテクチャー                              バージョン                                             リポジトリー                                   容量
==============================================================================================================================================================================================================
インストール中:
 zabbix-agent                                        x86_64                                        2.2.11-1.el6                                           zabbix                                        158 k
依存性関連でのインストールをします:
 zabbix                                              x86_64                                        2.2.11-1.el6                                           zabbix                                        152 k

トランザクションの要約
==============================================================================================================================================================================================================
インストール  1 パッケージ (+1 個の依存関係のパッケージ)

総ダウンロード容量: 310 k
インストール容量: 1.0 M
Is this ok [y/d/N]: N
Exiting on user command
Your transaction was saved, rerun it with:
 yum load-transaction /tmp/yum_save_tx.2016-03-16.12-11.QSikpz.yumtx

/etc/yum.repos.d/zabbix.repoに書かれているGPG鍵を削除
$cat /etc/yum.repos.d/zabbix.repo 
[zabbix]
name=Zabbix Official Repository - $basearch
baseurl=http://repo.zabbix.com/zabbix/2.4/rhel/6/$basearch/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX

[zabbix-non-supported]
name=Zabbix Official Repository non-supported - $basearch 
baseurl=http://repo.zabbix.com/non-supported/rhel/6/$basearch/
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX
gpgcheck=1

$ls -al /etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX 
-rw-r--r-- 1 root root 1332  9月 11  2014 /etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX

$sudo rm /etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX
$ls -al /etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX 

zabbixのyumリポジトリ設定を一度消して、再度インストール
$sudo yum remove zabbix-release.noarch
$sudo rpm -ivh http://repo.zabbix.com/zabbix/2.4/rhel/6/x86_64/zabbix-release-2.4-1.el6.noarch.rpm

yum installを実行すると無事に対象が2.4にあがっていました。
$sudo yum install zabbix-agent
読み込んだプラグイン:priorities, update-motd, upgrade-helper
zabbix/x86_64                                                                                                                                                                          |  951 B     00:00     
zabbix/x86_64/primary                                                                                                                                                                  |  23 kB     00:00     
zabbix                                                                                                                                                                                                145/145
zabbix-non-supported/x86_64                                                                                                                                                            |  951 B     00:00     
10 packages excluded due to repository priority protections
依存性の解決をしています
--> トランザクションの確認を実行しています。
---> パッケージ zabbix-agent.x86_64 0:2.4.7-1.el6 を インストール
--> 依存性の処理をしています: zabbix のパッケージ: zabbix-agent-2.4.7-1.el6.x86_64
--> トランザクションの確認を実行しています。
---> パッケージ zabbix.x86_64 0:2.4.7-1.el6 を インストール
--> 依存性解決を終了しました。

依存性を解決しました

==============================================================================================================================================================================================================
 Package                                              アーキテクチャー                               バージョン                                          リポジトリー                                    容量
==============================================================================================================================================================================================================
インストール中:
 zabbix-agent                                         x86_64                                         2.4.7-1.el6                                         zabbix                                         173 k
依存性関連でのインストールをします:
 zabbix                                               x86_64                                         2.4.7-1.el6                                         zabbix                                         163 k

トランザクションの要約
==============================================================================================================================================================================================================
インストール  1 パッケージ (+1 個の依存関係のパッケージ)

総ダウンロード容量: 336 k
インストール容量: 1.1 M
Is this ok [y/d/N]: N
Exiting on user command
Your transaction was saved, rerun it with:
 yum load-transaction /tmp/yum_save_tx.2016-03-16.14-47.04eYn1.yumtx

2016年3月3日木曜日

wordpressでサブディレクトリにアクセスできない

誰が作ったかわからないwordpressをもう一台(しかも人の作業途中から)作る必要があったのですが、
とりあえず同じような設定で構築したものでルートドメインにはアクセスできるものの、
サブディレクトリにはアクセスできませんでした。

httpd.confを見ても元と同じで問題なさそうだったのですが、
調べてくと.htaccessにも設定があって、新しい方にはそれが置いてなくてだめだったようです。
.htaccessにはこんな設定が書いてありました。。

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]


# END WordPress

wordpressさわるときは.htaccessも忘れないように


参考URL
http://www.seohacks.net/basic/knowledge/subdomain-subdirectly/
http://tetokon.com/2012/09/18/wordpress_permalink_404/
http://oxynotes.com/?p=7392

2016年2月26日金曜日

itamaeでrbenv入れるのにはまった恥ずかしい話

ec2でrbenv入れるのにitamaeで入れようとしてたのですが、
rbenvのインストール手順を普通になぞっていったら地味にはまってしまいました。

最初に書いたレシピはこんな感じ
rbenv/default.rb
%w(
  git
  gcc-c++
  glibc-headers
  openssl-devel
  readline
  libyaml-devel
  readline-devel
  zlib
  zlib-devel
  libffi-devel
  libxml2
  libxslt
  libxml2-devel
  libxslt-devel
  sqlite-devel
  mysql-devel
  patch
).each do |pkg|
  package "#{pkg}" do
    action :install
  end
end

git '/usr/local/rbenv' do
  repository 'https://github.com/sstephenson/rbenv.git'
end

directory "/urs/local/rbenv/plugins" do
  action :create
end

git '/usr/local/rbenv/plugins/ruby-build' do
  repository 'https://github.com/sstephenson/ruby-build.git'
end

remote_file "/etc/profile.d/rbenv.sh" do
  action :create
  source "files/etc/profile.d/rbenv.sh"
  owner 'root'
  group 'root'
  mode '644'
end

execute 'install ruby' do
  command("source /etc/profile.d/rbenv.sh; rbenv install 2.3.0")
  command("source /etc/profile.d/rbenv.sh; rbenv global 2.3.0; rbenv rehash")
end

実行してみるとこんな感じ
$ bundle exec itamae ssh -i pem/test.pem -h 172.31.21.186 roles/test.rb
 INFO : Starting Itamae...
 INFO : Recipe: /home/ec2-user/deploy/xxx/roles/test.rb
 INFO :   Recipe: /home/ec2-user/deploy/xxx/cookbooks/rbenv/default.rb
 INFO :     package[git] installed will change from 'false' to 'true'
 INFO :     package[gcc-c++] installed will change from 'false' to 'true'
 INFO :     package[openssl-devel] installed will change from 'false' to 'true'
 INFO :     package[libyaml-devel] installed will change from 'false' to 'true'
 INFO :     package[readline-devel] installed will change from 'false' to 'true'
 INFO :     package[libffi-devel] installed will change from 'false' to 'true'
 INFO :     package[libxml2-devel] installed will change from 'false' to 'true'
 INFO :     package[libxslt-devel] installed will change from 'false' to 'true'
 INFO :     package[sqlite-devel] installed will change from 'false' to 'true'
 INFO :     package[mysql-devel] installed will change from 'false' to 'true'
 INFO :     package[patch] installed will change from 'false' to 'true'
 INFO :     git[/usr/local/rbenv] exist will change from 'false' to 'true'
 INFO :     directory[/urs/local/rbenv/plugins] exist will change from 'false' to 'true'
 INFO :     git[/usr/local/rbenv/plugins/ruby-build] exist will change from 'false' to 'true'
 INFO :     remote_file[/etc/profile.d/rbenv.sh] exist will change from 'false' to 'true'
 INFO :     remote_file[/etc/profile.d/rbenv.sh] mode will be '0644'
 INFO :     remote_file[/etc/profile.d/rbenv.sh] owner will be 'root'
 INFO :     remote_file[/etc/profile.d/rbenv.sh] group will be 'root'
 INFO :     diff:
 INFO :     --- /dev/null 2016-02-25 02:37:28.211836042 +0000
 INFO :     +++ /tmp/itamae_tmp/1456368153.1309056 2016-02-25 02:42:33.144609603 +0000
 INFO :     @@ -0,0 +1,3 @@
 INFO :     +export RBENV_ROOT=/usr/local/rbenv
 INFO :     +export PATH="$RBENV_ROOT/bin:$PATH"
 INFO :     +eval "$(rbenv init -)"
 INFO :     execute[install ruby] executed will change from 'false' to 'true'

正常に終わったように見えてるが、rubyのバージョンが変わってない。。。
$ruby -v
ruby 2.0.0p648 (2015-12-16) [x86_64-linux]

レシピのrubyインストール部分を以下のようにコマンドを分割する形に修正
rbenv/default.rb
execute 'install ruby' do
  command("source /etc/profile.d/rbenv.sh; rbenv install 2.3.0")
end

execute 'set ruby global' do
  command("source /etc/profile.d/rbenv.sh; rbenv global 2.3.0; rbenv rehash")
end

再度実行してみる
$ bundle exec itamae ssh -i pem/test.pem -h 172.31.21.186 roles/test.rb
 INFO : Starting Itamae...
 INFO : Recipe: /home/ec2-user/deploy/xxx/roles/test.rb
 INFO :   Recipe: /home/ec2-user/deploy/xxx/cookbooks/rbenv/default.rb
 INFO :     execute[install ruby] executed will change from 'false' to 'true'
 INFO :     execute[set ruby global] executed will change from 'false' to 'true'

ちゃんとrubyのバージョンがrbenvで入れたものに変わりました
$ ruby -v
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]


参考URL
http://qiita.com/fukuiretu/items/337e6ae15c1f01e93ec3

2016年2月16日火曜日

simplecovでrspecのテスト書いているのにカバレッジ0%のクラスがある

simplecovを使ってrailsのカバレッジを計測しているのですが、
異常に数値が低いなと思い、詳細を見ていったところ、
rspec書いているのに0%になっているクラスがいたので調べてみました。

修正前のrails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rails'
require 'simplecov'
require 'simplecov-rcov'
〜
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
SimpleCov.start 'rails'

修正後のrails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'simplecov'
require 'simplecov-rcov'
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
SimpleCov.start 'rails'

require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rails'
〜

最初はsimplecovのrequireをrequireの中で一番下に書き、
rails_helper.rbの末尾のところでSimpleCov.startさせていました。
調べたところどうやら他のモジュールが読み込まれるよりも先に
simplecovを読み込ませるようにしないといけないようです。
カバレッジ0%だったものが修正後のものではちゃんと計測できていました。


参考URL
https://github.com/colszowka/simplecov/issues/77

2016年2月9日火曜日

railsで指定したid順にDBから取得する

railsで指定したidの順番でDBから取得したかったので調べました。
このやりかたはDBがMySQLのときしか使えないようです。

idlist = [3, 8 ,2 ,4 ,6]

users = users.order("field(id, #{idlist.join(',')})")

参考URL
http://qiita.com/corin8823/items/318220f6f1b14a1bb7ba
http://qiita.com/takuya-i/items/a7ef5105952e32f1affd

2016年2月6日土曜日

FactoryGirlでシリアライズしたデータを登録する

DBにHashをシリアライズしたものを文字列として保存していて、
そのテストデータをFactoryGirlで作りたくて調べました。

migration
class User < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.text :info
    end
  end
end

model
class User < ActiveRecord::Base
  serialize :info
end

最初に以下のようなStringで入れてみたりしましたがダメでした。
"{ memo1: 'memo', memo2: 'memo2', count: 2 }"

調べたところ、()や{}で囲えばよいようです
factory
require 'faker'
FactoryGirl.define do
  factory :user do
    id 1
    name 'Taro'
    info ({ memo1: 'memo', memo2: 'memo2', count: 2 })
  end
end

参考URL
http://www.rubycoloredglasses.com/2012/06/add-a-serialized-hash-attribute-to-a-factory_girl-definition/

2016年1月26日火曜日

daemon系プロセスでのファイルディスクリプタを一律で設定する

fluentdを入れる際にファイルディスクリプタの値を増やしたほうがいいと書いてあったので、
/etc/security/limits.confに書いたのですが、daemonとして立ち上げたときに
設定が効いてなかったので調べました。

検証環境
Amazon Linux AMI 2015.09

まずは現在のファイルディスクリプタの値とdaemonでの状態を確認
$ ulimit -n
1024

$ sudo service httpd start
Starting httpd:                                            [  OK  ]

$ chkconfig --list httpd
httpd           0:off 1:off 2:on  3:on  4:on  5:on  6:off

$ cat /proc/`pgrep httpd | head -1`/limits | grep 'open files'
Max open files            1024                 4096                 files

ulimitでファイルディスクリプタを設定して、手動で起動するとその設定値になります。
$ ulimit -n 4048
$ ulimit -n
4048

$ cat /proc/`pgrep httpd | head -1`/limits | grep 'open files'
Max open files            4048                 4048                 files

rebootすると戻ります。
$ cat /proc/`pgrep httpd | head -1`/limits | grep 'open files'
Max open files            1024                 4096                 files

調べたところ、/etc/sysconfig/initがdaemonでのプロセス起動時に実行されるようなので、
ここでulimitを実行するように追記しました。
$ sudo vim /etc/sysconfig/init 
$ tail -1 /etc/sysconfig/init 
ulimit -n 4048

rebootしても元に戻らないようになりました。
$ cat /proc/`pgrep httpd | head -1`/limits | grep 'open files'
Max open files            4048                 4048                 files


参考URL
http://staffblog.yumemi.jp/%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%83%87%E3%82%A3%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%97%E3%82%BF%E6%95%B0%E3%81%AE%E4%B8%8A%E9%99%90%E5%A4%89%E6%9B%B4%E3%81%A8limits-conf%E3%81%AE%E7%BD%A0-2/
http://d.hatena.ne.jp/akishin999/20130213/1360711554

2016年1月23日土曜日

RPM入れるときに使うGPG鍵を削除したい

RPMを入れる際にサードパーティのリポジトリを使うことがありますが、
そのときに入れたGPG鍵を削除する必要があったので調べました。

まず現在入れてあるGPG鍵を確認
$rpm -q gpg-pubkey --qf '%{name}-%{version}-%{release} --> %{summary}\n'
gpg-pubkey-21c0f39f-4e41dbdc --> gpg(Amazon Linux AMI (GA) )
gpg-pubkey-79ea5ed4-508d25a6 --> gpg(Zabbix SIA )
gpg-pubkey-a12e206f-52aecba3 --> gpg(Treasure Data, Inc (Treasure Agent Official Signing key) )

GPG鍵を削除
rpm -e gpg-pubkey-a12e206f-52aecba3

$rpm -q gpg-pubkey --qf '%{name}-%{version}-%{release} --> %{summary}\n'
gpg-pubkey-21c0f39f-4e41dbdc --> gpg(Amazon Linux AMI (GA) )
gpg-pubkey-79ea5ed4-508d25a6 --> gpg(Zabbix SIA )


参考URL
https://www.pochio.net/docs/linux/rpmrepo_gpgsign.html

2016年1月12日火曜日

gitで初回コミットを取り消す

コミットの粒度を考えずにサーバー上で勢いで大量にコミットしてしまったので、
ちゃんと細かく分けようとしてそのコミットを取り消そうとしたら、
最初のコミットだったのでgit resetで取り消せなくて困ったので調べました

消したいのはこのコミットです
$ git log
commit 9b5b12136372fe28ed73fec13df1268b58370d6c
Author: EC2 Default User 
Date:   Thu Dec 10 03:03:39 2015 +0000

    ssh経由でのテスト挙動確認

パッと思いつく限りの直前のコミットを取り消すコマンドを実行したのですが、
すべてエラーになったり消せなかったりしました。
$ git reset 9b5b12136372fe28ed73fec13df1268b58370d6c
$ git log
commit 9b5b12136372fe28ed73fec13df1268b58370d6c
Author: EC2 Default User 
Date:   Thu Dec 10 03:03:39 2015 +0000

$ git reset HEAD^
fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git  [...] -- [...]'

$ git reset --soft
$ git log
commit 9b5b12136372fe28ed73fec13df1268b58370d6c
Author: EC2 Default User 
Date:   Thu Dec 10 03:03:39 2015 +0000

$ git reset --soft HEAD^
fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git  [...] -- [...]'

調べたところ、このコマンドで初回コミットでもちゃんと消せるようです。
$ git update-ref -d HEAD

$ git log
fatal: bad default revision 'HEAD'


参考URL
http://suzuken.hatenablog.jp/entry/2014/03/28/100311