PerlでAzure(1)

 自分メモです。

 Perl によって Windows Azure の Table に REST API を使ってアクセスする方法を記述します。


 自分のアカウントを $account 、ストレージへのアクセスキーを $authkey とします。

# まずは使用するモジュールを
use Time::gmtime;
use Encode;
use MIME::Base64;
use Digest::SHA qw(hmac_sha256_base64);
use LWP::UserAgent;
use LWP::Simple;

package main;

my $ua = new LWP::UserAgent;
$ua->agent('PerlAzure/0.1');
$ua->timeout(5);

my $account = "ストレージのアカウント";
my $path    = "/Tables";
my $table   = "table.core.windows.net";
my $authkey = "ストレージへアクセスするための AuthorizationKey";

# アクセスURIの作成
my $request_to =  &create_uri($account, $table, $path);

# AuthKey をデコードしておく
my $basekey    = decode_base64($authkey);

# シグネイチャー作成(Table は Lite 認証でアクセス)
my $date = &create_utc();
my $sign = &create_lite_signature($account, $date, $path);
my $auth = &create_auth($account, "SharedKeyLite", $sign, $basekey);

# 必要に応じてプロキシーを設定
#$ENV{'HTTPS_PROXY'} = "";

# GET メソッドでテーブル一覧を取得するぜ
my $req = new HTTP::Request( GET => $request_to );

# 認証用の必須ヘッダーを記述
$ua->default_header("x-ms-date"      => $date );
$ua->default_header("Authorization"  => $auth);

# リクエスト送信
my $res = $ua->request($req);
if ( $res->is_success )
{
    print $res->content;
}
else
{
    print $res->status_line . "\n";
}

# おしまい
0;

# 以下に作成した関数を記述
# URI 作成
sub create_uri
{
    my $account = shift;
    my $target  = shift;
    my $path    = shift;

    return sprintf("https://%s.%s%s", $account, $target, $path);
}

# UTC の書式で現在時間を出力
sub create_utc
{
    my $gm    = gmtime();
    my $week  = (qw(Sun Mon Tue Wed Thu Fri Sat Sun))[ $gm->wday() ];
    my $month = (qw(Jan Feb Mar Apl May Jun Jul Aug Sep Oct Nov Dec))[ $gm->mon() ];
    my $year  = ( $gm->year() < 1900 ) ? $gm->year() + 1900 : $gm->year();
    my $date  = sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT", $week, $gm->mday(), $month, $year,
        $gm->hour(), $gm->min(), $gm->sec() );

    return $date;
}

# SharedLiteKey のシグネイチャー作成
sub create_lite_signature
{
    my $account = shift;
    my $date    = shift;
    my $path    = shift;

    return sprintf("%s\n/%s%s", $date, $account, $path);
}

# 認証コード作成
sub create_auth
{
    my $account = shift;
    my $type    = shift;
    my $sign    = shift;
    my $key     = shift;

    my $octets  = encode('utf8', $sign);
    my $code    = hmac_sha256_base64($octets, $key);
    $code      .= '=' while length($code) % 4;

    return sprintf("%s %s:%s", $type, $account, $code);
}

1;

 これで Perl から Windows Azure のテーブルのリストが取得できます。
 や、大変でした。何が悩んだって、AuthKey を最初に Base64 からデコードしとかなくちゃいけないのね。

 でも、なんかこれで Perl から自由に Azure にアクセスできるような気がする。
 Azure モジュールでも作ろうかな(w