ansibleを触っていこう

[vagrant@host ~]$ ansible –version
ansible 2.2.0.0
config file = /home/vagrant/ansible.cfg
configured module search path = Default w/o overrides

ansibleってレッドハットが所有してるんだ。どうりで。
https://www.ansible.com/

[vagrant@host ~]$ ssh web
Last login: Wed Nov 23 22:41:13 2016 from 192.168.43.51
[vagrant@web ~]$ exit
logout
Connection to 192.168.43.52 closed.
[vagrant@host ~]$ ssh db
Last login: Wed Nov 23 22:41:12 2016 from 192.168.43.51
[vagrant@db ~]$ exit
logout
Connection to 192.168.43.53 closed.

なんじゃこりゃー

inventry file

[web]
192.168.43.52

[db]
192.168.43.53

[vagrant@host ~]$ ansible all -i hosts -m ping
192.168.43.53 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
192.168.43.52 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}

ansible.cfg

[defaults]
hostfile = ./hosts

[vagrant@host ~]$ ansible all -m ping
192.168.43.53 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
192.168.43.52 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}

eclipseでmysqlに接続(3時間かかったーーーーー)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//		response.getWriter().append("Served at: ").append(request.getContextPath());
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;

		try {
		  Class.forName("com.mysql.jdbc.Driver").newInstance();
		  conn = DriverManager.getConnection("jdbc:mysql://localhost/sampledb?user=root&password=");
		  stmt = conn.createStatement();
		  rs = stmt.executeQuery("SELECT userid,status FROM userinfo");
		  
		  response.setContentType("text/plain");
		  while (rs.next()) {
		    response.getWriter().write("userid=" + rs.getString("userid") + ", ");
		    response.getWriter().write("status=" + rs.getString("status") + "\n");
		  }
		} catch(Exception e) {
		  e.printStackTrace();
		} finally {
		  if (rs != null ) { try {rs.close(); } catch (SQLException e) {e.printStackTrace();} }
		  if (stmt != null ) { try {stmt.close(); } catch (SQLException e) {e.printStackTrace();} }
		  if (conn != null ) { try {conn.close(); } catch (SQLException e) {e.printStackTrace();} }
		}
		
	}

見よ、涙の結晶を!! これだけで3時間くらいかかった。

疲れたので、あまり喜べない。。。
とりあえず、tomcat + servlet + jspで mysql、redirectまでは解った!!! 
すげーーーーーーーーーーーーーーーー
mysql connectorは鬼門だった。。
さあ~ ansible 行ってみよう♪♪♪♪♪ 

Loading class `com.mysql.jdbc.Driver’. This is deprecated.

Loading class `com.mysql.jdbc.Driver’. This is deprecated.

以下に変更

Class.forName("com.mysql.cj.jdbc.Driver").newInstance();

Loading class `com.mysql.jdbc.Driver’. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
java.sql.SQLException:

connectorがどうもおかしいっぽい。
なんか違うなーと思ったらconnector/jか! 間際らしい。

mysql-connector

eclipseのlibにmysql-connectorを配置する

servletを作成する。mysqltestとしよう。

add to build pathとする

とりあえずwindows10 のmysqlにテーブルとレコードを無理矢理つくります。
mysql> create database sampledb
-> ;
Query OK, 1 row affected (0.13 sec)

mysql> use sampledb
Database changed
mysql> create table userinfo(
-> userid varchar(10) primary_key,
-> status Int
-> );
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘primary_key,
status Int
)’ at line 2
mysql> create table userinfo(
-> userid varchar(10) primary key,
-> status int
-> );
Query OK, 0 rows affected (1.04 sec)

mysql> insert into userinfo (userid, status) values (“aaaa123”, 0),(“asdf123”, 1),(“xyzx123”,2);
Query OK, 3 rows affected (0.17 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> select * from userinfo;
+———+——–+
| userid | status |
+———+——–+
| aaaa123 | 0 |
| asdf123 | 1 |
| xyzx123 | 2 |
+———+——–+
3 rows in set (0.00 sec)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//		response.getWriter().append("Served at: ").append(request.getContextPath());
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;

		try {
		  Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
		  conn = DriverManager.getConnection("jdbc:mysql:C:/mysql-56/data/sampledb?user=root&password=");
		  stmt = conn.createStatement();
		  rs = stmt.executeQuery("SELECT userid,status FROM userinfo");
		  
		  response.setContentType("text/plain");
		  while (rs.next()) {
		    response.getWriter().write("userid=" + rs.getString("userid") + ", ");
		    response.getWriter().write("status=" + rs.getString("status") + "\n");
		  }
		} catch(Exception e) {
		  e.printStackTrace();
		} finally {
		  if (rs != null ) { try {rs.close(); } catch (SQLException e) {e.printStackTrace();} }
		  if (stmt != null ) { try {stmt.close(); } catch (SQLException e) {e.printStackTrace();} }
		  if (conn != null ) { try {conn.close(); } catch (SQLException e) {e.printStackTrace();} }
		}
		
	}

Loading class `com.mysql.jdbc.Driver’. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
java.sql.SQLException: No suitable driver found for jdbc:mysql:C:/mysql-56/data/sampledb?user=root&password=
at java.sql.DriverManager.getConnection(Unknown Source)

やりたいことはわかった。

servletのリダイレクト処理

doGetなどは関係ないが、とにかく、response.sendRedirect(url);でリダイレクトができる。

package todo.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class HelloServlet
 */
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
    	request.setAttribute("foo", "hogehoge");

		String view = "/WEB-INF/view/index.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(view);

		dispatcher.forward(request, response);
	}
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String value = request.getParameter("hoge");
		System.out.println(value);
		String url = "http://www.google.com";
		response.sendRedirect(url);
//		doGet(request, response);
	}

}

jspは省略
postを受け取って、redirect

OKOK。次はmysql接続

cloudfront

cloud front
-> 負荷を分散させ、大量のリクエストに対する対策を実施、通信にかかるレイテンシ(遅延)を改善

Amazon CloudFrontは、Amazon Web Services(AWS)のCDN(コンテンツデリバリネットワーク)サービス
– コンテンツファイルをサーバーから直接配信せず、CDNを介してユーザーに配信
– コンテンツをCloudFrontから配信すると、サーバーへのアクセスを減らせます。動的コンテンツをキャッシュすれば、データベースの負荷軽減も可能
– コンテンツがキャッシュされている限り、ユーザーは安定したレスポンスを得られる

capistranoを実行

config/deploy/development.rb

role :app, %w{vagrant@locahost}
role :web, %w{vagrant@locahost}
role :db, %w{vagrant@locahost}

server 'localhost', user: 'vagrant', roles: %w{web app}

task :first_task do
	run_locally do
		execute "echo hello world"
	end
end

[vagrant@localhost capistrano]$ cap development first_task
00:00 first_task
01 echo hello world
01 hello world
✔ 01 vagrant@localhost 0.026s

なんじゃこりゃーーーーーーーーーーーーーーーーーーーー?
はああああああああああああああ?

run_locally executeなので、localにログインらしい。。
ちょっとまてよ。なんだこれは。

capistranoのタスクの例

git cloneは git init、リモートリポジトリの各種設定(※)、git pullを一気に実行

set :application, 'finalge_sample_app'
set :repo_url, 'git@github.com:mumoshu/finagle_sample_app.git'

task :update do
	run_locally do
		application = fetch :application
			if test "[ -d #{application} ]"
				execute "cd #{application}; git pull"
			end
		else
			execute "git clone #{fetch :repo_url} #{application}"
		end
	end
end
task :archive => :update do
	run_locally do
		sbt_output = capture "cd #{fetch :application}; sbt pack-archive"

		sbt_output_without_escape_sequences = sbt_output.lines.map { |line| line.gsub(/\e\[\d{1,2}m/, '')}.join

		archive_relative_path = sbt_output_without_escape_sequences.match(/\[info\] Generating (?<archive_path>.+\.tar\.gz)\s*$/)[:archive_path]
		archive_name = archive_relative_path.match(/(?<archive_name>[^\/]+\.tar\.gz)$/)[:archive_name]
		archive_absolute_path = File.join(capture("cd #{fetch(:application)}; pwd").chomp, archive_relative_path)

		info archive_absolute_path
		info archive_name

		set :archive_absolute_path, archive_absolute_path
		set :archive_name, archive_name
	end
end
task :deploy => :archive do
	archive_path = fetch :archive_absolute_path
	archive_name = fetch :archive_name
	release_path = File.join(fetch(:deploy_to), fetch(:application))

	on roles(:web) do
		unless test "[ -d #{release_path} ]"
			execute "mkdir -p #{release_path}"
		end

		upload! archive_path, release_path

		execute "cd #{release_path}; tar -zxvf #{archive_name}"

		ここでアプリケーションの起動
	end
end

尋常じゃねー 差がありすぎて、追い付ける気が全くしねー
だいたいscalaなんて、全然やりこんでねーぞ。。。
capistranoの理解は若干進んだが、後退している気しかしねー

config/deploy.rb

ステージ間共通の設定を書く
– アプリケーション名
– レポジトリ名
– 利用するSCM
– タスク
– それぞれのタスクで実行するコマンド

※SCMとは?
Software Configuration Management(ソフトウェア構成管理)の略。 ソフトウェア開発プロジェクトの成果物を管理する方法論。

set :repo_url, 'git@github.com:mumoshu/finagle_sample_app'

fetch :repo_url

task

task: uptime do
	task somthing
end
task :uptime do
	run_locally do
		localmachine command
	end
	on server do
		server command
	end
end

task :uptime do
	run_locally do
		localmachine command
	end
	on roles(:web) do
		server command
	end
end

executeによるコマンド実行

task :uptime do
	run_locally do
		localmachine command
		execute "uptime"
	end
	on roles(:web) do
		server command
		execute "uptime"
	end
end

caputerによるコマンド実行結果の取得
output = caputer “uptime”
infoによるログ出力
output = caputer “uptime”
info output