パパエンジニアのアウトプット帳

30歳に突入した1児のパパエンジニアのブログ

postgresqlのクライアントだけをMacにインストールする

下記のstackoverflowの通りなんだけど、Mac新しくなると忘れそうなのでメモ。 Docker使うようになってホスト側にPostgresqlとか入れなくなったので、クライアントだけ欲しい感じです。

stackoverflow.com

$ brew install libpq
$ vi ~/.zshrc
---PATHに追加---
export PATH="/usr/local/opt/libpq/bin:$PATH"

AWS Elasticsearch Serviceの監視項目

初めてElasticsearchを実運用するので監視は何を見ればいいのかと思ったのですが、調べてみると公式ドキュメントにあるのでそれを参照するだけです。はい。

https://docs.aws.amazon.com/ja_jp/elasticsearch-service/latest/developerguide/cloudwatch-alarms.html

AWS EBSのボリュームサイズ変更をやった

やったと言っても、クラメソさんの下記のブログの通りにやっただけなんですねどねっていう。

dev.classmethod.jp

今回の対象はAmazonLinux1だったので下記のコマンドを実行した。

# 現状の確認
$ df -h 
$ lsblk

# パーミッション拡張
$ sudo growpart /dev/xvda 1
# ファイルシステム拡張
$ sudo resize2fs /dev/xvda1

# 拡張の確認
$ df -h 
$ lsblk

TypescriptをES2015+なJSにコンパイルするtsconfig.json

下記のようなtsconfig.jsonにしたらES2015+(今回の場合は正しくはES2016なんだけど)なjavascriptコンパイルできたっぽい。(Typescript入門したてで自信ない
moduleのコメントにES6なんてのはないけど、ドキュメントには書いてある。
試しにmoduleをes2015にしてみたが、自分の今回試したファイルではコンパイルされたjavascriptに特に差分は無かった。

{
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "ES2016",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "ES6",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [], /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  }
}

Typescriptちゃんと勉強せねば。

プライベートなVPC内のEC2にSession Managerで接続する

Internet GatewayすらアタッチされていないVPCにSession Managerで接続するにはVPCエンドポイントを設定すればいいんだろうなとは思っていたが実際にはやったことないので試してみた。


セットアップは公式に書いてある通り大体やればいいのだけど、それでできなくてちょっとハマった。 docs.aws.amazon.com

というのも、この通りやっても何故かSession Managerで接続できず探していたら下記のQ&Aを見つけた。

aws.amazon.com

手順5のVPCエンドポイントを作成する手順のこの一文。

[Enable Private DNS Name] で [Enable for this endpoint] を選択します。

これだ!!
これを設定するにはVPCの「DNS 解決」と「DNS ホスト名」の両方が有効になってないと、VPCエンドポイントの「プライベート DNS 名を有効にする」を有効にできないので、そのように設定したらSession Managerで接続することが出来るようになった。



一応、terraformでも書いてみた。
GitHub - masaru-tech/ssm-private-ec2-terraform: プライベートなVPCにあるEC2にSession Managerで接続出来るようにする構成

相変わらず、コンソールで操作→terraform import→terraform planで差分がなくなるまで修正が面倒。
この作業はしょうがないと自分では思っているが、世のterraformer達はもっと良いやり方とか知っているのだろうか?

ALBのログをAthenaで検索するために

Athenaのコンソールでテーブル定義ポチポチするの面倒だなーと思ったら公式ドキュメントにそのまま実行できるCREATE TABLEコマンドがあった。

docs.aws.amazon.com

DATABASEも分けておきたいので、CREATE DATABASE文も一緒に書いておく。

あとデフォルトだと全ログが対象になってしまうので、対象の日付が分かっているならその日付のLOCATIONを設定する方がお財布に優しい。

CREATE DATABASE elb_production;

CREATE EXTERNAL TABLE IF NOT EXISTS alb_logs (
            type string,
            time string,
            elb string,
            client_ip string,
            client_port int,
            target_ip string,
            target_port int,
            request_processing_time double,
            target_processing_time double,
            response_processing_time double,
            elb_status_code string,
            target_status_code string,
            received_bytes bigint,
            sent_bytes bigint,
            request_verb string,
            request_url string,
            request_proto string,
            user_agent string,
            ssl_cipher string,
            ssl_protocol string,
            target_group_arn string,
            trace_id string,
            domain_name string,
            chosen_cert_arn string,
            matched_rule_priority string,
            request_creation_time string,
            actions_executed string,
            redirect_url string,
            lambda_error_reason string,
            new_field string
            )
            ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
            WITH SERDEPROPERTIES (
            'serialization.format' = '1',
            'input.regex' = 
        '([^ ]*) ([^ ]*) ([^ ]*) ([^ ]*):([0-9]*) ([^ ]*)[:-]([0-9]*) ([-.0-9]*) ([-.0-9]*) ([-.0-9]*) (|[-0-9]*) (-|[-0-9]*) ([-0-9]*) ([-0-9]*) \"([^ ]*) ([^ ]*) (- |[^ ]*)\" \"([^\"]*)\" ([A-Z0-9-]+) ([A-Za-z0-9.-]*) ([^ ]*) \"([^\"]*)\" \"([^\"]*)\" \"([^\"]*)\" ([-.0-9]*) ([^ ]*) \"([^\"]*)\" \"([^\"]*)\"($| \"[^ ]*\")(.*)')
            LOCATION 's3://your-alb-logs-directory/AWSLogs/<ACCOUNT-ID>/elasticloadbalancing/<REGION>/yyyy/mm/dd/';

RailsのActiveRecord保存時にtimestamp(created_at,updated_at)が自動更新されないようにする

結論は下記なんだけど。

# Rails5以上
book.save(touch: false)

# Rails4以下
ActiveRecord::Base.record_timestamps = false

どうも古くからRailsをやっているからかsaveのtouchオプションが全く出てこず、record_timestampsの方でゴニョゴニョしたので下記は備忘として
きっとまだRails4みたいな古美術品に出会ったらやくに立つはず。。。



Railsでsaveした時にtimestamp(created_atやupdated_at)を更新したくない場合にどうするかをググると下記のように書くのが出てくる。

ActiveRecord::Base.record_timestamps = false
book.save
# 戻すの忘れずに!
ActiveRecord::Base.record_timestamps = true

昨今のpumaやsidekiqのようなマルチスレッド環境だと、こういうクラス変数っぽいものに代入しているのを見たときはかなり慎重に検証するようにしていて、 今回これだとマズそうだったのでどうにかできないか試行錯誤していた。

まず今回のケースだと

ActiveRecord::Base.record_timestamps = false
multi_table_copy
ActiveRecord::Base.record_timestamps = true

こんな感じにするとmulti_table_copyに時間がかかると他のスレッドまで ActiveRecord::Base.record_timestamps = false が効いた状態が長く続き、通常の処理が意図せず失敗してしまう。
(created_atなどが自動設定されないので通常のsaveで Field 'created_at' doesn't have a default value みたいにNot Null制約に引っかかるはず)


なので、その影響を少なくするためにsaveするところでrecord_timestampsのtrue/falseをバチバチ切り替えるようにしようと考えた。

def multi_table_copy
  ・・・
  target_records.each do |r|
    ActiveRecord::Base.record_timestamps = false
    r.save(validate: false)
    ActiveRecord::Base.record_timestamps = true
  end
  ・・・
end

しかし、これでも影響がゼロになった訳ではない。
(並列でジョブが動いていてrecord_timestamps = falseにするのと他のジョブのsaveが被らないとは言えないはず)


なので、他への影響を与えないようにできないものかと思って調べているとrecord_timestampsはcattr_accessorではなくclass_attributeで定義されているのでなんとかなりそうだと分かった。

※自分の今回初めてclass_attributeというものの存在を知った。
railsguides.jp


クラス変数だと継承先で上書きすると親クラスにも影響するが、class_attributeだと子クラスでの上書きが他へ影響しなくなる。

[1] pry(main)> class Base
[1] pry(main)*   class_attribute :record_timestamps, default: true  
[1] pry(main)* end  
=> [:record_timestamps]
[2] pry(main)> 
[3] pry(main)> 
[4] pry(main)> class A < Base
[4] pry(main)* end  
=> nil
[5] pry(main)> class B < Base
[5] pry(main)* end  
=> nil
[6] pry(main)> 
[7] pry(main)> 
[8] pry(main)> Base.record_timestamps
=> true
[9] pry(main)> A.record_timestamps
=> true
[10] pry(main)> B.record_timestamps
=> true
[11] pry(main)> 
[12] pry(main)> A.record_timestamps = false
=> false
[13] pry(main)> Base.record_timestamps
=> true
[14] pry(main)> A.record_timestamps
=> false
[15] pry(main)> B.record_timestamps
=> true

cattr_accessorだと他も上書きされてしまう。

[1] pry(main)> class Base
[1] pry(main)*   cattr_accessor :record_timestamps, default: true  
[1] pry(main)* end  
=> [:record_timestamps]
[2] pry(main)> class A < Base
[2] pry(main)* end  
=> nil
[3] pry(main)> class B < Base
[3] pry(main)* end  
=> nil
[4] pry(main)> 
[5] pry(main)> 
[6] pry(main)> Base.record_timestamps
=> true
[7] pry(main)> A.record_timestamps
=> true
[8] pry(main)> B.record_timestamps
=> true
[9] pry(main)> 
[10] pry(main)> A.record_timestamps = false
=> false
[11] pry(main)> 
[12] pry(main)> Base.record_timestamps
=> false
[13] pry(main)> A.record_timestamps
=> false
[14] pry(main)> B.record_timestamps
=> false

便利!

しかもclass_attributeはnewしたオブジェクトで上書きしても他のオブジェクトに影響しない。

[1] pry(main)> class Base
[1] pry(main)*   class_attribute :record_timestamps, default: true
[1] pry(main)* end  
=> [:record_timestamps]
[2] pry(main)> 
[3] pry(main)> class A < Base
[3] pry(main)* end  
=> nil
[4] pry(main)> class B < Base
[4] pry(main)* end  
=> nil
[5] pry(main)> a1 = A.new
=> #<A:0x00007fc684888568>
[6] pry(main)> a2 = A.new
=> #<A:0x00007fc68408aed8>
[7] pry(main)> 
[8] pry(main)> 
[9] pry(main)> a1.record_timestamps = false
=> false
[10] pry(main)> 
[11] pry(main)> 
[12] pry(main)> Base.record_timestamps
=> true
[13] pry(main)> A.record_timestamps
=> true
[14] pry(main)> B.record_timestamps
=> true
[15] pry(main)> a1.record_timestamps
=> false
[16] pry(main)> a2.record_timestamps
=> true

なので、Book.record_timestamps = falseとするよりは、book.record_timestamps = falseとした方が他への影響をなくすことができる。

しかもこの方法だとrecord_timestamps = trueに戻すことも考えなくていいので楽チン。


なので、最終的には下記のようにできる。

def multi_table_copy
  ・・・
  target_records.each do |r|
    r.record_timestamps = false
    r.save(validate: false)
  end
  ・・・
end

これで完璧や!!っと、ここまでやったところでRails5からはsave(touch: false)があることを思い出し無駄な時間を使っただけになってしまったのでした。。。