SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
Practical ngx_mruby
Middleware as a Code
self.introduce
=>
{
name: “SHIBATA Hiroshi”,
nickname: “hsbt”,
title: “Chief engineer at GMO Pepabo, Inc.”,
commit_bits: [“ruby”, “rake”, “rubygems”, “rdoc”, “tdiary”,
“hiki”, “railsgirls”, “railsgirls-jp”, …],
sites: [“hsbt.org”, ruby-lang.org”, “rubyci.org”, “railsgirls.com”,
“railsgirls.jp”],
}
pepabo.com
ngx_mruby
Introduction to ngx_mruby
“ngx_mruby is A Fast and Memory-Efficient Web Server Extension
Mechanism Using Scripting Language mruby for nginx.”
https://github.com/matsumoto-r/ngx_mruby#whats-ngx_mruby
location /proxy {
mruby_set_code $backend '
backends = [
"test1.example.com",
"test2.example.com",
"test3.example.com",
]
backends[rand(backends.length)]
';
}
location /hello {
mruby_content_handler /path/to/hello.rb cache;
}
In “nginx.conf”!!!
Why mruby?
See http://hb.matsumoto-r.jp/entry/2016/02/05/140442
How to build ngx_mruby (and mruby)
I suggest to try it on OS X or Linux environment. You can change
embedded mgem via “build_config.rb” in ngx_mruby repository.
$ git clone https://github.com/matsumoto-r/ngx_mruby
$ git clone https://github.com/nginx/nginx
$ cd ngx_mruby
$ git submodule init && git submodule update
comment-out mruby-redis and mruby-vedis
$ ./configure —with-ngx-src-root=../nginx
$ make build_mruby
$ make
$ cd ../nginx
$ ./objs/nginx -V
You can get rpm and deb packages via docker and docker-
compose
You can install via default package management tool like yum and
apt-get above packages.
Build on docker
https://github.com/hsbt/ngx_mruby-package-builder
$ docker-compose build centos7
$ docker-compose run centos7
=> nginx-ngx_mruby-1.9.3-1.el7.centos.ngx.x86_64.rpm
$ docker-compose build ubuntu14.04
$ docker-compose run ubutnu14.04
=> nginx-ngx_mruby_1.9.4-1~trusty_amd64.deb
Practical
example code
https://github.com/hsbt/nginx-tech-talk
p.228 Return to summation of argument
location /sum {
mruby_set_code $sum '
result = 0
for i in 0..Nginx::Var.new.arg_n.to_i do
result += i
end
result
';
return 200 $sum;
}
`mruby_set_code` sets

return variable to nginx

variable.
You can access via

Nginx::Var instance and

arg_* methods.
p.234 logging with log_hander
location / {
mruby_content_handler_code '
Nginx.echo "Hello"
';
mruby_log_handler_code '
if Nginx::Var.new.status == Nginx::HTTP_OK
Nginx.errlogger(Nginx::LOG_INFO, "Success")
else
Nginx.errlogger(Nginx::LOG_ERR, "Error")
end
';
}
log_handler invokes
after content_handler
ngx_mruby provides
status code with
Nginx::* constants.
ngx_mruby provides
errlogger method for

user logging.
p.244 internal redirect with ngx_mruby
location /internal_redirect {
mruby_content_handler_code '
Nginx.redirect "/internal"
';
}
location /internal {
return 200 "internal redirection";
}
ngx_mruby provides
redirect method for
internal redirect.
ngx_mruby can’t use
`@internal` style.
p.246 Rewrite URI using ngx_mruby
location /image/ {
mruby_rewrite_handler_code '
file = Nginx::Var.new.uri.match(/^/image/(.+.jpg)$/)
if !file
return Nginx::HTTP_FORBIDDEN
end
url = "/image/jpg/" + file[1]
Nginx.redirect url
';
}
You can rewrite uri
with rewrite_handler
phase.
String#match
provides Regexp
matcher.
p.248 Assign to variables with ngx_mruby
location / {
set $data1 "foo1";
mruby_set_code $data2 "bar1";
mruby_content_handler_code '
v = Nginx::Var.new
v.data1 = "foo2"
v.data2 = "bar2"
v.data3 = "buzz2"
Nginx.rputs "#{v.data1}, #{v.data2}, #{v.data3}"
';
}
It’s same behavior
with ngx_lua.
You can use
interpolation like
Ruby.
p.250 Reference with request arguments
location / {
mruby_content_handler_code '
args = Hash[*Nginx::Request.new.args.split("&").map{|arg| arg.split("=")}.flatten]
args.each do |k, v|
Nginx.echo "#{k}:#{v}"
end
';
}
args = Nginx::Request.new.get_uri_args You can access
Nginx::Request#args and modified
it for Hash access.I added helper method like ngx_lua
p.251 Assign variables to arguments
location / {
mruby_content_handler_code '
args = {"pass" => "ngx_lua"}
args = args.map{|k,v| "#{k}=#{v}"}.join("&")
r = Nginx::Request.new
r.args = args
Nginx.echo(r.args)
';
}
r.set_uri_args(args) I added helper method like ngx_lua
You can assign local
variable using
Nginx::Request#args=
p.253 Reference with post parameters
location / {
mruby_content_handler_code '
r = Nginx::Request.new
args = Nginx::Request.new.body
if !args
Nginx.echo "failed to get post args."
return
end
Hash[*args.split("&").map{|arg| arg.split("=")}.flatten]
args.each do |k, v|
Nginx.echo "#{k}:#{v}"
end
';
}
args = r.get_post_args
You can access using
Nginx::Request#body
when post request.
I added helper method like ngx_lua
Rubyists friendly
r.get_uri_args
r.set_uri_args(args)
r.get_post_args
r.uri_args
r.uri_args=(args)
r.post_args
p.254 Regular expression
Use mrbgem based onigumo. It’s embedded with mruby-core box.
https://github.com/mattn/mruby-onig-regexp
p.256 Data sharing with request phase
location / {
mruby_rewrite_handler_code '
Userdata.new.phases = ["rewrite"]
Nginx.return Nginx::DECLINED
';
mruby_access_handler_code '
Userdata.new.phases << "access"
Nginx.return Nginx::DECLINED
';
mruby_content_handler_code '
Userdata.new.phases << "content"
Userdata.new.phases.each do |phase|
Nginx.echo phase
end
';
}
You can share local variables use
`mruby-userdata` gem across
handlers.
You need to return
`Nginx::DECLINED` when finished to
handler processes. It’s specification
of ngx_mruby.
p.258 Data sharing with worker processes
mruby_init_code '
c = Cache.new :namespace => "writing"
c["publisher"] = "技術評論社"
c["book"] = "nginx実践入門"
';
server {
listen 3000;
location / {
mruby_content_handler_code '
c = Cache.new :namespace => "writing"
Nginx.echo "出版社: #{c["publisher"]}"
Nginx.echo "書籍名: #{c["book"]}"
';
}
}
You can share variables use `mruby-
cache` gem across master and
worker processes.
`mruby-cache` handles only string
keys. It’s limitation.
p.260 Processing with non blocking
Nothing. Stay tune…
Or You can implement it.
p.262 Authorization using ngx_mruby
set $publickey "nginx";
set $privatekey "mruby";
location / {
mruby_content_handler_code '
arg_publickey = Nginx::Var.new.arg_publickey
arg_signature = Nginx::Var.new.arg_signature
arg_expires = Nginx::Var.new.arg_expires
expires = arg_expires.to_i
publickey = Nginx::Var.new.publickey
privatekey = Nginx::Var.new.privatekey
if arg_publickey && arg_publickey.match(publickey) || !arg_expires
Nginx.return Nginx::HTTP_FORBIDDEN
end
plaintext = "#{Nginx::Var.new.request_method}#{Nginx::Var.new.uri}#{arg_expires}#{publickey}"
hmac_sha1 = Digest::HMAC.digest(plaintext, privatekey, Digest::SHA1)
signature = Base64::encode(hmac_sha1)
if expires < Time.now.to_i
Nginx.return Nginx::HTTP_FORBIDDEN
end
if signature == arg_signature
Nginx.echo "Sucess"
else
Nginx.return Nginx::HTTP_FORBIDDEN
end
';
}
p.262 Authorization using ngx_mruby
Practical ngx_mruby
https://github.com/matsumoto-r/
ngx_mruby

Contenu connexe

Tendances

20141210 rakuten techtalk
20141210 rakuten techtalk20141210 rakuten techtalk
20141210 rakuten techtalkHiroshi SHIBATA
 
The details of CI/CD environment for Ruby
The details of CI/CD environment for RubyThe details of CI/CD environment for Ruby
The details of CI/CD environment for RubyHiroshi SHIBATA
 
Dependency Resolution with Standard Libraries
Dependency Resolution with Standard LibrariesDependency Resolution with Standard Libraries
Dependency Resolution with Standard LibrariesHiroshi SHIBATA
 
Leave end-to-end testing to Capybara
Leave end-to-end testing to CapybaraLeave end-to-end testing to Capybara
Leave end-to-end testing to CapybaraHiroshi SHIBATA
 
How to develop Jenkins plugin using to ruby and Jenkins.rb
How to develop Jenkins plugin using to ruby and Jenkins.rbHow to develop Jenkins plugin using to ruby and Jenkins.rb
How to develop Jenkins plugin using to ruby and Jenkins.rbHiroshi SHIBATA
 
Gate of Agile Web Development
Gate of Agile Web DevelopmentGate of Agile Web Development
Gate of Agile Web DevelopmentKoichi ITO
 
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)ngotogenome
 
Hijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in RubyHijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in RubySATOSHI TAGOMORI
 
Ruby/rails performance and profiling
Ruby/rails performance and profilingRuby/rails performance and profiling
Ruby/rails performance and profilingDanny Guinther
 
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Tom Croucher
 
20140626 red dotrubyconf2014
20140626 red dotrubyconf201420140626 red dotrubyconf2014
20140626 red dotrubyconf2014Hiroshi SHIBATA
 
The Future of Dependency Management for Ruby
The Future of Dependency Management for RubyThe Future of Dependency Management for Ruby
The Future of Dependency Management for RubyHiroshi SHIBATA
 
20140419 oedo rubykaigi04
20140419 oedo rubykaigi0420140419 oedo rubykaigi04
20140419 oedo rubykaigi04Hiroshi SHIBATA
 
How to distribute Ruby to the world
How to distribute Ruby to the worldHow to distribute Ruby to the world
How to distribute Ruby to the worldHiroshi SHIBATA
 

Tendances (20)

20141210 rakuten techtalk
20141210 rakuten techtalk20141210 rakuten techtalk
20141210 rakuten techtalk
 
The details of CI/CD environment for Ruby
The details of CI/CD environment for RubyThe details of CI/CD environment for Ruby
The details of CI/CD environment for Ruby
 
RubyGems 3 & 4
RubyGems 3 & 4RubyGems 3 & 4
RubyGems 3 & 4
 
Dependency Resolution with Standard Libraries
Dependency Resolution with Standard LibrariesDependency Resolution with Standard Libraries
Dependency Resolution with Standard Libraries
 
Leave end-to-end testing to Capybara
Leave end-to-end testing to CapybaraLeave end-to-end testing to Capybara
Leave end-to-end testing to Capybara
 
How to develop Jenkins plugin using to ruby and Jenkins.rb
How to develop Jenkins plugin using to ruby and Jenkins.rbHow to develop Jenkins plugin using to ruby and Jenkins.rb
How to develop Jenkins plugin using to ruby and Jenkins.rb
 
Gate of Agile Web Development
Gate of Agile Web DevelopmentGate of Agile Web Development
Gate of Agile Web Development
 
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
 
Gems on Ruby
Gems on RubyGems on Ruby
Gems on Ruby
 
RubyGems 3 & 4
RubyGems 3 & 4RubyGems 3 & 4
RubyGems 3 & 4
 
Hijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in RubyHijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in Ruby
 
Ruby/rails performance and profiling
Ruby/rails performance and profilingRuby/rails performance and profiling
Ruby/rails performance and profiling
 
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012 Streams are Awesome - (Node.js) TimesOpen Sep 2012
Streams are Awesome - (Node.js) TimesOpen Sep 2012
 
20140626 red dotrubyconf2014
20140626 red dotrubyconf201420140626 red dotrubyconf2014
20140626 red dotrubyconf2014
 
The Future of Dependency Management for Ruby
The Future of Dependency Management for RubyThe Future of Dependency Management for Ruby
The Future of Dependency Management for Ruby
 
20140419 oedo rubykaigi04
20140419 oedo rubykaigi0420140419 oedo rubykaigi04
20140419 oedo rubykaigi04
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
 
What's new in RubyGems3
What's new in RubyGems3What's new in RubyGems3
What's new in RubyGems3
 
How to distribute Ruby to the world
How to distribute Ruby to the worldHow to distribute Ruby to the world
How to distribute Ruby to the world
 
20140918 ruby kaigi2014
20140918 ruby kaigi201420140918 ruby kaigi2014
20140918 ruby kaigi2014
 

Similaire à Practical ngx_mruby

JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)PROIDEA
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby TeamArto Artnik
 
Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web AppsMark
 
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine YardHow I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine YardSV Ruby on Rails Meetup
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introductionTse-Ching Ho
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
You're Going To Need A Bigger Toolbox
You're Going To Need A Bigger ToolboxYou're Going To Need A Bigger Toolbox
You're Going To Need A Bigger ToolboxGareth Rushgrove
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Karel Minarik
 
Crafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyCrafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyNikhil Mungel
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
Golang Project Layout and Practice
Golang Project Layout and PracticeGolang Project Layout and Practice
Golang Project Layout and PracticeBo-Yi Wu
 
Developing web applications in Rust
Developing web applications in RustDeveloping web applications in Rust
Developing web applications in RustSylvain Wallez
 
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DB
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DBWeb aplikāciju izstrāde ar Ruby on Rails un Oracle DB
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DBRaimonds Simanovskis
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationAndrew Rota
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2rubyMarc Chung
 
Streamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache AmbariStreamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache AmbariAlejandro Fernandez
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant) Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant) BigDataEverywhere
 

Similaire à Practical ngx_mruby (20)

JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
JDD 2017: Nginx + Lua = OpenResty (Marcin Stożek)
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web Apps
 
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine YardHow I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introduction
 
EC2
EC2EC2
EC2
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
You're Going To Need A Bigger Toolbox
You're Going To Need A Bigger ToolboxYou're Going To Need A Bigger Toolbox
You're Going To Need A Bigger Toolbox
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]
 
Crafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in RubyCrafting Beautiful CLI Applications in Ruby
Crafting Beautiful CLI Applications in Ruby
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Golang Project Layout and Practice
Golang Project Layout and PracticeGolang Project Layout and Practice
Golang Project Layout and Practice
 
Developing web applications in Rust
Developing web applications in RustDeveloping web applications in Rust
Developing web applications in Rust
 
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DB
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DBWeb aplikāciju izstrāde ar Ruby on Rails un Oracle DB
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DB
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP Application
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
 
Streamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache AmbariStreamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache Ambari
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant) Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
 

Plus de Hiroshi SHIBATA

Deep dive into Ruby's require - RubyConf Taiwan 2023
Deep dive into Ruby's require - RubyConf Taiwan 2023Deep dive into Ruby's require - RubyConf Taiwan 2023
Deep dive into Ruby's require - RubyConf Taiwan 2023Hiroshi SHIBATA
 
How resolve Gem dependencies in your code?
How resolve Gem dependencies in your code?How resolve Gem dependencies in your code?
How resolve Gem dependencies in your code?Hiroshi SHIBATA
 
How resolve Gem dependencies in your code?
How resolve Gem dependencies in your code?How resolve Gem dependencies in your code?
How resolve Gem dependencies in your code?Hiroshi SHIBATA
 
Ruby コミッターと歩む Ruby を用いたプロダクト開発
Ruby コミッターと歩む Ruby を用いたプロダクト開発Ruby コミッターと歩む Ruby を用いたプロダクト開発
Ruby コミッターと歩む Ruby を用いたプロダクト開発Hiroshi SHIBATA
 
Why ANDPAD commit Ruby and RubyKaigi?
Why ANDPAD commit Ruby and RubyKaigi?Why ANDPAD commit Ruby and RubyKaigi?
Why ANDPAD commit Ruby and RubyKaigi?Hiroshi SHIBATA
 
RailsGirls から始める エンジニアリングはじめの一歩
RailsGirls から始める エンジニアリングはじめの一歩RailsGirls から始める エンジニアリングはじめの一歩
RailsGirls から始める エンジニアリングはじめの一歩Hiroshi SHIBATA
 
How to develop the Standard Libraries of Ruby?
How to develop the Standard Libraries of Ruby?How to develop the Standard Libraries of Ruby?
How to develop the Standard Libraries of Ruby?Hiroshi SHIBATA
 
Roadmap for RubyGems 4 and Bundler 3
Roadmap for RubyGems 4 and Bundler 3Roadmap for RubyGems 4 and Bundler 3
Roadmap for RubyGems 4 and Bundler 3Hiroshi SHIBATA
 
The Future of library dependency management of Ruby
 The Future of library dependency management of Ruby The Future of library dependency management of Ruby
The Future of library dependency management of RubyHiroshi SHIBATA
 
Ruby Security the Hard Way
Ruby Security the Hard WayRuby Security the Hard Way
Ruby Security the Hard WayHiroshi SHIBATA
 
OSS Security the hard way
OSS Security the hard wayOSS Security the hard way
OSS Security the hard wayHiroshi SHIBATA
 
The Future of library dependency manageement of Ruby
The Future of library dependency manageement of RubyThe Future of library dependency manageement of Ruby
The Future of library dependency manageement of RubyHiroshi SHIBATA
 
The Future of Bundled Bundler
The Future of Bundled BundlerThe Future of Bundled Bundler
The Future of Bundled BundlerHiroshi SHIBATA
 
Productive Organization with Ruby
Productive Organization with RubyProductive Organization with Ruby
Productive Organization with RubyHiroshi SHIBATA
 
How to distribute Ruby to the world
How to distribute Ruby to the worldHow to distribute Ruby to the world
How to distribute Ruby to the worldHiroshi SHIBATA
 
Gemification for Ruby 2.5/3.0
Gemification for Ruby 2.5/3.0Gemification for Ruby 2.5/3.0
Gemification for Ruby 2.5/3.0Hiroshi SHIBATA
 
Gemification for Ruby 2.5/3.0
Gemification for Ruby 2.5/3.0Gemification for Ruby 2.5/3.0
Gemification for Ruby 2.5/3.0Hiroshi SHIBATA
 
Gemification plan of Standard Library on Ruby
Gemification plan of Standard Library on RubyGemification plan of Standard Library on Ruby
Gemification plan of Standard Library on RubyHiroshi SHIBATA
 
How to Begin to Develop Ruby Core
How to Begin to Develop Ruby CoreHow to Begin to Develop Ruby Core
How to Begin to Develop Ruby CoreHiroshi SHIBATA
 

Plus de Hiroshi SHIBATA (20)

Deep dive into Ruby's require - RubyConf Taiwan 2023
Deep dive into Ruby's require - RubyConf Taiwan 2023Deep dive into Ruby's require - RubyConf Taiwan 2023
Deep dive into Ruby's require - RubyConf Taiwan 2023
 
How resolve Gem dependencies in your code?
How resolve Gem dependencies in your code?How resolve Gem dependencies in your code?
How resolve Gem dependencies in your code?
 
How resolve Gem dependencies in your code?
How resolve Gem dependencies in your code?How resolve Gem dependencies in your code?
How resolve Gem dependencies in your code?
 
Ruby コミッターと歩む Ruby を用いたプロダクト開発
Ruby コミッターと歩む Ruby を用いたプロダクト開発Ruby コミッターと歩む Ruby を用いたプロダクト開発
Ruby コミッターと歩む Ruby を用いたプロダクト開発
 
Why ANDPAD commit Ruby and RubyKaigi?
Why ANDPAD commit Ruby and RubyKaigi?Why ANDPAD commit Ruby and RubyKaigi?
Why ANDPAD commit Ruby and RubyKaigi?
 
RailsGirls から始める エンジニアリングはじめの一歩
RailsGirls から始める エンジニアリングはじめの一歩RailsGirls から始める エンジニアリングはじめの一歩
RailsGirls から始める エンジニアリングはじめの一歩
 
How to develop the Standard Libraries of Ruby?
How to develop the Standard Libraries of Ruby?How to develop the Standard Libraries of Ruby?
How to develop the Standard Libraries of Ruby?
 
Roadmap for RubyGems 4 and Bundler 3
Roadmap for RubyGems 4 and Bundler 3Roadmap for RubyGems 4 and Bundler 3
Roadmap for RubyGems 4 and Bundler 3
 
The Future of library dependency management of Ruby
 The Future of library dependency management of Ruby The Future of library dependency management of Ruby
The Future of library dependency management of Ruby
 
Ruby Security the Hard Way
Ruby Security the Hard WayRuby Security the Hard Way
Ruby Security the Hard Way
 
OSS Security the hard way
OSS Security the hard wayOSS Security the hard way
OSS Security the hard way
 
The Future of library dependency manageement of Ruby
The Future of library dependency manageement of RubyThe Future of library dependency manageement of Ruby
The Future of library dependency manageement of Ruby
 
The Future of Bundled Bundler
The Future of Bundled BundlerThe Future of Bundled Bundler
The Future of Bundled Bundler
 
Productive Organization with Ruby
Productive Organization with RubyProductive Organization with Ruby
Productive Organization with Ruby
 
Gems on Ruby
Gems on RubyGems on Ruby
Gems on Ruby
 
How to distribute Ruby to the world
How to distribute Ruby to the worldHow to distribute Ruby to the world
How to distribute Ruby to the world
 
Gemification for Ruby 2.5/3.0
Gemification for Ruby 2.5/3.0Gemification for Ruby 2.5/3.0
Gemification for Ruby 2.5/3.0
 
Gemification for Ruby 2.5/3.0
Gemification for Ruby 2.5/3.0Gemification for Ruby 2.5/3.0
Gemification for Ruby 2.5/3.0
 
Gemification plan of Standard Library on Ruby
Gemification plan of Standard Library on RubyGemification plan of Standard Library on Ruby
Gemification plan of Standard Library on Ruby
 
How to Begin to Develop Ruby Core
How to Begin to Develop Ruby CoreHow to Begin to Develop Ruby Core
How to Begin to Develop Ruby Core
 

Dernier

Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 

Dernier (20)

Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 

Practical ngx_mruby

  • 2. self.introduce => { name: “SHIBATA Hiroshi”, nickname: “hsbt”, title: “Chief engineer at GMO Pepabo, Inc.”, commit_bits: [“ruby”, “rake”, “rubygems”, “rdoc”, “tdiary”, “hiki”, “railsgirls”, “railsgirls-jp”, …], sites: [“hsbt.org”, ruby-lang.org”, “rubyci.org”, “railsgirls.com”, “railsgirls.jp”], }
  • 5. Introduction to ngx_mruby “ngx_mruby is A Fast and Memory-Efficient Web Server Extension Mechanism Using Scripting Language mruby for nginx.” https://github.com/matsumoto-r/ngx_mruby#whats-ngx_mruby location /proxy { mruby_set_code $backend ' backends = [ "test1.example.com", "test2.example.com", "test3.example.com", ] backends[rand(backends.length)] '; } location /hello { mruby_content_handler /path/to/hello.rb cache; } In “nginx.conf”!!!
  • 7. How to build ngx_mruby (and mruby) I suggest to try it on OS X or Linux environment. You can change embedded mgem via “build_config.rb” in ngx_mruby repository. $ git clone https://github.com/matsumoto-r/ngx_mruby $ git clone https://github.com/nginx/nginx $ cd ngx_mruby $ git submodule init && git submodule update comment-out mruby-redis and mruby-vedis $ ./configure —with-ngx-src-root=../nginx $ make build_mruby $ make $ cd ../nginx $ ./objs/nginx -V
  • 8. You can get rpm and deb packages via docker and docker- compose You can install via default package management tool like yum and apt-get above packages. Build on docker https://github.com/hsbt/ngx_mruby-package-builder $ docker-compose build centos7 $ docker-compose run centos7 => nginx-ngx_mruby-1.9.3-1.el7.centos.ngx.x86_64.rpm $ docker-compose build ubuntu14.04 $ docker-compose run ubutnu14.04 => nginx-ngx_mruby_1.9.4-1~trusty_amd64.deb
  • 11. p.228 Return to summation of argument location /sum { mruby_set_code $sum ' result = 0 for i in 0..Nginx::Var.new.arg_n.to_i do result += i end result '; return 200 $sum; } `mruby_set_code` sets return variable to nginx variable. You can access via Nginx::Var instance and arg_* methods.
  • 12. p.234 logging with log_hander location / { mruby_content_handler_code ' Nginx.echo "Hello" '; mruby_log_handler_code ' if Nginx::Var.new.status == Nginx::HTTP_OK Nginx.errlogger(Nginx::LOG_INFO, "Success") else Nginx.errlogger(Nginx::LOG_ERR, "Error") end '; } log_handler invokes after content_handler ngx_mruby provides status code with Nginx::* constants. ngx_mruby provides errlogger method for user logging.
  • 13. p.244 internal redirect with ngx_mruby location /internal_redirect { mruby_content_handler_code ' Nginx.redirect "/internal" '; } location /internal { return 200 "internal redirection"; } ngx_mruby provides redirect method for internal redirect. ngx_mruby can’t use `@internal` style.
  • 14. p.246 Rewrite URI using ngx_mruby location /image/ { mruby_rewrite_handler_code ' file = Nginx::Var.new.uri.match(/^/image/(.+.jpg)$/) if !file return Nginx::HTTP_FORBIDDEN end url = "/image/jpg/" + file[1] Nginx.redirect url '; } You can rewrite uri with rewrite_handler phase. String#match provides Regexp matcher.
  • 15. p.248 Assign to variables with ngx_mruby location / { set $data1 "foo1"; mruby_set_code $data2 "bar1"; mruby_content_handler_code ' v = Nginx::Var.new v.data1 = "foo2" v.data2 = "bar2" v.data3 = "buzz2" Nginx.rputs "#{v.data1}, #{v.data2}, #{v.data3}" '; } It’s same behavior with ngx_lua. You can use interpolation like Ruby.
  • 16. p.250 Reference with request arguments location / { mruby_content_handler_code ' args = Hash[*Nginx::Request.new.args.split("&").map{|arg| arg.split("=")}.flatten] args.each do |k, v| Nginx.echo "#{k}:#{v}" end '; } args = Nginx::Request.new.get_uri_args You can access Nginx::Request#args and modified it for Hash access.I added helper method like ngx_lua
  • 17. p.251 Assign variables to arguments location / { mruby_content_handler_code ' args = {"pass" => "ngx_lua"} args = args.map{|k,v| "#{k}=#{v}"}.join("&") r = Nginx::Request.new r.args = args Nginx.echo(r.args) '; } r.set_uri_args(args) I added helper method like ngx_lua You can assign local variable using Nginx::Request#args=
  • 18. p.253 Reference with post parameters location / { mruby_content_handler_code ' r = Nginx::Request.new args = Nginx::Request.new.body if !args Nginx.echo "failed to get post args." return end Hash[*args.split("&").map{|arg| arg.split("=")}.flatten] args.each do |k, v| Nginx.echo "#{k}:#{v}" end '; } args = r.get_post_args You can access using Nginx::Request#body when post request. I added helper method like ngx_lua
  • 20. p.254 Regular expression Use mrbgem based onigumo. It’s embedded with mruby-core box. https://github.com/mattn/mruby-onig-regexp
  • 21. p.256 Data sharing with request phase location / { mruby_rewrite_handler_code ' Userdata.new.phases = ["rewrite"] Nginx.return Nginx::DECLINED '; mruby_access_handler_code ' Userdata.new.phases << "access" Nginx.return Nginx::DECLINED '; mruby_content_handler_code ' Userdata.new.phases << "content" Userdata.new.phases.each do |phase| Nginx.echo phase end '; } You can share local variables use `mruby-userdata` gem across handlers. You need to return `Nginx::DECLINED` when finished to handler processes. It’s specification of ngx_mruby.
  • 22. p.258 Data sharing with worker processes mruby_init_code ' c = Cache.new :namespace => "writing" c["publisher"] = "技術評論社" c["book"] = "nginx実践入門" '; server { listen 3000; location / { mruby_content_handler_code ' c = Cache.new :namespace => "writing" Nginx.echo "出版社: #{c["publisher"]}" Nginx.echo "書籍名: #{c["book"]}" '; } } You can share variables use `mruby- cache` gem across master and worker processes. `mruby-cache` handles only string keys. It’s limitation.
  • 23. p.260 Processing with non blocking Nothing. Stay tune… Or You can implement it.
  • 24. p.262 Authorization using ngx_mruby set $publickey "nginx"; set $privatekey "mruby"; location / { mruby_content_handler_code ' arg_publickey = Nginx::Var.new.arg_publickey arg_signature = Nginx::Var.new.arg_signature arg_expires = Nginx::Var.new.arg_expires expires = arg_expires.to_i publickey = Nginx::Var.new.publickey privatekey = Nginx::Var.new.privatekey if arg_publickey && arg_publickey.match(publickey) || !arg_expires Nginx.return Nginx::HTTP_FORBIDDEN end
  • 25. plaintext = "#{Nginx::Var.new.request_method}#{Nginx::Var.new.uri}#{arg_expires}#{publickey}" hmac_sha1 = Digest::HMAC.digest(plaintext, privatekey, Digest::SHA1) signature = Base64::encode(hmac_sha1) if expires < Time.now.to_i Nginx.return Nginx::HTTP_FORBIDDEN end if signature == arg_signature Nginx.echo "Sucess" else Nginx.return Nginx::HTTP_FORBIDDEN end '; } p.262 Authorization using ngx_mruby