【Rust】reqwestでVPSのaxumにPOSTできるかテストする

reqwestでipを指定して送る場合は、client.post(“***.**.***.**:3000/post”) だと送れないが、client.post(“http://***.**.***.**:3000/post”) だと問題なく送ることができる。

送る側(ローカル開発環境)

async fn test()-> Result<(), Box<dyn std::error::Error>> {
    let n = Name { family: "tanaka".to_string(), first:"taro".to_string(), age: 20 };
    let json = json!(n);
    println!("{:?}", &json);
    let client = reqwest::Client::new();
    let resp = client.post("http://***.**.***.**:3000/post")
        .json(&json)
        .send()
        .await?;
    let body = resp.text().await?;   
    println!("{}", body);
    Ok(())
}

受け取る側(VPS: ***.**.***.**)

async fn main() {

    let app = Router::new()
        .route("/", get(handle_index))
        .route("/post", post(handle_post))
        .route("/test", get(handle_test));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn handle_post(extract::Json(name): extract::Json<Name>) ->impl IntoResponse{
    println!("{:?}", name);
    return "All OK".into_response();
}

受け取る側
$ cargo run
Compiling axum v0.1.0 (/home/ubuntu/test/rust_test)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 12.90s
Running `target/debug/axum`
Name { family: “sato”, first: “taro”, age: 50 }
Name { family: “tanaka”, first: “taro”, age: 20 }

送る側
Compiling axum v0.1.0 (/home/vagrant/dev/rust/axum)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 12.59s
Running `target/debug/axum`
Object {“age”: Number(20), “family”: String(“tanaka”), “first”: String(“taro”)}
All OK

reqwestが使えるというのがわかったのは収穫だが、IPだけでなく、httpsかhttpかというプロトコルも一緒に取得する必要がある。

discussion
https://github.com/tokio-rs/axum/discussions/858

ちなみに、VPSでweb socketで待ち受けて、ws://***.**.***.**:3000/ws で接続しても問題なく接続できた。

async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>, ws: WebSocketUpgrade) -> Response {
    println!("{}", addr);
    ws.on_upgrade(handle_socket)
}

async fn handle_socket(mut socket: WebSocket) {
    while let Some(msg) = socket.recv().await {
        let mut msg = if let Ok(mut msg) = msg {
            msg
        } else {
            return;
        };
        if socket.send(msg).await.is_err() {
            // client disconnected
            return;
        }
    }
}

なるほど、reqwestが試せるだけで大分進んだ気がする。

【sakura vps】alma linuxにgitを入れる

ssh後にgitを確認
$ git –version
-bash: git: command not found

gitが入っていないのでgitを入れる
$ sudo dnf -y install git
Failed to set locale, defaulting to C.UTF-8
Killed

killedとなっているので、logを確認
$ sudo cat /var/log/messages
メモリが足りないっぽいのでswapを追加
$ sudo mkdir /var/swap
$ sudo dd if=/dev/zero of=/var/swap/swap0 bs=1M count=4096
$ sudo chmod 0600 /var/swap/swap0
$ sudo mkswap /var/swap/swap0
$ swapon /var/swap/swap0
$ free
total used free shared buff/cache available
Mem: 469712 94524 143384 15428 231804 336236
Swap: 4194300 40960 4153340

再度git をインストール
$ sudo dnf -y install git
$ git -v
git version 2.39.3

VPSでLet’s encryptを導入する

IPアドレス指定でアクセスする場合のSSLには対応していないので、独自ドメインをあらかじめ取得・設定しておく必要がある

$ sudo a2enmod ssl
$ sudo a2ensite default-ssl
$ service apache2 reload

$ sudo vi /etc/apache2/sites-available/virtual.host.conf

<VirtualHost *:80>
DocumentRoot /var/www/node
ServerName hoge.site
#ServerAlias www.hoge.site
# Other directives here

RewriteEngine on
RewriteCond %{SERVER_NAME} =hoge.site [OR]
RewriteCond %{SERVER_NAME} =www.hoge.site
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

<VirtualHost _default_:443>
DocumentRoot /var/www/node
ServerName hoge.site
ServerAlias www.hoge.site
# Other directives here

SSLCertificateFile /etc/letsencrypt/live/hoge.site/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/hoge.site/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>

$ sudo apt install firewalld
$ sudo firewall-cmd –add-service=http –zone=public –permanent
$ sudo firewall-cmd –add-service=https –zone=public –permanent
$ sudo systemctl restart firewalld
$ sudo firewall-cmd –list-all
services: dhcpv6-client http https ssh

$ sudo apt-get install certbot python3-certbot-apache
$ certbot –apache -d hoge-test.site

ほう

vpsでjarファイルを実行する

CREATE TABLE users (
id SERIAL NOT NULL,
name varchar(255),
department varchar(255),
PRIMARY KEY(id)
);

# java -jar practice-0.0.1-SNAPSHOT.jar

. ____ _ __ _ _
/\\ / ___’_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | ‘_ | ‘_| | ‘_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
‘ |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.3)

${id}:8765/test1/index
-> 動かない 何故だ。postgresも入れたし、localだと動くんだけどな。。
# lsof -i:8765

ずっとやってんだけど解決する見込みがない。。
まあ、keep going
次はauth

vpsでansibleを動かす準備をしよう

1.さくら共有サーバー2つ分のipアドレスを取得
2.vpsにanshibleをインストール
3.vpsからさくら共有サーバーにping ponコマンドを実行し、ansibleが動くことを確認
4.vpsからファイルを転送して、アクセスする

まずはここまでやりたい。1は終了。
ansibleのplaybookをどこで実行するか?var/wwwwはapacheが動いているので、/var/localにansibleフォルダを作るのが無難か。

ansibleをインストールします。
# sudo yum -y install ansible

ansibleが入りました。config fileはetcに入ってますね。いいのか?
[root@hoge ansible]# ansible –version
ansible 2.6.4
config file = /etc/ansible/ansible.cfg
configured module search path = [u’/root/.ansible/plugins/modules’, u’/usr/share/ansible/plugins/modules’]
ansible python module location = /usr/lib/python2.6/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)]

/httpd/conf.d/

ヴァーチャルホストの設定

<VirtualHost *:80>
DocumentRoot /var/www/html/hoge
DirectoryIndex index.html index.php
ServerName www.hoge.com
ServerAlias hoge.com
CustomLog logs/hoge.com-access.log common
ErrorLog  logs/hoge.com-error.log
AddDefaultCharset UTF-8
<Directory "/var/www/html/hoge/">
AllowOverride All
</Directory>
</VirtualHost>

vpsインストール後の鍵認証の設定

まず、yum update

Loaded plugins: fastestmirror, security
Setting up Update Process
Loading mirror speeds from cached hostfile
 * base: ftp.iij.ad.jp
 * epel: ftp.riken.jp
 * extras: ftp.iij.ad.jp
 * updates: ftp.iij.ad.jp
No Packages marked for Update

1.公開鍵の転送先ディレクトリの作成

# mkdir .ssh
# chmod 700 .ssh

ssh-keygenで、id_rsa id_rsa.pubを作成します。

vps

ログイン後に、言語設定

[root@tk2-234-26826 ~]# yum update
Loaded plugins: fastestmirror, security
Setting up Update Process
Loading mirror speeds from cached hostfile
 * base: ftp.iij.ad.jp
 * epel: ftp.riken.jp
 * extras: ftp.iij.ad.jp
 * updates: ftp.iij.ad.jp
No Packages marked for Update

[root@tk2-234-26826 ~]# vim /etc/sysconfig/i18n

userの設定

[root@tk2-234-26826 ~]# date
2016年 12月  5日 月曜日 12:39:36 JST
[root@tk2-234-26826 ~]# useradd user

権限の変更

[root@tk2-234-26826 ~]# usermod -G wheel user
[root@tk2-234-26826 ~]# visudo

sudo権限の変更

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

ドキュメントルート /www/root/html