From e7ff68633e61b50f209033e206fdb0ddc198bcd8 Mon Sep 17 00:00:00 2001 From: Oleg Pervushin Date: Mon, 15 Apr 2019 21:15:56 +0400 Subject: [PATCH] completed commit --- .docker/.DS_Store | Bin 0 -> 6148 bytes .docker/postgresql.conf | 661 ++++++++++++++++++ .dockerignore | 13 + .gitignore | 1 + Dockerfile | 46 ++ Gemfile | 11 + Gemfile.lock | 26 + app/controllers/trips_controller.rb | 5 +- app/jobs/application_job.rb | 2 - app/models/bus.rb | 3 +- app/models/buses_service.rb | 4 + app/models/service.rb | 3 +- app/services/entities_processing.rb | 97 +++ app/views/trips/_delimiter.html.erb | 1 - app/views/trips/_service.html.erb | 1 - app/views/trips/_services.html.erb | 6 - app/views/trips/_trip.html.erb | 26 +- app/views/trips/index.html.erb | 10 +- bin/benchmarking/asymptotics | 34 + bin/benchmarking/memory-profiler | 24 + bin/benchmarking/ruby-prof-cpu | 22 + bin/benchmarking/ruby-prof-memory | 23 + bin/install-railsexpress | 17 + bin/startup | 18 + config/application.rb | 1 + config/database.yml | 6 +- config/environments/development.rb | 9 + .../20190415105016_add_index_to_trip.rb | 7 + db/migrate/20190415105125_add_index_to_bus.rb | 7 + ...20190415105221_add_index_to_bus_service.rb | 7 + db/schema.rb | 6 +- docker-compose.yml | 60 ++ docker-entrypoint.sh | 6 + lib/tasks/utils.rake | 31 +- 34 files changed, 1131 insertions(+), 63 deletions(-) create mode 100644 .docker/.DS_Store create mode 100644 .docker/postgresql.conf create mode 100644 .dockerignore create mode 100644 Dockerfile delete mode 100644 app/jobs/application_job.rb create mode 100644 app/models/buses_service.rb create mode 100644 app/services/entities_processing.rb delete mode 100644 app/views/trips/_delimiter.html.erb delete mode 100644 app/views/trips/_service.html.erb delete mode 100644 app/views/trips/_services.html.erb create mode 100755 bin/benchmarking/asymptotics create mode 100755 bin/benchmarking/memory-profiler create mode 100755 bin/benchmarking/ruby-prof-cpu create mode 100755 bin/benchmarking/ruby-prof-memory create mode 100755 bin/install-railsexpress create mode 100755 bin/startup create mode 100644 db/migrate/20190415105016_add_index_to_trip.rb create mode 100644 db/migrate/20190415105125_add_index_to_bus.rb create mode 100644 db/migrate/20190415105221_add_index_to_bus_service.rb create mode 100644 docker-compose.yml create mode 100755 docker-entrypoint.sh diff --git a/.docker/.DS_Store b/.docker/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..2b58f3382b40a33bee55055174be1067fbe813d5 GIT binary patch literal 6148 zcmeHKO-sW-5PhQsiyqpW9{1>};6I3=f{Hi)fTS&W2nN*N^Uvd(4-3(pi^xpad6W6r zWFKTV13>Ei_6Ar2m~$wK8WW=K$8k#o_Kiw zhql`^ZPzePa^#YDJ($=s&amMs-+AruhR<;}7R*_A_At=?k-h!cv`yEwHdCr(AQ?yo zl7VF4xD4>jR+(QorcMTufn?yofbI{4L$M0%9c}BNvKD|iquYeG_7YlC0;|B@kr9e` zDbY(MS`6`W`b*?hfxV-bL!$YRc=C7iBKCC7Uo0I`Ii^kql7TS;+WS(Ldj8+>lbLMt zEhSYlkPQ4+24uE=Ue{b*oUOmssb_8Bc;Qgdyj~3o?a@yFZ*(8IvY^L{+RUp0dqxQ9|0pIRWfh{2EG7U4K14h literal 0 HcmV?d00001 diff --git a/.docker/postgresql.conf b/.docker/postgresql.conf new file mode 100644 index 0000000..2f66bf2 --- /dev/null +++ b/.docker/postgresql.conf @@ -0,0 +1,661 @@ +# ----------------------------- +# PostgreSQL configuration file +# ----------------------------- +# +# This file consists of lines of the form: +# +# name = value +# +# (The "=" is optional.) Whitespace may be used. Comments are introduced with +# "#" anywhere on a line. The complete list of parameter names and allowed +# values can be found in the PostgreSQL documentation. +# +# The commented-out settings shown in this file represent the default values. +# Re-commenting a setting is NOT sufficient to revert it to the default value; +# you need to reload the server. +# +# This file is read on server startup and when the server receives a SIGHUP +# signal. If you edit the file on a running system, you have to SIGHUP the +# server for the changes to take effect, run "pg_ctl reload", or execute +# "SELECT pg_reload_conf()". Some parameters, which are marked below, +# require a server shutdown and restart to take effect. +# +# Any parameter can also be given as a command-line option to the server, e.g., +# "postgres -c log_connections=on". Some parameters can be changed at run time +# with the "SET" SQL command. +# +# Memory units: kB = kilobytes Time units: ms = milliseconds +# MB = megabytes s = seconds +# GB = gigabytes min = minutes +# TB = terabytes h = hours +# d = days + + +#------------------------------------------------------------------------------ +# FILE LOCATIONS +#------------------------------------------------------------------------------ + +# The default values of these variables are driven from the -D command-line +# option or PGDATA environment variable, represented here as ConfigDir. + +#data_directory = 'ConfigDir' # use data in another directory + # (change requires restart) +#hba_file = 'ConfigDir/pg_hba.conf' # host-based authentication file + # (change requires restart) +#ident_file = 'ConfigDir/pg_ident.conf' # ident configuration file + # (change requires restart) + +# If external_pid_file is not explicitly set, no extra PID file is written. +#external_pid_file = '' # write an extra PID file + # (change requires restart) + + +#------------------------------------------------------------------------------ +# CONNECTIONS AND AUTHENTICATION +#------------------------------------------------------------------------------ + +# - Connection Settings - + +listen_addresses = '*' + # comma-separated list of addresses; + # defaults to 'localhost'; use '*' for all + # (change requires restart) +#port = 5432 # (change requires restart) +max_connections = 100 # (change requires restart) +#superuser_reserved_connections = 3 # (change requires restart) +#unix_socket_directories = '/var/run/postgresql' # comma-separated list of directories + # (change requires restart) +#unix_socket_group = '' # (change requires restart) +#unix_socket_permissions = 0777 # begin with 0 to use octal notation + # (change requires restart) +#bonjour = off # advertise server via Bonjour + # (change requires restart) +#bonjour_name = '' # defaults to the computer name + # (change requires restart) + +# - Security and Authentication - + +#authentication_timeout = 1min # 1s-600s +#ssl = off +#ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers +#ssl_prefer_server_ciphers = on +#ssl_ecdh_curve = 'prime256v1' +#ssl_dh_params_file = '' +#ssl_cert_file = 'server.crt' +#ssl_key_file = 'server.key' +#ssl_ca_file = '' +#ssl_crl_file = '' +#password_encryption = md5 # md5 or scram-sha-256 +#db_user_namespace = off +#row_security = on + +# GSSAPI using Kerberos +#krb_server_keyfile = '' +#krb_caseins_users = off + +# - TCP Keepalives - +# see "man 7 tcp" for details + +#tcp_keepalives_idle = 0 # TCP_KEEPIDLE, in seconds; + # 0 selects the system default +#tcp_keepalives_interval = 0 # TCP_KEEPINTVL, in seconds; + # 0 selects the system default +#tcp_keepalives_count = 0 # TCP_KEEPCNT; + # 0 selects the system default + + +#------------------------------------------------------------------------------ +# RESOURCE USAGE (except WAL) +#------------------------------------------------------------------------------ + +# - Memory - + +shared_buffers = 128MB # min 128kB + # (change requires restart) +#huge_pages = try # on, off, or try + # (change requires restart) +#temp_buffers = 8MB # min 800kB +#max_prepared_transactions = 0 # zero disables the feature + # (change requires restart) +# Caution: it is not advisable to set max_prepared_transactions nonzero unless +# you actively intend to use prepared transactions. +work_mem = 4MB # min 64kB +maintenance_work_mem = 64MB # min 1MB +#replacement_sort_tuples = 150000 # limits use of replacement selection sort +#autovacuum_work_mem = -1 # min 1MB, or -1 to use maintenance_work_mem +#max_stack_depth = 2MB # min 100kB +dynamic_shared_memory_type = posix # the default is the first option + # supported by the operating system: + # posix + # sysv + # windows + # mmap + # use none to disable dynamic shared memory + # (change requires restart) + +# - Disk - + +#temp_file_limit = -1 # limits per-process temp file space + # in kB, or -1 for no limit + +# - Kernel Resource Usage - + +#max_files_per_process = 1000 # min 25 + # (change requires restart) +#shared_preload_libraries = '' # (change requires restart) + +# - Cost-Based Vacuum Delay - + +#vacuum_cost_delay = 0 # 0-100 milliseconds +#vacuum_cost_page_hit = 1 # 0-10000 credits +#vacuum_cost_page_miss = 10 # 0-10000 credits +#vacuum_cost_page_dirty = 20 # 0-10000 credits +#vacuum_cost_limit = 200 # 1-10000 credits + +# - Background Writer - + +#bgwriter_delay = 200ms # 10-10000ms between rounds +#bgwriter_lru_maxpages = 100 # 0-1000 max buffers written/round +#bgwriter_lru_multiplier = 2.0 # 0-10.0 multiplier on buffers scanned/round +#bgwriter_flush_after = 512kB # measured in pages, 0 disables + +# - Asynchronous Behavior - + +#effective_io_concurrency = 1 # 1-1000; 0 disables prefetching +#max_worker_processes = 8 # (change requires restart) +#max_parallel_workers_per_gather = 2 # taken from max_parallel_workers +#max_parallel_workers = 8 # maximum number of max_worker_processes that + # can be used in parallel queries +#old_snapshot_threshold = -1 # 1min-60d; -1 disables; 0 is immediate + # (change requires restart) +#backend_flush_after = 0 # measured in pages, 0 disables + + +#------------------------------------------------------------------------------ +# WRITE AHEAD LOG +#------------------------------------------------------------------------------ + +# - Settings - + +#wal_level = replica # minimal, replica, or logical + # (change requires restart) +#fsync = on # flush data to disk for crash safety + # (turning this off can cause + # unrecoverable data corruption) +#synchronous_commit = on # synchronization level; + # off, local, remote_write, remote_apply, or on +#wal_sync_method = fsync # the default is the first option + # supported by the operating system: + # open_datasync + # fdatasync (default on Linux) + # fsync + # fsync_writethrough + # open_sync +#full_page_writes = on # recover from partial page writes +#wal_compression = off # enable compression of full-page writes +#wal_log_hints = off # also do full page writes of non-critical updates + # (change requires restart) +wal_buffers = 4MB # min 32kB, -1 sets based on shared_buffers + # (change requires restart) +#wal_writer_delay = 200ms # 1-10000 milliseconds +#wal_writer_flush_after = 1MB # measured in pages, 0 disables + +#commit_delay = 0 # range 0-100000, in microseconds +#commit_siblings = 5 # range 1-1000 + +# - Checkpoints - + +#checkpoint_timeout = 5min # range 30s-1d +max_wal_size = 1GB +min_wal_size = 80MB +checkpoint_completion_target = 0.5 # checkpoint target duration, 0.0 - 1.0 +#checkpoint_flush_after = 256kB # measured in pages, 0 disables +#checkpoint_warning = 30s # 0 disables + +# - Archiving - + +#archive_mode = off # enables archiving; off, on, or always + # (change requires restart) +#archive_command = '' # command to use to archive a logfile segment + # placeholders: %p = path of file to archive + # %f = file name only + # e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f' +#archive_timeout = 0 # force a logfile segment switch after this + # number of seconds; 0 disables + + +#------------------------------------------------------------------------------ +# REPLICATION +#------------------------------------------------------------------------------ + +# - Sending Server(s) - + +# Set these on the master and on any standby that will send replication data. + +#max_wal_senders = 10 # max number of walsender processes + # (change requires restart) +#wal_keep_segments = 0 # in logfile segments, 16MB each; 0 disables +#wal_sender_timeout = 60s # in milliseconds; 0 disables + +#max_replication_slots = 10 # max number of replication slots + # (change requires restart) +#track_commit_timestamp = off # collect timestamp of transaction commit + # (change requires restart) + +# - Master Server - + +# These settings are ignored on a standby server. + +#synchronous_standby_names = '' # standby servers that provide sync rep + # method to choose sync standbys, number of sync standbys, + # and comma-separated list of application_name + # from standby(s); '*' = all +#vacuum_defer_cleanup_age = 0 # number of xacts by which cleanup is delayed + +# - Standby Servers - + +# These settings are ignored on a master server. + +#hot_standby = on # "off" disallows queries during recovery + # (change requires restart) +#max_standby_archive_delay = 30s # max delay before canceling queries + # when reading WAL from archive; + # -1 allows indefinite delay +#max_standby_streaming_delay = 30s # max delay before canceling queries + # when reading streaming WAL; + # -1 allows indefinite delay +#wal_receiver_status_interval = 10s # send replies at least this often + # 0 disables +#hot_standby_feedback = off # send info from standby to prevent + # query conflicts +#wal_receiver_timeout = 60s # time that receiver waits for + # communication from master + # in milliseconds; 0 disables +#wal_retrieve_retry_interval = 5s # time to wait before retrying to + # retrieve WAL after a failed attempt + +# - Subscribers - + +# These settings are ignored on a publisher. + +#max_logical_replication_workers = 4 # taken from max_worker_processes + # (change requires restart) +#max_sync_workers_per_subscription = 2 # taken from max_logical_replication_workers + + +#------------------------------------------------------------------------------ +# QUERY TUNING +#------------------------------------------------------------------------------ + +# - Planner Method Configuration - + +#enable_bitmapscan = on +#enable_hashagg = on +#enable_hashjoin = on +#enable_indexscan = on +#enable_indexonlyscan = on +#enable_material = on +#enable_mergejoin = on +#enable_nestloop = on +#enable_seqscan = on +#enable_sort = on +#enable_tidscan = on + +# - Planner Cost Constants - + +#seq_page_cost = 1.0 # measured on an arbitrary scale +#random_page_cost = 4.0 # same scale as above +#cpu_tuple_cost = 0.01 # same scale as above +#cpu_index_tuple_cost = 0.005 # same scale as above +#cpu_operator_cost = 0.0025 # same scale as above +#parallel_tuple_cost = 0.1 # same scale as above +#parallel_setup_cost = 1000.0 # same scale as above +#min_parallel_table_scan_size = 8MB +#min_parallel_index_scan_size = 512kB +effective_cache_size = 4GB + +# - Genetic Query Optimizer - + +#geqo = on +#geqo_threshold = 12 +#geqo_effort = 5 # range 1-10 +#geqo_pool_size = 0 # selects default based on effort +#geqo_generations = 0 # selects default based on effort +#geqo_selection_bias = 2.0 # range 1.5-2.0 +#geqo_seed = 0.0 # range 0.0-1.0 + +# - Other Planner Options - + +default_statistics_target = 100 # range 1-10000 +#constraint_exclusion = partition # on, off, or partition +#cursor_tuple_fraction = 0.1 # range 0.0-1.0 +#from_collapse_limit = 8 +#join_collapse_limit = 8 # 1 disables collapsing of explicit + # JOIN clauses +#force_parallel_mode = off + + +#------------------------------------------------------------------------------ +# ERROR REPORTING AND LOGGING +#------------------------------------------------------------------------------ + +# - Where to Log - + +#log_destination = 'stderr' # Valid values are combinations of + # stderr, csvlog, syslog, and eventlog, + # depending on platform. csvlog + # requires logging_collector to be on. + +# This is used when logging to stderr: +#logging_collector = off # Enable capturing of stderr and csvlog + # into log files. Required to be on for + # csvlogs. + # (change requires restart) + +# These are only used if logging_collector is on: +#log_directory = 'log' # directory where log files are written, + # can be absolute or relative to PGDATA +#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' # log file name pattern, + # can include strftime() escapes +#log_file_mode = 0600 # creation mode for log files, + # begin with 0 to use octal notation +#log_truncate_on_rotation = off # If on, an existing log file with the + # same name as the new log file will be + # truncated rather than appended to. + # But such truncation only occurs on + # time-driven rotation, not on restarts + # or size-driven rotation. Default is + # off, meaning append to existing files + # in all cases. +#log_rotation_age = 1d # Automatic rotation of logfiles will + # happen after that time. 0 disables. +#log_rotation_size = 10MB # Automatic rotation of logfiles will + # happen after that much log output. + # 0 disables. + +# These are relevant when logging to syslog: +#syslog_facility = 'LOCAL0' +#syslog_ident = 'postgres' +#syslog_sequence_numbers = on +#syslog_split_messages = on + +# This is only relevant when logging to eventlog (win32): +# (change requires restart) +#event_source = 'PostgreSQL' + +# - When to Log - + +#client_min_messages = notice # values in order of decreasing detail: + # debug5 + # debug4 + # debug3 + # debug2 + # debug1 + # log + # notice + # warning + # error + +#log_min_messages = warning # values in order of decreasing detail: + # debug5 + # debug4 + # debug3 + # debug2 + # debug1 + # info + # notice + # warning + # error + # log + # fatal + # panic + +#log_min_error_statement = error # values in order of decreasing detail: + # debug5 + # debug4 + # debug3 + # debug2 + # debug1 + # info + # notice + # warning + # error + # log + # fatal + # panic (effectively off) + +#log_min_duration_statement = -1 # -1 is disabled, 0 logs all statements + # and their durations, > 0 logs only + # statements running at least this number + # of milliseconds + + +# - What to Log - + +#debug_print_parse = off +#debug_print_rewritten = off +#debug_print_plan = off +#debug_pretty_print = on +#log_checkpoints = off +#log_connections = off +#log_disconnections = off +#log_duration = off +#log_error_verbosity = default # terse, default, or verbose messages +#log_hostname = off +#log_line_prefix = '%m [%p] ' # special values: + # %a = application name + # %u = user name + # %d = database name + # %r = remote host and port + # %h = remote host + # %p = process ID + # %t = timestamp without milliseconds + # %m = timestamp with milliseconds + # %n = timestamp with milliseconds (as a Unix epoch) + # %i = command tag + # %e = SQL state + # %c = session ID + # %l = session line number + # %s = session start timestamp + # %v = virtual transaction ID + # %x = transaction ID (0 if none) + # %q = stop here in non-session + # processes + # %% = '%' + # e.g. '<%u%%%d> ' +#log_lock_waits = off # log lock waits >= deadlock_timeout +#log_statement = 'none' # none, ddl, mod, all +#log_replication_commands = off +#log_temp_files = -1 # log temporary files equal or larger + # than the specified size in kilobytes; + # -1 disables, 0 logs all temp files +log_timezone = 'UTC' + + +# - Process Title - + +#cluster_name = '' # added to process titles if nonempty + # (change requires restart) +#update_process_title = on + + +#------------------------------------------------------------------------------ +# RUNTIME STATISTICS +#------------------------------------------------------------------------------ + +# - Query/Index Statistics Collector - + +#track_activities = on +#track_counts = on +#track_io_timing = off +#track_functions = none # none, pl, all +#track_activity_query_size = 1024 # (change requires restart) +#stats_temp_directory = 'pg_stat_tmp' + + +# - Statistics Monitoring - + +#log_parser_stats = off +#log_planner_stats = off +#log_executor_stats = off +#log_statement_stats = off + + +#------------------------------------------------------------------------------ +# AUTOVACUUM PARAMETERS +#------------------------------------------------------------------------------ + +#autovacuum = on # Enable autovacuum subprocess? 'on' + # requires track_counts to also be on. +#log_autovacuum_min_duration = -1 # -1 disables, 0 logs all actions and + # their durations, > 0 logs only + # actions running at least this number + # of milliseconds. +#autovacuum_max_workers = 3 # max number of autovacuum subprocesses + # (change requires restart) +#autovacuum_naptime = 1min # time between autovacuum runs +#autovacuum_vacuum_threshold = 50 # min number of row updates before + # vacuum +#autovacuum_analyze_threshold = 50 # min number of row updates before + # analyze +#autovacuum_vacuum_scale_factor = 0.2 # fraction of table size before vacuum +#autovacuum_analyze_scale_factor = 0.1 # fraction of table size before analyze +#autovacuum_freeze_max_age = 200000000 # maximum XID age before forced vacuum + # (change requires restart) +#autovacuum_multixact_freeze_max_age = 400000000 # maximum multixact age + # before forced vacuum + # (change requires restart) +#autovacuum_vacuum_cost_delay = 20ms # default vacuum cost delay for + # autovacuum, in milliseconds; + # -1 means use vacuum_cost_delay +#autovacuum_vacuum_cost_limit = -1 # default vacuum cost limit for + # autovacuum, -1 means use + # vacuum_cost_limit + + +#------------------------------------------------------------------------------ +# CLIENT CONNECTION DEFAULTS +#------------------------------------------------------------------------------ + +# - Statement Behavior - + +#search_path = '"$user", public' # schema names +#default_tablespace = '' # a tablespace name, '' uses the default +#temp_tablespaces = '' # a list of tablespace names, '' uses + # only default tablespace +#check_function_bodies = on +#default_transaction_isolation = 'read committed' +#default_transaction_read_only = off +#default_transaction_deferrable = off +#session_replication_role = 'origin' +#statement_timeout = 0 # in milliseconds, 0 is disabled +#lock_timeout = 0 # in milliseconds, 0 is disabled +#idle_in_transaction_session_timeout = 0 # in milliseconds, 0 is disabled +#vacuum_freeze_min_age = 50000000 +#vacuum_freeze_table_age = 150000000 +#vacuum_multixact_freeze_min_age = 5000000 +#vacuum_multixact_freeze_table_age = 150000000 +#bytea_output = 'hex' # hex, escape +#xmlbinary = 'base64' +#xmloption = 'content' +#gin_fuzzy_search_limit = 0 +#gin_pending_list_limit = 4MB + +# - Locale and Formatting - + +datestyle = 'iso, mdy' +#intervalstyle = 'postgres' +timezone = 'UTC' +#timezone_abbreviations = 'Default' # Select the set of available time zone + # abbreviations. Currently, there are + # Default + # Australia (historical usage) + # India + # You can create your own file in + # share/timezonesets/. +#extra_float_digits = 0 # min -15, max 3 +#client_encoding = sql_ascii # actually, defaults to database + # encoding + +# These settings are initialized by initdb, but they can be changed. +lc_messages = 'en_US.utf8' # locale for system error message + # strings +lc_monetary = 'en_US.utf8' # locale for monetary formatting +lc_numeric = 'en_US.utf8' # locale for number formatting +lc_time = 'en_US.utf8' # locale for time formatting + +# default configuration for text search +default_text_search_config = 'pg_catalog.english' + +# - Other Defaults - + +#dynamic_library_path = '$libdir' +#local_preload_libraries = '' +#session_preload_libraries = '' + + +#------------------------------------------------------------------------------ +# LOCK MANAGEMENT +#------------------------------------------------------------------------------ + +#deadlock_timeout = 1s +#max_locks_per_transaction = 64 # min 10 + # (change requires restart) +#max_pred_locks_per_transaction = 64 # min 10 + # (change requires restart) +#max_pred_locks_per_relation = -2 # negative values mean + # (max_pred_locks_per_transaction + # / -max_pred_locks_per_relation) - 1 +#max_pred_locks_per_page = 2 # min 0 + + +#------------------------------------------------------------------------------ +# VERSION/PLATFORM COMPATIBILITY +#------------------------------------------------------------------------------ + +# - Previous PostgreSQL Versions - + +#array_nulls = on +#backslash_quote = safe_encoding # on, off, or safe_encoding +#default_with_oids = off +#escape_string_warning = on +#lo_compat_privileges = off +#operator_precedence_warning = off +#quote_all_identifiers = off +#standard_conforming_strings = on +#synchronize_seqscans = on + +# - Other Platforms and Clients - + +#transform_null_equals = off + + +#------------------------------------------------------------------------------ +# ERROR HANDLING +#------------------------------------------------------------------------------ + +#exit_on_error = off # terminate session on any error? +#restart_after_crash = on # reinitialize after backend crash? + + +#------------------------------------------------------------------------------ +# CONFIG FILE INCLUDES +#------------------------------------------------------------------------------ + +# These options allow settings to be loaded from files other than the +# default postgresql.conf. + +#include_dir = 'conf.d' # include files ending in '.conf' from + # directory 'conf.d' +#include_if_exists = 'exists.conf' # include file only if it exists +#include = 'special.conf' # include file + + +#------------------------------------------------------------------------------ +# CUSTOMIZED OPTIONS +#------------------------------------------------------------------------------ + +# Add settings for extensions here + +shared_preload_libraries = 'pg_stat_statements' +pg_stat_statements.track = all \ No newline at end of file diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3a78c9d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +node_modules +npm-debug.log +Dockerfile* +docker-compose* +.dockerignore +.git +.gitignore +.env +*/bin +*/obj +README.md +LICENSE +.vscode \ No newline at end of file diff --git a/.gitignore b/.gitignore index 18b43c9..c6dba2c 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,4 @@ # Ignore master key for decrypting credentials and more. /config/master.key +/.docker/*.tgz diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..2b5b543 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,46 @@ +FROM alpine:latest + +LABEL Alec Pervushin + +ENV RUBY_INSTALL_VERSION "0.7.0" +ENV RUBY_INSTALL_URL "https://github.com/postmodern/ruby-install/archive/v${RUBY_INSTALL_VERSION}.tar.gz" +ENV CHRUBY_VERSION '0.3.9' +ENV CHRUBY_URL "https://github.com/postmodern/chruby/archive/v${CHRUBY_VERSION}.tar.gz" + +RUN apk update && \ + apk upgrade && \ + apk add --no-cache gnupg curl bash procps musl zlib openssl \ + patch make gcc g++ gnupg musl-dev linux-headers zlib-dev openssl-dev \ + postgresql-dev tzdata ruby readline-dev + +SHELL ["/bin/bash", "-lc"] + +WORKDIR /tmp + +RUN curl -L -o ruby-install.tar.gz ${RUBY_INSTALL_URL} && \ + tar -xzvf ruby-install.tar.gz && \ + cd ruby-install-${RUBY_INSTALL_VERSION}/ && make install + +ADD .docker/current.tgz /opt/ + +COPY bin/install-railsexpress* /tmp/ +COPY .ruby-version* /root/ +COPY Gemfile* /tmp/ + +RUN echo 'export RUBY_VERSION=$([ -z "$RUBY_VERSION" ] && cat ~/.ruby-version || "$RUBY_VERSION")' >> /etc/profile + +RUN ./install-railsexpress railsexpress $RUBY_VERSION \ + --jobs=2 --cleanup --no-reinstall + +RUN curl -L -o chruby.tar.gz ${CHRUBY_URL} && \ + tar -xzvf chruby.tar.gz && \ + cd chruby-${CHRUBY_VERSION}/ && make install && \ + echo "source /usr/local/share/chruby/chruby.sh" >> /etc/profile && \ + echo 'chruby $RUBY_VERSION' >> /etc/profile + +RUN gem install bundler rb-readline && bundle check || bundle install + +RUN apk del gnupg musl-dev linux-headers ruby && \ + rm -rf /tmp/* /var/cache/apk/* + +COPY docker-entrypoint.sh* / \ No newline at end of file diff --git a/Gemfile b/Gemfile index 33017fd..b277961 100644 --- a/Gemfile +++ b/Gemfile @@ -13,10 +13,21 @@ group :development, :test do gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] end +gem 'strong_migrations', '~> 0.3.1' +gem 'oj', '~> 3.7.11' +gem 'activerecord-import', '~> 1.0.1' + group :development do # Access an interactive console on exception pages or by calling 'console' anywhere in the code. gem 'web-console', '>= 3.3.0' gem 'listen', '>= 3.0.5', '< 3.2' + gem 'rack-mini-profiler', '~> 1.0.2', require: false + gem 'memory_profiler', '~> 0.9.13', require: false + gem 'flamegraph', '~> 0.9.5', require: false + gem 'stackprof', '~> 0.2.12', require: false + gem 'ruby-prof', '~> 0.17.0', require: false + gem 'benchmark-ips', '~> 2.7.2', require: false + gem 'bullet', '~> 5.9.0' end group :test do diff --git a/Gemfile.lock b/Gemfile.lock index eb22e16..28a4976 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -33,6 +33,8 @@ GEM activemodel (= 5.2.3) activesupport (= 5.2.3) arel (>= 9.0) + activerecord-import (1.0.1) + activerecord (>= 3.2) activestorage (5.2.3) actionpack (= 5.2.3) activerecord (= 5.2.3) @@ -43,15 +45,20 @@ GEM minitest (~> 5.1) tzinfo (~> 1.1) arel (9.0.0) + benchmark-ips (2.7.2) bindex (0.6.0) bootsnap (1.4.2) msgpack (~> 1.0) builder (3.2.3) + bullet (5.9.0) + activesupport (>= 3.0.0) + uniform_notifier (~> 1.11) byebug (11.0.1) concurrent-ruby (1.1.5) crass (1.0.4) erubi (1.8.0) ffi (1.10.0) + flamegraph (0.9.5) globalid (0.4.2) activesupport (>= 4.2.0) i18n (1.6.0) @@ -67,6 +74,7 @@ GEM mini_mime (>= 0.1.1) marcel (0.3.3) mimemagic (~> 0.3.2) + memory_profiler (0.9.13) method_source (0.9.2) mimemagic (0.3.3) mini_mime (1.0.1) @@ -76,9 +84,12 @@ GEM nio4r (2.3.1) nokogiri (1.10.2) mini_portile2 (~> 2.4.0) + oj (3.7.11) pg (1.1.4) puma (3.12.1) rack (2.0.6) + rack-mini-profiler (1.0.2) + rack (>= 1.2.0) rack-test (1.1.0) rack (>= 1.0, < 3) rails (5.2.3) @@ -109,6 +120,7 @@ GEM rb-fsevent (0.10.3) rb-inotify (0.10.0) ffi (~> 1.0) + ruby-prof (0.17.0) ruby_dep (1.5.0) sprockets (3.7.2) concurrent-ruby (~> 1.0) @@ -117,10 +129,14 @@ GEM actionpack (>= 4.0) activesupport (>= 4.0) sprockets (>= 3.0.0) + stackprof (0.2.12) + strong_migrations (0.3.1) + activerecord (>= 3.2.0) thor (0.20.3) thread_safe (0.3.6) tzinfo (1.2.5) thread_safe (~> 0.1) + uniform_notifier (1.12.1) web-console (3.7.0) actionview (>= 5.0) activemodel (>= 5.0) @@ -134,12 +150,22 @@ PLATFORMS ruby DEPENDENCIES + activerecord-import (~> 1.0.1) + benchmark-ips (~> 2.7.2) bootsnap (>= 1.1.0) + bullet (~> 5.9.0) byebug + flamegraph (~> 0.9.5) listen (>= 3.0.5, < 3.2) + memory_profiler (~> 0.9.13) + oj (~> 3.7.11) pg (>= 0.18, < 2.0) puma (~> 3.11) + rack-mini-profiler (~> 1.0.2) rails (~> 5.2.3) + ruby-prof (~> 0.17.0) + stackprof (~> 0.2.12) + strong_migrations (~> 0.3.1) tzinfo-data web-console (>= 3.3.0) diff --git a/app/controllers/trips_controller.rb b/app/controllers/trips_controller.rb index acb38be..172f92d 100644 --- a/app/controllers/trips_controller.rb +++ b/app/controllers/trips_controller.rb @@ -2,6 +2,9 @@ class TripsController < ApplicationController def index @from = City.find_by_name!(params[:from]) @to = City.find_by_name!(params[:to]) - @trips = Trip.where(from: @from, to: @to).order(:start_time) + @trips = Trip. + joins(bus: :services). + where(from: @from, to: @to). + order(:start_time) end end diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb deleted file mode 100644 index a009ace..0000000 --- a/app/jobs/application_job.rb +++ /dev/null @@ -1,2 +0,0 @@ -class ApplicationJob < ActiveJob::Base -end diff --git a/app/models/bus.rb b/app/models/bus.rb index 1dcc54c..d97de31 100644 --- a/app/models/bus.rb +++ b/app/models/bus.rb @@ -13,7 +13,8 @@ class Bus < ApplicationRecord ].freeze has_many :trips - has_and_belongs_to_many :services, join_table: :buses_services + has_many :buses_services + has_many :services, through: :buses_services validates :number, presence: true, uniqueness: true validates :model, inclusion: { in: MODELS } diff --git a/app/models/buses_service.rb b/app/models/buses_service.rb new file mode 100644 index 0000000..6ec494e --- /dev/null +++ b/app/models/buses_service.rb @@ -0,0 +1,4 @@ +class BusesService < ApplicationRecord + belongs_to :bus + belongs_to :service +end \ No newline at end of file diff --git a/app/models/service.rb b/app/models/service.rb index 9cbb2a3..1781543 100644 --- a/app/models/service.rb +++ b/app/models/service.rb @@ -12,7 +12,8 @@ class Service < ApplicationRecord 'Можно не печатать билет', ].freeze - has_and_belongs_to_many :buses, join_table: :buses_services + has_many :buses_services + has_many :buses, through: :buses_services validates :name, presence: true validates :name, inclusion: { in: SERVICES } diff --git a/app/services/entities_processing.rb b/app/services/entities_processing.rb new file mode 100644 index 0000000..7b17638 --- /dev/null +++ b/app/services/entities_processing.rb @@ -0,0 +1,97 @@ +class EntitiesProcessing + class << self + def call(file_name:, with_gc: true) + GC.disabled unless with_gc + + json = Oj.load(File.read file_name) + + ActiveRecord::Base.transaction do + City.delete_all + Bus.delete_all + Service.delete_all + Trip.delete_all + BusesService.delete_all + + create_cities(json) + create_services + create_buses(json) + create_trips(json) + end + + clear_entities + end + + private + + def create_buses(json) + @buses = + json.each_with_object({}) do |trip, memo| + bus_number = trip['bus']['number'] + next if memo.has_key?(bus_number) + + memo[bus_number] = Bus.new( + number: bus_number, + model: trip['bus']['model'], + services: @services. + values_at(*trip['bus']['services']) + ) + end + + Bus.import(@buses.values, recursive: true, raise_error: true) + end + + def create_cities(json) + @cities = + json.each_with_object({}) do |trip, memo| + from = trip['from'] + to = trip['to'] + + next if memo.has_key?(from) && memo.has_key?(to) + name = memo.has_key?(from) ? to : from + + memo[name] = City.new(name: name) + end + + City.import(@cities.values, recursive: true, raise_error: true) + end + + def create_services + @services = + Service::SERVICES.sort.each_with_object({}) do |name, memo| + memo[name] = Service.new(name: name) + end + + Service.import(@services.values, recursive: true, raise_error: true) + end + + def create_trips(json) + @trips = + json.each_with_object({}) do |trip, memo| + from = @cities[trip['from']] + to = @cities[trip['to']] + bus = @buses[trip['bus']['number']] + start_time = trip['start_time'] + + + memo[start_time] = + Trip.new( + from: from, + to: to, + bus: bus, + start_time: start_time, + duration_minutes: trip['duration_minutes'], + price_cents: trip['price_cents'], + ) + end + + Trip.import(@trips.values, recursive: true, raise_error: true) + end + + def clear_entities + @trips.clear + @buses.clear + @cities.clear + @services.clear + end + end +end diff --git a/app/views/trips/_delimiter.html.erb b/app/views/trips/_delimiter.html.erb deleted file mode 100644 index 3f845ad..0000000 --- a/app/views/trips/_delimiter.html.erb +++ /dev/null @@ -1 +0,0 @@ -==================================================== diff --git a/app/views/trips/_service.html.erb b/app/views/trips/_service.html.erb deleted file mode 100644 index 178ea8c..0000000 --- a/app/views/trips/_service.html.erb +++ /dev/null @@ -1 +0,0 @@ -
  • <%= "#{service.name}" %>
  • diff --git a/app/views/trips/_services.html.erb b/app/views/trips/_services.html.erb deleted file mode 100644 index 2de639f..0000000 --- a/app/views/trips/_services.html.erb +++ /dev/null @@ -1,6 +0,0 @@ -
  • Сервисы в автобусе:
  • -
      - <% services.each do |service| %> - <%= render "service", service: service %> - <% end %> -
    diff --git a/app/views/trips/_trip.html.erb b/app/views/trips/_trip.html.erb index fa1de9a..ec7a242 100644 --- a/app/views/trips/_trip.html.erb +++ b/app/views/trips/_trip.html.erb @@ -1,5 +1,21 @@ -
  • <%= "Отправление: #{trip.start_time}" %>
  • -
  • <%= "Прибытие: #{(Time.parse(trip.start_time) + trip.duration_minutes.minutes).strftime('%H:%M')}" %>
  • -
  • <%= "В пути: #{trip.duration_minutes / 60}ч. #{trip.duration_minutes % 60}мин." %>
  • -
  • <%= "Цена: #{trip.price_cents / 100}р. #{trip.price_cents % 100}коп." %>
  • -
  • <%= "Автобус: #{trip.bus.model} №#{trip.bus.number}" %>
  • +<% cache [trip, trip.bus] do %> +
      +
    • <%= "Отправление: #{trip.start_time}" %>
    • +
    • <%= "Прибытие: #{(Time.parse(trip.start_time) + trip.duration_minutes.minutes).strftime('%H:%M')}" %>
    • +
    • <%= "В пути: #{trip.duration_minutes / 60}ч. #{trip.duration_minutes % 60}мин." %>
    • +
    • <%= "Цена: #{trip.price_cents / 100}р. #{trip.price_cents % 100}коп." %>
    • +
    • <%= "Автобус: #{trip.bus.model} №#{trip.bus.number}" %>
    • + + <% if trip.bus.services.exists? %> +
    • Сервисы в автобусе:
    • +
        + <% trip.bus.services.each do |service| %> + <% cache service do %> +
      • <%= "#{service.name}" %>
      • + <% end %> + <% end %> +
      + <% end %> +
    + ==================================================== +<% end %> \ No newline at end of file diff --git a/app/views/trips/index.html.erb b/app/views/trips/index.html.erb index a60bce4..1c0e62c 100644 --- a/app/views/trips/index.html.erb +++ b/app/views/trips/index.html.erb @@ -5,12 +5,4 @@ <%= "В расписании #{@trips.count} рейсов" %> -<% @trips.each do |trip| %> -
      - <%= render "trip", trip: trip %> - <% if trip.bus.services.present? %> - <%= render "services", services: trip.bus.services %> - <% end %> -
    - <%= render "delimiter" %> -<% end %> +<%= render @trips, cached: true%> diff --git a/bin/benchmarking/asymptotics b/bin/benchmarking/asymptotics new file mode 100755 index 0000000..833716d --- /dev/null +++ b/bin/benchmarking/asymptotics @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby + +require 'active_record' +require './app/models/application_record' +require './app/models/bus' +require './app/models/buses_service' +require './app/models/city' +require './app/models/service' +require './app/models/trip' +require './app/services/entities_processing' + +require 'benchmark/ips' +require 'oj' +require 'activerecord-import' + +config = YAML.load_file('config/database.yml')["development"]. + merge!('url' => ENV.fetch("DATABASE_URL"), 'pool' => 15) + +ActiveRecord::Base.establish_connection(config) + +Benchmark.ips do |bench| + bench.warmup = 0 + bench.report("SM Process") do + EntitiesProcessing.call(file_name: 'fixtures/small.json') + end + bench.report("MD Process") do + EntitiesProcessing.call(file_name: 'fixtures/medium.json') + end + bench.report("LG Process") do + EntitiesProcessing.call(file_name: 'fixtures/large.json') + end + + bench.compare! +end \ No newline at end of file diff --git a/bin/benchmarking/memory-profiler b/bin/benchmarking/memory-profiler new file mode 100755 index 0000000..e7abb5f --- /dev/null +++ b/bin/benchmarking/memory-profiler @@ -0,0 +1,24 @@ +#!/usr/bin/env ruby + +require 'active_record' +require './app/models/application_record' +require './app/models/bus' +require './app/models/city' +require './app/models/service' +require './app/models/trip' +require './app/services/entities_processing' + +require 'benchmark/ips' +require 'oj' +require 'memory_profiler' + +config = YAML.load_file('config/database.yml')["development"]. + merge!('url' => ENV.fetch("DATABASE_URL"), 'pool' => 15) + +ActiveRecord::Base.establish_connection(config) + +report = MemoryProfiler.report do + EntitiesProcessing.call(file_name: 'fixtures/small.json') +end + +report.pretty_print(scale_bytes: true) \ No newline at end of file diff --git a/bin/benchmarking/ruby-prof-cpu b/bin/benchmarking/ruby-prof-cpu new file mode 100755 index 0000000..d5dc59b --- /dev/null +++ b/bin/benchmarking/ruby-prof-cpu @@ -0,0 +1,22 @@ +#!/usr/bin/env ruby + +require './app/services/entities_processing' +require 'ruby-prof' +require 'active_record' +require 'pg' +require 'yaml' +require 'oj' + +config = YAML.load_file('config/database.yml')["development"]. + merge!('url' => ENV.fetch("DATABASE_URL")) + +ActiveRecord::Base.establish_connection(config) + +RubyProf.measure_mode = RubyProf::WALL_TIME + +result = RubyProf.profile do + EntitiesProcessing.call(file_name: 'fixtures/small.json', with_gc: false) +end + +printer = RubyProf::CallTreePrinter.new(result) +printer.print(path: "tmp", profile: 'profile_cpu') \ No newline at end of file diff --git a/bin/benchmarking/ruby-prof-memory b/bin/benchmarking/ruby-prof-memory new file mode 100755 index 0000000..b029119 --- /dev/null +++ b/bin/benchmarking/ruby-prof-memory @@ -0,0 +1,23 @@ +#!/usr/bin/env ruby + +require './app/services/entities_processing' +require 'ruby-prof' +require 'active_record' +require 'pg' +require 'yaml' +require 'oj' + +config = YAML.load_file('config/database.yml')["development"]. + merge!('url' => ENV.fetch("DATABASE_URL")) + +ActiveRecord::Base.establish_connection(config) + +GC.enable_stats +RubyProf.measure_mode = RubyProf::MEMORY + +result = RubyProf.profile do + EntitiesProcessing.call(file_name: 'fixtures/small.json') +end + +printer = RubyProf::CallTreePrinter.new(result) +printer.print(path: "tmp", profile: 'profile_memory') \ No newline at end of file diff --git a/bin/install-railsexpress b/bin/install-railsexpress new file mode 100755 index 0000000..1c66b56 --- /dev/null +++ b/bin/install-railsexpress @@ -0,0 +1,17 @@ +#!/usr/bin/env ruby + +require 'open-uri' +patchset = ARGV[0] +version = ARGV[1] +arguments = ARGV[2..-1].join(' ') + +raise 'Please specify a patchset' if patchset.nil? +raise 'Please specify a ruby version' if version.nil? + +patches = open("https://raw.githubusercontent.com/skaes/rvm-patchsets/master/patchsets/ruby/#{version}/#{patchset}").read.split("\n").map do |patch| + "-p https://raw.githubusercontent.com/skaes/rvm-patchsets/master/patches/ruby/#{version}/#{patch}" +end.join(" ") + +puts "Installing ruby with #{`ruby-install --version`}" +puts "Available Rubies: #{`ruby-install`}" +`ruby-install #{patches} #{arguments} ruby #{version}` diff --git a/bin/startup b/bin/startup new file mode 100755 index 0000000..b3a6d62 --- /dev/null +++ b/bin/startup @@ -0,0 +1,18 @@ +#!/usr/bin/env ruby +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = File.expand_path('..', __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a starting point to setup your application. + # Add necessary setup steps to this file. + + puts "\n== Starting application server ==" + system! 'bin/bundle exec rails server -b 0.0.0.0 -p 3000' +end diff --git a/config/application.rb b/config/application.rb index 9c33109..e2e4276 100644 --- a/config/application.rb +++ b/config/application.rb @@ -15,5 +15,6 @@ class Application < Rails::Application # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. + config.active_job.queue_adapter = :delayed_job end end diff --git a/config/database.yml b/config/database.yml index e116cfa..9427de3 100644 --- a/config/database.yml +++ b/config/database.yml @@ -20,6 +20,7 @@ default: &default # For details on connection pooling, see Rails configuration guide # http://guides.rubyonrails.org/configuring.html#database-pooling pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + url: <%= ENV.fetch("DATABASE_URL") %> development: <<: *default @@ -30,22 +31,17 @@ development: # When left blank, postgres will use the default role. This is # the same name as the operating system user that initialized the database. #username: task-4 - # The password associated with the postgres role (username). #password: - # Connect on a TCP socket. Omitted by default since the client uses a # domain socket that doesn't need configuration. Windows does not have # domain sockets, so uncomment these lines. #host: localhost - # The TCP port the server listens on. Defaults to 5432. # If your server runs on a different port number, change accordingly. #port: 5432 - # Schema search path. The server defaults to $user,public #schema_search_path: myapp,sharedapp,public - # Minimum log levels, in increasing order: # debug5, debug4, debug3, debug2, debug1, # log, notice, warning, error, fatal, and panic diff --git a/config/environments/development.rb b/config/environments/development.rb index 1311e3e..b3660d0 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -58,4 +58,13 @@ # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker + + config.after_initialize do + Bullet.enable = true + Bullet.console = true # stacktraces here + Bullet.add_footer = true + Bullet.bullet_logger = true # log/bullet.log, stacktraces here + Bullet.rails_logger = true + end + end diff --git a/db/migrate/20190415105016_add_index_to_trip.rb b/db/migrate/20190415105016_add_index_to_trip.rb new file mode 100644 index 0000000..fcdebad --- /dev/null +++ b/db/migrate/20190415105016_add_index_to_trip.rb @@ -0,0 +1,7 @@ +class AddIndexToTrip < ActiveRecord::Migration[5.2] + disable_ddl_transaction! + + def change + add_index :trips, [:from_id, :to_id], algorithm: :concurrently + end +end diff --git a/db/migrate/20190415105125_add_index_to_bus.rb b/db/migrate/20190415105125_add_index_to_bus.rb new file mode 100644 index 0000000..9c17f20 --- /dev/null +++ b/db/migrate/20190415105125_add_index_to_bus.rb @@ -0,0 +1,7 @@ +class AddIndexToBus < ActiveRecord::Migration[5.2] + disable_ddl_transaction! + + def change + add_index :buses, :number, algorithm: :concurrently + end +end diff --git a/db/migrate/20190415105221_add_index_to_bus_service.rb b/db/migrate/20190415105221_add_index_to_bus_service.rb new file mode 100644 index 0000000..8f57b8e --- /dev/null +++ b/db/migrate/20190415105221_add_index_to_bus_service.rb @@ -0,0 +1,7 @@ +class AddIndexToBusService < ActiveRecord::Migration[5.2] + disable_ddl_transaction! + + def change + add_index :buses_services, [:bus_id, :service_id], algorithm: :concurrently + end +end diff --git a/db/schema.rb b/db/schema.rb index f6921e4..a25a4af 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,19 +10,22 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2019_03_30_193044) do +ActiveRecord::Schema.define(version: 2019_04_15_105221) do # These are extensions that must be enabled in order to support this database + enable_extension "pg_stat_statements" enable_extension "plpgsql" create_table "buses", force: :cascade do |t| t.string "number" t.string "model" + t.index ["number"], name: "index_buses_on_number" end create_table "buses_services", force: :cascade do |t| t.integer "bus_id" t.integer "service_id" + t.index ["bus_id", "service_id"], name: "index_buses_services_on_bus_id_and_service_id" end create_table "cities", force: :cascade do |t| @@ -40,6 +43,7 @@ t.integer "duration_minutes" t.integer "price_cents" t.integer "bus_id" + t.index ["from_id", "to_id"], name: "index_trips_on_from_id_and_to_id" end end diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..9676373 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,60 @@ +version: "3.7" + +services: + task-4: + build: + context: . + stdin_open: true + tty: true + working_dir: /usr/src/app + networks: + - cources-network + ports: + - 127.0.1.1:3000:3000 + volumes: + - .:/usr/src/app + - rubies:/opt/rubies + depends_on: + - db + - arc + environment: + RAILS_ENV: development + DATABASE_URL: "postgres://postgres:password@db/" + entrypoint: /docker-entrypoint.sh + command: "bin/startup" + + db: + image: postgres:10-alpine + networks: + cources-network: + aliases: + - db + volumes: + - .docker/postgresql.conf:/var/lib/postgresql/data/postgresql.conf + arc: + image: alpine:latest + volumes: + - rubies:/cont/rubies + - .docker:/host/docker + networks: + - cources-network + working_dir: /cont + entrypoint: tar -czf /host/docker/current.tgz rubies/ + + pghero: + image: ankane/pghero + depends_on: + - db + ports: + - 127.0.1.1:8080:8080 + environment: + DATABASE_URL: "postgres://postgres:password@db/task-4_development" + networks: + - cources-network + +networks: + cources-network: + name: cources-network + +volumes: + rubies: diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh new file mode 100755 index 0000000..28a3d0c --- /dev/null +++ b/docker-entrypoint.sh @@ -0,0 +1,6 @@ +#! /bin/bash -l + +chruby + +# Execute the given or default command: +exec "$@" \ No newline at end of file diff --git a/lib/tasks/utils.rake b/lib/tasks/utils.rake index 540fe87..1b6d491 100644 --- a/lib/tasks/utils.rake +++ b/lib/tasks/utils.rake @@ -1,34 +1,5 @@ # Наивная загрузка данных из json-файла в БД # rake reload_json[fixtures/small.json] task :reload_json, [:file_name] => :environment do |_task, args| - json = JSON.parse(File.read(args.file_name)) - - ActiveRecord::Base.transaction do - City.delete_all - Bus.delete_all - Service.delete_all - Trip.delete_all - ActiveRecord::Base.connection.execute('delete from buses_services;') - - json.each do |trip| - from = City.find_or_create_by(name: trip['from']) - to = City.find_or_create_by(name: trip['to']) - services = [] - trip['bus']['services'].each do |service| - s = Service.find_or_create_by(name: service) - services << s - end - bus = Bus.find_or_create_by(number: trip['bus']['number']) - bus.update(model: trip['bus']['model'], services: services) - - Trip.create!( - from: from, - to: to, - bus: bus, - start_time: trip['start_time'], - duration_minutes: trip['duration_minutes'], - price_cents: trip['price_cents'], - ) - end - end + EntitiesProcessing.call(file_name: args.file_name) end