人生シーケンスブレイク

シーケンスブレイク(Sequence breaking、シークエンスブレイクとも)とは、テレビゲームにおいて開発が想定している攻略ルートを逸脱し、ショートカットする行為のことである。

Rails5で、Railsコンソールでupdated_atを更新せずにカラムを更新する

環境

状況

  • インターネットで調べた User.record_timestamps = false などを行っても、updated_atが更新されてしまった。
  • mysqlのテーブル情報を確認したら、ON UPDATE CURRENT_TIMESTAMP が付いていた。
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

対応

updated_at カラムに直接元のupdated_atを指定するSQLを実行したらupdated_atを更新せずに更新できた。

User.connection.execute("UPDATE users SET published_at = created_at, updated_at = updated_at WHERE published_at IS NULL")

メタプログラミングRuby

メタプログラミングRuby

使わないiOS Simulatorを削除する

Xcode上で古いiOS Simulatorが残ったままになっている為、手動で削除する。

f:id:ShineSpark:20180309150323p:plain

ここに古いSimulatorが残っている状態なのを解消する。

Runtimeを削除する

/Library/Developer/CoreSimulator/Profiles/Runtimes から、不要なシミュレータのバージョンのディレクトリを削除する。 rmtrash を使っている人はrmをシングルクォートで括って実行しよう。

/Library/Developer/CoreSimulator/Profiles/Runtimes $ sudo 'rm' -rf iOS\ 10.1.simruntime/
/Library/Developer/CoreSimulator/Profiles/Runtimes $ sudo 'rm' -rf iOS\ 10.3.simruntime/

シミュレータ環境の削除

~/Library/Developer/Xcode/iOS DeviceSupport にもバージョンごとにディレクトリが作成されているので、ここも削除する。

~/Library/Developer/Xcode/iOS DeviceSupport $ ll
total 0
drwxr-xr-x   6 user  staff   192B  1 25 14:41 ./
drwxr-xr-x  32 user  staff   1.0K  1 24 15:48 ../
drwxr-xr-x   5 user  staff   160B  1 25 12:00 11.2 (15C114)/
drwxr-xr-x   5 user  staff   160B  1  5 15:42 11.2.1 (15C153)/
drwxr-xr-x   5 user  staff   160B  1 16 12:55 11.2.2 (15C202)/
drwxr-xr-x   5 user  staff   160B  1 25 12:49 11.2.5 (15D60)/

自分は一度まっさらな状態にしたかったので全て消した。

~/Library/Developer/Xcode/iOS DeviceSupport $ rm 11.2*

確認

Xcodeを再起動して、Simulator一覧を確認したら、古いバージョンのものが削除されていることを確認。

f:id:ShineSpark:20180309150323p:plain

ビルド対象の一覧からも、不要なものが削除されていることを確認した。
(シミュレータ起動時に自動で再作成される)

f:id:ShineSpark:20180309154740p:plain

参考

特定ディレクトリ配下のgitリポジトリのみ別のconfig設定を適用する

デフォルトはGitHub用の設定を利用しているが、会社で利用しているGitLabだけhttp.proxyを適用したい際に以下の方法で実現した。

前提

以下のようなディレクトリ構成を想定

~/git/
├── GitHubのリポジトリ1
├── GitHubのリポジトリ2
├── ...
└── office/ # このディレクトリ配下のみ別の git config を適用したい
    ├── 会社用のリポジトリ1
    ├── 会社用のリポジトリ2
    └── ...

手順

~/.gitconfig に以下の設定を追記する

[includeIf "gitdir:~/git/office/"]
  path = ~/git/office/.gitconfig

会社用の設定を .gitconfig ファイルに記述する

このケースでは、 ~/git/office/.gitconfig に記述する。 以下の記述内容は例。

[user]
    name = <name>
    email = name@example.com
[http]
    proxy = proxy.example.com:8080

使う

~/git/office/ 以下では、~/git/office/.gitconfig の設定もインクルードされる。

リポジトリ単位で個別に設定する必要がなくなるので非常に便利。

参考: Git - git-config Documentation

わかばちゃんと学ぶ Git使い方入門〈GitHub、Bitbucket、SourceTree〉

わかばちゃんと学ぶ Git使い方入門〈GitHub、Bitbucket、SourceTree〉

  • 作者:湊川 あい
  • 発売日: 2017/04/21
  • メディア: 単行本(ソフトカバー)

Ubuntuでsudo apt-get -y upgradeするとdialogで止まる

概要

Packer で Ubuntu AMI を作成しようとしたら、 apt-get -y upgrade で処理が止まって困った時の解決方法。 もしかしたら Docker や Ansible でも出るのではないか。

{
  "variables": {
    "aws_access_key": "{{env `AWS_ACCESS_KEY_ID`}}",
    "aws_secret_key": "{{env `AWS_SECRET_ACCESS_KEY`}}",
    "region": "ap-northeast-1"
  },
  "builders": [{
    "type": "amazon-ebs",
    "access_key": "{{user `aws_access_key`}}",
    "secret_key": "{{user `aws_secret_key`}}",
    "region": "{{user `region`}}",
    "source_ami_filter": {
      "filters": {
        "virtualization-type": "hvm",
        "name": "ubuntu/images/*ubuntu-xenial-16.04-amd64-server-*",
        "root-device-type": "ebs"
      },
      "owners": ["099720109477"],
      "most_recent": true
    },
    "instance_type": "m3.medium",
    "ssh_username": "ubuntu",
    "ssh_timeout": "5m",
    "ami_name": "AMI/ubuntu/{{isotime | clean_ami_name}}"
  }],
  "provisioners": [{
    "type": "shell",
    "inline": [
      "sudo apt-get update",
      "sudo apt-get upgrade -y", # ここで止まる
      "sudo apt-get install -y python3-pip",
      "(略)"
    ]
  }]
}

確かにサーバーに直接ログインし、 apt-get upgrade -y したらインタラクティブな画面になってしまい、コマンド操作不能な状況になっていた。
これはヒドい。

対応方法

sudo apt-get upgrade -y ではなく、 sudo DEBIAN_FRONTEND=noninteractive apt-get upgrade -yq を使う。

参考:

うぶんちゅ! (電撃コミックスEX)

うぶんちゅ! (電撃コミックスEX)

Amazon LinuxでConfluenceのマクロの豆腐文字化けを直す。

概要

Amazon LinuxでConfluence 6.6.1をインストールしたら、

Confluence のマクロで日本語が表示されない - Atlassian Documentation や、 Docker ComposeでConfluenceを構築する - Qiita の対応を行っても文字化けが解消されなかったのだが、以下の方法で解消されたので記録。

インストール状況

  • service起動する為に、実行バイナリ版を sudo 付きでインストール
  • その為、java実行環境はOSのものではなくConfluence同梱の /opt/atlassian/confluence/jre

対応方法

例によって ipa-gothic をインストール

$ sudo yum install -y ipa-gothic-fonts

/opt/atlassian/confluence/bin/setenv.shに追記指定するパスは、 fallbackにフォントをコピーだったりシンボリックリンクでなく、直接 /usr/share/fonts/ipa-gothic/ を指定する。

CATALINA_OPTS="-Dconfluence.document.conversion.fontpath=/usr/share/fonts/ipa-gothic/ ${CATALINA_OPTS}"

これで Confluence を再起動すると、マクロのタイトル部分の文字化けが解消する。

CONFLUENCE

CONFLUENCE

  • アーティスト:NOB
  • 発売日: 2017/11/22
  • メディア: CD

Raspberry Pi3 に mackerel をインストールする

ダウンロードと配置

Releases · mackerelio/mackerel-agent · GitHub からARM用のソースコードをダウンロードする

$ wget https://github.com/mackerelio/mackerel-agent/releases/download/v0.47.1/mackerel-agent_linux_arm.tar.gz
$ tar xvzf ./mackerel-agent_linux_arm.tar.gz

任意の場所に配置して実行すると、 open /etc/mackerel-agent/mackerel-agent.conf: no such file or directory と怒られるので /etc/mackerel-agent に配置する。

$ sudo mv mackerel-agent_linux_arm /etc/mackerel-agent

# API キーの登録
$ sudo /etc/mackerel-agent/mackerel-agent init -apikey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

systemctl への登録

手動だと辛いので、 systemctl に登録する。

[Unit]
Description=mackerel-agent

[Service]
Type=simple
WorkingDirectory=/etc/mackerel-agent
ExecStart=/etc/mackerel-agent/mackerel-agent --conf=/etc/mackerel-agent/mackerel-agent.conf
TimeoutStopSec=5
StandardOutput=null
User=root
Group=root

[Install]
WantedBy = multi-user.target
# 有効化
$ sudo systemctl enable mackerel-agent

# 起動
$ sudo systemctl start mackerel-agent

数分して mackerel にデータが流れていればOK.

f:id:ShineSpark:20171116210504p:plain

参考

DB接続を伴わないRailsのヘルスチェックを実装する

あらすじ

Rails でDBがコケていたとしても、単体では動作していることをヘルスチェックで確認したかった。

Controller での実装の場合

こんなコントローラを書いたとする。

class HealthcheckController < ApplicationController  
  def index
    User.first
    render plain: 'Still Alive'
  rescue => e
    render plain: 'Not Still Alive', status: :internal_server_error
  end
end  

が、DBに接続できない時には、これ以前のMySQL serverへの接続の所でコケる(DBがMySQLの場合)。

f:id:ShineSpark:20170822003416p:plain

Action Dispatcherのミドルウェアスタック

Rails では Action Dispatcher を通して middleware の仕組みがある。

Rails on Rack — Ruby on Rails Guides

その為、MySQLに接続の前の middleware にヘルスチェックをする為のロジックを挿入すればよい。 ちなみに今呼ばれている middleware の一覧は、rails console から以下のコマンドで確認できる。

$ rails middleware
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use Rack::Runtime
use Rack::MethodOverride
use ActionDispatch::RequestId
use Sprockets::Rails::QuietAssets
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use WebConsole::Middleware
use ActionDispatch::DebugExceptions
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use Warden::Manager
run <Railsプロジェクト名>::Application.routes

または 

irb(main):010:0> <Railsプロジェクト名>::Application.config.middleware
=> #<ActionDispatch::MiddlewareStack:0x00563448c71938 @middlewares=[Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, ActiveSupport::Cache::Strategy::LocalCache::Middleware, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Sprockets::Rails::QuietAssets, Rails::Rack::Logger, ActionDispatch::ShowExceptions, WebConsole::Middleware, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETag, Warden::Manager]>

Action Dispatcherのミドルウェアスタックを利用したヘルスチェックの実装

コントローラーを特に書かずに、 app/middleware/healthcheck.rb を作成し、以下のように記述する

class Healthcheck  
  OK_RESPONSE = [ 200, { 'Content-Type' => 'text/plain' }, "Still Alive" ]

  def initialize(app)
    @app = app
  end

  def call(env)
    if env['PATH_INFO'] == '/health'
      return OK_RESPONSE
    else
      @app.call(env)
    end
  end
end  

config/application.rb に以下を追記する。

    config.middleware.insert_before 'ActionDispatch::ShowExceptions', 'Healthcheck'

ここでは、例外を発生させる ActionDispatch:ShowExceptions より前にこの middleware を追加している。 middleware の中では、 /health パスの時に限り、以降の処理を行わず Still Alive を返し、他にパスの時には通常通り処理を継続するようにする。
routes.rb に /health を書く必要はないが、何らかコメントして置いた方が他の人がハマりにくいと思う。

確認

Rails 再起動してDBだけ停止させた上で localhost/health にアクセスしてみる。

f:id:ShineSpark:20170822010607p:plain

OK。

参考