Skip to content

Commit

Permalink
Backend : building release with distillery
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthieu Segret committed Jul 3, 2018
1 parent cf0e336 commit 6352b67
Show file tree
Hide file tree
Showing 12 changed files with 160 additions and 49 deletions.
23 changes: 11 additions & 12 deletions config/prod.exs
Expand Up @@ -15,23 +15,20 @@ use Mix.Config
# which you typically run after static files are built.
config :yummy, YummyWeb.Endpoint,
load_from_system_env: true,
http: [port: {:system, "PORT"}, compress: true],
url: [scheme: "https", host: "yummy-phoenix-graphql.herokuapp.com", port: 443],
force_ssl: [rewrite_on: [:x_forwarded_proto]],
http: [port: {:system, "PORT"}],
url: [host: "${HOST}", port: {:system, "PORT"}],
cache_static_manifest: "priv/static/cache_manifest.json",
secret_key_base: Map.fetch!(System.get_env(), "SECRET_KEY_BASE")
secret_key_base: "${SECRET_KEY_BASE}",
version: Mix.Project.config()[:version],
server: true

# Do not print debug messages in production
config :logger, level: :info

# Configures Bamboo
config :yummy, Yummy.Mailer,
adapter: Bamboo.SendGridAdapter,
api_key: System.get_env("SENDGRID_API_KEY")

config :rollbax,
access_token: {:system, "ROLLBAR_ACCESS_TOKEN"},
environment: "production"
api_key: "${SENDGRID_API_KEY}"

config :ex_aws,
access_key_id: [{:system, "S3_KEY"}, :instance_role],
Expand All @@ -46,6 +43,8 @@ config :arc,
# Configure your database
config :yummy, Yummy.Repo,
adapter: Ecto.Adapters.Postgres,
url: System.get_env("DATABASE_URL"),
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
ssl: true
username: "${POSTGRES_USER}",
password: "${POSTGRES_PASSWORD}",
database: "${POSTGRES_DB}",
hostname: "${POSTGRES_HOST}",
pool_size: "${DB_POOL_SIZE}"
7 changes: 1 addition & 6 deletions config/test.exs
Expand Up @@ -3,7 +3,7 @@ use Mix.Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :yummy, YummyWeb.Endpoint,
http: [port: System.get_env("SERVER_PORT") || 4000],
http: [port: System.get_env("PORT") || 4000],
server: true

config :yummy, :sql_sandbox, true
Expand All @@ -28,11 +28,6 @@ config :yummy, Yummy.Repo,
# Configures Bamboo
config :yummy, Yummy.Mailer, adapter: Bamboo.TestAdapter

config :rollbax,
access_token: "",
environment: "test",
enabled: false

config :ex_aws,
access_key_id: ["fake", :instance_role],
secret_access_key: ["fake", :instance_role],
Expand Down
83 changes: 83 additions & 0 deletions lib/yummy/release_tasks.ex
@@ -0,0 +1,83 @@
defmodule Yummy.ReleaseTasks do
@start_apps [
:crypto,
:ssl,
:postgrex,
:ecto,
:ex_aws,
:arc,
:timex
]

def myapp, do: :yummy

def repos, do: Application.get_env(myapp(), :ecto_repos, [])

def seed do
# Setup the Repo(s) for myapp
setup()

# Run seed script
Enum.each(repos(), &run_seeds_for/1)

# Signal shutdown
IO.puts("Loading seeds success!")
:init.stop()
end

def migrate do
# Setup the Repo(s) for myapp
setup()

# Run migrations
Enum.each(repos(), &run_migrations_for/1)

# Signal shutdown
IO.puts("Migrating success!")
:init.stop()
end

def priv_dir(app), do: "#{:code.priv_dir(app)}"

defp setup do
me = myapp()

IO.puts("Loading #{me}..")
# Load the code for myapp, but don't start it
:ok = Application.load(me)

IO.puts("Starting dependencies..")
# Start apps necessary for executing migrations
Enum.each(@start_apps, &Application.ensure_all_started/1)

# Start the Repo(s) for myapp
IO.puts("Starting repos..")
Enum.each(repos(), & &1.start_link(pool_size: 1))
end

defp run_migrations_for(repo) do
app = Keyword.get(repo.config, :otp_app)
IO.puts("Running migrations for #{app}")
Ecto.Migrator.run(repo, migrations_path(repo), :up, all: true)
end

def run_seeds_for(repo) do
# Run the seed script if it exists
seed_script = seeds_path(repo)

if File.exists?(seed_script) do
IO.puts("Running seed script..")
Code.eval_file(seed_script)
end
end

def migrations_path(repo), do: priv_path_for(repo, "migrations")

def seeds_path(repo), do: priv_path_for(repo, "seeds.exs")

def priv_path_for(repo, filename) do
app = Keyword.get(repo.config, :otp_app)
repo_underscore = repo |> Module.split() |> List.last() |> Macro.underscore()
Path.join([priv_dir(app), repo_underscore, filename])
end
end
2 changes: 1 addition & 1 deletion lib/yummy_web/endpoint.ex
Expand Up @@ -51,7 +51,7 @@ defmodule YummyWeb.Endpoint do
"""
def init(_key, config) do
if config[:load_from_system_env] do
port = System.get_env("SERVER_PORT") || raise "expected the PORT environment variable to be set"
port = System.get_env("PORT") || raise "expected the PORT environment variable to be set"
{:ok, Keyword.put(config, :http, [:inet6, port: port])}
else
{:ok, config}
Expand Down
19 changes: 0 additions & 19 deletions lib/yummy_web/router.ex
@@ -1,6 +1,5 @@
defmodule YummyWeb.Router do
use YummyWeb, :router
use Plug.ErrorHandler

pipeline :api do
plug(:accepts, ["json"])
Expand All @@ -17,22 +16,4 @@ defmodule YummyWeb.Router do
forward("/emails", Bamboo.SentEmailViewerPlug)
end
end

defp handle_errors(_conn, %{reason: %Ecto.NoResultsError{}}), do: true
defp handle_errors(_conn, %{reason: %Phoenix.Router.NoRouteError{}}), do: true

defp handle_errors(conn, %{kind: kind, reason: reason, stack: stacktrace}) do
headers = Enum.into(conn.req_headers, %{})
reason = Map.delete(reason, :assigns)

Rollbax.report(kind, reason, stacktrace, %{}, %{
"request" => %{
"url" => "#{conn.scheme}://#{conn.host}#{conn.request_path}",
"user_ip" => Map.get(headers, "x-forwarded-for"),
"method" => conn.method,
"headers" => headers,
"params" => conn.params
}
})
end
end
4 changes: 1 addition & 3 deletions mix.exs
Expand Up @@ -60,6 +60,7 @@ defmodule Yummy.Mixfile do
{:secure_random, "~> 0.5"},
{:sweet_xml, "~> 0.6"},
{:timex, "~> 3.1"},
{:distillery, "~> 1.5", runtime: false},

# Mails
{:bamboo, github: "thoughtbot/bamboo"},
Expand All @@ -69,9 +70,6 @@ defmodule Yummy.Mixfile do
{:arc_ecto, "~> 0.8.0"},
{:ex_aws, "~> 1.1.3"},

# Errors
{:rollbax, "~> 0.8.2"},

# Dev
{:credo, "~> 0.9.3", only: :dev, runtime: false},

Expand Down
2 changes: 1 addition & 1 deletion mix.lock
Expand Up @@ -18,6 +18,7 @@
"dataloader": {:hex, :dataloader, "1.0.2", "90e788dc507bb80f7281f2d3d6c6e4bb1d18709c8351392365b6a0950bfe9f7d", [:mix], [{:ecto, ">= 0.0.0", [hex: :ecto, repo: "hexpm", optional: true]}], "hexpm"},
"db_connection": {:hex, :db_connection, "1.1.3", "89b30ca1ef0a3b469b1c779579590688561d586694a3ce8792985d4d7e575a61", [:mix], [{:connection, "~> 1.0.2", [hex: :connection, repo: "hexpm", optional: false]}, {:poolboy, "~> 1.5", [hex: :poolboy, repo: "hexpm", optional: true]}, {:sbroker, "~> 1.0", [hex: :sbroker, repo: "hexpm", optional: true]}], "hexpm"},
"decimal": {:hex, :decimal, "1.5.0", "b0433a36d0e2430e3d50291b1c65f53c37d56f83665b43d79963684865beab68", [:mix], [], "hexpm"},
"distillery": {:hex, :distillery, "1.5.3", "b2f4fc34ec71ab4f1202a796f9290e068883b042319aa8c9aa45377ecac8597a", [:mix], [], "hexpm"},
"ecto": {:hex, :ecto, "2.2.10", "e7366dc82f48f8dd78fcbf3ab50985ceeb11cb3dc93435147c6e13f2cda0992e", [:mix], [{:db_connection, "~> 1.1", [hex: :db_connection, repo: "hexpm", optional: true]}, {:decimal, "~> 1.2", [hex: :decimal, repo: "hexpm", optional: false]}, {:mariaex, "~> 0.8.0", [hex: :mariaex, repo: "hexpm", optional: true]}, {:poison, "~> 2.2 or ~> 3.0", [hex: :poison, repo: "hexpm", optional: true]}, {:poolboy, "~> 1.5", [hex: :poolboy, repo: "hexpm", optional: false]}, {:postgrex, "~> 0.13.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:sbroker, "~> 1.0", [hex: :sbroker, repo: "hexpm", optional: true]}], "hexpm"},
"elixir_make": {:hex, :elixir_make, "0.4.1", "6628b86053190a80b9072382bb9756a6c78624f208ec0ff22cb94c8977d80060", [:mix], [], "hexpm"},
"ex_aws": {:hex, :ex_aws, "1.1.5", "789173f385934f7e27f9ef36692a6c5f7dde06fd6e6f64d4cd92cda613d34bf9", [:mix], [{:configparser_ex, "~> 0.2.1", [hex: :configparser_ex, repo: "hexpm", optional: true]}, {:hackney, "1.6.3 or 1.6.5 or 1.7.1 or 1.8.6 or ~> 1.9", [hex: :hackney, repo: "hexpm", optional: true]}, {:jsx, "~> 2.8", [hex: :jsx, repo: "hexpm", optional: true]}, {:poison, ">= 1.2.0", [hex: :poison, repo: "hexpm", optional: true]}, {:sweet_xml, "~> 0.6", [hex: :sweet_xml, repo: "hexpm", optional: true]}, {:xml_builder, "~> 0.1.0", [hex: :xml_builder, repo: "hexpm", optional: true]}], "hexpm"},
Expand All @@ -42,7 +43,6 @@
"poolboy": {:hex, :poolboy, "1.5.1", "6b46163901cfd0a1b43d692657ed9d7e599853b3b21b95ae5ae0a777cf9b6ca8", [:rebar], [], "hexpm"},
"postgrex": {:hex, :postgrex, "0.13.5", "3d931aba29363e1443da167a4b12f06dcd171103c424de15e5f3fc2ba3e6d9c5", [:mix], [{:connection, "~> 1.0", [hex: :connection, repo: "hexpm", optional: false]}, {:db_connection, "~> 1.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.0", [hex: :decimal, repo: "hexpm", optional: false]}], "hexpm"},
"ranch": {:hex, :ranch, "1.3.2", "e4965a144dc9fbe70e5c077c65e73c57165416a901bd02ea899cfd95aa890986", [:rebar3], [], "hexpm"},
"rollbax": {:hex, :rollbax, "0.8.2", "204a47a83fe32745def19ea0307b297395c00315fb85f30dfda04d5009b5ecb9", [:mix], [{:hackney, "~> 1.1", [hex: :hackney, repo: "hexpm", optional: false]}, {:poison, "~> 1.4 or ~> 2.0 or ~> 3.0", [hex: :poison, repo: "hexpm", optional: false]}], "hexpm"},
"secure_random": {:hex, :secure_random, "0.5.1", "c5532b37c89d175c328f5196a0c2a5680b15ebce3e654da37129a9fe40ebf51b", [:mix], [], "hexpm"},
"ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.1", "28a4d65b7f59893bc2c7de786dec1e1555bd742d336043fe644ae956c3497fbe", [:make, :rebar], [], "hexpm"},
"sweet_xml": {:hex, :sweet_xml, "0.6.5", "dd9cde443212b505d1b5f9758feb2000e66a14d3c449f04c572f3048c66e6697", [:mix], [], "hexpm"},
Expand Down
18 changes: 11 additions & 7 deletions priv/repo/seeds.exs
Expand Up @@ -17,8 +17,12 @@ alias Yummy.Accounts.User
alias Yummy.Recipes
alias Yummy.Recipes.Recipe

images_path = Yummy.ReleaseTasks.priv_path_for(Yummy.Repo, "images")

User |> Repo.delete_all()
{:ok, user} = Accounts.create_user(%{name: "Jose", email: "jose@yummy.com", password: "password", password_confirmation: "password"})
{:ok, unconfirmed_user} = Accounts.create_user(%{name: "Jose", email: "jose@yummy.com", password: "password", password_confirmation: "password"})
{:ok, code, user_with_code} = Yummy.Confirmations.generate_confirmation_code(unconfirmed_user)
{:ok, user} = Yummy.Confirmations.confirm_account(user_with_code, code)

Recipe |> Repo.delete_all()

Expand Down Expand Up @@ -54,7 +58,7 @@ Recipes.create(user, %{
#### Etape 6
Un peu avant de servir, répartir le coulis et décorer avec les fruits réservés.],
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "panna-cotta.jpg", path: "priv/repo/images/panna-cotta.jpg"}
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "panna-cotta.jpg", path: Path.join([images_path, "panna-cotta.jpg"])}
})

Recipes.create(user, %{
Expand Down Expand Up @@ -83,7 +87,7 @@ Recipes.create(user, %{
#### Etape 4
Laisser tiédir la pâte précuite 10 mn. Etendre la confiture d'abricots, poser dessus les figues, face coupée dessous. Saupoudrer de sucre glace, passer au four 230 °C 7 à 8 mn pour caraméliser légèrement le dessus des figues.],
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "tarte-figues.jpg", path: "priv/repo/images/tarte-figues.jpg"}
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "tarte-figues.jpg", path: Path.join([images_path, "tarte-figues.jpg"])}
})

Recipes.create(user, %{
Expand Down Expand Up @@ -124,7 +128,7 @@ Recipes.create(user, %{
#### Etape 6
Quand le clafoutis est cuit, sortir le plat du four et laisser tiédir quelques minutes avant de déguster.],
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "clafoutis.jpg", path: "priv/repo/images/clafoutis.jpg"}
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "clafoutis.jpg", path: Path.join([images_path, "clafoutis.jpg"])}
})

Recipes.create(user, %{
Expand Down Expand Up @@ -158,7 +162,7 @@ Recipes.create(user, %{
#### Etape 7
Il est possible de saupoudrer de pistaches, de noix, de noisettes ou d'amandes concassées avant d'enfourner.],
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "feuilletee.jpg", path: "priv/repo/images/feuilletee.jpg"}
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "feuilletee.jpg", path: Path.join([images_path, "feuilletee.jpg"])}
})

Recipes.create(user, %{
Expand Down Expand Up @@ -187,7 +191,7 @@ Recipes.create(user, %{
#### Etape 4
Servir tiède ou froid.],
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "pain-courgettes.jpg", path: "priv/repo/images/pain-courgettes.jpg"}
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "pain-courgettes.jpg", path: Path.join([images_path, "pain-courgettes.jpg"])}
})

Recipes.create(user, %{
Expand Down Expand Up @@ -220,5 +224,5 @@ Recipes.create(user, %{
#### Etape 5
Faire cuire à 180 degrés pendant 45 min.
J'ajoute mon grain de sel.],
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "cake.jpg", path: "priv/repo/images/cake.jpg"}
image_url: %Plug.Upload{content_type: "image/jpeg", filename: "cake.jpg", path: Path.join([images_path, "cake.jpg"])}
})
4 changes: 4 additions & 0 deletions rel/commands/migrate.sh
@@ -0,0 +1,4 @@
#!/usr/bin/env sh

# running database migration
$RELEASE_ROOT_DIR/bin/yummy command Elixir.Yummy.ReleaseTasks migrate
4 changes: 4 additions & 0 deletions rel/commands/seeds.sh
@@ -0,0 +1,4 @@
#!/usr/bin/env sh

# loading seeds
$RELEASE_ROOT_DIR/bin/yummy command Elixir.Yummy.ReleaseTasks seed
35 changes: 35 additions & 0 deletions rel/config.exs
@@ -0,0 +1,35 @@
# Import all plugins from `rel/plugins`
# They can then be used by adding `plugin MyPlugin` to
# either an environment, or release definition, where
# `MyPlugin` is the name of the plugin module.
Path.join(["rel", "plugins", "*.exs"])
|> Path.wildcard()
|> Enum.map(&Code.eval_file(&1))

use Mix.Releases.Config,
default_release: :default,
default_environment: :prod

environment :prod do
set(include_erts: true)
set(include_src: false)
set(cookie: :";W^JBe|r10%%>?@&Y8XgVeZwH9kJ?w?bO/bl1!gjiD(P.<;2IkIz,[o<Mox:<.qg")

set(
commands: [
migrate: "rel/commands/migrate.sh",
seeds: "rel/commands/seeds.sh"
]
)
end

release :yummy do
set(version: current_version(:yummy))
set(vm_args: "rel/vm.args")

set(
applications: [
:runtime_tools
]
)
end
8 changes: 8 additions & 0 deletions rel/vm.args
@@ -0,0 +1,8 @@
## Name of the node
-name ${NODE_NAME}

## Cookie for distributed erlang
-setcookie ${NODE_COOKIE}

## App Settings
-yummy port ${PORT}

0 comments on commit 6352b67

Please sign in to comment.