end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

jQuery Templates -> JsRender/JsViews

javascriptのテンプレートとして、jQuery Templatesには重宝していましたが、更新をwatchしていなかったら、 プロジェクトが JsRender/JsViews に移行してました。

end0tknr.hateblo.jp

OLD

github.com

NEW

JsRender/JsViews

使用方法の詳細は、www.jsviews.com のdocumentの通りですが、以下のように書くだけで動作します。

<script id="msg_log_tmpl" type="text/x-jsrender">
  <tr class="msg_remote">
    <td style="text-align:right;">{{: user}} さんが<br>{{: time}} に追加</td>
    <td><div class="msg_body">【LOG LEVEL: {{: level}}{{: msg}}</div></td>
    <td></td>
  </tr>
</script>

<script id="msg_memo_tmpl" type="text/x-jsrender">
  <tr class="msg_local">
    <td></td>
    <td><div class="msg_body">{{: msg}}</div></td>
    <td>{{: user}} さんが<br>{{: time}} に追加</td>
  </tr>
</script>

<script src="/static/js/jquery-1.12.1.min.js"></script>
<script src="/static/js/jsrender.min.js"></script>
post_add_load_memo: function( data ){
    
    var tmpl_log  = $.templates('#msg_log_tmpl');
    var tmpl_memo = $.templates('#msg_memo_tmpl');
    for (var i=0;  i<data.recent_logs.length; i++ ){
        var recent_log = data.recent_logs[i];

        var html_tr = '';
        if( recent_log['level'] == 'MEMO'){
            html_tr = tmpl_memo.render( recent_log );
        } else {
            html_tr = tmpl_log.render( recent_log );
        }

        $('#msg_list tbody').prepend(html_tr);
        
    }

    p_util.hide_loading();
},

PMBOK (Project Management Body of Knowledge) の超・要約

自分で、よく混同する部分の抜粋

プロジェクトとは

ルーチン業務と比較して記載しています

project routine work
独自性 独自性あり 独自性なし
期限 期限あり 期限なし.例:受注業務
新製品の開発・設計
業務効率化の新業務ルール作成
既存製品の製造
手順が定型化された受注業務や経理業務

前提条件(Assumption)と、制約条件(Constraints)

前提条件 制約条件
プロジェクト開始時にプロジェクトチームが確証なく設定した条件.
システム開発プロジェクトの場合、想定利用者数、データ量等.
プロジェクトの作業に制限を与え、プロジェクトチームでは変更できない事項.
例:スケジュール、予算

スケジュール - リードとラグ

項目 説明
リード  先行タスク終了前に、後続タスクを開始できる場合の差
ラグ  先行タスク終了後に、後続タスクを開始できる場合の差

スケジュール短縮法 - クラッシングとファスト・トラッキング

項目 説明
クラッシング  要因等の追加資源を投入
ファスト・トラッキング  先行タスク終了前に、後続タスクを開始し、平行実施

リスク対策

そもそも リスクとは「不確定な要素」を指し、 プラス・リスクマイナス・リスクがあります。

マイナス・リスク対応

項目 説明
回避 リスクを避けたり、リスク発生原因を取り除く
転嫁 保険をかける等、影響を責任と共に第三者に移転
軽減 リスク発生確率や影響度を受容できる程度まで軽減
受容 軽減や回避を行わない。この場合、コンティンジェンシープランを作成。

コンティンジェンシープラン

識別したリスクが発現した場合に備えて事前に計画しておく対策や手続き。 リスク発生時の対処に必要な人員、資金等の資源や時間を確保。

プラス・リスク対応

項目 説明
活用 好機が確実に来るように
共有 好機を得やすくなるよう第三者と組む
強化 好機の発生確率やプラス影響を最大化
受領 マイナス・リスクと同様、何もしない

今度は cakephp 2.8.3 をinstall

end0tknr.hateblo.jp

先程の cakephp 3.2 に続き、cakephp 2.8.3 をインストール。 と言っても、cakephp3と異なり、cakephpはダウンロードしたファイルを解凍し、少々、設定するだけで利用できます

reference url

インストール — CakePHP Cookbook 2.x ドキュメント (日本語)

Installation — CakePHP Cookbook 2.x documentation (英語)

cakephp-2.8.3

cd /home/endo/dev/
wget https://github.com/cakephp/cakephp/archive/2.8.3.tar.gz
tar -zxvf 2.8.3.tar.gz
cd cakephp-2.8.3

edit apache's httpd.conf

$ vi /home/endo/local/apache22/conf/httpd.conf

<Directory "/home/endo/dev/cakephp-2.8.3/app/webroot">
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>
Alias /cakephp /home/endo/dev/cakephp-2.8.3/app/webroot

And you can access to "http://cent6.a5.jp:8081/cakephp/". Routing table exists in "/dev/cakephp-2.8.3/app/Config/routes.php".

php 5.6 + openssl 1.0.2 + cakephp 3.2 のインストール

参考url

http://book.cakephp.org/3.0/ja/installation.html http://book.cakephp.org/3.0/en/installation.html

openssl 1.0.2

opensslが、shared libraries 付でなかった為、再make.

$ wget https://www.openssl.org/source/openssl-1.0.2g.tar.gz
$ tar -zxvf openssl-1.0.2g.tar.gz
$ cd openssl-1.0.2g
$ less INSTALL
$ ./config --prefix=/usr/local/openssl_1.0.2 shared
$ make
$ make test
$ su
# make install

ICU - International Components for Unicode

cakephpが必要とする phpのintlモジュールが、更に icuを必要する為

$ wget http://download.icu-project.org/files/icu4c/57.1/icu4c-57_1-src.tgz
$ tar -zxvf icu4c-57_1-src.tgz
$ cd icu/source
$ ./configure
$ make
$ make check
$ su
# make install

php 5.6.21

http://end0tknr.hateblo.jp/entry/20140501/1398939088

  • ※ configureのoptionは、以前行った php 5.5.11に対して、cakephp3が必要とする " --enable-intl "を追加します
  • ※ make test で、14個の Tests failedがありましたが、無視して make installしました
$ wget http://jp2.php.net/get/php-5.6.21.tar.gz/from/this/mirror
$ mv mirror php-5.6.21.tar.gz
$ tar -zxvf php-5.6.21.tar.gz
$ cd php-5.6.21.tar.gz
$ ./configure \
  --with-apxs2=/home/endo/local/apache22/bin/apxs \
  --enable-mbstring \
  --with-mysql=/usr/local/mysql \
  --with-mysqli=/usr/local/mysql/bin/mysql_config \
  --with-pdo-mysql=/usr/local/mysql \
  --with-openssl=/usr/local/openssl_1.0.2 \
  --enable-intl
$ make
$ make test
  :
=====================================================================
TEST RESULT SUMMARY
---------------------------------------------------------------------
Exts skipped    :   46
Exts tested     :   33
---------------------------------------------------------------------

Number of tests : 13815             10408
Tests skipped   : 3407 ( 24.7%) --------
Tests warned    :    9 (  0.1%) (  0.1%)
Tests failed    :   14 (  0.1%) (  0.1%)
Expected fail   :   39 (  0.3%) (  0.4%)
Tests passed    : 10346 ( 74.9%) ( 99.4%)
---------------------------------------------------------------------
Time taken      :  597 seconds
=====================================================================
  :
=====================================================================
FAILED TEST SUMMARY
---------------------------------------------------------------------
Bug #62046  mysqli@mysqlnd can't iterate over stored sets after call to mysqli_stmt_reset() [ext/mysqli/tests/bug62046.phpt]
Bug #66043 (Segfault calling bind_param() on mysqli) [ext/mysqli/tests/bug66043.phpt]
API vs. SQL LAST_INSERT_ID() [ext/mysqli/tests/mysqli_last_insert_id.phpt]
Persistent connections and mysqli.max_links [ext/mysqli/tests/mysqli_pconn_max_links.phpt]
mysqli iterators [ext/mysqli/tests/mysqli_query_iterators.phpt]
mysqli_release_savepoint() [ext/mysqli/tests/mysqli_release_savepoint.phpt]
mysqli_store_result() [ext/mysqli/tests/mysqli_store_result_buffered_c.phpt]
Bug #65538: SSL context "cafile" disallows URL stream wrappers [ext/openssl/tests/bug65538_002.phpt]
Bug #70389 (PDO constructor changes unrelated variables) [ext/pdo_mysql/tests/bug70389.phpt]
Bug #61411 (PDO Segfaults with PERSISTENT == TRUE && EMULATE_PREPARES == FALSE) [ext/pdo_mysql/tests/bug_61411.phpt]
MySQL PDO->__construct(), PDO::MYSQL_ATTR_MAX_BUFFER_SIZE [ext/pdo_mysql/tests/pdo_mysql_attr_max_buffer_size.phpt]
PDO::ATTR_ORACLE_NULLS [ext/pdo_mysql/tests/pdo_mysql_attr_oracle_nulls.phpt]
MySQL PDO->exec(), affected rows [ext/pdo_mysql/tests/pdo_mysql_exec.phpt]
file_get_contents() test using offset parameter out of range [ext/standard/tests/file/file_get_contents_error001.phpt]
=====================================================================
  :
$ su
# make install
# cp php.ini-development /usr/local/lib/php.ini

パッケージ管理 Composer

phpではdefaultのpearがありますが、最近では、Composer もあるそうです。 cakephp3のdocumentによれば、Composer が cakephp3を管理するそうです。

$ cd /home/endo/dev
$ curl -s https://getcomposer.org/installer | /usr/local/bin/php
All settings correct for using Composer
Downloading 1.0.3...

Composer successfully installed to: /home/endo/dev/composer.phar
Use it: php composer.phar

cakephp3 プロジェクト作成

$ cd /home/endo/dev
$ /usr/local/bin/php composer.phar create-project --prefer-dist cakephp/app test_cake

ただし、intlモジュールのないphpで、cakephp3 のプロジェクトを作成しようとすると、次のようなエラーが表示されます

$ /usr/local/bin/php composer.phar create-project --prefer-dist cakephp/app my_app_name
Installing cakephp/app (3.2.6)
  - Installing cakephp/app (3.2.6)
    Downloading: 100%         
Created project in my_app_name
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
  Problem 1
    - cakephp/cakephp 3.2.8 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - cakephp/cakephp 3.2.7 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - cakephp/cakephp 3.2.6 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - cakephp/cakephp 3.2.5 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - cakephp/cakephp 3.2.4 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - cakephp/cakephp 3.2.3 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - cakephp/cakephp 3.2.2 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - cakephp/cakephp 3.2.1 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - cakephp/cakephp 3.2.0 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - Installation request for cakephp/cakephp ~3.2 -> satisfiable by cakephp/cakephp[3.2.0, 3.2.1, 3.2.2, 3.2.3, 3.2.4, 3.2.5, 3.2.6, 3.2.7, 3.2.8].
  To enable extensions, verify that they are enabled in those .ini files:
    - /usr/local/lib/php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
     :
$ 

cakephp3 の起動

$ cd /home/endo/dev
$ test_cake/bin/cake server -H cent6.a5.jp -p 5673

ACCESS TO http://cent6.a5.jp:5673

この後、ルーティングから読み進めるのであれば、$APP_ROOT/config/routes.php を参照

OpenAMって FQDNの名前解決に失敗すると、様々な機能が動作せず、ログすら出さない...

ハマった

しばらくopenamを停止し、mydns.jpの期限が切れたことがきっかけで、名前解決できないことが原因。

/etc/hosts に追記することで、暫定対処しましたが、ログも吐かないなんて、open am ... sensitive ね

Devel::NYTProf による plack(psgi, starlet)アプリの(実行≠テスト)カバレッジ計測

以前も、Devel::NYTProf::Apache + mod_perl2 で同様のことを行っていますが、今回は、Devel::NYTProf + plack(psgi, starlet)版です。 http://end0tknr.hateblo.jp/entry/20120907/1347015223

Devel::NYTProfは、元々、処理の遅い部分を見つける為のプロファイラの為、Devel::Coverのように、きちんとカバレッジ値は表示できませんが、Devel::Coverをplack下で動作させる方法が分かりませんでしたので、とりあえず、次のようにしました。

といっても、gihyo.jp のまんまです。 http://gihyo.jp/dev/serial/01/perl-hackers-hub/001702

STEP1/2 - require Devel::NYTProf 等の記載

*.psgiファイル(Amon2であれば、$AppName/script/$app-name-server )に対し、次のように記載します。

#!perl
use strict;
 :
use File::Path ();

use POSIX::AtFork qw/:all/;
my @opts = qw( addpid=1 start=no sigexit=int
               forkdepth=0 file=/home/endo/tmp/nytprof.out );
$ENV{"NYTPROF"} = join ":", @opts;
require Devel::NYTProf;
pthread_atfork(
    undef,
    undef,
    sub {
        DB::enable_profile() if $$ % 1 == 0;
    },
);

my $app = builder {
  :

STEP2/2 - nytprof.out.* のマージとhtmlの作成

以下のように実行し、作成されたindex.htmlを見ればOK。何となく、処理が通過した行を確認できます。

$ cd /home/endo/tmp
$ ls nytprof.out.*
$ nytprofmerge nytprof.out.*
$ nytprofhtml --file=nytprof-merged.out
$ ls -l nytprof/index.html 

その他 - Plack::Middleware::Profiler::NYTProf でも可能かも知れませんが...

*.psgi に以下のように記載して、動くようには見えましたが...

Plack::Middleware::Profiler::NYTProf はぶっこわれてるそうなので、つかわないのがいいとおもいます。」という記事があったので、利用していません。

my $app = builder {
    my $conf = Ean->load_config();
    enable 'Plack::Middleware::Static',
        path => qr{^(?:/static/)},
        root => File::Spec->catdir(dirname(__FILE__), '..');
        :
    enable 'Profiler::NYTProf',
         enable_profile       => sub { $$ % 1 == 0 },
         env_nytprof          => 'start=no:addpid=0:file=/dev/null',
         profiling_result_dir => sub { '/home/endo/tmp/ean_nytpro_file' },
         enable_reporting     => 1,
         nytprofhtml_path     => '/usr/local/bin/nytprofhtml';

    Ean::Web->to_app();
};

google map api for javascriptで、経路の距離を算出

↓こう書きます

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
</head>
<body>
<div class="container-fluid">

<h1>google map apiによる経路探索</h1>

<h2>1. はじめに</h2>
このプログラムは、
<a href="https://developers.google.com/maps/">google map api</a>
を使用し、2点間の経路距離を算出するものです。<br>

利用に際し、google map apiの
<a href="https://developers.google.com/maps/pricing-and-plans/">利用規約</a>
を予め、ご確認下さい。<br>
<br>
google map apiによる経路計測プログラムは、次のurlも参考になります。<br>

<a href="http://www.google-mapi.com/googlemaps/route-clearness.html">
  http://www.google-mapi.com/googlemaps/route-clearness.html</a><br>
<a href="http://www.google-mapi.com/googlemaps/route-two_points.html">
  http://www.google-mapi.com/googlemaps/route-two_points.html</a>

<h2>2. スタート地点</h2>
緯度(longitude)、経度(latitude)を指定して下さい。<br>
緯度経度が分からない場合、
<a href="http://www.geocoding.jp">http://www.geocoding.jp</a>
等で調べて下さい。<br>

緯度:<input type=test id="start_lon" value="36.000181"  style="width:150px">
経度:<input type=test id="start_lat" value="139.665844" style="width:150px">

<h2>3. ゴール地点</h2>
1行に緯度(longitude)、経度(latitude)をタブ区切りで指定して下さい。
(excelからのpasteでタブ区切りになるはずです)<br>

<textarea id="goal_lon_lat"
      style="width:400px; height:70px;"
      >35.668447  139.746661
35.660783   139.704045
</textarea>

<h2>4. 経路距離の計測結果(m)</h2>
<button type="button"
    onClick="calcDist.startCalcDists()">経路計測 実行</button><br>
google map apiから返された座標と経路距離(m)を表示します。<br>
指定したゴール座標とgoogle map apiから返された値が異なるのは
google map apiが最寄りの道路座標を探索している為かと思います。<br>
google map apiの算出結果を表示しているだけで、値の正しさは確認していません...<br>
<textarea id="calcResult"
      style="width:400px; height:70px;"></textarea>

</div>
<script type="text/javascript"
    src="http://maps.google.com/maps/api/js"></script>
<script type="text/javascript" src="js/calc-dist.js"></script>
<script>
 $(document).ready(function(){
 });
</script>
</body>
</html>
(function() {
    var directionsService = new google.maps.DirectionsService();
    var SLEEP_CALC_DIST = 500; //msec. google map apiでroute計算する実行間隔
    
    var CalcDist = function() {};
    CalcDist.prototype = {
        
        startCalcDists: function(){
            $('#calcResult').val(''); //結果欄のclear
            
            //スタート地点の座標
            this.start_lon_lat =
                [ $('#start_lon').val(), $('#start_lat').val() ];
            //ゴール地点の座標
            this.goals_str =  $('#goal_lon_lat').val().split("\n");
            
            this.calcDists(0);
        },

        calcDists: function(i){
            var goal_lon_lat = this.goals_str[i].split("\t");
            if(goal_lon_lat.length < 2){
                return false;
            }

            this.calcDist(new google.maps.LatLng( this.start_lon_lat[0],
                                                  this.start_lon_lat[1]),
                          new google.maps.LatLng( goal_lon_lat[0],
                                                  goal_lon_lat[1]) );

            var this_obj = this;
            setTimeout( function(param_i) {
                this_obj.calcDists(param_i);
            }, SLEEP_CALC_DIST, i+1);

        },

        calcDist: function(start_lon_lat, goal_lon_lat){
            
            //google map apiによる経路探索
            directionsService.route(
                {origin: start_lon_lat,
                 destination: goal_lon_lat,
                 travelMode: google.maps.DirectionsTravelMode.DRIVING,
                 unitSystem:
                 google.maps.DirectionsUnitSystem.METRIC, //m表示
                 optimizeWaypoints: true,//最適化された最短距離にする
                 avoidHighways: true,    //true=高速道路を使用しない
                 avoidTolls: true        //true=有料道路を使用しない
                },
                function(result, status) {
                    //google map apiからOKが返ってきたら、結果欄に表示
                    if (status == google.maps.DirectionsStatus.OK) {
                        //google map apiは複数のルートを返しますが
                        //「optimizeWaypoints: true」により
                        //最初が最短経路のはず...
                        var distance =
                            result.routes[0].legs[0].distance.value;
                        var end_location =
                            String( result.routes[0].legs[0].end_location );
                        
                        var match_result = end_location.match(/([\d\.]+)/g);
                        
                        var caltResultStr =
                            [match_result[0],
                             match_result[1],
                             distance].join("\t");
                        $('#calcResult').val(
                            $('#calcResult').val()+ caltResultStr+"\n");
                        
                    }
                });
        }
    };

    window.calcDist = new CalcDist();
})();

はてなブログと、wordpress.com におけるsrc highlight

markdownによるハイライト記法をすぐ忘れるのでメモ

はてなブログの場合

  ```javascript
    //
    // ここにsrcを記載
    //
  ```

wordpress.comの場合

 [sourcecode language="javascript"]
   //
   // ここにsrcを記載
   //
 [/sourcecode]

javascript:setTimeout() で sleep()代替

setTimeout()以外のことも書いていますが、以下の通りです。

(function() {
    var directionsService = new google.maps.DirectionsService();
    var SLEEP_CALC_DIST = 500; //msec. google map apiでroute計算する実行間隔
    
    var CalcDist = function() {};
    CalcDist.prototype = {
        
        startCalcDists: function(){
            $('#calcResult').val(''); //結果欄のclear
            
            //スタート地点の座標
            this.start_lon_lat =
                [ $('#start_lon').val(), $('#start_lat').val() ];
            //ゴール地点の座標
            this.goals_str =  $('#goal_lon_lat').val().split("\n");
            
            this.calcDists(0);
        },

        calcDists: function(i){
            var goal_lon_lat = this.goals_str[i].split("\t");
            if(goal_lon_lat.length < 2){
                return false;
            }

            this.calcDist(new google.maps.LatLng( this.start_lon_lat[0],
                                                  this.start_lon_lat[1]),
                          new google.maps.LatLng( goal_lon_lat[0],
                                                  goal_lon_lat[1]) );

            var this_obj = this;
            setTimeout( function(param_i) {  //////// HERE!!
                this_obj.calcDists(param_i); //////// HERE!!
            }, SLEEP_CALC_DIST, i+1);        //////// HERE!!

        },

        calcDist: function(start_lon_lat, goal_lon_lat){
            
            //google map apiによる経路探索
            directionsService.route(
                {origin: start_lon_lat,
                 destination: goal_lon_lat,
                 travelMode: google.maps.DirectionsTravelMode.DRIVING,
                 unitSystem:
                 google.maps.DirectionsUnitSystem.METRIC, //m表示
                 optimizeWaypoints: true,//最適化された最短距離にする
                 avoidHighways: true,    //true=高速道路を使用しない
                 avoidTolls: true        //true=有料道路を使用しない
                },
                function(result, status) {
                    //google map apiからOKが返ってきたら、結果欄に表示
                    if (status == google.maps.DirectionsStatus.OK) {
                        //google map apiは複数のルートを返しますが
                        //「optimizeWaypoints: true」により
                        //最初が最短経路のはず...
                        var distance =
                            result.routes[0].legs[0].distance.value;
                        var end_location =
                            String( result.routes[0].legs[0].end_location );
                        
                        var match_result = end_location.match(/([\d\.]+)/g);
                        
                        var caltResultStr =
                            [match_result[0],
                             match_result[1],
                             distance].join("\t");
                        $('#calcResult').val(
                            $('#calcResult').val()+ caltResultStr+"\n");
                        
                    }
                });
        }
    };

    window.calcDist = new CalcDist();
})();

openldapの属性にEQUA LITY=caseExactIA5Matchを指定すると、あいまい検索できない?

$ /usr/local/openldap/bin/ldapsearch -x -h ??.??.??.??  \
   -D "cn=Manager,dc=sso,dc=example,dc=com" -w ???????? \
   -b "ou=People,dc=sso,dc=example,dc=com" \
   "mail=*example*"

↑こちらのmailはできますが、↓こちらは、あいまい検索できない。

$ /usr/local/openldap/bin/ldapsearch -x -h ??.??.??.?? \
   -D "cn=Manager,dc=sso,dc=example,dc=com" -w ???????? \
   -b "ou=People,dc=sso,dc=example,dc=com" \
   "xemsSerialNo=*SA*"
/usr/local/openldap/bin/ldapsearch -x -h ??.??.??.?? \
   -D "cn=config" -w ???????? \
   -b 'olcDatabase={2}bdb,cn=config'

$ /usr/local/openldap/bin/ldapsearch -x -h ??.??.??.?? \
   -D "cn=config" -w ???????? \
   -b 'cn=config' '(objectClass=olcSchemaConfig)'

で、ldapの設定内容を確認できますが、caseExactIA5Match が影響している気がします。

他のIAMユーザにAWSのマネージメント・コンソールへのアクセス権限追加

あまりに多機能になってしまったAWS(amazon web services)...その使い方を忘れてしまうので、メモ

STEP1/4 IAM (Identity & Access Management) を表示

f:id:end0tknr:20160104114058p:plain

STEP2/4 IAMユーザ用のログインURLをメモ

権限を追加したIAMユーザの方へ、このurlを知らせて下さい f:id:end0tknr:20160104114101p:plain

STEP3/4 IAMユーザに管理ポリシー追加

アクセス許可に「AdministratorAccess」を指定して下さい f:id:end0tknr:20160104114052p:plain f:id:end0tknr:20160104114054p:plain

STEP4/4 IAMユーザにパスワード発行

f:id:end0tknr:20160104114056p:plain

nginx の rewrite における last と break

http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

「last : 評価を続ける」、「break: 評価を終える」と覚えると、よさそ

last

以下のnginxの設定の場合、「/A/foobar.jpg」にアクセスすると、最終的に「/C/foobar.jpg」にrewriteされます。

location /A {
    rewrite /A/(.*) /B/$1 last;
}

location /B {
    rewrite /B/(.*) /C/$1 last;
}

break

以下のnginxの設定の場合、「/A/foobar.jpg」にアクセスすると、「/B/foobar.jpg」までrewriteされます。

location /A {
    rewrite /A/(.*) /B/$1 break;
}

location /B {
    rewrite /B/(.*) /C/$1 last;
}

nginxにおけるlocation match の優先度

https://www.nginx.com/resources/admin-guide/nginx-web-server/ ポイントは、以下の2つ。

POINT1 - 前方一致 & 最長一致

例えば、nginx.conf に次のように設定されている場合、/images/foobar.gif に対するアクセスは、「location /images/」が適用されます。

server {
    location /images/ {
        root /data;
    }

    location / {
        proxy_pass http://www.example.com;
    }
}

POINT2 - 完全一致と正規表現での優先度

priority prefix example
1 = (完全一致) location = /path
2 ^~ (前方一致&後方不参照) location = /image
3 ~ (正規表現&大文字小文字 区別あり) location ~ /image/
4 ~* (正規表現&大文字小文字 区別なし) location ~* .(jpg|png)
5 なし(前方一致&後方参照) location /image

※「後方参照あり」の場合、一致した後も、他のlocationを評価し、より優先度の高い locationが見つかった場合、そちらを優先します

python uwsgi install error - Python.h: No such file or directory

エラー内容 - Python.h: No such file or directory

$ sudo pip install uwsgi
    :
[arm-linux-gnueabihf-gcc -pthreadIn file included from plugins/python/python_plugin.c:1:0:
plugins/python/uwsgi_python.h:2:20: fatal error: Python.h: No such file or directory
 #include <Python.h>
               ^
compilation terminated.
    :
[arm-linux-gnueabihf-gcc -pthread] core/config_py.o
*** uWSGI compiling embedded plugins ***
[arm-linux-gnueabihf-gcc -pthread] plugins/python/python_plugin.o
----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-dQkMew/uwsgi/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-ACw6M6-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip-build-dQkMew/uwsgi
Storing debug log for failure in /root/.pip/pip.log
$

解決策 - python-dev をインストール

$ sudo apt-get install python-dev 

nginxでbasic認証

http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html

STEP0/2 - htpasswd コマンドのinstall

basic認証に使用するパスワードファイルを作成する為、apacheに付属する htpasswd をinstallします。

centosの場合

# yum install httpd-tools

debian , raspbian の場合

# apt-get install apache2-utils

STEP1/2 - パスワードファイルの作成

$ sudo /usr/bin/htpasswd -c /usr/local/nginx19/conf/auth_basic_passwd end0tknr
New password: 
Re-type new password:

STEP2/2 - nginx.conf の編集

以下のように auth_basic を auth_basic_user_file を追記して下さい。

# vi /usr/local/nginx19/conf/nginx.conf
http {
    :
    server {
        listen       80;
        server_name  raspi.end0tknr.mydns.jp;
        return 302 https://$host$request_uri;
    }

    server {
        :
        auth_basic "MEMBER ONLY";
        auth_basic_user_file "auth_basic_passwd";

        location / {
            root   html;
            index  index.html;
#            auth_basic "off";
        }
    }
}

上記の例では、location / {} 内に 「auth_basic "off"」がありますが、 このような設定で url / path 毎に 認証の要/不要を分けることも可能です。