FreeBSD で 6rd 環境を構築しよう

前から 6rd のことは気になっていて、そろそろ Open Source で実装でないかなぁ、なんて思いながらもいっこうにでてきそうな気配もなく、こないだ JANOG25 で平井さんと松嶋さんが発表されてた “既存ユーザへのIPv6 提供と実装を考えてみる” を聞いたらやっぱり面白そうで、ここはひとつ FreeBSD に実装してみようか、ということで実装してみました。といってもすでに存在している 6to4 のインターフェース if_stf.c を改造しただけですけど。

  1. BR と CE 両方いけます。
  2. FreeBSD 8 用です。
  3. 利用にあたっては自己責任で。

6rd の詳細は “I-D. IPv6 via IPv4 Service Provider Networks “6rd”” を参照。

概要

とりあえずこんな感じを例に説明します。

6rdfig

4 つの 6rd elements はそれぞれ以下の通りとします。

IPv4PrefixLen 20
6rdPrefix fc00:0:0:1000::
6rdPrefixLen 52
6rdBRIPv4Address 10.0.0.1

6rdPrefixLen + (32 – IPv4PrefixLen) = 64 なので CE は fc00:0:0:1xxx::/64 をもらうことになります。 xxx の部分には IPv4 アドレスの下位 12 ビット(32 – IPv4PrefixLen)が埋まります。

準備

とりあえず上の図で 10.0.0.1/24 が振られている BR と 10.0.0.2/24 が振られている CE の設定方法を書きます。 10.0.0.3/24 の設定はほとんど 10.0.0.2/24 と同じです。違いは多分推測がつくと思います。

まずは パッチ を適用します。

# cd ~
# wget http://bougaidenpa.org/masakazu/wp-content/uploads/2010/01/freebsd8-6rd-20100130.patch.gz
# gzip -d freebsd8-6rd-20100130.patch.gz
# cd /usr
# patch -p0 < ~/freebsd8-6rd-20100130.patch

ifconfig のコンパイルのために if_srd.h が必要になるのでコピーします。

# cp /usr/src/sys/net/if_srd.h /usr/include/net/

ifconfig をコンパイルしてインストールします。

# cd /usr/src/sbin/ifconfig
# make
# make install

if_srd.ko をコンパイルしてインストールします。

# cd /usr/src/sys/modules/if_srd
# make
# make install

/etc/rc.conf にそれぞれ以下のような記述をして再起動します。

# BR の rc.conf
keymap="jp.106"
ipv6_enable="YES"
gateway_enable="YES"
ipv6_gateway_enable="YES"
cloned_interfaces="srd0"
ifconfig_em0="inet 10.0.0.1 netmask 255.255.255.0"
ifconfig_srd0="v4plen 20 pfix fc00:0:0:1000:: plen 52 braddr 10.0.0.1"
ipv6_ifconfig_em1="fc00:1:0:1001::1 prefixlen 64"
ipv6_ifconfig_srd0="fc00:0:0:1001:: prefixlen 128"
ipv6_static_routes="xxx"
ipv6_route_xxx="fc00:0:0:1000:: -prefixlen 52 ::1 -ifp srd0"
# CE の rc.conf
keymap="jp.106"
ipv6_enable="YES"
gateway_enable="YES"
ipv6_gateway_enable="YES"
cloned_interfaces="srd0"
ifconfig_le0="inet 10.0.0.2 netmask 255.255.255.0"
ifconfig_srd0="v4plen 20 pfix fc00:0:0:1000:: plen 52 braddr 10.0.0.1"
ipv6_ifconfig_le1="fc00:0:0:1002::1 prefixlen 64"
ipv6_ifconfig_srd0="fc00:0:0:1002:: prefixlen 128"
ipv6_defaultrouter="::1 -ifp srd0"

BR の em1 側に fc00:1:0:1001::/64 の端末を、 CE の le1 側に fc00:0:0:1002::/64 の端末をそれぞれ接続し、端末間で通信可能か確認します。

説明

4 つの 6rd elements を srd_softc のなかに入れてます。

struct srd_softc {
        struct ifnet    *sc_ifp;
        union {
                struct route  __sc_ro4;
                struct route_in6 __sc_ro6; /* just for safety */
        } __sc_ro46;
#define sc_ro   __sc_ro46.__sc_ro4
        struct mtx      sc_ro_mtx;
        u_int   sc_fibnum;
        const struct encaptab *encap_cookie;
        /* 6rd elements */
        u_int           sc_srd_v4plen;
        struct in6_addr sc_srd_pfix;
        u_int           sc_srd_plen;
        struct in_addr  sc_srd_braddr;
        /* 6rd calculated variables */
        struct in_addr  sc_srd_v4pmask;
        struct in6_addr sc_srd_pmask;
        struct in6_addr sc_srd_dpmask;
};

これらの値は ifconfig コマンドで参照したり設定したりできます。

# ifconfig srd0 create
# ifconfig srd0
srd0: flags=0<> metric 0 mtu 1280
	srd: v4plen 0 pfix :: plen 0 braddr 0.0.0.0
# ifconfig srd0 up
# ifconfig srd0 v4plen 20 pfix fc00:0:0:1000:: plen 52 braddr 10.0.0.1
# ifconfig srd0
srd0: flags=1<UP> metric 0 mtu 1280
	srd: v4plen 20 pfix fc00:0:0:1000:: plen 52 braddr 10.0.0.1

srd の設定をしたら適当にルーティングの設定をします。srd にルーティングをさせるためにはなにか IPv6 アドレスが振られていなければならないようなので適当なアドレスを振っておきます。

# BR の場合
# ifconfig srd0 inet6 fc00:0:0:1001:: prefixlen 128
# route add -inet6 fc00:0:0:1000:: -prefixlen 52 ::1 -ifp srd0
# CE の場合
# ifconfig srd0 inet6 fc00:0:0:1002:: prefixlen 128
# route add -inet6 default ::1 -ifp srd0

IPv4 アドレスの一部をもとに IPv6 プレフィクスが求まるので、実際のところは CE の LAN 側アドレスの設定は結構めんどくさくなると思います。ほとんどの場合で IPv4 アドレスは動的でしょうから。

あと、

Since 6rd delegated prefixes are selected algorithmically from an
IPv4 address, changing the IPv4 address will cause a change in the
IPv6 delegated prefix which would ripple through the site’s network
and could be disruptive. As such, the service provider should assign
CE IPv4 addresses with relatively long lifetimes.

なんて書かれていたりしますが、もしそんな状況になったお客さんから問い合わせがあったとしても「ルーターとパソコンを全部再起動してください。」くらいしか対応できないかも。そんな状況でも IPv4 は影響受けないと思うのでよけいたちが悪いような気もします。どうなんでしょうね。

Catalyst::Manual::Tutorial::CatalystBasics - Catalyst Tutorial - Part 2: Catalyst Application Development Basics [対訳]

Catalyst::Manual::Tutorial::CatalystBasics – Catalyst Tutorial – Part 2: Catalyst Application Development Basics の対訳。2008/01/18 時点での最新版 Catalyst-Manual-5.701003.tar.gz を元にしています。

書きかけなんだけど興味がなくなり更新見込みがなくなったので公開。

誤訳がありましたらコメントにてご指摘ください。

NAME

名前

Catalyst::Manual::Tutorial::CatalystBasics – Catalyst Tutorial – Part 2: Catalyst Application Development Basics

Catalyst::Manual::Tutorial::CatalystBasics – Catalyst チュートリアル – 第二部: Catalyst アプリケーション開発の基礎

OVERVIEW

概要

This is Part 2 of 9 for the Catalyst tutorial.

9 つある Catalyst チュートリアルのうちの 2 つめです。

Tutorial Overview

チュートリアルの概要

  1. Introduction
    導入
  2. Catalyst Basics
    Catalyst の基礎
  3. Basic CRUD
    基礎的な CRUD
  4. Authentication
    認証
  5. Authorization
    承認
  6. Debugging
    デバッグ
  7. Testing
    テスト
  8. Advanced CRUD
    高度な CRUD
  9. Appendices
    補遺
DESCRIPTION

説明

In this part of the tutorial, we will create a very basic Catalyst web application. Though simple in many respects, this section will already demonstrate a number of powerful capabilities such as:

このパートでは、とても基本的な Catalyst Web アプリケーションを作ります。シンプルな多くの側面を通して、次のようないくつかのパワフルな能力をデモします:

  • Helper Scriptsヘルパスクリプト

    Catalyst helper scripts that can be used to rapidly bootstrap the skeletal structure of an application.

    Catalyst ヘルパスクリプトはアプリケーションのひな形構造を素早く立ち上げるために利用されます。

  • MVCMVC

    Model/View/Controller (MVC) provides an architecture that facilitates a clean “separation of control” between the different portions of your application. Given that many other documents cover this subject in detail, MVC will not be discussed in depth here (for an excellent introduction to MVC and general Catalyst concepts, please see Catalyst::Manual::About. In short:

    モデル/ビュー/コントローラ(MVC) はアプリケーションの異なる部品間で容易にクリーンな “制御の分離” を行えるようにするためのアーキテクチャです。この件つついては詳細に説明する文書が多くあるので、ここではこれ以上深く掘り下げません(MVC と一般的な Catalyst のコンセプトについてのすばらしい導入については Catalyst::Manual::Abount を参照してください)。簡単に説明すると:

    • Modelモデル

      The model usually represents a data store. In most applications, the model equates to the objects that are created from and saved to your SQL database.

      モデルはたいていデータストアを表現します。多くのアプリケーションでは、モデルは SQL データベースに作られ、保存されるオブジェクトと同じです。

    • Viewビュー

      The view takes model objects and renders them into something for the end user to look at. Normally this involves a template-generation tool that creates HTML for the user’s web browser, but it could easily be code that generates other forms such as PDF documents, e-mails, or Excel spreadsheets.

      ビューはモデルオブジェクトを得てそれらをエンドユーザに見えるよう描画します。通常ユーザの Web ブラウザのための HTML を生成するテンプレート生成ツールを含みますが、それ以外のフォーム例えば PDF ドキュメントや e-mail や Excel シートなどの場合もあります。

    • Controller

      As suggested by its name, the controller takes user requests and routes them to the necessary model and view.

      名前の通り、コントローラはユーザのリクエストを得て必要なモデルとビユーへ送ります。

  • ORMORM

    The use of Object-Relational Mapping (ORM) technology for database access. Specifically, ORM provides an automated and standardized means to persist and restore objects to/from a relational database.

    データベースへのアクセスにオブジェクト-リレーショナルマッピング(ORM)技術を用います。特に、 ORM はオブジェクトをリレーショナルデータベースへ書き込んだり読み出したりするための自動的で標準かされた方法を提供します。

You can checkout the source code for this example from the catalyst subversion repository as per the instructions in Catalyst::Manual::Tutorial::Intro.

この例のソースコードを Catalyst Subversion リポジトリから Catalyst::Manual::Tutorial::Intro にある手順でチェックアウトできます。

CREATE A CATALYST PROJECT

Catalyst プロジェクトを作る

Catalyst provides a number of helper scripts that can be used to quickly flesh out the basic structure of your application. All Catalyst projects begin with the catalyst.pl helper (see Catalyst::Helper for more information on helpers). Also note that as of Catalyst 5.7000, you will not have the helper scripts unless you install both Catalyst::Runtime and Catalyst::Devel.

Catalyst にはアプリケーションの基本的な構造を素早く具体化するためのヘルパスクリプトがいくつか提供されています。すべての Catalyst プロジェクトは catalyst.pl ヘルパからはじまります(ヘルパに関する詳細な情報は Catalyst::Helper を参照してください)。Catalyst 5.7000 では Catalyst::Runtime と Catalyst::Devel の両方がインストールされていないとヘルパスクリプトを利用できないので注意してください。

In the case of this tutorial, use the Catalyst catalyst.pl script to initialize the framework for an application called MyApp:

このチュートリアルでは、 MyAppと呼ばれるアプリケーションのフレームワークを初期化するため catalyst.pl というスクリプトを用います:

$ catalyst.pl MyApp
created "MyApp"
created "MyApp/script"
created "MyApp/lib"
created "MyApp/root"
...
created "MyApp/script/myapp_create.pl"
$ cd MyApp

The catalyst.pl helper script will display the names of the directories and files it creates.

catalyst.pl ヘルパスクリプトは作成したディレクトリとファイルを表示します。

Though it’s too early for any significant celebration, we already have a functioning application. Run the following command to run this application with the built-in development web server:

お祝いするにはまだ早いですが、すでに機能するアプリケーションになりました。以下のコマンドを実行することで組み込みの開発 Web サーバでアクリケーションを実行できます:

$ script/myapp_server.pl
[debug] Debug messages enabled
[debug] Loaded plugins:
.----------------------------------------------------------------------------.
| Catalyst::Plugin::ConfigLoader  0.13                                       |
| Catalyst::Plugin::Static::Simple  0.14                                     |
'----------------------------------------------------------------------------'
[debug] Loaded dispatcher "Catalyst::Dispatcher"
[debug] Loaded engine "Catalyst::Engine::HTTP"
[debug] Found home "/home/me/MyApp"
[debug] Loaded Config "/home/me/myapp.yml"
[debug] Loaded components:
.-----------------------------------------------------------------+----------.
| Class                                                           | Type     |
+-----------------------------------------------------------------+----------+
| MyApp::Controller::Root                                         | instance |
'-----------------------------------------------------------------+----------'
[debug] Loaded Private actions:
.----------------------+--------------------------------------+--------------.
| Private              | Class                                | Method       |
+----------------------+--------------------------------------+--------------+
| /default             | MyApp::Controller::Root              | default      |
| /end                 | MyApp::Controller::Root              | end          |
'----------------------+--------------------------------------+--------------'
[info] MyApp powered by Catalyst 5.7002
You can connect to your server at http://localhost:3000

NOTE: Be sure you run the script/myapp_server.pl command from the ‘base’ directory of your application, not inside the script directory itself. It doesn’t make a difference at this point, but it will as soon as we get the database going in the next section.

ノート: script ディレクトリの中からではなく、アプリケーションの ‘ベース’ ディレクトリから script/myapp_server.pl コマンドを実行することに注意してください。現時点ではいずれにせよかわりありませんが、時節でデータベースが出た時点でかわってきます。

Point your web browser to http://localhost:3000 (substituting a different hostname or IP address as appropriate) and you should be greeted by the Catalyst welcome screen. Information similar to the following should be appended to the logging output of the development server:

Web ブラウザで http://localhost:3000 を参照すると(異なるホスト名や IP アドレスなど適するものに置き換えてください)、 Catalyst のようこそ画面が表示されるはずです。開発サーバでは以下のようなロギング出力が表示されるはずです:

[info] *** Request 1 (0.043/s) [6003] [Fri Jul  7 13:32:53 2006] ***
[debug] "GET" request for "/" from "127.0.0.1"
[info] Request took 0.067675s (14.777/s)
.----------------------------------------------------------------+-----------.
| Action                                                         | Time      |
+----------------------------------------------------------------+-----------+
| /default                                                       | 0.002844s |
| /end                                                           | 0.000207s |
'----------------------------------------------------------------+-----------'

Press Ctrl-C to break out of the development server.

Ctrl-C で開発サーバを停止します。

CREATE A SQLITE DATABASE

SQLite データベースの作成

In this step, we make a text file with the required SQL commands to create a database table and load some sample data. Open myapp01.sql in your editor and enter:

このステップでは、データベーステーブルを作りいくつかサンプルデータを読み込むために必要となる SQL コマンドを書いたテキストファイルを作ります。エディタで myapp01.sql を開き以下の内容を書いてください:

--
-- Create a very simple database to hold book and author information
--
CREATE TABLE books (
id          INTEGER PRIMARY KEY,
title       TEXT ,
rating      INTEGER
);
-- 'book_authors' is a many-to-many join table between books & authors
CREATE TABLE book_authors (
book_id     INTEGER,
author_id   INTEGER,
PRIMARY KEY (book_id, author_id)
);
CREATE TABLE authors (
id          INTEGER PRIMARY KEY,
first_name  TEXT,
last_name   TEXT
);
---
--- Load some sample data
---
INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
INSERT INTO authors VALUES (3, 'Christian', 'Degu');
INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
INSERT INTO authors VALUES (7, 'Nathan', 'Torkington');
INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
INSERT INTO book_authors VALUES (1, 1);
INSERT INTO book_authors VALUES (1, 2);
INSERT INTO book_authors VALUES (1, 3);
INSERT INTO book_authors VALUES (2, 4);
INSERT INTO book_authors VALUES (3, 5);
INSERT INTO book_authors VALUES (4, 6);
INSERT INTO book_authors VALUES (4, 7);
INSERT INTO book_authors VALUES (5, 8);

TIP: See Appendix 1 for tips on removing the leading spaces when cutting and pasting example code from POD-based documents.

TIP: POD ベースのドキュメントからサンプルコードをコピー&ペーストし最初にあるスペースを取り除く方法は補遺 1 をみてください。

Then use the following command to build a myapp.db SQLite database:

次のコマンドを実行し myapp.db SQLite データベースを構築します:

$ sqlite3 myapp.db < myapp01.sql

If you need to create the database more than once, you probably want to issue the rm myapp.db command to delete the database before you use the sqlite3 myapp.db < myapp01.sql command.

もし一回以上データベースを作成したいときは sqlite3 myapp.db < myapp01.sql を実行する前に rm myapp.db でデータベースを消したいと思うでしょう。

Once the myapp.db database file has been created and initialized, you can use the SQLite command line environment to do a quick dump of the database contents:

一度 myapp.db データベースが作成され、初期化されれば、 SQLite コマンドライン環境でデータベースの内容のクイックダンプを取得できます:

$ sqlite3 myapp.db
SQLite version 3.2.2
Enter ".help" for instructions
sqlite> select * from books;
1|CCSP SNRS Exam Certification Guide|5
2|TCP/IP Illustrated, Volume 1|5
3|Internetworking with TCP/IP Vol.1|4
4|Perl Cookbook|5
5|Designing with Web Standards|5
sqlite> .q
$

Or:

或は:

$ sqlite3 myapp.db "select * from books"
1|CCSP SNRS Exam Certification Guide|5
2|TCP/IP Illustrated, Volume 1|5
3|Internetworking with TCP/IP Vol.1|4
4|Perl Cookbook|5
5|Designing with Web Standards|5

As with most other SQL tools, if you are using the full “interactive” environment you need to terminate your SQL commands with a “;” (it’s not required if you do a single SQL statement on the command line). Use “.q” to exit from SQLite from the SQLite interactive mode and return to your OS command prompt.

ほとんどの他の SQL ツールのように、もし完全に “インタラクティブ” な環境を使っているのであれば SQL コマンドを “;” で終端する必要がある(これはコマンドラインからひとつの SQL 分を実行するときは必要ない)。SQLite のインタラクティブモードから抜けたいときは “.q” を使う。そうすると OS のコマンドプロンプトに戻ることができる。

EDIT THE LIST OF CATALYST PLUGINS

Catalyst プラグインリストの編集

One of the greatest benefits of Catalyst is that it has such a large library of plugins available. Plugins are used to seamlessly integrate existing Perl modules into the overall Catalyst framework. In general, they do this by adding additional methods to the context object (generally written as $c) that Catalyst passes to every component throughout the framework.

Catalyst を使う最も大きな利点のひとつは利用可能なプラグインライブラリ大量に存在することです。プラグインは Catalyst フレームワークを超えてすでに存在する Perl モジュールとシームレスに利用できます。一般に、フレームワークないのすべてのコンポーネントに渡される context オブジェクト(一般に $c と書かれます)に追加のメソッドを加えることによって実現します。

By default, Catalyst enables three plugins/flags:

デフォルトでは、 Catalyst は以下の 3 つのプラグインとフラグを有効にします:

  • -Debug Flag-Debug フラグ

    Enables the Catalyst debug output you saw when we started the script/myapp_server.pl development server earlier. You can remove this plugin when you place your application into production.

    先ほど開発サーバーで script/myapp_server.pl を実行した際にみた Catalyst デバッグ出力を有効にします。アプリケーションを製品として設置する際にこのプラグインを削ることができます。

    As you may have noticed, -Debug is not a plugin, but a flag. Although most of the items specified on the use Catalyst line of your application class will be plugins, Catalyst supports a limited number of flag options (of these, -Debug is the most common). See the documentation for Catalyst.pm to get details on other flags (currently -Engine, -Home, and -Log).

    気づいたかもしれませんが -Debug はプラグインではなく、フラグです。しかしながら、ほとんどの use Catalyst 行で指定されるアイテムはプラグインです。 Catalyst でサポートしているフラグの数は限られています(これらのなかで -Debug が最も一般的です)。他のフラグ(現時点では -Engine、 -Home、そして -Log があります)の詳細については Catalyst.pm のドキュメントを参照してください。

    If you prefer, you can use the $c->debug method to enable debug messages.

    お好みに応じて、 $c->debug というメソッドを用いてデバッグメッセージを有効化することもできます。

  • Catalyst::Plugin::ConfigLoaderCatalyst::Plugin::ConfigLoader

    ConfigLoader provides an automatic way to load configurable parameters for your application from a central YAML file (versus having the values hard-coded inside your Perl modules). If you have not been exposed to YAML before, it is a human-readable data serialization format that can be used to read (and write) values to/from text files. We will see how to use this feature of Catalyst during the authentication and authorization sections (Part 4 and Part 5).

    ConfigLoader はあなたのアプリケーションで(Perl コード中に値をハードコードする代わりに)自動的に中央に配置した YAML ファイルから設定パラメータを取得する方法を提供します。YAML に触れたことがない方のために説明すると、 YAML はテキストファイル(から/へ)データを読む(もしくは書く)ことができる人が読めるデータ永続化フォーマットです。認証と承認の箇所(第四部と第五部)でこれらの機能の使い方をみます。

  • Catalyst::Plugin::Static::SimpleCatalyst::Plugin::Static::Simple

    Static::Simple provides an easy method of serving static content such as images and CSS files under the development server.

    Static::Simple は開発サーバで画像や CSS ファイルといったスタティックなコンテンツを簡単に提供するための方法を提供します。

To modify the list of plugins, edit lib/MyApp.pm (this file is generally referred to as your application class) and delete the line with:

プラグインリストを変更するためには、 lib/MyApp.pm(このファイルはアプリケーションクラスとして参照されます)を編集し、以下の行を:

use Catalyst qw/-Debug ConfigLoader Static::Simple/;

Replace it with:

以下のように差し替えます:

use Catalyst qw/
-Debug
ConfigLoader
Static::Simple
StackTrace
/;

This tells Catalyst to start using one new plugin:

上記では Catalyst に対して新しいプラグインを使い始めることを教えています。

  • Catalyst::Plugin::StackTraceCatalyst::Plugin::StackTrace

    Adds a stack trace to the standard Catalyst “debug screen” (this is the screen Catalyst sends to your browser when an error occurs).

    標準の Catalyst “デバッグ画面”(エラーが起こったときに Catalyst がブラウザに対して表示する画面です)にスタックトレースを追加します。

    Note: StackTrace output appears in your browser, not in the console window from which you’re running your application, which is where logging output usually goes.

    StackTrace 出力はアプリケーションを実行しているコンソール上ではなくブラウザ上に現れます。ログ出力は通常こちらに現れます。

Note that when specifying plugins on the use Catalyst line, you can omit Catalyst::Plugin:: from the name. Additionally, you can spread the plugin names across multiple lines as shown here, or place them all on one (or more) lines as with the default configuration.

use Catalyst 行でプラグインを指定する際、その名前から Catalyst::Plugin:: を省くことができます。また、ここに書いたようにプラグイン名を複数業にわたって書くことも、デフォルトの設定のようにすべてを一行(あるいはもっと)に書くこともできます。

TIP: You may see examples that include the Catalyst::Plugin::DefaultEnd plugins. As of Catalyst 5.7000, DefaultEnd has been deprecated in favor of Catalyst::Action::RenderView (as the name of the package suggests, RenderView is not a plugin, but an action). The purpose of both is essentially the same: forward processing to the view to be rendered. Applications generated under 5.7000 should automatically use RenderView and “just work” for most applications. For more information on RenderView and the various options for forwarding to your view logic, please refer to the “Using RenderView for the Default View” section under “CATALYST VIEWS” below.

Catalyst::Plugin::DefaultEnd を利用しているサンプルを見かけるかもしれません。Catalyst 5.7000 現在、 DefaultEnd は Catalyst::Action::RenderView(名前の通り RenderView はプラグインではなくアクションです)により非推奨となっています。これらの目的は本質的には一緒です: 表示されるべきビューへ処理を進めます。 5.7000 の元に生成されたアプリケーションは自動的に RenderView を利用し、ほとんどのアプリケーションで”うまく動きます”。 RenderView の詳細な情報とビューロジックを転送する多彩なオプションについては以下の “Catalyst ビュー” の “デフォルトのビューに RenderView を使う” を参照してください。

DATABASE ACCESS WITH DBIx::Class

DBIx::Class によるデータベースアクセス

Catalyst can be used with virtually any form of persistent datastore available via Perl. For example, Catalyst::Model::DBI can be used to easily access databases through the traditional Perl DBI interface. However, most Catalyst applications use some form of ORM technology to automatically create and save model objects as they are used. Although Tony Bowden’s Class::DBI has been the traditional Perl ORM engine, Matt Trout’s DBIx::Class (abbreviated as “DBIC”) has rapidly emerged as the Perl-based ORM technology of choice. Most new Catalyst applications rely on DBIC, as will this tutorial.

Catalyst は Perl で利用可能なすべての永続データストアを仮想的に利用できます。例えば Catalyst::Model::DBI を伝統的な Perl の DBI インターフェースを通じた簡単なデータベースアクセスに利用できます。しかし、ほとんどの Catalyst アプリケーションは利用するモデルオブジェクトを自動的に生成したり保存したりするためになにかしらの ORM 技術を利用します。Tony Bowden の Class:DBI は伝統的な Perl ORM エンジンですが、 Matt Trout の DBIx::Class(“DBIC” と略されます) は Perl での ORM 技術の選択として急に浮かび上がってきました。ほとんどの新しい Catalyst アプリケーションは DBIC に依っていますので、このチュートリアルでも従います。

Note: See Catalyst::Model::CDBI for more information on using Catalyst with Class::DBI.

ノート: Class::DBI で Catalyst を利用するときの詳細な情報は Catalyst::Model::CDBI を参照してください。

Create a DBIC Schema File

DBIC スキーマファイルの作成

DBIx::Class uses a schema file to load other classes that represent the tables in your database (DBIC refers to these “table objects” as “result sources”; see DBIx::Class::ResultSource). In this case, we want to load the model object for the books, book_authors, and authors tables created in the previous step.

Create lib/MyAppDB.pm in your editor and insert:

package MyAppDB;
=head1 NAME
MyAppDB - DBIC Schema Class
=cut
# Our schema needs to inherit from 'DBIx::Class::Schema'
use base qw/DBIx::Class::Schema/;
# Need to load the DB Model classes here.
# You can use this syntax if you want:
#    __PACKAGE__->load_classes(qw/Book BookAuthor Author/);
# Also, if you simply want to load all of the classes in a directory
# of the same name as your schema class (as we do here) you can use:
#    __PACKAGE__->load_classes(qw//);
# But the variation below is more flexible in that it can be used to
# load from multiple namespaces.
__PACKAGE__->load_classes({
MyAppDB => [qw/Book BookAuthor Author/]
});
1;

Note: __PACKAGE__ is just a shorthand way of referencing the name of the package where it is used. Therefore, in MyAppDB.pm, __PACKAGE__ is equivalent to MyAppDB.

Note: As with any Perl package, we need to end the last line with a statement that evaluates to true. This is customarily done with 1 on a line by itself as shown above.

Create the DBIC “Result Source” Files

In this step, we create “table classes” (again, these are called a “result source” classes in DBIC) that act as model objects for the books, book_authors, and authors tables in our database.

First, create a directory to hold the class:

$ mkdir lib/MyAppDB

Then create lib/MyAppDB/Book.pm in your editor and enter:

package MyAppDB::Book;
use base qw/DBIx::Class/;
# Load required DBIC stuff
__PACKAGE__->load_components(qw/PK::Auto Core/);
# Set the table name
__PACKAGE__->table('books');
# Set columns in table
__PACKAGE__->add_columns(qw/id title rating/);
# Set the primary key for the table
__PACKAGE__->set_primary_key(qw/id/);
#
# Set relationships:
#
# has_many():
#   args:
#     1) Name of relationship, DBIC will create accessor with this name
#     2) Name of the model class referenced by this relationship
#     3) Column name in *foreign* table
__PACKAGE__->has_many(book_authors => 'MyAppDB::BookAuthor', 'book_id');
# many_to_many():
#   args:
#     1) Name of relationship, DBIC will create accessor with this name
#     2) Name of has_many() relationship this many_to_many() is shortcut for
#     3) Name of belongs_to() relationship in model class of has_many() above
#   You must already have the has_many() defined to use a many_to_many().
__PACKAGE__->many_to_many(authors => 'book_authors', 'author');
=head1 NAME
MyAppDB::Book - A model object representing a book.
=head1 DESCRIPTION
This is an object that represents a row in the 'books' table of your application
database.  It uses DBIx::Class (aka, DBIC) to do ORM.
For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
Offline utilities may wish to use this class directly.
=cut
1;

This defines both a has_many and a many_to_many relationship. The many_to_many relationship is optional, but it makes it easier to map a book to its collection of authors. Without it, we would have to “walk” though the book_authors table as in $book->book_authors->first->author->last_name (we will see examples on how to use DBIC objects in your code soon, but note that because $book->book_authors can return multiple authors, we have to use first to display a single author). many_to_many allows us to use the shorter $book->authors->first->last_name. Note that you cannot define a many_to_many relationship without also having the has_many relationship in place.

Next, create lib/MyAppDB/Author.pm in your editor and enter:

package MyAppDB::Author;
use base qw/DBIx::Class/;
# Load required DBIC stuff
__PACKAGE__->load_components(qw/PK::Auto Core/);
# Set the table name
__PACKAGE__->table('authors');
# Set columns in table
__PACKAGE__->add_columns(qw/id first_name last_name/);
# Set the primary key for the table
__PACKAGE__->set_primary_key(qw/id/);
#
# Set relationships:
#
# has_many():
#   args:
#     1) Name of relationship, DBIC will create accessor with this name
#     2) Name of the model class referenced by this relationship
#     3) Column name in *foreign* table
__PACKAGE__->has_many(book_author => 'MyAppDB::BookAuthor', 'author_id');
# many_to_many():
#   args:
#     1) Name of relationship, DBIC will create accessor with this name
#     2) Name of has_many() relationship this many_to_many() is shortcut for
#     3) Name of belongs_to() relationship in model class of has_many() above
#   You must already have the has_many() defined to use a many_to_many().
__PACKAGE__->many_to_many(books => 'book_author', 'book');
=head1 NAME
MyAppDB::Author - A model object representing an author of a book (if a book has
multiple authors, each will be represented be separate Author object).
=head1 DESCRIPTION
This is an object that represents a row in the 'authors' table of your application
database.  It uses DBIx::Class (aka, DBIC) to do ORM.
For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
Offline utilities may wish to use this class directly.
=cut
1;

Finally, create lib/MyAppDB/BookAuthor.pm in your editor and enter:

package MyAppDB::BookAuthor;
use base qw/DBIx::Class/;
# Load required DBIC stuff
__PACKAGE__->load_components(qw/PK::Auto Core/);
# Set the table name
__PACKAGE__->table('book_authors');
# Set columns in table
__PACKAGE__->add_columns(qw/book_id author_id/);
# Set the primary key for the table
__PACKAGE__->set_primary_key(qw/book_id author_id/);
#
# Set relationships:
#
# belongs_to():
#   args:
#     1) Name of relationship, DBIC will create accessor with this name
#     2) Name of the model class referenced by this relationship
#     3) Column name in *this* table
__PACKAGE__->belongs_to(book => 'MyAppDB::Book', 'book_id');
# belongs_to():
#   args:
#     1) Name of relationship, DBIC will create accessor with this name
#     2) Name of the model class referenced by this relationship
#     3) Column name in *this* table
__PACKAGE__->belongs_to(author => 'MyAppDB::Author', 'author_id');
=head1 NAME
MyAppDB::BookAuthor - A model object representing the JOIN between an author and
a book.
=head1 DESCRIPTION
This is an object that represents a row in the 'book_authors' table of your
application database.  It uses DBIx::Class (aka, DBIC) to do ORM.
You probably won't need to use this class directly -- it will be automatically
used by DBIC where joins are needed.
For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
Offline utilities may wish to use this class directly.
=cut
1;

Note: This sample application uses a plural form for the database tables (e.g., books and authors) and a singular form for the model objects (e.g., Book and Author); however, Catalyst places no restrictions on the naming conventions you wish to use.

Use Catalyst::Model::DBIC::Schema To Load The Model Class

When Catalyst::Model::DBIC::Schema is in use, Catalyst essentially reads an existing copy of your database model and creates a new set of objects under MyApp::Model for use inside of Catalyst.

Note: With Catalyst::Model::DBIC::Schema you essentially end up with two sets of model classes (only one of which you write… the other set is created automatically in memory when your Catalyst application initializes). For this tutorial application, the important points to remember are: you write the result source files in MyAppDB, but within Catalyst you use the automatically created model classes in MyApp::Model.

Use the Catalyst::Helper::Model::DBIC::Schema helper script to create the model class that loads up the model we created in the previous step:

$ script/myapp_create.pl model MyAppDB DBIC::Schema MyAppDB dbi:SQLite:myapp.db '' '' '{ AutoCommit => 1 }'
exists "/root/dev/MyApp/script/../lib/MyApp/Model"
exists "/root/dev/MyApp/script/../t"
created "/root/dev/MyApp/script/../lib/MyApp/Model/MyAppDB.pm"
created "/root/dev/MyApp/script/../t/model_MyAppDB.t"

Where the first MyAppDB is the name of the class to be created by the helper in lib/MyApp/Model and the second MyAppDB is the name of existing schema file we created (in lib/MyAppDB.pm). You can see that the helper creates a model file under lib/MyApp/Model (Catalyst has a separate directory under lib/MyApp for each of the three parts of MVC: Model, View, and Controller [although older Catalyst applications often use the directories M, V, and C]).

CREATE A CATALYST CONTROLLER

Controllers are where you write methods that interact with user input–typically, controller methods respond to GET and POST messages from the user’s web browser.

Use the Catalyst create script to add a controller for book-related actions:

$ script/myapp_create.pl controller Books
exists "/root/dev/MyApp/script/../lib/MyApp/Controller"
exists "/root/dev/MyApp/script/../t"
created "/root/dev/MyApp/script/../lib/MyApp/Controller/Books.pm"
created "/root/dev/MyApp/script/../t/controller_Books.t"

Then edit lib/MyApp/Controller/Books.pm and add the following method to the controller:

=head2 list
Fetch all book objects and pass to books/list.tt2 in stash to be displayed
=cut
sub list : Local {
# Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
# 'Context' that's used to 'glue together' the various components
# that make up the application
my ($self, $c) = @_;
# Retrieve all of the book records as book model objects and store in the
# stash where they can be accessed by the TT template
$c->stash->{books} = [$c->model('MyAppDB::Book')->all];
# Set the TT template to use.  You will almost always want to do this
# in your action methods (action methods respond to user input in
# your controllers).
$c->stash->{template} = 'books/list.tt2';
}

Note: Programmers experienced with object-oriented Perl should recognize $self as a reference to the object where this method was called. On the other hand, $c will be new to many Perl programmers who have not used Catalyst before (it’s sometimes written as $context). The Context object is automatically passed to all Catalyst components. It is used to pass information between components and provide access to Catalyst and plugin functionality.

TIP: You may see the $c->model(‘MyAppDB::Book’) used above written as $c->model(‘MyAppDB’)->resultset(‘Book). The two are equivalent.

Note: Catalyst actions are regular Perl methods, but they make use of Nicholas Clark’s attributes module (that’s the : Local next to the sub list in the code above) to provide additional information to the Catalyst dispatcher logic.

CATALYST VIEWS

Views are where you render output, typically for display in the user’s web browser, but also possibly using other display output-generation systems. As with virtually every aspect of Catalyst, options abound when it comes to the specific view technology you adopt inside your application. However, most Catalyst applications use the Template Toolkit, known as TT (for more information on TT, see http://www.template-toolkit.org). Other popular view technologies include Mason (http://www.masonhq.com and http://www.masonbook.com) and HTML::Template (http://html-template.sourceforge.net).

Create a Catalyst View Using TTSite

When using TT for the Catalyst view, there are two main helper scripts:

  • Catalyst::Helper::View::TT
  • Catalyst::Helper::View::TTSite

Both are similar, but TT merely creates the lib/MyApp/View/TT.pm file and leaves the creation of any hierarchical template organization entirely up to you. (It also creates a t/view_TT.t file for testing; test cases will be discussed in Part 7). The TTSite helper creates a modular and hierarchical view layout with separate Template Toolkit (TT) files for common header and footer information, configuration values, a CSS stylesheet, and more.

While TTSite is useful to bootstrap a project, we recommend that unless you know what your’re doing or want to pretty much use the supplied templates as is, that you use the plain Template Toolkit view when starting a project from scratch. This is because TTSite can be tricky to customize. Additionally TT contains constructs that you need to learn yourself if you’re going to be a serious user of TT. Our experience suggests that you’re better off learning these from scratch. We use TTSite here precisely because it is useful for bootstrap/prototype purposes.

Enter the following command to enable the TTSite style of view rendering for this tutorial:

$ script/myapp_create.pl view TT TTSite
exists "/root/dev/MyApp/script/../lib/MyApp/View"
exists "/root/dev/MyApp/script/../t"
created "/root/dev/MyApp/script/../lib/MyApp/View/TT.pm"
created "/root/dev/MyApp/script/../root/lib"
...
created "/root/dev/MyApp/script/../root/src/ttsite.css"

This puts a number of files in the root/lib and root/src directories that can be used to customize the look and feel of your application. Also take a look at lib/MyApp/View/TT.pm for config values set by the TTSite helper.

TIP: Note that TTSite does one thing that could confuse people who are used to the normal TT Catalyst view: it redefines the Catalyst context object in templates from its usual c to Catalyst. When looking at other Catalyst examples, remember that they almost always use c. Note that Catalyst and TT do not complain when you use the wrong name to access the context object…TT simply outputs blanks for that bogus logic (see next tip to change this behavior with TT DEBUG options). Finally, be aware that this change in name only applies to how the context object is accessed inside your TT templates; your controllers will continue to use $c (or whatever name you use when fetching the reference from @_ inside your methods). (You can change back to the “default” behavior be removing the CATALYST_VAR line from lib/MyApp/View/TT.pm, but you will also have to edit root/lib/config/main and root/lib/config/url. If you do this, be careful not to have a collision between your own c variable and the Catalyst c variable.)

TIP: When troubleshooting TT it can be helpful to enable variable DEBUG options. You can do this in a Catalyst environment by adding a DEBUG line to the __PACKAGE__-config> declaration in lib/MyApp/View/TT.pm:

__PACKAGE__->config({
CATALYST_VAR => 'Catalyst',
...
DEBUG        => 'undef',
...
});

There are a variety of options you can use, such as ‘undef’, ‘all’, ‘service’, ‘context’, ‘parser’, ‘provider’, and ‘service’. See Template::Constants for more information (remove the DEBUG_ portion of the name shown in the TT docs and convert to lower case for use inside Catalyst).

NOTE: Please be sure to disable TT debug options before continuing the tutorial (especially the ‘undef’ option — leaving this enabled will conflict with several of the conventions used by this tutorial and TTSite to leave some variables undefined on purpose).

Using RenderView for the Default View

Once your controller logic has processed the request from a user, it forwards processing to your view in order to generate the appropriate response output. Catalyst v5.7000 ships with a new mechanism, Catalyst::Action::RenderView, that automatically performs this operation. If you look in lib/MyApp/Controller/Root.pm, you should see the empty definition for the sub end method:

sub end : ActionClass('RenderView') {}

The following bullet points provide a quick overview of the RenderView process:

  • Root.pm is designed to hold application-wide logic.
  • At the end of a given user request, Catalyst will call the most specific end method that’s appropriate. For example, if the controller for a request has an end method defined, it will be called. However, if the controller does not define a controller-specific end method, the “global” end method in Root.pm will be called.
  • Because the definition includes an ActionClass attribute, the Catalyst::Action::RenderView logic will be executed after any code inside the definition of sub end is run. See Catalyst::Manual::Actions for more information on ActionClass.
  • Because sub end is empty, this effectively just runs the default logic in RenderView. However, you can easily extend the RenderView logic by adding your own code inside the empty method body ({}) created by the Catalyst Helpers when we first ran the catalyst.pl to initialize our application. See Catalyst::Action::RenderView for more detailed information on how to extended RenderView in sub end.
The History Leading Up To RenderView

Although RenderView strikes a nice balance between default behavior and easy extensibility, it is a new feature that won’t appear in most existing Catalyst examples. This section provides some brief background on the evolution of default view rendering logic with an eye to how they can be migrated to RenderView:

  • Private end Action in Application ClassOlder Catalyst-related documents often suggest that you add a “private end action” to your application class (MyApp.pm) or Root.pm (MyApp/Controller/Root.pm). These examples should be easily converted to RenderView by simply adding the attribute :ActionClass(‘RenderView’) to the sub end definition. If end sub is defined in your application class (MyApp.pm), you should also migrate it to MyApp/Controller/Root.pm.
  • Catalyst::Plugin::DefaultEndDefaultEnd represented the “next step” in passing processing from your controller to your view. It has the advantage of only requiring that DefaultEnd be added to the list of plugins in lib/MyApp.pm. It also allowed you to add “dump_info=1″ (precede with “?” or “&” depending on where it is in the URL) to force the debug screen at the end of the Catalyst request processing cycle. However, it was more difficult to extend than the RenderView mechanism, and is now deprecated.
  • Catalyst::Action::RenderViewAs discussed above, the current recommended approach to handling your view logic relies on Catalyst::Action::RenderView. Although similar in first appearance to the “private end action” approach, it utilizes Catalyst’s “ActionClass” mechanism to provide both automatic default behavior (you don’t have to include a plugin as with DefaultEnd) and easy extensibility. As with DefaultEnd, it allows you to add “dump_info=1″ (precede with “?” or “&” depending on where it is in the URL) to force the debug screen at the end of the Catalyst request processing cycle.

It is recommended that all Catalyst applications use or migrate to the RenderView approach.

Globally Customize Every View

When using TTSite, files in the subdirectories of root/lib can be used to make changes that will appear in every view. For example, to display optional status and error messages in every view, edit root/lib/site/layout, updating it to match the following (the two HTML span elements are new):

<div id="header">[% PROCESS site/header %]</div>
<div id="content">
<span class="message">[% status_msg %]</span>
<span class="error">[% error_msg %]</span>
[% content %]
</div>
<div id="footer">[% PROCESS site/footer %]</div>

If we set either message in the Catalyst stash (e.g., $c->stash->{status_msg} = ‘Request was successful!’) it will be displayed whenever any view used by that request is rendered. The message and error CSS styles are automatically defined in root/src/ttsite.css and can be customized to suit your needs.

Note: The Catalyst stash only lasts for a single HTTP request. If you need to retain information across requests you can use Catalyst::Plugin::Session (we will use Catalyst sessions in the Authentication part of the tutorial).

Create a TT Template Page

To add a new page of content to the TTSite view hierarchy, just create a new .tt2 file in root/src. Only include HTML markup that goes inside the HTML and tags, TTSite will use the contents of root/lib/site to add the top and bottom.

First create a directory for book-related TT templates:

$ mkdir root/src/books

Then create root/src/books/list.tt2 in your editor and enter:

[% # This is a TT comment.  The '-' at the end "chomps" the newline.  You won't -%]
[% # see this "chomping" in your browser because HTML ignores blank lines, but  -%]
[% # it WILL eliminate a blank line if you view the HTML source.  It's purely   -%]
[%- # optional, but both the beginning and the ending TT tags support chomping. -%]
[% # Provide a title to root/lib/site/header -%]
[% META title = 'Book List' -%]
<table>
<tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
[% # Display each book in a table row %]
[% FOREACH book IN books -%]
<tr>
<td>[% book.title %]</td>
<td>[% book.rating %]</td>
<td>
[% # First initialize a TT variable to hold a list.  Then use a TT FOREACH -%]
[% # loop in 'side effect notation' to load just the last names of the     -%]
[% # authors into the list.  Note that the 'push' TT vmethod does not      -%]
[% # a value, so nothing will be printed here.  But, if you have something -%]
[% # in TT that does return a method and you don't want it printed, you    -%]
[% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to     -%]
[% # call it and discard the return value.                                 -%]
[% tt_authors = [ ];
tt_authors.push(author.last_name) FOREACH author = book.authors %]
[% # Now use a TT 'virtual method' to display the author count in parens   -%]
([% tt_authors.size %])
[% # Use another TT vmethod to join & print the names & comma separators   -%]
[% tt_authors.join(', ') %]
</td>
</tr>
[% END -%]
</table>

As indicated by the inline comments above, the META title line uses TT’s META feature to provide a title to root/lib/site/header. Meanwhile, the outer FOREACH loop iterates through each book model object and prints the title and rating fields. An inner FOREACH loop prints the last name of each author in a comma-separated list within a single table cell.

If you are new to TT, the [% and %] tags are used to delimit TT code. TT supports a wide variety of directives for “calling” other files, looping, conditional logic, etc. In general, TT simplifies the usual range of Perl operators down to the single dot (.) operator. This applies to operations as diverse as method calls, hash lookups, and list index values (see http://www.template-toolkit.org/docs/default/Manual/Variables.html for details and examples). In addition to the usual Template module Pod documentation, you can access the TT manual at http://www.template-toolkit.org/docs/default/.

NOTE: The TTSite helper creates several TT files using an extension of .tt2. Most other Catalyst and TT examples use an extension of .tt. You can use either extension (or no extension at all) with TTSite and TT, just be sure to use the appropriate extension for both the file itself and the $c->stash->{template} = … line in your controller. This document will use .tt2 for consistency with the files already created by the TTSite helper.

RUN THE APPLICATION

First, let’s enable an environment variable option that causes DBIx::Class to dump the SQL statements it’s using to access the database (this option can provide extremely helpful troubleshooting information):

$ export DBIC_TRACE=1

NOTE: You can also use the older export DBIX_CLASS_STORAGE_DBI_DEBUG=1, but that’s a lot more to type.

This assumes you are using BASH as your shell — adjust accordingly if you are using a different shell (for example, under tcsh, use setenv DBIX_CLASS_STORAGE_DBI_DEBUG 1).

NOTE: You can also set this in your code using $class->storage->debug(1);. See DBIx::Class::Manual::Troubleshooting for details (including options to log to file instead of displaying to the Catalyst development server log).

Then run the Catalyst “demo server” script:

$ script/myapp_server.pl

Your development server log output should display something like:

$ script/myapp_server.pl
[debug] Debug messages enabled
[debug] Loaded plugins:
.----------------------------------------------------------------------------.
| Catalyst::Plugin::ConfigLoader  0.13                                       |
| Catalyst::Plugin::StackTrace  0.06                                         |
| Catalyst::Plugin::Static::Simple  0.14                                     |
'----------------------------------------------------------------------------'
[debug] Loaded dispatcher "Catalyst::Dispatcher"
[debug] Loaded engine "Catalyst::Engine::HTTP"
[debug] Found home "/home/me/MyApp"
[debug] Loaded Config "/home/me/myapp.yml"
[debug] Loaded components:
.-----------------------------------------------------------------+----------.
| Class                                                           | Type     |
+-----------------------------------------------------------------+----------+
| MyApp::Controller::Books                                        | instance |
| MyApp::Controller::Root                                         | instance |
| MyApp::Model::MyAppDB                                           | instance |
| MyApp::Model::MyAppDB::Author                                   | class    |
| MyApp::Model::MyAppDB::Book                                     | class    |
| MyApp::Model::MyAppDB::BookAuthor                               | class    |
| MyApp::View::TT                                                 | instance |
'-----------------------------------------------------------------+----------'
[debug] Loaded Private actions:
.----------------------+--------------------------------------+--------------.
| Private              | Class                                | Method       |
+----------------------+--------------------------------------+--------------+
| /default             | MyApp::Controller::Root              | default      |
| /end                 | MyApp::Controller::Root              | end          |
| /books/index         | MyApp::Controller::Books             | index        |
| /books/list          | MyApp::Controller::Books             | list         |
'----------------------+--------------------------------------+--------------'
[debug] Loaded Path actions:
.-------------------------------------+--------------------------------------.
| Path                                | Private                              |
+-------------------------------------+--------------------------------------+
| /books/list                         | /books/list                          |
'-------------------------------------+--------------------------------------'
[info] MyApp powered by Catalyst 5.7002
You can connect to your server at http://localhost:3000

Some things you should note in the output above:

  • Catalyst::Model::DBIC::Schema took our MyAppDB::Book and made it MyApp::Model::MyAppDB::Book (and similar actions were performed on MyAppDB::Author and MyAppDB::BookAuthor).
  • The “list” action in our Books controller showed up with a path of /books/list.

Point your browser to http://localhost:3000 and you should still get the Catalyst welcome page.

Next, to view the book list, change the URL in your browser to http://localhost:3000/books/list. You should get a list of the five books loaded by the myapp01.sql script above, with TTSite providing the formatting for the very simple output we generated in our template. The count and space-separated list of author last names appear on the end of each row.

Also notice in the output of the script/myapp_server.pl that DBIC used the following SQL to retrieve the data:

SELECT me.id, me.title, me.rating FROM books me

Along with a list of the following commands to retrieve the authors for each book (the lines have been “word wrapped” here to improve legibility):

SELECT author.id, author.first_name, author.last_name
FROM book_authors me
JOIN authors author ON ( author.id = me.author_id )
WHERE ( me.book_id = ? ): `1'

You should see 5 such lines of debug output as DBIC fetches the author information for each book.

USING THE DEFAULT TEMPLATE NAME

By default, Catalyst::View::TT will look for a template that uses the same name as your controller action, allowing you to save the step of manually specifying the template name in each action. For example, this would allow us to remove the $c->stash->{template} = ‘books/list.tt2′; line of our list action in the Books controller. Open lib/MyApp/Controller/Books.pm in your editor and comment out this line to match the following (only the $c->stash->{template} line has changed):

=head2 list
Fetch all book objects and pass to books/list.tt2 in stash to be displayed
=cut
sub list : Local {
# Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
# 'Context' that's used to 'glue together' the various components
# that make up the application
my ($self, $c) = @_;
# Retrieve all of the book records as book model objects and store in the
# stash where they can be accessed by the TT template
$c->stash->{books} = [$c->model('MyAppDB::Book')->all];
# Set the TT template to use.  You will almost always want to do this
# in your action methods (actions methods respond to user input in
# your controllers).
#$c->stash->{template} = 'books/list.tt2';
}

Catalyst::View::TT defaults to looking for a template with no extension. In our case, we need to override this to look for an extension of .tt2. Open lib/MyApp/View/TT.pm and add the TEMPLATE_EXTENSION definition as follows:

__PACKAGE__->config({
CATALYST_VAR => 'Catalyst',
INCLUDE_PATH => [
MyApp->path_to( 'root', 'src' ),
MyApp->path_to( 'root', 'lib' )
],
PRE_PROCESS  => 'config/main',
WRAPPER      => 'site/wrapper',
ERROR        => 'error.tt2',
TIMER        => 0,
TEMPLATE_EXTENSION => '.tt2',
});

You should now be able to restart the development server as per the previous section and access the http://localhost:3000/books/list as before.

NOTE: Please note that if you use the default template technique, you will not be able to use either the $c->forward or the $c->detach mechanisms (these are discussed in Part 2 and Part 8 of the Tutorial).

RETURN TO A MANUALLY-SPECIFIED TEMPLATE

In order to be able to use $c->forward and $c->detach later in the tutorial, you should remove the comment from the statement in sub list:

$c->stash->{template} = 'books/list.tt2';

Then delete the TEMPLATE_EXTENSION line in lib/MyApp/View/TT.pm.

You should then be able to restart the development server and access http://localhost:3000/books/list in the same manner as with earlier sections.

AUTHOR

著者

Kennedy Clark, hkclark [a] gmail.com

Kennedy Clark, hkclark [a] gmail.com

Please report any errors, issues or suggestions to the author. The most recent version of the Catalyst Tutorial can be found at http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/.

Please report any errors, issues or suggestions to the author. The most recent version of the Catalyst Tutorial can be found at http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/.

Copyright 2006, Kennedy Clark, under Creative Commons License (http://creativecommons.org/licenses/by-nc-sa/2.5/).

Copyright 2006, Kennedy Clark, under Creative Commons License (http://creativecommons.org/licenses/by-nc-sa/2.5/).

Primary/Primary 構成の DRBD デバイス上に構築した Cluster Filesystem 上に構築した Xen 準仮想化仮想マシン上の Filesystem Benchmark

以下の環境で iozone による Benchmark を実施してみました。

  • /dev/sdb1 上に作成した Ext3 Filesystem
  • /dev/drbd0 上に作成した Ext3 Filesystem
  • /dev/drbd0 上に作成した OCFS2 Filesystem
  • /dev/drbd0 上に作成した GFS Filesystem
  • /dev/sdb1 上に作成した Ext3 Filesystem 上に作成したファイルを Disk Image として構築した Xen 準仮想化仮想マシン上に作成した Ext3 Filesystem
  • /dev/drbd0 上に作成した Ext3 Filesystem 上に作成したファイルを Disk Image として構築した Xen 準仮想化仮想マシン上に作成した Ext3 Filesystem
  • /dev/drbd0 上に作成した OCFS2 Filesystem 上に作成したファイルを Disk Image として構築した Xen 準仮想化仮想マシン上に作成した Ext3 Filesystem
  • /dev/drbd0 上に作成した GFS Filesystem 上に作成したファイルを Disk Image として構築した Xen 準仮想化仮想マシン上に作成した Ext3 Filesystem

Benchmark 実行環境は以下の通り。

CPU Intel(R) Pentium(R) D CPU 3.00GHz
メモリ 2GB(ただし Dom0 に 512MB のみ割り当て)
ディスク FUJITSU MAX3073RC(容量:73.5GB/回転数:15000rpm/SAS 3Gbps)
NIC Broadcom NetXtreme BCM5721 Gigabit Ethernet PCI Express

DRBD でミラー先として用いた環境は以下の通り。

CPU Intel(R) Celeron(R) CPU 3.06GHz
メモリ 1GB(ただし Dom0 に 512MB のみ割り当て)
ディスク FUJITSU MAX3073RC(容量:73.5GB/回転数:15000rpm/SAS 3Gbps)
NIC Broadcom NetXtreme BCM5721 Gigabit Ethernet PCI Express

結果は以下の通り。念のため 3 回実行した平均値を求めています。

書き込み系の処理ではなぜか OCFS2/GFS の方がローカルディスクの Ext3 よりもスループットが高いことになってしまいました。なんでこんな結果になるのか理解できません。ひょっとしてライトバックでもしている?

あと Xen 上の Filesystem が全然遅くなっていない。本当か?

Xen の仮想マシン上はもっと性能が悪いのかと思っていたけど実際にはなかなかよさげです。

Catalyst::Manual::Tutorial::Intro - Catalyst Tutorial - Part 1: Introduction [対訳]

Catalyst::Manual::Tutorial::Intro – Catalyst Tutorial – Part 1: Introduction の対訳。2008/01/18 時点での最新版 Catalyst-Manual-5.701003.tar.gz を元にしています。

誤訳がありましたらコメントにてご指摘ください。

NAME

名前

Catalyst::Manual::Tutorial::Intro – Catalyst Tutorial – Part 1: Introduction

Catalyst::Manual::Tutorial::Intro – Catalyst チュートリアル – 第一部: 導入

OVERVIEW

概要

This is Part 1 of 9 of the Catalyst Tutorial.

9 つある Catalyst チュートリアルのうちの 1 つめです。

Tutorial Overview

チュートリアルの概要

  1. Introduction
    導入
  2. Catalyst Basics
    Catalyst の基礎
  3. Basic CRUD
    基礎的な CRUD
  4. Authentication
    認証
  5. Authorization
    承認
  6. Debugging
    デバッグ
  7. Testing
    テスト
  8. Advanced CRUD
    高度な CRUD
  9. Appendices
    補遺
DESCRIPTION

説明

This tutorial provides a multipart introduction to the Catalyst web framework. It seeks to provide a rapid overview of many of its most commonly used features. The focus is on the real-world best practices required in the construction of nearly all Catalyst applications.

このチュートリアルは Catalyst web フレームワークへの複合的な導入を提供します。最もよく利用されるたくさんの機能の概要を素早く提供しようと努めます。ほぼすべての Catalyst アプリケーションの構築で必要とされる実用的な良い慣例に焦点を合わせます。

Although the primary target of the tutorial is users new to the Catalyst framework, experienced users may wish to review specific sections (for example, how to use DBIC for their model classes or how to add authentication and authorization to an existing application).

このチュートリアルの第一ターゲットは Catalyst フレームワークを初めて使うユーザですが、経験者もいくつかのセクションを再考したいと考えるかもしれません(たとえば、自分のモデルクラスで DBIC を使う方法だとか、すでに存在するアプリケーションに認証と承認を加える方法など)。

You can obtain the code for all the tutorial examples from the catalyst subversion repository by issuing the command:

以下のコマンドを実行することでこのチュートリアルの例すべてのコードを Catalyst の Subversion リポジトリから取得することができます:

svn co http://dev.catalyst.perl.org/repos/Catalyst/tags/examples/Tutorial/MyApp/5.7/ CatalystTutorial

This will download the current code for each tutorial chapter in the CatalystTutorial directory. Each example application directory has the same name as the tutorial chapter.

このコマンドを実行すると CatalystTutorial というディレクトリに各チュートリアルの章ごとの最新のコードがダウンロードされます。それぞれのサンプルアプリケーションディレクトリはチュートリアルの章と同じ名前になっています。

These reference implementations are provided so that when you follow the tutorial, you can use the code from the subversion repository to ensure that your system is set up correctly, and that you have not inadvertently made any typographic errors, or accidentally skipped part of the tutorial.

これらの参照実装はチュートリアルを追いかけていく為に提供されているので、 Subversion リポジトリから得たコードによりあなたのシステムが正しくセットアップされているかを確認でますし、うっかり文字の打ち間違いによるエラーを起こすことも、チュートリアルを一部読み飛ばしてしまうというアクシデントも起こりません。

Additionally, if you’re reading this manual online, you can download the example program and all the necessary dependencies to your local machine by installing the Task::Catalyst::Tutorial distribution from CPAN:

加えて、もしこのマニュアルをオンラインで読んでいるのであれば、 Task::Catalyst::Tutorial ディストリビューションを CPAN からインストールすることでサンプルプログラムとあなたのローカルマシンで必要となるすべての依存するものをダウンロードすることができます:

cpan Task::Catalyst::Tutorial

This will also test to make sure the dependencies are working. If you have trouble installing these, please ask for help on the #catalyst IRC channel, or the Catalyst mailing list.

このコマンドでは依存するものがちゃんと動いているかも確認してくれます。もしこれらのインストールで問題があったなら、 IRC の #catalyst チャネルか Catalyst メーリングリストに助けを求めてください。

Subjects covered include:

ここでふれる話題は以下の通りです:

  • A simple application that lists and adds books.

    本を表示したり加えたりする単純なアプリケーション。

  • The use of DBIx::Class (DBIC) for the model.

    モデルのためにDBIx::Class(DBIC) を使う。

  • How to write CRUD (Create, Read, Update, and Delete) operations in Catalyst.

    Catalyst で CRUD(Create, Read, Update,と Delete) を書くための方法。

  • Authentication (“auth”).

    認証(“auth”)。

  • Role-based authorization (“authz”).

    ロールによる承認(“authz”)。

  • Attempts to provide an example showing current (5.7XXX) Catalyst practices. For example, the use of Catalyst::Action::RenderView, DBIC, Catalyst::Plugin::ConfigLoader with myapp.yml, the use of lib/MyApp/Controller/Root.pm vs. lib/MyApp.pm, etc.

    Catalyst の最新(5.7XXX) の機能を見せるためのサンプルを提供することを試みる。例えば、 Catalyst::Action::RenderView の使い方、 DBIC、 Catalyst::Plugin::ConfigLoader と myapp.yml、 lib/MyApp/Controller/Root.pm 対 lib/MyApp.pm の使い方、など。

  • The use of Template Toolkit (TT) and the Catalyst::Helper::View::TTSite view helper.

    Template Toolkit(TT) と Catalyst::Helper::View::TTSite ビューヘルパーの使い方。

  • Useful techniques for troubleshooting and debugging Catalyst applications.

    Catalyst アプリケーションでのトラブルシューティングとデバッグに役立つテクニック。

  • The use of SQLite as a database (with code also provided for MySQL and PostgreSQL).

    SQLite をデータベースとして使う方法(MySQL と PostgreSQL も同じように提供)。

  • The use of HTML::Widget for automated form processing and validation.

    自動 FORM 処理と値検査のための HTML::Widget の使い方。

This tutorial makes the learning process its main priority. For example, the level of comments in the code found here would likely be considered excessive in a “normal project”. Because of their contextual value, this tutorial will generally favor inline comments over a separate discussion in the text. It also deliberately tries to demonstrate multiple approaches to various features (in general, you should try to be as consistent as possible with your own production code).

このチュートリアルでは学ぶプロセスを確立することを第一優先としています。例えば、コードの中には “普通のプロジェクト” からみたら過度なレベルのコメントが見られます。文脈上の価値のために、このチュートリアルでは一般にテキストで議論を分断するよりもインラインコメントの方を好むからです。またさまざまな機能に対して意図的に複数のアプローチのしかたを試みることもあります(一般には、あなたのプロジェクトのコードではできるだけ一貫性をもたせるようにすべきです)。

Furthermore, this tutorial tries to minimize the number of controllers, models, TT templates, and database tables. Although this does result in things being a bit contrived at times, the concepts should be applicable to more complex environments. More complete and complicated example applications can be found in the examples area of the Catalyst Subversion repository at http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/.

さらに、このチュートリアルではコントローラ、モデル、 TT テンプレート、そしてデータベースを最小限とするよう努めています。より複雑な環境へ適用できるようにというコンセプトによる意図的な結果です。より完全で複雑なサンプルアプリケーションは http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/ にある Catalyst Subversion リポジトリの examples エリアにあります。

Note: There are a variety of other introductory materials available through the Catalyst web site and at http://dev.catalyst.perl.org/wiki/UserIntroductions and http://dev.catalyst.perl.org/.

ノート: ほかにもさまざまな紹介的なものが Catalyst の Web サイトと http://dev.catalyst.perl.org/wiki/UserIntroductions と http://dev.catalyst.perl.org/ を通じて手に入れることができます。

VERSIONS AND CONVENTIONS USED IN THIS TUTORIAL

このチュートリアルで用いられるバージョンと慣例

This tutorial was built using the following resources. Please note that you may need to make adjustments for different environments and versions:

このチュートリアルは以下のリソースを用いて構築されています。違う環境やバージョンではどこか調整しなければならなくなるかもしれないことに注意してください:

  • OS = CentOS 4 Linux (RHEL 4)

    OS = CentOS 4 Linux (RHEL 4)

  • Catalyst v5.7

    Catalyst v5.7

  • Catalyst::Devel v1.02

    Catalyst::Devel v1.02

  • DBIx::Class v0.06003

    DBIx::Class v0.06003

  • Catalyst Plugins – The plugins used in this tutorial all have sufficiently stable APIs that you shouldn’t need to worry about versions. However, there could be cases where the tutorial is affected by what version of plugins you use. This tutorial has been tested against the following set of plugins:

    Catalyst プラグイン – このチュートリアルで用いるプラグインはすべて十分に安定している API なのでバージョンに関する心配は必要ありません。しかしながら、あなたが使っているプラグインのバージョンの影響を受けるケースもあるかもしれません。このチュートリアルは以下のプラグインでテストしています。

    • Catalyst::Plugin::Authentication — 0.09

      Catalyst::Plugin::Authentication — 0.09

    • Catalyst::Plugin::Authentication::Store::DBIC — 0.07

      Catalyst::Plugin::Authentication::Store::DBIC — 0.07

    • Catalyst::Plugin::Authorization::ACL — 0.08

      Catalyst::Plugin::Authorization::ACL — 0.08

    • Catalyst::Plugin::Authorization::Roles — 0.04

      Catalyst::Plugin::Authorization::Roles — 0.04

    • Catalyst::Plugin::ConfigLoader — 0.13

      Catalyst::Plugin::ConfigLoader — 0.13

    • Catalyst::Plugin::HTML::Widget — 1.1

      Catalyst::Plugin::HTML::Widget — 1.1

    • Catalyst::Plugin::Session — 0.12

      Catalyst::Plugin::Session — 0.12

    • Catalyst::Plugin::Session::State::Cookie — 0.05

      Catalyst::Plugin::Session::State::Cookie — 0.05

    • Catalyst::Plugin::Session::Store::FastMmap — 0.02

      Catalyst::Plugin::Session::Store::FastMmap — 0.02

    • Catalyst::Plugin::StackTrace — 0.06

      Catalyst::Plugin::StackTrace — 0.06

    • Catalyst::Plugin::Static::Simple — 0.14

      Catalyst::Plugin::Static::Simple — 0.14

  • Since the web browser is being used on the same box where Perl and the Catalyst development server is running, the URL of http://localhost:3000 will be used (the Catalyst development server defaults to port 3000). If you are running Perl on a different box than where your web browser is located (or using a different port number via the -p port_number option to the development server), then you will need to update the URL you use accordingly.

    Perl と Catalyst 開発サーバが動作するのと同じマシンで Web ブラウザを利用するのであれば、 http://localhost:3000 という URL を使います(Catalyst 開発サーバのデフォルトのポートは 3000 です)。もし Web ブラウザを実行しているのと異なるマシンで Perl を実行しているのであれば(もしくは開発サーバで -p port_number オプションにより異なるポート番号を用いているのであれば)、それに応じて URL をアップデートする必要があります。

  • Depending on the web browser you are using, you might need to hit Shift+Reload to pull a fresh page when testing your application at various points. Also, the -k keepalive option to the development server can be necessary with some browsers (especially Internet Explorer).

    使っている Web ブラウザによっては、いくつかの点であなたのアプリケーションをテストする際に最新ページを引っ張ってくるためには Shift+Reload を押す必要があるかもしれません。また、いくつかのブラウザ(特に Internet Explorer)では開発サーバで -k keepalive オプションが必要となるかもしれません。

CATALYST INSTALLATION

Catalyst のインストール

Unfortunately, one of the most daunting tasks faced by newcomers to Catalyst is getting it installed. Although a compelling strength of Catalyst is that it can easily make use of many of the modules in the vast repository that is CPAN, this can result in initial installations that are both time consuming and frustrating. However, there are a growing number of methods that can dramatically ease this undertaking. Of these, the following are likely to be applicable to the largest number of potential new users:

不幸にも、 Catalyst 初心者がもっともよく直面するやる気をなくしてしまう作業の一つがそのインストールです。Although a compelling strength of Catalyst is that it can easily make use of many of the modules in the vast repository that is CPAN, this can result in initial installations that are both time consuming and frustrating. しかしながら、これらを劇的に簡単にしてくれる方法がたくさん存在しています。もちろん、これらの方法は多くの潜在的な新規利用者にも適用できます。

  • Matt Trout’s cat-install – Available at http://www.shadowcatsystems.co.uk/static/cat-install, cat-install can be a quick and painless way to get Catalyst up and running. Just download the script from the link above and type perl cat-install.

    Matt Trout の cat-install – http://www.shadowcatsystems.co.uk/static/cat-install から入手できる cat-install は Catalyst の入手と実行を素早く苦痛なしに実現する方法です。ただスクリプトを上記リンクからダウンロードし perl cat-install を打ち込むだけでけです。

  • Chris Laco’s CatInABox – Download the tarball from http://handelframework.com/downloads/CatInABox.tar.gz and unpack it on your machine. Depending on your OS platform, either run start.bat or start.sh.

    Chris Laco の CatInABox – http://handelframework.com/downloads/CatInABox.tar.gz から Tar アーカイブをダウンロードしあなたのマシンに解凍してください。あなたの OS プラットフォームに依存しますが、 start.bat か start.sh を実行します。

  • Pre-Built VMWare Images – Under the VMWare community program, work is ongoing to develop a number of VMWare images where an entire Catalyst development environment has already been installed, complete with database engines and a full complement of Catalyst plugins.

    Pre-Built VMWare Images – VMWare コミュニティプログラムの元、いくつかのデータベースエンジンとすべての Catalyst プラグインを含む Catalyst 開発環境があらかじめインストールされた VMWare イメージが継続して開発されています。

For additional information and recommendations on Catalyst installation, please refer to Catalyst::Manual::Installation.

Catalyst のインストールに関する追加の情報とおすすめは Catalyst::Manual::Installation を参照してください。

NOTE: Step-by-step instructions to replicate the environment on which this tutorial was developed can be found at Catalyst::Manual::Installation::CentOS4. Using these instructions, you should be able to build a complete CentOS 4.X server with Catalyst and all the plugins required to run this tutorial.

ノート: このチュートリアルを開発した環境を複製するためのステップバイステップ手順は Catalyst::Manual::Installation::CentOS4 にあります。これらの手順を使えば、このチュートリアルを実行するために必要となる Catalyst とすべてのプラグインがそろった完全な CentOS 4.x サーバを構築することができます。

DATABASES

データベース

This tutorial will primarily focus on SQLite because of its simplicity of installation and use; however, modifications in the script required to support MySQL and PostgreSQL will be presented in Appendix 2.

このチュートリアルではインストールと利用が簡単な SQLite に焦点を当てます。が、 MySQL と PostgreSQL をサポートするために必要となるスクリプトの変更について補遺 2 で紹介します。

Note: One of the advantages of the MVC design patterns is that applications become much more database independent. As such, you will notice that only the .sql files used to initialize the database change between database systems: the Catalyst code generally remains the same.

ノート: MVC デザインパターンのひとつの利点はアプリケーションがデータベースに依存しなくなることです。そのため、 .sql ファイルはデータベース間をまたがるデータベース変更のときのみ用いられることに注意してください: Catalyst コードは同じままです。

WHERE TO GET WORKING CODE

動いているコードがある場所

Each part of the tutorial has complete code available in the main Catalyst Subversion repository (see the note at the beginning of each part for the appropriate svn command to use). Additionally, the final code is available as a ready-to-run tarball at http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/Final_Tarball/MyApp.tgz.

チュートリアルのそれぞれの部分はメインの Catalyst Subversion リポジトリ(実行すべき svn コマンドはそれぞれの部の冒頭にあるノートをみてください)から得られる完全なコードを持っています。加えて、実行可能な最終コードの Tar アーカイブが http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/Final_Tarball/MyApp.tgz にあります。

NOTE: You can run the test cases for the final code with the following commands:

ノート: 次のコマンドにより最終コードのテストケースを実行することができます:

wget http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/Final_Tarball/MyApp.tgz
tar zxvf MyApp.tgz
cd MyApp
CATALYST_DEBUG=0 prove --lib lib  t
AUTHOR

著者

Kennedy Clark, hkclark [a] gmail.com

Kennedy Clark, hkclark [a] gmail.com

Please report any errors, issues or suggestions to the author. The most recent version of the Catalyst Tutorial can be found at http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/.

Please report any errors, issues or suggestions to the author. The most recent version of the Catalyst Tutorial can be found at http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/.

Copyright 2006, Kennedy Clark, under Creative Commons License (http://creativecommons.org/licenses/by-nc-sa/2.5/).

Copyright 2006, Kennedy Clark, under Creative Commons License (http://creativecommons.org/licenses/by-nc-sa/2.5/).

Catalyst::Manual::Tutorial – Catalyst Tutorial: Overview [対訳]

Catalyst::Manual::Tutorial – Catalyst Tutorial: Overview の対訳。2008/01/18 時点での最新版 Catalyst-Manual-5.701003.tar.gz を元にしています。

このページは目次ばっかりでつまんないのでとりあえず後回しにします。

誤訳がありましたらコメントにてご指摘ください。

NAME

名前

Catalyst::Manual::Tutorial – Catalyst Tutorial: Overview

Catalyst::Manual::Tutorial – Catalyst チュートリアル: 概要

DESCRIPTION

説明

The Catalyst framework is a flexible and comprehensive environment for quickly building high-functionality web applications. This tutorial is designed to provide a rapid introduction to its basics and its most commonly used features while focusing on real-world best practices.

Catalyst フレームワークは、素早く高機能な Web アプリケーションを構築するための、柔軟で包括的な環境です。このチュートリアルは、実世界で用いられているよい慣例に焦点を当て、その基礎とよく共通して用いられる機能を足早に紹介するために作られています。

The tutorial is divided into the following sections:

このチュートリアルは以下のセクションに分かれています:

NOTE: CLICK THESE LINKS TO JUMP TO CHAPTERS (the index links above only navigate inside this page).

ノート: これらのリンクをクリックすることで対応する各章へ移動することができます(以下のインデックスリンクはこのページ内でのナビゲートしかしてくれません)。

A tarball of the final application is available at http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/Final_Tarball/MyApp.tgz.

最終的なアプリケーションを tar で固めたものが http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/Final_Tarball/MyApp.tgz にあります。

Detailed Table of Contents

詳しい目次

Part 1: Introduction

第一部: 導入
  • VERSIONS AND CONVENTIONS USED IN THIS TUTORIAL

    このチュートリアルで用いられるバージョンと慣例
  • CATALYST INSTALLATION

    Catalyst のインストール
  • DATABASES

    データベース
  • WHERE TO GET WORKING CODE

    動いているコードがある場所
Part 2: Catalyst Basics

第二部: Catalyst の基礎
  • CREATE A CATALYST PROJECT

    Catalyst プロジェクトを作る
  • CREATE A SQLITE DATABASE

    SQLite データベースを作る
  • EDIT THE LIST OF CATALYST PLUGINS

    Catalyst プラグインのリストを編集する
  • DATABASE ACCESS WITH DBIx::Class

    DBIx::Class をつかってデータベースへアクセスする

    • Create a DBIC Schema File

      DBIC スキーマファイルの作成
    • Create the DBIC “Result Source” Files

      DBIC “Result Source” ファイルの作成
    • Use Catalyst::Model::DBIC::Schema to Load the Model Class

      Catalyst::Model::DBIC::Schema を使ってモデルクラスの読み込み
  • CREATE A CATALYST CONTROLLER

    Catalyst コントローラを作る
  • CATALYST VIEWS

    Catalyst ビュー

    • Create a Catalyst View Using TTSite

      TTSite を利用した Catalyst ビューの作成
    • Using RenderView for the Default View

      RenderView を利用したデフォルトビュー
    • Globally Customize Every View

      すべてのビューへの大域的なカスタマイズ
    • Create a TT Template Page

      TT テンプレートページの作成
  • RUN THE APPLICATION

    アプリケーションを実行する
  • USING THE DEFAULT TEMPLATE NAME

    デフォルトのテンプレート名を使う
Part 3: Basic CRUD

第三部: CRUD の基礎
  • FORMLESS SUBMISSION

    FORM を用いない SUBMIT 処理

    • Include a Create Action in the Books Controller

      Book コントローラへクリエイトアクションを組み込む
    • Include a Template for the url_create Action:

      url_create アクションへテンプレートを組み込む
    • Try the url_create Feature

      url_create 機能を試す
  • MANUALLY BUILDING A CREATE FORM

    手動でクリエイトフォームを構築する

    • Add a Method to Display the Form

      フォームを表示するメソッドを追加する
    • Add a Template for the Form

      フォームにテンプレートを追加する
    • Add Method to Process Form Values and Update Database

      フォーム変数を処理するメソッドとデータベースを更新するメソッドを追加する
    • Test Out the Form

      フォームをテストする
  • A SIMPLE DELETE FEATURE

    単純な削除機能

    • Include a Delete Link in the List

      リストにリンクを削除を組み込む
    • Add a Delete Action to the Controller

      コントローラに削除アクションを加える
    • Try the Delete Feature

      削除機能を試す
Part 4: Authentication

第四部: 認証
  • BASIC AUTHENTICATION

    基本認証

    • Add Users and Roles to the Database

      データベースへユーザとロールを追加する
    • Add User and Role Information to DBIC Schema

      ユーザとロールの情報を DBIC スキーマへ追加する
    • Create New “Result Source Objects”

      新しい “Result Source Objects” を作成する
    • Sanity-Check Reload of Development Server

    • Include Authentication and Session Plugins

    • Configure Authentication

    • Add Login and Logout Controllers

    • Add a Login Form TT Template Page

    • Add Valid User Check

    • Displaying Content Only to Authenticated Users

    • Try Out Authentication

  • USING PASSWORD HASHES

    • Get a SHA-1 Hash for the Password

    • Switch to SHA-1 Password Hashes in the Database

    • Enable SHA-1 Hash Passwords in Catalyst::Plugin::Authentication::Store::DBIC

    • Try Out the Hashed Passwords

Part 5: Authorization

第五部: 承認
  • BASIC AUTHORIZATION

    • Update Plugins to Include Support for Authorization

    • Add Config Information for Authorization

    • Add Role-Specific Logic to the “Book List” Template

    • Limit Books::add to admin Users

    • Try Out Authentication And Authorization

  • ENABLE ACL-BASED AUTHORIZATION

    • Add the Catalyst::Plugin::Authorization::ACL Plugin

    • Add ACL Rules to the Application Class

    • Add a Method to Handle Access Violations

Part 6: Debugging

第六部: デバッグ
  • LOG STATEMENTS

  • RUNNING CATALYST UNDER THE PERL DEBUGGER

  • DEBUGGING MODULES FROM CPAN

Part 7: Testing

第七部: テスト
  • RUNNING THE “CANNED” CATALYST TESTS

  • RUNNING A SINGLE TEST

  • ADDING YOUR OWN TEST SCRIPT

  • SUPPORTING BOTH PRODUCTION AND TEST DATABASES

Part 8: Advanced CRUD

第八部: 高度な CRUD
  • HTML::WIDGET FORM CREATION

    • Add the HTML::Widget Plugin

    • Add a Form Creation Helper Method

    • Add Actions to Display and Save the Form

    • Update the CSS

    • Create a Template Page To Display The Form

    • Add Links for Create and Update via HTML::Widget

    • Test The <HTML::Widget> Create Form

  • HTML::WIDGET VALIDATION AND FILTERING

    • Add Constraints and Filters to the Widget Creation Method

    • Rebuild the Form Submission Method to Include Validation

    • Try Out the Form

  • Enable DBIx::Class::HTMLWidget Support

    • Add DBIx::Class::HTMLWidget to DBIC Model

    • Use populate_from_widget in hw_create_do

Part 9: Appendices

第九部: 補遺
  • APPENDIX 1: CUT AND PASTE FOR POD-BASED EXAMPLES

    • “Un-indenting” with Vi/Vim

    • “Un-indenting” with Emacs

  • APPENDIX 2: USING MYSQL AND POSTGRESQL

    • MySQL

    • PostgreSQL

  • APPENDIX 3: IMPROVED HASHING SCRIPT

THANKS

謝辞













AUTHOR

著者

Kennedy Clark, hkclark [a] gmail.com

Kennedy Clark, hkclark [a] gmail.com

Please report any errors, issues or suggestions to the author. The most recent version of the Catalyst Tutorial can be found at http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/.

Please report any errors, issues or suggestions to the author. The most recent version of the Catalyst Tutorial can be found at http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/.

Copyright 2006, Kennedy Clark, under Creative Commons License (http://creativecommons.org/licenses/by-nc-sa/2.5/).

Copyright 2006, Kennedy Clark, under Creative Commons License (http://creativecommons.org/licenses/by-nc-sa/2.5/).

プログラミング言語 Erlang 入門

かなり久々の更新。

最近何かと話題のプログラミング言語 Erlang の入門書がようやく日本語で読めるように。ということでさっそく読んでみました。

Erlang はスウェーデンの通信機器メーカー、エリクソン社が開発した関数型言語です。他の関数型言語にはない大きな特徴として並行処理と分散処理のサポートが上げられます。 Erlang 自体は結構枯れた言語ということですが、この並行処理と分散処理のサポートのおかげで、最近は(ごく一部で?)注目を集めているようです。

なぜ並行処理と分散処理がサポートされていることで注目を集めているのか?という疑問に答えるためには、最近になって CPU 開発の方向性が変わってきていることに触れる必要があります。

CPU の性能の指標として一番わかりやすいものに“クロックスピード”があります。CPU は、クロックと呼ばれる定期的に発生する時間刻みにしたがいながら命令を実行していきます。一秒間あたりにクロックを何回発生させるかがクロックスピードです。当然、クロックスピードを早くすればその分一秒間あたりに実行できる命令数は多くなるので CPU の性能が上がることになります。つい最近まではこの方法で CPU は性能を向上させてきました。

もちろん、いまでもクロックスピードを上げることで性能を向上させよう(させたい?)という基本的な動きに変わりはないのですが、ここにきて様々な技術的制約によりクロックスピードを上げにくいような状況になってしまっているのです。そこで最近の Intel や AMD は、クロックスピードを上げるよりもコア数を増やし並行処理で CPU の性能を強化しようという方針にシフトしているわけです。

ところが、たとえば CPU の数を二倍にしたからといって性能も単純に二倍になるかというとそうはいかないわけです。OS や実行するプログラム側で同時に複数の CPU を利用するような工夫がされていなければせっかく二つある CPU も片方しか利用されません。しかしプログラム側でマルチコアを有効活用できるような工夫をするのは結構面倒で…

ということで、並行処理と分散処理を言語の特徴として謳う Erlang ってどうなんだろう、と、実は結構まえから気になっていたのです。

そして… ちょっと魔法のようなモノを期待しちゃってたかもしれません…

読んでみての率直な感想を言うと、“やっぱりお手軽に並行実行可能なプログラムを書くことはできないんだな”と、すこしがっかりしてしまいました。“逐次実行っぽくない”、“状態を持たない”といった聞きかじりの知識による偏見たっぷりの関数型言語への無理解も手伝い、プログラマがまったく意識しなくても並行処理してくれるような凄いモノを想像しちゃっていたので…

並行処理について触れるのは一番最後の章で、フィボナッチ級数を求める関数を並行実行させているんですけど、なんか pthread で実装させるのとたいして変わんないんじゃない?ってくらい並行処理を意識しなきゃならない実装になっているような気がしました。メモリを共有しない(できない?)ことで同期処理について意識する必要がなくなるという特徴についてもうすこし説明が欲しいように感じましたが、それは普通の thread プログラミングの知識を前提しなければ難しいのかもしれません。

ただ Erlang という言語を学ぶ本としては割とよくできているように思います。例文もしっかりしていて、はじめて関数型言語に触れるというひとでも読みやすいんじゃないでしょうか。ただ関数型言語の勉強がしたい、というのであれば、個人的には“ふつうのHaskellプログラミング ふつうのプログラマのための関数型言語入門”の方が極端でおすすめですが…

はたしてプログラマがなにも意識せずともマルチコアの恩恵をうけるプログラムが書けるようになる時代は来るのでしょうか。

以下は参考です。

めがね

最近たそがれてないなぁ。
もしハマダが実在するなら、僕は絶対行くね。
才能ある自信あるし。
そこにいる才能。

ていうか市川実日子の存在感が絶妙すぎる。
劇中何度か出てくる「死にたい。」と吐く場面が特に素晴らしい。
このこやばいかも。

こういう日本映画、僕は大好きです。
ていうか「こういうの意味わかんない」とかいうひととはうまくやっていける気がしない。
それくらい。

DRBD & Heartbeat – takeover/failback verification

DRBD 上の ext3 filesystem を Heartbeat 配下に設定し、 Primary を落としたときと、落としてからあげたときの syslog。

何が起きているのかさっぱりですが、時間を作って追っかけたいと思います。

とりあえず、 Primary で mount されてた /var/lib/mysql という directory は、 Primary の shutdown 後、ちゃんと Secondary で mount されました。そして落とした Primary の復旧後、ちゃんと Secondary から Primary に戻りました。

以下の document が参考になるかも。

以下は設定。

FILE: /etc/drbd.conf
--
resource r0 {
protocol C;
incon-degr-cmd "echo '!DRBD! pri on incon-degr' | wall ; sleep 60 ; halt -f";
startup {
degr-wfc-timeout 120;
}
disk {
on-io-error   detach;
}
net {
}
syncer {
rate 10M;
group 1;
al-extents 257;
}
on debiancluster1 {
device     /dev/drbd0;
disk       /dev/sdb1;
address    192.168.2.16:7788;
meta-disk  internal;
}
on debiancluster2 {
device    /dev/drbd0;
disk      /dev/sdb1;
address   192.168.2.17:7788;
meta-disk internal;
}
}
FILE: /etc/ha.d/ha.cf
--
logfacility     local0
ucast eth1 192.168.2.17
#ucast eth1 192.168.2.16
auto_failback on
node debiancluster1
node debiancluster2
FILE: /etc/ha.d/haresources
--
debiancluster1 drbddisk::r0 Filesystem::/dev/drbd0::/var/lib/mysql::ext3

以下は Primary 側を強制 shutdown させたときの Secondary 側の syslog。

Sep 13 00:08:38 debiancluster2 kernel: drbd0: PingAck did not arrive in time.
Sep 13 00:08:38 debiancluster2 kernel: drbd0: drbd0_asender [6652]: cstate Connected --> NetworkFailure
Sep 13 00:08:38 debiancluster2 kernel: drbd0: asender terminated
Sep 13 00:08:38 debiancluster2 kernel: drbd0: drbd0_receiver [3462]: cstate NetworkFailure --> BrokenPipe
Sep 13 00:08:38 debiancluster2 kernel: drbd0: short read expecting header on sock: r=-512
Sep 13 00:08:38 debiancluster2 kernel: drbd0: worker terminated
Sep 13 00:08:38 debiancluster2 kernel: drbd0: drbd0_receiver [3462]: cstate BrokenPipe --> Unconnected
Sep 13 00:08:38 debiancluster2 kernel: drbd0: Connection lost.
Sep 13 00:08:38 debiancluster2 kernel: drbd0: drbd0_receiver [3462]: cstate Unconnected --> WFConnection
Sep 13 00:08:56 debiancluster2 heartbeat: [6088]: WARN: node debiancluster1: is dead
Sep 13 00:08:56 debiancluster2 heartbeat: [6088]: WARN: No STONITH device configured.
Sep 13 00:08:56 debiancluster2 heartbeat: [6088]: WARN: Shared disks are not protected.
Sep 13 00:08:56 debiancluster2 heartbeat: [6088]: info: Resources being acquired from debiancluster1.
Sep 13 00:08:56 debiancluster2 heartbeat: [6088]: info: Link debiancluster1:eth1 dead.
Sep 13 00:08:56 debiancluster2 heartbeat: [6925]: debug: notify_world: setting SIGCHLD Handler to SIG_DFL
Sep 13 00:08:56 debiancluster2 harc[6925]: info: Running /etc/ha.d/rc.d/status status
Sep 13 00:08:56 debiancluster2 heartbeat: [6926]: info: No local resources [/usr/lib/heartbeat/ResourceManager listkeys debiancluster2] to acquire.
Sep 13 00:08:56 debiancluster2 heartbeat: [6088]: debug: StartNextRemoteRscReq(): child count 1
Sep 13 00:08:56 debiancluster2 mach_down[6945]: info: Taking over resource group drbddisk::r0
Sep 13 00:08:57 debiancluster2 ResourceManager[6965]: info: Acquiring resource group: debiancluster1 drbddisk::r0 Filesystem::/dev/drbd0::/var/lib/mysql::ext3
Sep 13 00:08:57 debiancluster2 ResourceManager[6965]: info: Running /etc/ha.d/resource.d/drbddisk r0 start
Sep 13 00:08:57 debiancluster2 ResourceManager[6965]: debug: Starting /etc/ha.d/resource.d/drbddisk r0 start
Sep 13 00:08:57 debiancluster2 kernel: drbd0: Secondary/Unknown --> Primary/Unknown
Sep 13 00:08:57 debiancluster2 ResourceManager[6965]: debug: /etc/ha.d/resource.d/drbddisk r0 start done. RC=0
Sep 13 00:08:57 debiancluster2 Filesystem[7101]: INFO: Running status for /dev/drbd0 on /var/lib/mysql
Sep 13 00:08:57 debiancluster2 Filesystem[7101]: INFO: /var/lib/mysql is unmounted (stopped)
Sep 13 00:08:57 debiancluster2 Filesystem[7037]: INFO: Filesystem Resource is stopped
Sep 13 00:08:57 debiancluster2 ResourceManager[6965]: info: Running /etc/ha.d/resource.d/Filesystem /dev/drbd0 /var/lib/mysql ext3 start
Sep 13 00:08:57 debiancluster2 ResourceManager[6965]: debug: Starting /etc/ha.d/resource.d/Filesystem /dev/drbd0 /var/lib/mysql ext3 start
Sep 13 00:08:57 debiancluster2 Filesystem[7210]: INFO: Running start for /dev/drbd0 on /var/lib/mysql
Sep 13 00:08:57 debiancluster2 kernel: kjournald starting.  Commit interval 5 seconds
Sep 13 00:08:57 debiancluster2 kernel: EXT3 FS on drbd0, internal journal
Sep 13 00:08:57 debiancluster2 kernel: EXT3-fs: recovery complete.
Sep 13 00:08:57 debiancluster2 kernel: EXT3-fs: mounted filesystem with ordered data mode.
Sep 13 00:08:57 debiancluster2 Filesystem[7146]: INFO: Filesystem Success
Sep 13 00:08:58 debiancluster2 ResourceManager[6965]: debug: /etc/ha.d/resource.d/Filesystem /dev/drbd0 /var/lib/mysql ext3 start done. RC=0
Sep 13 00:08:58 debiancluster2 mach_down[6945]: info: /usr/lib/heartbeat/mach_down: nice_failback: foreign resources acquired
Sep 13 00:08:58 debiancluster2 mach_down[6945]: info: mach_down takeover complete for node debiancluster1.
Sep 13 00:08:58 debiancluster2 heartbeat: [6088]: info: mach_down takeover complete.

以下は強制 shutdown した Primary を再起動したときの Primary 側の syslog。

Sep 13 09:11:24 debiancluster1 kernel: drbd: initialised. Version: 0.7.21 (api:79/proto:74)
Sep 13 09:11:24 debiancluster1 kernel: drbd: SVN Revision: 2326 build by root@debiancluster1, 2007-09-13 07:55:36
Sep 13 09:11:24 debiancluster1 kernel: drbd: registered as block device major 147
Sep 13 09:11:24 debiancluster1 kernel: drbd0: resync bitmap: bits=5208430 words=81382
Sep 13 09:11:24 debiancluster1 kernel: drbd0: size = 19 GB (20833720 KB)
Sep 13 09:11:24 debiancluster1 kernel: drbd0: 0 KB marked out-of-sync by on disk bit-map.
Sep 13 09:11:24 debiancluster1 kernel: drbd0: Found 6 transactions (267 active extents) in activity log.
Sep 13 09:11:24 debiancluster1 kernel: drbd0: Marked additional 809 MB as out-of-sync based on AL.
Sep 13 09:11:24 debiancluster1 kernel: drbd0: drbdsetup [2198]: cstate Unconfigured --> StandAlone
Sep 13 09:11:25 debiancluster1 kernel: drbd0: drbdsetup [2211]: cstate StandAlone --> Unconnected
Sep 13 09:11:25 debiancluster1 kernel: drbd0: drbd0_receiver [2212]: cstate Unconnected --> WFConnection
Sep 13 09:11:25 debiancluster1 kernel: drbd0: drbd0_receiver [2212]: cstate WFConnection --> WFReportParams
Sep 13 09:11:25 debiancluster1 kernel: drbd0: Handshake successful: DRBD Network Protocol version 74
Sep 13 09:11:25 debiancluster1 kernel: drbd0: Connection established.
Sep 13 09:11:25 debiancluster1 kernel: drbd0: I am(S): 1:00000002:00000001:00000003:00000002:10
Sep 13 09:11:25 debiancluster1 kernel: drbd0: Peer(P): 1:00000002:00000001:00000003:00000003:10
Sep 13 09:11:25 debiancluster1 kernel: drbd0: drbd0_receiver [2212]: cstate WFReportParams --> WFBitMapT
Sep 13 09:11:25 debiancluster1 kernel: drbd0: Secondary/Unknown --> Secondary/Primary
Sep 13 09:11:25 debiancluster1 kernel: drbd0: drbd0_receiver [2212]: cstate WFBitMapT --> SyncTarget
Sep 13 09:11:25 debiancluster1 kernel: drbd0: Resync started as SyncTarget (need to sync 828856 KB [207214 bits set]).
Sep 13 09:11:30 debiancluster1 heartbeat: [2278]: WARN: Core dumps could be lost if multiple dumps occur
Sep 13 09:11:30 debiancluster1 heartbeat: [2278]: WARN: Consider setting /proc/sys/kernel/core_uses_pid (or equivalent) to 1 for maximum supportability
Sep 13 09:11:31 debiancluster1 heartbeat: [2278]: WARN: Logging daemon is disabled --enabling logging daemon is recommended
Sep 13 09:11:31 debiancluster1 heartbeat: [2278]: info: **************************
Sep 13 09:11:31 debiancluster1 heartbeat: [2278]: info: Configuration validated. Starting heartbeat 2.0.7
Sep 13 09:11:31 debiancluster1 heartbeat: [2279]: info: heartbeat: version 2.0.7
Sep 13 09:11:31 debiancluster1 heartbeat: [2279]: info: Heartbeat generation: 4
Sep 13 09:11:31 debiancluster1 heartbeat: [2279]: info: G_main_add_TriggerHandler: Added signal manual handler
Sep 13 09:11:31 debiancluster1 heartbeat: [2279]: info: G_main_add_TriggerHandler: Added signal manual handler
Sep 13 09:11:31 debiancluster1 heartbeat: [2279]: info: Removing /var/run/heartbeat/rsctmp failed, recreating.
Sep 13 09:11:31 debiancluster1 heartbeat: [2279]: info: glib: ucast: write socket priority set to IPTOS_LOWDELAY on eth1
Sep 13 09:11:31 debiancluster1 heartbeat: [2279]: info: glib: ucast: bound send socket to device: eth1
Sep 13 09:11:31 debiancluster1 heartbeat: [2279]: info: glib: ucast: bound receive socket to device: eth1
Sep 13 09:11:31 debiancluster1 heartbeat: [2279]: info: glib: ucast: started on port 694 interface eth1 to 192.168.2.17
Sep 13 09:11:31 debiancluster1 heartbeat: [2279]: info: G_main_add_SignalHandler: Added signal handler for signal 17
Sep 13 00:11:42 debiancluster1 heartbeat: [2279]: info: Local status now set to: 'up'
Sep 13 00:11:42 debiancluster1 heartbeat: [2279]: info: Link debiancluster2:eth1 up.
Sep 13 00:11:42 debiancluster1 heartbeat: [2279]: info: Status update for node debiancluster2: status active
Sep 13 00:11:42 debiancluster1 heartbeat: [2343]: debug: notify_world: setting SIGCHLD Handler to SIG_DFL
Sep 13 00:11:42 debiancluster1 harc[2343]: info: Running /etc/ha.d/rc.d/status status
Sep 13 00:11:43 debiancluster1 heartbeat: [2279]: info: Comm_now_up(): updating status to active
Sep 13 00:11:43 debiancluster1 heartbeat: [2279]: info: Local status now set to: 'active'
Sep 13 00:11:43 debiancluster1 heartbeat: [2279]: WARN: G_CH_dispatch_int: Dispatch function for read child took too long to execute: 480 ms (> 50 ms) (GSource: 0x5dfeb8)
Sep 13 00:11:43 debiancluster1 heartbeat: [2279]: info: remote resource transition completed.
Sep 13 00:11:43 debiancluster1 heartbeat: [2279]: info: remote resource transition completed.
Sep 13 00:11:43 debiancluster1 heartbeat: [2279]: info: Local Resource acquisition completed. (none)
Sep 13 00:11:44 debiancluster1 heartbeat: [2279]: info: debiancluster2 wants to go standby [foreign]
Sep 13 00:11:46 debiancluster1 kernel: drbd0: Secondary/Primary --> Secondary/Secondary
Sep 13 00:11:46 debiancluster1 heartbeat: [2279]: info: standby: acquire [foreign] resources from debiancluster2
Sep 13 00:11:46 debiancluster1 heartbeat: [2354]: info: acquire local HA resources (standby).
Sep 13 00:11:46 debiancluster1 ResourceManager[2364]: info: Acquiring resource group: debiancluster1 drbddisk::r0 Filesystem::/dev/drbd0::/var/lib/mysql::ext3
Sep 13 00:11:46 debiancluster1 ResourceManager[2364]: info: Running /etc/ha.d/resource.d/drbddisk r0 start
Sep 13 00:11:46 debiancluster1 ResourceManager[2364]: debug: Starting /etc/ha.d/resource.d/drbddisk r0 start
Sep 13 00:11:46 debiancluster1 kernel: drbd0: Secondary/Secondary --> Primary/Secondary
Sep 13 00:11:46 debiancluster1 ResourceManager[2364]: debug: /etc/ha.d/resource.d/drbddisk r0 start done. RC=0
Sep 13 00:11:47 debiancluster1 Filesystem[2500]: INFO: Running status for /dev/drbd0 on /var/lib/mysql
Sep 13 00:11:47 debiancluster1 Filesystem[2500]: INFO: /var/lib/mysql is unmounted (stopped)
Sep 13 00:11:47 debiancluster1 Filesystem[2436]: INFO: Filesystem Resource is stopped
Sep 13 00:11:47 debiancluster1 ResourceManager[2364]: info: Running /etc/ha.d/resource.d/Filesystem /dev/drbd0 /var/lib/mysql ext3 start
Sep 13 00:11:47 debiancluster1 ResourceManager[2364]: debug: Starting /etc/ha.d/resource.d/Filesystem /dev/drbd0 /var/lib/mysql ext3 start
Sep 13 00:11:47 debiancluster1 Filesystem[2609]: INFO: Running start for /dev/drbd0 on /var/lib/mysql
Sep 13 00:11:49 debiancluster1 kernel: kjournald starting.  Commit interval 5 seconds
Sep 13 00:11:49 debiancluster1 kernel: EXT3 FS on drbd0, internal journal
Sep 13 00:11:49 debiancluster1 kernel: EXT3-fs: mounted filesystem with ordered data mode.
Sep 13 00:11:49 debiancluster1 Filesystem[2545]: INFO: Filesystem Success
Sep 13 00:11:49 debiancluster1 ResourceManager[2364]: debug: /etc/ha.d/resource.d/Filesystem /dev/drbd0 /var/lib/mysql ext3 start done. RC=0
Sep 13 00:11:49 debiancluster1 heartbeat: [2354]: info: local HA resource acquisition completed (standby).
Sep 13 00:11:49 debiancluster1 heartbeat: [2279]: info: Standby resource acquisition done [foreign].
Sep 13 00:11:49 debiancluster1 heartbeat: [2279]: info: Initial resource acquisition complete (auto_failback)
Sep 13 00:11:49 debiancluster1 heartbeat: [2279]: info: remote resource transition completed.
Sep 13 00:13:40 debiancluster1 kernel: drbd0: Resync done (total 127 sec; paused 0 sec; 6524 K/sec)
Sep 13 00:13:40 debiancluster1 kernel: drbd0: drbd0_worker [2199]: cstate SyncTarget --> Connected

以下は強制 shutdown した Primary を再起動したときの Secondary 側の syslog。

Sep 13 00:11:32 debiancluster2 kernel: drbd0: drbd0_receiver [3462]: cstate WFConnection --> WFReportParams
Sep 13 00:11:32 debiancluster2 kernel: drbd0: Handshake successful: DRBD Network Protocol version 74
Sep 13 00:11:32 debiancluster2 kernel: drbd0: Connection established.
Sep 13 00:11:32 debiancluster2 kernel: drbd0: I am(P): 1:00000002:00000001:00000003:00000003:10
Sep 13 00:11:32 debiancluster2 kernel: drbd0: Peer(S): 1:00000002:00000001:00000003:00000002:10
Sep 13 00:11:32 debiancluster2 kernel: drbd0: drbd0_receiver [3462]: cstate WFReportParams --> WFBitMapS
Sep 13 00:11:32 debiancluster2 kernel: drbd0: Primary/Unknown --> Primary/Secondary
Sep 13 00:11:32 debiancluster2 kernel: drbd0: drbd0_receiver [3462]: cstate WFBitMapS --> SyncSource
Sep 13 00:11:32 debiancluster2 kernel: drbd0: Resync started as SyncSource (need to sync 828856 KB [207214 bits set]).
Sep 13 00:11:42 debiancluster2 heartbeat: [6088]: info: Heartbeat restart on node debiancluster1
Sep 13 00:11:42 debiancluster2 heartbeat: [6088]: info: Link debiancluster1:eth1 up.
Sep 13 00:11:42 debiancluster2 heartbeat: [6088]: info: Status update for node debiancluster1: status init
Sep 13 00:11:42 debiancluster2 heartbeat: [6088]: info: Status update for node debiancluster1: status up
Sep 13 00:11:42 debiancluster2 heartbeat: [6088]: debug: StartNextRemoteRscReq(): child count 1
Sep 13 00:11:42 debiancluster2 heartbeat: [6088]: debug: get_delnodelist: delnodelist=
Sep 13 00:11:42 debiancluster2 heartbeat: [7260]: debug: notify_world: setting SIGCHLD Handler to SIG_DFL
Sep 13 00:11:42 debiancluster2 harc[7260]: info: Running /etc/ha.d/rc.d/status status
Sep 13 00:11:42 debiancluster2 heartbeat: [7270]: debug: notify_world: setting SIGCHLD Handler to SIG_DFL
Sep 13 00:11:42 debiancluster2 harc[7270]: info: Running /etc/ha.d/rc.d/status status
Sep 13 00:11:43 debiancluster2 heartbeat: [6088]: info: Status update for node debiancluster1: status active
Sep 13 00:11:43 debiancluster2 heartbeat: [7280]: debug: notify_world: setting SIGCHLD Handler to SIG_DFL
Sep 13 00:11:43 debiancluster2 harc[7280]: info: Running /etc/ha.d/rc.d/status status
Sep 13 00:11:43 debiancluster2 heartbeat: [6088]: info: remote resource transition completed.
Sep 13 00:11:43 debiancluster2 heartbeat: [6088]: info: debiancluster2 wants to go standby [foreign]
Sep 13 00:11:44 debiancluster2 heartbeat: [6088]: info: standby: debiancluster1 can take our foreign resources
Sep 13 00:11:44 debiancluster2 heartbeat: [7290]: info: give up foreign HA resources (standby).
Sep 13 00:11:44 debiancluster2 ResourceManager[7300]: info: Releasing resource group: debiancluster1 drbddisk::r0 Filesystem::/dev/drbd0::/var/lib/mysql::ext3
Sep 13 00:11:44 debiancluster2 ResourceManager[7300]: info: Running /etc/ha.d/resource.d/Filesystem /dev/drbd0 /var/lib/mysql ext3 stop
Sep 13 00:11:44 debiancluster2 ResourceManager[7300]: debug: Starting /etc/ha.d/resource.d/Filesystem /dev/drbd0 /var/lib/mysql ext3 stop
Sep 13 00:11:45 debiancluster2 Filesystem[7399]: INFO: Running stop for /dev/drbd0 on /var/lib/mysql
Sep 13 00:11:45 debiancluster2 Filesystem[7399]: INFO: Trying to unmount /var/lib/mysql
Sep 13 00:11:45 debiancluster2 Filesystem[7399]: INFO: unmounted /var/lib/mysql successfully
Sep 13 00:11:45 debiancluster2 Filesystem[7335]: INFO: Filesystem Success
Sep 13 00:11:45 debiancluster2 ResourceManager[7300]: debug: /etc/ha.d/resource.d/Filesystem /dev/drbd0 /var/lib/mysql ext3 stop done. RC=0
Sep 13 00:11:45 debiancluster2 ResourceManager[7300]: info: Running /etc/ha.d/resource.d/drbddisk r0 stop
Sep 13 00:11:45 debiancluster2 ResourceManager[7300]: debug: Starting /etc/ha.d/resource.d/drbddisk r0 stop
Sep 13 00:11:45 debiancluster2 kernel: drbd0: Primary/Secondary --> Secondary/Secondary
Sep 13 00:11:46 debiancluster2 ResourceManager[7300]: debug: /etc/ha.d/resource.d/drbddisk r0 stop done. RC=0
Sep 13 00:11:46 debiancluster2 heartbeat: [7290]: info: foreign HA resource release completed (standby).
Sep 13 00:11:46 debiancluster2 heartbeat: [6088]: info: Local standby process completed [foreign].
Sep 13 00:11:46 debiancluster2 kernel: drbd0: Secondary/Secondary --> Secondary/Primary
Sep 13 00:11:49 debiancluster2 heartbeat: [6088]: WARN: 1 lost packet(s) for [debiancluster1] [17:19]
Sep 13 00:11:49 debiancluster2 heartbeat: [6088]: info: remote resource transition completed.
Sep 13 00:11:49 debiancluster2 heartbeat: [6088]: info: No pkts missing from debiancluster1!
Sep 13 00:11:49 debiancluster2 heartbeat: [6088]: info: Other node completed standby takeover of foreign resources.
Sep 13 00:13:32 debiancluster2 kernel: drbd0: [drbd0_worker/6924] sock_sendmsg time expired, ko = 4294967295
Sep 13 00:13:40 debiancluster2 kernel: drbd0: Resync done (total 127 sec; paused 0 sec; 6524 K/sec)
Sep 13 00:13:40 debiancluster2 kernel: drbd0: drbd0_worker [6924]: cstate SyncSource --> Connected

mixi clone on rails 04

本日の目標

とりあえずトップページだけ作ってみます(その 2)。

前回に引き続き今日は、

  1. mixlone の Controller 機能を集約する Main Controller の作成
  2. 認証情報(ひとの情報)を格納する Person Model の作成
  3. ログイン処理をする login Action の実装
  4. ログイン済みか確認しログインしていなければログインページへリダイレクトする before Filter の実装と設定

の残り 3 と 4 を実装します。

login Action の実装

login Action では以下の処理を行うことにします。

  • ログインフォームの表示 – メールアドレスとパスワードを入力するフォームを表示します。下には“ログイン”ボタンがあり、これを押すと login Action 自身へ POST されるようにします。
  • ログイン処理の実施 – POST されたメールアドレスとパスワードに一致する Person が存在するか確認します。一致する Person が存在する場合は session[:person_id] に Person の id を格納し home Action へリダイレクトします。一致する Person が存在しない場合はエラーメッセージを表示します。

まずはログインフォームの準備から始めましょう。

http://(サーバの IP アドレス):3000/main/login へアクセスした際に表示されるのは app/views/main/login.rhtml でした。これを以下の通り変更します。

FILE: app/views/main/login.rhtml
1  <h1>Main#login</h1>
2  <p><%= flash[:login] %></p>
3  <%= start_form_tag %>
4  <p><label for="person_email_address">Email address</label><br/>
5  <%= text_field 'person', 'email_address'  %></p>
6  <p><label for="person_password">Password</label><br/>
7  <%= password_field 'person', 'password'  %></p>
8  <%= submit_tag 'LOGIN' %>
9  <%= end_form_tag %>

続いて login Action の Action メソッドを修正します。

http://(サーバの IP アドレス):3000/main/login へアクセスした際に実行されるのは app/controllers/main_controller.rb で定義された login メソッドでした。これを以下の通り変更します。

FILE: app/controllers/main_controller.rb
1  class MainController < ApplicationController
2    model :person
3
4    def home
5    end
6
7    def login
8      if request.post? then
9        person = Person.find(:first, :conditions => [ 'email_address = :email_address and password = :password', params[:person]])
10        if person then
11          session[:person_id] = person[:id]
12          redirect_to :action => :home
13        else
14          flash[:login] = 'LOGIN ERROR'
15        end
16      end
17    end
18  end

http request が POST かどうか調べています(8 行目)。もし POST であれば 9 行目から 15 行目までを実行します。

POST であれば Person モデルで email_address と password がフォームから入力されたものと一致するオブジェクトがないか探します(9 行目)。一致するものがあれば Person オブジェクトが返され、なければ nil が返されます。

person に値が入っているか(nil かどうか)確認します(10 行目)。もし値が入っていれば person オブジェクトの :id を session[:person_id] に代入し(11 行目) home Action へリダイレクトします(12 行目)。person が nil なら flash[:login] にエラーメッセージを代入します(14 行目)。

before Filter の実装と設定

Action メソッドを実行するまえに実行したい処理をメソッドとして定義し before Filter として設定することができます。同じように Action メソッド実行のあとに実行したい処理を after Filter として設定することができます。ついでに before と after をペアで around Filter として設定することもできます。

“session[:person_id] がセットされているかを確認しセットされていなかったら login Action へリダイレクトする”というメソッドを用意し before Filter に設定することでログインしないとコンテンツを閲覧できないように制限することが出来ます。

app/controllers/main_controller.rb を以下の通り修正します。

FILE: app/controllers/main_controller.rb
1  class MainController < ApplicationController
2    model :person
3    before_filter :authorize, :except => :login
4
5    def home
6    end
7
8    def login
...
18    end
19
20    private
21    def authorize
22      unless session[:person_id] then
23        redirect_to :action => :login
24      end
25    end
26  end

authorize という private なメソッドを定義し(20 行目 〜 25 行目)、before_filter で Main Controller にアタッチしています(3 行目)。ただし login Action に関しては before_filter の対象から外さなければならないので :except オプションで対象外としています(そうしないと無限リダイレクトにはまってしまいます)。

script/server を起動し意図した通り動作するか確認しましょう。

とりあえず、今日はここまで。

mixi clone on rails 03

本日の目標

とりあえずトップページだけ作ってみます(その 1)。

閉鎖的な mixlone ではアカウントを持った人がログインした状態でないといかなるコンテンツも閲覧出来ないようにします。そのためには、

  1. mixlone の Controller 機能を集約する Main Controller の作成
  2. 認証情報(ひとの情報)を格納する Person Model の作成
  3. ログイン処理をする login Action の実装
  4. ログイン済みか確認しログインしていなければログインページへリダイレクトする before Filter の実装と設定

を実装しなければならないわけですが、今日は上記のうち 1 と 2 を実装します。

Main Controller の作成

Rails には Model や View/Controller のひな形を作成してくれる便利な script/generate というスクリプトが用意されています。

以下の通り script/generate を実行し Main Controller(と home Action と login Action) のひな形を作成します。

masakazu@debian:~/mixlone$ script/generate controller Main home login
exists  app/controllers/
exists  app/helpers/
create  app/views/main
exists  test/functional/
create  app/controllers/main_controller.rb
create  test/functional/main_controller_test.rb
create  app/helpers/main_helper.rb
create  app/views/main/home.rhtml
create  app/views/main/login.rhtml

app/controllers/main_controller.rb というのが Main Controller の本体です。なかみはこんな感じになっています。

FILE: app/controllers/main_controller.rb
1  class MainController < ApplicationController
2
3    def home
4    end
5
6    def login
7    end
8  end

app/views/main/home.rhtml と app/views/main/login.rhtml というファイルが作られていますが、これが View のテンプレートになります。なかみはこんな感じです(以下は home.rhtml ですが login.rhtml も基本的にいっしょです)。

FILE: app/views/main/home.rhtml
1  <h1>Main#home</h1>
2  <p>Find me in app/views/main/home.rhtml</p>

この状態で script/server -b 0.0.0.0 を実行し http://(サーバの IP アドレス):3000/main/home へアクセスすると以下の処理が実行されます(Helper Module のこととかはとりあえず無視)。

  1. main_controller.rb が読み込まれます
  2. MainController のインスタンスが生成されます
  3. MainController の home メソッドが実行されます
  4. home.rhtml をテンプレートとして HTML が生成されクライアントへ返されます

home.rhtml のひな形には static は HTML 文しか書かれていませんがここには <%= @variable %> のように変数を埋め込んだり <% 1.upto(10) do |i| %><%= “#{i}<br>” %><% end %> のように Ruby code も埋め込めます。ただし .rhtml ファイルに Ruby code が埋め込めるからといってロジックを .rhtml ファイルに書くようなことは避けるべきです。Controller 内の Action メソッドでロジックを実行し .rhtml ファイルはそれを埋め込むだけ、というスタイルにしておくのが良い習慣と言えます。View と Controller を分離することで、ロジックのことを考えるときはロジックのことだけに集中でき、見栄えのことを考えるときは見栄えのことだけに集中できるようになるからです。

Rails では Controller を複数作ることができます。本当であれば機能のまとまりごとに Controller を複数用意し Action を分離すべきなのかもしれませんが、 mixlon では、そんなに複雑にはならないであろうことと、第一めんどくさいので、 Main という Controller をひとつ用意してすべての Action を Main に集約することにします。

ただしこの次の Person Model の作成で scaffold を作りますが、 Model の scaffold に関しては Model::XxxController という名前の Controller を作成することにします。これは管理目的で使うもので利用者へは見せないということにします。

Person Model の作成

以下の通り script/generate で Person Model のテンプレートを作成します。

masakazu@debian:~/mixlone$ script/generate model Person
exists  app/models/
exists  test/unit/
exists  test/fixtures/
create  app/models/person.rb
create  test/unit/person_test.rb
create  test/fixtures/people.yml
create  db/migrate
create  db/migrate/001_create_people.rb

Person という名前の Model をつくっているのに最後の行で 001_create_people.rb というファイルが生成されていますが… Rails では Model のインスタンスを格納するデータベースのテーブル名は Model の“英語での”複数形にするという暗黙のルールが設けられています。このルールは必ず守らなければならないというわけではないですが、このルールに従っておくと Model とテーブルの対応付けを Rails が勝手にやってくれます。逆にルールを破るときは Rails に“この Model のテーブルは xxx ですよ”と教えてあげなければなりません。

app/models/person.rb というのが Person Model の本体です。なかみはこんな感じになってます。

FILE: app/models/person.rb
1  class Person < ActiveRecord::Base
2  end

ご覧の通り、 script/generate が生成する Model のひな形は Class の外枠があるだけです。

Person Model のインスタンスの保存先としてデータベースに people テーブルを作らなきゃならないわけですが、ふつうにデータベースに接続して CREATE TABLE … としてもいいんですが、 Rails には SQL 文をかかずに Ruby code だけでテーブルを作るための migration という機能があるので、使ってみます。

db/migrate/001_create_people.rb というファイルが生成されていますが、これを以下のように修正します(修正箇所を太字にしています)。

FILE: db/migrate/001_create_people.rb
1  class CreatePeople < ActiveRecord::Migration
2    def self.up
3      create_table :people do |t|
4        # t.column :name, :string
5        t.column :last_name, :string
6        t.column :first_name, :string
7        t.column :nickname, :string
8        t.column :password, :string
9        t.column :address_prefecture, :integer
10        t.column :address_city, :integer
11        t.column :sex, :integer
12        t.column :birth_year, :integer
13        t.column :birth_month, :integer
14        t.column :birth_day, :integer
15        t.column :blood_group, :integer
16        t.column :birthplace_prefecture, :integer
17        t.column :birthplace_city, :integer
18  #      t.column :hobies, :integer
19        t.column :o ccupatioo, :integer
20        t.column :belonging, :string
21        t.column :self_introduction, :text
22        t.column :favorite1, :integer
23        t.column :favorite2, :integer
24        t.column :favorite3, :integer
25      end
26    end
27
28    def self.down
29      drop_table :people
30    end
31  end

以下の通り rake db:migrate を実行すると 001_create_people.rb に書いた通り CREATE TABLE が実行されます。

masakazu@debian:~/mixlone$ rake db:migrate
(in /home/masakazu/mixlone)
== CreatePeople: migrating ====================================================
-- create_table(:people)
NOTICE:  CREATE TABLE will create implicit sequence "people_id_seq" for serial column "people.id"
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "people_pkey" for table "people"
-> 0.0490s
== CreatePeople: migrated (0.0494s) ===========================================

ためしに psql で確認してみるとちゃんと people というテーブルが出来ています。

postgres@debian:~$ psql -d mixlone_development
Welcome to psql 8.1.9, the PostgreSQL interactive terminal.
Type:  \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit
mixlone_development=# \d
List of relations
Schema |     Name      |   Type   |  Owner
--------+---------------+----------+---------
public | people        | table    | mixlone
public | people_id_seq | sequence | mixlone
public | schema_info   | table    | mixlone
(3 rows)
mixlone_development=# \d people
Table "public.people"
Column         |          Type          |                      Modifiers
-----------------------+------------------------+-----------------------------------------------------
id                    | integer                | not null default nextval('people_id_seq'::regclass)
email_address         | character varying(255) |
password              | character varying(255) |
last_name             | character varying(255) |
first_name            | character varying(255) |
nickname              | character varying(255) |
address_prefecture    | integer                |
address_city          | integer                |
sex                   | integer                |
birth_year            | integer                |
birth_month           | integer                |
birth_day             | integer                |
blood_group           | integer                |
birthplace_prefecture | integer                |
birthplace_city       | integer                |
occupatioo            | integer                |
belonging             | character varying(255) |
self_introduction     | text                   |
favorite1             | integer                |
favorite2             | integer                |
favorite3             | integer                |
Indexes:
"people_pkey" PRIMARY KEY, btree (id)

people のほかに schema_info というテーブルができてますが、これは migration で管理するバージョン情報のようです。 migration 用のファイルは 001_create_people.rb のように数字 3 文字で始まるのですが、この 3 文字の数字が migration のバージョン番号になります。 migration を何個も作っていくとこの部分が 002, 003, … と増えていき rake db:migrate を実行するたびに schema_info の version よりも新しい migration 用のファイルが実行されていきます。 rake db:migrate には VERSION=xxx というオプションも指定でき、現在よりも古い状態まで戻すことが出来ます。そのときはすでに実行された migration 用ファイルの down クラスメソッドが逆順で実行されていきます。

Person Model も出来たしデータベースには people テーブルもできたのであとはひとの情報を入力していくわけですが、いちいち INSERT, UPDATE を実行していたのでは面倒です。Rails にはおなじみの scaffold という Model の情報を一覧表示したり新規追加したり削除したりするための View/Controller を用意してくれる機能があるのでこれを使って Person オブジェクトを管理するようにします。

以下の通り script/generate を実行します。

masakazu@debian:~/mixlone$ script/generate scaffold Person Model::Person
create  app/controllers/model
create  app/helpers/model
create  app/views/model/person
create  test/functional/model
dependency  model
exists    app/models/
exists    test/unit/
exists    test/fixtures/
identical    app/models/person.rb
identical    test/unit/person_test.rb
identical    test/fixtures/people.yml
create  app/views/model/person/_form.rhtml
create  app/views/model/person/list.rhtml
create  app/views/model/person/show.rhtml
create  app/views/model/person/new.rhtml
create  app/views/model/person/edit.rhtml
create  app/controllers/model/person_controller.rb
create  test/functional/model/person_controller_test.rb
create  app/helpers/model/person_helper.rb
create  app/views/layouts/person.rhtml
create  public/stylesheets/scaffold.css

上記では Person Model に対する scaffold を Model::Person という Controller に作成しています。

script/server -b 0.0.0.0 を実行し http://(サーバの IP アドレス):3000/model/person へアクセスするとこんな画面が表示されます。

New person をクリックすると新しい Person を登録するためのフォームが表示されるので適当に入力して自分のアカウントを作りましょう。アカウントとパスワードだけは直近で使う予定があるので空白だと困りますけど、それ以外はとりあえずは空白でもかまいません。追々 UNIQUE 制約とか NOT NULL 制約とかつけてきましょう。ひょっとしたら DB 側はそのままで Rails 側の Validation のみでいくかもしれないけど…

とりあえず今日はここまで。