Upgrade to Pro — share decks privately, control downloads, hide ads and more …

gems, executáveis e configurações

Lucas Mazza
September 18, 2015

gems, executáveis e configurações

Lucas Mazza

September 18, 2015
Tweet

More Decks by Lucas Mazza

Other Decks in Technology

Transcript

  1. gems,
    executáveis e
    configurações

    View full-size slide

  2. https:/
    /sp.femug.com
    https:/
    /github.com/braziljs/femug

    View full-size slide

  3. Funcionalidades

    View full-size slide

  4. Ferramental
    Funcionalidades

    View full-size slide

  5. Ninguém sabe ¯\_(
    Ferramental
    Funcionalidades

    View full-size slide

  6. Ninguém sabe ¯\_(
    Ferramental
    Funcionalidades
    #SCIENCE

    View full-size slide

  7. Ninguém sabe ¯\_(
    Ferramental
    Funcionalidades
    #SCIENCE

    View full-size slide

  8. Frameworks
    Gems
    CLIs
    Provisionadores
    Versionamento
    Servers de build
    Linters e analisadores de sintaxe
    Performance

    View full-size slide

  9. “A carpenter is only
    as good as their tools.”

    View full-size slide

  10. executáveis

    View full-size slide

  11. configurações

    View full-size slide

  12. Você sabe o que a sua aplicação
    está fazendo agora?

    View full-size slide

  13. GET /orders
    SELECT * FROM orders
    WHERE user_id = ?

    View full-size slide

  14. GET /orders
    orders/index.html.erb
    SELECT * FROM orders
    WHERE user_id = ?

    View full-size slide

  15. GET /orders
    GET /oauth/tokens

    View full-size slide

  16. GET /orders
    SELECT * FROM orders
    WHERE user_id = ?
    GET /oauth/tokens

    View full-size slide

  17. GET /orders
    SELECT * FROM orders
    WHERE user_id = ?
    GET /oauth/tokens
    redis GET
    cache/orders/12893128739

    View full-size slide

  18. GET /orders
    SELECT * FROM orders
    WHERE user_id = ?
    GET /oauth/tokens
    redis SADD
    queues:default ‘{job: “…”}’
    redis GET
    cache/orders/12893128739

    View full-size slide

  19. GET /orders
    SELECT * FROM orders
    WHERE user_id = ?
    GET /oauth/tokens
    redis SADD
    queues:default ‘{job: “…”}’
    ☕☕☕
    redis GET
    cache/orders/12893128739

    View full-size slide

  20. GET /orders
    orders/index.html.erb
    SELECT * FROM orders
    WHERE user_id = ?
    GET /oauth/tokens
    redis SADD
    queues:default ‘{job: “…”}’
    ☕☕☕
    redis GET
    cache/orders/12893128739

    View full-size slide

  21. Completed 200 OK in 6791ms (Views: 3.4ms | ActiveRecord: 5.2ms)
    ಠ_ಠ

    View full-size slide

  22. “Reality doesn’t exist until we
    measure it*”
    *at least on a very small scale
    http:/
    /www.sciencealert.com/reality-doesn-t-exist-until-we-measure-it-quantum-experiment-confirms

    View full-size slide

  23. • Quais recursos externos a aplicação depende?

    View full-size slide

  24. • Quais recursos externos a aplicação depende?
    • Quanto tempo/memória é gasto em cada operação?

    View full-size slide

  25. • Quais recursos externos a aplicação depende?
    • Quanto tempo/memória é gasto em cada operação?
    • O que deu certo e o que deu errado?

    View full-size slide

  26. • Logs
    • Métricas

    View full-size slide

  27. • Logs
    • Métricas
    • Detalhes

    View full-size slide

  28. • Logs
    • Métricas
    • Detalhes
    • E mais logs

    View full-size slide

  29. plataformatec/faraday-log-subscriber

    View full-size slide

  30. Article.first
    # Article Load (0.4ms) SELECT * from "articles.*" ...
    Article.where(published: true).count
    # SELECT COUNT(*) from "articles.*" ...

    View full-size slide

  31. APIClient.get('articles/1')
    # ?????
    APIClient.get('articles', published: true)
    # ?????

    View full-size slide

  32. gem 'faraday-log-subscriber'
    gem 'faraday_middleware'
    client = Faraday.new('https://api.github.com') do |builder|
    builder.use :instrumentation
    # ...
    end
    client.get('repos/plataformatec/devise')

    View full-size slide

  33. Faraday HTTP Cache [store] https://api.github.com/user/repos/plataformatec/devise
    Faraday GET [200] (530.0ms) https://api.github.com/user/repos/plataformatec/devise
    Completed 200 OK in 900ms (Views: 339.0ms | Faraday: 530.0ms | ActiveRecord: 11.6ms)

    View full-size slide

  34. Faraday HTTP Cache [store] https://api.github.com/user/repos/plataformatec/devise
    Faraday GET [200] (530.0ms) https://api.github.com/user/repos/plataformatec/devise
    Completed 200 OK in 900ms (Views: 339.0ms | Faraday: 530.0ms | ActiveRecord: 11.6ms)

    View full-size slide

  35. Faraday HTTP Cache [store] https://api.github.com/user/repos/plataformatec/devise
    Faraday GET [200] (530.0ms) https://api.github.com/user/repos/plataformatec/devise
    Completed 200 OK in 900ms (Views: 339.0ms | Faraday: 530.0ms | ActiveRecord: 11.6ms)

    View full-size slide

  36. Faraday HTTP Cache [store] https://api.github.com/user/repos/plataformatec/devise
    Faraday GET [200] (530.0ms) https://api.github.com/user/repos/plataformatec/devise
    Completed 200 OK in 900ms (Views: 339.0ms | Faraday: 530.0ms | ActiveRecord: 11.6ms)

    View full-size slide

  37. ❤❤❤ ActiveSupport::Notifications ❤❤❤

    View full-size slide

  38. module Faraday
    class LogSubscriber < ActiveSupport::LogSubscriber
    def request(event)
    # ...
    end
    attach_to :faraday
    end
    end
    ActiveSupport::Notifications.instrument 'faraday.request' do
    # ...
    end

    View full-size slide

  39. module
    attach_to
    end
    ActiveSupport
    end
    An Instrumented Library in ~ 30 minutes
    http:/
    /www.railstips.org/blog/archives/2013/01/23/an-instrumented-library-in-30-lines/

    View full-size slide

  40. • plugável no seu statsd/graphite/etc

    View full-size slide

  41. • plugável no seu statsd/graphite/etc
    • baixo custo de implementação

    View full-size slide

  42. • plugável no seu statsd/graphite/etc
    • baixo custo de implementação
    • compatível com outros serviços e gems

    View full-size slide

  43. peek-dalli
    peek-gc

    View full-size slide

  44. peek-pg
    peek-dalli
    peek-gc

    View full-size slide

  45. peek-pg
    peek-dalli peek-faraday
    peek-gc

    View full-size slide

  46. peek-pg peek-performance-bar
    peek-dalli peek-faraday
    peek-gc

    View full-size slide

  47. • métricas em desenvolvimento

    View full-size slide

  48. • métricas em desenvolvimento
    • páginas/registros específicos

    View full-size slide

  49. • métricas em desenvolvimento
    • páginas/registros específicos
    • usável em produção

    View full-size slide

  50. • métricas em desenvolvimento
    • páginas/registros específicos
    • usável em produção
    • API pequena para criar plugins

    View full-size slide

  51. schneems/derailed_benchmarks

    View full-size slide

  52. $ derailed bundle:mem
    TOP: 53.043 MiB
    rails/all: 17.7539 MiB
    active_record/railtie: 8.7227 MiB
    active_record: 7.5273 MiB
    arel: 3.2109 MiB
    arel/nodes: 1.2539 MiB
    arel/visitors: 1.1172 MiB
    arel/visitors/to_sql: 0.4648 MiB
    active_record/type: 0.8867 MiB

    View full-size slide

  53. derailed bundle:objects
    Measuring objects created by gems in groups [:default, "production"]
    Total allocated: 14388737 bytes (94532 objects)
    Total retained: 5009330 bytes (14661 objects)
    allocated memory by gem
    -----------------------------------
    4572996 activesupport-4.2.4
    2832576 actionpack-4.2.4
    1370497 therubyracer-0.12.2
    957367 commonjs-0.2.7
    572490 2.2.2/lib
    463779 bundler-1.10.6

    View full-size slide

  54. @schneems - Speed Science
    https:/
    /www.youtube.com/watch?v=m2nj5sUE3hg

    View full-size slide

  55. NewRelic
    AppSignal
    Skylight
    etc

    View full-size slide

  56. configurações

    View full-size slide

  57. # Gemfile
    gem 'rails', '4.2.4'

    View full-size slide

  58. # Gemfile
    gem 'rails', '4.2.4'
    # Gemfile
    gem 'actionmailer', '4.2.4'
    gem 'actionpack', '4.2.4'
    gem 'actionview', '4.2.4'
    gem 'activejob', '4.2.4'
    gem 'activemodel', '4.2.4'
    gem 'activerecord', '4.2.4'
    gem 'activesupport', '4.2.4'
    gem 'railties', '4.2.1'
    gem 'sprockets-rails'

    View full-size slide

  59. # config/application.rb
    require 'rails/all'

    View full-size slide

  60. # config/application.rb
    require 'rails/all'
    # config/application.rb
    require 'active_record/railtie'
    require 'action_controller/railtie'
    require 'action_view/railtie'
    require 'action_mailer/railtie'
    require 'active_job/railtie'
    require 'rails/test_unit/railtie'
    require 'sprockets/railtie'

    View full-size slide

  61. # config/application.rb
    require 'rails/all'
    # config/application.rb
    require 'active_record/railtie'
    require 'action_controller/railtie'
    require 'action_view/railtie'
    require 'action_mailer/railtie'
    require 'active_job/railtie'
    require 'rails/test_unit/railtie'
    require 'sprockets/railtie'

    View full-size slide

  62. A. Sem CSS/JavaScript?

    View full-size slide

  63. A. Sem CSS/JavaScript?
    B. Sem banco relacional?

    View full-size slide

  64. A. Sem CSS/JavaScript?
    B. Sem banco relacional?
    C. Sem background jobs?

    View full-size slide

  65. A. Sem CSS/JavaScript?
    B. Sem banco relacional?
    C. Sem background jobs?
    D. Sem envio de emails?

    View full-size slide

  66. A. Sem CSS/JavaScript?
    B. Sem banco relacional?
    C. Sem background jobs?
    D. Sem envio de emails?
    E. Todos as anteriores.

    View full-size slide

  67. # config/application.rb
    require 'rails'
    require 'action_controller/railtie'
    # Gemfile
    gem 'railties', '4.2.4'
    gem 'actionpack', '4.2.4'

    View full-size slide

  68. ✂ gems e requires

    View full-size slide

  69. ✂ gems e requires
    ✂ Rails.application.config.something

    View full-size slide

  70. ✂ gems e requires
    ✂ Rails.application.config.something
    ✂ ActiveSupport.on_load(:something) { }

    View full-size slide

  71. ✂ gems e requires
    ✂ Rails.application.config.something
    ✂ ActiveSupport.on_load(:something) { }
    ✏ config/initializers/*.rb

    View full-size slide

  72. # config/application.rb
    require 'rails'
    require ‘action_controller/railtie'
    require ‘active_record/railtie’
    # Gemfile
    gem 'railties', '4.2.4'
    gem 'actionpack', '4.2.4'
    gem 'activerecord', '4.2.4'

    View full-size slide

  73. • Reduz o tempo de boot e instalação

    View full-size slide

  74. • Reduz o tempo de boot e instalação
    • Pode reduzir o uso de memória

    View full-size slide

  75. • Reduz o tempo de boot e instalação
    • Pode reduzir o uso de memória
    • Simplifica a árvore de dependências

    View full-size slide

  76. $ ls -1 config/*.yml

    View full-size slide

  77. $ ls -1 config/*.yml
    config/appsignal.yml
    config/database.yml
    config/secrets.yml
    config/sidekiq.yml
    config/skylight.yml
    config/aws.yml
    config/settings.yml
    config/omgwtfbbq.yml

    View full-size slide

  78. bkeepers/dotenv

    View full-size slide

  79. # .env
    DATABASE_URL=''
    SECRET_KEY_BASE=''
    CDN_URL=''
    MEMCACHE_SERVERS='qa.memcache.foo-bar.com:11211'
    REDIS_URL='redis://qa.redis.foo-bar.com:6379/0'
    CACHE_DEFAULT_TTL='300'
    STORAGE_ACCESS_KEY_ID='f95eac983815617738676de5d56fe6eb'
    STORAGE_ACCESS_KEY_KEY='9d2e141a547a7c7f27bb40e836f9f9a2'

    View full-size slide

  80. config.cache_store = :dalli_store,
    ENV['MEMCACHIER_SERVERS'].to_s.split(','),
    {
    username: ENV['MEMCACHIER_USERNAME'],
    password: ENV['MEMCACHIER_PASSWORD'],
    failover: true,
    socket_timeout: 1.5,
    socket_failure_delay: 0.2
    }

    View full-size slide

  81. # config/application.rb
    %w(
    DATABASE_URL
    MEMCACHE_SERVERS
    STORAGE_ACCESS_KEY_ID
    STORAGE_SECRET_ACCESS_KEY
    ).each do |key|
    raise "Missing env variable: #{key}." if ENV[key].blank?
    end

    View full-size slide

  82. • Todas as configurações em um arquivo só

    View full-size slide

  83. • Todas as configurações em um arquivo só
    • Configuração auto documentável

    View full-size slide

  84. • Todas as configurações em um arquivo só
    • Configuração auto documentável
    • Portabilidade entre ambientes

    View full-size slide

  85. executáveis

    View full-size slide

  86. You have already activated activesupport 4.2.4, but your Gemfile
    requires activesupport 4.2.3. Prepending `bundle exec` to your
    command may solve this.
    (╯°□°)╯︵ ┻━┻

    View full-size slide

  87. bundle exec rspec

    View full-size slide

  88. bundle exec rspec

    View full-size slide

  89. bundle binstub rspec-core
    bin/rspec

    View full-size slide

  90. $ ls -1 bin/
    cap*
    foreman*
    puma*
    rails*
    rake*
    sidekiq*
    sidekiqctl*
    whenever*

    View full-size slide

  91. • Como eu instalo “X” ?

    View full-size slide

  92. • Como eu instalo “X” ?
    • Diferença de versões

    View full-size slide

  93. • Como eu instalo “X” ?
    • Diferença de versões
    • Configurações e dependências externas

    View full-size slide

  94. • Como eu instalo “X” ?
    • Diferença de versões
    • Configurações e dependências externas
    • bin/setup && bin/rake = ,

    View full-size slide

  95. ✓ versão do ruby

    View full-size slide

  96. ✓ versão do ruby
    ✓ pg, redis, memcache

    View full-size slide

  97. ✓ versão do ruby
    ✓ pg, redis, memcache
    ✓ arquivos de configuração

    View full-size slide

  98. ✓ versão do ruby
    ✓ pg, redis, memcache
    ✓ arquivos de configuração
    ✓ bundle/bower/npm install

    View full-size slide

  99. ✓ versão do ruby
    ✓ pg, redis, memcache
    ✓ arquivos de configuração
    ✓ bundle/bower/npm install
    ✓ APIs, sandboxes, etc

    View full-size slide

  100. #!/usr/bin/env ruby
    require 'pathname'
    APP_ROOT = Pathname.new File.expand_path('..', __dir__)
    Dir.chdir APP_ROOT do
    puts '== Installing dependencies =='
    system 'gem install bundler --conservative'
    system('bundle check') or system('bundle install')
    puts "\n== Preparing database =="
    system 'ruby bin/rake db:setup'
    system 'RAILS_ENV=test ruby bin/rake db:create'
    puts "\n== Removing old logs and tempfiles =="
    system 'ruby bin/rake log:clear tmp:clear'
    end

    View full-size slide

  101. #!/usr/bin/env bash
    echo "Setting up your environment..."
    # ...
    check_ruby "$(cat .ruby-version)"
    test_dependency "psql" "PostgreSQL" "brew install postgresql"
    test_dependency "redis-cli" "Redis" "brew install redis"
    test_dependency "docker" "docker" "brew cask install dockertoolbox"
    install_bundler
    # ...
    download_phantomjs_2
    bundle_install
    copy_dotenv
    torba_install
    setup_db
    echo "Done!"

    View full-size slide

  102. ✓ vagrant up

    View full-size slide

  103. ¯\_(ツ)_/¯

    View full-size slide

  104. • capistrano

    View full-size slide

  105. • capistrano
    • mina

    View full-size slide

  106. • capistrano
    • mina
    • docker

    View full-size slide

  107. • capistrano
    • mina
    • docker
    • heroku

    View full-size slide

  108. • capistrano
    • mina
    • docker
    • heroku
    • RPM

    View full-size slide

  109. • capistrano
    • mina
    • docker
    • heroku
    • RPM
    • intervenção divina

    View full-size slide

  110. #!/usr/bin/env bash
    # USAGE: deploy [ENVIRONMENT]
    #
    # This program check for all deployment prerequisites before running the
    # Capistrano deployment task.
    # We currently check for the following dependencies:
    #
    # * Current ruby version.
    # * The gem dependencies listed in the Gemfile.
    bundle check &> /dev/null || bundle install --quiet
    exec bin/cap ${1:-"production"} deploy

    View full-size slide

  111. bin/qualquer-coisa

    View full-size slide

  112. • dump/restore de bancos

    View full-size slide

  113. • dump/restore de bancos
    • CRUDs sem UIs

    View full-size slide

  114. • dump/restore de bancos
    • CRUDs sem UIs
    • troubleshooting geral

    View full-size slide

  115. # bin/push-notifications
    #!/usr/bin/env ruby
    require_relative '../config/application'
    require 'thor'
    class PushNotifications < Thor
    # ...
    end
    PushNotifications.start(ARGV)

    View full-size slide

  116. # bin/pull-db
    #!/usr/bin/env bash
    set -e
    timestamp=$(date +%s)
    ssh [email protected] "pg_dump -U DB_USER -W DB_NAME -Fc > ~/dump-$timestamp.dump"
    scp [email protected]:"dump-$timestamp.dump" "/tmp/dump-$timestamp.dump"
    pg_restore --verbose --clean --no-acl --no-owner -h localhost -U \
    $USER -d DB_DEV_NAME "/tmp/dump-$timestamp.dump"

    View full-size slide

  117. https:/
    /github.com/github/scripts-to-rule-them-all

    View full-size slide

  118. Conheça suas
    ferramentas

    View full-size slide

  119. Entenda o contexto
    da sua aplicação

    View full-size slide

  120. Automatize
    trabalho braçal e falhas bestas

    View full-size slide

  121. Faça as ferramentas
    trabalharem para você
    E não o contrário

    View full-size slide

  122. ❄ Não pense que o seu
    projeto é um floco de neve ❄

    View full-size slide

  123. “Certeza que alguém já resolveu
    essa #^%#$&@!^”
    Lucas Mazza
    Quase todo santo dia

    View full-size slide

  124. Gostamos mais de ter escolhas
    do que ter que escolher

    View full-size slide

  125. ➖ tempo em escolhas
    ➕ tempo desenvolvendo software

    View full-size slide

  126. Esse código / projeto / módulo / repositório
    não é
    para você

    View full-size slide

  127. Converse com o seu time

    View full-size slide

  128. gem install trololol

    View full-size slide

  129. gem install trololol


    View full-size slide

  130. Conhecimento & informação

    View full-size slide

  131. Conhecimento & informação
    Disseminação & educação

    View full-size slide

  132. Conhecimento & informação
    Disseminação & educação
    Uso & benefícios

    View full-size slide

  133. Conhecimento & informação
    Disseminação & educação
    Uso & benefícios
    ((╯°□°)╯︵ ┻━┻ e voltar ao passo 1)

    View full-size slide

  134. Obrigado!
    @lucasmazza

    View full-size slide