[GCP] Cloud BuildでGithubからGCEにデプロイ

AWSのCode Deployの様に、GithubからGCEにdeployするのに、Git cloneではなくCloud Buildでデプロイをする

1. Cloud BuildでGithubの対象レポジトリをauthorizeする
2. IAMから、Cloud Buildのユーザ(*@cloudbuild.gserviceaccount.com)に、「Compute Admin」「Service Account User」の権限を付与する
3. cloudbuild.yamlにspcコマンドを書く

steps:
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
  entrypoint: gcloud
  args: ['compute', 'scp', '--recurse', 'index.html', 'instance-1:/var/www/html/index.html' , '--zone','asia-northeast1-a']

4. git pushすると、pushをtrigerにファイルがGCEにコピーされる

GCEのexternal ipを叩くと、pushした内容が反映されていることがわかる

cloud source repositoryは特に必要ないですね。。

全体は大分できてきた

あとはELBか…

[GCP] Cloud Source Repositoryを利用

1. Add a repositoryでConnect external repositoryを選択

2. Githubをaurthorizeする

3. Cloud Source Repositories APIをenableにする
 
4. RepositoryとConnectする

5. テキストを追加してGit push

<p>Paragraph added!</p>

$ git add .
$ git commit -m “text added”
$ git push -u origin master

6. Githubの変更が自動的に反映
Cloud Source Repositoryにミラーリングされているのがわかる

なるほど、githubみたいなもんだな
これをGCEにデプロイしたい

[GCP] お名前.comのドメインを使いたい

1. CloudDNSを開く

2. Create DNS Zone
zone name: test
dns name: ${お名前.comのdomain}
DNSSEC: off

3. Create A record
GCEのExternal IPをIPv4 Addressに割り当てる

4. GCP DNSのNSをお名前.comの対象ドメインに割り当てる
ns-cloud-e1.googledomains.com.
ns-cloud-e2.googledomains.com.
ns-cloud-e3.googledomains.com.
ns-cloud-e4.googledomains.com.

5. GCEにapache2をインストール
$ ssh ${external ip} -i id_rsa
$ sudo apt update
$ sudo apt install apache2
$ sudo systemctl status apache2
$ sudo systemctl enable apache2

// NS反映までしばらく待ちます。

6. 動作確認
– GCEのExternal IPを叩いて、apacheの画面が表示されるか確認
– 続いて、お名前.comのドメインを叩いてApacheの画面が表示されるか確認

きたあああああああああああああああああああああああ
完全に理解した

次は、GithubからGCEへのDeploy
最後にELBとしたい

[GCP] SQLでMySQLを作成してローカルから接続

1. GCPでSQLを選択します
2. CREATE INSTANCE
L mysqlを選択します

allo accessで自分のIPを入力する

3. ローカルから接続
UserはGCP SQLのコントロールパネルから編集する

mysqlのinstance typeなどはEditで編集できる

### 接続
$ mysql -u root -h ${public ip} -P 3306 -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 110
Server version: 5.7.36-google-log (Google)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the current input statement.

mysql> show databases;
+——————–+
| Database |
+——————–+
| information_schema |
| mysql |
| performance_schema |
| sys |
+——————–+
4 rows in set (0.29 sec)

ぬおおおおおおおおおおお
意外と簡単に行けるやんかああああああああああああ

次はドメイン、ELB、デプロイだが

[GCP] GCS(cloud storage)を使ってみよう

### Basic
– GCS : GCPが提供するストレージ
– バケット : データを格納するコンテナ、ロケーションやストレージクラスの設定が可能
– オブジェクト : GCSに保存する個々のデータ
– ストレージクラス : Multi-Regional, Regional, Nearline, Coldine
– ライフサイクル : 有効期限、アーカイブ、コスト管理などができる

### 1. バケット作成

img upload

permissionはpublic accessになってますね。。
なるほど、まあ割と簡単ですね。続いてSQLを使いたい。

[GCP] シンプルな設計

もっともシンプルな設計は、projectの中にGCEがあるって状態

さて、ここからどうするか
-> ひとつひとつサービスを触っていく
-> Google App Engineはマネージドサービス、Cloud Runはコンテナ基盤、Firestoreはno sql, Cloud SQLはRDS, kubernetisはGKE
-> GCEからCloud SQLに接続する場合はVPCを経由する
-> LBはcloud loadbalancer
-> 監視、ログ集計、CDNのほか、BigQueryなども充実

まずはGCPのストレージからか..GCS(Google Cloud Strage)からか…

html・Javascriptでwebカメラを使用する方法

<h1>Webカメラの映像表示</h1>
	<div>
		<video id="video" width="600px" height="400px"></video>
	</div>
	<script>
		const video = document.getElementById("video")
		navigator.mediaDevices.getUserMedia({
			video: true,
			audio: false,
		}).then(stream => {
			video.srcObject = stream;
			video.play()
		}).catch(e => {
			console.log(e)
		})
	</script>

このファイルが次の許可を求めていますと表示される。

OK これでjsのopenCVを使いたい

[GCP] ローカル(mac)からGCEにCyberduckで接続したい

$ ssh-keygen
-> .ssh/id_rsaと.ssh/id_rsa.pubが生成される

Setting -> Metadata -> SSH Key -> addItem -> add Public SSH Key
L id_rsa.pubを貼り付ける

### コマンドラインから接続
$ ssh ${ExternalIP} -i id_rsa
->
mac@instance-1:~$

### Cyberduckから接続
同様に、ExternalIPに対して、SSH Private Keyを、.ssh/id_rsaで設定して接続

きたあああああああああああああああああああああ
ここまできたらGCEの3割ぐらいは前進したかな
大満足🥺 後はデプロイ周りとネットワーキング、ELB

[ubuntu20.04] openCVをinstallしたい

$ sudo apt-get update
$ sudo apt-get install libopencv-dev python3-opencv
$ python3
Python 3.8.10 (default, Sep 28 2021, 16:10:42)
[GCC 9.3.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import cv2
>>> cv2.__version__
‘4.2.0’

$ sudo apt-get install python3-pip
$ pip3 install pillow

import cv2

img = cv2.imread("src/test.jpg")

imgG = img.mean(axis=2)

from PIL import Image
imgP = Image.fromarray(imgG)
imgP = imgP.convert('RGB')
imgP.save('src/test2.jpg')

$ wget https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_alt.xml

### face-detection
$ wget https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml

import cv2
 
cascade_file = "haarcascade_frontalface_default.xml"
cascade = cv2.CascadeClassifier(cascade_file)
 
img = cv2.imread("src/face.jpg")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 
face_list = cascade.detectMultiScale(img_gray, minSize=(50,50))
 
if len(face_list) == 0:
    print("false")
    quit()
 
for (x,y,w,h) in face_list:
    print(" 顔の座標=", x, y, w, h)
    red = (0, 0, 255)
    cv2.rectangle(img, (x, y), (x+w, y+h), red, thickness=5)
 
cv2.imwrite("src/face-detect.png", img)

マスク画像

マスクでも行けるのは行けるのか

[Node.js] AWS Kinesis Video Streamのclipのmp4をDownloadする

### kvs起動
gst-launch-1.0 avfvideosrc device-index=0 ! videoconvert ! video/x-raw,format=I420,width=1280,height=720 ! vtenc_h264_hw allow-frame-reordering=FALSE realtime=TRUE max-keyframe-interval=45 bitrate=512 ! h264parse ! video/x-h264,stream-format=avc,alignment=au,profile=baseline ! kvssink stream-name=MyKinesisVideoStream storage-size=512 access-key=”YourAccessKeyId” secret-key=”YourSecretAccessKey” aws-region=”ap-northeast-1″

### node.js側

const fs = require('fs');
const AWS = require('aws-sdk')

AWS.config.update({accessKeyId: "***",
  secretAccessKey: "***",region: "ap-northeast-1"});

async function main(){

	const streamName = 'MyKinesisVideoStream';
	const kinesisvideo = new AWS.KinesisVideo();

	const param = {
		APIName: "GET_CLIP",
		StreamName: streamName
	};
	const e = await kinesisvideo.getDataEndpoint(param).promise();
	const kinesisvideoarchivedmedia = new AWS.KinesisVideoArchivedMedia({endpoint: e.DataEndpoint});

	startTime = new Date(2021, 10, 13, 23, 40, 30); // UTC時間
	endTime = new Date(2021, 10, 13, 23, 41, 38); // UTC時間

	const params = {
        ClipFragmentSelector: { 
          FragmentSelectorType: "PRODUCER_TIMESTAMP",
          TimestampRange: {
            EndTimestamp: endTime,
            StartTimestamp: startTime 
          }
        },
        StreamName: streamName
    };
    const data = await kinesisvideoarchivedmedia.getClip(params).promise();

	const filePath = "test.mp4"
	fs.writeFileSync(filePath, data.Payload);
}

main()

$ node get-mp4.js
うおおおおおおおおおおおおおおおおおおおお

### トラブルシューティング
ずっとこれが出てたんだが、何かなと思ってたら
$ node get-mp4.js
(node:137900) UnhandledPromiseRejectionWarning: ResourceNotFoundException: No fragments found in the stream for the clip request.

jsでtimestampを作るとき、monthは -1なのね。
new Date(2021, 10, 13, 23, 40, 30); // 2021/11/13 23:40:30

new Date(2021, 11, 13, 23, 40, 30) でやってたから、No fragments foundだった。。あほやわ
よっしゃあああああああああああああああああああ