Githubのcommitは以下のように書く
Fixed bug *, Added new, Changed, Updated, Removed, Simplified, Restructured, Rewrote
e.g.
Fixed a bug where the "paste as text" option in the Paste Plugin didn't work.
OSSのchange logの書き方は非常に参考になる。
随机应变 ABCD: Always Be Coding and … : хороший
Githubのcommitは以下のように書く
Fixed bug *, Added new, Changed, Updated, Removed, Simplified, Restructured, Rewrote
e.g.
Fixed a bug where the "paste as text" option in the Paste Plugin didn't work.
OSSのchange logの書き方は非常に参考になる。
Incomming Webhookをセットアップして、ターミナルから挙動確認します。
curl -X POST --data-urlencode "payload={\"channel\": \"#hpscript\", \"username\": \"webhookbot\", \"text\": \"これは webhookbot という名のボットから #general に投稿されています。\", \"icon_emoji\": \":ghost:\"}" https://hooks.slack.com/services/hogeL/hogehoge
curlでslackの#hpscriptのチャネルに投稿されていることを確認できます。
### 1.env設定
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/hogeL/hogehoge
### 2.guzzlehttp/guzzle、slack-notification-channelインストール
$ php composer.phar require guzzlehttp/guzzle
$ php composer.phar require laravel/slack-notification-channel
### 3. Notification作成
$ php artisan make:notification Slack
app/Notifications/Slack.php
use Illuminate\Notifications\Messages\SlackMessage;
class Slack extends Notification
{
use Queueable;
protected $content;
public function __construct($message)
{
$this->content = $message;
}
public function via($notifiable)
{
return ['slack'];
}
public function toSlack($notifiable)
{
return (new SlackMessage)
->from('hpscript', ':bomb:')
->to('#general')
->content($this->content);
}
public function toArray($notifiable)
{
return [
];
}
}
app/User.php
public function routeNotificationForSlack($notification){
return env('SLACK_WEBHOOK_URL');
}
### 4.slack通知コマンド作成
$ php artisan make:command SendSlackCommand
app/Console/Commands/SendSlackCommand.php
use App\User;
use App\Notifications\Slack;
class SendSlackCommand extends Command
{
protected $signature = 'slack:send {message}';
protected $description = 'Send Slack Notification';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$user = new User();
$user->notify(new Slack($this->argument('message')));
}
}
### 5.実行
$ php artisan slack:send ‘slack通知のテストです’
-> Slackの#generalのチャネルで挙動確認

コントローラで使いたい場合
use App\Notifications\Slack;
use App\User;
public function index(Request $request)
{
//
$user = Auth::user();
$user->notify(new Slack($user->name.'さんがログインしました'));
return view('subscriber.index', compact('user'));
}

※メモ
– Notifications/Slack.phpのconstructorでenv()は使えない
– slack-notification-channelは、laravel/frameworkと分離してインストールされるがインストール場所が変わっても名前空間は同じため、使い方は同じ
想像以上に手こずりました。
TravisCI + CodeDeployのフロー
【High Level】
– Merge Pull Request on master
– Travis Builds project automatically / run tests
– Travis uploads zipped project up to S3
– Travis then tells AWS Code Deploy to deploy to EC2 instance
【Index】
1. Pre-Setup
2. Policy For Server
3. Policy For Travis CI
4. Creating Travis User in IAM
5. Role for EC2 Instance
6. Role for Code Deploy Application
7. Create EC2 Instance
8. Create EC2 Tag
9. Create S3 Bucket
10. Setup Code Deploy
11. Project Setup
12. Setting Up Travis User Credentials on Travis
13. Code Deploy Agent Setup
### 1. IAMでEC2のPolicy作成
Policies -> Create Policy
Name: CodeDeployDemo-EC2-Permissions
Description: CodeDeployDemo-EC2-Permissions
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:Get*",
"s3:List*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
-> このポリシーによって、EC2がS3からデータを持ってこれる
### 2. IAMでTravisCI、CodeDeployの為のPolicy作成
1.TravisがS3にアップロード
Travis-Deploy-To-S3
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject"
],
"Resource": [
"*"
]
}
]
}
2.CodeDeployがEC2にデプロイ
Travis-Code-Deploy-Policy
※AccIdHEREはAWSの数字のID
※NameOfTheCodeDeployApplicationNameHEREはCodeDeployのapplication name
※ServerRegionHEREはap-northeast-1
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"codedeploy:RegisterApplicationRevision",
"codedeploy:GetApplicationRevision"
],
"Resource": [
"arn:aws:codedeploy:ServerRegionHERE:AccIdHERE:application:NameOfTheCodeDeployApplicationNameHERE"
]
},
{
"Effect": "Allow",
"Action": [
"codedeploy:CreateDeployment",
"codedeploy:GetDeployment"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"codedeploy:GetDeploymentConfig"
],
"Resource": [
"arn:aws:codedeploy:ServerRegionHERE:AccIdHERE:deploymentconfig:CodeDeployDefault.OneAtATime",
"arn:aws:codedeploy:ServerRegionHERE:AccIdHERE:deploymentconfig:CodeDeployDefault.HalfAtATime",
"arn:aws:codedeploy:ServerRegionHERE:AccIdHERE:deploymentconfig:CodeDeployDefault.AllAtOnce"
]
}
]
}
### 3. IAMでTravisユーザ作成
UserName: Travis
access type: Programmatic access
Set permissions: 上記で作成したTravis-Deploy-To-S3、Travis-Code-Deploy-Policy
->作成後、accesskey、secretkeyを保存
### 4. EC2のロール作成
Create role -> AWS service EC2
Permissions:CodeDeployDemo-EC2-Permissions
Role Name: CodeDeploy_EC2_DEPLOY_INSTANCE
### 5. CodeDeployアプリの為のロール作成
Create role -> CodeDeploy
Permissions: AWSCodeDeployRole
Role Name: CodeDeployServiceRole
### 6. EC2 launch
Amazon Linux 2 AMI (HVM), SSD Volume Type 64x t2.nano 8GiB GP2
Auto-assign Public IP: enable
IAM role: CodeDeploy_EC2_DEPLOY_INSTANCE
Tag: Name travisci
### 7. S3バケット作成
create bucket -> demo-travis-s3
### 8. CodeDeploy作成
Create application -> application nameはIAMのTravis-Code-Deploy-Policyで設定したname
platform: EC2/On-premises
Create Deployment Group -> Deployment Group Name : TravisCodeDeployDemoDeploymentGroup(何でもOK)
Envrionment Configuration -> Amazon EC2 -> 6で作成したtagを選択(Name travisci)
CodeDeployDefault.AllAtOnce
### 9. travis.yml
language: php
php:
- 7.3
services:
- mysql
before_script:
- cp .env.travis .env
- mysql -e 'create database test;'
- composer self-update
- composer install
- chmod -R 777 storage
script:
- ./vendor/bin/phpunit
deploy:
- provider: s3
access_key_id: $AWS_ACCESS_KEY
secret_access_key: $AWS_SECRET_KEY
local_dir: dpl_cd_upload
skip_cleanup: true
on: &2
repo: hoge/hogehoge
bucket: demo-travis-s3
region: ap-northeast-1
- provider: codedeploy
access_key_id: $AWS_ACCESS_KEY
secret_access_key: $AWS_SECRET_KEY
bucket: demo-travis-s3
key: latest.zip
bundle_type: zip
application: travisci
deployment_group: TravisCodeDeployDemoDeploymentGroup
region: ap-northeast-1
on: *2
script:
- zip -r latest *
- mkdir -p dpl_cd_upload
- mv latest.zip dpl_cd_upload/latest.zip
### 10.Travis側でcrudentialの登録
Environment Variables
– AWS_ACCESS_KEY, AWS_SECRET_KEYを入力
### 11. EC2にCodeDeployインストール
$ sudo yum update
$ sudo yum install ruby
$ sudo yum install aws-cli
$ aws s3 cp s3://aws-codedeploy-ap-northeast-1/latest/install . –region ap-northeast-1
$ chmod +x ./install
$ sudo ./install auto
$ sudo service codedeploy-agent status
$ sudo yum info codedeploy-agent
### 12. appspec.yml
version: 0.0
os: linux
files:
- source: ./
destination: /home/test/travisci
### 13. git push & deploy
$ git push -u origin master
### 14. travisci
-> passed
-> Done. Your build exited with 0.
### 15. EC2で動作確認
$ cd /home/test/travisci
$ ls
README.md artisan composer.lock database phpunit.xml routes tests
app bootstrap composer.phar package-lock.json public server.php vendor
appspec.yml composer.json config package.json resources storage webpack.mix.js
– 所感
circleCIはデプロイのjob実装に一日かかりましたが、Travisは多少IAMの設定に時間がかかりましたが、デプロイは一発で上手くいきました。
Gitpullではなく、CodeDeployでデプロイできるので、AWSとはTravisの方が相性が良さそう。
ただ、unitテストはmasterへのpushではなく、ブランチのリポジトリへのpushのタイミングの方が良さそう。
.travis.yml
language: php
php:
- 7.3
services:
- mysql
before_script:
- cp .env.travis .env
- mysql -e 'create database test;'
- composer self-update
- composer install
- chmod -R 777 storage
script:
- ./vendor/bin/phpunit
notifications:
emails:
- hoge@gmail.com
config.database.php
'testing' => [
'driver' => 'mysql',
'host' => env('DB_TEST_HOST', 'localhost'),
'database' => env('DB_TEST_DATABASE', 'test'),
'username' => env('DB_TEST_USERNAME', 'homestead'),
'password' => env('DB_TEST_PASSWORD', 'secret'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
.env.travis
APP_ENV=testing APP_KEY=base64:**** DB_CONNECTION=testing DB_TEST_USERNAME=root DB_TEST_PASSWORD= CACHE_DRIVER=array SESSION_DRIVER=array QUEUE_DRIVER=sync
Travis CI: Travis側(Ubuntu)でテストが行われる
Jenkins: テスト環境の構築が必要
### TravisCIの機能
– 自動でソースコードをcheckoutして、予め指定しておいたビルドやテスト処理を実行
– テスト結果をTravis CIのサイト上や各種API、メールで開発者に通知
– テストが問題なければ、予め指定しておいたホスティングサービスにデプロイする
– ビルドやテスト処理は「.travis.yml」に記述する
### 前準備(ローカル環境)
– Vagrant Amazon Linux 2
– Laravel 7.3.0, MySQL 8.0.18
### TravisCI側の操作
– Approve & Install Travis CI
— Only select repositories: publicを選択
— approve & install
### .travis.yml作成
– Laravelのルートディレクトリに.travis.ymlを作成
language: php
php:
- 7.3
before_script:
- composer self-update
- composer install
- chmod -R 777 storage
- php artisan key:generate
script:
- ./vendor/bin/phpunit
notifications:
emails:
- hoge@gmail.com
1) Tests\Feature\ExampleTest::testBasicTest RuntimeException: No application encryption key has been specified.
APP_KEYが必要のようなので、before_scriptでAPP_KEYを読み込むようにします。
.env.travis
APP_ENV=testing APP_KEY=base64:*****
before_script: - cp .env.travis .env - composer self-update - composer install - chmod -R 777 storage
0.23s$ ./vendor/bin/phpunit
PHPUnit 8.5.2 by Sebastian Bergmann and contributors.
.. 2 / 2 (100%)
Time: 165 ms, Memory: 20.00 MB
OK (2 tests, 2 assertions)
The command “./vendor/bin/phpunit” exited with 0.
割とすぐ上手くいきました。仕組みとしては、CircleCIと似ていますが、Dockerじゃないとこが異なりますね。
$ ssh-keygen -m pem
$ cd .ssh
$ ls
authorized_keys config id_rsa id_rsa.pub
id_rsa(秘密鍵)を Circle CI -> PROJECT SETTINGS -> Add SSH Keyに登録
その際、Host NameはインスタンスのIPアドレスを登録する
id_rsa.pub(公開鍵)をEC2 .ssh/authorized_keysに追加
$ git push -u origin master
The authenticity of host ‘************* (*************)’ can’t be established.
config.yml
- run: ssh -o 'StrictHostKeyChecking no' ${USER_NAME}@${PUBLIC_IP} 'cd /var/www && git pull'
#!/bin/bash -eo pipefail
ssh -o 'StrictHostKeyChecking no' ${USER_NAME}@${PUBLIC_IP} 'cd /var/www && git pull'
Warning: Permanently added '*************' (ECDSA) to the list of known hosts.
fatal: not a git repository (or any of the parent directories): .git
Exited with code exit status 128
あ、エラー内容が変わりました。
$ cd /var/www
$ sudo git clone https://github.com/hoge/circleci.git
config.yml
- run: ssh -o 'StrictHostKeyChecking no' ${USER_NAME}@${PUBLIC_IP} 'cd /var/www/circleci && git pull'
error: cannot open .git/FETCH_HEAD: Permission denied
$ sudo chmod 777 .git/
$ git remote add origin https://{username}:{password}@github.com/{username}/project.git
error: insufficient permission for adding an object to repository database .git/objects
fatal: failed to write object
fatal: unpack-objects failed
$ sudo chmod 777 objects/
error: cannot lock ref ‘refs/remotes/origin/master’: Unable to create ‘/var/www/circleci/.git/refs/remotes/origin/master.lock’: Permission denied
$ git remote prune origin
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
error: unable to unlink old ‘.circleci/config.yml’: Permission denied
error: unable to unlink old ‘resources/views/home.blade.php’: Permission denied
$ sudo chown -R ec2-user ./

やっといけました。1日かかりました。
他の方は ssh -o ‘StrictHostKeyChecking no’やgitのpermission変更などせずに行けているようなのであまり参考にならないかもしれませんが。
### 環境
– vagrant Amazon Linux2
– Laravel7.2.1, Mysql8.0
### 前提
– .circleci/config.ymlを配置済み
– git pushすると、phpunitが走る
– これにデプロイのjobを追加したい
公式: https://circleci.com/docs/ja/2.0/deployment-integrations/
公式のソースコード:
-> runコマンドを見るとgit pushでデプロイしていますね。
deploy:
machine:
enabled: true
working_directory: ~/circleci-demo-workflows
environment:
HEROKU_APP: "sleepy-refuge-55486"
steps:
- checkout
- run:
name: Master を Heroku にデプロイ
command: |
git push https://heroku:$HEROKU_API_KEY@git.heroku.com/$HEROKU_APP.git master
workflows:
version: 2
build-and-deploy:
jobs:
- build
- deploy:
requires:
- build
filters:
branches:
only: sequential-branch-filter
ec2にsshログインしているので、これをconfig.ymlに書いてやってみたいと思います。
ssh ec2-user@{publicIP} -i ~/.ssh/***.pem
### 1. テスト用のEC2インスタンス作成
– Amazon Linux 2 AMI (HVM), SSD Volume Type 64bit
– t2.nano
– public subnet
– Auto-assign Public IP: enable
– gp2 8GiB
– SecurityGroup: SSH 0.0.0.0/0
– keypair: create | select
->SSHログインテスト
ssh ec2-user@{publicIP} -i ~/.ssh/***.pem
### 2. EC2にGitインストール
// インストール手順は省略
$ git –version
git version 2.19.2
$ cd /var
$ sudo mkdir www
### 3. CircleCI Project setting
CircleCIのコンソールにログインし、対象リポジトリのproject settingのページに遷移
– Environment Variables
KEY: PUBLIC_IP, VALUE: **.***.***.**
KEY: USER_NAME, VALUE: ec2-user
– SSH Permissions
Hostname: 任意
Private Key:秘密鍵の中身
-----BEGIN RSA PRIVATE KEY----- // 省略 -----END RSA PRIVATE KEY-----
### 4.config.ymlにdeploy追加
version: 2
jobs:
build:
// buildは省略
deploy:
machine:
image: circleci/classic:edge
steps:
- checkout
- add_ssh_keys:
- run: ssh ${USER_NAME}@${PUBLIC_IP} 'cd /var/www && git pull
workflows:
version: 2
build_and_deploy:
jobs:
- build
- deploy:
requires:
- build
filters:
branches:
only: master
### 5.git push
$ git push -u origin master
$ echo -e “Host github.com\n\tStrictHostKeyChecking no\n” > ~/.ssh/config
#!/bin/bash -eo pipefail
ssh ${USER_NAME}@${PUBLIC_IP} ‘cd /var/www && git pull’
The authenticity of host ‘************* (*************)’ can’t be established.
buildはsuccessだがdeployが何度やってもダメだ。。。丸一日潰れた。
ん?
EC2 インスタンス上で秘密鍵 (pem ファイル) を作成して CircleCI に登録する必要があります。
秘密鍵はec2で作成するの???
あああああああああ
### TIOBE
ロジック : Index Definition
-> 検索エンジンに対して、クエリを発行した結果を元にランキングを付けている。
+"<language> programming"
1位 Java, 2位 C, 3位 Python, 4位 C++, 5位 C#, 6位 Visual Basic.NET, 7位 JavaScript, 8位 PHP, 9位 SQL, 10位 Go
### PYPL
1位 Python, 2位 Java, 3位 Javascript, 4位 C#, 5位 PHP, 6位 C/C++, 7位 R, 8位 Objective-C, 9位 Swift, 10位 Matlab
ロジック: The Index is created by analyzing how often language tutorials are searched on Google
### RedMonk: Programming Language Ranking
ロジック: GitHubのアクティブリポジトリ、StackOverflowでの質問、Redditでの投稿数、求人サイトでの募集の数
1位 JavaScript, 2位 Python, 3位 Java, 4位 PHP, 5位 C#, 6位 C++, 7位 Ruby, 8位 CSS, 9位 TypeScript, 9位 C
### GitHub Octoverse
Top OSS
1位 microsoft/vscode, 2位 MicrosoftDocs/azure-docs, 3位 flutter/flutter, 4位 firstcontributions/first-contributions, 5位 tensoflow/tensorflow, 6位 facebook/react-native, 7位 kubernetes/kubernetes, 8位 DefinitelyTyped/DefinitelyTyped, 9位 ansible/ansible, 10位 home-assistant/home-assistant
Top Language
1位 JavaScript, 2位 Python, 3位 Java, 4位 PHP, 5位 C#, 6位 C++, 7位 TypeScript, 8位 Shell, 9位 C, 9位 Ruby
Google indexとGitHubだとランキングに差があるが、概ねJava, Python, JavaScriptが上位はほぼ変わらずか。
$ sudo apt install hhvm
$ hhvm –version
HipHop VM 3.21.0 (rel)
Compiler: 3.21.0+dfsg-2ubuntu2
Repo schema: ebd0a4633a34187463466c1d3bd327c131251849
$ echo ‘‘ >/tmp/hello.php
$ hhvm /tmp/hello.php
Hello HHVM
echo "hello world!";
$ hhvm hello.php
Fatal error: /home/vagrant/hhvm/hello.php appears to be a Hack file, but you do not appear to be running the Hack typechecker. See the documentation at http://docs.hhvm.com/hack/typechecker/setup for information on getting it running. You can also set `-d hhvm.hack.lang.look_for_typechecker=0` to disable this check (not recommended).
サイトを見ます。
getting-started
$ touch .hhconfig
$ hhvm hello.php
Warning: Hack typechecking failed: server not ready. Unless you have run “hh_client” manually, you may be missing Hack type errors! Once the typechecker server has started up, the errors, if any, will then show up in this error log.
hello world!
とりあえずHHVMの環境つくって動かしてみました ってところより先の記事が少ない。PHP7.0以上が高速になったので、みんな様子見ってところか。
PHPは、ZendEngineというインタプリタエンジンを使って動いている
インタプリタの挙動
1. テキストファイルを読み込む(IO処理)
2. ソースコードをパースしてopcodeに変換(CPU処理)
3. opcodeを順番に実行
Opcacheを用いることで一度変換したopcodeをメモリ上に載せておき、2回目以降の処理はメモリにキャッシュされたopcodeを取り出して実行する
opcodeは中間言語の為、cpuやosなど実行環境に応じて実行される。その為、JavaやCなどのコンパイル言語よりも実行速度が遅い
c++やgolangは最初のコンパイルで機械語まで変換する
### Hip Hop Virtual Machine
PHPやHack言語をx64CPU向けにJITコンパイルするvirtual machine。つまり、Zend Engineで実行する代わりにJITコンパイルして実行する
HHVMはFacebook開発
HHVMはPHP7からは非推奨だが、Hack言語のサポート
### Hack言語
PHPに静的型付け機能を追加し、HHVMに最適化
開始するタグが < ?php ではなく < ?hhで、HTMLに埋め込む形ができない
Hackは非同期機能をサポート
Wikipedia, baiduなどが採用
PHPフレームワークやライブラリが使えない? -> Codeigniter, cake, laravel, Yiiなど動作する
### Hack言語の機能
Generic(型をパラメータとして与え、型だけ違って処理の内容が同じものを作るときに使う)
Map(keyとvalueをset) / Vector(順番に値を保持) / Set(重複不可) / Pair(2つの値をセット)
Enum(値を列挙)
async, awaitで並列実行
hh_client(実行前に構文チェック)