ラベル linux の投稿を表示しています。 すべての投稿を表示
ラベル linux の投稿を表示しています。 すべての投稿を表示

Juliusのサーバインストールと動作テスト

Juliusをインストールする

いずれモジュールモードで動かしてみるつもりだ。

$ git clone https://github.com/julius-speech/julius

ファイルがgithubからローカルにコピーされる。

$ cd julius
$ ./configure

でコマンドラインが流れた後、こんな表示が出る。

****************************************************************
Julius/Julian libsent library rev.4.4.2.1:

- Audio I/O
    primary mic device API   : oss (Open Sound System compatible)
    available mic device API : oss
    supported audio format   : RAW and WAV only
    NetAudio support         : no
- Language Modeling
    class N-gram support     : yes
- Libraries
    file decompression by    : zlib library
- Process management
    fork on adinnet input    : no

  Note: compilation time flags are now stored in "libsent-config".
        If you link this library, please add output of
        "libsent-config --cflags" to CFLAGS and
        "libsent-config --libs" to LIBS.
****************************************************************

じゃ、先に進みますか。

$ make
$ sudo make install

なんだか、一瞬で作業終了。
警告も出ていないのでインストールされた、、、のかな??

文法認識キットをインストール。

その前に、gitから大型ファイルをダウンロードするためのツールgit lfsをインストールしろというご命令が。。。
種々のサイトを参考にしてみたけれど、Ubuntu17でパッケージインストール成功報告がない。
で、とりあえずコマンドを叩いてみた。

$ sudo apt install git-lfs
[sudo] cooloctober のパスワード:
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています               
状態情報を読み取っています... 完了
以下のパッケージが新たにインストールされます:
  git-lfs
アップグレード: 0 個、新規インストール: 1 個、削除: 0 個、保留: 0 個。

…… 以下略 ……

なんかしれっとインストールできたっぽい。
ありがたや。

で、あらためて文法認識キットを導入してみる。

$ git lfs clone https://github.com/julius-speech/grammar-kit

導入成功。
そんなにでかいファイルじゃない感じもするしで、git lfsが必要だったのかよく分からん。

テストしてみよう。
サーバに置いてあるので、直接マイクを使えない環境。
テスト音声ファイルを使って動作テストを行う。

$ cd grammar-kit
$ julius -C testmic.jconf -nostrip -charconv SJIS UTF-8 -input rawfile

STAT: include config: testmic.jconf
STAT: include config: hmm_ptm.jconf
STAT: jconf successfully finalized
STAT: *** loading AM00 _default
Stat: init_phmm: Reading in HMM definition
Stat: read_binhmm: binary format HMM definition
Stat: read_binhmm: this HMM does not need multipath handling
Stat: init_phmm: defined HMMs:  7946
Stat: init_phmm: loading ascii hmmlist
Stat: init_phmm: logical names: 21424 in HMMList
Stat: init_phmm: base phones:    43 used in logical
Stat: init_phmm: finished reading HMM definitions
STAT: making pseudo bi/mono-phone for IW-triphone
Stat: hmm_lookup: 10 pseudo phones are added to logical HMM list
STAT: *** AM00 _default loaded
STAT: *** loading LM00 _default
STAT: reading [SampleGrammars/fruit/fruit.dfa] and [SampleGrammars/fruit/fruit.dict]...
Stat: init_voca: read 20 words
STAT: done
STAT: Gram #0 fruit registered
STAT: Gram #0 fruit: new grammar loaded, now mash it up for recognition
STAT: Gram #0 fruit: extracting category-pair constraint for the 1st pass
STAT: Gram #0 fruit: installed
STAT: Gram #0 fruit: turn on active
STAT: grammar update completed
STAT: *** LM00 _default loaded
STAT: ------
STAT: All models are ready, go for final fusion
STAT: [1] create MFCC extraction instance(s)
STAT: *** create MFCC calculation modules from AM
STAT: AM 0 _default: create a new module MFCC01
STAT: 1 MFCC modules created
STAT: [2] create recognition processing instance(s) with AM and LM
STAT: composing recognizer instance SR00 _default (AM00 _default, LM00 _default)
STAT: Building HMM lexicon tree
STAT: lexicon size: 201+0=201
STAT: coordination check passed
STAT: multi-gram: beam width set to 200 (guess) by lexicon change
STAT: wchmm (re)build completed
STAT: SR00 _default composed
STAT: [3] initialize for acoustic HMM calculation
Stat: outprob_init: all mixture PDFs are tied-mixture, use calc_tied_mix()
Stat: addlog: generating addlog table (size = 1953 kB)
Stat: addlog: addlog table generated
STAT: [4] prepare MFCC storage(s)
STAT: All init successfully done

STAT: ###### initialize input device
----------------------- System Information begin ---------------------
JuliusLib rev.4.4.2.1 (fast)

Engine specification:
 -  Base setup   : fast
 -  Supported LM : DFA, N-gram, Word
 -  Extension    :
 -  Compiled by  : gcc -O6 -fomit-frame-pointer
Library configuration: version 4.4.2.1
 - Audio input
    primary A/D-in driver   : oss (Open Sound System compatible)
    available drivers       : oss
    wavefile formats        : RAW and WAV only
    max. length of an input : 320000 samples, 150 words
 - Language Model
    class N-gram support    : yes
    MBR weight support      : yes
    word id unit            : short (2 bytes)
 - Acoustic Model
    multi-path treatment    : autodetect
 - External library
    file decompression by   : zlib library
 - Process hangling
    fork on adinnet input   : no
 - built-in SIMD instruction set for DNN
    SSE AVX FMA
    AVX is available maximum on this cpu, use it


------------------------------------------------------------
Configuration of Modules

 Number of defined modules: AM=1, LM=1, SR=1

 Acoustic Model (with input parameter spec.):
 - AM00 "_default"
    hmmfilename=model/phone_m/hmmdefs_ptm_gid.binhmm
    hmmmapfilename=model/phone_m/logicalTri

 Language Model:
 - LM00 "_default"
    grammar #1:
        dfa  = SampleGrammars/fruit/fruit.dfa
        dict = SampleGrammars/fruit/fruit.dict

 Recognizer:
 - SR00 "_default" (AM00, LM00)

------------------------------------------------------------
Speech Analysis Module(s)

[MFCC01]  for [AM00 _default]

 Acoustic analysis condition:
           parameter = MFCC_E_D_N_Z (25 dim. from 12 cepstrum + energy, abs energy supressed with CMN)
    sample frequency = 16000 Hz
       sample period =  625  (1 = 100ns)
         window size =  400 samples (25.0 ms)
         frame shift =  160 samples (10.0 ms)
        pre-emphasis = 0.97
        # filterbank = 24
       cepst. lifter = 22
          raw energy = False
    energy normalize = False
        delta window = 2 frames (20.0 ms) around
         hi freq cut = OFF
         lo freq cut = OFF
     zero mean frame = OFF
           use power = OFF
                 CVN = OFF
                VTLN = OFF

    spectral subtraction = off

 cep. mean normalization = yes, with per-utterance self mean
 cep. var. normalization = no

     base setup from = Julius defaults

------------------------------------------------------------
Acoustic Model(s)

[AM00 "_default"]

 HMM Info:
    7946 models, 3131 states, 3131 mpdfs, 8256 Gaussians are defined
          model type = has tied-mixture, context dependency handling ON
      training parameter = MFCC_E_N_D_Z
       vector length = 25
    number of stream = 1
         stream info = [0-24]
    cov. matrix type = DIAGC
       duration type = NULLD
        codebook num = 129
       max codebook size = 64
    max mixture size = 64 Gaussians
     max length of model = 5 states
     logical base phones = 43
       model skip trans. = not exist, no multi-path handling

 AM Parameters:
        Gaussian pruning = beam  (-gprune)
  top N mixtures to calc = 2 / 64  (-tmix)
    short pause HMM name = "sp" specified, "sp" applied (physical)  (-sp)
  cross-word CD on pass1 = handle by approx. (use average prob. of same LC)

------------------------------------------------------------
Language Model(s)

[LM00 "_default"] type=grammar

 DFA grammar info:
      8 nodes, 10 arcs, 9 terminal(category) symbols
      category-pair matrix: 60 bytes (1024 bytes allocated)

 Vocabulary Info:
        vocabulary size  = 20 words, 67 models
        average word len = 3.3 models, 10.1 states
       maximum state num = 21 nodes per word
       transparent words = not exist
       words under class = not exist

 Parameters:
   found sp category IDs =

------------------------------------------------------------
Recognizer(s)

[SR00 "_default"]  AM00 "_default"  +  LM00 "_default"

 Lexicon tree:
     total node num =    201
      root node num =     20
      leaf node num =     20

    (-penalty1) IW penalty1 = +0.0
    (-penalty2) IW penalty2 = +0.0
    (-cmalpha)CM alpha coef = 0.050000

 Search parameters:
        multi-path handling = no
    (-b) trellis beam width = 200 (-1 or not specified - guessed)
    (-bs)score pruning thres= disabled
    (-n)search candidate num= 1
    (-s)  search stack size = 500
    (-m)    search overflow = after 2000 hypothesis poped
            2nd pass method = searching sentence, generating N-best
    (-b2)  pass2 beam width = 30
    (-lookuprange)lookup range= 5  (tm-5 <= t     (-sb)2nd scan beamthres = 80.0 (in logscore)
    (-n)        search till = 1 candidates found
    (-output)    and output = 1 candidates out of above
     IWCD handling:
       1st pass: approximation (use average prob. of same LC)
       2nd pass: loose (apply when hypo. is popped and scanned)
     all possible words will be expanded in 2nd pass
     build_wchmm2() used
     lcdset limited by word-pair constraint
    progressive output on 1st pass
    short pause segmentation = off
            progout interval = 300 msec
    fall back on search fail = off, returns search failure

------------------------------------------------------------
Decoding algorithm:

    1st pass input processing = buffered, batch
    1st pass method = 1-best approx. generating indexed trellis
    output word confidence measure based on search-time scores

------------------------------------------------------------
FrontEnd:

 Input stream:
                 input type = waveform
               input source = waveform file
              input filelist = (none, get file name from stdin)
              sampling freq. = 16000 Hz required
             threaded A/D-in = supported, off
       zero frames stripping = off
             silence cutting = off
        long-term DC removal = off
        level scaling factor = 1.00 (disabled)
          reject short input = off
          reject  long input = off

----------------------- System Information end -----------------------

Notice for feature extraction (01),
    *************************************************************
    * Cepstral mean normalization for batch decoding:           *
    * per-utterance mean will be computed and applied.          *
    *************************************************************

enter filename->sample.wav
Stat: adin_file: input speechfile: sample.wav
STAT: 33984 samples (2.12 sec.)
STAT: ### speech analysis (waveform -> MFCC)
pass1_best: リンゴ 3 個 を ください           
sentence1: リンゴ 3 個 を ください


認識できているみたいです。

(備忘録)現在の開発環境へのアクセス方法を記載

セキュリティの観点から、ポートはsshだけしか開けていない。
WebブラウザでWebアプリにアクセスする場合も、sshのポートフォワーディングで行う。

手順:
■sshでサーバにアクセスして通信確立。
■Webアプリケーションを使う場合は、あらかじめコマンドラインでプログラムを立ち上げておく。
■Webブラウザでアクセスする時は、http://localhost:8080/hogehoge/

これでWebブラウザになにか表示されるはず。

nginxの設定を変更

なかなかよく分かっていなかったnginx.confの書き方。
現在はこんな感じになっている。

=== 以下、設定サンプル ===

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;

    client_max_body_size 1024m;

    default_type  application/octet-stream;

    sendfile        off;
    keepalive_timeout  65;

    index index.html index.htm;

    server {
        listen       80;
        server_name  localhost;
    proxy_read_timeout 10m;
    autoindex on;

    location = /favicon.ico {
        log_not_found off;
    }


    location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
            root   /var/www/static/;
            access_log        off;
            expires           30d;
    }

        location / {
        proxy_pass http://localhost:53000;    # tornado(アプリ)が53000でListenしている前提
           break;
        }

    location /echo {
        alias /var/www/apps/echo;
           proxy_pass http://localhost:53001;        # tornado(アプリ)がWebsocketを使っている場合
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        index echo.html;
    }

    location /chat {
        alias /var/www/apps/chat;
                proxy_pass http://localhost:53001;              # tornado(アプリ)がWebsocketを使っている場合
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        index main.html;
    }


    location /data/ {
        proxy_http_version 1.1;
        expires off;
        proxy_request_buffering off;
        chunked_transfer_encoding on;
        root /var/www/data/;
    }
    }

}

=== ここまで ===

ハマったポイントとしては、
location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
   root   /var/www/static/;
  以下略
}

と設定してあるので、各アプリケーション絡みのjpgやcssファイルは/www/static/適当なフォルダ/に保存しないと動かないこと。

下の設定は、Websocketを使うアプリケーションのもの。

location /chat {
    alias /var/www/apps/chat;
        proxy_pass http://localhost:53001; 
        # tornado(アプリ)がWebsocketを使っている場合
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    index main.html;
}

Webブラウザから http://hogehoge.com/chat と入力するとポート番号53001で待機しているtornadoアプリケーションにフォワードされる。
アプリケーションが動かなくてすごく悩まされたのは、alias設定を書いていなかったため。
そりゃそうだ。
ポート番号53001に来たパケットをフォワードしようにも、どこのアプリケーションにフォワードするのか記述がなければ動くわけないよな。。。。(>_<)

ちなみに上記の設定では、http://hogehoge.com/data/にアクセスすると、/var/www/data/に行く設定になっている。

nginxをリバースプロキシ化して、nginx unitを呼び出す

やっとわかってきたぞ。

$ cd /etc/nginx/
$ sudo vi nginx.conf

で、設定ファイルの内容を変更する。
念のためにnginx.confのバックアップを取っておくことを超お勧めする。

全文は次の通り。
色の変わっているところが変更部分だ。
とりあえずの設定だから、80ポートにアクセスするとwsgiファイルが反応する。
他のhtmlファイル等は反応できないので、それは別途調整が必要。

=== 以下、nginx.confファイルの内容===
worker_processes  1;

events {
    worker_connections  1024;
}


http {
    include       mime.types;

    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    upstream unit_backend {
        server 127.0.0.1:8400;
        }



    server {
        listen       80;

        server_name  localhost;

        location / {
           proxy_pass http://unit_backend;
           proxy_set_header Host $host;


        }

    }

}

wsgiファイルをいじってみる

Pythonのコードを書いてゆくうえで、まずはwsgiを変更してゆけばよい

wsgi.pyを変更したら、
$ sudo systemctl restart unit

でnginx unitの再起動が必要。

テストから離れたディレクトリの変更などは、別途挑戦予定。

→ディレクトリ変更はできた。
 /var/www/python-app に移動して、表示できることを確認済み。

nginx unitの設定値を見てみる

まず現状のnginx unitの設定値がどうなっているのか調べてみる。

$ sudo curl --unix-socket /var/run/control.unit.sock http://localhost/
{
        "applications": {
                "example_python": {
                        "type": "python 3.6",
                        "user": "nobody",
                        "processes": 2,
                        "path": "/usr/share/doc/unit-python3.6/examples/python-app",
                        "module": "wsgi"
                }
        },

        "listeners": {
                "*:8400": {
                        "application": "example_python"
                }
        }
}

なんか良く分からないが、8400ポートはexsample_pythonというアプリケーションのリスナーに使われている。
アプリケーションの設定は"applications"の中で定義されていて、ポート8400にアクセスがあると、/usr/share/doc/unit-python3.6/examples/python-app というディレクトリにあるwsgiというモジュールを読み込んでいるらしい。wsgiファイルはwsgi.py が正式なファイル名だった。

では、ここから実験。
アプリケーションリスナー設定を削除してみる。

$ sudo curl -X DELETE --unix-socket /var/run/control.unit.sock http://localhost/listeners/*:8400
{
        "success": "Reconfiguration done."
}

アプリケーション設定も削除してみる。
$ sudo curl -X DELETE --unix-socket /var/run/control.unit.sock http://localhost/applications/example_python
{
        "success": "Reconfiguration done."
}

本当に削除されたのか確認。

$ sudo curl --unix-socket /var/run/control.unit.sock http://localhost/
{
        "applications": {},
        "listeners": {}
}

削除されて空っぽになっている。
この状態でポート番号8400にアクセスするとどうなるのか?

$ curl http://localhost:8400
curl: (7) Failed to connect to localhost port 8400: 接続を拒否されました

予定通り繋がらなくなっている。

じゃあ最初の設定を start.json というファイルに保存して、再設定を掛けたらどうなるのか?

$ sudo curl -X PUT -d @start.json --unix-socket /var/run/control.unit.sock http://localhost/
{
        "success": "Reconfiguration done."
}

成功したらしい。
ちゃんと動いているのか確認してみる。

$ curl http://localhost:8400
2018-07-13 01:49:38 PM

Python: 3.6.5 (default, Apr  1 2018, 05:46:30)
[GCC 7.3.0]

ENV Variables:

LANG    ja_JP.UTF-8
LANGUAGE        ja_JP:ja
PATH    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
INVOCATION_ID   4495414f19f340b695fbcf64bf14c449
JOURNAL_STREAM  9:19378
DAEMON_ARGS     --log /var/log/unit.log --pid /run/unit.pid


動いているね。
ふむふむ、少しずつ分かってきたような。。。気もしてきた。

/etc/nginx/mime.types の中身

types {
    text/html                                        html htm shtml;
    text/css                                         css;
    text/xml                                         xml;
    image/gif                                        gif;
    image/jpeg                                       jpeg jpg;
    application/javascript                           js;
    application/atom+xml                             atom;
    application/rss+xml                              rss;

    text/mathml                                      mml;
    text/plain                                       txt;
    text/vnd.sun.j2me.app-descriptor                 jad;
    text/vnd.wap.wml                                 wml;
    text/x-component                                 htc;

    image/png                                        png;
    image/svg+xml                                    svg svgz;
    image/tiff                                       tif tiff;
    image/vnd.wap.wbmp                               wbmp;
    image/webp                                       webp;
    image/x-icon                                     ico;
    image/x-jng                                      jng;
    image/x-ms-bmp                                   bmp;

    font/woff                                        woff;
    font/woff2                                       woff2;

    application/java-archive                         jar war ear;
    application/json                                 json;
    application/mac-binhex40                         hqx;
    application/msword                               doc;
    application/pdf                                  pdf;
    application/postscript                           ps eps ai;
    application/rtf                                  rtf;
    application/vnd.apple.mpegurl                    m3u8;
    application/vnd.google-earth.kml+xml             kml;
    application/vnd.google-earth.kmz                 kmz;
    application/vnd.ms-excel                         xls;
    application/vnd.ms-fontobject                    eot;
    application/vnd.ms-powerpoint                    ppt;
    application/vnd.oasis.opendocument.graphics      odg;
    application/vnd.oasis.opendocument.presentation  odp;
    application/vnd.oasis.opendocument.spreadsheet   ods;
    application/vnd.oasis.opendocument.text          odt;
    application/vnd.openxmlformats-officedocument.presentationml.presentation
                                                     pptx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                                                     xlsx;
    application/vnd.openxmlformats-officedocument.wordprocessingml.document
                                                     docx;
    application/vnd.wap.wmlc                         wmlc;
    application/x-7z-compressed                      7z;
    application/x-cocoa                              cco;
    application/x-java-archive-diff                  jardiff;
    application/x-java-jnlp-file                     jnlp;
    application/x-makeself                           run;
    application/x-perl                               pl pm;
    application/x-pilot                              prc pdb;
    application/x-rar-compressed                     rar;
    application/x-redhat-package-manager             rpm;
    application/x-sea                                sea;
    application/x-shockwave-flash                    swf;
    application/x-stuffit                            sit;
    application/x-tcl                                tcl tk;
    application/x-x509-ca-cert                       der pem crt;
    application/x-xpinstall                          xpi;
    application/xhtml+xml                            xhtml;
    application/xspf+xml                             xspf;
    application/zip                                  zip;

    application/octet-stream                         bin exe dll;
    application/octet-stream                         deb;
    application/octet-stream                         dmg;
    application/octet-stream                         iso img;
    application/octet-stream                         msi msp msm;

    audio/midi                                       mid midi kar;
    audio/mpeg                                       mp3;
    audio/ogg                                        ogg;
    audio/x-m4a                                      m4a;
    audio/x-realaudio                                ra;

    video/3gpp                                       3gpp 3gp;
    video/mp2t                                       ts;
    video/mp4                                        mp4;
    video/mpeg                                       mpeg mpg;
    video/quicktime                                  mov;
    video/webm                                       webm;
    video/x-flv                                      flv;
    video/x-m4v                                      m4v;
    video/x-mng                                      mng;
    video/x-ms-asf                                   asx asf;
    video/x-ms-wmv                                   wmv;
    video/x-msvideo                                  avi;
}

/etc/nginx/nginx.conf の中身

#user  nobody;
#Defines which Linux system user will own and run the Nginx server

worker_processes  1;
#Referes to single threaded process. Generally set to be equal to the number of CPUs or cores.

#error_log  logs/error.log; #error_log  logs/error.log  notice;
#Specifies the file where server logs.

#pid        logs/nginx.pid;
#nginx will write its master process ID(PID).

events {
    worker_connections  1024;
    # worker_processes and worker_connections allows you to calculate maxclients value:
    # max_clients = worker_processes * worker_connections
}


http {
    include       mime.types;
    # anything written in /opt/nginx/conf/mime.types is interpreted as if written inside the http { } block

    default_type  application/octet-stream;
    #

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    # If serving locally stored static files, sendfile is essential to speed up the server,
    # But if using as reverse proxy one can deactivate it

    #tcp_nopush     on;
    # works opposite to tcp_nodelay. Instead of optimizing delays, it optimizes the amount of data sent at once.

    #keepalive_timeout  0;
    keepalive_timeout  65;
    # timeout during which a keep-alive client connection will stay open.

    #gzip  on;
    # tells the server to use on-the-fly gzip compression.

    server {
        # You would want to make a separate file with its own server block for each virtual domain
        # on your server and then include them.
        listen       80;
        #tells Nginx the hostname and the TCP port where it should listen for HTTP connections.
        # listen 80; is equivalent to listen *:80;

        server_name  localhost;
        # lets you doname-based virtual hosting

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            #The location setting lets you configure how nginx responds to requests for resources within the server.
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

/etc/nginx/conf.default.conf の中身

#user  nobody;
#Defines which Linux system user will own and run the Nginx server

worker_processes  1;
#Referes to single threaded process. Generally set to be equal to the number of CPUs or cores.

#error_log  logs/error.log; #error_log  logs/error.log  notice;
#Specifies the file where server logs. 

#pid        logs/nginx.pid;
#nginx will write its master process ID(PID).

events {
    worker_connections  1024;
    # worker_processes and worker_connections allows you to calculate maxclients value: 
    # max_clients = worker_processes * worker_connections
}


http {
    include       mime.types;
    # anything written in /opt/nginx/conf/mime.types is interpreted as if written inside the http { } block

    default_type  application/octet-stream;
    #

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    # If serving locally stored static files, sendfile is essential to speed up the server,
    # But if using as reverse proxy one can deactivate it
    
    #tcp_nopush     on;
    # works opposite to tcp_nodelay. Instead of optimizing delays, it optimizes the amount of data sent at once.

    #keepalive_timeout  0;
    keepalive_timeout  65;
    # timeout during which a keep-alive client connection will stay open.

    #gzip  on;
    # tells the server to use on-the-fly gzip compression.

    server {
        # You would want to make a separate file with its own server block for each virtual domain
        # on your server and then include them.
        listen       80;
        #tells Nginx the hostname and the TCP port where it should listen for HTTP connections.
        # listen 80; is equivalent to listen *:80;
        
        server_name  localhost;
        # lets you doname-based virtual hosting

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            #The location setting lets you configure how nginx responds to requests for resources within the server.
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

nginxの再インストールでハマった件

なんかnginx unitと組み合わせてごちゃごちゃやっていたら壊れてしまった。
再インストールしても起動しなかった。

理由は次の3つのファイルがないため。
/etc/nginx/conf/default.conf
/etc/nginx/nginx.conf
/etc/nginx/mime.types

これが再インストール時に自動的に復活しない仕様はどうなんだよ、と思う。

Nginx Unitを自動起動させるには

毎回手動で立ち上げるのはめんどくさいからさ。

Nginx Unitをサーバ起動時に自動的に稼働させるためには
$ sudo systemctl enable unit
Synchronizing state of unit.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable unit

ではリブートした後どうなるか?

$ curl http://localhost:8400/
2018-07-03 08:44:39 PM

Python: 3.6.5 (default, Apr  1 2018, 05:46:30)
[GCC 7.3.0]

ENV Variables:

LANG    ja_JP.UTF-8
LANGUAGE        ja_JP:ja
PATH    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
INVOCATION_ID   8bc876ae223a4d618ebed74ed7ed9650
JOURNAL_STREAM  9:20761
DAEMON_ARGS     --log /var/log/unit.log --pid /run/unit.pid

うん、立ち上がっているね!!

Nginx Unitのインストール

Ubuntuだと比較的楽にインストールできるそうだ。

最初にキーファイルをダウンロードする。

$ wget https://nginx.org/keys/nginx_signing.key
--2018-07-02 20:15:26--  https://nginx.org/keys/nginx_signing.key
nginx.org (nginx.org) をDNSに問いあわせています... 2606:7100:1:69::3f, 2001:1af8:4060:a004:21::e3, 206.251.255.63, ...
nginx.org (nginx.org)|2606:7100:1:69::3f|:443 に接続しています... 接続しました。
HTTP による接続要求を送信しました、応答を待っています... 200 OK
長さ: 1561 (1.5K) [text/plain]
`nginx_signing.key' に保存中

nginx_signing.key             100%[=================================================>]   1.52K  --.-KB/s    時間 0s

2018-07-02 20:15:26 (105 MB/s) - `nginx_signing.key' へ保存完了 [1561/1561]

apt-keyでキーファイルを追加する。

$ sudo apt-key add nginx_signing.key

/etc/apt/sources.list.d/unit.listを作成する。

$ sudo vi /etc/apt/sources.list.d/unit.list

今回はUbuntu18.04を使っているので、次の内容を記載して保存する。

deb https://packages.nginx.org/unit/ubuntu/ bionic unit
deb-src https://packages.nginx.org/unit/ubuntu/ bionic unit

それじゃインストールを始めますか。

$ sudo apt update
$ sudo apt install unit

インストールが終わるとこんなメッセージが出る。

----------------------------------------------------------------------

Thank you for installing NGINX Unit!

Additional modules are available in standalone packages.
To see the available modules, run: apt search --names-only '^unit-'

Online documentation is available at https://unit.nginx.org/

----------------------------------------------------------------------

追加モジュールをインストールしろということなのな。
で、何を利用できるのか、追加モジュール一覧を表示させてみる。

$ apt search --names-only '^unit-'
ソート中... 完了
全文検索... 完了
unit-dbg/stable 1.2-1~bionic amd64
  NGINX Unit (debug symbols)

unit-go1.10/stable 1.2-1~bionic all
  Go 1.10 module for NGINX Unit

unit-go1.9/stable 1.2-1~bionic all
  Go 1.9 module for NGINX Unit

unit-perl/stable 1.2-1~bionic amd64
  Perl module for NGINX Unit

unit-perl-dbg/stable 1.2-1~bionic amd64
  Perl module for NGINX Unit (debug symbols)

unit-php/stable 1.2-1~bionic amd64
  PHP module for NGINX Unit

unit-php-dbg/stable 1.2-1~bionic amd64
  PHP module for NGINX Unit (debug symbols)

unit-python2.7/stable 1.2-1~bionic amd64
  Python 2.7 module for NGINX Unit

unit-python2.7-dbg/stable 1.2-1~bionic amd64
  Python 2.7 module for NGINX Unit (debug symbols)

unit-python3.6/stable 1.2-1~bionic amd64
  Python 3.6 module for NGINX Unit

unit-python3.6-dbg/stable 1.2-1~bionic amd64
  Python 3.6 module for NGINX Unit (debug symbols)

unit-ruby/stable 1.2-1~bionic amd64
  Ruby module for NGINX Unit

unit-ruby-dbg/stable 1.2-1~bionic amd64
  Ruby module for NGINX Unit (debug symbols)

今回はPythonだから、次のコマンドで追加モジュールをインストールする。

$ sudo apt install unit-python3.6

インストールが終わるとこんなメッセージが表示される。

----------------------------------------------------------------------

The Python 3.6 module for NGINX Unit has been installed.

To check out the sample app, run these commands:

 sudo service unit restart
 sudo service unit loadconfig /usr/share/doc/unit-python3.6/examples/unit.config
 curl http://localhost:8400/

Online documentation is available at https://unit.nginx.org

----------------------------------------------------------------------

いったんサーバをリブートしてみる。

$ sudo service unit restart
$ sudo service unit loadconfig /usr/share/doc/unit-python3.6/examples/unit.config
Loading configuration from /usr/share/doc/unit-python3.6/examples/unit.config...
{
        "success": "Reconfiguration done."
}
$ curl http://localhost:8400/
2018-07-02 08:39:02 PM

Python: 3.6.5 (default, Apr  1 2018, 05:46:30)
[GCC 7.3.0]

ENV Variables:

LANG    ja_JP.UTF-8
LANGUAGE        ja_JP:ja
PATH    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
INVOCATION_ID   11aa09ac823a44d2ab01da6ad6208da1
JOURNAL_STREAM  9:26162
DAEMON_ARGS     --log /var/log/unit.log --pid /run/unit.pid

なんかよくわからないが、なんか動いているんだよね。

Nginx稼働に関する管理方法

大事なことだから転記しておく。

Nginxを停止する場合
$ sudo systemctl stop nginx

停止していたNginxを稼働させる場合
$ sudo systemctl start nginx

Nginxを再起動(一旦停止後再起動)させる場合
$ sudo systemctl restart nginx

Nginxの設定を変更した場合は、再起動させずに設定の反映が可能
$ sudo systemctl reload nginx

Nginxをサーバ起動時に自動的に稼働させたくない場合
$ sudo systemctl disable nginx

Nginxをサーバ起動時に自動的に稼働させたい場合
$ sudo systemctl enable nginx

Ubuntu18にNginxをインストールする

参考にしたのはこちら。
https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-18-04

$ sudo apt update
$ sudo apt install nginx

シレっとインストール完了。

FireWallのステータスを確認する。

$ sudo ufw app list
利用可能なアプリケーション:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH
  Samba

で、Nginxのためにポートを開放する。

$ sudo ufw allow 'Nginx HTTP'
ルールを追加しました
ルールを追加しました (v6)

じゃ状況はどうなったか?

$ sudo ufw status
状態: アクティブ

To                         Action      From
--                         ------      ----
Nginx HTTP                 ALLOW       Anywhere
Nginx HTTP (v6)            ALLOW       Anywhere (v6)

OK、OK。
もちろん上記には、差しさわりのあるポート開放情報は表示はさせていないよ。

Webサーバのステータスはどんな感じ?

$ systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2018-07-02 05:24:27 JST; 7min ago
     Docs: man:nginx(8)
  Process: 2360 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 2348 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
 Main PID: 2361 (nginx)
    Tasks: 5 (limit: 4370)
   CGroup: /system.slice/nginx.service
           ├─2361 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           ├─2364 nginx: worker process
           ├─2366 nginx: worker process
           ├─2368 nginx: worker process
           └─2370 nginx: worker process

 7月 02 05:24:27 niwatori systemd[1]: Starting A high performance web server and a reverse proxy server...
 7月 02 05:24:27 niwatori systemd[1]: Started A high performance web server and a reverse proxy server.

動いてはいるが、プロセスを5つも立ち上げる必要はないな。
これはあとで調整しよう。

で、念のためにサーバをリブートして、ブラウザからhttp://IPアドレスと打ってどうなるか?

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

と表示されたら成功だ。

Jupyter NotebookにSSHポートフォワーディングで接続する

毎回コマンドラインでちまちまポートフォワーディング設定するのは面倒。
.ssh/configに設定を書き込んで楽したいのです。

Host サーバ名(sshコマンドで呼び出す設定名)
  HostName サーバのIPアドレス
  Port sshのポート番号(デフォルトだと22だが、絶対変えるべき)
  User ユーザID
  IdentityFile  ~/.ssh/id_rsa
  LocalForward ポートフォワードするサーバ側のポート番号 localhost:ローカル端末のポート番号

こいつを書き込んでおけばOK。
例えばWebサーバのIPアドレスとポート番号が 192.168.1.200:10000 とする。
上記のconfigファイルでポートフォワーディングすると、WebブラウザのURL欄に
http://localhost:10000
と入力すると、http://192.168.1.200:10000に接続される。

で、楽になると。

サーバを作り直したら、SSHが鍵認証されなくなった

タイトル通り、サーバを作り直したら、SSHが鍵認証されなくなったorz

・SSHが鍵認証されないとき、パーミッションを疑え。
http://takuya-1st.hatenablog.jp/entry/20090216/1234742055

記事の通り原因はパーミッションだった。
authorized_keysや.sshのパーミッションは見ていたけど、さらに上位のフォルダのパーミッションが775になってしまっていたのが原因。

chmod で権限を変更。

$ sudo chmod 755 /home/hogehoge/

まったく、無駄な時間を使ったわ。

リモートサーバ側でJupyter notebookを起動して使う場合

個別の端末に開発環境を整えるのもありなんだが、サーバ側でjupyter notebookを起動させると、開発ファイルなんかもサーバ側に置けて便利だ。
もっとも、便利な分いつもネットワーク環境が必要となるんだけどね。

じゃリモートからJupyter notebookを使うための設定は次の通り。

まずリモートサーバ側のhome/ユーザディレクトリで、下記のコマンドを実行する。

$ jupyter notebook --generate-config
Writing default config to: /home/hogehoge/.jupyter/jupyter_notebook_config.py


次にパスワードのハッシュ値を計算する。

$ ipython
Python 3.6.5 (default, May 23 2018, 19:51:39)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from IPython.lib import passwd

In [2]: passwd()
Enter password:
Verify password:
Out[2]: 'sha1:パスワードのハッシュ値'

Jupyter notebookの設定ファイルを編集する。

$ cd .jupyter
$ sudo vi jupyter_notebook_config.py

ファイルの最終行に下記を追加。

# 追加部分
c.IPKernelApp.pylab = 'inline'
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 9999
c.NotebookApp.password = u'sha1:パスワードのハッシュ値'

保存してファイル編集を終了する

じゃ、動作確認をしてみる。
リモートサーバ側で下記のコマンドを打ってみよう。

$ jupyter notebook &
[1] 2309
$ [W 20:35:35.035 NotebookApp] WARNING: The notebook server is listening on all IP addresses and not using encryption. This is not recommended.
[I 20:35:35.035 NotebookApp] The port 9999 is already in use, trying another port.
[I 20:35:35.043 NotebookApp] Serving notebooks from local directory: /home/hogehoge
[I 20:35:35.043 NotebookApp] 0 active kernels
[I 20:35:35.043 NotebookApp] The Jupyter Notebook is running at:
[I 20:35:35.043 NotebookApp] http://サーバ名:10000/
[I 20:35:35.043 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

手元の端末のブラウザを立ち上げ、http://サーバのIPアドレス:9999 でアクセスしてみる。
パスワードを入力する認証ページが立ち上がったら、設定は成功だ!

Python3にOpenCVをインストールする

それじゃOpebCVから。

$ sudo pip install opencv-python
Successfully installed numpy-1.14.3 opencv-python-3.4.1.15

まずはインストール成功。

次に拡張モジュール群のOpenCV contribをインストール。

$ sudo pip install opencv-contrib-python
Successfully installed opencv-contrib-python-3.4.1.15

インストール成功。

必要なものを次々インストール。

$ sudo pip install matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.0.1 matplotlib-2.2.2 pyparsing-2.2.0 python-dateutil-2.7.3 pytz-2018.4 six-1.11.0

$ sudo pip install scipy
Successfully installed scipy-1.1.0

$ sudo pip install ipython pyreadline
Successfully installed backcall-0.1.0 decorator-4.3.0 ipython-6.4.0 ipython-genutils-0.2.0 jedi-0.12.0 parso-0.2.1 pexpect-4.5.0 pickleshare-0.7.4 prompt-toolkit-1.0.15 ptyprocess-0.5.2 pygments-2.2.0 pyreadline-2.1 simplegeneric-0.8.1 traitlets-4.3.2 wcwidth-0.1.7

$ sudo pip install jupyter
Successfully installed MarkupSafe-1.0 Send2Trash-1.5.0 bleach-2.1.3 entrypoints-0.2.3 html5lib-1.0.1 ipykernel-4.8.2 ipywidgets-7.2.1 jinja2-2.10 jsonschema-2.6.0 jupyter-1.0.0 jupyter-client-5.2.3 jupyter-console-5.2.0 jupyter-core-4.4.0 mistune-0.8.3 nbconvert-5.3.1 nbformat-4.4.0 notebook-5.5.0 pandocfilters-1.4.2 pyzmq-17.0.0 qtconsole-4.3.1 terminado-0.8.1 testpath-0.3.1 tornado-5.0.2 webencodings-0.5.1 widgetsnbextension-3.2.1

正常に動くかテスト。

$ ipython
Python 3.6.5 (default, May 23 2018, 19:51:39)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import cv2

In [2]: cv2.__version__
Out[2]: '3.4.1'


ちゃんと動いてるね。

Ubuntu18.04にPyenvでPython3がインストールできない件

まさにタイトル通りのトラブル。
なんで出来ないんだろうね?!

$ sudo pyenv install 3.6.5
Downloading Python-3.6.5.tar.xz...
-> https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz
Installing Python-3.6.5...

BUILD FAILED (Ubuntu 18.04 using python-build 1.2.4-2-gdad0fc7)

Inspect or clean up the working tree at /tmp/python-build.20180523192934.2619
Results logged to /tmp/python-build.20180523192934.2619.log

Last 10 log lines:
    sys.exit(ensurepip._main())
  File "/tmp/python-build.20180523192934.2619/Python-3.6.5/Lib/ensurepip/__init__.py", line 204, in _main
    default_pip=args.default_pip,
  File "/tmp/python-build.20180523192934.2619/Python-3.6.5/Lib/ensurepip/__init__.py", line 117, in _bootstrap
    return _run_pip(args + [p[0] for p in _PROJECTS], additional_paths)
  File "/tmp/python-build.20180523192934.2619/Python-3.6.5/Lib/ensurepip/__init__.py", line 27, in _run_pip
    import pip
zipimport.ZipImportError: can't decompress data; zlib not available
Makefile:1099: recipe for target 'install' failed
make: *** [install] Error 1


このエラーをどうするのか…………。

原因はこれらしい。

Hi, look at #945, it's because Debian 9 uses OpenSSL 1.1.0 which support in CPython was added in 3.5.3 (more details in the issue above). Cheers
https://github.com/pyenv/pyenv/issues/950#issuecomment-325500154

ウチのUbuntuサーバの状態はどうなのか?

$ openssl version
OpenSSL 1.1.0g  2 Nov 2017

はぁ……ダメじゃん orz

解決方法はこれだそうだ。

$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \
libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \
xz-utils tk-dev

で、その後に再度Python3.6.5のインストールをやってみる。

$ sudo pyenv install 3.6.5
Downloading Python-3.6.5.tar.xz...
-> https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz
Installing Python-3.6.5...
Installed Python-3.6.5 to /usr/local/pyenv/versions/3.6.5

なんかインストールされたっぽい。
確認してみようか。

$ pyenv versions
  3.6.5

インストールされてるね。
それじゃデフォルトインタプリタに指定しましょか。

$ sudo pyenv global 3.6.5
$ pyenv versions
* 3.6.5 (set by /usr/local/pyenv/version)

ん。
ちゃんと3.6.5がデフォルトになってるね。

vftpdをインストール

FTPサーバを動かしてみるってことで。

1)vftpdをインストール
$ sudo apt-get install vsftpd -y

2)configファイルの編集

$ sudo vi /etc/vsftpd.conf

ファイルの中身の以下を書き換えた。
行数はバージョンよって少し異なるようだ。

▼25行目:匿名ユーザのアクセスを拒否する
anonymous_enable=NO

▼31行目:ファイルシステムを変更するFTPコマンドを許可する
write_enable=YES

▼99行目:アスキーモードのアップロードを許可する
ascii_upload_enable=YES

▼100行目:アスキーモードのダウンロードを許可する
ascii_download_enable=YES

▼120行目:設定したディレクトリより上層への移動を禁止する
chroot_local_user=YES

▼121行目:YESの場合、リストアップされたユーザはchrootの対象から除外される
chroot_list_enable=YES

▼125行目:リストアップのファイルの場所を指定する
chroot_list_file=/etc/vsftpd.chroot_list

▼131行目:サブフォルダを含む一括アップロード・ダウンロードを出来るようにする
ls_recurse_enable=YES

▼最終行に追加:ルートディレクトリを指定する
local_root =

※指定しない場合はユーザーのホームディレクトリ直下になる。
 今回は/home/shareに来るようにした。

▼最終行に追加:seccomp filter をオフを追記する
seccomp_sandbox=NO


3)アクセス許可するユーザを設定する
$ sudo vi /etc/vsftpd.chroot_list

ファイルに1ユーザ名1行で記載してゆく。
当然ながら、サーバにローカルアカウントのないユーザは認証されない。
ここに記載されたローカルユーザでFTPサーバにアクセスする。

4)vsftpdを再起動する
$ sudo service vsftpd restart

5)FTPサーバが動作しているか確認する
$ telnet localhost 21
Trying ::1...
Connected to localhost.localdomain.
Escape character is '^]'.
220 (vsFTPd 3.0.3)

上記の表示が出れば動作していることが確認できる。

FTPクライアントソフトを使う前に、軽くWebブラウザでアクセスしてみた。



認証をクリアすると、


うん。
動いているね。

6)FTPサーバを自動起動する設定
$ sudo systemctl enable vsftpd.service

ちなみに、自動起動を解除したい場合は、
$ sudo systemctl disable vsftpd.service

となる。