CombinedText
stringlengths
4
3.42M
# -*- encoding: utf-8 -*- require 'rubygems' unless Object.const_defined?(:Gem) require File.dirname(__FILE__) + "/lib/ripl/rails" Gem::Specification.new do |s| s.name = "ripl-rails" s.version = Ripl::Rails::VERSION s.authors = ["Gabriel Horner"] s.email = "gabriel.horner@gmail.com" s.homepage = "http://github/com/cldwalker/ripl-rails" s.summary = "Alternative to script/console using ripl" s.description = "This provides an alternative to script/console and a ripl Rails plugin to be reused with app-specific shells. Compatible with Rails 2.3.x and Rails 3.x." s.required_rubygems_version = ">= 1.3.6" s.rubyforge_project = 'tagaholic' s.executables = ['ripl-rails'] s.add_dependency 'ripl', '>= 0.1.2' s.files = Dir.glob(%w[{lib,test}/**/*.rb bin/* [A-Z]*.{txt,rdoc} ext/**/*.{rb,c} **/deps.rip]) + %w{Rakefile .gemspec} s.extra_rdoc_files = ["README.rdoc", "LICENSE.txt"] s.license = 'MIT' end fix gemspec # -*- encoding: utf-8 -*- require 'rubygems' unless Object.const_defined?(:Gem) require File.dirname(__FILE__) + "/lib/ripl/rails" Gem::Specification.new do |s| s.name = "ripl-rails" s.version = Ripl::Rails::VERSION s.authors = ["Gabriel Horner"] s.email = "gabriel.horner@gmail.com" s.homepage = "http://github.com/cldwalker/ripl-rails" s.summary = "Alternative to script/console using ripl" s.description = "This provides an alternative to script/console and a ripl Rails plugin to be reused with app-specific shells. Compatible with Rails 2.3.x and Rails 3.x." s.required_rubygems_version = ">= 1.3.6" s.rubyforge_project = 'tagaholic' s.executables = ['ripl-rails'] s.add_dependency 'ripl', '>= 0.1.2' s.files = Dir.glob(%w[{lib,test}/**/*.rb bin/* [A-Z]*.{txt,rdoc} ext/**/*.{rb,c} **/deps.rip]) + %w{Rakefile .gemspec} s.extra_rdoc_files = ["README.rdoc", "LICENSE.txt"] s.license = 'MIT' end
lib = File.expand_path('../lib', __FILE__) $:.unshift lib unless $:.include?(lib) require 'saas_pulse/version' Gem::Specification.new do |s| s.name = "saas_pulse-ruby" s.version = Totango::VERSION s.platform = Gem::Platform::RUBY s.authors = ["jonah honeyman"] s.email = ["jonah@honeyman.org"] s.summary = "API wrapper for Totango tracking integration" s.description = "Enables easy integration of Totango tracking, with options for different ruby web frameworks" s.homepage = "https://github.com/jonuts/saas_pulse-ruby" s.required_rubygems_version = ">= 1.3.6" s.rubyforge_project = "totango-ruby" s.add_development_dependency "rspec" s.files = Dir.glob("lib/**/*") + %w(LICENSE README.md) s.require_path = "lib" end Updates gemspec lib = File.expand_path('../lib', __FILE__) $:.unshift lib unless $:.include?(lib) require 'totango/version' Gem::Specification.new do |s| s.name = "rubango" s.version = Totango::VERSION s.platform = Gem::Platform::RUBY s.authors = ["jonah honeyman"] s.email = ["jonah@honeyman.org"] s.summary = "API wrapper for Totango tracking integration" s.description = "Enables easy integration of Totango tracking, with options for different ruby web frameworks" s.homepage = "https://github.com/jonuts/rubango" s.required_rubygems_version = ">= 1.3.6" s.rubyforge_project = "rubango" s.add_development_dependency "rspec" s.files = Dir.glob("lib/**/*") + %w(LICENSE README.md) s.require_path = "lib" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "api/territory/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "api_territory" s.version = Mexico::API::Territory::VERSION s.authors = ["Jair Gaxiola"] s.email = ["jyr.gaxiola@gmail.com"] s.homepage = "https://github.com/codeformexico" s.summary = %q{The United Mexican States (Spanish: Estados Unidos Mexicanos) is a federal republic composed of 32 federal entities: 31 states and 1 federal district.} s.description = %q{The United Mexican States (Spanish: Estados Unidos Mexicanos) is a federal republic composed of 32 federal entities: 31 states and 1 federal district.} s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 3.2.13" s.add_development_dependency "pg" end add sqlite3 dependency $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "api/territory/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "api_territory" s.version = Mexico::API::Territory::VERSION s.authors = ["Jair Gaxiola"] s.email = ["jyr.gaxiola@gmail.com"] s.homepage = "https://github.com/codeformexico" s.summary = %q{The United Mexican States (Spanish: Estados Unidos Mexicanos) is a federal republic composed of 32 federal entities: 31 states and 1 federal district.} s.description = %q{The United Mexican States (Spanish: Estados Unidos Mexicanos) is a federal republic composed of 32 federal entities: 31 states and 1 federal district.} s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 3.2.13" s.add_development_dependency "sqlite3" end
module ActiveRecord # == Multi-Table ActiveRecord::MTI module MTI module Registry def self.[]=(klass, tableoid) ActiveRecord::MTI.logger.debug "Adding #{klass} to MTI list with #{tableoid}" tableoids[klass] = tableoid end def self.find_mti_class(tableoid) tableoids.key(tableoid) end def self.tableoid?(klass) tableoids[klass] end private mattr_accessor :tableoids self.tableoids = { ActiveRecord::Base => false } end end end Reorganize, remove useless access modifier module ActiveRecord # == Multi-Table ActiveRecord::MTI module MTI module Registry mattr_accessor :tableoids self.tableoids = { ActiveRecord::Base => false } def self.[]=(klass, tableoid) ActiveRecord::MTI.logger.debug "Adding #{klass} to MTI list with #{tableoid}" tableoids[klass] = tableoid end def self.find_mti_class(tableoid) tableoids.key(tableoid) end def self.tableoid?(klass) tableoids[klass] end end end end
module RamonTayag module Allow module SubscriptionsHelper def link_to_subscription(object, options={}) options[:logged_out_text] ||= "" if logged_in? options.delete(:logged_out_text) if object.subscribed_by?(current_user) link_to_unsubscribe(object, options.merge!(:text => options[:unsubscribe_text], :confirm => options[:unsubscribe_confirm])) else link_to_subscribe(object, options.merge!(:text => options[:subscribe_text], :confirm => options[:subscribe_confirm])) end else options[:logged_out_text] end end def link_to_subscribe(object, options = {}) options[:text] ||= "Subscribe" options[:confirm] ||= "Are you sure?" text = options[:text] options.merge!({:subscribable_id => object.id, :subscribable_type => object.class.name}) options.delete(:text) link_to(text, subscriptions_path(options), :confirm => options[:confirm], :method => :post) end def link_to_unsubscribe(object, options = {}) options[:text] ||= "Unsubscribe" options[:confirm] ||= "Are you sure?" text = options[:text] options.merge!({:subscribable_id => object.id, :subscribable_type => object.class.name}) options.delete(:text) link_to(text, subscription_path(options), :confirm => options[:confirm], :method => :delete) end end end end removed confirmation by default for subscribing module RamonTayag module Allow module SubscriptionsHelper def link_to_subscription(object, options={}) options[:logged_out_text] ||= "" if logged_in? options.delete(:logged_out_text) if object.subscribed_by?(current_user) link_to_unsubscribe(object, options.merge!(:text => options[:unsubscribe_text], :confirm => options[:unsubscribe_confirm])) else link_to_subscribe(object, options.merge!(:text => options[:subscribe_text], :confirm => options[:subscribe_confirm])) end else options[:logged_out_text] end end def link_to_subscribe(object, options = {}) options[:text] ||= "Subscribe" text = options[:text] options.merge!({:subscribable_id => object.id, :subscribable_type => object.class.name}) options.delete(:text) link_to(text, subscriptions_path(options), :confirm => options[:confirm], :method => :post) end def link_to_unsubscribe(object, options = {}) options[:text] ||= "Unsubscribe" options[:confirm] ||= "Are you sure?" text = options[:text] options.merge!({:subscribable_id => object.id, :subscribable_type => object.class.name}) options.delete(:text) link_to(text, subscription_path(options), :confirm => options[:confirm], :method => :delete) end end end end
module Bright class ResponseError < StandardError attr_reader :response def initialize(response, message = nil) @response = response @message = message end def to_s "Failed with #{response.code} #{response.message if response.respond_to?(:message)}" end end class UnknownAttributeError < NoMethodError attr_reader :record, :attribute def initialize(record, attribute) @record = record @attribute = attribute super("unknown attribute '#{attribute}' for #{@record.class}.") end end end clean up some of the error displays module Bright class ResponseError < StandardError attr_reader :response def initialize(response, message = nil) @response = response @message = message end def to_s "Failed with #{response.code} #{response.message if response.respond_to?(:message)}".strip end def body response.body end end class UnknownAttributeError < NoMethodError attr_reader :record, :attribute def initialize(record, attribute) @record = record @attribute = attribute super("unknown attribute '#{attribute}' for #{@record.class}.") end end end
module Brreg VERSION = "0.1.0" end version 0.2.0 module Brreg VERSION = "0.2.0" end
module SSHKit VERSION = "0.0.30" end Preparing v0.0.31 module SSHKit VERSION = "0.0.31" end
require "socket" require "thread" require "monitor" require "bunny/transport" require "bunny/channel_id_allocator" require "bunny/heartbeat_sender" require "bunny/reader_loop" require "bunny/authentication/credentials_encoder" require "bunny/authentication/plain_mechanism_encoder" require "bunny/authentication/external_mechanism_encoder" if defined?(JRUBY_VERSION) require "bunny/concurrent/linked_continuation_queue" else require "bunny/concurrent/continuation_queue" end require "amq/protocol/client" require "amq/settings" module Bunny # Represents AMQP 0.9.1 connection (to a RabbitMQ node). # @see http://rubybunny.info/articles/connecting.html Connecting to RabbitMQ guide class Session # Default host used for connection DEFAULT_HOST = "127.0.0.1" # Default virtual host used for connection DEFAULT_VHOST = "/" # Default username used for connection DEFAULT_USER = "guest" # Default password used for connection DEFAULT_PASSWORD = "guest" # Default heartbeat interval, the same value as RabbitMQ 3.0 uses. DEFAULT_HEARTBEAT = :server # @private DEFAULT_FRAME_MAX = 131072 # backwards compatibility # @private CONNECT_TIMEOUT = Transport::DEFAULT_CONNECTION_TIMEOUT # @private DEFAULT_CONTINUATION_TIMEOUT = if RUBY_VERSION.to_f < 1.9 8000 else 4000 end # RabbitMQ client metadata DEFAULT_CLIENT_PROPERTIES = { :capabilities => { :publisher_confirms => true, :consumer_cancel_notify => true, :exchange_exchange_bindings => true, :"basic.nack" => true, :"connection.blocked" => true, # See http://www.rabbitmq.com/auth-notification.html :authentication_failure_close => true }, :product => "Bunny", :platform => ::RUBY_DESCRIPTION, :version => Bunny::VERSION, :information => "http://rubybunny.info", } # @private DEFAULT_LOCALE = "en_GB" # Default reconnection interval for TCP connection failures DEFAULT_NETWORK_RECOVERY_INTERVAL = 5.0 # # API # # @return [Bunny::Transport] attr_reader :transport attr_reader :status, :host, :port, :heartbeat, :user, :pass, :vhost, :frame_max, :threaded attr_reader :server_capabilities, :server_properties, :server_authentication_mechanisms, :server_locales attr_reader :default_channel attr_reader :channel_id_allocator # Authentication mechanism, e.g. "PLAIN" or "EXTERNAL" # @return [String] attr_reader :mechanism # @return [Logger] attr_reader :logger # @return [Integer] Timeout for blocking protocol operations (queue.declare, queue.bind, etc), in milliseconds. Default is 4000. attr_reader :continuation_timeout # @param [String, Hash] connection_string_or_opts Connection string or a hash of connection options # @param [Hash] optz Extra options not related to connection # # @option connection_string_or_opts [String] :host ("127.0.0.1") Hostname or IP address to connect to # @option connection_string_or_opts [Integer] :port (5672) Port RabbitMQ listens on # @option connection_string_or_opts [String] :username ("guest") Username # @option connection_string_or_opts [String] :password ("guest") Password # @option connection_string_or_opts [String] :vhost ("/") Virtual host to use # @option connection_string_or_opts [Integer] :heartbeat (600) Heartbeat interval. 0 means no heartbeat. # @option connection_string_or_opts [Integer] :network_recovery_interval (4) Recovery interval periodic network recovery will use. This includes initial pause after network failure. # @option connection_string_or_opts [Boolean] :tls (false) Should TLS/SSL be used? # @option connection_string_or_opts [String] :tls_cert (nil) Path to client TLS/SSL certificate file (.pem) # @option connection_string_or_opts [String] :tls_key (nil) Path to client TLS/SSL private key file (.pem) # @option connection_string_or_opts [Array<String>] :tls_ca_certificates Array of paths to TLS/SSL CA files (.pem), by default detected from OpenSSL configuration # @option connection_string_or_opts [Integer] :continuation_timeout (4000) Timeout for client operations that expect a response (e.g. {Bunny::Queue#get}), in milliseconds. # @option connection_string_or_opts [Integer] :connection_timeout (5) Timeout in seconds for connecting to the server. # # @option optz [String] :auth_mechanism ("PLAIN") Authentication mechanism, PLAIN or EXTERNAL # @option optz [String] :locale ("PLAIN") Locale RabbitMQ should use # # @see http://rubybunny.info/articles/connecting.html Connecting to RabbitMQ guide # @see http://rubybunny.info/articles/tls.html TLS/SSL guide # @api public def initialize(connection_string_or_opts = Hash.new, optz = Hash.new) opts = case (ENV["RABBITMQ_URL"] || connection_string_or_opts) when nil then Hash.new when String then self.class.parse_uri(ENV["RABBITMQ_URL"] || connection_string_or_opts) when Hash then connection_string_or_opts end.merge(optz) @opts = opts @host = self.hostname_from(opts) @port = self.port_from(opts) @user = self.username_from(opts) @pass = self.password_from(opts) @vhost = self.vhost_from(opts) @logfile = opts[:log_file] || opts[:logfile] || STDOUT @threaded = opts.fetch(:threaded, true) @logger = opts.fetch(:logger, init_logger(opts[:log_level] || ENV["BUNNY_LOG_LEVEL"] || Logger::WARN)) # should automatic recovery from network failures be used? @automatically_recover = if opts[:automatically_recover].nil? && opts[:automatic_recovery].nil? true else opts[:automatically_recover] || opts[:automatic_recovery] end @network_recovery_interval = opts.fetch(:network_recovery_interval, DEFAULT_NETWORK_RECOVERY_INTERVAL) # in ms @continuation_timeout = opts.fetch(:continuation_timeout, DEFAULT_CONTINUATION_TIMEOUT) @status = :not_connected @blocked = false # these are negotiated with the broker during the connection tuning phase @client_frame_max = opts.fetch(:frame_max, DEFAULT_FRAME_MAX) @client_channel_max = opts.fetch(:channel_max, 65536) @client_heartbeat = self.heartbeat_from(opts) @client_properties = opts[:properties] || DEFAULT_CLIENT_PROPERTIES @mechanism = opts.fetch(:auth_mechanism, "PLAIN") @credentials_encoder = credentials_encoder_for(@mechanism) @locale = @opts.fetch(:locale, DEFAULT_LOCALE) @mutex_impl = @opts.fetch(:mutex_impl, Monitor) # mutex for the channel id => channel hash @channel_mutex = @mutex_impl.new # transport operations/continuations mutex. A workaround for # the non-reentrant Ruby mutexes. MK. @transport_mutex = @mutex_impl.new @channels = Hash.new @origin_thread = Thread.current self.reset_continuations self.initialize_transport end # @return [String] RabbitMQ hostname (or IP address) used def hostname; self.host; end # @return [String] Username used def username; self.user; end # @return [String] Password used def password; self.pass; end # @return [String] Virtual host used def virtual_host; self.vhost; end # @return [Integer] Heartbeat interval used def heartbeat_interval; self.heartbeat; end # @return [Boolean] true if this connection uses TLS (SSL) def uses_tls? @transport.uses_tls? end alias tls? uses_tls? # @return [Boolean] true if this connection uses TLS (SSL) def uses_ssl? @transport.uses_ssl? end alias ssl? uses_ssl? # @return [Boolean] true if this connection uses a separate thread for I/O activity def threaded? @threaded end # @private attr_reader :mutex_impl # Provides a way to fine tune the socket used by connection. # Accepts a block that the socket will be yielded to. def configure_socket(&block) raise ArgumentError, "No block provided!" if block.nil? @transport.configure_socket(&block) end # Starts the connection process. # # @see http://rubybunny.info/articles/getting_started.html # @see http://rubybunny.info/articles/connecting.html # @api public def start return self if connected? @status = :connecting # reset here for cases when automatic network recovery kicks in # when we were blocked. MK. @blocked = false self.reset_continuations begin # close existing transport if we have one, # to not leak sockets @transport.maybe_initialize_socket @transport.post_initialize_socket @transport.connect if @socket_configurator @transport.configure_socket(&@socket_configurator) end self.init_connection self.open_connection @reader_loop = nil self.start_reader_loop if threaded? @default_channel = self.create_channel rescue Exception => e @status = :not_connected raise e end self end # Socket operation timeout used by this connection # @return [Integer] # @private def read_write_timeout @transport.read_write_timeout end # Opens a new channel and returns it. This method will block the calling # thread until the response is received and the channel is guaranteed to be # opened (this operation is very fast and inexpensive). # # @return [Bunny::Channel] Newly opened channel def create_channel(n = nil, consumer_pool_size = 1) if n && (ch = @channels[n]) ch else ch = Bunny::Channel.new(self, n, ConsumerWorkPool.new(consumer_pool_size || 1)) ch.open ch end end alias channel create_channel # Closes the connection. This involves closing all of its channels. def close if @transport.open? close_all_channels Bunny::Timeout.timeout(@transport.disconnect_timeout, ClientTimeout) do self.close_connection(true) end maybe_shutdown_reader_loop close_transport @status = :closed end end alias stop close # Creates a temporary channel, yields it to the block given to this # method and closes it. # # @return [Bunny::Session] self def with_channel(n = nil) ch = create_channel(n) yield ch ch.close if ch.open? self end # @return [Boolean] true if this connection is still not fully open def connecting? status == :connecting end # @return [Boolean] true if this AMQP 0.9.1 connection is closed def closed? status == :closed end # @return [Boolean] true if this AMQP 0.9.1 connection is open def open? (status == :open || status == :connected || status == :connecting) && @transport.open? end alias connected? open? # @return [Boolean] true if this connection has automatic recovery from network failure enabled def automatically_recover? @automatically_recover end # # Backwards compatibility # # @private def queue(*args) @default_channel.queue(*args) end # @private def direct(*args) @default_channel.direct(*args) end # @private def fanout(*args) @default_channel.fanout(*args) end # @private def topic(*args) @default_channel.topic(*args) end # @private def headers(*args) @default_channel.headers(*args) end # @private def exchange(*args) @default_channel.exchange(*args) end # Defines a callback that will be executed when RabbitMQ blocks the connection # because it is running low on memory or disk space (as configured via config file # and/or rabbitmqctl). # # @yield [AMQ::Protocol::Connection::Blocked] connection.blocked method which provides a reason for blocking # # @api public def on_blocked(&block) @block_callback = block end # Defines a callback that will be executed when RabbitMQ unblocks the connection # that was previously blocked, e.g. because the memory or disk space alarm has cleared. # # @see #on_blocked # @api public def on_unblocked(&block) @unblock_callback = block end # @return [Boolean] true if the connection is currently blocked by RabbitMQ because it's running low on # RAM, disk space, or other resource; false otherwise # @see #on_blocked # @see #on_unblocked def blocked? @blocked end # Parses an amqp[s] URI into a hash that {Bunny::Session#initialize} accepts. # # @param [String] uri amqp or amqps URI to parse # @return [Hash] Parsed URI as a hash def self.parse_uri(uri) AMQ::Settings.parse_amqp_url(uri) end # Checks if a queue with given name exists. # # Implemented using queue.declare # with passive set to true and a one-off (short lived) channel # under the hood. # # @param [String] name Queue name # @return [Boolean] true if queue exists def queue_exists?(name) ch = create_channel begin ch.queue(name, :passive => true) true rescue Bunny::NotFound => _ false ensure ch.close if ch.open? end end # Checks if a exchange with given name exists. # # Implemented using exchange.declare # with passive set to true and a one-off (short lived) channel # under the hood. # # @param [String] name Exchange name # @return [Boolean] true if exchange exists def exchange_exists?(name) ch = create_channel begin ch.exchange(name, :passive => true) true rescue Bunny::NotFound => _ false ensure ch.close if ch.open? end end # # Implementation # # @private def open_channel(ch) n = ch.number self.register_channel(ch) @transport_mutex.synchronize do @transport.send_frame(AMQ::Protocol::Channel::Open.encode(n, AMQ::Protocol::EMPTY_STRING)) end @last_channel_open_ok = wait_on_continuations raise_if_continuation_resulted_in_a_connection_error! @last_channel_open_ok end # @private def close_channel(ch) n = ch.number @transport.send_frame(AMQ::Protocol::Channel::Close.encode(n, 200, "Goodbye", 0, 0)) @last_channel_close_ok = wait_on_continuations raise_if_continuation_resulted_in_a_connection_error! self.unregister_channel(ch) @last_channel_close_ok end # @private def close_all_channels @channels.reject {|n, ch| n == 0 || !ch.open? }.each do |_, ch| Bunny::Timeout.timeout(@transport.disconnect_timeout, ClientTimeout) { ch.close } end end # @private def close_connection(sync = true) if @transport.open? @transport.send_frame(AMQ::Protocol::Connection::Close.encode(200, "Goodbye", 0, 0)) maybe_shutdown_heartbeat_sender @status = :not_connected if sync @last_connection_close_ok = wait_on_continuations end end end # Handles incoming frames and dispatches them. # # Channel methods (`channel.open-ok`, `channel.close-ok`) are # handled by the session itself. # Connection level errors result in exceptions being raised. # Deliveries and other methods are passed on to channels to dispatch. # # @private def handle_frame(ch_number, method) @logger.debug "Session#handle_frame on #{ch_number}: #{method.inspect}" case method when AMQ::Protocol::Channel::OpenOk then @continuations.push(method) when AMQ::Protocol::Channel::CloseOk then @continuations.push(method) when AMQ::Protocol::Connection::Close then @last_connection_error = instantiate_connection_level_exception(method) @continuations.push(method) @origin_thread.raise(@last_connection_error) when AMQ::Protocol::Connection::CloseOk then @last_connection_close_ok = method begin @continuations.clear rescue StandardError => e @logger.error e.class.name @logger.error e.message @logger.error e.backtrace ensure @continuations.push(:__unblock__) end when AMQ::Protocol::Connection::Blocked then @blocked = true @block_callback.call(method) if @block_callback when AMQ::Protocol::Connection::Unblocked then @blocked = false @unblock_callback.call(method) if @unblock_callback when AMQ::Protocol::Channel::Close then begin ch = @channels[ch_number] ch.handle_method(method) ensure self.unregister_channel(ch) end when AMQ::Protocol::Basic::GetEmpty then @channels[ch_number].handle_basic_get_empty(method) else if ch = @channels[ch_number] ch.handle_method(method) else @logger.warn "Channel #{ch_number} is not open on this connection!" end end end # @private def raise_if_continuation_resulted_in_a_connection_error! raise @last_connection_error if @last_connection_error end # @private def handle_frameset(ch_number, frames) method = frames.first case method when AMQ::Protocol::Basic::GetOk then @channels[ch_number].handle_basic_get_ok(*frames) when AMQ::Protocol::Basic::GetEmpty then @channels[ch_number].handle_basic_get_empty(*frames) when AMQ::Protocol::Basic::Return then @channels[ch_number].handle_basic_return(*frames) else @channels[ch_number].handle_frameset(*frames) end end # @private def handle_network_failure(exception) raise NetworkErrorWrapper.new(exception) unless @threaded @status = :disconnected if !recovering_from_network_failure? @recovering_from_network_failure = true if recoverable_network_failure?(exception) @logger.warn "Recovering from a network failure..." @channels.each do |n, ch| ch.maybe_kill_consumer_work_pool! end maybe_shutdown_heartbeat_sender recover_from_network_failure else # TODO: investigate if we can be a bit smarter here. MK. end end end # @private def recoverable_network_failure?(exception) # TODO: investigate if we can be a bit smarter here. MK. true end # @private def recovering_from_network_failure? @recovering_from_network_failure end # @private def recover_from_network_failure begin sleep @network_recovery_interval @logger.debug "About to start connection recovery..." self.initialize_transport self.start if open? @recovering_from_network_failure = false recover_channels end rescue TCPConnectionFailed, AMQ::Protocol::EmptyResponseError => e @logger.warn "TCP connection failed, reconnecting in 5 seconds" sleep @network_recovery_interval retry if recoverable_network_failure?(e) end end # @private def recover_channels # default channel is reopened right after connection # negotiation is completed, so make sure we do not try to open # it twice. MK. @channels.reject { |n, ch| ch == @default_channel }.each do |n, ch| ch.open ch.recover_from_network_failure end end # @private def instantiate_connection_level_exception(frame) case frame when AMQ::Protocol::Connection::Close then klass = case frame.reply_code when 320 then ConnectionForced when 501 then FrameError when 503 then CommandInvalid when 504 then ChannelError when 505 then UnexpectedFrame when 506 then ResourceError when 541 then InternalError else raise "Unknown reply code: #{frame.reply_code}, text: #{frame.reply_text}" end klass.new("Connection-level error: #{frame.reply_text}", self, frame) end end # @private def hostname_from(options) options[:host] || options[:hostname] || DEFAULT_HOST end # @private def port_from(options) fallback = if options[:tls] || options[:ssl] AMQ::Protocol::TLS_PORT else AMQ::Protocol::DEFAULT_PORT end options.fetch(:port, fallback) end # @private def vhost_from(options) options[:virtual_host] || options[:vhost] || DEFAULT_VHOST end # @private def username_from(options) options[:username] || options[:user] || DEFAULT_USER end # @private def password_from(options) options[:password] || options[:pass] || options[:pwd] || DEFAULT_PASSWORD end # @private def heartbeat_from(options) options[:heartbeat] || options[:heartbeat_interval] || options[:requested_heartbeat] || DEFAULT_HEARTBEAT end # @private def next_channel_id @channel_id_allocator.next_channel_id end # @private def release_channel_id(i) @channel_id_allocator.release_channel_id(i) end # @private def register_channel(ch) @channel_mutex.synchronize do @channels[ch.number] = ch end end # @private def unregister_channel(ch) @channel_mutex.synchronize do n = ch.number self.release_channel_id(n) @channels.delete(ch.number) end end # @private def start_reader_loop reader_loop.start end # @private def reader_loop @reader_loop ||= ReaderLoop.new(@transport, self, Thread.current) end # @private def maybe_shutdown_reader_loop if @reader_loop @reader_loop.stop if threaded? # this is the easiest way to wait until the loop # is guaranteed to have terminated @reader_loop.raise(ShutdownSignal) # joining the thread here may take forever # on JRuby because sun.nio.ch.KQueueArrayWrapper#kevent0 is # a native method that cannot be (easily) interrupted. # So we use this ugly hack or else our test suite takes forever # to run on JRuby (a new connection is opened/closed per example). MK. if defined?(JRUBY_VERSION) sleep 0.075 else @reader_loop.join end else # single threaded mode, nothing to do. MK. end end @reader_loop = nil end # @private def close_transport begin @transport.close rescue StandardError => e @logger.error "Exception when closing transport:" @logger.error e.class.name @logger.error e.message @logger.error e.backtrace end end # @private def signal_activity! @heartbeat_sender.signal_activity! if @heartbeat_sender end # Sends frame to the peer, checking that connection is open. # Exposed primarily for Bunny::Channel # # @raise [ConnectionClosedError] # @private def send_frame(frame, signal_activity = true) if open? @transport.write(frame.encode) signal_activity! if signal_activity else raise ConnectionClosedError.new(frame) end end # Sends frame to the peer, checking that connection is open. # Uses transport implementation that does not perform # timeout control. Exposed primarily for Bunny::Channel. # # @raise [ConnectionClosedError] # @private def send_frame_without_timeout(frame, signal_activity = true) if open? @transport.write_without_timeout(frame.encode) signal_activity! if signal_activity else raise ConnectionClosedError.new(frame) end end # Sends multiple frames, one by one. For thread safety this method takes a channel # object and synchronizes on it. # # @private def send_frameset(frames, channel) # some developers end up sharing channels between threads and when multiple # threads publish on the same channel aggressively, at some point frames will be # delivered out of order and broker will raise 505 UNEXPECTED_FRAME exception. # If we synchronize on the channel, however, this is both thread safe and pretty fine-grained # locking. Note that "single frame" methods do not need this kind of synchronization. MK. channel.synchronize do frames.each { |frame| self.send_frame(frame, false) } signal_activity! end end # send_frameset(frames) # Sends multiple frames, one by one. For thread safety this method takes a channel # object and synchronizes on it. Uses transport implementation that does not perform # timeout control. # # @private def send_frameset_without_timeout(frames, channel) # some developers end up sharing channels between threads and when multiple # threads publish on the same channel aggressively, at some point frames will be # delivered out of order and broker will raise 505 UNEXPECTED_FRAME exception. # If we synchronize on the channel, however, this is both thread safe and pretty fine-grained # locking. Note that "single frame" methods do not need this kind of synchronization. MK. channel.synchronize do frames.each { |frame| self.send_frame_without_timeout(frame, false) } signal_activity! end end # send_frameset_without_timeout(frames) # @private def send_raw_without_timeout(data, channel) # some developers end up sharing channels between threads and when multiple # threads publish on the same channel aggressively, at some point frames will be # delivered out of order and broker will raise 505 UNEXPECTED_FRAME exception. # If we synchronize on the channel, however, this is both thread safe and pretty fine-grained # locking. Note that "single frame" methods do not need this kind of synchronization. MK. channel.synchronize do @transport.write(data) signal_activity! end end # send_frameset_without_timeout(frames) # @return [String] # @api public def to_s "#<#{self.class.name}:#{object_id} #{@user}@#{@host}:#{@port}, vhost=#{@vhost}>" end protected # @private def init_connection self.send_preamble connection_start = @transport.read_next_frame.decode_payload @server_properties = connection_start.server_properties @server_capabilities = @server_properties["capabilities"] @server_authentication_mechanisms = (connection_start.mechanisms || "").split(" ") @server_locales = Array(connection_start.locales) @status = :connected end # @private def open_connection @transport.send_frame(AMQ::Protocol::Connection::StartOk.encode(@client_properties, @mechanism, self.encode_credentials(username, password), @locale)) @logger.debug "Sent connection.start-ok" frame = begin @transport.read_next_frame # frame timeout means the broker has closed the TCP connection, which it # does per 0.9.1 spec. rescue Errno::ECONNRESET, ClientTimeout, AMQ::Protocol::EmptyResponseError, EOFError, IOError => e nil end if frame.nil? @state = :closed @logger.error "RabbitMQ closed TCP connection before AMQP 0.9.1 connection was finalized. Most likely this means authentication failure." raise Bunny::PossibleAuthenticationFailureError.new(self.user, self.vhost, self.password.size) end response = frame.decode_payload if response.is_a?(AMQ::Protocol::Connection::Close) @state = :closed @logger.error "Authentication with RabbitMQ failed: #{response.reply_code} #{response.reply_text}" raise Bunny::AuthenticationFailureError.new(self.user, self.vhost, self.password.size) end connection_tune = response @frame_max = negotiate_value(@client_frame_max, connection_tune.frame_max) @channel_max = negotiate_value(@client_channel_max, connection_tune.channel_max) # this allows for disabled heartbeats. MK. @heartbeat = if heartbeat_disabled?(@client_heartbeat) 0 else negotiate_value(@client_heartbeat, connection_tune.heartbeat) end @logger.debug "Heartbeat interval negotiation: client = #{@client_heartbeat}, server = #{connection_tune.heartbeat}, result = #{@heartbeat}" @logger.info "Heartbeat interval used (in seconds): #{@heartbeat}" @channel_id_allocator = ChannelIdAllocator.new(@channel_max) @transport.send_frame(AMQ::Protocol::Connection::TuneOk.encode(@channel_max, @frame_max, @heartbeat)) @logger.debug "Sent connection.tune-ok with heartbeat interval = #{@heartbeat}, frame_max = #{@frame_max}, channel_max = #{@channel_max}" @transport.send_frame(AMQ::Protocol::Connection::Open.encode(self.vhost)) @logger.debug "Sent connection.open with vhost = #{self.vhost}" frame2 = begin @transport.read_next_frame # frame timeout means the broker has closed the TCP connection, which it # does per 0.9.1 spec. rescue Errno::ECONNRESET, ClientTimeout, AMQ::Protocol::EmptyResponseError, EOFError => e nil end if frame2.nil? @state = :closed @logger.warn "RabbitMQ closed TCP connection before AMQP 0.9.1 connection was finalized. Most likely this means authentication failure." raise Bunny::PossibleAuthenticationFailureError.new(self.user, self.vhost, self.password.size) end connection_open_ok = frame2.decode_payload @status = :open if @heartbeat && @heartbeat > 0 initialize_heartbeat_sender end raise "could not open connection: server did not respond with connection.open-ok" unless connection_open_ok.is_a?(AMQ::Protocol::Connection::OpenOk) end def heartbeat_disabled?(val) 0 == val || val.nil? end # @private def negotiate_value(client_value, server_value) return server_value if client_value == :server if client_value == 0 || server_value == 0 [client_value, server_value].max else [client_value, server_value].min end end # @private def initialize_heartbeat_sender maybe_shutdown_heartbeat_sender @logger.debug "Initializing heartbeat sender..." @heartbeat_sender = HeartbeatSender.new(@transport, @logger) @heartbeat_sender.start(@heartbeat) end # @private def maybe_shutdown_heartbeat_sender @heartbeat_sender.stop if @heartbeat_sender end # @private def initialize_transport @transport = Transport.new(self, @host, @port, @opts.merge(:session_thread => @origin_thread)) end # @private def maybe_close_transport @transport.close if @transport end # Sends AMQ protocol header (also known as preamble). # @private def send_preamble @transport.write(AMQ::Protocol::PREAMBLE) @logger.debug "Sent protocol preamble" end # @private def encode_credentials(username, password) @credentials_encoder.encode_credentials(username, password) end # encode_credentials(username, password) # @private def credentials_encoder_for(mechanism) Authentication::CredentialsEncoder.for_session(self) end if defined?(JRUBY_VERSION) # @private def reset_continuations @continuations = Concurrent::LinkedContinuationQueue.new end else # @private def reset_continuations @continuations = Concurrent::ContinuationQueue.new end end # @private def wait_on_continuations unless @threaded reader_loop.run_once until @continuations.length > 0 end @continuations.poll(@continuation_timeout) end # @private def init_logger(level) lgr = ::Logger.new(@logfile) lgr.level = normalize_log_level(level) lgr.progname = self.to_s lgr end # @private def normalize_log_level(level) case level when :debug, Logger::DEBUG, "debug" then Logger::DEBUG when :info, Logger::INFO, "info" then Logger::INFO when :warn, Logger::WARN, "warn" then Logger::WARN when :error, Logger::ERROR, "error" then Logger::ERROR when :fatal, Logger::FATAL, "fatal" then Logger::FATAL else Logger::WARN end end end # Session # backwards compatibility Client = Session end Shut down consumer work pools when connection is closed References #172. require "socket" require "thread" require "monitor" require "bunny/transport" require "bunny/channel_id_allocator" require "bunny/heartbeat_sender" require "bunny/reader_loop" require "bunny/authentication/credentials_encoder" require "bunny/authentication/plain_mechanism_encoder" require "bunny/authentication/external_mechanism_encoder" if defined?(JRUBY_VERSION) require "bunny/concurrent/linked_continuation_queue" else require "bunny/concurrent/continuation_queue" end require "amq/protocol/client" require "amq/settings" module Bunny # Represents AMQP 0.9.1 connection (to a RabbitMQ node). # @see http://rubybunny.info/articles/connecting.html Connecting to RabbitMQ guide class Session # Default host used for connection DEFAULT_HOST = "127.0.0.1" # Default virtual host used for connection DEFAULT_VHOST = "/" # Default username used for connection DEFAULT_USER = "guest" # Default password used for connection DEFAULT_PASSWORD = "guest" # Default heartbeat interval, the same value as RabbitMQ 3.0 uses. DEFAULT_HEARTBEAT = :server # @private DEFAULT_FRAME_MAX = 131072 # backwards compatibility # @private CONNECT_TIMEOUT = Transport::DEFAULT_CONNECTION_TIMEOUT # @private DEFAULT_CONTINUATION_TIMEOUT = if RUBY_VERSION.to_f < 1.9 8000 else 4000 end # RabbitMQ client metadata DEFAULT_CLIENT_PROPERTIES = { :capabilities => { :publisher_confirms => true, :consumer_cancel_notify => true, :exchange_exchange_bindings => true, :"basic.nack" => true, :"connection.blocked" => true, # See http://www.rabbitmq.com/auth-notification.html :authentication_failure_close => true }, :product => "Bunny", :platform => ::RUBY_DESCRIPTION, :version => Bunny::VERSION, :information => "http://rubybunny.info", } # @private DEFAULT_LOCALE = "en_GB" # Default reconnection interval for TCP connection failures DEFAULT_NETWORK_RECOVERY_INTERVAL = 5.0 # # API # # @return [Bunny::Transport] attr_reader :transport attr_reader :status, :host, :port, :heartbeat, :user, :pass, :vhost, :frame_max, :threaded attr_reader :server_capabilities, :server_properties, :server_authentication_mechanisms, :server_locales attr_reader :default_channel attr_reader :channel_id_allocator # Authentication mechanism, e.g. "PLAIN" or "EXTERNAL" # @return [String] attr_reader :mechanism # @return [Logger] attr_reader :logger # @return [Integer] Timeout for blocking protocol operations (queue.declare, queue.bind, etc), in milliseconds. Default is 4000. attr_reader :continuation_timeout # @param [String, Hash] connection_string_or_opts Connection string or a hash of connection options # @param [Hash] optz Extra options not related to connection # # @option connection_string_or_opts [String] :host ("127.0.0.1") Hostname or IP address to connect to # @option connection_string_or_opts [Integer] :port (5672) Port RabbitMQ listens on # @option connection_string_or_opts [String] :username ("guest") Username # @option connection_string_or_opts [String] :password ("guest") Password # @option connection_string_or_opts [String] :vhost ("/") Virtual host to use # @option connection_string_or_opts [Integer] :heartbeat (600) Heartbeat interval. 0 means no heartbeat. # @option connection_string_or_opts [Integer] :network_recovery_interval (4) Recovery interval periodic network recovery will use. This includes initial pause after network failure. # @option connection_string_or_opts [Boolean] :tls (false) Should TLS/SSL be used? # @option connection_string_or_opts [String] :tls_cert (nil) Path to client TLS/SSL certificate file (.pem) # @option connection_string_or_opts [String] :tls_key (nil) Path to client TLS/SSL private key file (.pem) # @option connection_string_or_opts [Array<String>] :tls_ca_certificates Array of paths to TLS/SSL CA files (.pem), by default detected from OpenSSL configuration # @option connection_string_or_opts [Integer] :continuation_timeout (4000) Timeout for client operations that expect a response (e.g. {Bunny::Queue#get}), in milliseconds. # @option connection_string_or_opts [Integer] :connection_timeout (5) Timeout in seconds for connecting to the server. # # @option optz [String] :auth_mechanism ("PLAIN") Authentication mechanism, PLAIN or EXTERNAL # @option optz [String] :locale ("PLAIN") Locale RabbitMQ should use # # @see http://rubybunny.info/articles/connecting.html Connecting to RabbitMQ guide # @see http://rubybunny.info/articles/tls.html TLS/SSL guide # @api public def initialize(connection_string_or_opts = Hash.new, optz = Hash.new) opts = case (ENV["RABBITMQ_URL"] || connection_string_or_opts) when nil then Hash.new when String then self.class.parse_uri(ENV["RABBITMQ_URL"] || connection_string_or_opts) when Hash then connection_string_or_opts end.merge(optz) @opts = opts @host = self.hostname_from(opts) @port = self.port_from(opts) @user = self.username_from(opts) @pass = self.password_from(opts) @vhost = self.vhost_from(opts) @logfile = opts[:log_file] || opts[:logfile] || STDOUT @threaded = opts.fetch(:threaded, true) @logger = opts.fetch(:logger, init_logger(opts[:log_level] || ENV["BUNNY_LOG_LEVEL"] || Logger::WARN)) # should automatic recovery from network failures be used? @automatically_recover = if opts[:automatically_recover].nil? && opts[:automatic_recovery].nil? true else opts[:automatically_recover] || opts[:automatic_recovery] end @network_recovery_interval = opts.fetch(:network_recovery_interval, DEFAULT_NETWORK_RECOVERY_INTERVAL) # in ms @continuation_timeout = opts.fetch(:continuation_timeout, DEFAULT_CONTINUATION_TIMEOUT) @status = :not_connected @blocked = false # these are negotiated with the broker during the connection tuning phase @client_frame_max = opts.fetch(:frame_max, DEFAULT_FRAME_MAX) @client_channel_max = opts.fetch(:channel_max, 65536) @client_heartbeat = self.heartbeat_from(opts) @client_properties = opts[:properties] || DEFAULT_CLIENT_PROPERTIES @mechanism = opts.fetch(:auth_mechanism, "PLAIN") @credentials_encoder = credentials_encoder_for(@mechanism) @locale = @opts.fetch(:locale, DEFAULT_LOCALE) @mutex_impl = @opts.fetch(:mutex_impl, Monitor) # mutex for the channel id => channel hash @channel_mutex = @mutex_impl.new # transport operations/continuations mutex. A workaround for # the non-reentrant Ruby mutexes. MK. @transport_mutex = @mutex_impl.new @channels = Hash.new @origin_thread = Thread.current self.reset_continuations self.initialize_transport end # @return [String] RabbitMQ hostname (or IP address) used def hostname; self.host; end # @return [String] Username used def username; self.user; end # @return [String] Password used def password; self.pass; end # @return [String] Virtual host used def virtual_host; self.vhost; end # @return [Integer] Heartbeat interval used def heartbeat_interval; self.heartbeat; end # @return [Boolean] true if this connection uses TLS (SSL) def uses_tls? @transport.uses_tls? end alias tls? uses_tls? # @return [Boolean] true if this connection uses TLS (SSL) def uses_ssl? @transport.uses_ssl? end alias ssl? uses_ssl? # @return [Boolean] true if this connection uses a separate thread for I/O activity def threaded? @threaded end # @private attr_reader :mutex_impl # Provides a way to fine tune the socket used by connection. # Accepts a block that the socket will be yielded to. def configure_socket(&block) raise ArgumentError, "No block provided!" if block.nil? @transport.configure_socket(&block) end # Starts the connection process. # # @see http://rubybunny.info/articles/getting_started.html # @see http://rubybunny.info/articles/connecting.html # @api public def start return self if connected? @status = :connecting # reset here for cases when automatic network recovery kicks in # when we were blocked. MK. @blocked = false self.reset_continuations begin # close existing transport if we have one, # to not leak sockets @transport.maybe_initialize_socket @transport.post_initialize_socket @transport.connect if @socket_configurator @transport.configure_socket(&@socket_configurator) end self.init_connection self.open_connection @reader_loop = nil self.start_reader_loop if threaded? @default_channel = self.create_channel rescue Exception => e @status = :not_connected raise e end self end # Socket operation timeout used by this connection # @return [Integer] # @private def read_write_timeout @transport.read_write_timeout end # Opens a new channel and returns it. This method will block the calling # thread until the response is received and the channel is guaranteed to be # opened (this operation is very fast and inexpensive). # # @return [Bunny::Channel] Newly opened channel def create_channel(n = nil, consumer_pool_size = 1) if n && (ch = @channels[n]) ch else ch = Bunny::Channel.new(self, n, ConsumerWorkPool.new(consumer_pool_size || 1)) ch.open ch end end alias channel create_channel # Closes the connection. This involves closing all of its channels. def close if @transport.open? close_all_channels Bunny::Timeout.timeout(@transport.disconnect_timeout, ClientTimeout) do self.close_connection(true) end maybe_shutdown_reader_loop close_transport end shut_down_all_consumer_work_pools @status = :closed end alias stop close # Creates a temporary channel, yields it to the block given to this # method and closes it. # # @return [Bunny::Session] self def with_channel(n = nil) ch = create_channel(n) yield ch ch.close if ch.open? self end # @return [Boolean] true if this connection is still not fully open def connecting? status == :connecting end # @return [Boolean] true if this AMQP 0.9.1 connection is closed def closed? status == :closed end # @return [Boolean] true if this AMQP 0.9.1 connection is open def open? (status == :open || status == :connected || status == :connecting) && @transport.open? end alias connected? open? # @return [Boolean] true if this connection has automatic recovery from network failure enabled def automatically_recover? @automatically_recover end # # Backwards compatibility # # @private def queue(*args) @default_channel.queue(*args) end # @private def direct(*args) @default_channel.direct(*args) end # @private def fanout(*args) @default_channel.fanout(*args) end # @private def topic(*args) @default_channel.topic(*args) end # @private def headers(*args) @default_channel.headers(*args) end # @private def exchange(*args) @default_channel.exchange(*args) end # Defines a callback that will be executed when RabbitMQ blocks the connection # because it is running low on memory or disk space (as configured via config file # and/or rabbitmqctl). # # @yield [AMQ::Protocol::Connection::Blocked] connection.blocked method which provides a reason for blocking # # @api public def on_blocked(&block) @block_callback = block end # Defines a callback that will be executed when RabbitMQ unblocks the connection # that was previously blocked, e.g. because the memory or disk space alarm has cleared. # # @see #on_blocked # @api public def on_unblocked(&block) @unblock_callback = block end # @return [Boolean] true if the connection is currently blocked by RabbitMQ because it's running low on # RAM, disk space, or other resource; false otherwise # @see #on_blocked # @see #on_unblocked def blocked? @blocked end # Parses an amqp[s] URI into a hash that {Bunny::Session#initialize} accepts. # # @param [String] uri amqp or amqps URI to parse # @return [Hash] Parsed URI as a hash def self.parse_uri(uri) AMQ::Settings.parse_amqp_url(uri) end # Checks if a queue with given name exists. # # Implemented using queue.declare # with passive set to true and a one-off (short lived) channel # under the hood. # # @param [String] name Queue name # @return [Boolean] true if queue exists def queue_exists?(name) ch = create_channel begin ch.queue(name, :passive => true) true rescue Bunny::NotFound => _ false ensure ch.close if ch.open? end end # Checks if a exchange with given name exists. # # Implemented using exchange.declare # with passive set to true and a one-off (short lived) channel # under the hood. # # @param [String] name Exchange name # @return [Boolean] true if exchange exists def exchange_exists?(name) ch = create_channel begin ch.exchange(name, :passive => true) true rescue Bunny::NotFound => _ false ensure ch.close if ch.open? end end # # Implementation # # @private def open_channel(ch) n = ch.number self.register_channel(ch) @transport_mutex.synchronize do @transport.send_frame(AMQ::Protocol::Channel::Open.encode(n, AMQ::Protocol::EMPTY_STRING)) end @last_channel_open_ok = wait_on_continuations raise_if_continuation_resulted_in_a_connection_error! @last_channel_open_ok end # @private def close_channel(ch) n = ch.number @transport.send_frame(AMQ::Protocol::Channel::Close.encode(n, 200, "Goodbye", 0, 0)) @last_channel_close_ok = wait_on_continuations raise_if_continuation_resulted_in_a_connection_error! self.unregister_channel(ch) @last_channel_close_ok end # @private def close_all_channels @channels.reject {|n, ch| n == 0 || !ch.open? }.each do |_, ch| Bunny::Timeout.timeout(@transport.disconnect_timeout, ClientTimeout) { ch.close } end end # @private def close_connection(sync = true) if @transport.open? @transport.send_frame(AMQ::Protocol::Connection::Close.encode(200, "Goodbye", 0, 0)) if sync @last_connection_close_ok = wait_on_continuations end end shut_down_all_consumer_work_pools maybe_shutdown_heartbeat_sender @status = :not_connected end # Handles incoming frames and dispatches them. # # Channel methods (`channel.open-ok`, `channel.close-ok`) are # handled by the session itself. # Connection level errors result in exceptions being raised. # Deliveries and other methods are passed on to channels to dispatch. # # @private def handle_frame(ch_number, method) @logger.debug "Session#handle_frame on #{ch_number}: #{method.inspect}" case method when AMQ::Protocol::Channel::OpenOk then @continuations.push(method) when AMQ::Protocol::Channel::CloseOk then @continuations.push(method) when AMQ::Protocol::Connection::Close then @last_connection_error = instantiate_connection_level_exception(method) @continuations.push(method) @origin_thread.raise(@last_connection_error) when AMQ::Protocol::Connection::CloseOk then @last_connection_close_ok = method begin @continuations.clear rescue StandardError => e @logger.error e.class.name @logger.error e.message @logger.error e.backtrace ensure @continuations.push(:__unblock__) end when AMQ::Protocol::Connection::Blocked then @blocked = true @block_callback.call(method) if @block_callback when AMQ::Protocol::Connection::Unblocked then @blocked = false @unblock_callback.call(method) if @unblock_callback when AMQ::Protocol::Channel::Close then begin ch = @channels[ch_number] ch.handle_method(method) ensure self.unregister_channel(ch) end when AMQ::Protocol::Basic::GetEmpty then @channels[ch_number].handle_basic_get_empty(method) else if ch = @channels[ch_number] ch.handle_method(method) else @logger.warn "Channel #{ch_number} is not open on this connection!" end end end # @private def raise_if_continuation_resulted_in_a_connection_error! raise @last_connection_error if @last_connection_error end # @private def handle_frameset(ch_number, frames) method = frames.first case method when AMQ::Protocol::Basic::GetOk then @channels[ch_number].handle_basic_get_ok(*frames) when AMQ::Protocol::Basic::GetEmpty then @channels[ch_number].handle_basic_get_empty(*frames) when AMQ::Protocol::Basic::Return then @channels[ch_number].handle_basic_return(*frames) else @channels[ch_number].handle_frameset(*frames) end end # @private def handle_network_failure(exception) raise NetworkErrorWrapper.new(exception) unless @threaded @status = :disconnected if !recovering_from_network_failure? @recovering_from_network_failure = true if recoverable_network_failure?(exception) @logger.warn "Recovering from a network failure..." @channels.each do |n, ch| ch.maybe_kill_consumer_work_pool! end maybe_shutdown_heartbeat_sender recover_from_network_failure else # TODO: investigate if we can be a bit smarter here. MK. end end end # @private def recoverable_network_failure?(exception) # TODO: investigate if we can be a bit smarter here. MK. true end # @private def recovering_from_network_failure? @recovering_from_network_failure end # @private def recover_from_network_failure begin sleep @network_recovery_interval @logger.debug "About to start connection recovery..." self.initialize_transport self.start if open? @recovering_from_network_failure = false recover_channels end rescue TCPConnectionFailed, AMQ::Protocol::EmptyResponseError => e @logger.warn "TCP connection failed, reconnecting in 5 seconds" sleep @network_recovery_interval retry if recoverable_network_failure?(e) end end # @private def recover_channels # default channel is reopened right after connection # negotiation is completed, so make sure we do not try to open # it twice. MK. @channels.reject { |n, ch| ch == @default_channel }.each do |n, ch| ch.open ch.recover_from_network_failure end end # @private def instantiate_connection_level_exception(frame) case frame when AMQ::Protocol::Connection::Close then klass = case frame.reply_code when 320 then ConnectionForced when 501 then FrameError when 503 then CommandInvalid when 504 then ChannelError when 505 then UnexpectedFrame when 506 then ResourceError when 541 then InternalError else raise "Unknown reply code: #{frame.reply_code}, text: #{frame.reply_text}" end klass.new("Connection-level error: #{frame.reply_text}", self, frame) end end # @private def hostname_from(options) options[:host] || options[:hostname] || DEFAULT_HOST end # @private def port_from(options) fallback = if options[:tls] || options[:ssl] AMQ::Protocol::TLS_PORT else AMQ::Protocol::DEFAULT_PORT end options.fetch(:port, fallback) end # @private def vhost_from(options) options[:virtual_host] || options[:vhost] || DEFAULT_VHOST end # @private def username_from(options) options[:username] || options[:user] || DEFAULT_USER end # @private def password_from(options) options[:password] || options[:pass] || options[:pwd] || DEFAULT_PASSWORD end # @private def heartbeat_from(options) options[:heartbeat] || options[:heartbeat_interval] || options[:requested_heartbeat] || DEFAULT_HEARTBEAT end # @private def next_channel_id @channel_id_allocator.next_channel_id end # @private def release_channel_id(i) @channel_id_allocator.release_channel_id(i) end # @private def register_channel(ch) @channel_mutex.synchronize do @channels[ch.number] = ch end end # @private def unregister_channel(ch) @channel_mutex.synchronize do n = ch.number self.release_channel_id(n) @channels.delete(ch.number) end end # @private def start_reader_loop reader_loop.start end # @private def reader_loop @reader_loop ||= ReaderLoop.new(@transport, self, Thread.current) end # @private def maybe_shutdown_reader_loop if @reader_loop @reader_loop.stop if threaded? # this is the easiest way to wait until the loop # is guaranteed to have terminated @reader_loop.raise(ShutdownSignal) # joining the thread here may take forever # on JRuby because sun.nio.ch.KQueueArrayWrapper#kevent0 is # a native method that cannot be (easily) interrupted. # So we use this ugly hack or else our test suite takes forever # to run on JRuby (a new connection is opened/closed per example). MK. if defined?(JRUBY_VERSION) sleep 0.075 else @reader_loop.join end else # single threaded mode, nothing to do. MK. end end @reader_loop = nil end # @private def close_transport begin @transport.close rescue StandardError => e @logger.error "Exception when closing transport:" @logger.error e.class.name @logger.error e.message @logger.error e.backtrace end end # @private def signal_activity! @heartbeat_sender.signal_activity! if @heartbeat_sender end # Sends frame to the peer, checking that connection is open. # Exposed primarily for Bunny::Channel # # @raise [ConnectionClosedError] # @private def send_frame(frame, signal_activity = true) if open? @transport.write(frame.encode) signal_activity! if signal_activity else raise ConnectionClosedError.new(frame) end end # Sends frame to the peer, checking that connection is open. # Uses transport implementation that does not perform # timeout control. Exposed primarily for Bunny::Channel. # # @raise [ConnectionClosedError] # @private def send_frame_without_timeout(frame, signal_activity = true) if open? @transport.write_without_timeout(frame.encode) signal_activity! if signal_activity else raise ConnectionClosedError.new(frame) end end # Sends multiple frames, one by one. For thread safety this method takes a channel # object and synchronizes on it. # # @private def send_frameset(frames, channel) # some developers end up sharing channels between threads and when multiple # threads publish on the same channel aggressively, at some point frames will be # delivered out of order and broker will raise 505 UNEXPECTED_FRAME exception. # If we synchronize on the channel, however, this is both thread safe and pretty fine-grained # locking. Note that "single frame" methods do not need this kind of synchronization. MK. channel.synchronize do frames.each { |frame| self.send_frame(frame, false) } signal_activity! end end # send_frameset(frames) # Sends multiple frames, one by one. For thread safety this method takes a channel # object and synchronizes on it. Uses transport implementation that does not perform # timeout control. # # @private def send_frameset_without_timeout(frames, channel) # some developers end up sharing channels between threads and when multiple # threads publish on the same channel aggressively, at some point frames will be # delivered out of order and broker will raise 505 UNEXPECTED_FRAME exception. # If we synchronize on the channel, however, this is both thread safe and pretty fine-grained # locking. Note that "single frame" methods do not need this kind of synchronization. MK. channel.synchronize do frames.each { |frame| self.send_frame_without_timeout(frame, false) } signal_activity! end end # send_frameset_without_timeout(frames) # @private def send_raw_without_timeout(data, channel) # some developers end up sharing channels between threads and when multiple # threads publish on the same channel aggressively, at some point frames will be # delivered out of order and broker will raise 505 UNEXPECTED_FRAME exception. # If we synchronize on the channel, however, this is both thread safe and pretty fine-grained # locking. Note that "single frame" methods do not need this kind of synchronization. MK. channel.synchronize do @transport.write(data) signal_activity! end end # send_frameset_without_timeout(frames) # @return [String] # @api public def to_s "#<#{self.class.name}:#{object_id} #{@user}@#{@host}:#{@port}, vhost=#{@vhost}>" end protected # @private def init_connection self.send_preamble connection_start = @transport.read_next_frame.decode_payload @server_properties = connection_start.server_properties @server_capabilities = @server_properties["capabilities"] @server_authentication_mechanisms = (connection_start.mechanisms || "").split(" ") @server_locales = Array(connection_start.locales) @status = :connected end # @private def open_connection @transport.send_frame(AMQ::Protocol::Connection::StartOk.encode(@client_properties, @mechanism, self.encode_credentials(username, password), @locale)) @logger.debug "Sent connection.start-ok" frame = begin @transport.read_next_frame # frame timeout means the broker has closed the TCP connection, which it # does per 0.9.1 spec. rescue Errno::ECONNRESET, ClientTimeout, AMQ::Protocol::EmptyResponseError, EOFError, IOError => e nil end if frame.nil? @state = :closed @logger.error "RabbitMQ closed TCP connection before AMQP 0.9.1 connection was finalized. Most likely this means authentication failure." raise Bunny::PossibleAuthenticationFailureError.new(self.user, self.vhost, self.password.size) end response = frame.decode_payload if response.is_a?(AMQ::Protocol::Connection::Close) @state = :closed @logger.error "Authentication with RabbitMQ failed: #{response.reply_code} #{response.reply_text}" raise Bunny::AuthenticationFailureError.new(self.user, self.vhost, self.password.size) end connection_tune = response @frame_max = negotiate_value(@client_frame_max, connection_tune.frame_max) @channel_max = negotiate_value(@client_channel_max, connection_tune.channel_max) # this allows for disabled heartbeats. MK. @heartbeat = if heartbeat_disabled?(@client_heartbeat) 0 else negotiate_value(@client_heartbeat, connection_tune.heartbeat) end @logger.debug "Heartbeat interval negotiation: client = #{@client_heartbeat}, server = #{connection_tune.heartbeat}, result = #{@heartbeat}" @logger.info "Heartbeat interval used (in seconds): #{@heartbeat}" @channel_id_allocator = ChannelIdAllocator.new(@channel_max) @transport.send_frame(AMQ::Protocol::Connection::TuneOk.encode(@channel_max, @frame_max, @heartbeat)) @logger.debug "Sent connection.tune-ok with heartbeat interval = #{@heartbeat}, frame_max = #{@frame_max}, channel_max = #{@channel_max}" @transport.send_frame(AMQ::Protocol::Connection::Open.encode(self.vhost)) @logger.debug "Sent connection.open with vhost = #{self.vhost}" frame2 = begin @transport.read_next_frame # frame timeout means the broker has closed the TCP connection, which it # does per 0.9.1 spec. rescue Errno::ECONNRESET, ClientTimeout, AMQ::Protocol::EmptyResponseError, EOFError => e nil end if frame2.nil? @state = :closed @logger.warn "RabbitMQ closed TCP connection before AMQP 0.9.1 connection was finalized. Most likely this means authentication failure." raise Bunny::PossibleAuthenticationFailureError.new(self.user, self.vhost, self.password.size) end connection_open_ok = frame2.decode_payload @status = :open if @heartbeat && @heartbeat > 0 initialize_heartbeat_sender end raise "could not open connection: server did not respond with connection.open-ok" unless connection_open_ok.is_a?(AMQ::Protocol::Connection::OpenOk) end def heartbeat_disabled?(val) 0 == val || val.nil? end # @private def negotiate_value(client_value, server_value) return server_value if client_value == :server if client_value == 0 || server_value == 0 [client_value, server_value].max else [client_value, server_value].min end end # @private def initialize_heartbeat_sender maybe_shutdown_heartbeat_sender @logger.debug "Initializing heartbeat sender..." @heartbeat_sender = HeartbeatSender.new(@transport, @logger) @heartbeat_sender.start(@heartbeat) end # @private def maybe_shutdown_heartbeat_sender @heartbeat_sender.stop if @heartbeat_sender end # @private def initialize_transport @transport = Transport.new(self, @host, @port, @opts.merge(:session_thread => @origin_thread)) end # @private def maybe_close_transport @transport.close if @transport end # Sends AMQ protocol header (also known as preamble). # @private def send_preamble @transport.write(AMQ::Protocol::PREAMBLE) @logger.debug "Sent protocol preamble" end # @private def encode_credentials(username, password) @credentials_encoder.encode_credentials(username, password) end # encode_credentials(username, password) # @private def credentials_encoder_for(mechanism) Authentication::CredentialsEncoder.for_session(self) end if defined?(JRUBY_VERSION) # @private def reset_continuations @continuations = Concurrent::LinkedContinuationQueue.new end else # @private def reset_continuations @continuations = Concurrent::ContinuationQueue.new end end # @private def wait_on_continuations unless @threaded reader_loop.run_once until @continuations.length > 0 end @continuations.poll(@continuation_timeout) end # @private def init_logger(level) lgr = ::Logger.new(@logfile) lgr.level = normalize_log_level(level) lgr.progname = self.to_s lgr end # @private def normalize_log_level(level) case level when :debug, Logger::DEBUG, "debug" then Logger::DEBUG when :info, Logger::INFO, "info" then Logger::INFO when :warn, Logger::WARN, "warn" then Logger::WARN when :error, Logger::ERROR, "error" then Logger::ERROR when :fatal, Logger::FATAL, "fatal" then Logger::FATAL else Logger::WARN end end # @private def shut_down_all_consumer_work_pools @channels.each do |_, ch| ch.maybe_kill_consumer_work_pool! end end end # Session # backwards compatibility Client = Session end
module Authorization module BlockAccess protected # Block access to all actions in the controller, designed to be used as a <tt>before_filter</tt>. # class ApplicationController < ActionController::Base # before_filter :block_access # end def block_access die_if_undefined unless @authenticated.nil? # Find the user's roles roles = [] roles << @authenticated.role if @authenticated.respond_to?(:role) access_allowed_for.keys.each do |role| roles << role.to_s if @authenticated.respond_to?("#{role}?") and @authenticated.send("#{role}?") end # Check if any of the roles give her access roles.each do |role| return true if access_allowed?(params, role, @authenticated) end end return true if access_allowed?(params, :all, @authenticated) access_forbidden end # Checks if access is allowed for the params, role and authenticated user. # access_allowed?({:action => :show, :id => 1}, :admin, @authenticated) def access_allowed?(params, role, authenticated=nil) die_if_undefined if (rules = access_allowed_for[role]).nil? logger.debug(" \e[31mCan't find rules for `#{role}'\e[0m") return false end !rules.detect do |rule| if !action_allowed_by_rule?(rule, params, role) or !resource_allowed_by_rule?(rule, params, role, authenticated) or !block_allowed_by_rule?(rule) logger.debug(" \e[31mAccess DENIED by RULE #{rule.inspect} FOR `#{role}'\e[0m") false else logger.debug(" \e[32mAccess GRANTED by RULE #{rule.inspect} FOR `#{role}'\e[0m") true end end.nil? end # <tt>access_forbidden</tt> is called by <tt>block_access</tt> when access is forbidden. This method does # nothing by default. Make sure you return <tt>false</tt> from the method if you want to halt the filter # chain. def access_forbidden false end # Checks if a certain action can be accessed by the role. # If you want to check for <tt>action_allowed?</tt>, <tt>resource_allowed?</tt> and <tt>block_allowed?</tt> # use <tt>access_allowed?</tt>. # action_allowed?({:action => :show, :id => 1}, :editor) def action_allowed?(params, role=:all) die_if_undefined return false if (rules = access_allowed_for[role]).nil? !rules.detect { |rule| action_allowed_by_rule?(rule, params, role) }.nil? end def action_allowed_by_rule?(rule, params, role) #:nodoc: return false if (action = params[:action]).nil? directives = rule[:directives] return false if directives[:only].kind_of?(Array) and !directives[:only].include?(action.to_sym) return false if directives[:only].kind_of?(Symbol) and directives[:only] != action.to_sym return false if directives[:except].kind_of?(Array) and directives[:except].include?(action.to_sym) return false if directives[:except].kind_of?(Symbol) and directives[:except] == action.to_sym true end # Checks if the resource indicated by the params can be accessed by user. # If you want to check for <tt>action_allowed?</tt>, <tt>resource_allowed?</tt> and <tt>block_allowed?</tt> # use <tt>access_allowed?</tt>. # resource_allowed?({:id => 1, :organization_id => 12}, :guest, @authenticated) def resource_allowed?(params, role=:all, user=nil) user ||= @authenticated die_if_undefined return false if (rules = access_allowed_for[role]).nil? !rules.detect { |rule| resource_allowed_by_rule?(rule, params, role, user) }.nil? end def resource_allowed_by_rule?(rule, params, role, user) #:nodoc: directives = rule[:directives] if directives[:authenticated] return false unless user end begin if directives[:user_resource] return false if params[:id].nil? or user.id.nil? return false if params[:id].to_i != user.id.to_i end rescue NoMethodError end begin if scope = directives[:scope] assoc_id = params["#{scope}_id"].to_i begin object_id = user.send(scope).id.to_i rescue NoMethodError return false end return false if assoc_id.nil? or object_id.nil? return false if assoc_id != object_id end rescue NoMethodError end true end # Checks if the blocks associated with the rules doesn't stop the user from acessing the resource. # If you want to check for <tt>action_allowed?</tt>, <tt>resource_allowed?</tt> and <tt>block_allowed?</tt> # use <tt>access_allowed?</tt>. # block_allowed?(:guest) def block_allowed?(role) die_if_undefined return false if (rules = access_allowed_for[role]).nil? !rules.detect { |rule| block_allowed_by_rule?(rule) }.nil? end def block_allowed_by_rule?(rule) #:nodoc: return false if !rule[:block].nil? and !rule[:block].bind(self).call true end def die_if_undefined #:nodoc: if !self.respond_to?(:access_allowed_for) or access_allowed_for.nil? raise ArgumentError, "Please specify access control using `allow_access' in the controller" end end end end Remove some stray whitespace. module Authorization module BlockAccess protected # Block access to all actions in the controller, designed to be used as a <tt>before_filter</tt>. # class ApplicationController < ActionController::Base # before_filter :block_access # end def block_access die_if_undefined unless @authenticated.nil? # Find the user's roles roles = [] roles << @authenticated.role if @authenticated.respond_to?(:role) access_allowed_for.keys.each do |role| roles << role.to_s if @authenticated.respond_to?("#{role}?") and @authenticated.send("#{role}?") end # Check if any of the roles give her access roles.each do |role| return true if access_allowed?(params, role, @authenticated) end end return true if access_allowed?(params, :all, @authenticated) access_forbidden end # Checks if access is allowed for the params, role and authenticated user. # access_allowed?({:action => :show, :id => 1}, :admin, @authenticated) def access_allowed?(params, role, authenticated=nil) die_if_undefined if (rules = access_allowed_for[role]).nil? logger.debug(" \e[31mCan't find rules for `#{role}'\e[0m") return false end !rules.detect do |rule| if !action_allowed_by_rule?(rule, params, role) or !resource_allowed_by_rule?(rule, params, role, authenticated) or !block_allowed_by_rule?(rule) logger.debug(" \e[31mAccess DENIED by RULE #{rule.inspect} FOR `#{role}'\e[0m") false else logger.debug(" \e[32mAccess GRANTED by RULE #{rule.inspect} FOR `#{role}'\e[0m") true end end.nil? end # <tt>access_forbidden</tt> is called by <tt>block_access</tt> when access is forbidden. This method does # nothing by default. Make sure you return <tt>false</tt> from the method if you want to halt the filter # chain. def access_forbidden false end # Checks if a certain action can be accessed by the role. # If you want to check for <tt>action_allowed?</tt>, <tt>resource_allowed?</tt> and <tt>block_allowed?</tt> # use <tt>access_allowed?</tt>. # action_allowed?({:action => :show, :id => 1}, :editor) def action_allowed?(params, role=:all) die_if_undefined return false if (rules = access_allowed_for[role]).nil? !rules.detect { |rule| action_allowed_by_rule?(rule, params, role) }.nil? end def action_allowed_by_rule?(rule, params, role) #:nodoc: return false if (action = params[:action]).nil? directives = rule[:directives] return false if directives[:only].kind_of?(Array) and !directives[:only].include?(action.to_sym) return false if directives[:only].kind_of?(Symbol) and directives[:only] != action.to_sym return false if directives[:except].kind_of?(Array) and directives[:except].include?(action.to_sym) return false if directives[:except].kind_of?(Symbol) and directives[:except] == action.to_sym true end # Checks if the resource indicated by the params can be accessed by user. # If you want to check for <tt>action_allowed?</tt>, <tt>resource_allowed?</tt> and <tt>block_allowed?</tt> # use <tt>access_allowed?</tt>. # resource_allowed?({:id => 1, :organization_id => 12}, :guest, @authenticated) def resource_allowed?(params, role=:all, user=nil) user ||= @authenticated die_if_undefined return false if (rules = access_allowed_for[role]).nil? !rules.detect { |rule| resource_allowed_by_rule?(rule, params, role, user) }.nil? end def resource_allowed_by_rule?(rule, params, role, user) #:nodoc: directives = rule[:directives] if directives[:authenticated] return false unless user end begin if directives[:user_resource] return false if params[:id].nil? or user.id.nil? return false if params[:id].to_i != user.id.to_i end rescue NoMethodError end begin if scope = directives[:scope] assoc_id = params["#{scope}_id"].to_i begin object_id = user.send(scope).id.to_i rescue NoMethodError return false end return false if assoc_id.nil? or object_id.nil? return false if assoc_id != object_id end rescue NoMethodError end true end # Checks if the blocks associated with the rules doesn't stop the user from acessing the resource. # If you want to check for <tt>action_allowed?</tt>, <tt>resource_allowed?</tt> and <tt>block_allowed?</tt> # use <tt>access_allowed?</tt>. # block_allowed?(:guest) def block_allowed?(role) die_if_undefined return false if (rules = access_allowed_for[role]).nil? !rules.detect { |rule| block_allowed_by_rule?(rule) }.nil? end def block_allowed_by_rule?(rule) #:nodoc: return false if !rule[:block].nil? and !rule[:block].bind(self).call true end def die_if_undefined #:nodoc: if !self.respond_to?(:access_allowed_for) or access_allowed_for.nil? raise ArgumentError, "Please specify access control using `allow_access' in the controller" end end end end
# OO Basics: Student # I worked on this challenge [by myself, with: ]. # This challenge took me [#] hours. # Pseudocode =begin CREATE five student objects Each student has a first_name and an array of 5 test scores PUSH student objects into students array =end # Initial Solution class Student attr_accessor :scores, :first_name def initialize(first_name, scores) #Use named arguments! if (scores.is_a?(Array) == false || scores[0].is_a?(Integer) == false) raise ArgumentError, "The argument must be an array of test scores." end @scores = scores; @first_name = first_name; end def average() sum = 0 @scores.each{ |a| sum += a } sum / @scores.length end def letter_grade() case self.average when 90..100 return "A" when 80..90 return "B" when 70..80 return "C" when 60..70 return "D" else return "F" end end end alex = Student.new( "Alex", [100,100,100,0,100] ); bonnie = Student.new( "Bonnie", [75, 80, 85, 90, 95]); carlos = Student.new( "Carlos", [85, 88, 91, 94, 97]); dana = Student.new("Dana", [90, 86, 82, 78, 86]); eric = Student.new("Eric", [95, 75, 85, 80, 90]); students = [ alex, bonnie, carlos, dana, eric ]; def linear_search(array, target) array.each_index do |i| if array[i].first_name == target then return i end end return -1 end def binary_search(array, target) p "==================" # p target # p array[array.length/2].first_name #unless array.include?(target) then return -1 end if array[array.length/2].first_name == target return array.length/2; elsif array[array.length/2].first_name > target array.slice!(0..(array.length/2)); print array.length; puts; binary_search(array, target); else array.slice!( (array.length/2) + 1, array.length) print array.length; puts; binary_search(array, target); end end p binary_search(students, "Alex"); # Refactored Solution # DRIVER TESTS GO BELOW THIS LINE # Initial Tests: p students[0].first_name == "Alex" p students[0].scores.length == 5 p students[0].scores[0] == students[0].scores[4] p students[0].scores[3] == 0 # Additional Tests 1: p students[0].average == 80 p students[0].letter_grade == 'B' # Additional Tests 2: p linear_search(students, "Alex") == 0 p linear_search(students, "NOT A STUDENT") == -1 p binary_search(students, "Eric") == 3 p binary_search(students, "NOT A STUDENT") == -1 # Reflection =begin =end 8.6 Obj-Or: Initial solution complete # OO Basics: Student # I worked on this challenge [by myself, with: ]. # This challenge took me [#] hours. # Pseudocode =begin CLASS definition:.............................................................. Accessors: scores, first_name INITIALIZE: ACCEPT arguments: scores, first_name VALIDATE scores is array of integers SET instance variables for scores, first_name equal to arguments AVERAGE: DECLARE local variable to hold sum during calculation ITERATE over scores array, adding each score to the sum DIVIDE the sum by the length of the scores array LETTER GRADE: CASE -- check average score for student WHEN average is 90+, A WHEN average is 80+, B WHEN average is 70+, C WHEN average is 60+, D ELSE, F GLOBAL METHODS................................................................. LINEAR SEARCH: ACCEPT arguments: array, target ITERATE over array by index IF array[index] matches target, return index IF target is not found in array, return -1 BINARY SEARCH: ACCEPT arguments: sorted array, target CREATE variables min_index = 0 max_index = array.length - 1 mid_index = max_index / 2 WHILE min_index <= max_index CASE target is less than, equal to, or greater than array[mid-index] WHEN target is less than mid_index SET max_index = middle element WHEN target is greater than middle element SET min_index = middle element ELSE return mid_index RUN-TIME CODE:................................................................. CREATE five student objects Each student has a first_name and an array of 5 test scores PUSH student objects into students array CALL all methods =end # Initial Solution ============================================================ =begin class Student attr_accessor :scores, :first_name def initialize(first_name, scores) #Use named arguments! if (scores.is_a?(Array) == false || scores[0].is_a?(Integer) == false) raise ArgumentError, "The argument must be an array of test scores." end @scores = scores; @first_name = first_name; end def average() sum = 0 @scores.each{ |a| sum += a } sum / @scores.length end def letter_grade() case self.average when 90..100 return "A" when 80..90 return "B" when 70..80 return "C" when 60..70 return "D" else return "F" end end end def linear_search(array, target) array.each_index do |i| if array[i].first_name == target then return i end end return -1 end def binary_search(array, target) min_index = 0; max_index = array.length - 1; mid_index = max_index / 2; while min_index != max_index if target < array[mid_index].first_name max_index = mid_index - 1 mid_index = (max_index + min_index) / 2 elsif target > array[mid_index].first_name min_index = mid_index + 1 mid_index = (max_index + min_index) / 2 else max_index = mid_index min_index = mid_index end end if target == array[mid_index].first_name return mid_index else return -1 end end alex = Student.new( "Alex", [100,100,100,0,100] ); bonnie = Student.new( "Bonnie", [75, 80, 85, 90, 95]); carlos = Student.new( "Carlos", [85, 88, 91, 94, 97]); dana = Student.new("Dana", [90, 86, 82, 78, 86]); eric = Student.new("Eric", [95, 75, 85, 80, 90]); fred = Student.new( "Fred", [100,100,100,0,100] ); gert = Student.new( "Gert", [75, 80, 85, 90, 95]); hazel = Student.new( "Hazel", [85, 88, 91, 94, 97]); ivan = Student.new("Ivan", [90, 86, 82, 78, 86]); jeff = Student.new("Jeff", [95, 75, 85, 80, 90]); students = [ alex, bonnie, carlos, dana, eric, fred, gert, hazel, ivan, jeff ]; =end # Refactored Solution class Student attr_accessor :scores, :first_name def initialize(first_name, scores) #Use named arguments! if (scores.is_a?(Array) == false || scores[0].is_a?(Integer) == false) raise ArgumentError, "The argument must be an array of test scores." end @scores = scores; @first_name = first_name; end def average() @scores.reduce(:+) / @scores.length end def letter_grade() case self.average when 90..100 return "A" when 80..90 return "B" when 70..80 return "C" when 60..70 return "D" else return "F" end end end def linear_search(array, target) array.each_index do |i| if array[i].first_name == target then return i end end return -1 end def binary_search(array, target) min = 0; max = array.length - 1; def mid(min, max) (min + max) / 2 end while min != max if target < array[mid(min, max)].first_name max = mid(min, max) - 1 elsif target > array[mid(min, max)].first_name min = mid(min, max) + 1 else max = mid(min, max) min = mid(min, max) end end # case min != max # when target < array[mid(min, max)].first_name # max = mid(min, max) - 1 # when target > array[mid(min, max)].first_name # min = mid(min, max) + 1 # else # max = mid(min, max) # min = mid(min, max) # end if target == array[mid(min, max)].first_name return mid(min, max) else return -1 end end alex = Student.new( "Alex", [100,100,100,0,100] ); bonnie = Student.new( "Bonnie", [75, 80, 85, 90, 95]); carlos = Student.new( "Carlos", [85, 88, 91, 94, 97]); dana = Student.new("Dana", [90, 86, 82, 78, 86]); eric = Student.new("Eric", [95, 75, 85, 80, 90]); fred = Student.new( "Fred", [100,100,100,0,100] ); gert = Student.new( "Gert", [75, 80, 85, 90, 95]); hazel = Student.new( "Hazel", [85, 88, 91, 94, 97]); ivan = Student.new("Ivan", [90, 86, 82, 78, 86]); jeff = Student.new("Jeff", [95, 75, 85, 80, 90]); students = [ alex, bonnie, carlos, dana, eric, fred, gert, hazel, ivan, jeff ]; # DRIVER TESTS GO BELOW THIS LINE # Initial Tests: p students[0].first_name == "Alex" p students[0].scores.length == 5 p students[0].scores[0] == students[0].scores[4] p students[0].scores[3] == 0 # Additional Tests 1: p students[0].average == 80 p students[0].letter_grade == 'B' # Additional Tests 2: p linear_search(students, "Alex") == 0 p linear_search(students, "NOT A STUDENT") == -1 # Tests added for binary_search: p "==============" p binary_search(students, "Alex") == 0 p binary_search(students, "Bonnie") == 1 p binary_search(students, "Carlos") == 2 p binary_search(students, "Dana") == 3 p binary_search(students, "Eric") == 4 p binary_search(students, "Fred") == 5 p binary_search(students, "Gert") == 6 p binary_search(students, "Hazel") == 7 p binary_search(students, "Ivan") == 8 p binary_search(students, "Jeff") == 9 p binary_search(students, "NOT A STUDENT") == -1 # Reflection =begin =end
# TODO: PR to HER # Fix to_params when embeded_params is nil # Fix to_params when changes is nil # --> allow all params - this is required to be able to make class level # requests like MyModel.post(path,{some: 'data'}) # module Her module Model # This module handles resource data parsing at the model level (after the parsing middleware) module Parse extend ActiveSupport::Concern module ClassMethods # @private def to_params(attributes, changes = nil) filtered_attributes = attributes.dup.symbolize_keys filtered_attributes.merge!(embeded_params(attributes) || {}) if her_api && her_api.options[:send_only_modified_attributes] && !changes.nil? filtered_attributes = changes.symbolize_keys.keys.inject({}) do |hash, attribute| hash[attribute] = filtered_attributes[attribute] hash end end if include_root_in_json? if json_api_format? { included_root_element => [filtered_attributes] } else { included_root_element => filtered_attributes } end else filtered_attributes end end # @private # TODO: Handle has_one def embeded_params(attributes) associations[:has_many].select { |a| attributes.include?(a[:data_key])}.compact.inject({}) do |hash, association| params = attributes[association[:data_key]].map(&:to_params) next hash if params.empty? if association[:class_name].constantize.include_root_in_json? root = association[:class_name].constantize.root_element hash[association[:data_key]] = params.map { |n| n[root] } else hash[association[:data_key]] = params end hash end end end end end end make the patch more visible # TODO: PR to HER # Fix to_params when embeded_params is nil # Fix to_params when changes is nil # --> allow all params - this is required to be able to make class level # requests like MyModel.post(path,{some: 'data'}) # module Her module Model # This module handles resource data parsing at the model level (after the parsing middleware) module Parse extend ActiveSupport::Concern module ClassMethods # @private def to_params(attributes, changes = nil) filtered_attributes = attributes.dup.symbolize_keys filtered_attributes.merge!(embeded_params(attributes) || {}) if her_api && her_api.options[:send_only_modified_attributes] && !changes.nil? filtered_attributes = changes.symbolize_keys.keys.inject({}) do |hash, attribute| hash[attribute] = filtered_attributes[attribute] hash end end if include_root_in_json? if json_api_format? { included_root_element => [filtered_attributes] } else { included_root_element => filtered_attributes } end else filtered_attributes end end # @private # TODO: Handle has_one def embeded_params(attributes) associations[:has_many].select { |a| attributes.include?(a[:data_key])}.compact.inject({}) do |hash, association| params = attributes[association[:data_key]].map(&:to_params) # <PATCH> - Return hash next hash if params.empty? # </PATCH> if association[:class_name].constantize.include_root_in_json? root = association[:class_name].constantize.root_element hash[association[:data_key]] = params.map { |n| n[root] } else hash[association[:data_key]] = params end hash end end end end end end
require 'stax/aws/ecs' module Stax module Ecs def self.included(thor) thor.desc(:ecs, 'ECS subcommands') thor.subcommand(:ecs, Cmd::Ecs) end def ecs_cluster_name 'default' end end module Cmd class Ecs < SubCommand COLORS = { ACTIVE: :green, INACTIVE: :red, RUNNING: :green, STOPPED: :red, } no_commands do def ecs_task_definitions @_ecs_task_definitions ||= Aws::Cfn.resources_by_type(my.stack_name, 'AWS::ECS::TaskDefinition' ) end def ecs_task_definition(id) Aws::Cfn.id(my.stack_name, id) end def ecs_services @_ecs_services ||= Aws::Cfn.resources_by_type(my.stack_name, 'AWS::ECS::Service') end end desc 'clusters', 'ECS cluster for stack' def clusters print_table Aws::Ecs.clusters(my.ecs_cluster_name).map { |c| [ c.cluster_name, color(c.status, COLORS), "instances:#{c.registered_container_instances_count}", "pending:#{c.pending_tasks_count}", "running:#{c.running_tasks_count}", ] } end desc 'services', 'ECS services for stack' def services print_table Aws::Ecs.services(my.ecs_cluster_name, ecs_services.map(&:physical_resource_id)).map { |s| [s.service_name, color(s.status, COLORS), s.task_definition.split('/').last, "#{s.running_count}/#{s.desired_count}"] } end desc 'definitions', 'ECS task definitions for stack' def definitions print_table ecs_task_definitions.map { |r| t = Aws::Ecs.task_definition(r.physical_resource_id) [r.logical_resource_id, t.family, t.revision, color(t.status, COLORS)] } end desc 'tasks' , 'ECS tasks for stack' method_option :status, aliases: '-s', type: :string, default: 'RUNNING', desc: 'status to list' def tasks print_table Aws::Ecs.tasks(my.ecs_cluster_name, options[:status].upcase).map { |t| [ t.task_arn.split('/').last, t.task_definition_arn.split('/').last, t.container_instance_arn.split('/').last, color(t.last_status, COLORS), "(#{t.desired_status})", t.started_by, ] } end desc 'instances', 'ECS instances' def instances print_table Aws::Ecs.instances(my.ecs_cluster_name).map { |i| [ i.container_instance_arn.split('/').last, i.ec2_instance_id, i.agent_connected, color(i.status, COLORS), i.running_tasks_count, "(#{i.pending_tasks_count})", "agent #{i.version_info.agent_version}", i.version_info.docker_version, ] } end desc 'run_task [ID]', 'run task by id' def run_task(id) Aws::Ecs.run(my.ecs_cluster_name, Aws::Cfn.id(my.stack_name, id)).tap do |tasks| puts tasks.map(&:container_instance_arn) end end desc 'stop_task [TASK]', 'stop task' def stop_task(task) Aws::Ecs.stop(my.ecs_cluster_name, task).tap do |task| puts task.container_instance_arn end end end end end container_instance_arn can be nil with fargate tasks require 'stax/aws/ecs' module Stax module Ecs def self.included(thor) thor.desc(:ecs, 'ECS subcommands') thor.subcommand(:ecs, Cmd::Ecs) end def ecs_cluster_name 'default' end end module Cmd class Ecs < SubCommand COLORS = { ACTIVE: :green, INACTIVE: :red, RUNNING: :green, STOPPED: :red, } no_commands do def ecs_task_definitions @_ecs_task_definitions ||= Aws::Cfn.resources_by_type(my.stack_name, 'AWS::ECS::TaskDefinition' ) end def ecs_task_definition(id) Aws::Cfn.id(my.stack_name, id) end def ecs_services @_ecs_services ||= Aws::Cfn.resources_by_type(my.stack_name, 'AWS::ECS::Service') end end desc 'clusters', 'ECS cluster for stack' def clusters print_table Aws::Ecs.clusters(my.ecs_cluster_name).map { |c| [ c.cluster_name, color(c.status, COLORS), "instances:#{c.registered_container_instances_count}", "pending:#{c.pending_tasks_count}", "running:#{c.running_tasks_count}", ] } end desc 'services', 'ECS services for stack' def services print_table Aws::Ecs.services(my.ecs_cluster_name, ecs_services.map(&:physical_resource_id)).map { |s| [s.service_name, color(s.status, COLORS), s.task_definition.split('/').last, "#{s.running_count}/#{s.desired_count}"] } end desc 'definitions', 'ECS task definitions for stack' def definitions print_table ecs_task_definitions.map { |r| t = Aws::Ecs.task_definition(r.physical_resource_id) [r.logical_resource_id, t.family, t.revision, color(t.status, COLORS)] } end desc 'tasks' , 'ECS tasks for stack' method_option :status, aliases: '-s', type: :string, default: 'RUNNING', desc: 'status to list' def tasks print_table Aws::Ecs.tasks(my.ecs_cluster_name, options[:status].upcase).map { |t| [ t.task_arn.split('/').last, t.task_definition_arn.split('/').last, t.container_instance_arn&.split('/')&.last || '--', color(t.last_status, COLORS), "(#{t.desired_status})", t.started_by, ] } end desc 'instances', 'ECS instances' def instances print_table Aws::Ecs.instances(my.ecs_cluster_name).map { |i| [ i.container_instance_arn.split('/').last, i.ec2_instance_id, i.agent_connected, color(i.status, COLORS), i.running_tasks_count, "(#{i.pending_tasks_count})", "agent #{i.version_info.agent_version}", i.version_info.docker_version, ] } end desc 'run_task [ID]', 'run task by id' def run_task(id) Aws::Ecs.run(my.ecs_cluster_name, Aws::Cfn.id(my.stack_name, id)).tap do |tasks| puts tasks.map(&:container_instance_arn) end end desc 'stop_task [TASK]', 'stop task' def stop_task(task) Aws::Ecs.stop(my.ecs_cluster_name, task).tap do |task| puts task.container_instance_arn end end end end end
class Cache VERSION = "0.2.7" end bump minor class Cache VERSION = "0.3.0" end
require 'faraday' require 'faraday_middleware' require 'aweplug/cache/yaml_file_cache' require 'logger' # WARNING: monkey patching faraday # TODO: See if we can the new refinements to work module Faraday module Utils def build_nested_query(value, prefix = nil) case value when Array value.map { |v| build_nested_query(v, "#{prefix}") }.join("&") when Hash value.map { |k, v| build_nested_query(v, prefix ? "#{prefix}%5B#{escape(k)}%5D" : escape(k)) }.join("&") when NilClass prefix else raise ArgumentError, "value must be a Hash" if prefix.nil? "#{prefix}=#{escape(value)}" end end end end module Aweplug module Helpers # Public: A helper class for using Searchisko. class Searchisko # Public: Initialization of the object, keeps a Faraday connection cached. # # opts - symbol keyed hash. Current keys used: # :base_url - base url for the searchisko instance # :authenticate - boolean flag for authentication # :searchisko_username - Username to use for auth # :searchisko_password - Password to use for auth # :logger - Boolean to log responses or an instance of Logger to use # :raise_error - Boolean flag if 404 and 500 should raise exceptions # :adapter - faraday adapter to use, defaults to :net_http # :cache - Instance of a cache to use, required. # # Returns a new instance of Searchisko. def initialize opts={} @faraday = Faraday.new(:url => opts[:base_url]) do |builder| if opts[:authenticate] if opts[:searchisko_username] && opts[:searchisko_password] builder.request :basic_auth, opts[:searchisko_username], opts[:searchisko_password] else $LOG.warn 'Missing username and / or password for searchisko' if $LOG.warn end end if (opts[:logger]) if (opts[:logger].is_a?(::Logger)) builder.response :logger, @logger = opts[:logger] else builder.response :logger, @logger = ::Logger.new('_tmp/faraday.log', 'daily') end end builder.request :url_encoded builder.response :raise_error if opts[:raise_error] builder.use FaradayMiddleware::Caching, opts[:cache], {} #builder.response :json, :content_type => /\bjson$/ builder.adapter opts[:adapter] || :net_http_persistent end end # Public: Performs a GET search against the Searchisko instance using # provided parameters. # # params - Hash of parameters to use as query string. See # http://docs.jbossorg.apiary.io/#searchapi for more information # about parameters and how they affect the search. # # Example # # searchisko.search {:query => 'Search query'} # # => {...} # # Returns the String result of the search. def search params = {} get '/search', params end # Public: Makes an HTTP GET to host/v1/rest/#{path} and returns the # result from the Faraday request. # # path - String containing the rest of the path. # params - Hash containing query string parameters. # # Example # # searchisko.get 'feed', {:query => 'Search Query'} # # => Faraday Response Object # # Returns the Faraday Response for the request. def get path, params = {} response = @faraday.get "/v1/rest/" + path, params unless response.success? $LOG.warn "Error making searchisko request to #{path}. Status: #{response.status}. Params: #{params}" if $LOG.warn? end response end # Public: Posts content to Searchisko. # # content_type - String of the Searchisko sys_content_type for the content # being posted. # content_id - String of the Searchisko sys_content_id for the content. # params - Hash containing the content to push. # # Examples # # searchisko.push_content 'jbossdeveloper_bom', id, content_hash # # => Faraday Response # # Returns a Faraday Response from the POST. def push_content content_type, content_id, params = {} post "/content/#{content_type}/#{content_id}", params end # Public: Perform an HTTP POST to Searchisko. # # path - String containing the rest of the path. # params - Hash containing the POST body. # # Examples # # searchisko.post "rating/#{searchisko_document_id}", {rating: 3} # # => Faraday Response def post path, params = {} resp = @faraday.post do |req| req.url "/v1/rest/" + path req.headers['Content-Type'] = 'application/json' req.body = params if @logger @logger.debug "request body: #{req.body}" end end if @logger && !resp.status.between?(200, 300) @logger.debug "response body: #{resp.body}" end unless resp.success? if $LOG.warn? $LOG.warn "Error making searchisko request to '#{path}'. Status: #{resp.status}. Params: #{params}. Response body: #{resp.body}" else puts "No log error" end end end end end end Display any warnings from searchisko POSTs require 'faraday' require 'faraday_middleware' require 'aweplug/cache/yaml_file_cache' require 'logger' # WARNING: monkey patching faraday # TODO: See if we can the new refinements to work module Faraday module Utils def build_nested_query(value, prefix = nil) case value when Array value.map { |v| build_nested_query(v, "#{prefix}") }.join("&") when Hash value.map { |k, v| build_nested_query(v, prefix ? "#{prefix}%5B#{escape(k)}%5D" : escape(k)) }.join("&") when NilClass prefix else raise ArgumentError, "value must be a Hash" if prefix.nil? "#{prefix}=#{escape(value)}" end end end end module Aweplug module Helpers # Public: A helper class for using Searchisko. class Searchisko # Public: Initialization of the object, keeps a Faraday connection cached. # # opts - symbol keyed hash. Current keys used: # :base_url - base url for the searchisko instance # :authenticate - boolean flag for authentication # :searchisko_username - Username to use for auth # :searchisko_password - Password to use for auth # :logger - Boolean to log responses or an instance of Logger to use # :raise_error - Boolean flag if 404 and 500 should raise exceptions # :adapter - faraday adapter to use, defaults to :net_http # :cache - Instance of a cache to use, required. # # Returns a new instance of Searchisko. def initialize opts={} @faraday = Faraday.new(:url => opts[:base_url]) do |builder| if opts[:authenticate] if opts[:searchisko_username] && opts[:searchisko_password] builder.request :basic_auth, opts[:searchisko_username], opts[:searchisko_password] else $LOG.warn 'Missing username and / or password for searchisko' if $LOG.warn end end if (opts[:logger]) if (opts[:logger].is_a?(::Logger)) builder.response :logger, @logger = opts[:logger] else builder.response :logger, @logger = ::Logger.new('_tmp/faraday.log', 'daily') end end builder.request :url_encoded builder.response :raise_error if opts[:raise_error] builder.use FaradayMiddleware::Caching, opts[:cache], {} #builder.response :json, :content_type => /\bjson$/ builder.adapter opts[:adapter] || :net_http_persistent end end # Public: Performs a GET search against the Searchisko instance using # provided parameters. # # params - Hash of parameters to use as query string. See # http://docs.jbossorg.apiary.io/#searchapi for more information # about parameters and how they affect the search. # # Example # # searchisko.search {:query => 'Search query'} # # => {...} # # Returns the String result of the search. def search params = {} get '/search', params end # Public: Makes an HTTP GET to host/v1/rest/#{path} and returns the # result from the Faraday request. # # path - String containing the rest of the path. # params - Hash containing query string parameters. # # Example # # searchisko.get 'feed', {:query => 'Search Query'} # # => Faraday Response Object # # Returns the Faraday Response for the request. def get path, params = {} response = @faraday.get "/v1/rest/" + path, params unless response.success? $LOG.warn "Error making searchisko request to #{path}. Status: #{response.status}. Params: #{params}" if $LOG.warn? end response end # Public: Posts content to Searchisko. # # content_type - String of the Searchisko sys_content_type for the content # being posted. # content_id - String of the Searchisko sys_content_id for the content. # params - Hash containing the content to push. # # Examples # # searchisko.push_content 'jbossdeveloper_bom', id, content_hash # # => Faraday Response # # Returns a Faraday Response from the POST. def push_content content_type, content_id, params = {} post "/content/#{content_type}/#{content_id}", params end # Public: Perform an HTTP POST to Searchisko. # # path - String containing the rest of the path. # params - Hash containing the POST body. # # Examples # # searchisko.post "rating/#{searchisko_document_id}", {rating: 3} # # => Faraday Response def post path, params = {} resp = @faraday.post do |req| req.url "/v1/rest/" + path req.headers['Content-Type'] = 'application/json' req.body = params if @logger @logger.debug "request body: #{req.body}" end end body = JSON.parse(resp.body) if @logger && (!resp.status.between?(200, 300) || body.has_key?("warnings")) @logger.debug "response body: #{resp.body}" end if $LOG.warn? if !resp.success? $LOG.warn "Error making searchisko request to '#{path}'. Status: #{resp.status}. Params: #{params}. Response body: #{resp.body}" elsif body.has_key? "warnings" $LOG.warn "Searchisko content POST to '#{path}' succeeded with warnings: #{body["warnings"]}" end end end end end end
class CacheManager attr_reader :cache def initialize(cache) @cache = cache end def read(name, options = nil) @cache.read(name, options) rescue StandardError => error Api::Root.logger.warn("Got error #{error} attempting to read cache #{name}.") return nil end def write(name, value, options = nil) # Limit string size to 10kb to avoid cache errors in Redis @cache.write(name, value, options) if value.to_s.bytesize < 10.kilobytes rescue StandardError => error Api::Root.logger.warn("Got error #{error} attempting to write cache #{name}.") return nil end end Increase cache size class CacheManager attr_reader :cache def initialize(cache) @cache = cache end def read(name, options = nil) @cache.read(name, options) rescue StandardError => error Api::Root.logger.warn("Got error #{error} attempting to read cache #{name}.") return nil end def write(name, value, options = nil) # Limit string size to 10kb to avoid cache errors in Redis @cache.write(name, value, options) if value.to_s.bytesize < 100.megabytes rescue StandardError => error Api::Root.logger.warn("Got error #{error} attempting to write cache #{name}.") return nil end end
# encoding: utf-8 require 'eventmachine' require "em-synchrony" require "em-synchrony/em-http" require 'fileutils' require 'logger' require 'ext/multi_delegator' module Worker # Public: To create a worker of some sort you need to start by including # this Base module. This will give give you the methods required to spawn # the worker through the executable, add logging & process tracking. module Base def self.included(base) base.extend(ClassMethods) end module ClassMethods # Public: Initializes a worker and calls start on it's instance it straight after # # options - A hash of options for the worker # # Examples # # SomeWorker.start # # Returns whatever start returns. def start(options={}) self.new(options).start end # Public: Initializes a worker and calls start on it's instance it straight after # # options - A hash of options for the worker # # Examples # # SomeWorker.start # # Returns whatever start returns. # def spawn(options={}) # self.new(options).start # end end # Public: Initializes a worker # # options - A hash of options for the worker # # Examples # # SomeWorker.new() # # Returns the worker object. def initialize(options={}) @root = File.expand_path('../../../../../', __FILE__) # if @log.nil? # @logdir = @root + "/log/worker" # FileUtils.mkdir_p @logdir # @logfile = @logdir + "/#{self.class.to_s.downcase}.log" # FileUtils.touch @logfile # # @log = Logger.new MultiDelegator.delegate(:write, :close).to(STDOUT, File.open(@logfile,'a')) # @log.level = Logger::DEBUG # TODO Only log if development environment # # @log.formatter = proc do |severity, datetime, progname, msg| # "[#{severity}] - #{datetime}: #{msg}\n" # end # # @log.info("Started logging in: #{@logfile}") # end return self end # Public: Returns the log object # # Returns the log object. def log @log end # Internal This is used gracefully kill the application # when process receives certain signals. # # Examples # # EM.run do # shutdown! # end # def register_signal_handlers trap('TERM') { shutdown } trap('INT') { shutdown } trap('QUIT') { shutdown } trap 'SIGHUP', 'IGNORE' end # Public: Starts the worker eventloop # # Examples # # worker = SomeWorker.new() # worker.start # def start register_signal_handlers log.info("Registered event handlers...") EM.synchrony do do_work end end # Internal Gracefully kills the eventmachine loop # # Examples # # EM.run do # ... do stuff ... # shutdown # end # def shutdown EM.stop_event_loop log.info("Shutting down...") end # Internal A method called inside of an eventmachine loop # on the class including the Base module. Remember adding # a do_work method to any other module included in the same # class as Base will need to call super to not break any # functionality. # # Examples # # EM.run do # do_work # end # def do_work # does things end end end Renabled SEMILOGGING WAT? # encoding: utf-8 require 'eventmachine' require "em-synchrony" require "em-synchrony/em-http" require 'fileutils' require 'logger' require 'ext/multi_delegator' module Worker # Public: To create a worker of some sort you need to start by including # this Base module. This will give give you the methods required to spawn # the worker through the executable, add logging & process tracking. module Base def self.included(base) base.extend(ClassMethods) end module ClassMethods # Public: Initializes a worker and calls start on it's instance it straight after # # options - A hash of options for the worker # # Examples # # SomeWorker.start # # Returns whatever start returns. def start(options={}) self.new(options).start end # Public: Initializes a worker and calls start on it's instance it straight after # # options - A hash of options for the worker # # Examples # # SomeWorker.start # # Returns whatever start returns. # def spawn(options={}) # self.new(options).start # end end # Public: Initializes a worker # # options - A hash of options for the worker # # Examples # # SomeWorker.new() # # Returns the worker object. def initialize(options={}) @root = File.expand_path('../../../../../', __FILE__) if @log.nil? # @logdir = @root + "/log/worker" # FileUtils.mkdir_p @logdir # @logfile = @logdir + "/#{self.class.to_s.downcase}.log" # FileUtils.touch @logfile @log = Logger.new #MultiDelegator.delegate(:write, :close).to(STDOUT, File.open(@logfile,'a')) @log.level = Logger::DEBUG # TODO Only log if development environment @log.formatter = proc do |severity, datetime, progname, msg| "[#{severity}] - #{datetime}: #{msg}\n" end @log.info("Started logging in: #{@logfile}") end return self end # Public: Returns the log object # # Returns the log object. def log @log end # Internal This is used gracefully kill the application # when process receives certain signals. # # Examples # # EM.run do # shutdown! # end # def register_signal_handlers trap('TERM') { shutdown } trap('INT') { shutdown } trap('QUIT') { shutdown } trap 'SIGHUP', 'IGNORE' end # Public: Starts the worker eventloop # # Examples # # worker = SomeWorker.new() # worker.start # def start register_signal_handlers log.info("Registered event handlers...") EM.synchrony do do_work end end # Internal Gracefully kills the eventmachine loop # # Examples # # EM.run do # ... do stuff ... # shutdown # end # def shutdown EM.stop_event_loop log.info("Shutting down...") end # Internal A method called inside of an eventmachine loop # on the class including the Base module. Remember adding # a do_work method to any other module included in the same # class as Base will need to call super to not break any # functionality. # # Examples # # EM.run do # do_work # end # def do_work # does things end end end
# frozen_string_literal: true # rubocop: disable all module Stones VERSION = '1.2.0' # 2022-02-12 # VERSION = '1.1.3' # 2021-06-23 # VERSION = '1.1.2' # 2020-04-27 # VERSION = '1.1.1' # 2020-03-22 # VERSION = '1.1.0' # 2020-03-02 # VERSION = '1.0.10'# 2019-09-27 # VERSION = '1.0.9' # 2018-11-11 # VERSION = '1.0.7' # 2018-11-10 # VERSION = '1.0.6' # 2018-10-29 # VERSION = '1.0.5' # 2018-09-09 # VERSION = '1.0.4' # 2018-08-06 # VERSION = '1.0.3' end 'v1.2.1' # frozen_string_literal: true # rubocop: disable all module Stones VERSION = '1.2.1' # 2022-09-29 # VERSION = '1.2.0' # 2022-02-12 # VERSION = '1.1.3' # 2021-06-23 # VERSION = '1.1.2' # 2020-04-27 # VERSION = '1.1.1' # 2020-03-22 # VERSION = '1.1.0' # 2020-03-02 # VERSION = '1.0.10'# 2019-09-27 # VERSION = '1.0.9' # 2018-11-11 # VERSION = '1.0.7' # 2018-11-10 # VERSION = '1.0.6' # 2018-10-29 # VERSION = '1.0.5' # 2018-09-09 # VERSION = '1.0.4' # 2018-08-06 # VERSION = '1.0.3' end
begin require 'rails' require 'cached_counts/railtie' rescue LoadError #do nothing end require 'cached_counts/Active_record_base_methods' require 'cached_counts/active_record_relation_methods' require 'cached_counts/cache' require 'cached_counts/version' module CachedCounts end Lowercase filenames, duh begin require 'rails' require 'cached_counts/railtie' rescue LoadError #do nothing end require 'cached_counts/active_record_base_methods' require 'cached_counts/active_record_relation_methods' require 'cached_counts/cache' require 'cached_counts/version' module CachedCounts end
require 'rschema' require 'rschema/cidr_schema' require 'rschema/aws_region' require 'rschema/aws_ami' require 'rschema/aws_instance_type' require 'baustelle/config/validator/application' module Baustelle module Config module Validator include RSchema::DSL::Base extend self def call(config_hash) RSchema.validation_error(schema(config_hash), config_hash) end private def schema(config_hash) root = root_schema(config_hash) root.merge('environments' => hash_of( String => optional_tree(root).merge(environment_schema(config_hash)) )) end def environment_schema(config_hash) environments = Set.new(config_hash.fetch('environments', {}).keys) RSchema.schema { { optional('eb_application_version_source') => enum(environments + ['git']) } } end def optional_tree(root) case root when Hash root.inject({}) { |result, (key, value)| result.merge(optional_key(key) => optional_tree(value)) } when RSchema::GenericHashSchema RSchema::GenericHashSchema.new(optional_key(root.key_subschema), optional_tree(root.value_subschema)) when RSchema::EitherSchema RSchema::EitherSchema.new(root.alternatives.map(&method(:optional_tree))) when Array root.map(&method(:optional_tree)) else root end end def optional_key(key) case key when RSchema::OptionalHashKey, Class, Struct then key else RSchema::OptionalHashKey.new(key) end end def root_schema(config_hash) RSchema.schema { { optional('base_amis') => hash_of( String => in_each_region { |region| existing_ami(region) }. merge('user' => String, 'system' => enum(%w(ubuntu amazon)), optional('user_data') => String) ), optional('jenkins') => { 'connection' => { 'server_url' => String, 'username' => String, 'password' => String }, 'options' => { 'credentials' => { 'git' => String, optional('dockerhub') => String }, optional('maven_settings_id') => String } }, 'vpc' => { 'cidr' => cidr, 'subnets' => hash_of(enum(%w(a b c d e)) => cidr), optional('peers') => hash_of( String => { 'vpc_id' => predicate("valid vpc id") { |v| v.is_a?(String) && v =~ /^vpc-.+$/ }, 'cidr' => cidr } ) }, 'stacks' => hash_of( String => { 'solution' => String, optional('ami') => in_each_region { |region| existing_ami(region) } } ), optional('bastion') => { 'instance_type' => instance_type, 'ami' => in_each_region { |region| existing_ami(region) }, 'github_ssh_keys' => [String] }, 'backends' => { optional('RabbitMQ') => hash_of( String => { 'ami' => in_each_region { |region| existing_ami(region) }, 'cluster_size' => Fixnum } ), optional('Redis') => hash_of( String => { 'cache_node_type' => instance_type(:cache), 'cluster_size' => Fixnum, optional('instance_type') => instance_type } ), optional('Kinesis') => hash_of( String => { 'shard_count' => Fixnum } ), optional('Postgres') => hash_of( String => { 'storage' => Fixnum, 'instance_type' => instance_type(:rds), 'username' => String, 'password' => String, optional('multi_az') => boolean } ), optional('External') => hash_of(String => Hash) }, 'applications' => hash_of( String => Validator::Application.new(config_hash).schema ), 'environments' => Hash } } end end end end Allow dns_zone param in bastion config require 'rschema' require 'rschema/cidr_schema' require 'rschema/aws_region' require 'rschema/aws_ami' require 'rschema/aws_instance_type' require 'baustelle/config/validator/application' module Baustelle module Config module Validator include RSchema::DSL::Base extend self def call(config_hash) RSchema.validation_error(schema(config_hash), config_hash) end private def schema(config_hash) root = root_schema(config_hash) root.merge('environments' => hash_of( String => optional_tree(root).merge(environment_schema(config_hash)) )) end def environment_schema(config_hash) environments = Set.new(config_hash.fetch('environments', {}).keys) RSchema.schema { { optional('eb_application_version_source') => enum(environments + ['git']) } } end def optional_tree(root) case root when Hash root.inject({}) { |result, (key, value)| result.merge(optional_key(key) => optional_tree(value)) } when RSchema::GenericHashSchema RSchema::GenericHashSchema.new(optional_key(root.key_subschema), optional_tree(root.value_subschema)) when RSchema::EitherSchema RSchema::EitherSchema.new(root.alternatives.map(&method(:optional_tree))) when Array root.map(&method(:optional_tree)) else root end end def optional_key(key) case key when RSchema::OptionalHashKey, Class, Struct then key else RSchema::OptionalHashKey.new(key) end end def root_schema(config_hash) RSchema.schema { { optional('base_amis') => hash_of( String => in_each_region { |region| existing_ami(region) }. merge('user' => String, 'system' => enum(%w(ubuntu amazon)), optional('user_data') => String) ), optional('jenkins') => { 'connection' => { 'server_url' => String, 'username' => String, 'password' => String }, 'options' => { 'credentials' => { 'git' => String, optional('dockerhub') => String }, optional('maven_settings_id') => String } }, 'vpc' => { 'cidr' => cidr, 'subnets' => hash_of(enum(%w(a b c d e)) => cidr), optional('peers') => hash_of( String => { 'vpc_id' => predicate("valid vpc id") { |v| v.is_a?(String) && v =~ /^vpc-.+$/ }, 'cidr' => cidr } ) }, 'stacks' => hash_of( String => { 'solution' => String, optional('ami') => in_each_region { |region| existing_ami(region) } } ), optional('bastion') => { 'instance_type' => instance_type, 'ami' => in_each_region { |region| existing_ami(region) }, 'github_ssh_keys' => [String], 'dns_zone' => String }, 'backends' => { optional('RabbitMQ') => hash_of( String => { 'ami' => in_each_region { |region| existing_ami(region) }, 'cluster_size' => Fixnum } ), optional('Redis') => hash_of( String => { 'cache_node_type' => instance_type(:cache), 'cluster_size' => Fixnum, optional('instance_type') => instance_type } ), optional('Kinesis') => hash_of( String => { 'shard_count' => Fixnum } ), optional('Postgres') => hash_of( String => { 'storage' => Fixnum, 'instance_type' => instance_type(:rds), 'username' => String, 'password' => String, optional('multi_az') => boolean } ), optional('External') => hash_of(String => Hash) }, 'applications' => hash_of( String => Validator::Application.new(config_hash).schema ), 'environments' => Hash } } end end end end
module Storys VERSION = "0.0.5" end Bump version module Storys VERSION = "0.0.6" end
module BcmsTools module Thumbnails # for future bcms tools gem #http://snippets.dzone.com/posts/show/295 #def close_tags(text) # open_tags = [] # text.scan(/\<([^\>\s\/]+)[^\>\/]*?\>/).each { |t| open_tags.unshift(t) } # text.scan(/\<\/([^\>\s\/]+)[^\>]*?\>/).each { |t| open_tags.slice!(open_tags.index(t)) } # open_tags.each {|t| text += "</#{t}>" } # text #end def self.thumbnail_name_from_attachment(aAttachment,aWidth,aHeight) extThumb = aAttachment.file_extension size = "#{aWidth}x#{aHeight}" return File.basename(aAttachment.file_location)+'-'+size+'.'+extThumb end def self.attachment_from_url(aUrl) if aUrl.begins_with?('/cms/attachments/') id,version = aUrl.scan(/\/cms\/attachments\/([0-9]+)\?version=([0-9]+)/).flatten.map {|i| i.to_i} att = Attachment.find_by_id_and_version(id,version) else att = Attachment.find_live_by_file_path(aUrl) end end def self.image_location_from_url(aUrl) att = attachment_from_url(aUrl) return att && att.full_file_location end def self.scale_to_fit(aWidth,aHeight,aDestWidth,aDestHeight) wRatio = aDestWidth / aWidth hRatio = aDestHeight / aHeight ratio = (wRatio < hRatio ? wRatio : hRatio) return aWidth*ratio,aHeight*ratio end end module PageHelper def container_sized(aName,aWidth,aHeight) StringUtils.split3(container(aName),/<img.*?>/,-1) do |head,img,tail| src = XmlUtils.quick_att_from_tag(img,'src') if src.begins_with?('/images/cms/') # a cms button img else thumberize_img(img,aWidth,aHeight) # an image in the container end end end # with_images( container(:image_bar) ) do |img| # thumberize_img(img,width,height) # end def with_images(aContainer) return nil if aContainer.nil? result = aContainer.clone offset = 0 aContainer.scan_md(/<img.*?>/).each do |img_md| src = XmlUtils.quick_att_from_tag(img_md.to_s,'src') next if !src || src.begins_with?('/images/cms/') first,last = img_md.offset(0) output = yield(img_md.to_s) result[first+offset..last-1+offset] = output offset += output.length - (last-first) end result end def thumberize_img(img,aWidth,aHeight) begin urlImage = XmlUtils.quick_att_from_tag(img,'src') att = BcmsTools::Thumbnails::attachment_from_url(urlImage) pathImage = att && att.full_file_location throw RuntimeError.new("file doesn't exist #{pathImage}") unless File.exists? pathImage throw RuntimeError.new("could not get file geometry #{pathImage}") unless geomImage = Paperclip::Geometry.from_file(pathImage) aDestWidth,aDestHeight = BcmsTools::Thumbnails::scale_to_fit(geomImage.width,geomImage.height,aWidth,aHeight).map {|i| i.to_i} nameThumb = BcmsTools::Thumbnails::thumbnail_name_from_attachment(att,aWidth,aHeight) pathThumb = File.join(APP_CONFIG[:thumbs_cache],nameThumb) if !File.exists?(pathThumb) # generate thumbnail at size to fit container throw RuntimeError.new("Failed reading image #{pathImage}") unless objThumb = Paperclip::Thumbnail.new(File.new(pathImage), "#{aDestWidth}x#{aDestHeight}") throw RuntimeError.new("Failed making thumbnail #{pathImage}") unless foThumb = objThumb.make FileUtils.cp(foThumb.path,pathThumb,:force => true) FileUtils.rm(foThumb.path) #POpen4::shell_out("sudo -u tca chgrp www-data #{pathThumb}; sudo -u tca chmod 644 #{pathThumb}") end img = XmlUtils.quick_set_att(img,'src',File.join(APP_CONFIG[:thumbs_url],nameThumb)) return HtmlUtils.fixed_frame_image(img,aWidth,aHeight,aDestWidth,aDestHeight) rescue Exception => e RAILS_DEFAULT_LOGGER.warn "thumberize_img error: #{e.inspect}" RAILS_DEFAULT_LOGGER.debug e.backtrace return img end end def attachment_cropped_src(aAttachment,aWidth,aHeight) begin pathImage = aAttachment.full_file_location throw RuntimeError.new("file doesn't exist #{pathImage}") unless File.exists? pathImage nameThumb = BcmsTools::Thumbnails::thumbnail_name_from_attachment(aAttachment,aWidth,aHeight) pathThumb = File.join(APP_CONFIG[:thumbs_cache],nameThumb) if !File.exists?(pathThumb) # generate thumbnail at size to fit container throw RuntimeError.new("Failed reading image #{pathImage}") unless objThumb = Paperclip::Thumbnail.new(File.new(pathImage), "#{aWidth}x#{aHeight}#") throw RuntimeError.new("Failed making thumbnail #{pathImage}") unless foThumb = objThumb.make FileUtils.cp(foThumb.path,pathThumb,:force => true) FileUtils.rm(foThumb.path) end return File.join(APP_CONFIG[:thumbs_url],nameThumb) rescue Exception => e RAILS_DEFAULT_LOGGER.warn "thumberize_img error: #{e.inspect}" RAILS_DEFAULT_LOGGER.debug e.backtrace return '' end end def framed_attachment_img(aAttachment,aWidth,aHeight) begin pathImage = aAttachment.full_file_location throw RuntimeError.new("file doesn't exist #{pathImage}") unless File.exists? pathImage throw RuntimeError.new("could not get file geometry #{pathImage}") unless geomImage = Paperclip::Geometry.from_file(pathImage) aDestWidth,aDestHeight = BcmsTools::Thumbnails::scale_to_fit(geomImage.width,geomImage.height,aWidth,aHeight).map {|i| i.to_i} nameThumb = BcmsTools::Thumbnails::thumbnail_name_from_attachment(aAttachment,aWidth,aHeight) pathThumb = File.join(APP_CONFIG[:thumbs_cache],nameThumb) if !File.exists?(pathThumb) throw RuntimeError.new("Failed reading image #{pathImage}") unless objThumb = Paperclip::Thumbnail.new(File.new(pathImage), "#{aDestWidth}x#{aDestHeight}") throw RuntimeError.new("Failed making thumbnail #{pathImage}") unless foThumb = objThumb.make FileUtils.cp(foThumb.path,pathThumb,:force => true) FileUtils.rm(foThumb.path) end img = "<img src=\"#{File.join(APP_CONFIG[:thumbs_url],nameThumb)}\" width=\"#{aDestWidth}\" height=\"#{aDestHeight}\" />" return HtmlUtils.fixed_frame_image(img,aWidth,aHeight,aDestWidth,aDestHeight) rescue Exception => e RAILS_DEFAULT_LOGGER.warn "thumberize_img error: #{e.inspect}" RAILS_DEFAULT_LOGGER.debug e.backtrace return '' end end end end set mode of thumbnail file module BcmsTools module Thumbnails # for future bcms tools gem #http://snippets.dzone.com/posts/show/295 #def close_tags(text) # open_tags = [] # text.scan(/\<([^\>\s\/]+)[^\>\/]*?\>/).each { |t| open_tags.unshift(t) } # text.scan(/\<\/([^\>\s\/]+)[^\>]*?\>/).each { |t| open_tags.slice!(open_tags.index(t)) } # open_tags.each {|t| text += "</#{t}>" } # text #end def self.thumbnail_name_from_attachment(aAttachment,aWidth,aHeight) extThumb = aAttachment.file_extension size = "#{aWidth}x#{aHeight}" return File.basename(aAttachment.file_location)+'-'+size+'.'+extThumb end def self.attachment_from_url(aUrl) if aUrl.begins_with?('/cms/attachments/') id,version = aUrl.scan(/\/cms\/attachments\/([0-9]+)\?version=([0-9]+)/).flatten.map {|i| i.to_i} att = Attachment.find_by_id_and_version(id,version) else att = Attachment.find_live_by_file_path(aUrl) end end def self.image_location_from_url(aUrl) att = attachment_from_url(aUrl) return att && att.full_file_location end def self.scale_to_fit(aWidth,aHeight,aDestWidth,aDestHeight) wRatio = aDestWidth / aWidth hRatio = aDestHeight / aHeight ratio = (wRatio < hRatio ? wRatio : hRatio) return aWidth*ratio,aHeight*ratio end end module PageHelper def container_sized(aName,aWidth,aHeight) StringUtils.split3(container(aName),/<img.*?>/,-1) do |head,img,tail| src = XmlUtils.quick_att_from_tag(img,'src') if src.begins_with?('/images/cms/') # a cms button img else thumberize_img(img,aWidth,aHeight) # an image in the container end end end # with_images( container(:image_bar) ) do |img| # thumberize_img(img,width,height) # end def with_images(aContainer) return nil if aContainer.nil? result = aContainer.clone offset = 0 aContainer.scan_md(/<img.*?>/).each do |img_md| src = XmlUtils.quick_att_from_tag(img_md.to_s,'src') next if !src || src.begins_with?('/images/cms/') first,last = img_md.offset(0) output = yield(img_md.to_s) result[first+offset..last-1+offset] = output offset += output.length - (last-first) end result end def thumberize_img(img,aWidth,aHeight) begin urlImage = XmlUtils.quick_att_from_tag(img,'src') att = BcmsTools::Thumbnails::attachment_from_url(urlImage) pathImage = att && att.full_file_location throw RuntimeError.new("file doesn't exist #{pathImage}") unless File.exists? pathImage throw RuntimeError.new("could not get file geometry #{pathImage}") unless geomImage = Paperclip::Geometry.from_file(pathImage) aDestWidth,aDestHeight = BcmsTools::Thumbnails::scale_to_fit(geomImage.width,geomImage.height,aWidth,aHeight).map {|i| i.to_i} nameThumb = BcmsTools::Thumbnails::thumbnail_name_from_attachment(att,aWidth,aHeight) pathThumb = File.join(APP_CONFIG[:thumbs_cache],nameThumb) if !File.exists?(pathThumb) # generate thumbnail at size to fit container throw RuntimeError.new("Failed reading image #{pathImage}") unless objThumb = Paperclip::Thumbnail.new(File.new(pathImage), "#{aDestWidth}x#{aDestHeight}") throw RuntimeError.new("Failed making thumbnail #{pathImage}") unless foThumb = objThumb.make FileUtils.cp(foThumb.path,pathThumb,:preserve => true) FileUtils.chmod(0644,pathThumb) FileUtils.rm(foThumb.path) #POpen4::shell_out("sudo -u tca chgrp www-data #{pathThumb}; sudo -u tca chmod 644 #{pathThumb}") end img = XmlUtils.quick_set_att(img,'src',File.join(APP_CONFIG[:thumbs_url],nameThumb)) return HtmlUtils.fixed_frame_image(img,aWidth,aHeight,aDestWidth,aDestHeight) rescue Exception => e RAILS_DEFAULT_LOGGER.warn "thumberize_img error: #{e.inspect}" RAILS_DEFAULT_LOGGER.debug e.backtrace return img end end def attachment_cropped_src(aAttachment,aWidth,aHeight) begin pathImage = aAttachment.full_file_location throw RuntimeError.new("file doesn't exist #{pathImage}") unless File.exists? pathImage nameThumb = BcmsTools::Thumbnails::thumbnail_name_from_attachment(aAttachment,aWidth,aHeight) pathThumb = File.join(APP_CONFIG[:thumbs_cache],nameThumb) if !File.exists?(pathThumb) # generate thumbnail at size to fit container throw RuntimeError.new("Failed reading image #{pathImage}") unless objThumb = Paperclip::Thumbnail.new(File.new(pathImage), "#{aWidth}x#{aHeight}#") throw RuntimeError.new("Failed making thumbnail #{pathImage}") unless foThumb = objThumb.make FileUtils.cp(foThumb.path,pathThumb) FileUtils.chmod(0644,pathThumb) FileUtils.rm(foThumb.path) end return File.join(APP_CONFIG[:thumbs_url],nameThumb) rescue Exception => e RAILS_DEFAULT_LOGGER.warn "thumberize_img error: #{e.inspect}" RAILS_DEFAULT_LOGGER.debug e.backtrace return '' end end def framed_attachment_img(aAttachment,aWidth,aHeight) begin pathImage = aAttachment.full_file_location throw RuntimeError.new("file doesn't exist #{pathImage}") unless File.exists? pathImage throw RuntimeError.new("could not get file geometry #{pathImage}") unless geomImage = Paperclip::Geometry.from_file(pathImage) aDestWidth,aDestHeight = BcmsTools::Thumbnails::scale_to_fit(geomImage.width,geomImage.height,aWidth,aHeight).map {|i| i.to_i} nameThumb = BcmsTools::Thumbnails::thumbnail_name_from_attachment(aAttachment,aWidth,aHeight) pathThumb = File.join(APP_CONFIG[:thumbs_cache],nameThumb) if !File.exists?(pathThumb) throw RuntimeError.new("Failed reading image #{pathImage}") unless objThumb = Paperclip::Thumbnail.new(File.new(pathImage), "#{aDestWidth}x#{aDestHeight}") throw RuntimeError.new("Failed making thumbnail #{pathImage}") unless foThumb = objThumb.make FileUtils.cp(foThumb.path,pathThumb) FileUtils.chmod(0644,pathThumb) FileUtils.rm(foThumb.path) end img = "<img src=\"#{File.join(APP_CONFIG[:thumbs_url],nameThumb)}\" width=\"#{aDestWidth}\" height=\"#{aDestHeight}\" />" return HtmlUtils.fixed_frame_image(img,aWidth,aHeight,aDestWidth,aDestHeight) rescue Exception => e RAILS_DEFAULT_LOGGER.warn "thumberize_img error: #{e.inspect}" RAILS_DEFAULT_LOGGER.debug e.backtrace return '' end end end end
module Calais class Client # base attributes of the call attr_accessor :content attr_accessor :license_id # processing directives attr_accessor :content_type, :output_format, :reltag_base_url, :calculate_relevance, :omit_outputting_original_text attr_accessor :metadata_enables, :metadata_discards # user directives attr_accessor :allow_distribution, :allow_search, :external_id, :submitter attr_accessor :external_metadata attr_accessor :use_beta def initialize(options={}, &block) options.each {|k,v| send("#{k}=", v)} yield(self) if block_given? end def enlighten post_args = { "licenseID" => @license_id, "content" => Iconv.iconv('UTF-8//IGNORE', 'UTF-8', "#{@content} ").first[0..-2], "paramsXML" => params_xml } @client ||= Curl::Easy.new @client.url = @use_beta ? BETA_REST_ENDPOINT : REST_ENDPOINT @client.timeout = HTTP_TIMEOUT post_fields = post_args.map {|k,v| Curl::PostField.content(k, v) } do_request(post_fields) end def params_xml check_params document = Nokogiri::XML::Document.new params_node = Nokogiri::XML::Node.new('c:params', document) params_node['xmlns:c'] = 'http://s.opencalais.com/1/pred/' params_node['xmlns:rdf'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' processing_node = Nokogiri::XML::Node.new('c:processingDirectives', document) processing_node['c:contentType'] = AVAILABLE_CONTENT_TYPES[@content_type] if @content_type processing_node['c:outputFormat'] = AVAILABLE_OUTPUT_FORMATS[@output_format] if @output_format processing_node['c:calculateRelevanceScore'] = 'false' if @calculate_relevance == false processing_node['c:reltagBaseURL'] = @reltag_base_url.to_s if @reltag_base_url processing_node['c:enableMetadataType'] = @metadata_enables.join(',') unless @metadata_enables.empty? processing_node['c:discardMetadata'] = @metadata_discards.join(';') unless @metadata_discards.empty? processing_node['c:omitOutputtingOriginalText'] = 'true' if @omit_outputting_original_text user_node = Nokogiri::XML::Node.new('c:userDirectives', document) user_node['c:allowDistribution'] = @allow_distribution.to_s unless @allow_distribution.nil? user_node['c:allowSearch'] = @allow_search.to_s unless @allow_search.nil? user_node['c:externalID'] = @external_id.to_s if @external_id user_node['c:submitter'] = @submitter.to_s if @submitter params_node << processing_node params_node << user_node if @external_metadata external_node = Nokogiri::XML::Node.new('c:externalMetadata', document) external_node << @external_metadata params_node << external_node end params_node.to_xml(:indent => 2) end private def check_params raise 'missing content' if @content.nil? || @content.empty? content_length = @content.length raise 'content is too small' if content_length < MIN_CONTENT_SIZE raise 'content is too large' if content_length > MAX_CONTENT_SIZE raise 'missing license id' if @license_id.nil? || @license_id.empty? raise 'unknown content type' unless AVAILABLE_CONTENT_TYPES.keys.include?(@content_type) if @content_type raise 'unknown output format' unless AVAILABLE_OUTPUT_FORMATS.keys.include?(@output_format) if @output_format %w[calculate_relevance allow_distribution allow_search].each do |variable| value = self.send(variable) unless NilClass === value || TrueClass === value || FalseClass === value raise "expected a boolean value for #{variable} but got #{value}" end end @metadata_enables ||= [] unknown_enables = Set.new(@metadata_enables) - KNOWN_ENABLES raise "unknown metadata enables: #{unknown_enables.to_ainspect}" unless unknown_enables.empty? @metadata_discards ||= [] unknown_discards = Set.new(@metadata_discards) - KNOWN_DISCARDS raise "unknown metadata discards: #{unknown_discards.to_ainspect}" unless unknown_discards.empty? end def do_request(post_fields) unless @client.http_post(post_fields) raise 'unable to post to api endpoint' end @client.body_str end end end added store_rdf option which enables the docRDFaccessible processing directive module Calais class Client # base attributes of the call attr_accessor :content attr_accessor :license_id # processing directives attr_accessor :content_type, :output_format, :reltag_base_url, :calculate_relevance, :omit_outputting_original_text attr_accessor :store_rdf, :metadata_enables, :metadata_discards # user directives attr_accessor :allow_distribution, :allow_search, :external_id, :submitter attr_accessor :external_metadata attr_accessor :use_beta def initialize(options={}, &block) options.each {|k,v| send("#{k}=", v)} yield(self) if block_given? end def enlighten post_args = { "licenseID" => @license_id, "content" => Iconv.iconv('UTF-8//IGNORE', 'UTF-8', "#{@content} ").first[0..-2], "paramsXML" => params_xml } @client ||= Curl::Easy.new @client.url = @use_beta ? BETA_REST_ENDPOINT : REST_ENDPOINT @client.timeout = HTTP_TIMEOUT post_fields = post_args.map {|k,v| Curl::PostField.content(k, v) } do_request(post_fields) end def params_xml check_params document = Nokogiri::XML::Document.new params_node = Nokogiri::XML::Node.new('c:params', document) params_node['xmlns:c'] = 'http://s.opencalais.com/1/pred/' params_node['xmlns:rdf'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' processing_node = Nokogiri::XML::Node.new('c:processingDirectives', document) processing_node['c:contentType'] = AVAILABLE_CONTENT_TYPES[@content_type] if @content_type processing_node['c:outputFormat'] = AVAILABLE_OUTPUT_FORMATS[@output_format] if @output_format processing_node['c:calculateRelevanceScore'] = 'false' if @calculate_relevance == false processing_node['c:reltagBaseURL'] = @reltag_base_url.to_s if @reltag_base_url processing_node['c:enableMetadataType'] = @metadata_enables.join(',') unless @metadata_enables.empty? processing_node['c:docRDFaccessible'] = @store_rdf if @store_rdf processing_node['c:discardMetadata'] = @metadata_discards.join(';') unless @metadata_discards.empty? processing_node['c:omitOutputtingOriginalText'] = 'true' if @omit_outputting_original_text user_node = Nokogiri::XML::Node.new('c:userDirectives', document) user_node['c:allowDistribution'] = @allow_distribution.to_s unless @allow_distribution.nil? user_node['c:allowSearch'] = @allow_search.to_s unless @allow_search.nil? user_node['c:externalID'] = @external_id.to_s if @external_id user_node['c:submitter'] = @submitter.to_s if @submitter params_node << processing_node params_node << user_node if @external_metadata external_node = Nokogiri::XML::Node.new('c:externalMetadata', document) external_node << @external_metadata params_node << external_node end params_node.to_xml(:indent => 2) end private def check_params raise 'missing content' if @content.nil? || @content.empty? content_length = @content.length raise 'content is too small' if content_length < MIN_CONTENT_SIZE raise 'content is too large' if content_length > MAX_CONTENT_SIZE raise 'missing license id' if @license_id.nil? || @license_id.empty? raise 'unknown content type' unless AVAILABLE_CONTENT_TYPES.keys.include?(@content_type) if @content_type raise 'unknown output format' unless AVAILABLE_OUTPUT_FORMATS.keys.include?(@output_format) if @output_format %w[calculate_relevance store_rdf allow_distribution allow_search].each do |variable| value = self.send(variable) unless NilClass === value || TrueClass === value || FalseClass === value raise "expected a boolean value for #{variable} but got #{value}" end end @metadata_enables ||= [] unknown_enables = Set.new(@metadata_enables) - KNOWN_ENABLES raise "unknown metadata enables: #{unknown_enables.to_ainspect}" unless unknown_enables.empty? @metadata_discards ||= [] unknown_discards = Set.new(@metadata_discards) - KNOWN_DISCARDS raise "unknown metadata discards: #{unknown_discards.to_ainspect}" unless unknown_discards.empty? end def do_request(post_fields) unless @client.http_post(post_fields) raise 'unable to post to api endpoint' end @client.body_str end end end
# This Service handles creating and updating Stripe subscriptions, # because these 2 actions have VAT/invoice consequences. class StripeService # customer_id - Stripe customer id. def initialize(customer_id:) @customer_id = customer_id end # When creating a subscription in Stripe, an invoice is created, # and paid (charged) IMMEDIATELY. This would result in an invoice # without VAT charges. # # Our solution is to first add VAT charges to the upcoming invoice # and then subscribing the customer to the plan. # # options - All options that can be passed to Stripe subscription create. # # Returns the created Stripe subscription and invoice. def create_subscription(options) # Get the plan. plan = Stripe::Plan.retrieve(options[:plan]) # Charge VAT in advance because subscription call will create and pay an invoice. # TK actually we need to apply VAT for invoiceitems that are pending and scheduled # for the next invoice. # Do not charge VAT if the plan or the subscription is still in trial (invoice will come later). vat, invoice_item = charge_vat_of_plan(plan) unless \ plan.trial_period_days || (options[:trial_end] && options[:trial_end] != 'now') # Start subscription. # This call automatically creates an invoice, always. subscription = customer.subscriptions.create(options) [subscription, last_invoice] rescue Stripe::StripeError => e # Something failed in Stripe, if we already charged for VAT, # we need to rollback this. As we may charge twice later otherwise. invoice_item.delete if invoice_item raise e end # Applies VAT to a Stripe invoice if necessary. # Copies customer metadata to the invoice, to make it immutable # for the invoice (in case the customer's metadata changes). # # invoice - A Stripe invoice object. # # Returns the finalized stripe invoice. def apply_vat(invoice_id:) stripe_invoice = Stripe::Invoice.retrieve(invoice_id) # Add VAT to the invoice. vat, invoice_item = charge_vat(stripe_invoice.subtotal, invoice_id: invoice_id, currency: stripe_invoice.currency) Stripe::Invoice.retrieve(invoice_id) end # Snapshots the final correct state of an invoice. It copies # customer metadata to invoice metadata and figures out the right # amount of VAT and discount. # # stripe_invoice - The Stripe invoice to snapshot. # # Returns a hash that contains all snapshotted data. def snapshot_final(stripe_invoice:) # Start off with the customer metadata. metadata = customer.metadata.to_h # Find the VAT invoice item. vat_line = stripe_invoice.lines.find { |line| line.metadata[:type] == 'vat' } other_lines = stripe_invoice.lines.to_a - [vat_line] subtotal = other_lines.map(&:amount).inject(:+) metadata.merge! \ subtotal: subtotal, total: stripe_invoice.total # If there is vat and a discount, we need to recalculate VAT and the discount. more = if vat_line && stripe_invoice.discount p subtotal # Recalculate discount based on the sum of all lines besides the vat line. discount = calculate_discount(subtotal, stripe_invoice.discount.coupon) subtotal_after_discount = subtotal - discount # Recalculate VAT based on the total after discount vat_amount, vat_rate = calculate_vat(subtotal_after_discount).to_a { discount_amount: discount, subtotal_after_discount: subtotal_after_discount, vat_amount: vat_amount, vat_rate: vat_rate } else { discount_amount: stripe_invoice.subtotal - stripe_invoice.total, subtotal_after_discount: stripe_invoice.total, vat_amount: (vat_line && vat_line.metadata[:amount]).to_i, vat_rate: (vat_line && vat_line.metadata[:rate]).to_i } end stripe_invoice.metadata = metadata.merge!(more) stripe_invoice.save metadata end private def last_invoice Stripe::Invoice.all(customer: customer.id, limit: 1).first end def charge_vat_of_plan(plan) # Add vat charges. charge_vat(plan.amount, currency: plan.currency) end # Charges VAT for a certain amount. # # amount - Amount to charge VAT for. # invoice_id - optional invoice_id (upcoming invoice by default). # # Returns a VatCharge object. def charge_vat(amount, currency:, invoice_id: nil) # Calculate the amount of VAT to be paid. vat = calculate_vat(amount) # Add an invoice item to the invoice with this amount. invoice_item = Stripe::InvoiceItem.create( customer: customer.id, invoice: invoice_id, amount: vat.amount, currency: currency, description: "VAT (#{vat.rate}%)", metadata: { type: 'vat', amount: vat.amount, rate: vat.rate } ) unless vat.amount.zero? [vat, invoice_item] end def calculate_vat(amount) vat_service.calculate \ amount: amount, country_code: customer.metadata[:country_code], vat_registered: (customer.metadata[:vat_registered] == 'true') end # Calculates the amount of discount given on an amount # with a certain Stripe coupon. def calculate_discount(amount, coupon) if coupon.percent_off ((amount*coupon.percent_off)/100.0).round else amount - coupon.amount_off end end def customer @customer ||= Stripe::Customer.retrieve(@customer_id) end def vat_service @vat_service ||= VatService.new end end remove print # This Service handles creating and updating Stripe subscriptions, # because these 2 actions have VAT/invoice consequences. class StripeService # customer_id - Stripe customer id. def initialize(customer_id:) @customer_id = customer_id end # When creating a subscription in Stripe, an invoice is created, # and paid (charged) IMMEDIATELY. This would result in an invoice # without VAT charges. # # Our solution is to first add VAT charges to the upcoming invoice # and then subscribing the customer to the plan. # # options - All options that can be passed to Stripe subscription create. # # Returns the created Stripe subscription and invoice. def create_subscription(options) # Get the plan. plan = Stripe::Plan.retrieve(options[:plan]) # Charge VAT in advance because subscription call will create and pay an invoice. # TK actually we need to apply VAT for invoiceitems that are pending and scheduled # for the next invoice. # Do not charge VAT if the plan or the subscription is still in trial (invoice will come later). vat, invoice_item = charge_vat_of_plan(plan) unless \ plan.trial_period_days || (options[:trial_end] && options[:trial_end] != 'now') # Start subscription. # This call automatically creates an invoice, always. subscription = customer.subscriptions.create(options) [subscription, last_invoice] rescue Stripe::StripeError => e # Something failed in Stripe, if we already charged for VAT, # we need to rollback this. As we may charge twice later otherwise. invoice_item.delete if invoice_item raise e end # Applies VAT to a Stripe invoice if necessary. # Copies customer metadata to the invoice, to make it immutable # for the invoice (in case the customer's metadata changes). # # invoice - A Stripe invoice object. # # Returns the finalized stripe invoice. def apply_vat(invoice_id:) stripe_invoice = Stripe::Invoice.retrieve(invoice_id) # Add VAT to the invoice. vat, invoice_item = charge_vat(stripe_invoice.subtotal, invoice_id: invoice_id, currency: stripe_invoice.currency) Stripe::Invoice.retrieve(invoice_id) end # Snapshots the final correct state of an invoice. It copies # customer metadata to invoice metadata and figures out the right # amount of VAT and discount. # # stripe_invoice - The Stripe invoice to snapshot. # # Returns a hash that contains all snapshotted data. def snapshot_final(stripe_invoice:) # Start off with the customer metadata. metadata = customer.metadata.to_h # Find the VAT invoice item. vat_line = stripe_invoice.lines.find { |line| line.metadata[:type] == 'vat' } other_lines = stripe_invoice.lines.to_a - [vat_line] subtotal = other_lines.map(&:amount).inject(:+) metadata.merge! \ subtotal: subtotal, total: stripe_invoice.total # If there is vat and a discount, we need to recalculate VAT and the discount. more = if vat_line && stripe_invoice.discount # Recalculate discount based on the sum of all lines besides the vat line. discount = calculate_discount(subtotal, stripe_invoice.discount.coupon) subtotal_after_discount = subtotal - discount # Recalculate VAT based on the total after discount vat_amount, vat_rate = calculate_vat(subtotal_after_discount).to_a { discount_amount: discount, subtotal_after_discount: subtotal_after_discount, vat_amount: vat_amount, vat_rate: vat_rate } else { discount_amount: stripe_invoice.subtotal - stripe_invoice.total, subtotal_after_discount: stripe_invoice.total, vat_amount: (vat_line && vat_line.metadata[:amount]).to_i, vat_rate: (vat_line && vat_line.metadata[:rate]).to_i } end stripe_invoice.metadata = metadata.merge!(more) stripe_invoice.save metadata end private def last_invoice Stripe::Invoice.all(customer: customer.id, limit: 1).first end def charge_vat_of_plan(plan) # Add vat charges. charge_vat(plan.amount, currency: plan.currency) end # Charges VAT for a certain amount. # # amount - Amount to charge VAT for. # invoice_id - optional invoice_id (upcoming invoice by default). # # Returns a VatCharge object. def charge_vat(amount, currency:, invoice_id: nil) # Calculate the amount of VAT to be paid. vat = calculate_vat(amount) # Add an invoice item to the invoice with this amount. invoice_item = Stripe::InvoiceItem.create( customer: customer.id, invoice: invoice_id, amount: vat.amount, currency: currency, description: "VAT (#{vat.rate}%)", metadata: { type: 'vat', amount: vat.amount, rate: vat.rate } ) unless vat.amount.zero? [vat, invoice_item] end def calculate_vat(amount) vat_service.calculate \ amount: amount, country_code: customer.metadata[:country_code], vat_registered: (customer.metadata[:vat_registered] == 'true') end # Calculates the amount of discount given on an amount # with a certain Stripe coupon. def calculate_discount(amount, coupon) if coupon.percent_off ((amount*coupon.percent_off)/100.0).round else amount - coupon.amount_off end end def customer @customer ||= Stripe::Customer.retrieve(@customer_id) end def vat_service @vat_service ||= VatService.new end end
require 'httparty' require 'json' module Cascade module Roles def self.get(fqdn) begin response = HTTParty.get(Cascade.uri + '/v1/catalog/node/' + fqdn, timeout: 15) JSON.parse(response.body)['Node']['Services']['cascade']['Tags'] rescue [] end end end end fix role parsing require 'httparty' require 'json' module Cascade module Roles def self.get(fqdn) begin response = HTTParty.get(Cascade.uri + '/v1/catalog/node/' + fqdn, timeout: 15) JSON.parse(response.body)['Services']['cascade']['Tags'] rescue [] end end end end
require 'uri' require 'net/https' # Encapsulates CAS functionality. This module is meant to be included in # the CASServer::Controllers module. module CASServer::CAS include CASServer::Models def generate_login_ticket # 3.5 (login ticket) lt = LoginTicket.new lt.ticket = "LT-" + CASServer::Utils.random_string lt.client_hostname = env['REMOTE_HOST'] || env['REMOTE_ADDR'] lt.save! $LOG.debug("Generated login ticket '#{lt.ticket}' for client" + " at '#{lt.client_hostname}'") lt end def generate_ticket_granting_ticket(username) # 3.6 (ticket granting cookie/ticket) tgt = TicketGrantingTicket.new tgt.ticket = "TGC-" + CASServer::Utils.random_string tgt.username = username tgt.client_hostname = env['REMOTE_HOST'] || env['REMOTE_ADDR'] tgt.save! $LOG.debug("Generated ticket granting ticket '#{tgt.ticket}' for user" + " '#{tgt.username}' at '#{tgt.client_hostname}'") tgt end def generate_service_ticket(service, username, tgt) # 3.1 (service ticket) st = ServiceTicket.new st.ticket = "ST-" + CASServer::Utils.random_string st.service = service st.username = username st.ticket_granting_ticket = tgt st.client_hostname = env['REMOTE_HOST'] || env['REMOTE_ADDR'] st.save! $LOG.debug("Generated service ticket '#{st.ticket}' for service '#{st.service}'" + " for user '#{st.username}' at '#{st.client_hostname}'") st end def generate_proxy_ticket(target_service, pgt) # 3.2 (proxy ticket) pt = ProxyTicket.new pt.ticket = "PT-" + CASServer::Utils.random_string pt.service = target_service pt.username = pgt.service_ticket.username pt.proxy_granting_ticket_id = pgt.id pt.client_hostname = env['REMOTE_HOST'] || env['REMOTE_ADDR'] pt.save! $LOG.debug("Generated proxy ticket '#{pt.ticket}' for target service '#{pt.service}'" + " for user '#{pt.username}' at '#{pt.client_hostname}' using proxy-granting" + " ticket '#{pgt.ticket}'") pt end def generate_proxy_granting_ticket(pgt_url, st) uri = URI.parse(pgt_url) https = Net::HTTP.new(uri.host,uri.port) https.use_ssl = true # Here's what's going on here: # # 1. We generate a ProxyGrantingTicket (but don't store it in the database just yet) # 2. Deposit the PGT and it's associated IOU at the proxy callback URL. # 3. If the proxy callback URL responds with HTTP code 200, store the PGT and return it; # otherwise don't save it and return nothing. # https.start do |conn| path = uri.path.empty? ? '/' : uri.path pgt = ProxyGrantingTicket.new pgt.ticket = "PGT-" + CASServer::Utils.random_string(60) pgt.iou = "PGTIOU-" + CASServer::Utils.random_string(57) pgt.service_ticket_id = st.id pgt.client_hostname = env['REMOTE_HOST'] || env['REMOTE_ADDR'] # FIXME: The CAS protocol spec says to use 'pgt' as the parameter, but in practice # the JA-SIG and Yale server implementations use pgtId. We'll go with the # in-practice standard. path += (uri.query.nil? || uri.query.empty? ? '?' : '&') + "pgtId=#{pgt.ticket}&pgtIou=#{pgt.iou}" response = conn.request_get(path) # TODO: follow redirects... 2.5.4 says that redirects MAY be followed if response.code.to_i == 200 # 3.4 (proxy-granting ticket IOU) pgt.save! $LOG.debug "PGT generated for pgt_url '#{pgt_url}': #{pgt.inspect}" pgt else $LOG.warn "PGT callback server responded with a bad result code '#{response.code}'. PGT will not be stored." end end end def validate_login_ticket(ticket) $LOG.debug("Validating login ticket '#{ticket}'") success = false if ticket.nil? error = "Your login request did not include a login ticket. There may be a problem with the authentication system." $LOG.warn("Missing login ticket.") elsif lt = LoginTicket.find_by_ticket(ticket) if lt.consumed? error = "The login ticket you provided has already been used up. Please try logging in again." $LOG.warn("Login ticket '#{ticket}' previously used up") elsif Time.now - lt.created_on < CASServer::Conf.login_ticket_expiry $LOG.info("Login ticket '#{ticket}' successfully validated") else error = "Your login ticket has expired. Please try logging in again." $LOG.warn("Expired login ticket '#{ticket}'") end else error = "The login ticket you provided is invalid. Please try logging in again." $LOG.warn("Invalid login ticket '#{ticket}'") end lt.consume! if lt error end def validate_ticket_granting_ticket(ticket) $LOG.debug("Validating ticket granting ticket '#{ticket}'") if ticket.nil? error = "No ticket granting ticket given." $LOG.debug(error) elsif tgt = TicketGrantingTicket.find_by_ticket(ticket) if CASServer::Conf.expire_sessions && Time.now - tgt.created_on > CASServer::Conf.ticket_granting_ticket_expiry error = "Your session has expired. Please log in again." $LOG.info("Ticket granting ticket '#{ticket}' for user '#{tgt.username}' expired.") else $LOG.info("Ticket granting ticket '#{ticket}' for user '#{tgt.username}' successfully validated.") end else error = "Invalid ticket granting ticket '#{ticket}' (no matching ticket found in the database)." $LOG.warn(error) end [tgt, error] end def validate_service_ticket(service, ticket, allow_proxy_tickets = false) $LOG.debug("Validating service/proxy ticket '#{ticket}' for service '#{service}'") if service.nil? or ticket.nil? error = Error.new("INVALID_REQUEST", "Ticket or service parameter was missing in the request.") $LOG.warn("#{error.code} - #{error.message}") elsif st = ServiceTicket.find_by_ticket(ticket) if st.consumed? error = Error.new("INVALID_TICKET", "Ticket '#{ticket}' has already been used up.") $LOG.warn("#{error.code} - #{error.message}") elsif st.kind_of?(CASServer::Models::ProxyTicket) && !allow_proxy_tickets error = Error.new("INVALID_TICKET", "Ticket '#{ticket}' is a proxy ticket, but only service tickets are allowed here.") $LOG.warn("#{error.code} - #{error.message}") elsif Time.now - st.created_on > CASServer::Conf.service_ticket_expiry error = Error.new("INVALID_TICKET", "Ticket '#{ticket}' has expired.") $LOG.warn("Ticket '#{ticket}' has expired.") elsif !st.matches_service? service error = Error.new("INVALID_SERVICE", "The ticket '#{ticket}' belonging to user '#{st.username}' is valid,"+ " but the requested service '#{service}' does not match the service '#{st.service}' associated with this ticket.") $LOG.warn("#{error.code} - #{error.message}") else $LOG.info("Ticket '#{ticket}' for service '#{service}' for user '#{st.username}' successfully validated.") end else error = Error.new("INVALID_TICKET", "Ticket '#{ticket}' not recognized.") $LOG.warn("#{error.code} - #{error.message}") end if st st.consume! end [st, error] end def validate_proxy_ticket(service, ticket) pt, error = validate_service_ticket(service, ticket, true) if pt.kind_of?(CASServer::Models::ProxyTicket) && !error if not pt.proxy_granting_ticket error = Error.new("INTERNAL_ERROR", "Proxy ticket '#{pt}' belonging to user '#{pt.username}' is not associated with a proxy granting ticket.") elsif not pt.proxy_granting_ticket.service_ticket error = Error.new("INTERNAL_ERROR", "Proxy granting ticket '#{pt.proxy_granting_ticket}'"+ " (associated with proxy ticket '#{pt}' and belonging to user '#{pt.username}' is not associated with a service ticket.") end end [pt, error] end def validate_proxy_granting_ticket(ticket) if ticket.nil? error = Error.new("INVALID_REQUEST", "pgt parameter was missing in the request.") $LOG.warn("#{error.code} - #{error.message}") elsif pgt = ProxyGrantingTicket.find_by_ticket(ticket) if pgt.service_ticket $LOG.info("Proxy granting ticket '#{ticket}' belonging to user '#{pgt.service_ticket.username}' successfully validated.") else error = Error.new("INTERNAL_ERROR", "Proxy granting ticket '#{ticket}' is not associated with a service ticket.") $LOG.error("#{error.code} - #{error.message}") end else error = Error.new("BAD_PGT", "Invalid proxy granting ticket '#{ticket}' (no matching ticket found in the database).") $LOG.warn("#{error.code} - #{error.message}") end [pgt, error] end # Takes an existing ServiceTicket object (presumably pulled from the database) # and sends a POST with logout information to the service that the ticket # was generated for. # # This makes possible the "single sign-out" functionality added in CAS 3.1. # See http://www.ja-sig.org/wiki/display/CASUM/Single+Sign+Out def send_logout_notification_for_service_ticket(st) uri = URI.parse(st.service) http = Net::HTTP.new(uri.host,uri.port) #http.use_ssl = true if uri.scheme = 'https' http.start do |conn| path = uri.path || '/' time = Time.now rand = CASServer::Utils.random_string data = %{<samlp:LogoutRequest ID="#{rand}" Version="2.0" IssueInstant="#{time.rfc2822}"> <saml:NameID></saml:NameID> <samlp:SessionIndex>#{st.ticket}</samlp:SessionIndex> </samlp:LogoutRequest>} response = conn.request_post(path, data) if response.code.to_i == 200 $LOG.info "Logout notification successfully posted to #{st.service.inspect}." return true else $LOG.error "Service #{st.service.inspect} responed to logout notification with code '#{response.code}'." return false end end end def service_uri_with_ticket(service, st) raise ArgumentError, "Second argument must be a ServiceTicket!" unless st.kind_of? CASServer::Models::ServiceTicket # This will choke with a URI::InvalidURIError if service URI is not properly URI-escaped... # This exception is handled further upstream (i.e. in the controller). service_uri = URI.parse(service) if service.include? "?" if service_uri.query.empty? query_separator = "" else query_separator = "&" end else query_separator = "?" end service_with_ticket = service + query_separator + "ticket=" + st.ticket service_with_ticket end # Strips CAS-related parameters from a service URL and normalizes it, # removing trailing / and ?. # # For example, "http://google.com?ticket=12345" will be returned as # "http://google.com". Also, "http://google.com/" would be returned as # "http://google.com". # # Note that only the first occurance of each CAS-related parameter is # removed, so that "http://google.com?ticket=12345&ticket=abcd" would be # returned as "http://google.com?ticket=abcd". def clean_service_url(dirty_service) clean_service = dirty_service.dup ['service', 'ticket', 'gateway', 'renew'].each do |p| clean_service.sub!(Regexp.new("#{p}=[^&]*"), '') end clean_service.gsub!(/[\/\?]$/, '') return clean_service end module_function :clean_service_url end fixed error with blank service git-svn-id: 4c0742455dee89240ab9120cf46ec5680225e32d@287 fffcb96a-a727-0410-ad3e-7b35c796b8d7 require 'uri' require 'net/https' # Encapsulates CAS functionality. This module is meant to be included in # the CASServer::Controllers module. module CASServer::CAS include CASServer::Models def generate_login_ticket # 3.5 (login ticket) lt = LoginTicket.new lt.ticket = "LT-" + CASServer::Utils.random_string lt.client_hostname = env['REMOTE_HOST'] || env['REMOTE_ADDR'] lt.save! $LOG.debug("Generated login ticket '#{lt.ticket}' for client" + " at '#{lt.client_hostname}'") lt end def generate_ticket_granting_ticket(username) # 3.6 (ticket granting cookie/ticket) tgt = TicketGrantingTicket.new tgt.ticket = "TGC-" + CASServer::Utils.random_string tgt.username = username tgt.client_hostname = env['REMOTE_HOST'] || env['REMOTE_ADDR'] tgt.save! $LOG.debug("Generated ticket granting ticket '#{tgt.ticket}' for user" + " '#{tgt.username}' at '#{tgt.client_hostname}'") tgt end def generate_service_ticket(service, username, tgt) # 3.1 (service ticket) st = ServiceTicket.new st.ticket = "ST-" + CASServer::Utils.random_string st.service = service st.username = username st.ticket_granting_ticket = tgt st.client_hostname = env['REMOTE_HOST'] || env['REMOTE_ADDR'] st.save! $LOG.debug("Generated service ticket '#{st.ticket}' for service '#{st.service}'" + " for user '#{st.username}' at '#{st.client_hostname}'") st end def generate_proxy_ticket(target_service, pgt) # 3.2 (proxy ticket) pt = ProxyTicket.new pt.ticket = "PT-" + CASServer::Utils.random_string pt.service = target_service pt.username = pgt.service_ticket.username pt.proxy_granting_ticket_id = pgt.id pt.client_hostname = env['REMOTE_HOST'] || env['REMOTE_ADDR'] pt.save! $LOG.debug("Generated proxy ticket '#{pt.ticket}' for target service '#{pt.service}'" + " for user '#{pt.username}' at '#{pt.client_hostname}' using proxy-granting" + " ticket '#{pgt.ticket}'") pt end def generate_proxy_granting_ticket(pgt_url, st) uri = URI.parse(pgt_url) https = Net::HTTP.new(uri.host,uri.port) https.use_ssl = true # Here's what's going on here: # # 1. We generate a ProxyGrantingTicket (but don't store it in the database just yet) # 2. Deposit the PGT and it's associated IOU at the proxy callback URL. # 3. If the proxy callback URL responds with HTTP code 200, store the PGT and return it; # otherwise don't save it and return nothing. # https.start do |conn| path = uri.path.empty? ? '/' : uri.path pgt = ProxyGrantingTicket.new pgt.ticket = "PGT-" + CASServer::Utils.random_string(60) pgt.iou = "PGTIOU-" + CASServer::Utils.random_string(57) pgt.service_ticket_id = st.id pgt.client_hostname = env['REMOTE_HOST'] || env['REMOTE_ADDR'] # FIXME: The CAS protocol spec says to use 'pgt' as the parameter, but in practice # the JA-SIG and Yale server implementations use pgtId. We'll go with the # in-practice standard. path += (uri.query.nil? || uri.query.empty? ? '?' : '&') + "pgtId=#{pgt.ticket}&pgtIou=#{pgt.iou}" response = conn.request_get(path) # TODO: follow redirects... 2.5.4 says that redirects MAY be followed if response.code.to_i == 200 # 3.4 (proxy-granting ticket IOU) pgt.save! $LOG.debug "PGT generated for pgt_url '#{pgt_url}': #{pgt.inspect}" pgt else $LOG.warn "PGT callback server responded with a bad result code '#{response.code}'. PGT will not be stored." end end end def validate_login_ticket(ticket) $LOG.debug("Validating login ticket '#{ticket}'") success = false if ticket.nil? error = "Your login request did not include a login ticket. There may be a problem with the authentication system." $LOG.warn("Missing login ticket.") elsif lt = LoginTicket.find_by_ticket(ticket) if lt.consumed? error = "The login ticket you provided has already been used up. Please try logging in again." $LOG.warn("Login ticket '#{ticket}' previously used up") elsif Time.now - lt.created_on < CASServer::Conf.login_ticket_expiry $LOG.info("Login ticket '#{ticket}' successfully validated") else error = "Your login ticket has expired. Please try logging in again." $LOG.warn("Expired login ticket '#{ticket}'") end else error = "The login ticket you provided is invalid. Please try logging in again." $LOG.warn("Invalid login ticket '#{ticket}'") end lt.consume! if lt error end def validate_ticket_granting_ticket(ticket) $LOG.debug("Validating ticket granting ticket '#{ticket}'") if ticket.nil? error = "No ticket granting ticket given." $LOG.debug(error) elsif tgt = TicketGrantingTicket.find_by_ticket(ticket) if CASServer::Conf.expire_sessions && Time.now - tgt.created_on > CASServer::Conf.ticket_granting_ticket_expiry error = "Your session has expired. Please log in again." $LOG.info("Ticket granting ticket '#{ticket}' for user '#{tgt.username}' expired.") else $LOG.info("Ticket granting ticket '#{ticket}' for user '#{tgt.username}' successfully validated.") end else error = "Invalid ticket granting ticket '#{ticket}' (no matching ticket found in the database)." $LOG.warn(error) end [tgt, error] end def validate_service_ticket(service, ticket, allow_proxy_tickets = false) $LOG.debug("Validating service/proxy ticket '#{ticket}' for service '#{service}'") if service.nil? or ticket.nil? error = Error.new("INVALID_REQUEST", "Ticket or service parameter was missing in the request.") $LOG.warn("#{error.code} - #{error.message}") elsif st = ServiceTicket.find_by_ticket(ticket) if st.consumed? error = Error.new("INVALID_TICKET", "Ticket '#{ticket}' has already been used up.") $LOG.warn("#{error.code} - #{error.message}") elsif st.kind_of?(CASServer::Models::ProxyTicket) && !allow_proxy_tickets error = Error.new("INVALID_TICKET", "Ticket '#{ticket}' is a proxy ticket, but only service tickets are allowed here.") $LOG.warn("#{error.code} - #{error.message}") elsif Time.now - st.created_on > CASServer::Conf.service_ticket_expiry error = Error.new("INVALID_TICKET", "Ticket '#{ticket}' has expired.") $LOG.warn("Ticket '#{ticket}' has expired.") elsif !st.matches_service? service error = Error.new("INVALID_SERVICE", "The ticket '#{ticket}' belonging to user '#{st.username}' is valid,"+ " but the requested service '#{service}' does not match the service '#{st.service}' associated with this ticket.") $LOG.warn("#{error.code} - #{error.message}") else $LOG.info("Ticket '#{ticket}' for service '#{service}' for user '#{st.username}' successfully validated.") end else error = Error.new("INVALID_TICKET", "Ticket '#{ticket}' not recognized.") $LOG.warn("#{error.code} - #{error.message}") end if st st.consume! end [st, error] end def validate_proxy_ticket(service, ticket) pt, error = validate_service_ticket(service, ticket, true) if pt.kind_of?(CASServer::Models::ProxyTicket) && !error if not pt.proxy_granting_ticket error = Error.new("INTERNAL_ERROR", "Proxy ticket '#{pt}' belonging to user '#{pt.username}' is not associated with a proxy granting ticket.") elsif not pt.proxy_granting_ticket.service_ticket error = Error.new("INTERNAL_ERROR", "Proxy granting ticket '#{pt.proxy_granting_ticket}'"+ " (associated with proxy ticket '#{pt}' and belonging to user '#{pt.username}' is not associated with a service ticket.") end end [pt, error] end def validate_proxy_granting_ticket(ticket) if ticket.nil? error = Error.new("INVALID_REQUEST", "pgt parameter was missing in the request.") $LOG.warn("#{error.code} - #{error.message}") elsif pgt = ProxyGrantingTicket.find_by_ticket(ticket) if pgt.service_ticket $LOG.info("Proxy granting ticket '#{ticket}' belonging to user '#{pgt.service_ticket.username}' successfully validated.") else error = Error.new("INTERNAL_ERROR", "Proxy granting ticket '#{ticket}' is not associated with a service ticket.") $LOG.error("#{error.code} - #{error.message}") end else error = Error.new("BAD_PGT", "Invalid proxy granting ticket '#{ticket}' (no matching ticket found in the database).") $LOG.warn("#{error.code} - #{error.message}") end [pgt, error] end # Takes an existing ServiceTicket object (presumably pulled from the database) # and sends a POST with logout information to the service that the ticket # was generated for. # # This makes possible the "single sign-out" functionality added in CAS 3.1. # See http://www.ja-sig.org/wiki/display/CASUM/Single+Sign+Out def send_logout_notification_for_service_ticket(st) uri = URI.parse(st.service) http = Net::HTTP.new(uri.host,uri.port) #http.use_ssl = true if uri.scheme = 'https' http.start do |conn| path = uri.path || '/' time = Time.now rand = CASServer::Utils.random_string data = %{<samlp:LogoutRequest ID="#{rand}" Version="2.0" IssueInstant="#{time.rfc2822}"> <saml:NameID></saml:NameID> <samlp:SessionIndex>#{st.ticket}</samlp:SessionIndex> </samlp:LogoutRequest>} response = conn.request_post(path, data) if response.code.to_i == 200 $LOG.info "Logout notification successfully posted to #{st.service.inspect}." return true else $LOG.error "Service #{st.service.inspect} responed to logout notification with code '#{response.code}'." return false end end end def service_uri_with_ticket(service, st) raise ArgumentError, "Second argument must be a ServiceTicket!" unless st.kind_of? CASServer::Models::ServiceTicket # This will choke with a URI::InvalidURIError if service URI is not properly URI-escaped... # This exception is handled further upstream (i.e. in the controller). service_uri = URI.parse(service) if service.include? "?" if service_uri.query.empty? query_separator = "" else query_separator = "&" end else query_separator = "?" end service_with_ticket = service + query_separator + "ticket=" + st.ticket service_with_ticket end # Strips CAS-related parameters from a service URL and normalizes it, # removing trailing / and ?. # # For example, "http://google.com?ticket=12345" will be returned as # "http://google.com". Also, "http://google.com/" would be returned as # "http://google.com". # # Note that only the first occurance of each CAS-related parameter is # removed, so that "http://google.com?ticket=12345&ticket=abcd" would be # returned as "http://google.com?ticket=abcd". def clean_service_url(dirty_service) return dirty_service if dirty_service.blank? clean_service = dirty_service.dup ['service', 'ticket', 'gateway', 'renew'].each do |p| clean_service.sub!(Regexp.new("#{p}=[^&]*"), '') end clean_service.gsub!(/[\/\?]$/, '') return clean_service end module_function :clean_service_url end
require "active_support/core_ext/hash/keys" require "active_support/inflector" module Cassieq module Utils def underscore_and_symobolize_keys(data) transform_keys_in_structure(data) { |key| key.underscore.to_sym } end def camelize_and_stringify_keys(data) transform_keys_in_structure(data) { |key| key.to_s.camelize(:lower) } end def formated_time_now Time.now.utc.iso8601 end private def transform_keys_in_structure(data) case data when Hash data.transform_keys { |key| yield(key) } when Array data.map do |hash| hash.transform_keys { |key| yield(key) } end end end end end Require time for iso formatting require "active_support/core_ext/hash/keys" require "active_support/inflector" require "time" module Cassieq module Utils def underscore_and_symobolize_keys(data) transform_keys_in_structure(data) { |key| key.underscore.to_sym } end def camelize_and_stringify_keys(data) transform_keys_in_structure(data) { |key| key.to_s.camelize(:lower) } end def formated_time_now Time.now.utc.iso8601 end private def transform_keys_in_structure(data) case data when Hash data.transform_keys { |key| yield(key) } when Array data.map do |hash| hash.transform_keys { |key| yield(key) } end end end end end
[DEMAD-270] Correción rake
# DEPLOYING LOOMIO # To run a full deploy simply run # `rake deploy` # # This will push the current master branch to production. # You can also specify the heroku remote, and the branch to be deployed, like so: # `rake deploy <remote> <branch>` # # So, running `rake deploy loomio-clone test-feature` will deploy the test-feature branch # to the heroku remote named loomio-clone # # This script is also modular, meaning you can run any part of it individually. # The order of operations goes: # # rake deploy:build -- acquire plugins and build all clientside assets # rake deploy:commit -- commit all non-repository code to a branch for pushing # rake deploy:push -- push deploy branch to heroku # rake deploy:bump_version -- add a commit to master which bumps the current version (when deploying to loomio-production only) # rake deploy:heroku_reset -- run rake db:migrate on heroku, restart dynos, and notify clients of version update task :deploy do remote, branch = ARGV[1] || 'loomio-production', ARGV[2] || 'master' is_production_push = remote == 'loomio-production' && branch == 'master' id = Time.now.to_i temp_branch = build_branch(remote, branch, id) puts "Deploying branch #{branch} to #{remote}..." run_commands [ "git checkout #{branch}", # move to specified deploy branch "git checkout -b #{temp_branch}", # cut a new deploy branch based on specified branch "bundle exec rake deploy:bump_version[#{temp_branch},#{is_production_push}]", # bump version if this is a production deploy "bundle exec rake deploy:build", # build assets "bundle exec rake deploy:commit", # add deploy commit "bundle exec rake deploy:push[#{remote},#{branch},#{id}]", # deploy to heroku "bundle exec rake deploy:heroku_reset[#{remote}]" # clean up heroku deploy ] at_exit { cleanup(remote, branch, id) } end def cleanup(remote, branch, id) run_commands ["git checkout #{branch}; git branch -D #{build_branch(remote, branch, id)}"] end namespace :deploy do desc "Setup heroku and github for deployment" task :setup do remote = ARGV[1] || 'loomio-production' run_commands [ "sh script/heroku_login.sh $DEPLOY_EMAIL $DEPLOY_PASSWORD", # login to heroku "echo \"Host heroku.com\n StrictHostKeyChecking no\" > ~/.ssh/config", # don't prompt for confirmation of heroku.com host "git config user.email $DEPLOY_EMAIL && git config user.name $DEPLOY_NAME", # setup git commit user "git remote add #{remote} https://git.heroku.com/#{remote}.git" # add https heroku remote ] end desc "Builds assets for production push" task :build, [:plugin_set] do |t, args| plugin_set = args[:plugin_set] || :plugins puts "Building clientside assets, using plugin set #{plugin_set}..." run_commands [ "rake 'plugins:fetch[#{plugin_set}]' plugins:install", # install plugins specified in plugins/plugins.yml "rm -rf plugins/**/.git", # allow cloned plugins to be added to this repo "cd angular && yarn && node_modules/gulp/bin/gulp.js compile && cd ../", # build the app via gulp "cp -r public/client/development public/client/#{Loomio::Version.current}" # version assets ] end desc "Commits built assets to deployment branch" task :commit do puts "Committing assets to deployment branch..." run_commands [ "find fetched_plugins -name '*.*' | xargs git add -f", # add plugins folder to commit "find public/img/emojis -name '*.png' | xargs git add -f", # add emojis to commit "rm plugins; ln -s fetched_plugins plugins", # add plugins symlink "git add -f plugins", # add symlink to repo "git add public/client/#{Loomio::Version.current} public/client/fonts -f", # add assets to commit "git commit -m 'Add compiled assets / plugin code'" # commit assets ] end desc "Bump version of repository if pushing to production" task :bump_version, [:branch, :is_production_push] do |t, args| raise 'branch must be specified' unless branch = args[:branch] is_production_push = args[:is_production_push] == 'true' puts "Bumping version from #{Loomio::Version.current}..." run_commands [ "ruby script/bump_version.rb #{is_production_push ? 'patch' : 'test'}", "git add lib/version", "git commit -m 'bump version to #{Loomio::Version.current}'", ("git push origin #{branch}:master" if is_production_push) ] end desc "Push to heroku!" task :push, [:remote,:branch,:id] do |t, args| raise 'remote must be specified' unless remote = args[:remote] raise 'branch must be specified' unless branch = args[:branch] raise 'deploy branch id must be specified' unless id = args[:id] puts "Deploying #{build_branch(remote, branch, id)} to heroku remote #{remote}" run_commands [ "git push #{remote} #{build_branch(remote, branch, id)}:master -f", # DEPLOY! ] end desc "Migrate heroku database and restart dynos" task :heroku_reset, [:remote] do |t, args| puts "Migrating & resetting heroku..." raise 'remote must be specified!' unless remote = args[:remote] cmd = `which heroku`.chomp run_commands [ "#{cmd} run rake db:migrate -a #{remote}", # Migrate Heroku DB "#{cmd} restart -a #{remote}" # Restart Heroku dynos ] end end def build_branch(remote, branch, id) "deploy-#{remote}-#{branch}-#{id}" end def run_commands(commands) commands.compact.each do |command| puts "\n-> #{command}" return false unless system(command) end end checkout as orphan branch to make deployment faster (#4353) # DEPLOYING LOOMIO # To run a full deploy simply run # `rake deploy` # # This will push the current master branch to production. # You can also specify the heroku remote, and the branch to be deployed, like so: # `rake deploy <remote> <branch>` # # So, running `rake deploy loomio-clone test-feature` will deploy the test-feature branch # to the heroku remote named loomio-clone # # This script is also modular, meaning you can run any part of it individually. # The order of operations goes: # # rake deploy:build -- acquire plugins and build all clientside assets # rake deploy:commit -- commit all non-repository code to a branch for pushing # rake deploy:push -- push deploy branch to heroku # rake deploy:bump_version -- add a commit to master which bumps the current version (when deploying to loomio-production only) # rake deploy:heroku_reset -- run rake db:migrate on heroku, restart dynos, and notify clients of version update task :deploy do remote, branch = ARGV[1] || 'loomio-production', ARGV[2] || 'master' is_production_push = remote == 'loomio-production' && branch == 'master' id = Time.now.to_i temp_branch = build_branch(remote, branch, id) puts "Deploying branch #{branch} to #{remote}..." run_commands [ "git checkout #{branch}", # move to specified deploy branch "git checkout --orphan #{temp_branch}", # cut a new deploy branch based on specified branch "bundle exec rake deploy:bump_version[#{temp_branch},#{is_production_push}]", # bump version if this is a production deploy "bundle exec rake deploy:build", # build assets "bundle exec rake deploy:commit", # add deploy commit "bundle exec rake deploy:push[#{remote},#{branch},#{id}]", # deploy to heroku "bundle exec rake deploy:heroku_reset[#{remote}]" # clean up heroku deploy ] at_exit { cleanup(remote, branch, id) } end def cleanup(remote, branch, id) run_commands ["git checkout #{branch}; git branch -D #{build_branch(remote, branch, id)}"] end namespace :deploy do desc "Setup heroku and github for deployment" task :setup do remote = ARGV[1] || 'loomio-production' run_commands [ "sh script/heroku_login.sh $DEPLOY_EMAIL $DEPLOY_PASSWORD", # login to heroku "echo \"Host heroku.com\n StrictHostKeyChecking no\" > ~/.ssh/config", # don't prompt for confirmation of heroku.com host "git config user.email $DEPLOY_EMAIL && git config user.name $DEPLOY_NAME", # setup git commit user "git remote add #{remote} https://git.heroku.com/#{remote}.git" # add https heroku remote ] end desc "Builds assets for production push" task :build, [:plugin_set] do |t, args| plugin_set = args[:plugin_set] || :plugins puts "Building clientside assets, using plugin set #{plugin_set}..." run_commands [ "rake 'plugins:fetch[#{plugin_set}]' plugins:install", # install plugins specified in plugins/plugins.yml "rm -rf plugins/**/.git", # allow cloned plugins to be added to this repo "cd angular && yarn && node_modules/gulp/bin/gulp.js compile && cd ../", # build the app via gulp "cp -r public/client/development public/client/#{Loomio::Version.current}" # version assets ] end desc "Commits built assets to deployment branch" task :commit do puts "Committing assets to deployment branch..." run_commands [ "find fetched_plugins -name '*.*' | xargs git add -f", # add plugins folder to commit "find public/img/emojis -name '*.png' | xargs git add -f", # add emojis to commit "rm plugins; ln -s fetched_plugins plugins", # add plugins symlink "git add -f plugins", # add symlink to repo "git add public/client/#{Loomio::Version.current} public/client/fonts -f", # add assets to commit "git commit -m 'Add compiled assets / plugin code'" # commit assets ] end desc "Bump version of repository if pushing to production" task :bump_version, [:branch, :is_production_push] do |t, args| raise 'branch must be specified' unless branch = args[:branch] is_production_push = args[:is_production_push] == 'true' puts "Bumping version from #{Loomio::Version.current}..." run_commands [ "ruby script/bump_version.rb #{is_production_push ? 'patch' : 'test'}", "git add lib/version", "git commit -m 'bump version to #{Loomio::Version.current}'", ("git push origin #{branch}:master" if is_production_push) ] end desc "Push to heroku!" task :push, [:remote,:branch,:id] do |t, args| raise 'remote must be specified' unless remote = args[:remote] raise 'branch must be specified' unless branch = args[:branch] raise 'deploy branch id must be specified' unless id = args[:id] puts "Deploying #{build_branch(remote, branch, id)} to heroku remote #{remote}" run_commands [ "git push #{remote} #{build_branch(remote, branch, id)}:master -f", # DEPLOY! ] end desc "Migrate heroku database and restart dynos" task :heroku_reset, [:remote] do |t, args| puts "Migrating & resetting heroku..." raise 'remote must be specified!' unless remote = args[:remote] cmd = `which heroku`.chomp run_commands [ "#{cmd} run rake db:migrate -a #{remote}", # Migrate Heroku DB "#{cmd} restart -a #{remote}" # Restart Heroku dynos ] end end def build_branch(remote, branch, id) "deploy-#{remote}-#{branch}-#{id}" end def run_commands(commands) commands.compact.each do |command| puts "\n-> #{command}" return false unless system(command) end end
require 'fileutils' # Warning: The following deploy task will completely overwrite whatever is currently deployed to Heroku. # The deploy branch is rebased onto master, so the push needs to be forced. desc "Deploy app to Heroku after precompiling assets" task :deploy do deploy_branch = 'master' remote = 'staging' deploy_repo_dir = "tmp/heroku_deploy" begin # Check branch and working directory. Fail if not on clean master branch. branch = `branch_name=$(git symbolic-ref HEAD 2>/dev/null); branch_name=${branch_name##refs/heads/}; echo ${branch_name:-HEAD}`.strip if branch != 'master' raise "You have checked out the #{branch} branch, please only deploy from the master branch!" end if `git status --porcelain`.present? raise "You have unstaged or uncommitted changes! Please only deploy from a clean working directory!" end unless File.exists? deploy_repo_dir # Copy repo to tmp dir so we can continue working while it deploys @new_repo = true puts "Copying repo to #{deploy_repo_dir}..." # Can't copy into self, so copy to /tmp first #FileUtils.cp_r Rails.root.to_s, "/tmp/heroku_deploy" #FileUtils.mv "/tmp/heroku_deploy", Rails.root.join('tmp') `sudo cp -r #{Rails.root.to_s} /tmp/heroku_deploy` `sudo mv /tmp/heroku_deploy #{Rails.root.join('tmp')}` %x{sudo chown -R `whoami` #{Rails.root.join('tmp')}} end # Change working directory to copied repo Dir.chdir(deploy_repo_dir) # Create new deploy branch if starting with a fresh repo if @new_repo # Set remote to parent git dir, so we can fetch updates on future deploys system "git remote set-url origin ../.." system "git checkout -b #{deploy_branch}" # Allow git to see public/assets puts "Removing public/assets from .gitignore..." system %q{sed -i -e '/public\/assets/d' .gitignore} system 'git add .gitignore; git commit -m "Allow git to commit public/assets"' else # Otherwise, we're already on the deploy branch, so fetch any new changes from original repo system "git fetch origin" # Rebase onto origin/master. # This step should never fail, because we are rebasing commits for files # that should be ignored by the master repo. unless system "git rebase origin/master" raise "Rebase Failed! Please delete tmp/heroku_deploy and start again." end end # Precompile assets Rake::Task['assets:precompile'].invoke # Add any extra tasks you want to run here, such as compiling static pages, etc. # Add all changes and new files system 'git add -A' commit_message = "Added precompiled assets" if @new_repo # Create new commit for new repo system "git commit -m '#{commit_message}'"#, :out => "/dev/null" else # If existing repo, amend previous assets commit system "git commit --amend -m '#{commit_message}'"#, :out => "/dev/null" end puts "Commit: #{commit_message}" # Force push deploy branch to Heroku puts "Pushing #{deploy_branch} branch to master on #{remote}..." IO.popen("git push #{remote} #{deploy_branch}:master -f") do |io| while (line = io.gets) do puts line end end end end Updates deployment script require 'fileutils' # Warning: The following deploy task will completely overwrite whatever is currently deployed to Heroku. # The deploy branch is rebased onto master, so the push needs to be forced. desc "Deploy app to Heroku after precompiling assets" task :deploy do deploy_branch = 'master' remote = ENV['DEPLOY_TO'] || 'staging' deploy_repo_dir = "tmp/heroku_deploy" begin # Check branch and working directory. Fail if not on clean master branch. branch = `branch_name=$(git symbolic-ref HEAD 2>/dev/null); branch_name=${branch_name##refs/heads/}; echo ${branch_name:-HEAD}`.strip if branch != 'master' raise "You have checked out the #{branch} branch, please only deploy from the master branch!" end if `git status --porcelain`.present? raise "You have unstaged or uncommitted changes! Please only deploy from a clean working directory!" end unless File.exists? deploy_repo_dir # Copy repo to tmp dir so we can continue working while it deploys @new_repo = true puts "Copying repo to #{deploy_repo_dir}..." # Can't copy into self, so copy to /tmp first #FileUtils.cp_r Rails.root.to_s, "/tmp/heroku_deploy" #FileUtils.mv "/tmp/heroku_deploy", Rails.root.join('tmp') `sudo cp -r #{Rails.root.to_s} /tmp/heroku_deploy` `sudo mv /tmp/heroku_deploy #{Rails.root.join('tmp')}` %x{sudo chown -R `whoami` #{Rails.root.join('tmp')}} end # Change working directory to copied repo Dir.chdir(deploy_repo_dir) # Create new deploy branch if starting with a fresh repo if @new_repo # Set remote to parent git dir, so we can fetch updates on future deploys system "git remote set-url origin ../.." system "git checkout -b #{deploy_branch}" # Allow git to see public/assets puts "Removing public/assets from .gitignore..." system %q{sed -i -e '/public\/assets/d' .gitignore} system 'git add .gitignore; git commit -m "Allow git to commit public/assets"' else # Otherwise, we're already on the deploy branch, so fetch any new changes from original repo system "git fetch origin" # Rebase onto origin/master. # This step should never fail, because we are rebasing commits for files # that should be ignored by the master repo. unless system "git rebase origin/master" raise "Rebase Failed! Please delete tmp/heroku_deploy and start again." end end # Precompile assets Rake::Task['assets:precompile'].invoke # Add any extra tasks you want to run here, such as compiling static pages, etc. # Add all changes and new files system 'git add -A' commit_message = "Added precompiled assets" if @new_repo # Create new commit for new repo system "git commit -m '#{commit_message}'"#, :out => "/dev/null" else # If existing repo, amend previous assets commit system "git commit --amend -m '#{commit_message}'"#, :out => "/dev/null" end puts "Commit: #{commit_message}" # Force push deploy branch to Heroku puts "Pushing #{deploy_branch} branch to master on #{remote}..." IO.popen("git push #{remote} #{deploy_branch}:master -f") do |io| while (line = io.gets) do puts line end end end end
require 'active_support/core_ext/hash/indifferent_access' module Chanko module Loader mattr_accessor :units mattr_accessor :loaded mattr_accessor :current_scopes mattr_accessor :__invoked mattr_accessor :__requested mattr_accessor :__aborted self.units = ::HashWithIndifferentAccess.new class<<self def size units.size end def reset! self.units = ::HashWithIndifferentAccess.new if Rails.env.test? if Chanko.config.cache_classes self.loaded ||= ::HashWithIndifferentAccess.new else self.loaded = ::HashWithIndifferentAccess.new end self.current_scopes = [] self.__invoked = [] self.__requested = [] self.__aborted = [] end def paths(name) self.directories.map { |directory| File.join(directory, name) } end def javascripts(name) Chanko::Loader.paths(name).inject([]) do |js, path| js += Pathname.glob(File.join(path, 'javascripts/*.js')) end end def clear_cache! Chanko::Unit.clear_cache! self.reset! self.loaded = ::HashWithIndifferentAccess.new end def invoked(unit_names) self.__invoked.concat(Array.wrap(unit_names).map(&:to_s)) end def requested(unit_names) self.__requested.concat(Array.wrap(unit_names).map(&:to_s)) end def aborted(unit_names) self.__aborted.concat(Array.wrap(unit_names).map(&:to_s)) end def fetch(unit_name) return nil unless self.load_unit(unit_name) unit = begin unit_name.to_s.singularize.camelize.constantize; rescue; end return nil unless unit return nil unless unit.ancestors.include?(Chanko::Unit) unit end def push_scope(label) self.current_scopes.push label end def pop_scope self.current_scopes.pop end def current_scope self.current_scopes.last end def invoked_units self.__invoked.uniq end def requested_units self.__requested.uniq end def aborted_units self.__aborted.uniq end def load_expander(unit_name) %w(models helpers).each do |targets| Chanko::Loader.directories.each do |directory| Pathname.glob(directory.join("#{unit_name}/#{targets}/*.rb")).sort.each do |target| require_dependency "#{target.dirname}/#{target.basename}" end end end unit_name.to_s.camelize.constantize.tap do |unit| unit.expand! end end private :load_expander def load_core(unit_name, options={}) Chanko::Loader.directories.each do |directory| Pathname.glob(directory.join("#{unit_name}/#{unit_name}.rb")).sort.each do |filename| if require_or_updating_load("#{filename.dirname}/#{filename.basename}") Chanko::Unit.clear_function_cache(unit_name.to_s.classify) end end end begin self.loaded[unit_name.to_sym] = load_expander(unit_name) rescue NameError => e unless options[:skip_raise] Chanko::ExceptionNotifier.notify("missing #{unit_name}", false, :key => "#{unit_name} load module", :exception => e, :context => options[:context], :backtrace => e.backtrace[0..20]) end self.loaded[unit_name.to_sym] = false end self.loaded[unit_name.to_sym] ||= false self.loaded[unit_name.to_sym] rescue Exception => e Chanko::ExceptionNotifier.notify("except #{unit_name}", false, :key => "#{unit_name} load module", :exception => e, :context => options[:context], :backtrace => e.backtrace[0..20]) self.loaded[unit_name.to_sym] ||= false self.loaded[unit_name.to_sym] end private :load_core def load_unit(unit_name, options={}) return loaded[unit_name.to_sym] if loaded?(unit_name) load_core(unit_name, options) end def loaded?(unit) !self.loaded[unit.to_sym].nil? end def register(obj) self.units[obj.name] = obj end def deregister(obj) self.units.delete(obj.name) Chanko::Helper.deregister(obj.name) end def load_path_file(file, root) @directories = Chanko::Directories.load_path_file(file, root) end def add_path(path) @directories ||= Chanko::Directories.new @directories.add(path) end def remove_path(path) @directories ||= Chanko::Directories.new @directories.remove(path) end def directories @directories ||= Chanko::Directories.new @directories.directories end end end end remove needless sigularize require 'active_support/core_ext/hash/indifferent_access' module Chanko module Loader mattr_accessor :units mattr_accessor :loaded mattr_accessor :current_scopes mattr_accessor :__invoked mattr_accessor :__requested mattr_accessor :__aborted self.units = ::HashWithIndifferentAccess.new class<<self def size units.size end def reset! self.units = ::HashWithIndifferentAccess.new if Rails.env.test? if Chanko.config.cache_classes self.loaded ||= ::HashWithIndifferentAccess.new else self.loaded = ::HashWithIndifferentAccess.new end self.current_scopes = [] self.__invoked = [] self.__requested = [] self.__aborted = [] end def paths(name) self.directories.map { |directory| File.join(directory, name) } end def javascripts(name) Chanko::Loader.paths(name).inject([]) do |js, path| js += Pathname.glob(File.join(path, 'javascripts/*.js')) end end def clear_cache! Chanko::Unit.clear_cache! self.reset! self.loaded = ::HashWithIndifferentAccess.new end def invoked(unit_names) self.__invoked.concat(Array.wrap(unit_names).map(&:to_s)) end def requested(unit_names) self.__requested.concat(Array.wrap(unit_names).map(&:to_s)) end def aborted(unit_names) self.__aborted.concat(Array.wrap(unit_names).map(&:to_s)) end def fetch(unit_name) return nil unless self.load_unit(unit_name) unit = begin unit_name.to_s.camelize.constantize; rescue; end return nil unless unit return nil unless unit.ancestors.include?(Chanko::Unit) unit end def push_scope(label) self.current_scopes.push label end def pop_scope self.current_scopes.pop end def current_scope self.current_scopes.last end def invoked_units self.__invoked.uniq end def requested_units self.__requested.uniq end def aborted_units self.__aborted.uniq end def load_expander(unit_name) %w(models helpers).each do |targets| Chanko::Loader.directories.each do |directory| Pathname.glob(directory.join("#{unit_name}/#{targets}/*.rb")).sort.each do |target| require_dependency "#{target.dirname}/#{target.basename}" end end end unit_name.to_s.camelize.constantize.tap do |unit| unit.expand! end end private :load_expander def load_core(unit_name, options={}) Chanko::Loader.directories.each do |directory| Pathname.glob(directory.join("#{unit_name}/#{unit_name}.rb")).sort.each do |filename| if require_or_updating_load("#{filename.dirname}/#{filename.basename}") Chanko::Unit.clear_function_cache(unit_name.to_s.classify) end end end begin self.loaded[unit_name.to_sym] = load_expander(unit_name) rescue NameError => e unless options[:skip_raise] Chanko::ExceptionNotifier.notify("missing #{unit_name}", false, :key => "#{unit_name} load module", :exception => e, :context => options[:context], :backtrace => e.backtrace[0..20]) end self.loaded[unit_name.to_sym] = false end self.loaded[unit_name.to_sym] ||= false self.loaded[unit_name.to_sym] rescue Exception => e Chanko::ExceptionNotifier.notify("except #{unit_name}", false, :key => "#{unit_name} load module", :exception => e, :context => options[:context], :backtrace => e.backtrace[0..20]) self.loaded[unit_name.to_sym] ||= false self.loaded[unit_name.to_sym] end private :load_core def load_unit(unit_name, options={}) return loaded[unit_name.to_sym] if loaded?(unit_name) load_core(unit_name, options) end def loaded?(unit) !self.loaded[unit.to_sym].nil? end def register(obj) self.units[obj.name] = obj end def deregister(obj) self.units.delete(obj.name) Chanko::Helper.deregister(obj.name) end def load_path_file(file, root) @directories = Chanko::Directories.load_path_file(file, root) end def add_path(path) @directories ||= Chanko::Directories.new @directories.add(path) end def remove_path(path) @directories ||= Chanko::Directories.new @directories.remove(path) end def directories @directories ||= Chanko::Directories.new @directories.directories end end end end
# rake db:import:emails[db/emails.csv] begin namespace :db do namespace :import do task :emails, [:file] => :environment do |t, args| # pass variables like so bundle exec rake db:import:emails[db/emails.csv] require File.expand_path("../../config/environment", File.dirname(__FILE__)) #this is needed because rake tasks load classes lazily; from the command line, the task will #otherwise fail because it takes the below intended monkeypatch as first definition puts Organization.import_emails(args[:file],1000) end end end end Describe rake db:import:emails[file] so that it is listed by `rake -T` # rake db:import:emails[db/emails.csv] begin namespace :db do namespace :import do desc 'Import email addresses from a named CSV file' task :emails, [:file] => :environment do |t, args| # pass variables like so bundle exec rake db:import:emails[db/emails.csv] require File.expand_path("../../config/environment", File.dirname(__FILE__)) #this is needed because rake tasks load classes lazily; from the command line, the task will #otherwise fail because it takes the below intended monkeypatch as first definition puts Organization.import_emails(args[:file],1000) end end end end
module Chore module Version #:nodoc: MAJOR = 2 MINOR = 0 PATCH = 1 STRING = [ MAJOR, MINOR, PATCH ].join('.') end end Tag v2.0.2 release module Chore module Version #:nodoc: MAJOR = 2 MINOR = 0 PATCH = 2 STRING = [ MAJOR, MINOR, PATCH ].join('.') end end
logger = Mumukit::Nuntius::Logger namespace :events do task listen: :environment do logger.info 'Listening to events' Mumukit::Nuntius::EventConsumer.start 'atheneum' end end Quick fix logger = Mumukit::Nuntius::Logger namespace :events do task listen: :environment do logger.info 'Listening to events' Mumukit::Nuntius::EventConsumer.start 'laboratory' end end
module Cielo VERSION = "0.0.5" end bump up version module Cielo VERSION = "0.0.6" end
require 'rake' namespace :rigse do namespace :convert do desc 'Add the author role to all users who have authored an Investigation' task :add_author_role_to_authors => :environment do User.find(:all).each do |user| if user.has_investigations? print '.' STDOUT.flush user.add_role('author') end end puts end desc 'Remove the author role from users who have not authored an Investigation' task :remove_author_role_from_non_authors => :environment do User.find(:all).each do |user| unless user.has_investigations? print '.' STDOUT.flush user.remove_role('author') end end puts end desc 'transfer any Investigations owned by the anonymous user to the site admin user' task :transfer_investigations_owned_by_anonymous => :environment do admin_user = User.find_by_login(APP_CONFIG[:admin_login]) anonymous_investigations = User.find_by_login('anonymous').investigations if anonymous_investigations.length > 0 puts "#{anonymous_investigations.length} Investigations owned by the anonymous user" puts "resetting ownership to the site admin user: #{admin_user.name}" anonymous_investigations.each do |inv| inv.deep_set_user(admin_user) print '.' STDOUT.flush end else puts 'no Investigations owned by the anonymous user' end end ####################################################################### # # Assign Vernier go!Link as default vendor_interface for users # without a vendor_interface. # ####################################################################### desc "Assign Vernier go!Link as default vendor_interface for users without a vendor_interface." task :assign_vernier_golink_to_users => :environment do interface = Probe::VendorInterface.find_by_short_name('vernier_goio') User.find(:all).each do |u| unless u.vendor_interface u.vendor_interface = interface u.save end end end desc 'ensure investigations have publication_status' task :pub_status => :environment do Investigation.find(:all).each do |i| if i.publication_status.nil? i.update_attribute(:publication_status,'draft') end end end desc 'Data Collectors with a static graph_type to a static attribute; Embeddable::DataCollectors with a graph_type_id of nil to Sensor' task :data_collectors_with_invalid_graph_types => :environment do puts <<HEREDOC This task will search for all Data Collectors with a graph_type_id == 3 (Static) which was used to indicate a static graph type, and set the graph_type_id to 1 (Sensor) and set the new boolean attribute static to true. In addition it will set the graph_type_id to 1 if the existing graph_type_id is nil. These Embeddable::DataCollectors appeared to be created by the ITSI importer. There is no way for this transformation to tell whether the original graph was a sensor or prediction graph_type so it sets the type to 1 (Sensor). HEREDOC old_style_static_graphs = Embeddable::DataCollector.find_all_by_graph_type_id(3) puts "converting #{old_style_static_graphs.length} old style static graphs and changing type to Sensor" attributes = { :graph_type_id => 1, :static => true } old_style_static_graphs.each do |dc| dc.update_attributes(attributes) print '.'; STDOUT.flush end puts nil_graph_types = Embeddable::DataCollector.find_all_by_graph_type_id(nil) puts "changing type of #{nil_graph_types.length} Embeddable::DataCollectors with nil graph_type_ids to Sensor" attributes = { :graph_type_id => 1, :static => false } nil_graph_types.each do |dc| dc.update_attributes(attributes) print '.'; STDOUT.flush end puts end desc 'copy truncated Embeddable::Xhtml from Embeddable::Xhtml#content, Embeddable::OpenResponse and Embeddable::MultipleChoice#prompt into name' task :copy_truncated_xhtml_into_name => :environment do models = [Embeddable::Xhtml, Embeddable::OpenResponse, Embeddable::MultipleChoice] puts "\nprocessing #{models.join(', ')} models to generate new names from soft-truncated xhtml.\n" [Embeddable::Xhtml, Embeddable::OpenResponse, Embeddable::MultipleChoice].each do |klass| puts "\nprocessing #{klass.count} #{klass} model instances, extracting truncated text from xhtml and generating new name attribute\n" klass.find_in_batches(:batch_size => 100) do |group| group.each { |x| x.save! } print '.'; STDOUT.flush end end puts end desc 'create default Project from config/settings.yml' task :create_default_project_from_config_settings_yml => :environment do Admin::Project.create_or_update_default_project_from_settings_yml end desc 'generate date_str attributes from version_str for MavenJnlp::VersionedJnlpUrls' task :generate_date_str_for_versioned_jnlp_urls => :environment do puts "\nprocessing #{MavenJnlp::VersionedJnlpUrl.count} MavenJnlp::VersionedJnlpUrl model instances, generating date_str from version_str\n" MavenJnlp::VersionedJnlpUrl.find_in_batches do |group| group.each { |j| j.save! } print '.'; STDOUT.flush end puts end desc "Create bundle and console loggers for learners" task :create_bundle_and_console_loggers_for_learners => :environment do Portal::Learner.find(:all).each do |learner| learner.console_logger = Dataservice::ConsoleLogger.create! unless learner.console_logger learner.bundle_logger = Dataservice::BundleLogger.create! unless learner.bundle_logger learner.save! end end desc "Create bundle and console loggers for learners" task :create_bundle_and_console_loggers_for_learners => :environment do Portal::Learner.find(:all).each do |learner| learner.console_logger = Dataservice::ConsoleLogger.create! unless learner.console_logger learner.bundle_logger = Dataservice::BundleLogger.create! unless learner.bundle_logger learner.save! end end def find_and_report_on_invalid_bundle_contents(&block) count = Dataservice::BundleContent.count puts "\nScanning #{count} Dataservice::BundleContent model instances for invalid bodies\n\n" invalid = [] Dataservice::BundleContent.find_in_batches(:batch_size => 10) do |group| invalid << group.find_all { |bc| !bc.valid? } print '.'; STDOUT.flush end invalid.flatten! if invalid.empty? puts "\n\nAll #{count} were valid.\n\n" else puts "\n\nFound #{invalid.length} invalid Dataservice::BundleContent models.\n\n" invalid.each do |bc| learner = bc.bundle_logger.learner puts "id: #{bc.id}" puts " learner #{learner.id}: #{learner.name}; #{learner.student.user.login}" puts " investigation: #{learner.offering.runnable.id}: #{learner.offering.name}" puts " date #{bc.created_at}" yield(bc) if block puts end end end desc "Find and report on invalid Dataservice::BundleContent objects" task :find_and_report_on_invalid_dataservice_bundle_content_objects => :environment do find_and_report_on_invalid_bundle_contents end desc "Find and delete invalid Dataservice::BundleContent objects" task :find_and_delete_invalid_dataservice_bundle_content_objects => :environment do find_and_report_on_invalid_bundle_contents do |bc| puts puts " deleting Dataservice::BundleContent id:#{bc.id}..." bc.destroy end end desc "generate otml, valid_xml, and empty attributes for BundleContent objects" task :generate_otml_valid_xml_and_empty_attributes_for_bundle_content_objects => :environment do count = Dataservice::BundleContent.count puts "\nRe-saving #{count} Dataservice::BundleContent model instances\n\n" Dataservice::BundleContent.find_in_batches(:batch_size => 10) do |group| group.each { |bc| !bc.save! } print '.'; STDOUT.flush end end desc "Convert Existing Clazzes so that multiple Teachers can own a clazz. (many to many change)" task :convert_clazzes_to_multi_teacher => :environment do MultiteacherClazzes.make_all_multi_teacher end desc "Fixup inner pages so they have a satic area (run migrations first)" task :add_static_page_to_inner_pages => :environment do innerPageElements = PageElement.all.select { |pe| pe.embeddable_type == "Embeddable::InnerPage" } innerPages = innerPageElements.map { |pe| pe.embeddable } innerPages.each do |ip| if ip.static_page.nil? ip.static_page = Page.new ip.static_page.user = ip.user ip.save end end end # Feb 3, 2010 desc "Extract and process learner responses from existing OTrunk bundles" task :extract_learner_responses_from_existing_bundles => :environment do bl_count = Dataservice::BundleLogger.count bc_count = Dataservice::BundleContent.count puts "Extracting learner responses from #{bc_count} existing OTrunk bundles belonging to #{bl_count} learners." Dataservice::BundleLogger.find_in_batches(:batch_size => 10) do |bundle_logger| bundle_logger.each { |bl| bl.extract_open_responses } print '.'; STDOUT.flush end puts end desc "Erase all learner responses and reset the tables" task :erase_all_learner_responses_and_reset_the_tables => :environment do puts "Erase all saveable learner responses and reset the tables" saveable_models = Dir["app/models/saveable/**/*.rb"].collect { |m| m[/app\/models\/(.+?).rb/, 1] }.collect { |m| m.camelize.constantize } saveable_models.each do |model| ActiveRecord::Base.connection.delete("TRUNCATE `#{model.table_name}`") puts "deleted: all from #{model}" end puts end MULTI_CHOICE = /<object refid="([a-fA-F0-9\-]+)!\/multiple_choice_(\d+)\/input\/choices\[(\d+)\]"(.*?)>/m desc "Fix learner bundle contents so that Multiple Choice answers point using an OTrunk local id instead of a path id." task :convert_choice_answers_to_local_ids => :environment do unchanged = {} changed = {} problems = {} Dataservice::BundleContent.find_in_batches do |batch| batch.each do |bundle_content| new_otml = bundle_content.otml.gsub(MULTI_CHOICE) { retval = "" begin m_choice = Embeddable::MultipleChoice.find($2.to_i) if m_choice choice = m_choice.choices[$3.to_i] if choice retval = "<object refid=\"#{$1}!/embeddable__multiple_choice_choice_#{choice.id}\"#{$4}>" else raise "Couldn't find choice #{$3} in Multiple Choice #{$2}" end else raise "Couldn't find Multiple Choice #{$2}" end rescue => e problems[bundle_content.id] ||= [] problems[bundle_content.id] << "#{e} (#{$&})" retval = $& end retval } if new_otml != bundle_content.otml changed[bundle_content.id] = true bundle_content.otml = new_otml # Now convert the otml into actual bundle content bundle_content.body = bundle_content.convert_otml_to_body bundle_content.save else unchanged[bundle_content.id] = true end end # end batch.each end # end find_in_batches puts "Finished fixing multiple choice references." puts "#{changed.size} bundles changed, #{unchanged.size} were unchanged." puts "The following bundles had problems: " problems.entries.sort.each do |entry| puts " BC #{entry[0]} (#{changed[entry[0]] ? "changed" : "unchanged"}):" entry[1].each do |prob| puts " #{prob}" end end end # end task end end Modified multiple choice reference regexp to support finding references to Embeddable::MultipleChoice questions as well. require 'rake' namespace :rigse do namespace :convert do desc 'Add the author role to all users who have authored an Investigation' task :add_author_role_to_authors => :environment do User.find(:all).each do |user| if user.has_investigations? print '.' STDOUT.flush user.add_role('author') end end puts end desc 'Remove the author role from users who have not authored an Investigation' task :remove_author_role_from_non_authors => :environment do User.find(:all).each do |user| unless user.has_investigations? print '.' STDOUT.flush user.remove_role('author') end end puts end desc 'transfer any Investigations owned by the anonymous user to the site admin user' task :transfer_investigations_owned_by_anonymous => :environment do admin_user = User.find_by_login(APP_CONFIG[:admin_login]) anonymous_investigations = User.find_by_login('anonymous').investigations if anonymous_investigations.length > 0 puts "#{anonymous_investigations.length} Investigations owned by the anonymous user" puts "resetting ownership to the site admin user: #{admin_user.name}" anonymous_investigations.each do |inv| inv.deep_set_user(admin_user) print '.' STDOUT.flush end else puts 'no Investigations owned by the anonymous user' end end ####################################################################### # # Assign Vernier go!Link as default vendor_interface for users # without a vendor_interface. # ####################################################################### desc "Assign Vernier go!Link as default vendor_interface for users without a vendor_interface." task :assign_vernier_golink_to_users => :environment do interface = Probe::VendorInterface.find_by_short_name('vernier_goio') User.find(:all).each do |u| unless u.vendor_interface u.vendor_interface = interface u.save end end end desc 'ensure investigations have publication_status' task :pub_status => :environment do Investigation.find(:all).each do |i| if i.publication_status.nil? i.update_attribute(:publication_status,'draft') end end end desc 'Data Collectors with a static graph_type to a static attribute; Embeddable::DataCollectors with a graph_type_id of nil to Sensor' task :data_collectors_with_invalid_graph_types => :environment do puts <<HEREDOC This task will search for all Data Collectors with a graph_type_id == 3 (Static) which was used to indicate a static graph type, and set the graph_type_id to 1 (Sensor) and set the new boolean attribute static to true. In addition it will set the graph_type_id to 1 if the existing graph_type_id is nil. These Embeddable::DataCollectors appeared to be created by the ITSI importer. There is no way for this transformation to tell whether the original graph was a sensor or prediction graph_type so it sets the type to 1 (Sensor). HEREDOC old_style_static_graphs = Embeddable::DataCollector.find_all_by_graph_type_id(3) puts "converting #{old_style_static_graphs.length} old style static graphs and changing type to Sensor" attributes = { :graph_type_id => 1, :static => true } old_style_static_graphs.each do |dc| dc.update_attributes(attributes) print '.'; STDOUT.flush end puts nil_graph_types = Embeddable::DataCollector.find_all_by_graph_type_id(nil) puts "changing type of #{nil_graph_types.length} Embeddable::DataCollectors with nil graph_type_ids to Sensor" attributes = { :graph_type_id => 1, :static => false } nil_graph_types.each do |dc| dc.update_attributes(attributes) print '.'; STDOUT.flush end puts end desc 'copy truncated Embeddable::Xhtml from Embeddable::Xhtml#content, Embeddable::OpenResponse and Embeddable::MultipleChoice#prompt into name' task :copy_truncated_xhtml_into_name => :environment do models = [Embeddable::Xhtml, Embeddable::OpenResponse, Embeddable::MultipleChoice] puts "\nprocessing #{models.join(', ')} models to generate new names from soft-truncated xhtml.\n" [Embeddable::Xhtml, Embeddable::OpenResponse, Embeddable::MultipleChoice].each do |klass| puts "\nprocessing #{klass.count} #{klass} model instances, extracting truncated text from xhtml and generating new name attribute\n" klass.find_in_batches(:batch_size => 100) do |group| group.each { |x| x.save! } print '.'; STDOUT.flush end end puts end desc 'create default Project from config/settings.yml' task :create_default_project_from_config_settings_yml => :environment do Admin::Project.create_or_update_default_project_from_settings_yml end desc 'generate date_str attributes from version_str for MavenJnlp::VersionedJnlpUrls' task :generate_date_str_for_versioned_jnlp_urls => :environment do puts "\nprocessing #{MavenJnlp::VersionedJnlpUrl.count} MavenJnlp::VersionedJnlpUrl model instances, generating date_str from version_str\n" MavenJnlp::VersionedJnlpUrl.find_in_batches do |group| group.each { |j| j.save! } print '.'; STDOUT.flush end puts end desc "Create bundle and console loggers for learners" task :create_bundle_and_console_loggers_for_learners => :environment do Portal::Learner.find(:all).each do |learner| learner.console_logger = Dataservice::ConsoleLogger.create! unless learner.console_logger learner.bundle_logger = Dataservice::BundleLogger.create! unless learner.bundle_logger learner.save! end end desc "Create bundle and console loggers for learners" task :create_bundle_and_console_loggers_for_learners => :environment do Portal::Learner.find(:all).each do |learner| learner.console_logger = Dataservice::ConsoleLogger.create! unless learner.console_logger learner.bundle_logger = Dataservice::BundleLogger.create! unless learner.bundle_logger learner.save! end end def find_and_report_on_invalid_bundle_contents(&block) count = Dataservice::BundleContent.count puts "\nScanning #{count} Dataservice::BundleContent model instances for invalid bodies\n\n" invalid = [] Dataservice::BundleContent.find_in_batches(:batch_size => 10) do |group| invalid << group.find_all { |bc| !bc.valid? } print '.'; STDOUT.flush end invalid.flatten! if invalid.empty? puts "\n\nAll #{count} were valid.\n\n" else puts "\n\nFound #{invalid.length} invalid Dataservice::BundleContent models.\n\n" invalid.each do |bc| learner = bc.bundle_logger.learner puts "id: #{bc.id}" puts " learner #{learner.id}: #{learner.name}; #{learner.student.user.login}" puts " investigation: #{learner.offering.runnable.id}: #{learner.offering.name}" puts " date #{bc.created_at}" yield(bc) if block puts end end end desc "Find and report on invalid Dataservice::BundleContent objects" task :find_and_report_on_invalid_dataservice_bundle_content_objects => :environment do find_and_report_on_invalid_bundle_contents end desc "Find and delete invalid Dataservice::BundleContent objects" task :find_and_delete_invalid_dataservice_bundle_content_objects => :environment do find_and_report_on_invalid_bundle_contents do |bc| puts puts " deleting Dataservice::BundleContent id:#{bc.id}..." bc.destroy end end desc "generate otml, valid_xml, and empty attributes for BundleContent objects" task :generate_otml_valid_xml_and_empty_attributes_for_bundle_content_objects => :environment do count = Dataservice::BundleContent.count puts "\nRe-saving #{count} Dataservice::BundleContent model instances\n\n" Dataservice::BundleContent.find_in_batches(:batch_size => 10) do |group| group.each { |bc| !bc.save! } print '.'; STDOUT.flush end end desc "Convert Existing Clazzes so that multiple Teachers can own a clazz. (many to many change)" task :convert_clazzes_to_multi_teacher => :environment do MultiteacherClazzes.make_all_multi_teacher end desc "Fixup inner pages so they have a satic area (run migrations first)" task :add_static_page_to_inner_pages => :environment do innerPageElements = PageElement.all.select { |pe| pe.embeddable_type == "Embeddable::InnerPage" } innerPages = innerPageElements.map { |pe| pe.embeddable } innerPages.each do |ip| if ip.static_page.nil? ip.static_page = Page.new ip.static_page.user = ip.user ip.save end end end # Feb 3, 2010 desc "Extract and process learner responses from existing OTrunk bundles" task :extract_learner_responses_from_existing_bundles => :environment do bl_count = Dataservice::BundleLogger.count bc_count = Dataservice::BundleContent.count puts "Extracting learner responses from #{bc_count} existing OTrunk bundles belonging to #{bl_count} learners." Dataservice::BundleLogger.find_in_batches(:batch_size => 10) do |bundle_logger| bundle_logger.each { |bl| bl.extract_open_responses } print '.'; STDOUT.flush end puts end desc "Erase all learner responses and reset the tables" task :erase_all_learner_responses_and_reset_the_tables => :environment do puts "Erase all saveable learner responses and reset the tables" saveable_models = Dir["app/models/saveable/**/*.rb"].collect { |m| m[/app\/models\/(.+?).rb/, 1] }.collect { |m| m.camelize.constantize } saveable_models.each do |model| ActiveRecord::Base.connection.delete("TRUNCATE `#{model.table_name}`") puts "deleted: all from #{model}" end puts end MULTI_CHOICE = /<object refid="([a-fA-F0-9\-]+)!\/(?:embeddable__)?multiple_choice_(\d+)\/input\/choices\[(\d+)\]"(.*?)>/m desc "Fix learner bundle contents so that Multiple Choice answers point using an OTrunk local id instead of a path id." task :convert_choice_answers_to_local_ids => :environment do unchanged = {} changed = {} problems = {} Dataservice::BundleContent.find_in_batches do |batch| batch.each do |bundle_content| new_otml = bundle_content.otml.gsub(MULTI_CHOICE) { retval = "" begin m_choice = Embeddable::MultipleChoice.find($2.to_i) if m_choice choice = m_choice.choices[$3.to_i] if choice retval = "<object refid=\"#{$1}!/embeddable__multiple_choice_choice_#{choice.id}\"#{$4}>" else raise "Couldn't find choice #{$3} in Multiple Choice #{$2}" end else raise "Couldn't find Multiple Choice #{$2}" end rescue => e problems[bundle_content.id] ||= [] problems[bundle_content.id] << "#{e} (#{$&})" retval = $& end retval } if new_otml != bundle_content.otml changed[bundle_content.id] = true bundle_content.otml = new_otml # Now convert the otml into actual bundle content bundle_content.body = bundle_content.convert_otml_to_body bundle_content.save else unchanged[bundle_content.id] = true end end # end batch.each end # end find_in_batches puts "Finished fixing multiple choice references." puts "#{changed.size} bundles changed, #{unchanged.size} were unchanged." puts "The following #{problems.size} bundles had problems: " problems.entries.sort.each do |entry| puts " BC #{entry[0]} (#{changed[entry[0]] ? "changed" : "unchanged"}):" entry[1].each do |prob| puts " #{prob}" end end end # end task end end
module Clamp VERSION = "0.1.3".freeze end Moving ahead. module Clamp VERSION = "0.1.4.dev".freeze end
require 'net/http' require 'uri' namespace :images do desc 'Fetch representatives images from stortinget.no' task :fetch_representatives => :environment do rep_image_path = Rails.root.join("app/assets/images/representatives") Representative.all.each do |rep| url = URI.parse("http://stortinget.no/Personimages/PersonImages_ExtraLarge/#{URI.escape rep.external_id}_ekstrastort.jpg") filename = rep_image_path.join("#{rep.slug}.jpg") if ENV['FORCE'].nil? && filename.exist? puts "skipping download for existing #{filename}, use FORCE=true to override" rep.image = filename rep.save! next end File.open(filename.to_s, "wb") do |destination| resp = Net::HTTP.get_response(url) do |response| total = response.content_length progress = 0 segment_count = 0 response.read_body do |segment| progress += segment.length segment_count += 1 if segment_count % 15 == 0 percent = (progress.to_f / total.to_f) * 100 print "\rDownloading #{url}: #{percent.to_i}% (#{progress} / #{total})" $stdout.flush segment_count = 0 end destination.write(segment) end end destination.close if !resp.kind_of?(Net::HTTPSuccess) puts "\nERROR:#{resp.code} for #{url}" File.delete(destination.path) else if File.zero?(destination.path) puts "\nERROR: url #{url} returned an empty file" File.delete(destination.path) else print "\rDownloading #{url} finished. Saved as #{filename}\n" $stdout.flush rep.image = Pathname.new filename end end rep.save! end end end desc 'Save party logos to Party models' task :party_logos => :environment do puts "Mapping each party's logo to image attribute" path_to_logos = Rails.root.join("app/assets/images/party_logos") Party.all.each do |party| party.image = path_to_logos.join("#{party.external_id}_logo_large.jpg") party.save! puts "\t#{party.name}" end end desc 'Set up all images' task :all => %w[images:fetch_representatives images:party_logos] end Fixed fetch_representatives task so it sets images if they are already downloaded. Useful if db was dropped but images don't need to be re-downloaded. require 'net/http' require 'uri' namespace :images do desc 'Fetch representatives images from stortinget.no' task :fetch_representatives => :environment do rep_image_path = Rails.root.join("app/assets/images/representatives") Representative.all.each do |rep| url = URI.parse("http://stortinget.no/Personimages/PersonImages_ExtraLarge/#{URI.escape rep.external_id}_ekstrastort.jpg") filename = rep_image_path.join("#{rep.slug}.jpg") if ENV['FORCE'].nil? && filename.exist? puts "skipping download for existing #{filename}, use FORCE=true to override" rep.image = Pathname.new filename rep.save! next end File.open(filename.to_s, "wb") do |destination| resp = Net::HTTP.get_response(url) do |response| total = response.content_length progress = 0 segment_count = 0 response.read_body do |segment| progress += segment.length segment_count += 1 if segment_count % 15 == 0 percent = (progress.to_f / total.to_f) * 100 print "\rDownloading #{url}: #{percent.to_i}% (#{progress} / #{total})" $stdout.flush segment_count = 0 end destination.write(segment) end end destination.close if !resp.kind_of?(Net::HTTPSuccess) puts "\nERROR:#{resp.code} for #{url}" File.delete(destination.path) else if File.zero?(destination.path) puts "\nERROR: url #{url} returned an empty file" File.delete(destination.path) else print "\rDownloading #{url} finished. Saved as #{filename}\n" $stdout.flush rep.image = Pathname.new filename end end rep.save! end end end desc 'Save party logos to Party models' task :save_party_logos => :environment do puts "Mapping each party's logo to image attribute" path_to_logos = Rails.root.join("app/assets/images/party_logos") Party.all.each do |party| party.image = Pathname.new("#{path_to_logos}/#{party.external_id}_logo_large.jpg") party.save! puts "Logo for #{party.name} mapped." end end task :all => %w[images:fetch_representatives images:save_party_logos] end
namespace :gs do namespace :import do def sql_string(table) File.open(File.join(Rails.root, 'db', 'original_site_data', "#{table}.sql")) { |f| f.read } end def songs @songs ||= begin songs_by_id = {} song_sql = sql_string('songs') song_regex = /^\((\d+), '[^']+', '([^']+)'/ # http://rubular.com/regexes/12057 song_sql.scan(song_regex) do |captures| songs_by_id[captures[0].to_i] = captures[1] end songs_by_id end end def ratings @ratings ||= begin ratings = [] rating_sql = sql_string('ratings') rating_regex = /^\(\d+, (\d+), '([^']+)', '[^']+', (\d+), '([^']+)'/ # http://rubular.com/regexes/12058 rating_sql.scan(rating_regex) do |captures| ratings << { :rating => captures[0].to_i, :created_at => DateTime.parse(captures[1]), :song_id => captures[2].to_i, :user_ip_address => captures[3] } end ratings end end desc 'Import ratings data from the original ghosts and spirits site' task :ratings => :environment do Rating.delete_all Page.update_all({ :average_rating => 0 }) puts "Importing ratings..." ratings.each do |r| parent_page = Page.find_by_slug!('the-album') page = Page.find_by_parent_id_and_slug!(parent_page.id, songs[r[:song_id]]) user_token = Digest::SHA1.hexdigest(r[:user_ip_address]) page.add_rating(r[:rating], user_token) print '.' end end end end Added rake task to import comments from the original ghost and spirits web site. namespace :gs do namespace :import do def sql_string(table) File.open(File.join(Rails.root, 'db', 'original_site_data', "#{table}.sql")) { |f| f.read } end def songs @songs ||= begin songs_by_id = {} song_sql = sql_string('songs') song_regex = /^\((\d+), '[^']+', '([^']+)'/ # http://rubular.com/regexes/12057 song_sql.scan(song_regex) do |captures| songs_by_id[captures[0].to_i] = captures[1] end songs_by_id end end def ratings @ratings ||= begin ratings = [] rating_sql = sql_string('ratings') rating_regex = /^\(\d+, (\d+), '([^']+)', '[^']+', (\d+), '([^']+)'/ # http://rubular.com/regexes/12058 rating_sql.scan(rating_regex) do |captures| ratings << { :rating => captures[0].to_i, :created_at => DateTime.parse(captures[1]), :song_id => captures[2].to_i, :user_ip_address => captures[3] } end ratings end end def comments @comments ||= begin comments = [] comment_sql = sql_string('comments') comment_regex = /^\(\d+, '(.+?)', '([^']+)', (\d+), '[^']+', '([\d\.]+)', '([^']+)', '([^']+)', '([^']*)', '([^']+)', '([^']+)'/ # http://rubular.com/regexes/12122 comment_sql.scan(comment_regex) do |captures| comments << { :content => captures[0].gsub("''", "'").gsub(/<i>(.+?)<\/i>/, '_\1_').gsub("\\r", "\r").gsub("\\n", "\n"), :created_at => DateTime.parse(captures[1]), :song_id => captures[2].to_i, :author_ip => captures[3], :author => captures[4], :author_email => captures[5], :author_url => captures[6], :parent_page_slug => captures[7], :updated_at => DateTime.parse(captures[8]) } end comments end end desc 'Import dynamic data from the original ghosts and spirits site' task :all => [:environment, :ratings, :comments] desc 'Import ratings data from the original ghosts and spirits site' task :ratings => :environment do $stdout.sync = true Rating.delete_all Page.update_all({ :average_rating => 0 }) puts "Importing ratings: " ratings.each do |r| parent_page = Page.find_by_slug!('the-album') page = Page.find_by_parent_id_and_slug!(parent_page.id, songs[r[:song_id]]) user_token = Digest::SHA1.hexdigest(r[:user_ip_address]) page.add_rating(r[:rating], user_token) print '.' end puts end desc 'Import comments data from the original ghosts and spirits site' task :comments => :environment do Comment.class_eval do def auto_approve? true end def filter TextileFilter end end SimpleSpamFilter.class_eval do def valid?(comment) true end end $stdout.sync = true Comment.delete_all Page.update_all({ :comments_count => 0 }) puts "Importing comments: " comments.each do |c| parent_page = Page.find_by_slug!(c.delete(:parent_page_slug)) page = parent_page.children.find_by_slug!(songs[c.delete(:song_id)]) comment = page.comments.build(c) comment.referrer = "http://ghostsandspirits.net#{page.url}" comment.author_ip = c[:author_ip] comment.save! Comment.update_all({ :created_at => c[:created_at], :updated_at => c[:updated_at] }, { :id => comment.id }) print '.' end puts end end end
namespace :import do namespace :xml_files do desc 'Import the latest XML of every ontology again.' task :again => :environment do ActiveRecord::Base.logger = Logger.new($stdout) Ontology.all.map(&:import_latest_version) end end namespace :hets do desc 'Import the hets library.' task :lib => :environment do def find_hets_lib_path settings_for_development['paths']['hets']['hets_lib']. map { |path| File.expand_path path }. find { |path| File.directory?(path) } end hets_lib_path = ENV['HETS_LIB'] hets_lib_path ||= find_hets_lib_path unless File.directory?(hets_lib_path) raise 'No path to hets-lib given or it is not a directory. '\ 'Please specify the path to hets-lib in the environment '\ 'variable HETS_LIB.' end user = User.find_by_email! ENV['EMAIL'] unless ENV['EMAIL'].nil? user ||= User.find_all_by_admin(true).first repo = Repository.new(name: 'Hets lib') begin repo.save! rescue ActiveRecord::RecordInvalid abort '"Hets lib" repository already existing.' end repo.import_ontologies(user, hets_lib_path) end end desc 'Import logic graph.' task :logicgraph => :environment do RakeHelper.import_logicgraph(ENV['EMAIL']) end desc 'Import keywords starting with P.' task :keywords => :environment do ontologySearch = OntologySearch.new() puts ontologySearch.makeKeywordListJson('P') end def settings_for_development @settings_for_development ||= YAML.load_file(Rails.root.join('config', 'settings_for_development.yml').to_s) end end Fix rake import:logicgraph. namespace :import do namespace :xml_files do desc 'Import the latest XML of every ontology again.' task :again => :environment do ActiveRecord::Base.logger = Logger.new($stdout) Ontology.all.map(&:import_latest_version) end end namespace :hets do desc 'Import the hets library.' task :lib => :environment do def find_hets_lib_path settings_for_development['paths']['hets']['hets_lib']. map { |path| File.expand_path path }. find { |path| File.directory?(path) } end hets_lib_path = ENV['HETS_LIB'] hets_lib_path ||= find_hets_lib_path unless File.directory?(hets_lib_path) raise 'No path to hets-lib given or it is not a directory. '\ 'Please specify the path to hets-lib in the environment '\ 'variable HETS_LIB.' end user = User.find_by_email! ENV['EMAIL'] unless ENV['EMAIL'].nil? user ||= User.find_all_by_admin(true).first repo = Repository.new(name: 'Hets lib') begin repo.save! rescue ActiveRecord::RecordInvalid abort '"Hets lib" repository already existing.' end repo.import_ontologies(user, hets_lib_path) end end desc 'Import logic graph.' task :logicgraph => :environment do RakeHelper::LogicGraph.import(ENV['EMAIL']) end desc 'Import keywords starting with P.' task :keywords => :environment do ontologySearch = OntologySearch.new() puts ontologySearch.makeKeywordListJson('P') end def settings_for_development @settings_for_development ||= YAML.load_file(Rails.root.join('config', 'settings_for_development.yml').to_s) end end
namespace :locale do desc "Extract strings from en.yml and store them in a ruby file for gettext:find" task :store_dictionary_strings do output_strings = [ "# This is automatically generated file (rake locale:store_dictionary_strings).", "# The file contains strings extracted from en.yml for gettext to find." ] no_plurals = %w(NFS OS) # strings which we don't want to create automatic plurals for dict = YAML.load(File.open(Rails.root.join("config/locales/en.yml")))["en"]["dictionary"] dict.keys.each do |tree| next unless %w(column model table).include?(tree) # subtrees of interest dict[tree].keys.each do |item| if dict[tree][item].kind_of?(String) # leaf node output_strings.push("# TRANSLATORS: en.yml key: dictionary.#{tree}.#{item}") value = dict[tree][item] output_strings.push('_("%s")' % value) if %w(model table).include?(tree) && # create automatic plurals for model and table subtrees !no_plurals.include?(value) m = /(.+)(\s+\(.+\))/.match(value) # strings like: "Infrastructure Provider (Openstack)" value_plural = m ? "#{m[1].pluralize}#{m[2]}" : value.pluralize if value != value_plural output_strings.push("# TRANSLATORS: en.yml key: dictionary.#{tree}.#{item} (plural form)") output_strings.push('_("%s")' % value_plural) end end elsif dict[tree][item].kind_of?(Hash) # subtree dict[tree][item].keys.each do |subitem| output_strings.push("# TRANSLATORS: en.yml key: dictionary.#{tree}.#{item}.#{subitem}") output_strings.push('_("%s")' % dict[tree][item][subitem]) end end end end File.open(Rails.root.join("config/dictionary_strings.rb"), "w+") do |f| f.puts(output_strings) end end desc "Extract strings from various yaml files and store them in a ruby file for gettext:find" task :extract_yaml_strings do def update_output(string, file, output) return if string.nil? || string.empty? if output.key?(string) output[string].append(file) else output[string] = [file] end end def parse_object(object, keys, file, output) if object.kind_of?(Hash) object.keys.each do |key| if keys.include?(key) || keys.include?(key.to_s) if object[key].kind_of?(Array) object[key].each { |i| update_output(i, file, output) } else update_output(object[key], file, output) end end parse_object(object[key], keys, file, output) end elsif object.kind_of?(Array) object.each do |item| parse_object(item, keys, file, output) end end end yamls = { "db/fixtures/miq_product_features.*" => %w(name description), "db/fixtures/miq_report_formats.*" => %w(description), "product/timelines/miq_reports/*.*" => %w(title name headers), "product/views/*.*" => %w(title name headers) } output = {} yamls.keys.each do |yaml_glob| Dir.glob(yaml_glob).each do |file| yml = YAML.load_file(Rails.root.join(file)) parse_object(yml, yamls[yaml_glob], file, output) end end File.open(Rails.root.join("config/yaml_strings.rb"), "w+") do |f| f.puts "# This is automatically generated file (rake locale:extract_yaml_strings)." f.puts "# The file contains strings extracted from various yaml files for gettext to find." output.keys.each do |key| output[key].sort.uniq.each do |file| f.puts "# TRANSLATORS: file: #{file}" end f.puts '_("%s")' % key end end end desc "Extract human locale names from translation catalogs and store them in a yaml file" task :extract_locale_names do require 'yaml/store' require Rails.root.join("lib/vmdb/fast_gettext_helper") Vmdb::FastGettextHelper.register_locales locale_hash = {} FastGettext.available_locales.each do |locale| FastGettext.locale = locale # TRANSLATORS: Provide locale name in native language (e.g. English, Deutsch or Português) human_locale = Vmdb::FastGettextHelper.locale_name human_locale = locale if human_locale == "locale_name" locale_hash[locale] = human_locale end store = YAML::Store.new("config/human_locale_names.yaml") store.transaction do store['human_locale_names'] = locale_hash end end desc "Extract model attribute names and virtual column names" task "store_model_attributes" do require 'gettext_i18n_rails/model_attributes_finder' require_relative 'model_attribute_override.rb' attributes_file = 'config/locales/model_attributes.rb' File.unlink(attributes_file) if File.exist?(attributes_file) Rake::Task['gettext:store_model_attributes'].invoke FileUtils.mv(attributes_file, 'config/model_attributes.rb') end desc "Extract plugin strings - execute as: rake locale:plugin:find[plugin_name]" task "plugin:find", :engine do |_, args| unless args.has_key?(:engine) $stderr.puts "You need to specify a plugin name: rake locale:plugin:find[plugin_name]" exit 1 end @domain = args[:engine].gsub('::', '_') @engine = "#{args[:engine].camelize}::Engine".constantize @engine_root = @engine.root namespace :gettext do def locale_path @engine_root.join('locale').to_s end def files_to_translate Dir.glob("#{@engine.root}/{app,db,lib,config,locale}/**/*.{rb,erb,haml,slim,rhtml,js}") end def text_domain @domain end end FastGettext.add_text_domain(@domain, :path => @engine_root.join('locale').to_s, :type => :po, :ignore_fuzzy => true, :report_warning => false) Rake::Task['gettext:find'].invoke end end move model_attributes.rb under locale/ namespace :locale do desc "Extract strings from en.yml and store them in a ruby file for gettext:find" task :store_dictionary_strings do output_strings = [ "# This is automatically generated file (rake locale:store_dictionary_strings).", "# The file contains strings extracted from en.yml for gettext to find." ] no_plurals = %w(NFS OS) # strings which we don't want to create automatic plurals for dict = YAML.load(File.open(Rails.root.join("config/locales/en.yml")))["en"]["dictionary"] dict.keys.each do |tree| next unless %w(column model table).include?(tree) # subtrees of interest dict[tree].keys.each do |item| if dict[tree][item].kind_of?(String) # leaf node output_strings.push("# TRANSLATORS: en.yml key: dictionary.#{tree}.#{item}") value = dict[tree][item] output_strings.push('_("%s")' % value) if %w(model table).include?(tree) && # create automatic plurals for model and table subtrees !no_plurals.include?(value) m = /(.+)(\s+\(.+\))/.match(value) # strings like: "Infrastructure Provider (Openstack)" value_plural = m ? "#{m[1].pluralize}#{m[2]}" : value.pluralize if value != value_plural output_strings.push("# TRANSLATORS: en.yml key: dictionary.#{tree}.#{item} (plural form)") output_strings.push('_("%s")' % value_plural) end end elsif dict[tree][item].kind_of?(Hash) # subtree dict[tree][item].keys.each do |subitem| output_strings.push("# TRANSLATORS: en.yml key: dictionary.#{tree}.#{item}.#{subitem}") output_strings.push('_("%s")' % dict[tree][item][subitem]) end end end end File.open(Rails.root.join("config/dictionary_strings.rb"), "w+") do |f| f.puts(output_strings) end end desc "Extract strings from various yaml files and store them in a ruby file for gettext:find" task :extract_yaml_strings do def update_output(string, file, output) return if string.nil? || string.empty? if output.key?(string) output[string].append(file) else output[string] = [file] end end def parse_object(object, keys, file, output) if object.kind_of?(Hash) object.keys.each do |key| if keys.include?(key) || keys.include?(key.to_s) if object[key].kind_of?(Array) object[key].each { |i| update_output(i, file, output) } else update_output(object[key], file, output) end end parse_object(object[key], keys, file, output) end elsif object.kind_of?(Array) object.each do |item| parse_object(item, keys, file, output) end end end yamls = { "db/fixtures/miq_product_features.*" => %w(name description), "db/fixtures/miq_report_formats.*" => %w(description), "product/timelines/miq_reports/*.*" => %w(title name headers), "product/views/*.*" => %w(title name headers) } output = {} yamls.keys.each do |yaml_glob| Dir.glob(yaml_glob).each do |file| yml = YAML.load_file(Rails.root.join(file)) parse_object(yml, yamls[yaml_glob], file, output) end end File.open(Rails.root.join("config/yaml_strings.rb"), "w+") do |f| f.puts "# This is automatically generated file (rake locale:extract_yaml_strings)." f.puts "# The file contains strings extracted from various yaml files for gettext to find." output.keys.each do |key| output[key].sort.uniq.each do |file| f.puts "# TRANSLATORS: file: #{file}" end f.puts '_("%s")' % key end end end desc "Extract human locale names from translation catalogs and store them in a yaml file" task :extract_locale_names do require 'yaml/store' require Rails.root.join("lib/vmdb/fast_gettext_helper") Vmdb::FastGettextHelper.register_locales locale_hash = {} FastGettext.available_locales.each do |locale| FastGettext.locale = locale # TRANSLATORS: Provide locale name in native language (e.g. English, Deutsch or Português) human_locale = Vmdb::FastGettextHelper.locale_name human_locale = locale if human_locale == "locale_name" locale_hash[locale] = human_locale end store = YAML::Store.new("config/human_locale_names.yaml") store.transaction do store['human_locale_names'] = locale_hash end end desc "Extract model attribute names and virtual column names" task "store_model_attributes" do require 'gettext_i18n_rails/model_attributes_finder' require_relative 'model_attribute_override.rb' attributes_file = 'locale/model_attributes.rb' File.unlink(attributes_file) if File.exist?(attributes_file) Rake::Task['gettext:store_model_attributes'].invoke FileUtils.mv(attributes_file, 'config/model_attributes.rb') end desc "Extract plugin strings - execute as: rake locale:plugin:find[plugin_name]" task "plugin:find", :engine do |_, args| unless args.has_key?(:engine) $stderr.puts "You need to specify a plugin name: rake locale:plugin:find[plugin_name]" exit 1 end @domain = args[:engine].gsub('::', '_') @engine = "#{args[:engine].camelize}::Engine".constantize @engine_root = @engine.root namespace :gettext do def locale_path @engine_root.join('locale').to_s end def files_to_translate Dir.glob("#{@engine.root}/{app,db,lib,config,locale}/**/*.{rb,erb,haml,slim,rhtml,js}") end def text_domain @domain end end FastGettext.add_text_domain(@domain, :path => @engine_root.join('locale').to_s, :type => :po, :ignore_fuzzy => true, :report_warning => false) Rake::Task['gettext:find'].invoke end end
require_relative 'replicant' module Ava class Client attr_accessor :host, :port, :socket, :response def initialize host: 'localhost', port: 2016, key: nil self.host = host self.port = port @client_id = {key: nil, iv: nil, encrypt: false} get_id(key) if key end def inspect "#<#{self.class}:#{self.object_id}>" end def connect @socket = TCPSocket.open(@host, @port) end def close @socket.close if defined?(@socket) end def get_id key @client_id[:encrypt] = false response = request :controller, :secret_key, key if response @client_id = response true else false end end def get_object name Replicant.new name, self if registered_objects.include?(name) end def registered_objects request(:controller, :registered_objects) end def required_gems request(:controller, :required_gems) end def missing_gems required_gems - Gem.loaded_specs.keys end def require_missing_gems missing_gems.map do |gem| begin require gem [gem, true] rescue [gem, false] end end.to_h end def method_missing *args, **named if args.size == 1 && (named == {} || named.nil?) && registered_objects.any?{ |o| o.to_sym == args.first} Replicant.new args.first, self else request args.first, args[1], *args[2..-1], **named end end def request object, method = nil, *args, **named return get_object(object) if method.nil? connect raw = named.delete(:raw) argument = (named.nil? ? {} : named).merge({args:args}) request = {object => { method => argument }, client_id: @client_id[:key], raw: raw } @socket.puts encrypt_msg(request.to_yaml) lines = Array.new while line = @socket.gets lines << line end @response = decrypt_msg(YAML.load(lines.join)).map{ |k,v| [k.to_sym, v]}.to_h close @response[:response] ? @response[:response] : (raise @response[:error]) end def send_file bits, save_to = '' request :send_file, :send_file, bits, path: save_to end def get_file path, save_to = Dir.pwd save_to+= path.file_name if File.directory?(save_to) File.open(save_to, 'w') do |file| file.write(read_file(path)) end File.exists?(save_to) end def read_file path request :get_file, :get_file, path: path end def encrypt_msg msg return msg if !@client_id[:encrypt] cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") cipher.encrypt cipher.key = @client_id[:key] cipher.iv = @client_id[:iv] enc = cipher.update msg.to_yaml enc << cipher.final {encrypted: enc, client_id: @client_id[:key]}.to_yaml end def decrypt_msg msg return msg if !@client_id[:encrypt] || !msg.include?(:encrypted) cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") cipher.decrypt cipher.key = @client_id[:key] cipher.iv = @client_id[:iv] dec = cipher.update msg[:encrypted] dec << cipher.final YAML.load(YAML.load(dec)) end end end get_object now throws an error if the object name is not found rather than just returning nil. require_relative 'replicant' module Ava class Client attr_accessor :host, :port, :socket, :response def initialize host: 'localhost', port: 2016, key: nil self.host = host self.port = port @client_id = {key: nil, iv: nil, encrypt: false} get_id(key) if key end def inspect "#<#{self.class}:#{self.object_id}>" end def connect @socket = TCPSocket.open(@host, @port) end def close @socket.close if defined?(@socket) end def get_id key @client_id[:encrypt] = false response = request :controller, :secret_key, key if response @client_id = response true else false end end def get_object name raise ArgumentError, "No object is registered under the name '#{name}'." unless registered_objects.include?(name) Replicant.new name, self end def registered_objects request(:controller, :registered_objects) end def required_gems request(:controller, :required_gems) end def missing_gems required_gems - Gem.loaded_specs.keys end def require_missing_gems missing_gems.map do |gem| begin require gem [gem, true] rescue [gem, false] end end.to_h end def method_missing *args, **named if args.size == 1 && (named == {} || named.nil?) && registered_objects.any?{ |o| o.to_sym == args.first} Replicant.new args.first, self else request args.first, args[1], *args[2..-1], **named end end def request object, method = nil, *args, **named return get_object(object) if method.nil? connect raw = named.delete(:raw) argument = (named.nil? ? {} : named).merge({args:args}) request = {object => { method => argument }, client_id: @client_id[:key], raw: raw } @socket.puts encrypt_msg(request.to_yaml) lines = Array.new while line = @socket.gets lines << line end @response = decrypt_msg(YAML.load(lines.join)).map{ |k,v| [k.to_sym, v]}.to_h close @response[:response] ? @response[:response] : (raise @response[:error]) end def send_file bits, save_to = '' request :send_file, :send_file, bits, path: save_to end def get_file path, save_to = Dir.pwd save_to+= path.file_name if File.directory?(save_to) File.open(save_to, 'w') do |file| file.write(read_file(path)) end File.exists?(save_to) end def read_file path request :get_file, :get_file, path: path end def encrypt_msg msg return msg if !@client_id[:encrypt] cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") cipher.encrypt cipher.key = @client_id[:key] cipher.iv = @client_id[:iv] enc = cipher.update msg.to_yaml enc << cipher.final {encrypted: enc, client_id: @client_id[:key]}.to_yaml end def decrypt_msg msg return msg if !@client_id[:encrypt] || !msg.include?(:encrypted) cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc") cipher.decrypt cipher.key = @client_id[:key] cipher.iv = @client_id[:iv] dec = cipher.update msg[:encrypted] dec << cipher.final YAML.load(YAML.load(dec)) end end end
namespace :mobile do namespace :assets do task precompile: :environment do puts 'Precompiling the rails assets' `RAILS_ENV=local_production bundle exec rake assets:clobber assets:precompile` end namespace :copy do desc 'Copies the application.js file to the mobile application' # This task assumes that the mobile application is checked out as # "mykonote-app" in the same directory as this project task js: :precompile do puts 'Copying the latest application.js to the mobile app' `cat $(ls -tr public/assets/application-*.js | tail -1) | \ sed -r 's#"/assets/logo-donkeywhite-.+\.png"#"img/logo.png"#' > \ ../mykonote-app/www/js/application.js` end desc 'Copies the application.css file to the mobile application' # This task assumes that the mobile application is checked out as # "mykonote-app" in the same directory as this project task css: :precompile do puts 'Copying the latest application.css to the mobile app' `cp $(ls -tr public/assets/application-*.css | tail -1) \ ../mykonote-app/www/css/application.css` end end desc 'Copies the application.{css,js} files to the mobile application' task copy: [:'mobile:assets:copy:js', :'mobile:assets:copy:css'] end end logo replacement for mobile version is obsolete namespace :mobile do namespace :assets do task precompile: :environment do puts 'Precompiling the rails assets' `RAILS_ENV=local_production bundle exec rake assets:clobber assets:precompile` end namespace :copy do desc 'Copies the application.js file to the mobile application' # This task assumes that the mobile application is checked out as # "mykonote-app" in the same directory as this project task js: :precompile do puts 'Copying the latest application.js to the mobile app' `cat $(ls -tr public/assets/application-*.js | tail -1) > \ ../mykonote-app/www/js/application.js` end desc 'Copies the application.css file to the mobile application' # This task assumes that the mobile application is checked out as # "mykonote-app" in the same directory as this project task css: :precompile do puts 'Copying the latest application.css to the mobile app' `cp $(ls -tr public/assets/application-*.css | tail -1) \ ../mykonote-app/www/css/application.css` end end desc 'Copies the application.{css,js} files to the mobile application' task copy: [:'mobile:assets:copy:js', :'mobile:assets:copy:css'] end end
namespace :app do namespace :report do desc "Generate an account report" task :account, [:filename] => :environment do |t, args| args.with_defaults(:filename => 'account.xls') filename = args[:filename] File.new(filename, 'w') do |file| rep = Reports::Account.new({:verbose => true}) rep.run_report(file) end end desc "Generate a detail report" task :detail, [:filename] => :environment do |t, args| args.with_defaults(:filename => 'detail.xls', :hostname => 'portal.concord.org') include ActionController::UrlWriter default_url_options[:host] = args[:hostname] filename = args[:filename] File.new(filename, 'w') do |file| rep = Reports::Detail.new({:verbose => true, :blobs_url => dataservice_blobs_url}) rep.run_report(file) end end desc "Generate an usage report" task :usage, [:filename, :hostname] => :environment do |t, args| args.with_defaults(:filename => 'usage.xls', :hostname => 'portal.concord.org') include ActionController::UrlWriter default_url_options[:host] = args[:hostname] filename = args[:filename] File.new(filename, 'w') do |file| rep = Reports::Usage.new({:verbose => true, :blobs_url => dataservice_blobs_url}) rep.run_report(file) end end desc "Generate some usage counts" task :counts => :environment do |t| Reports::Counts.new.report end desc "Regenerate all of the Report::Learner objects" task :update_report_learners, [:force] => :environment do |t, args| args.with_defaults(:force => false) learners = Portal::Learner.all puts "#{learners.size} learners to process...\n" learners.each_with_index do |l,i| print ("\n%5d: " % i) if (i % 250 == 0) rl = Report::Learner.for_learner(l) if args[:force] || (l.bundle_logger.last_non_empty_bundle_content && l.bundle_logger.last_non_empty_bundle_content.updated_at != rl.last_run) rl.update_fields end print '.' if (i % 5 == 4) end puts " done." end end end Protect against learners that are no longer associated with an offering namespace :app do namespace :report do desc "Generate an account report" task :account, [:filename] => :environment do |t, args| args.with_defaults(:filename => 'account.xls') filename = args[:filename] File.new(filename, 'w') do |file| rep = Reports::Account.new({:verbose => true}) rep.run_report(file) end end desc "Generate a detail report" task :detail, [:filename] => :environment do |t, args| args.with_defaults(:filename => 'detail.xls', :hostname => 'portal.concord.org') include ActionController::UrlWriter default_url_options[:host] = args[:hostname] filename = args[:filename] File.new(filename, 'w') do |file| rep = Reports::Detail.new({:verbose => true, :blobs_url => dataservice_blobs_url}) rep.run_report(file) end end desc "Generate an usage report" task :usage, [:filename, :hostname] => :environment do |t, args| args.with_defaults(:filename => 'usage.xls', :hostname => 'portal.concord.org') include ActionController::UrlWriter default_url_options[:host] = args[:hostname] filename = args[:filename] File.new(filename, 'w') do |file| rep = Reports::Usage.new({:verbose => true, :blobs_url => dataservice_blobs_url}) rep.run_report(file) end end desc "Generate some usage counts" task :counts => :environment do |t| Reports::Counts.new.report end desc "Regenerate all of the Report::Learner objects" task :update_report_learners, [:force] => :environment do |t, args| args.with_defaults(:force => false) learners = Portal::Learner.all puts "#{learners.size} learners to process...\n" learners.each_with_index do |l,i| print ("\n%5d: " % i) if (i % 250 == 0) if l.offering rl = Report::Learner.for_learner(l) if args[:force] || (l.bundle_logger.last_non_empty_bundle_content && l.bundle_logger.last_non_empty_bundle_content.updated_at != rl.last_run) rl.update_fields end end print '.' if (i % 5 == 4) end puts " done." end end end
require 'resque/tasks' require 'resque_scheduler/tasks' require 'resque-retry' require 'resque/failure/redis' require 'resque/failure/airbrake' require 'resque/pool/tasks' Resque::Failure::MultipleWithRetrySuppression.classes = [Resque::Failure::Redis, Resque::Failure::Airbrake] Resque::Failure.backend = Resque::Failure::MultipleWithRetrySuppression # Monkeypatch to fix reconnection issues. See https://github.com/resque/resque/pull/1193 module Resque class Worker alias_method :orig_startup, :startup def startup reconnect orig_startup end alias_method :orig_unregister_worker, :unregister_worker def unregister_worker exception = nil log "#{exception.render}" if exception orig_unregister_worker(exception) end end end def reset_log log_name logfile = File.open(File.join(Rails.root, 'log', log_name), 'a') logfile.sync = true Resque.logger = ActiveSupport::Logger.new(logfile) Resque.logger.level = Logger::INFO Resque.logger.formatter = Resque::VeryVerboseFormatter.new end reset_log 'resque_base.log' Resque.logger.info 'base logger initiated' task 'resque:setup' => :environment do Resque.logger.info 'setup initiated' Resque.before_first_fork = lambda {|args| # for the parent queue_name = args.try(:queue) reset_log(queue_name ? "resque_#{queue_name}_parent.log" : 'resque_worker_parent.log') } Resque.after_fork = lambda {|args| # for the child queue_name = args.try(:queue) reset_log(queue_name ? "resque_#{queue_name}.log" : 'resque_worker.log') ActiveRecord::Base.establish_connection } # Resque::Scheduler.dynamic = true Resque::Scheduler.configure do |c| reset_log 'resque_scheduler.log' c.mute = false end Resque.schedule = YAML.load_file(File.join(Rails.root, 'config', 'resque_schedule.yml')) end # Example usage: # Resque.enqueue_in(5.days, SendFollowUpEmail, :user_id => current_user.id) # or remove the job later: # # with exactly the same parameters # Resque.remove_delayed(SendFollowUpEmail, :user_id => current_user.id) # # or partial matching # Resque.remove_delayed_selection { |args| args[0]['user_id'] == current_user.id } task 'resque:pool:setup' do # close any sockets or files in pool manager ActiveRecord::Base.connection.disconnect! # and re-open them in the resque worker parent Resque::Pool.after_prefork do |_job| reset_log 'resque_pool.log' ActiveRecord::Base.establish_connection Resque.redis.client.reconnect end end relax to Proc.new for Resque hooks require 'resque/tasks' require 'resque_scheduler/tasks' require 'resque-retry' require 'resque/failure/redis' require 'resque/failure/airbrake' require 'resque/pool/tasks' Resque::Failure::MultipleWithRetrySuppression.classes = [Resque::Failure::Redis, Resque::Failure::Airbrake] Resque::Failure.backend = Resque::Failure::MultipleWithRetrySuppression # Monkeypatch to fix reconnection issues. See https://github.com/resque/resque/pull/1193 module Resque class Worker alias_method :orig_startup, :startup def startup reconnect orig_startup end alias_method :orig_unregister_worker, :unregister_worker def unregister_worker exception = nil log "#{exception.render}" if exception orig_unregister_worker(exception) end end end def reset_log log_name logfile = File.open(File.join(Rails.root, 'log', log_name), 'a') logfile.sync = true Resque.logger = ActiveSupport::Logger.new(logfile) Resque.logger.level = Logger::INFO Resque.logger.formatter = Resque::VeryVerboseFormatter.new end reset_log 'resque_base.log' Resque.logger.info 'base logger initiated' task 'resque:setup' => :environment do Resque.logger.info 'setup initiated' # Proc.new instead of lambda because args might not be passed # (and lambda does strict argument checking) Resque.before_first_fork = Proc.new {|args| # for the parent queue_name = args.try(:queue) reset_log(queue_name ? "resque_#{queue_name}_parent.log" : 'resque_worker_parent.log') } Resque.after_fork = Proc.new {|args| # for the child queue_name = args.try(:queue) reset_log(queue_name ? "resque_#{queue_name}.log" : 'resque_worker.log') ActiveRecord::Base.establish_connection } # Resque::Scheduler.dynamic = true Resque::Scheduler.configure do |c| reset_log 'resque_scheduler.log' c.mute = false end Resque.schedule = YAML.load_file(File.join(Rails.root, 'config', 'resque_schedule.yml')) end # Example usage: # Resque.enqueue_in(5.days, SendFollowUpEmail, :user_id => current_user.id) # or remove the job later: # # with exactly the same parameters # Resque.remove_delayed(SendFollowUpEmail, :user_id => current_user.id) # # or partial matching # Resque.remove_delayed_selection { |args| args[0]['user_id'] == current_user.id } task 'resque:pool:setup' do # close any sockets or files in pool manager ActiveRecord::Base.connection.disconnect! # and re-open them in the resque worker parent Resque::Pool.after_prefork do |_job| reset_log 'resque_pool.log' ActiveRecord::Base.establish_connection Resque.redis.client.reconnect end end
namespace :d_script do task :runner, :name, :script, :output_file do |t, args| name = args[:name] script = args[:script] output_file = args[:output_file] puts "d_script:runner started with name=#{name} script=#{script} output_file=#{output_file}" load_script = lambda { load script } load_script.call puts "loaded #{script}" pub_redis = Redis.new(REDIS_SETTINGS) sub_redis = Redis.new(REDIS_SETTINGS) output = File.open(output_file, 'w') if output_file runner_ch = name + '-runner-' + pub_redis.incr(name).to_s master_ch = name + "-master" ready_msg = {msg: "ready", name: runner_ch}.to_json pub_redis.publish(master_ch, ready_msg) handle_msg = lambda do |data| begin puts "running #{script} with #{data}" if output CurrentDScript.run(data["start_id"], data["end_id"], output) else CurrentDScript.run(data["start_id"], data["end_id"]) end rescue Exception => e puts "error running #{data}" puts e.inspect until (eval(gets.chomp)) ; end handle_msg(data) end end sub_redis.subscribe(runner_ch) do |on| on.subscribe do |ch, subscriptions| puts "subscribed to ##{ch} (#{subscriptions} subscriptions)" end on.unsubscribe do |ch, subscriptions| puts "unsubscribed to ##{ch} (#{subscriptions} subscriptions)" end on.message do |ch, msg| if msg == "done" sub_redis.unsubscribe(runner_ch) else handle_msg.call(JSON.parse(msg)) pub_redis.publish(master_ch, ready_msg) end end end puts "done" end end pring message namespace :d_script do task :runner, :name, :script, :output_file do |t, args| name = args[:name] script = args[:script] output_file = args[:output_file] puts "d_script:runner started with name=#{name} script=#{script} output_file=#{output_file}" load_script = lambda { load script } load_script.call puts "loaded #{script}" pub_redis = Redis.new(REDIS_SETTINGS) sub_redis = Redis.new(REDIS_SETTINGS) output = File.open(output_file, 'w') if output_file runner_ch = name + '-runner-' + pub_redis.incr(name).to_s master_ch = name + "-master" ready_msg = {msg: "ready", name: runner_ch}.to_json pub_redis.publish(master_ch, ready_msg) handle_msg = lambda do |data| begin puts "running #{script} with #{data}" if output CurrentDScript.run(data["start_id"], data["end_id"], output) else CurrentDScript.run(data["start_id"], data["end_id"]) end rescue Exception => e puts "error running #{data}" puts e.inspect until (eval(gets.chomp)) ; end handle_msg(data) end end sub_redis.subscribe(runner_ch) do |on| on.subscribe do |ch, subscriptions| puts "subscribed to ##{ch} (#{subscriptions} subscriptions)" end on.unsubscribe do |ch, subscriptions| puts "unsubscribed to ##{ch} (#{subscriptions} subscriptions)" end on.message do |ch, msg| puts "received #{msg}" if msg == "done" sub_redis.unsubscribe(runner_ch) else handle_msg.call(JSON.parse(msg)) pub_redis.publish(master_ch, ready_msg) end end end puts "done" end end
namespace :states do desc "Migrate states to state machine and publishings to edition actions" task :migrate => :environment do @state_migrations = { 'assigned' => 'lined_up', 'created' => 'lined_up', 'new_version' => 'draft', 'work_started' => 'draft', 'review_requested' => 'in_review', 'reviewed' => 'amends_needed', 'request_amendments' => 'amends_needed', 'okayed' => 'ready', 'approve_review' => 'ready', 'fact_check_requested' => 'fact_check', 'fact_check_received' => 'fact_check_received', 'published' => 'published', } Publication.all.each do |p| p.editions.each do |e| last_action = e.actions.where(:request_type.ne => 'note').last.request_type state = @state_migrations[last_action] if state and state.nil? puts "Error: no match for last action \"#{last_action}\"" elsif e.update_attribute(:state, state) puts "Updated \"#{p.name}\" (v#{e.version_number}) from action \"#{last_action}\" to state \"#{state}\"" else puts "Could not update \"#{p.name}\"" end end p.publishings.each do |publishing| puts "Finding version #{publishing.version_number}..." edition = p.editions.where(version_number: publishing.version_number).first puts "Found edition #{edition.id}. Edition has #{edition.actions.count} actions." action = edition.actions.where(request_type: 'published').first puts action.inspect if action and action.update_attributes(notes: publishing.change_notes) puts "Updated notes with \"#{publishing.change_notes}\"" else puts "Could not update notes." end end end end end Updated migration script namespace :states do desc "Migrate states to state machine and publishings to edition actions" task :migrate => :environment do @state_migrations = { 'assigned' => 'lined_up', 'assign' => 'lined_up', 'created' => 'lined_up', 'new_version' => 'draft', 'work_started' => 'draft', 'start_work' => 'draft', 'review_requested' => 'in_review', 'reviewed' => 'amends_needed', 'request_amendments' => 'amends_needed', 'okayed' => 'ready', 'approve_review' => 'ready', 'fact_check_requested' => 'fact_check', 'fact_check_received' => 'fact_check_received', 'receive_fact_check' => 'fact_check_received', 'published' => 'published', 'publish' => 'published', } Publication.all.each do |p| p.editions.each do |e| last_action = e.actions.where(:request_type.ne => 'note').last.request_type rescue '' unless e.state.nil? puts "State \"#{e.state}\" already present for \"#{p.name}\".".colorize(:cyan) next end state = @state_migrations[last_action] if !state or state.nil? puts "Error: no match for last action \"#{last_action}\"".colorize(:red) elsif e.update_attribute(:state, state) puts "Updated \"#{p.name}\" (v#{e.version_number}) from action \"#{last_action}\" to state \"#{state}\"".colorize(:green) else puts "Could not update \"#{p.name}\", existing state \"#{state}\"".colorize(:red) end end p.publishings.each do |publishing| puts "Finding version #{publishing.version_number}..." edition = p.editions.where(version_number: publishing.version_number).first action = edition.actions.where(request_type: 'published').first action_type = action.request_type rescue nil unless action_type.nil? puts "Found edition #{edition.id}. Edition has #{edition.actions.count} actions. Published action found: \"#{action_type}\"" if action and action.update_attributes(notes: publishing.change_notes) puts "Migrated publish notes with \"#{publishing.change_notes}\"".colorize(:green) else puts "Could not update notes.".colorize(:red) end else puts "No published action found." end end end end end
require 'optparse' module Commands class Base attr_accessor :input, :output, :options def initialize(input=STDIN, output=STDOUT, *args) @input = input @output = output @options = {} parse_gitconfig parse_argv(*args) end def put(string, newline=true) @output.print(newline ? string + "\n" : string) unless options[:quiet] end def sys(cmd) put cmd if options[:verbose] system cmd end def get(cmd) put cmd if options[:verbose] `#{cmd}` end def run! unless options[:api_token] && options[:project_id] put "Pivotal Tracker API Token and Project ID are required" return 1 end end protected def project @project ||= api.projects.find(:id => options[:project_id]) end def api @api ||= Pivotal::Api.new(:api_token => options[:api_token]) end def integration_branch options[:integration_branch] || "master" end private def parse_gitconfig token = get("git config --get pivotal.api-token").strip id = get("git config --get pivotal.project-id").strip name = get("git config --get pivotal.full-name").strip integration_branch = get("git config --get pivotal.integration-branch").strip only_mine = get("git config --get pivotal.only-mine").strip options[:api_token] = token unless token == "" options[:project_id] = id unless id == "" options[:full_name] = name unless name == "" options[:integration_branch] = integration_branch unless integration_branch == "" options[:only_mine] = only_mine unless name == "" end def parse_argv(*args) OptionParser.new do |opts| opts.banner = "Usage: git pick [options]" opts.on("-k", "--api-key=", "Pivotal Tracker API key") { |k| options[:api_token] = k } opts.on("-p", "--project-id=", "Pivotal Trakcer project id") { |p| options[:project_id] = p } opts.on("-n", "--full-name=", "Pivotal Trakcer full name") { |n| options[:full_name] = n } opts.on("-b", "--integration-branch=", "The branch to merge finished stories back down onto") { |b| options[:integration_branch] = b } opts.on("-m", "--only-mine", "Only select Pivotal Tracker stories assigned to you") { |m| options[:only_mine] = m } opts.on("-q", "--quiet", "Quiet, no-interaction mode") { |q| options[:quiet] = q } opts.on("-v", "--[no-]verbose", "Run verbosely") { |v| options[:verbose] = v } opts.on_tail("-h", "--help", "This usage guide") { put opts; exit 0 } end.parse!(args) end end end fixing help message require 'optparse' module Commands class Base attr_accessor :input, :output, :options def initialize(input=STDIN, output=STDOUT, *args) @input = input @output = output @options = {} parse_gitconfig parse_argv(*args) end def put(string, newline=true) @output.print(newline ? string + "\n" : string) unless options[:quiet] end def sys(cmd) put cmd if options[:verbose] system cmd end def get(cmd) put cmd if options[:verbose] `#{cmd}` end def run! unless options[:api_token] && options[:project_id] put "Pivotal Tracker API Token and Project ID are required" return 1 end end protected def project @project ||= api.projects.find(:id => options[:project_id]) end def api @api ||= Pivotal::Api.new(:api_token => options[:api_token]) end def integration_branch options[:integration_branch] || "master" end private def parse_gitconfig token = get("git config --get pivotal.api-token").strip id = get("git config --get pivotal.project-id").strip name = get("git config --get pivotal.full-name").strip integration_branch = get("git config --get pivotal.integration-branch").strip only_mine = get("git config --get pivotal.only-mine").strip options[:api_token] = token unless token == "" options[:project_id] = id unless id == "" options[:full_name] = name unless name == "" options[:integration_branch] = integration_branch unless integration_branch == "" options[:only_mine] = only_mine unless name == "" end def parse_argv(*args) OptionParser.new do |opts| opts.banner = "Usage: git pick [options]" opts.on("-k", "--api-key=", "Pivotal Tracker API key") { |k| options[:api_token] = k } opts.on("-p", "--project-id=", "Pivotal Trakcer project id") { |p| options[:project_id] = p } opts.on("-n", "--full-name=", "Pivotal Trakcer full name") { |n| options[:full_name] = n } opts.on("-b", "--integration-branch=", "The branch to merge finished stories back down onto") { |b| options[:integration_branch] = b } opts.on("-m", "--only-mine", "Only select Pivotal Tracker stories assigned to you") { |m| options[:only_mine] = m } opts.on("-q", "--quiet", "Quiet, no-interaction mode") { |q| options[:quiet] = q } opts.on("-v", "--[no-]verbose", "Run verbosely") { |v| options[:verbose] = v } opts.on_tail("-h", "--help", "This usage guide") { put opts.to_s; exit 0 } end.parse!(args) end end end
# coding: utf-8 namespace :import do # Imports rinks straight-forwardly from spreadsheet. desc 'Add rinks from Google Spreadsheets' task :google => :environment do require 'csv' require 'open-uri' CSV.parse(open('https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AtzgYYy0ZABtdEgwenRMR2MySmU5NFBDVk5wc1RQVEE&single=true&gid=0&output=csv').read, headers: true) do |row| arrondissement = Arrondissement.find_or_initialize_by_nom_arr row['nom_arr'] arrondissement.source = 'docs.google.com' arrondissement.save! row.delete('nom_arr') row.delete('extra') row.delete('source_url') patinoire = Patinoire.find_or_initialize_by_parc_and_genre_and_disambiguation_and_arrondissement_id row['parc'], row['genre'], row['disambiguation'], arrondissement.id patinoire.attributes = row.to_hash patinoire.source = 'docs.google.com' patinoire.save! end end desc 'Add contact info from Google Spreadsheets' task :contacts => :environment do require 'csv' require 'open-uri' CSV.parse(open('https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AtzgYYy0ZABtdFMwSF94MjRxcW1yZ1JYVkdqM1Fzanc&single=true&gid=0&output=csv').read, headers: true) do |row| arrondissement = Arrondissement.find_or_initialize_by_nom_arr row['Authority'] arrondissement.attributes = { name: [row['Name'], row['Title']].compact.join(', '), email: row['Email'], tel: row['Phone'] && row['Phone'].sub(/x\d+/, '').gsub(/\D/, ''), ext: row['Phone'] && row['Phone'][/x(\d+)/, 1], } arrondissement.source ||= 'docs.google.com' arrondissement.save! end end desc 'Add rinks from Sherlock and add addresses to rinks from donnees.ville.montreal.qc.ca' task :sherlock => :environment do require 'iconv' require 'open-uri' TEL_REGEX = /\d{3}.?\d{3}.?\d{4}/ GENRE_REGEX = /C|PP|PPL|PSE|anneau de glace|étang avec musique|rond de glace|patinoire réfrigérée du Canadien de Montréal/ # List of boroughs represented on donnees.ville.montreal.qc.ca ARRONDISSEMENTS_FROM_XML = Arrondissement.where(source: 'donnees.ville.montreal.qc.ca').all.map(&:nom_arr) def update_patinoires(arrondissement, attributes, text) # Find the rink to update. matches = Patinoire.where(attributes.slice(:parc, :genre, :disambiguation).merge(arrondissement_id: arrondissement.id)).all # If no rink found, switch PP for PPL. if matches.empty? && ARRONDISSEMENTS_FROM_XML.include?(arrondissement.nom_arr) matches = Patinoire.where(attributes.slice(:parc, :disambiguation).merge(genre: attributes[:genre] == 'PP' ? 'PPL' : 'PP', arrondissement_id: arrondissement.id)).all end # If single match found, just update address. if matches.size > 1 puts %("#{text}" matches many rinks) elsif attributes[:parc] == 'Sir-Wilfrid-Laurier' # @note Sherlock uses nord, sud, but XML uses no 1, no 2, no 3. Do nothing. elsif matches.size == 1 matches.first.update_attributes attributes.slice(:adresse, :tel, :ext).select{|k,v| v.present?} # Special case. if text[/2 PSE/] Patinoire.where(attributes.slice(:parc, :genre).merge(arrondissement_id: arrondissement.id, disambiguation: 'no 2')).first.update_attributes attributes.slice(:adresse, :tel, :ext).select{|k,v| v.present?} end elsif matches.empty? # donnees.ville.montreal.qc.ca should generally have all a borough's rinks. if ARRONDISSEMENTS_FROM_XML.include?(arrondissement.nom_arr) puts %("#{text}" matches no rink. Creating!) end arrondissement.patinoires.create! attributes.slice(:genre, :disambiguation, :parc, :adresse, :tel, :ext).merge(source: 'ville.montreal.qc.ca') end end nom_arr = nil tel = nil ext = nil flip = 1 # As the source data is poorly formatted, go line by line with regex. open('http://www11.ville.montreal.qc.ca/sherlock2/servlet/template/sherlock%2CAfficherDocumentInternet.vm/nodocument/154').each do |line| line = Iconv.conv('UTF-8', 'ISO-8859-1', line).gsub(/[[:space:]]/, ' ').decode_html_entities.chomp text = ActionController::Base.helpers.strip_tags(line) # If it's a borough header: if match = line[%r{<strong>([^<]+)</strong>.+\d+ patinoires}, 1] nom_arr = match.gsub("\u0096", '—') # fix dashes tel = line[TEL_REGEX] ext = line[/poste (\d+)/, 1] else attributes = {} # If it's a rink: if genre = line[/[^>]\b(#{GENRE_REGEX})\b/, 1] attributes = { genre: genre, tel: text[TEL_REGEX] || tel, ext: ext, parc: text[/\A([^(,*]+)/, 1].andand.strip, adresse: text[/,(?: \()?((?:[^()](?! 514))+)/, 1].andand.strip, patinoire: text[/\bet \(?(#{GENRE_REGEX})\)/, 1].andand.strip, disambiguation: text[/\((nord|sud|petite|grande)\)/, 1].andand.strip, extra: text.scan(/\((1 M|LA|abri|cabane|chalet|chalet fermé|chalet pas toujours ouvert|pas de chalet|roulotte|toilettes)\)/).flatten.map(&:strip), } # If it's a rink, with no rink type specified: elsif line[/\A(Parc <strong>|<strong>Bassin\b)/] attributes = { parc: text[/\A([^(,*]+)/, 1].andand.strip, adresse: text[/,(?: \()?((?:[^()](?! 514))+)/, 1].andand.strip, extra: [], } end unless attributes.empty? raw = Marshal.load(Marshal.dump(attributes)) # deep copy # Append attributes. if text['*'] attributes[:disambiguation] = 'réfrigérée' end if attributes[:genre] == 'étang avec musique' attributes[:extra] << 'musique' end # From joseeboudreau@ville.montreal.qc.ca if %w(Gohier Hartenstein).include? attributes[:parc] attributes[:extra] << 'glissade' end if text[/réfrigérée/] attributes[:description] = 'Patinoire réfrigérée' attributes[:disambiguation] = 'réfrigérée' end # Clean attributes. attributes[:parc].slice!(/\A(Parc|Patinoire) /) if attributes[:parc][Patinoire::PREPOSITIONS] attributes[:parc][Patinoire::PREPOSITIONS] = attributes[:parc][Patinoire::PREPOSITIONS].downcase end if attributes[:tel] attributes[:tel].delete!('^0-9') end # Map attributes. if attributes[:patinoire] == 'rond de glace' attributes[:patinoire] = 'PPL' end attributes[:extra].map! do |v| {'1 M' => 'musique', 'LA' => 'location et aiguisage'}[v] || v end attributes[:genre] = { 'anneau de glace' => 'PP', # Daniel-Johnson 'étang avec musique' => 'PP', # Jarry 'rond de glace' => 'PPL', 'patinoire réfrigérée du Canadien de Montréal' => 'PSE', }[attributes[:genre]] || attributes[:genre] attributes[:parc] = { 'Bleu Blanc Bouge Le Carignan' => 'Le Carignan', 'Bleu Blanc Bouge de Saint-Michel' => 'François-Perrault', 'Bleu Blanc Bouge' => 'Willibrord', # must be after above "de l'école Dalpé-Viau" => 'école Dalbé-Viau', 'de Kent' => 'Kent', 'Lasalle' => 'LaSalle', "Terrain de piste et pelouse attenant à l'aréna Martin-Brodeur" => 'Saint-Léonard', }.reduce(attributes[:parc]) do |string,(from,to)| string.sub(from, to) end # Special case. if text[/2 PSE/] attributes[:disambiguation] = 'no 1' end # There are identical lines in Sherlock. if (attributes[:parc] == 'Eugène-Dostie' && attributes[:genre] == 'PSE') || (attributes[:parc] == 'Alexander' && attributes[:genre] == 'PPL') || (attributes[:parc] == 'À-Ma-Baie' && attributes[:genre] == 'PPL') attributes[:disambiguation] = "no #{flip}" flip = flip == 1 ? 2 : 1 end # Sherlock has useless address. if attributes[:adresse] == 'PAT' attributes[:adresse] = nil end # Sherlock has the wrong rink type. attributes[:genre] = case attributes[:parc] when 'Maurice-Cullen' 'PPL' when 'Champdoré' 'PSE' when 'Chamberland' 'PSE' # from joseeboudreau@ville.montreal.qc.ca when 'Kent' if attributes[:disambiguation].nil? 'PPL' else attributes[:genre] end when 'Van Horne' 'PP' else attributes[:genre] end # Fill in missing genre. attributes[:genre] ||= case attributes[:parc] when 'Pilon', 'Saint-Léonard', 'Bassin Bonsecours' 'PPL' end # Create boroughs and rinks. arrondissement = Arrondissement.find_or_initialize_by_nom_arr nom_arr arrondissement.source ||= 'ville.montreal.qc.ca' arrondissement.save! update_patinoires arrondissement, attributes, text if attributes[:patinoire] update_patinoires arrondissement, attributes.merge(genre: attributes[:patinoire]), text end # Check if any text has been omitted from extraction. rest = raw.reduce(text.dup) do |s,(_,v)| if Array === v v.each do |x| s.sub!(x, '') end elsif v s.sub!(v, '') end s end.sub(%r{\bet\b|\((demi-glace|anciennement Marc-Aurèle-Fortin|Habitations Jeanne-Mance|lac aux Castors|Paul-Émile-Léger|rue D'Iberville/rue de Rouen|St-Anthony)\)}, '').gsub(/\p{Punct}/, '').strip puts %(didn't extract "#{rest}" from "#{text}") unless rest.empty? end end end end end fix import for outremont # coding: utf-8 namespace :import do # Imports rinks straight-forwardly from spreadsheet. desc 'Add rinks from Google Spreadsheets' task :google => :environment do require 'csv' require 'open-uri' CSV.parse(open('https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AtzgYYy0ZABtdEgwenRMR2MySmU5NFBDVk5wc1RQVEE&single=true&gid=0&output=csv').read, headers: true) do |row| arrondissement = Arrondissement.find_or_initialize_by_nom_arr row['nom_arr'] arrondissement.source = 'docs.google.com' arrondissement.save! row.delete('nom_arr') row.delete('extra') row.delete('source_url') patinoire = Patinoire.find_or_initialize_by_parc_and_genre_and_disambiguation_and_arrondissement_id row['parc'], row['genre'], row['disambiguation'], arrondissement.id patinoire.attributes = row.to_hash patinoire.source = 'docs.google.com' patinoire.save! end end desc 'Add contact info from Google Spreadsheets' task :contacts => :environment do require 'csv' require 'open-uri' CSV.parse(open('https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AtzgYYy0ZABtdFMwSF94MjRxcW1yZ1JYVkdqM1Fzanc&single=true&gid=0&output=csv').read, headers: true) do |row| arrondissement = Arrondissement.find_or_initialize_by_nom_arr row['Authority'] arrondissement.attributes = { name: [row['Name'], row['Title']].compact.join(', '), email: row['Email'], tel: row['Phone'] && row['Phone'].sub(/x\d+/, '').gsub(/\D/, ''), ext: row['Phone'] && row['Phone'][/x(\d+)/, 1], } arrondissement.source ||= 'docs.google.com' arrondissement.save! end end desc 'Add rinks from Sherlock and add addresses to rinks from donnees.ville.montreal.qc.ca' task :sherlock => :environment do require 'iconv' require 'open-uri' TEL_REGEX = /\d{3}.?\d{3}.?\d{4}/ GENRE_REGEX = /C|PP|PPL|PSE|anneau de glace|étang avec musique|rond de glace|patinoire réfrigérée du Canadien de Montréal/ # List of boroughs represented on donnees.ville.montreal.qc.ca ARRONDISSEMENTS_FROM_XML = Arrondissement.where(source: 'donnees.ville.montreal.qc.ca').all.map(&:nom_arr) def update_patinoires(arrondissement, attributes, text) # Find the rink to update. matches = Patinoire.where(attributes.slice(:parc, :genre, :disambiguation).merge(arrondissement_id: arrondissement.id)).all # If no rink found, switch PP for PPL. if matches.empty? && ARRONDISSEMENTS_FROM_XML.include?(arrondissement.nom_arr) matches = Patinoire.where(attributes.slice(:parc, :disambiguation).merge(genre: attributes[:genre] == 'PP' ? 'PPL' : 'PP', arrondissement_id: arrondissement.id)).all end # If single match found, just update address. if matches.size > 1 puts %("#{text}" matches many rinks) elsif attributes[:parc] == 'Sir-Wilfrid-Laurier' # @note Sherlock uses nord, sud, but XML uses no 1, no 2, no 3. Do nothing. elsif matches.size == 1 matches.first.update_attributes attributes.slice(:adresse, :tel, :ext).select{|k,v| v.present?} # Special case. if text[/2 PSE/] Patinoire.where(attributes.slice(:parc, :genre).merge(arrondissement_id: arrondissement.id, disambiguation: 'no 2')).first.update_attributes attributes.slice(:adresse, :tel, :ext).select{|k,v| v.present?} end elsif matches.empty? # donnees.ville.montreal.qc.ca should generally have all a borough's rinks. if ARRONDISSEMENTS_FROM_XML.include?(arrondissement.nom_arr) puts %("#{text}" matches no rink. Creating!) end arrondissement.patinoires.create! attributes.slice(:genre, :disambiguation, :parc, :adresse, :tel, :ext).merge(source: 'ville.montreal.qc.ca') end end nom_arr = nil tel = nil ext = nil flip = 1 # As the source data is poorly formatted, go line by line with regex. open('http://www11.ville.montreal.qc.ca/sherlock2/servlet/template/sherlock%2CAfficherDocumentInternet.vm/nodocument/154').each do |line| line = Iconv.conv('UTF-8', 'ISO-8859-1', line).gsub(/[[:space:]]/, ' ').decode_html_entities.chomp text = ActionController::Base.helpers.strip_tags(line) # If it's a borough header: if match = line[%r{<strong>([^<]+)</strong>.+\d+ patinoires}, 1] nom_arr = match.gsub("\u0096", '—') # fix dashes tel = line[TEL_REGEX] ext = line[/poste (\d+)/, 1] else attributes = {} # If it's a rink: if genre = line[/[^>]\b(#{GENRE_REGEX})\b/, 1] attributes = { genre: genre, tel: text[TEL_REGEX] || tel, ext: ext, parc: text[/\A([^(,*]+)/, 1].andand.strip, adresse: text[/,(?: \()?((?:[^()](?! 514))+)/, 1].andand.strip, patinoire: text[/\bet \(?(#{GENRE_REGEX})\)/, 1].andand.strip, disambiguation: text[/\((nord|sud|petite|grande)\)/, 1].andand.strip, extra: text.scan(/\((1 M|LA|abri|cabane|chalet|chalet fermé|chalet pas toujours ouvert|pas de chalet|roulotte|toilettes)\)/).flatten.map(&:strip), } # If it's a rink, with no rink type specified: elsif line[/\A(Parc <strong>|<strong>Bassin\b)/] attributes = { parc: text[/\A([^(,*]+)/, 1].andand.strip, adresse: text[/,(?: \()?((?:[^()](?! 514))+)/, 1].andand.strip, extra: [], } end unless attributes.empty? raw = Marshal.load(Marshal.dump(attributes)) # deep copy # Append attributes. if text['*'] attributes[:disambiguation] = 'réfrigérée' end if attributes[:genre] == 'étang avec musique' attributes[:extra] << 'musique' end # From joseeboudreau@ville.montreal.qc.ca if %w(Gohier Hartenstein).include? attributes[:parc] attributes[:extra] << 'glissade' end if text[/réfrigérée/] attributes[:description] = 'Patinoire réfrigérée' attributes[:disambiguation] = 'réfrigérée' end # Clean attributes. attributes[:parc].slice!(/\A(Parc|Patinoire) /) if attributes[:parc][Patinoire::PREPOSITIONS] attributes[:parc][Patinoire::PREPOSITIONS] = attributes[:parc][Patinoire::PREPOSITIONS].downcase end if attributes[:tel] attributes[:tel].delete!('^0-9') end # Map attributes. if attributes[:patinoire] == 'rond de glace' attributes[:patinoire] = 'PPL' end attributes[:extra].map! do |v| {'1 M' => 'musique', 'LA' => 'location et aiguisage'}[v] || v end attributes[:genre] = { 'anneau de glace' => 'PP', # Daniel-Johnson 'étang avec musique' => 'PP', # Jarry 'rond de glace' => 'PPL', 'patinoire réfrigérée du Canadien de Montréal' => 'PSE', }[attributes[:genre]] || attributes[:genre] attributes[:parc] = { 'Bleu Blanc Bouge Le Carignan' => 'Le Carignan', 'Bleu Blanc Bouge de Saint-Michel' => 'François-Perrault', 'Bleu Blanc Bouge' => 'Willibrord', # must be after above "de l'école Dalpé-Viau" => 'école Dalbé-Viau', 'de Kent' => 'Kent', 'Lasalle' => 'LaSalle', 'Pierre-E.-Trudeau' => 'Pierre-E-Trudeau', "Terrain de piste et pelouse attenant à l'aréna Martin-Brodeur" => 'Saint-Léonard', }[attributes[:parc]] || attributes[:parc] # Special case. if text[/2 PSE/] attributes[:disambiguation] = 'no 1' end # There are identical lines in Sherlock. if (attributes[:parc] == 'Eugène-Dostie' && attributes[:genre] == 'PSE') || (attributes[:parc] == 'Alexander' && attributes[:genre] == 'PPL') || (attributes[:parc] == 'À-Ma-Baie' && attributes[:genre] == 'PPL') attributes[:disambiguation] = "no #{flip}" flip = flip == 1 ? 2 : 1 end # Sherlock has useless address. if attributes[:adresse] == 'PAT' attributes[:adresse] = nil end # Sherlock has the wrong rink type. attributes[:genre] = case attributes[:parc] when 'Maurice-Cullen' 'PPL' when 'Champdoré' 'PSE' when 'Chamberland' 'PSE' # from joseeboudreau@ville.montreal.qc.ca when 'Kent' if attributes[:disambiguation].nil? 'PPL' else attributes[:genre] end when 'Oakwood' 'PPL' when 'Van Horne' 'PP' else attributes[:genre] end # Fill in missing genre. if ['Pilon', 'Saint-Léonard', 'Bassin Bonsecours'].include? attributes[:parc] attributes[:genre] ||= 'PPL' end # Fix dashes. nom_arr = { 'Côte-des-Neiges–Notre-Dame-de-Grâce' => 'Côte-des-Neiges—Notre-Dame-de-Grâce', "L'Île-Bizard–Sainte-Geneviève" => "L'Île-Bizard—Sainte-Geneviève", 'Mercier–Hochelaga-Maisonneuve' => 'Mercier—Hochelaga-Maisonneuve', 'Rivière-des-Prairies–Pointe-aux-Trembles' => 'Rivière-des-Prairies—Pointe-aux-Trembles', 'Rosemont–La Petite-Patrie' => 'Rosemont—La Petite-Patrie', 'Villeray–Saint-Michel–Parc-Extension' => 'Villeray—Saint-Michel—Parc-Extension', }[nom_arr] || nom_arr # Create boroughs and rinks. arrondissement = Arrondissement.find_or_initialize_by_nom_arr nom_arr arrondissement.source ||= 'ville.montreal.qc.ca' arrondissement.save! update_patinoires arrondissement, attributes, text if attributes[:patinoire] update_patinoires arrondissement, attributes.merge(genre: attributes[:patinoire]), text end # Check if any text has been omitted from extraction. rest = raw.reduce(text.dup) do |s,(_,v)| if Array === v v.each do |x| s.sub!(x, '') end elsif v s.sub!(v, '') end s end.sub(%r{\bet\b|\((demi-glace|anciennement Marc-Aurèle-Fortin|Habitations Jeanne-Mance|lac aux Castors|Paul-Émile-Léger|rue D'Iberville/rue de Rouen|St-Anthony)\)}, '').gsub(/\p{Punct}/, '').strip puts %(didn't extract "#{rest}" from "#{text}") unless rest.empty? end end end end end
require "yaml" namespace :tracks do desc "Create a yaml file with the current tracks and subjects info" task current_info: :environment do tracks_info = {"tracks" => {}} tracks = Track.all.includes(:subjects, :aeics).order(code: :asc) tracks.each do |t| t_info = { name: t.name, short_name: t.short_name, code: t.code, aeics: t.aeics.map(&:full_name), fields: t.subjects.map(&:name) }.stringify_keys tracks_info["tracks"][t.name.parameterize] = t_info end File.open("tracks_current_info.yml", "w") do |f| f.write tracks_info.to_yaml end end desc "Import tracks and subjects from the lib/tracks.yml file" task import: :environment do tracks_info = YAML.load_file(Rails.root + "lib/tracks.yml") tracks_info["tracks"].each_pair do |k, v| track = Track.find_or_initialize_by(name: v["name"]) track.code = v["code"] track.short_name = v["short_name"] track.save! v["fields"].each do |subject| s = Subject.find_or_initialize_by(name: subject) s.track_id = track.id s.save! end end end end Update import subjects task require "yaml" namespace :tracks do desc "Create a yaml file with the current tracks and subjects info" task current_info: :environment do tracks_info = {"tracks" => {}} tracks = Track.all.includes(:subjects, :aeics).order(code: :asc) tracks.each do |t| t_info = { name: t.name, short_name: t.short_name, code: t.code, aeics: t.aeics.map(&:full_name), fields: t.subjects.map(&:name) }.stringify_keys tracks_info["tracks"][t.name.parameterize] = t_info end File.open("tracks_current_info.yml", "w") do |f| f.write tracks_info.to_yaml end end namespace :import do desc "Import subjects from the lib/tracks.yml file" task subjects: :environment do tracks_info = YAML.load_file(Rails.root + "lib/tracks.yml") tracks_info["tracks"].each_pair do |k, v| track = Track.find_by(name: v["name"].to_s.strip) if track.nil? puts "!! There is not a '#{v["name"]}' track. Please create it before importing the subjects." else track.subjects.delete_all v["fields"].each do |subject| s = Subject.find_or_initialize_by(name: subject) s.track_id = track.id s.save! end puts "- Track '#{v["name"]}': #{v['fields'].size} subjects imported" end end end end end
namespace :update do desc "Refetch all tools from coresponding APIs" task all: :environment do Tool.find_each do |tool| tool.save puts "Tool #{tool.id} updated to: #{tool.to_yaml}" end end end Explicitly update Tool metadata and recalculate reproduciblity scores in the update task. namespace :update do desc "Refetch all tools from coresponding APIs" task all: :environment do Tool.find_each do |tool| tool.get_metadata tool.check_health tool.calculate_reproducibility_score tool.save puts "Tool #{tool.id} updated to: #{tool.to_yaml}" end end end
module Tex2id VERSION = "1.3.0" end Version 1.3.1 module Tex2id VERSION = "1.3.1" end
module Topicz VERSION = "0.1.0" end New version for fixes. module Topicz VERSION = "0.1.1" end
module Trusty VERSION = "0.0.3" end Version bump module Trusty VERSION = "0.0.4" end
require "aws-sdk" require "tus/info" require "tus/checksum" require "tus/errors" require "json" require "cgi/util" Aws.eager_autoload!(services: ["S3"]) module Tus module Storage class S3 MIN_PART_SIZE = 5 * 1024 * 1024 attr_reader :client, :bucket, :prefix, :upload_options def initialize(bucket:, prefix: nil, upload_options: {}, thread_count: 10, **client_options) resource = Aws::S3::Resource.new(**client_options) @client = resource.client @bucket = resource.bucket(bucket) @prefix = prefix @upload_options = upload_options @thread_count = thread_count end def create_file(uid, info = {}) tus_info = Tus::Info.new(info) options = upload_options.dup options[:content_type] = tus_info.metadata["content_type"] if filename = tus_info.metadata["filename"] options[:content_disposition] ||= "inline" options[:content_disposition] += "; filename=\"#{CGI.escape(filename).gsub("+", " ")}\"" end multipart_upload = object(uid).initiate_multipart_upload(options) info["multipart_id"] = multipart_upload.id info["multipart_parts"] = [] multipart_upload end def concatenate(uid, part_uids, info = {}) multipart_upload = create_file(uid, info) objects = part_uids.map { |part_uid| object(part_uid) } parts = copy_parts(objects, multipart_upload) parts.each do |part| info["multipart_parts"] << { "part_number" => part[:part_number], "etag" => part[:etag] } end finalize_file(uid, info) delete(part_uids.flat_map { |part_uid| [object(part_uid), object("#{part_uid}.info")] }) # Tus server requires us to return the size of the concatenated file. object = client.head_object(bucket: bucket.name, key: object(uid).key) object.content_length rescue => error abort_multipart_upload(multipart_upload) if multipart_upload raise error end def patch_file(uid, input, info = {}) upload_id = info["multipart_id"] part_number = info["multipart_parts"].count + 1 multipart_upload = object(uid).multipart_upload(upload_id) multipart_part = multipart_upload.part(part_number) md5 = Tus::Checksum.new("md5").generate(input) response = multipart_part.upload(body: input, content_md5: md5) info["multipart_parts"] << { "part_number" => part_number, "etag" => response.etag[/"(.+)"/, 1], } rescue Aws::S3::Errors::NoSuchUpload raise Tus::NotFound end def finalize_file(uid, info = {}) upload_id = info["multipart_id"] parts = info["multipart_parts"].map do |part| { part_number: part["part_number"], etag: part["etag"] } end multipart_upload = object(uid).multipart_upload(upload_id) multipart_upload.complete(multipart_upload: {parts: parts}) info.delete("multipart_id") info.delete("multipart_parts") end def read_info(uid) response = object("#{uid}.info").get JSON.parse(response.body.string) rescue Aws::S3::Errors::NoSuchKey raise Tus::NotFound end def update_info(uid, info) object("#{uid}.info").put(body: info.to_json) end def get_file(uid, info = {}, range: nil) object = object(uid) range = "bytes=#{range.begin}-#{range.end}" if range raw_chunks = object.enum_for(:get, range: range) # Start the request to be notified if the object doesn't exist, and to # get Aws::S3::Object#content_length. first_chunk = raw_chunks.next chunks = Enumerator.new do |yielder| yielder << first_chunk loop { yielder << raw_chunks.next } end Response.new( chunks: chunks, length: object.content_length, ) rescue Aws::S3::Errors::NoSuchKey raise Tus::NotFound end def delete_file(uid, info = {}) if info["multipart_id"] multipart_upload = object(uid).multipart_upload(info["multipart_id"]) abort_multipart_upload(multipart_upload) delete [object("#{uid}.info")] else delete [object(uid), object("#{uid}.info")] end end def expire_files(expiration_date) old_objects = bucket.objects.select do |object| object.last_modified <= expiration_date end delete(old_objects) bucket.multipart_uploads.each do |multipart_upload| next unless multipart_upload.initiated <= expiration_date most_recent_part = multipart_upload.parts.sort_by(&:last_modified).last if most_recent_part.nil? || most_recent_part.last_modified <= expiration_date abort_multipart_upload(multipart_upload) end end end private def delete(objects) # S3 can delete maximum of 1000 objects in a single request objects.each_slice(1000) do |objects_batch| delete_params = {objects: objects_batch.map { |object| {key: object.key} }} bucket.delete_objects(delete: delete_params) end end # In order to ensure the multipart upload was successfully aborted, # we need to check whether all parts have been deleted, and retry # the abort if the list is nonempty. def abort_multipart_upload(multipart_upload) loop do multipart_upload.abort break unless multipart_upload.parts.any? end rescue Aws::S3::Errors::NoSuchUpload # multipart upload was successfully aborted or doesn't exist end def copy_parts(objects, multipart_upload) parts = compute_parts(objects, multipart_upload) queue = parts.inject(Queue.new) { |queue, part| queue << part } threads = @thread_count.times.map { copy_part_thread(queue) } threads.flat_map(&:value).sort_by { |part| part[:part_number] } end def compute_parts(objects, multipart_upload) objects.map.with_index do |object, idx| { bucket: multipart_upload.bucket_name, key: multipart_upload.object_key, upload_id: multipart_upload.id, copy_source: [object.bucket_name, object.key].join("/"), part_number: idx + 1, } end end def copy_part_thread(queue) Thread.new do Thread.current.abort_on_exception = true begin results = [] loop do part = queue.deq(true) rescue break results << copy_part(part) end results rescue => error queue.clear raise error end end end def copy_part(part) response = client.upload_part_copy(part) { part_number: part[:part_number], etag: response.copy_part_result.etag } end def object(key) bucket.object([*prefix, key].join("/")) end class Response def initialize(chunks:, length:) @chunks = chunks @length = length end def length @length end def each(&block) @chunks.each(&block) end def close # aws-sdk doesn't provide an API to terminate the HTTP connection end end end end end Don't try to fix the etag with double quotes Multipart upload completes just fine with those double quotes, so no need to fix them. require "aws-sdk" require "tus/info" require "tus/checksum" require "tus/errors" require "json" require "cgi/util" Aws.eager_autoload!(services: ["S3"]) module Tus module Storage class S3 MIN_PART_SIZE = 5 * 1024 * 1024 attr_reader :client, :bucket, :prefix, :upload_options def initialize(bucket:, prefix: nil, upload_options: {}, thread_count: 10, **client_options) resource = Aws::S3::Resource.new(**client_options) @client = resource.client @bucket = resource.bucket(bucket) @prefix = prefix @upload_options = upload_options @thread_count = thread_count end def create_file(uid, info = {}) tus_info = Tus::Info.new(info) options = upload_options.dup options[:content_type] = tus_info.metadata["content_type"] if filename = tus_info.metadata["filename"] options[:content_disposition] ||= "inline" options[:content_disposition] += "; filename=\"#{CGI.escape(filename).gsub("+", " ")}\"" end multipart_upload = object(uid).initiate_multipart_upload(options) info["multipart_id"] = multipart_upload.id info["multipart_parts"] = [] multipart_upload end def concatenate(uid, part_uids, info = {}) multipart_upload = create_file(uid, info) objects = part_uids.map { |part_uid| object(part_uid) } parts = copy_parts(objects, multipart_upload) parts.each do |part| info["multipart_parts"] << { "part_number" => part[:part_number], "etag" => part[:etag] } end finalize_file(uid, info) delete(part_uids.flat_map { |part_uid| [object(part_uid), object("#{part_uid}.info")] }) # Tus server requires us to return the size of the concatenated file. object = client.head_object(bucket: bucket.name, key: object(uid).key) object.content_length rescue => error abort_multipart_upload(multipart_upload) if multipart_upload raise error end def patch_file(uid, input, info = {}) upload_id = info["multipart_id"] part_number = info["multipart_parts"].count + 1 multipart_upload = object(uid).multipart_upload(upload_id) multipart_part = multipart_upload.part(part_number) md5 = Tus::Checksum.new("md5").generate(input) response = multipart_part.upload(body: input, content_md5: md5) info["multipart_parts"] << { "part_number" => part_number, "etag" => response.etag, } rescue Aws::S3::Errors::NoSuchUpload raise Tus::NotFound end def finalize_file(uid, info = {}) upload_id = info["multipart_id"] parts = info["multipart_parts"].map do |part| { part_number: part["part_number"], etag: part["etag"] } end multipart_upload = object(uid).multipart_upload(upload_id) multipart_upload.complete(multipart_upload: {parts: parts}) info.delete("multipart_id") info.delete("multipart_parts") end def read_info(uid) response = object("#{uid}.info").get JSON.parse(response.body.string) rescue Aws::S3::Errors::NoSuchKey raise Tus::NotFound end def update_info(uid, info) object("#{uid}.info").put(body: info.to_json) end def get_file(uid, info = {}, range: nil) object = object(uid) range = "bytes=#{range.begin}-#{range.end}" if range raw_chunks = object.enum_for(:get, range: range) # Start the request to be notified if the object doesn't exist, and to # get Aws::S3::Object#content_length. first_chunk = raw_chunks.next chunks = Enumerator.new do |yielder| yielder << first_chunk loop { yielder << raw_chunks.next } end Response.new( chunks: chunks, length: object.content_length, ) rescue Aws::S3::Errors::NoSuchKey raise Tus::NotFound end def delete_file(uid, info = {}) if info["multipart_id"] multipart_upload = object(uid).multipart_upload(info["multipart_id"]) abort_multipart_upload(multipart_upload) delete [object("#{uid}.info")] else delete [object(uid), object("#{uid}.info")] end end def expire_files(expiration_date) old_objects = bucket.objects.select do |object| object.last_modified <= expiration_date end delete(old_objects) bucket.multipart_uploads.each do |multipart_upload| next unless multipart_upload.initiated <= expiration_date most_recent_part = multipart_upload.parts.sort_by(&:last_modified).last if most_recent_part.nil? || most_recent_part.last_modified <= expiration_date abort_multipart_upload(multipart_upload) end end end private def delete(objects) # S3 can delete maximum of 1000 objects in a single request objects.each_slice(1000) do |objects_batch| delete_params = {objects: objects_batch.map { |object| {key: object.key} }} bucket.delete_objects(delete: delete_params) end end # In order to ensure the multipart upload was successfully aborted, # we need to check whether all parts have been deleted, and retry # the abort if the list is nonempty. def abort_multipart_upload(multipart_upload) loop do multipart_upload.abort break unless multipart_upload.parts.any? end rescue Aws::S3::Errors::NoSuchUpload # multipart upload was successfully aborted or doesn't exist end def copy_parts(objects, multipart_upload) parts = compute_parts(objects, multipart_upload) queue = parts.inject(Queue.new) { |queue, part| queue << part } threads = @thread_count.times.map { copy_part_thread(queue) } threads.flat_map(&:value).sort_by { |part| part[:part_number] } end def compute_parts(objects, multipart_upload) objects.map.with_index do |object, idx| { bucket: multipart_upload.bucket_name, key: multipart_upload.object_key, upload_id: multipart_upload.id, copy_source: [object.bucket_name, object.key].join("/"), part_number: idx + 1, } end end def copy_part_thread(queue) Thread.new do Thread.current.abort_on_exception = true begin results = [] loop do part = queue.deq(true) rescue break results << copy_part(part) end results rescue => error queue.clear raise error end end end def copy_part(part) response = client.upload_part_copy(part) { part_number: part[:part_number], etag: response.copy_part_result.etag } end def object(key) bucket.object([*prefix, key].join("/")) end class Response def initialize(chunks:, length:) @chunks = chunks @length = length end def length @length end def each(&block) @chunks.each(&block) end def close # aws-sdk doesn't provide an API to terminate the HTTP connection end end end end end
#-- ############################################################################### # # # twitter2jabber - Twitter-to-Jabber gateway. # # # # Copyright (C) 2009-2011 Jens Wille # # # # Authors: # # Jens Wille <ww@blackwinter.de> # # # # twitter2jabber is free software; you can redistribute it and/or modify it # # under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation; either version 3 of the License, or (at your # # option) any later version. # # # # twitter2jabber is distributed in the hope that it will be useful, but # # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public # # License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with twitter2jabber. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### #++ require 'time' require 'erb' require 'rubygems' require 'twitter' require 'xmpp4r-simple' require 'shorturl' require 'longurl' require 'nuggets/array/runiq' require 'twitter2jabber/version' class Twitter2Jabber MAX_LENGTH = 140 DEFAULT_PAUSE = 60 DEFAULT_FORMATS = %w[txt] DEFAULT_TEMPLATES = File.expand_path(File.join(File.dirname(__FILE__), %w[.. example templates])) JABBER_NS = 'http://jabber.org/protocol/xhtml-im' XHTML_NS = 'http://www.w3.org/1999/xhtml' def self.loop(options, recipients = [], pause = nil, last = nil, &block) new(options).loop(recipients, pause, last, &block) end def self.run(options, recipients = [], last = nil, &block) new(options).run(recipients, last, &block) end attr_reader :id, :verbose, :debug, :log, :twitter, :jabber, :filter, :formats, :templates, :_erb def initialize(options, &block) [:twitter, :jabber].each { |client| raise ArgumentError, "#{client} config missing" unless options[client].is_a?(Hash) } @id = "#{options[:twitter][:consumer_token]} -> #{options[:jabber][:user]}" @verbose = options[:verbose] @debug = options[:debug] @log = options[:log] log.sync = true logm 'HAI!' @twitter = twitter_connect(options[:twitter]) @jabber = jabber_connect(options[:jabber]) @filter = options[:filter] || block @formats = options[:formats] || DEFAULT_FORMATS @templates = Dir[ File.join(options[:template_dir] || DEFAULT_TEMPLATES, 'tweet.*') ].inject({}) { |hash, template| hash.update(File.extname(template).sub(/\A\./, '') => File.read(template)) } @_erb = Hash.new { |hash, format| template = templates[format] hash[format] = template && ERB.new(template) } end def run(recipients = [], last = nil, flag = true, &block) last = deliver_tweets(recipients, last, &block) if flag post_messages(recipients) last end def loop(recipients = [], pause = nil, last = nil, &block) pause ||= DEFAULT_PAUSE i = 1 trap(:INT) { logm 'SIGINT received, shutting down...' i = -1 } while i > 0 last = run(recipients, last, i % pause == 1, &block) sleep 1 i += 1 end logm 'KTHXBYE!' last end def deliver_tweets(recipients, last = nil, &block) get_tweets(last).each { |tweet| logt last = tweet.id # apply filters next if filter && !filter[tweet] next if block && !block[tweet] msg = format_tweet(tweet) recipients.each { |recipient| deliver(recipient, msg) } sleep 1 } last end def post_messages(recipients = []) allowed = %r{\A(?:#{recipients.map { |r| Regexp.escape(r) }.join('|')})\z}i jabber.received_messages { |msg| next unless msg.type == :chat next unless msg.from.bare.to_s =~ allowed logj msg.id handle_command(msg.body, msg.from) } end private def twitter_connect(options) auth = Twitter::OAuth.new(options[:consumer_token], options[:consumer_secret]) auth.authorize_from_access(options[:access_token], options[:access_secret]) client = Twitter::Base.new(auth) # verify credentials client.verify_credentials logt 'connected' client rescue Twitter::TwitterError => err raise "Can't connect to Twitter with ID '#{options[:consumer_token]}': #{err}" end def jabber_connect(options) client = Jabber::Simple.new(options[:user], options[:pass]) logj 'connected' client rescue Jabber::JabberError => err raise "Can't connect to Jabber with JID '#{options[:user]}': #{err}" end def get_tweets(last = nil) options = {} options[:since_id] = last if last tweets = twitter.friends_timeline(options) return [] unless tweets.is_a?(Array) tweets.sort_by { |tweet| tweet.created_at = Time.parse(tweet.created_at) } rescue Twitter::TwitterError, Twitter::Unavailable, Timeout::Error [] rescue => err warn "#{err} (#{err.class})" [] end def format_tweet(tweet) user = tweet.user msg = Jabber::Message.new.set_type(:chat) formats.each { |format| if erb = _erb[format] msg.add_element(format_element(format, erb.result(binding))) end } msg end # cf. <http://devblog.famundo.com/articles/2006/10/18/ruby-and-xmpp-jabber-part-3-adding-html-to-the-messages> def format_element(format, text) text = process_message(text) body = REXML::Element.new('body') case format when 'html' REXML::Text.new(process_html(text), false, body, true, nil, /.^/) html = REXML::Element.new('html').add_namespace(JABBER_NS) html.add(body.add_namespace(XHTML_NS)) html else REXML::Text.new(process_text(text), true, body, true, nil, /.^/) body end end def process_message(text) text.gsub(/https?:\/\/\S+/) { |match| LongURL.expand(match) rescue match } end def process_html(text) text.gsub(/(\A|\W)@(\w+)/, '\1@<a href="http://twitter.com/\2">\2</a>'). gsub(/(\A|\W)#(\w+)/, '\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>') end def process_text(text) text end def handle_command(body, from, execute = true) case body when /\A(?:he?(?:lp)?|\?)\z/i deliver(from, <<-HELP) if execute h[e[lp]]|? -- Print this help de[bug] -- Print debug mode de[bug] on|off -- Turn debug mode on/off bl[ock] @USER -- Block USER fa[v[orite]] #ID -- Add ID to favorites bm|bookmark[s] -- List bookmarks bm|bookmark #ID -- Bookmark ID bm|bookmark -#ID -- Remove ID from bookmarks rt|retweet #ID [!] [STATUS] -- Retweet ID re[ply] #ID [!] STATUS -- Reply to ID d[m]|direct[_message] @USER [!] STATUS -- Send direct message to USER le[n[gth]] STATUS -- Determine length [!] STATUS -- Update status (Note: STATUS must be under #{MAX_LENGTH} characters; force send with '!'.) HELP when /\Ade(?:bug)?(?:\s+(on|off))?\z/i if execute flag = $1.downcase if $1 case flag when 'on' @debug = true when 'off' @debug = false end deliver(from, "DEBUG = #{debug ? 'on' : 'off'}") end when /\Abl(?:ock)?\s+[@#]?(\w+)\z/i twitter.block($1) if execute && !debug when /\Afav?(?:orite)?\s+#?(\d+)\z/i twitter.favorite_create($1) if execute && !debug when /\A(?:bm|bookmarks?)\z/i deliver(from, bookmarks.map { |bm| st = twitter.status(bm) st = "@#{st.user.screen_name}: #{st.text[0, 10]}..." if st.is_a?(Hashie::Mash) "#{bm} - #{st || '???'}" }.join("\n")) if execute && !debug when /\A(?:bm|bookmark)\s+(\d+)\z/i if execute && !debug bookmarks << $1 bookmarks.runiq! end when /\A(?:bm|bookmark)\s+-(\d+)\z/i bookmarks.delete($1) if execute && !debug else command, options = nil, {} if execute && body.sub!(/\Alen?(?:gth)?\s+/i, '') if body = handle_command(body, from, false) length = body.length hint = length <= MAX_LENGTH ? 'OK' : 'TOO LONG' deliver(from, "#{length} [#{hint}]: #{body}") end return end begin if body.sub!(/\A(?:rt|retweet)\s+#?(\d+)(:?)(?:\s+|\z)/i, '') id, colon = $1, $2 tweet = twitter.status(id) raise Twitter::NotFound unless tweet.is_a?(Hashie::Mash) if body.empty? options[:id] = id command = :rt else body << " RT @#{tweet.user.screen_name}#{colon} #{tweet.text}" end elsif body.sub!(/\Are(?:ply)?\s+#?(\d+)(:?)\s+/i, '') id, colon = $1, $2 tweet = twitter.status(id) raise Twitter::NotFound unless tweet.is_a?(Hashie::Mash) body.insert(0, ' ') unless body.empty? body.insert(0, "@#{tweet.user.screen_name}#{colon}") options[:in_reply_to_status_id] = id end rescue Twitter::NotFound deliver(from, "TWEET NOT FOUND: #{id}") return end if body.sub!(/\A(?:dm?|direct(?:_message)?)\s+[@#]?(\w+):?\s+/i, '') options[:user] = $1 command = :dm end if body.sub!(/\A!(?:\s+|\z)/, '') force = true end body.gsub!(/https?:\/\/\S+/) { |match| match.length < 30 ? match : ShortURL.shorten(match) } return body unless execute if force || body.length <= MAX_LENGTH case command when :rt if debug logt "RT: #{options.inspect}", true else twitter.retweet(options[:id]) end when :dm if debug logt "DM: #{body} (#{options.inspect})", true else twitter.direct_message_create(options[:user], body) end else update(body, options) end deliver(from, "MSG SENT: #{body.inspect}, #{options.inspect}") else deliver(from, "MSG TOO LONG (> #{MAX_LENGTH}): #{body.inspect}") end end end def deliver(recipient, msg) if debug logj "#{recipient}: #{msg}", true return end jabber.deliver(recipient, msg) rescue => err warn "#{err} (#{err.class})" end def update(msg, options = {}) if debug logt "#{msg} (#{options.inspect})", true return end twitter.update(msg, options) end def log_(msg, verbose = verbose) log.puts msg if verbose end def logm(msg, verbose = verbose) log_("#{Time.now} [#{id}] #{msg}", verbose) end def logt(msg, verbose = verbose) logm("TWITTER #{msg}", verbose) end def logj(msg, verbose = verbose) logm("JABBER #{msg}", verbose) end def bookmarks @bookmarks ||= [] end end lib/twitter2jabber.rb (deliver): Retry if server disconnected. #-- ############################################################################### # # # twitter2jabber - Twitter-to-Jabber gateway. # # # # Copyright (C) 2009-2011 Jens Wille # # # # Authors: # # Jens Wille <ww@blackwinter.de> # # # # twitter2jabber is free software; you can redistribute it and/or modify it # # under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation; either version 3 of the License, or (at your # # option) any later version. # # # # twitter2jabber is distributed in the hope that it will be useful, but # # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public # # License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with twitter2jabber. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### #++ require 'time' require 'erb' require 'rubygems' require 'twitter' require 'xmpp4r-simple' require 'shorturl' require 'longurl' require 'nuggets/array/runiq' require 'twitter2jabber/version' class Twitter2Jabber MAX_LENGTH = 140 DEFAULT_PAUSE = 60 DEFAULT_FORMATS = %w[txt] DEFAULT_TEMPLATES = File.expand_path(File.join(File.dirname(__FILE__), %w[.. example templates])) JABBER_NS = 'http://jabber.org/protocol/xhtml-im' XHTML_NS = 'http://www.w3.org/1999/xhtml' def self.loop(options, recipients = [], pause = nil, last = nil, &block) new(options).loop(recipients, pause, last, &block) end def self.run(options, recipients = [], last = nil, &block) new(options).run(recipients, last, &block) end attr_reader :id, :verbose, :debug, :log, :twitter, :jabber, :filter, :formats, :templates, :_erb def initialize(options, &block) [:twitter, :jabber].each { |client| raise ArgumentError, "#{client} config missing" unless options[client].is_a?(Hash) } @id = "#{options[:twitter][:consumer_token]} -> #{options[:jabber][:user]}" @verbose = options[:verbose] @debug = options[:debug] @log = options[:log] log.sync = true logm 'HAI!' twitter_connect(options[:twitter]) jabber_connect(options[:jabber]) @filter = options[:filter] || block @formats = options[:formats] || DEFAULT_FORMATS @templates = Dir[ File.join(options[:template_dir] || DEFAULT_TEMPLATES, 'tweet.*') ].inject({}) { |hash, template| hash.update(File.extname(template).sub(/\A\./, '') => File.read(template)) } @_erb = Hash.new { |hash, format| template = templates[format] hash[format] = template && ERB.new(template) } end def run(recipients = [], last = nil, flag = true, &block) last = deliver_tweets(recipients, last, &block) if flag post_messages(recipients) last end def loop(recipients = [], pause = nil, last = nil, &block) pause ||= DEFAULT_PAUSE i = 1 trap(:INT) { logm 'SIGINT received, shutting down...' i = -1 } while i > 0 last = run(recipients, last, i % pause == 1, &block) sleep 1 i += 1 end logm 'KTHXBYE!' last end def deliver_tweets(recipients, last = nil, &block) get_tweets(last).each { |tweet| logt last = tweet.id # apply filters next if filter && !filter[tweet] next if block && !block[tweet] msg = format_tweet(tweet) recipients.each { |recipient| deliver(recipient, msg) } sleep 1 } last end def post_messages(recipients = []) allowed = %r{\A(?:#{recipients.map { |r| Regexp.escape(r) }.join('|')})\z}i jabber.received_messages { |msg| next unless msg.type == :chat next unless msg.from.bare.to_s =~ allowed logj msg.id handle_command(msg.body, msg.from) } end private def twitter_connect(options = @twitter_options) @twitter_options = options auth = Twitter::OAuth.new(options[:consumer_token], options[:consumer_secret]) auth.authorize_from_access(options[:access_token], options[:access_secret]) @twitter = Twitter::Base.new(auth) # verify credentials @twitter.verify_credentials logt 'connected' @twitter rescue Twitter::TwitterError => err raise "Can't connect to Twitter with ID '#{options[:consumer_token]}': #{err}" end def jabber_connect(options = @jabber_options) @jabber_options = options @jabber = Jabber::Simple.new(options[:user], options[:pass]) logj 'connected' @jabber rescue Jabber::JabberError => err raise "Can't connect to Jabber with JID '#{options[:user]}': #{err}" end def get_tweets(last = nil) options = {} options[:since_id] = last if last tweets = twitter.friends_timeline(options) return [] unless tweets.is_a?(Array) tweets.sort_by { |tweet| tweet.created_at = Time.parse(tweet.created_at) } rescue Twitter::TwitterError, Twitter::Unavailable, Timeout::Error [] rescue => err warn "#{err} (#{err.class})" [] end def format_tweet(tweet) user = tweet.user msg = Jabber::Message.new.set_type(:chat) formats.each { |format| if erb = _erb[format] msg.add_element(format_element(format, erb.result(binding))) end } msg end # cf. <http://devblog.famundo.com/articles/2006/10/18/ruby-and-xmpp-jabber-part-3-adding-html-to-the-messages> def format_element(format, text) text = process_message(text) body = REXML::Element.new('body') case format when 'html' REXML::Text.new(process_html(text), false, body, true, nil, /.^/) html = REXML::Element.new('html').add_namespace(JABBER_NS) html.add(body.add_namespace(XHTML_NS)) html else REXML::Text.new(process_text(text), true, body, true, nil, /.^/) body end end def process_message(text) text.gsub(/https?:\/\/\S+/) { |match| LongURL.expand(match) rescue match } end def process_html(text) text.gsub(/(\A|\W)@(\w+)/, '\1@<a href="http://twitter.com/\2">\2</a>'). gsub(/(\A|\W)#(\w+)/, '\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>') end def process_text(text) text end def handle_command(body, from, execute = true) case body when /\A(?:he?(?:lp)?|\?)\z/i deliver(from, <<-HELP) if execute h[e[lp]]|? -- Print this help de[bug] -- Print debug mode de[bug] on|off -- Turn debug mode on/off bl[ock] @USER -- Block USER fa[v[orite]] #ID -- Add ID to favorites bm|bookmark[s] -- List bookmarks bm|bookmark #ID -- Bookmark ID bm|bookmark -#ID -- Remove ID from bookmarks rt|retweet #ID [!] [STATUS] -- Retweet ID re[ply] #ID [!] STATUS -- Reply to ID d[m]|direct[_message] @USER [!] STATUS -- Send direct message to USER le[n[gth]] STATUS -- Determine length [!] STATUS -- Update status (Note: STATUS must be under #{MAX_LENGTH} characters; force send with '!'.) HELP when /\Ade(?:bug)?(?:\s+(on|off))?\z/i if execute flag = $1.downcase if $1 case flag when 'on' @debug = true when 'off' @debug = false end deliver(from, "DEBUG = #{debug ? 'on' : 'off'}") end when /\Abl(?:ock)?\s+[@#]?(\w+)\z/i twitter.block($1) if execute && !debug when /\Afav?(?:orite)?\s+#?(\d+)\z/i twitter.favorite_create($1) if execute && !debug when /\A(?:bm|bookmarks?)\z/i deliver(from, bookmarks.map { |bm| st = twitter.status(bm) st = "@#{st.user.screen_name}: #{st.text[0, 10]}..." if st.is_a?(Hashie::Mash) "#{bm} - #{st || '???'}" }.join("\n")) if execute && !debug when /\A(?:bm|bookmark)\s+(\d+)\z/i if execute && !debug bookmarks << $1 bookmarks.runiq! end when /\A(?:bm|bookmark)\s+-(\d+)\z/i bookmarks.delete($1) if execute && !debug else command, options = nil, {} if execute && body.sub!(/\Alen?(?:gth)?\s+/i, '') if body = handle_command(body, from, false) length = body.length hint = length <= MAX_LENGTH ? 'OK' : 'TOO LONG' deliver(from, "#{length} [#{hint}]: #{body}") end return end begin if body.sub!(/\A(?:rt|retweet)\s+#?(\d+)(:?)(?:\s+|\z)/i, '') id, colon = $1, $2 tweet = twitter.status(id) raise Twitter::NotFound unless tweet.is_a?(Hashie::Mash) if body.empty? options[:id] = id command = :rt else body << " RT @#{tweet.user.screen_name}#{colon} #{tweet.text}" end elsif body.sub!(/\Are(?:ply)?\s+#?(\d+)(:?)\s+/i, '') id, colon = $1, $2 tweet = twitter.status(id) raise Twitter::NotFound unless tweet.is_a?(Hashie::Mash) body.insert(0, ' ') unless body.empty? body.insert(0, "@#{tweet.user.screen_name}#{colon}") options[:in_reply_to_status_id] = id end rescue Twitter::NotFound deliver(from, "TWEET NOT FOUND: #{id}") return end if body.sub!(/\A(?:dm?|direct(?:_message)?)\s+[@#]?(\w+):?\s+/i, '') options[:user] = $1 command = :dm end if body.sub!(/\A!(?:\s+|\z)/, '') force = true end body.gsub!(/https?:\/\/\S+/) { |match| match.length < 30 ? match : ShortURL.shorten(match) } return body unless execute if force || body.length <= MAX_LENGTH case command when :rt if debug logt "RT: #{options.inspect}", true else twitter.retweet(options[:id]) end when :dm if debug logt "DM: #{body} (#{options.inspect})", true else twitter.direct_message_create(options[:user], body) end else update(body, options) end deliver(from, "MSG SENT: #{body.inspect}, #{options.inspect}") else deliver(from, "MSG TOO LONG (> #{MAX_LENGTH}): #{body.inspect}") end end end def deliver(recipient, msg) if debug logj "#{recipient}: #{msg}", true return end jabber.deliver(recipient, msg) rescue => err warn "#{err} (#{err.class})" jabber_connect and retry if err.is_a?(Jabber::ServerDisconnected) end def update(msg, options = {}) if debug logt "#{msg} (#{options.inspect})", true return end twitter.update(msg, options) end def log_(msg, verbose = verbose) log.puts msg if verbose end def logm(msg, verbose = verbose) log_("#{Time.now} [#{id}] #{msg}", verbose) end def logt(msg, verbose = verbose) logm("TWITTER #{msg}", verbose) end def logj(msg, verbose = verbose) logm("JABBER #{msg}", verbose) end def bookmarks @bookmarks ||= [] end end
module Umlaut VERSION = "3.0.0beta2" end bump version module Umlaut VERSION = "3.0.0beta3" end
module Usagewatch # Show disk used in GB def uw_diskused df = `df -kl` sum = 0.00 df.each_line.with_index do |line, line_index| next if line_index.eql? 0 line = line.split(" ") next if line[0] =~ /localhost/ #ignore backup filesystem sum += ((line[2].to_f)/1024)/1024 end sum.round(2) end # Show the percentage of disk used. def uw_diskused_perc df = `df -kl` total = 0.0 used = 0.0 df.each_line.with_index do |line, line_index| df.split(" ").last.to_f.round(2) next if line_index.eql? 0 line = line.split(" ") next if line[0] =~ /localhost/ #ignore backup filesystem total += ((line[3].to_f)/1024)/1024 used +=((line[2].to_f)/1024)/1024 end ((used/total) * 100).round(2) end # todo #def uw_cpuused # #end # return hash of top ten proccesses by cpu consumption # example [["apache2", 12.0], ["passenger", 13.2]] def uw_cputop ps = `ps aux | awk '{print $11, $3}' | sort -k2nr | head -n 10` array = [] ps.each_line do |line| line = line.chomp.split(" ") array << [line.first.gsub(/[\[\]]/, ""), line.last] end array end # todo #def uw_tcpused # #end # todo #def uw_udpused # #end # return hash of top ten proccesses by mem consumption # example [["apache2", 12.0], ["passenger", 13.2]] def uw_memtop ps = `ps aux | awk '{print $11, $4}' | sort -k2nr | head -n 10` array = [] ps.each_line do |line| line = line.chomp.split(" ") array << [line.first.gsub(/[\[\]]/, "").split("/").last, line.last] end array end #todo #def uw_memused # #end #todo #def uw_load # #end #todo #def uw_bandrx # #end #todo #def uw_bandtx # #end #todo #def uw_diskioreads # #end #todo #def uw_diskiowrites # #end end add class module Usagewatch class Usagewatch # Show disk used in GB def uw_diskused df = `df -kl` sum = 0.00 df.each_line.with_index do |line, line_index| next if line_index.eql? 0 line = line.split(" ") next if line[0] =~ /localhost/ #ignore backup filesystem sum += ((line[2].to_f)/1024)/1024 end sum.round(2) end # Show the percentage of disk used. def uw_diskused_perc df = `df -kl` total = 0.0 used = 0.0 df.each_line.with_index do |line, line_index| df.split(" ").last.to_f.round(2) next if line_index.eql? 0 line = line.split(" ") next if line[0] =~ /localhost/ #ignore backup filesystem total += ((line[3].to_f)/1024)/1024 used +=((line[2].to_f)/1024)/1024 end ((used/total) * 100).round(2) end # todo #def uw_cpuused # #end # return hash of top ten proccesses by cpu consumption # example [["apache2", 12.0], ["passenger", 13.2]] def uw_cputop ps = `ps aux | awk '{print $11, $3}' | sort -k2nr | head -n 10` array = [] ps.each_line do |line| line = line.chomp.split(" ") array << [line.first.gsub(/[\[\]]/, ""), line.last] end array end # todo #def uw_tcpused # #end # todo #def uw_udpused # #end # return hash of top ten proccesses by mem consumption # example [["apache2", 12.0], ["passenger", 13.2]] def uw_memtop ps = `ps aux | awk '{print $11, $4}' | sort -k2nr | head -n 10` array = [] ps.each_line do |line| line = line.chomp.split(" ") array << [line.first.gsub(/[\[\]]/, "").split("/").last, line.last] end array end #todo #def uw_memused # #end #todo #def uw_load # #end #todo #def uw_bandrx # #end #todo #def uw_bandtx # #end #todo #def uw_diskioreads # #end #todo #def uw_diskiowrites # #end end end
namespace :magento do namespace :maintenance do desc "Turn on maintenance mode by creating maintenance.flag file" task :on do on roles(:app) do within release_path do execute :touch, "#{release_path}/maintenance.flag" end end end desc "Turn off maintenance mode by removing maintenance.flag file" task :off do on roles(:app) do within release_path do execute :rm, "-f", "#{release_path}/maintenance.flag" end end end end namespace :compiler do desc "Run compilation process and enable compiler include path" task :compile do on roles(:app) do within "#{release_path}/shell" do execute :php, "-f", "compiler.php", "--", "compile" end end end desc "Enable compiler include path" task :enable do on roles(:app) do within "#{release_path}/shell" do execute :php, "-f", "compiler.php", "--", "enable" end end end desc "Disable compiler include path" task :disable do on roles(:app) do within "#{release_path}/shell" do execute :php, "-f", "compiler.php", "--", "disable" end end end desc "Disable compiler include path and remove compiled files" task :clear do on roles(:app) do within "#{release_path}/shell" do execute :php, "-f", "compiler.php", "--", "clear" end end end end end namespace :load do task :defaults do set :linked_dirs, fetch(:linked_dirs, []).push("var", "media", "sitemaps") set :linked_files, fetch(:linked_files, []).push("app/etc/local.xml") end end Adds indexer command line task namespace :magento do namespace :maintenance do desc "Turn on maintenance mode by creating maintenance.flag file" task :on do on roles(:app) do within release_path do execute :touch, "#{release_path}/maintenance.flag" end end end desc "Turn off maintenance mode by removing maintenance.flag file" task :off do on roles(:app) do within release_path do execute :rm, "-f", "#{release_path}/maintenance.flag" end end end end namespace :compiler do desc "Run compilation process and enable compiler include path" task :compile do on roles(:app) do within "#{release_path}/shell" do execute :php, "-f", "compiler.php", "--", "compile" end end end desc "Enable compiler include path" task :enable do on roles(:app) do within "#{release_path}/shell" do execute :php, "-f", "compiler.php", "--", "enable" end end end desc "Disable compiler include path" task :disable do on roles(:app) do within "#{release_path}/shell" do execute :php, "-f", "compiler.php", "--", "disable" end end end desc "Disable compiler include path and remove compiled files" task :clear do on roles(:app) do within "#{release_path}/shell" do execute :php, "-f", "compiler.php", "--", "clear" end end end end namespace :indexer do desc "Reindex data by all indexers" task :reindexall do on roles(:db) do within "#{release_path}/shell" do execute :php, "-f", "indexer.php", "--", "reindexall" end end end end end namespace :load do task :defaults do set :linked_dirs, fetch(:linked_dirs, []).push("var", "media", "sitemaps") set :linked_files, fetch(:linked_files, []).push("app/etc/local.xml") end end
require 'capistrano/dsl/unicorn_paths' require 'capistrano/unicorn_nginx_osx/helpers' include Capistrano::UnicornNginxOsx::Helpers include Capistrano::DSL::UnicornPaths namespace :load do task :defaults do set :unicorn_service, -> { "unicorn_#{fetch(:application)}_#{fetch(:stage)}" } set :templates_path, 'config/deploy/templates' set :unicorn_pid, -> { unicorn_default_pid_file } set :unicorn_config, -> { unicorn_default_config_file } set :unicorn_plist, -> { unicorn_default_config_plist } set :unicorn_logrotate_config, -> { unicorn_default_logrotate_config_file } set :unicorn_workers, 2 set :unicorn_env, "" # environmental variables passed to unicorn/Ruby. Useful for GC tweaking, etc set :unicorn_worker_timeout, 30 set :unicorn_tcp_listen_port, 8080 set :unicorn_use_tcp, -> { roles(:app, :web).count > 1 } # use tcp if web and app nodes are on different servers set :unicorn_app_env, -> { fetch(:rails_env) || fetch(:stage) } # set :unicorn_user # default set in `unicorn:defaults` task set :unicorn_logrotate_enabled, false # by default, don't use logrotate to rotate unicorn logs set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids') set :plist, "#{fetch(:shared_path)}/config/unicorn.plist" end end namespace :unicorn do task :defaults do on roles :app do set :unicorn_user, fetch(:unicorn_user, deploy_user) end end desc 'Setup Unicorn initializer' task :setup_initializer do on roles :app do execute :mkdir, '-pv', File.dirname(fetch(:unicorn_config)) upload! template('unicorn.plist.erb'), fetch(:unicorn_plist) upload! template('unicorn.rb.erb'), fetch(:unicorn_config) end end %w[restart].each do |command| desc "#{command} unicorn" task command do on roles :app do execute "/Users/deployer/apps/unicorn_control.sh mediforum #{command}" end end after "deploy:#{command}", "unicorn:#{command}" end desc 'Setup Unicorn app configuration' task :setup_app_config do on roles :app do execute :mkdir, '-pv', File.dirname(fetch(:unicorn_config)) upload! template('unicorn.rb.erb'), fetch(:unicorn_config) end end desc 'Setup logrotate configuration' task :setup_logrotate do on roles :app do sudo :mkdir, '-pv', File.dirname(fetch(:unicorn_logrotate_config)) sudo_upload! template('unicorn-logrotate.rb.erb'), fetch(:unicorn_logrotate_config) sudo 'chown', 'root:root', fetch(:unicorn_logrotate_config) end end before :setup_initializer, :defaults before :setup_logrotate, :defaults end namespace :deploy do after :publishing, 'unicorn:restart' end desc 'Server setup tasks' task :setup do invoke 'unicorn:setup_initializer' invoke 'unicorn:setup_app_config' if fetch(:unicorn_logrotate_enabled) invoke 'unicorn:setup_logrotate' end end # after "deploy:setup", "unicorn:setup_initializer" updated unicorn.rake require 'capistrano/dsl/unicorn_paths' require 'capistrano/unicorn_nginx_osx/helpers' include Capistrano::UnicornNginxOsx::Helpers include Capistrano::DSL::UnicornPaths namespace :load do task :defaults do set :unicorn_service, -> { "unicorn_#{fetch(:application)}_#{fetch(:stage)}" } set :templates_path, 'config/deploy/templates' set :unicorn_pid, -> { unicorn_default_pid_file } set :unicorn_config, -> { unicorn_default_config_file } set :unicorn_plist, -> { unicorn_default_config_plist } set :unicorn_logrotate_config, -> { unicorn_default_logrotate_config_file } set :unicorn_workers, 2 set :unicorn_env, "" # environmental variables passed to unicorn/Ruby. Useful for GC tweaking, etc set :unicorn_worker_timeout, 30 set :unicorn_tcp_listen_port, 8080 set :unicorn_use_tcp, -> { roles(:app, :web).count > 1 } # use tcp if web and app nodes are on different servers set :unicorn_app_env, -> { fetch(:rails_env) || fetch(:stage) } # set :unicorn_user # default set in `unicorn:defaults` task set :unicorn_logrotate_enabled, false # by default, don't use logrotate to rotate unicorn logs set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids') set :plist, "#{fetch(:shared_path)}/config/unicorn.plist" end end namespace :unicorn do task :defaults do on roles :app do set :unicorn_user, fetch(:unicorn_user, deploy_user) end end desc 'Setup Unicorn initializer' task :setup_initializer do on roles :app do execute :mkdir, '-pv', File.dirname(fetch(:unicorn_config)) upload! template('unicorn.plist.erb'), "~/Library/LaunchAgents/apps.mediforum.unicorn.plist" upload! template('unicorn.rb.erb'), fetch(:unicorn_config) end end %w[restart].each do |command| desc "#{command} unicorn" task command do on roles :app do execute "/Users/deployer/apps/unicorn_control.sh mediforum #{command}" end end after "deploy:#{command}", "unicorn:#{command}" end desc 'Setup Unicorn app configuration' task :setup_app_config do on roles :app do execute :mkdir, '-pv', File.dirname(fetch(:unicorn_config)) upload! template('unicorn.rb.erb'), fetch(:unicorn_config) end end desc 'Setup logrotate configuration' task :setup_logrotate do on roles :app do sudo :mkdir, '-pv', File.dirname(fetch(:unicorn_logrotate_config)) sudo_upload! template('unicorn-logrotate.rb.erb'), fetch(:unicorn_logrotate_config) sudo 'chown', 'root:root', fetch(:unicorn_logrotate_config) end end before :setup_initializer, :defaults before :setup_logrotate, :defaults end namespace :deploy do after :publishing, 'unicorn:restart' end desc 'Server setup tasks' task :setup do invoke 'unicorn:setup_initializer' invoke 'unicorn:setup_app_config' if fetch(:unicorn_logrotate_enabled) invoke 'unicorn:setup_logrotate' end end # after "deploy:setup", "unicorn:setup_initializer"
class Opencv < Formula homepage "http://opencv.org/" head "https://github.com/Itseez/opencv.git" stable do url "https://github.com/Itseez/opencv/archive/2.4.10.1.tar.gz" sha256 "1be191790a0e279c085ddce62f44b63197f2801e3eb66b5dcb5e19c52a8c7639" # do not blacklist GStreamer # https://github.com/Itseez/opencv/pull/3639 patch :DATA end bottle do root_url "https://downloads.sf.net/project/machomebrew/Bottles/science" sha1 "ccc506ef6cf339048d21c4ef3d8995c76706c9d9" => :yosemite sha1 "fc69f870b36504f271dfe42deb5cb27c49bf21cd" => :mavericks sha1 "1726a921ced13ebe7f2df0f18f64997091070f71" => :mountain_lion end devel do url "https://github.com/Itseez/opencv/archive/3.0.0-beta.tar.gz" sha1 "560895197d1a61ed88fab9ec791328c4c57c0179" version "3.0.0-beta" end option "32-bit" option "with-java", "Build with Java support" option "with-qt", "Build the Qt4 backend to HighGUI" option "with-tbb", "Enable parallel code in OpenCV using Intel TBB" option "without-tests", "Build without accuracy & performance tests" option "without-opencl", "Disable GPU code in OpenCV using OpenCL" option "with-cuda", "Build with CUDA support" option "with-quicktime", "Use QuickTime for Video I/O insted of QTKit" option "with-opengl", "Build with OpenGL support" option "without-brewed-numpy", "Build without Homebrew-packaged NumPy" option :cxx11 depends_on :ant if build.with? "java" depends_on "cmake" => :build depends_on "eigen" => :recommended depends_on "gstreamer" => :optional depends_on "gst-plugins-good" if build.with? "gstreamer" depends_on "jasper" => :optional depends_on "jpeg" depends_on "libpng" depends_on "libtiff" depends_on "libdc1394" => :optional depends_on "openexr" => :recommended depends_on "openni" => :optional depends_on "pkg-config" => :build depends_on "qt" => :optional depends_on "tbb" => :optional depends_on :python => :recommended depends_on "homebrew/python/numpy" if build.with? "brewed-numpy" # Can also depend on ffmpeg, but this pulls in a lot of extra stuff that # you don't need unless you're doing video analysis, and some of it isn't # in Homebrew anyway. Will depend on openexr if it's installed. depends_on "ffmpeg" => :optional def arg_switch(opt) (build.with? opt) ? "ON" : "OFF" end def install ENV.cxx11 if build.cxx11? jpeg = Formula["jpeg"] dylib = OS.mac? ? "dylib" : "so" py_ver = build.stable? ? "" : "2" args = std_cmake_args + %W[ -DCMAKE_OSX_DEPLOYMENT_TARGET= -DBUILD_ZLIB=OFF -DBUILD_TIFF=OFF -DBUILD_PNG=OFF -DBUILD_OPENEXR=OFF -DBUILD_JASPER=OFF -DBUILD_JPEG=OFF -DJPEG_INCLUDE_DIR=#{jpeg.opt_include} -DJPEG_LIBRARY=#{jpeg.opt_lib}/libjpeg.#{dylib} ] args << "-DBUILD_TESTS=OFF" << "-DBUILD_PERF_TESTS=OFF" if build.without? "tests" args << "-DBUILD_opencv_python#{py_ver}=" + arg_switch("python") args << "-DBUILD_opencv_java=" + arg_switch("java") args << "-DWITH_OPENEXR=" + arg_switch("openexr") args << "-DWITH_EIGEN=" + arg_switch("eigen") args << "-DWITH_TBB=" + arg_switch("tbb") args << "-DWITH_FFMPEG=" + arg_switch("ffmpeg") args << "-DWITH_QUICKTIME=" + arg_switch("quicktime") args << "-DWITH_1394=" + arg_switch("libdc1394") args << "-DWITH_OPENGL=" + arg_switch("opengl") args << "-DWITH_JASPER=" + arg_switch("jasper") args << "-DWITH_QT=" + arg_switch("qt") args << "-DWITH_GSTREAMER=" + arg_switch("gstreamer") if build.with? "python" py_prefix = `python-config --prefix`.chomp py_lib = OS.linux? ? `python-config --configdir`.chomp : "#{py_prefix}/lib" args << "-DPYTHON#{py_ver}_LIBRARY=#{py_lib}/libpython2.7.#{dylib}" args << "-DPYTHON#{py_ver}_INCLUDE_DIR=#{py_prefix}/include/python2.7" end if build.with? "cuda" ENV["CUDA_NVCC_FLAGS"] = "-Xcompiler -stdlib=libstdc++; -Xlinker -stdlib=libstdc++" inreplace "cmake/FindCUDA.cmake", "list(APPEND CUDA_LIBRARIES -Wl,-rpath \"-Wl,${_cuda_path_to_cudart}\")", "#list(APPEND CUDA" args << "-DWITH_CUDA=ON" args << "-DCMAKE_CXX_FLAGS=-stdlib=libstdc++" else args << "-DWITH_CUDA=OFF" end # OpenCL 1.1 is required, but Snow Leopard and older come with 1.0 args << "-DWITH_OPENCL=OFF" if build.without?("opencl") || MacOS.version < :lion if build.with? "openni" args << "-DWITH_OPENNI=ON" # Set proper path for Homebrew's openni inreplace "cmake/OpenCVFindOpenNI.cmake" do |s| s.gsub! "/usr/include/ni", "#{Formula["openni"].opt_include}/ni" s.gsub! "/usr/lib", "#{Formula["openni"].opt_lib}" end end if build.include? "32-bit" args << "-DCMAKE_OSX_ARCHITECTURES=i386" args << "-DOPENCV_EXTRA_C_FLAGS='-arch i386 -m32'" args << "-DOPENCV_EXTRA_CXX_FLAGS='-arch i386 -m32'" end if ENV.compiler == :clang && !build.bottle? args << "-DENABLE_SSSE3=ON" if Hardware::CPU.ssse3? args << "-DENABLE_SSE41=ON" if Hardware::CPU.sse4? args << "-DENABLE_SSE42=ON" if Hardware::CPU.sse4_2? args << "-DENABLE_AVX=ON" if Hardware::CPU.avx? end mkdir "macbuild" do system "cmake", "..", *args system "make" system "make", "install" end end test do Language::Python.each_python(build) do |python, _version| system python, "-c", "import cv2" end end end __END__ diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d7d78a..1e92c52 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -135,7 +135,7 @@ OCV_OPTION(WITH_NVCUVID "Include NVidia Video Decoding library support" OCV_OPTION(WITH_EIGEN "Include Eigen2/Eigen3 support" ON) OCV_OPTION(WITH_VFW "Include Video for Windows support" ON IF WIN32 ) OCV_OPTION(WITH_FFMPEG "Include FFMPEG support" ON IF (NOT ANDROID AND NOT IOS)) -OCV_OPTION(WITH_GSTREAMER "Include Gstreamer support" ON IF (UNIX AND NOT APPLE AND NOT ANDROID) ) +OCV_OPTION(WITH_GSTREAMER "Include Gstreamer support" ON IF (UNIX AND NOT ANDROID) ) OCV_OPTION(WITH_GSTREAMER_0_10 "Enable Gstreamer 0.10 support (instead of 1.x)" OFF ) OCV_OPTION(WITH_GTK "Include GTK support" ON IF (UNIX AND NOT APPLE AND NOT ANDROID) ) OCV_OPTION(WITH_IMAGEIO "ImageIO support for OS X" OFF IF APPLE ) opencv: add missing depends_on :java Closes #1897. Signed-off-by: Ian Lancaster <4149eb996d53c157338856d755d8c021b4cb355b@gmail.com> class Opencv < Formula homepage "http://opencv.org/" head "https://github.com/Itseez/opencv.git" stable do url "https://github.com/Itseez/opencv/archive/2.4.10.1.tar.gz" sha256 "1be191790a0e279c085ddce62f44b63197f2801e3eb66b5dcb5e19c52a8c7639" # do not blacklist GStreamer # https://github.com/Itseez/opencv/pull/3639 patch :DATA end bottle do root_url "https://downloads.sf.net/project/machomebrew/Bottles/science" sha1 "ccc506ef6cf339048d21c4ef3d8995c76706c9d9" => :yosemite sha1 "fc69f870b36504f271dfe42deb5cb27c49bf21cd" => :mavericks sha1 "1726a921ced13ebe7f2df0f18f64997091070f71" => :mountain_lion end devel do url "https://github.com/Itseez/opencv/archive/3.0.0-beta.tar.gz" sha1 "560895197d1a61ed88fab9ec791328c4c57c0179" version "3.0.0-beta" end option "32-bit" option "with-java", "Build with Java support" option "with-qt", "Build the Qt4 backend to HighGUI" option "with-tbb", "Enable parallel code in OpenCV using Intel TBB" option "without-tests", "Build without accuracy & performance tests" option "without-opencl", "Disable GPU code in OpenCV using OpenCL" option "with-cuda", "Build with CUDA support" option "with-quicktime", "Use QuickTime for Video I/O insted of QTKit" option "with-opengl", "Build with OpenGL support" option "without-brewed-numpy", "Build without Homebrew-packaged NumPy" option :cxx11 depends_on :ant if build.with? "java" depends_on "cmake" => :build depends_on "eigen" => :recommended depends_on "gstreamer" => :optional depends_on "gst-plugins-good" if build.with? "gstreamer" depends_on "jasper" => :optional depends_on :java => :optional depends_on "jpeg" depends_on "libpng" depends_on "libtiff" depends_on "libdc1394" => :optional depends_on "openexr" => :recommended depends_on "openni" => :optional depends_on "pkg-config" => :build depends_on "qt" => :optional depends_on "tbb" => :optional depends_on :python => :recommended depends_on "homebrew/python/numpy" if build.with? "brewed-numpy" # Can also depend on ffmpeg, but this pulls in a lot of extra stuff that # you don't need unless you're doing video analysis, and some of it isn't # in Homebrew anyway. Will depend on openexr if it's installed. depends_on "ffmpeg" => :optional def arg_switch(opt) (build.with? opt) ? "ON" : "OFF" end def install ENV.cxx11 if build.cxx11? jpeg = Formula["jpeg"] dylib = OS.mac? ? "dylib" : "so" py_ver = build.stable? ? "" : "2" args = std_cmake_args + %W[ -DCMAKE_OSX_DEPLOYMENT_TARGET= -DBUILD_ZLIB=OFF -DBUILD_TIFF=OFF -DBUILD_PNG=OFF -DBUILD_OPENEXR=OFF -DBUILD_JASPER=OFF -DBUILD_JPEG=OFF -DJPEG_INCLUDE_DIR=#{jpeg.opt_include} -DJPEG_LIBRARY=#{jpeg.opt_lib}/libjpeg.#{dylib} ] args << "-DBUILD_TESTS=OFF" << "-DBUILD_PERF_TESTS=OFF" if build.without? "tests" args << "-DBUILD_opencv_python#{py_ver}=" + arg_switch("python") args << "-DBUILD_opencv_java=" + arg_switch("java") args << "-DWITH_OPENEXR=" + arg_switch("openexr") args << "-DWITH_EIGEN=" + arg_switch("eigen") args << "-DWITH_TBB=" + arg_switch("tbb") args << "-DWITH_FFMPEG=" + arg_switch("ffmpeg") args << "-DWITH_QUICKTIME=" + arg_switch("quicktime") args << "-DWITH_1394=" + arg_switch("libdc1394") args << "-DWITH_OPENGL=" + arg_switch("opengl") args << "-DWITH_JASPER=" + arg_switch("jasper") args << "-DWITH_QT=" + arg_switch("qt") args << "-DWITH_GSTREAMER=" + arg_switch("gstreamer") if build.with? "python" py_prefix = `python-config --prefix`.chomp py_lib = OS.linux? ? `python-config --configdir`.chomp : "#{py_prefix}/lib" args << "-DPYTHON#{py_ver}_LIBRARY=#{py_lib}/libpython2.7.#{dylib}" args << "-DPYTHON#{py_ver}_INCLUDE_DIR=#{py_prefix}/include/python2.7" end if build.with? "cuda" ENV["CUDA_NVCC_FLAGS"] = "-Xcompiler -stdlib=libstdc++; -Xlinker -stdlib=libstdc++" inreplace "cmake/FindCUDA.cmake", "list(APPEND CUDA_LIBRARIES -Wl,-rpath \"-Wl,${_cuda_path_to_cudart}\")", "#list(APPEND CUDA" args << "-DWITH_CUDA=ON" args << "-DCMAKE_CXX_FLAGS=-stdlib=libstdc++" else args << "-DWITH_CUDA=OFF" end # OpenCL 1.1 is required, but Snow Leopard and older come with 1.0 args << "-DWITH_OPENCL=OFF" if build.without?("opencl") || MacOS.version < :lion if build.with? "openni" args << "-DWITH_OPENNI=ON" # Set proper path for Homebrew's openni inreplace "cmake/OpenCVFindOpenNI.cmake" do |s| s.gsub! "/usr/include/ni", "#{Formula["openni"].opt_include}/ni" s.gsub! "/usr/lib", "#{Formula["openni"].opt_lib}" end end if build.include? "32-bit" args << "-DCMAKE_OSX_ARCHITECTURES=i386" args << "-DOPENCV_EXTRA_C_FLAGS='-arch i386 -m32'" args << "-DOPENCV_EXTRA_CXX_FLAGS='-arch i386 -m32'" end if ENV.compiler == :clang && !build.bottle? args << "-DENABLE_SSSE3=ON" if Hardware::CPU.ssse3? args << "-DENABLE_SSE41=ON" if Hardware::CPU.sse4? args << "-DENABLE_SSE42=ON" if Hardware::CPU.sse4_2? args << "-DENABLE_AVX=ON" if Hardware::CPU.avx? end mkdir "macbuild" do system "cmake", "..", *args system "make" system "make", "install" end end test do Language::Python.each_python(build) do |python, _version| system python, "-c", "import cv2" end end end __END__ diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d7d78a..1e92c52 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -135,7 +135,7 @@ OCV_OPTION(WITH_NVCUVID "Include NVidia Video Decoding library support" OCV_OPTION(WITH_EIGEN "Include Eigen2/Eigen3 support" ON) OCV_OPTION(WITH_VFW "Include Video for Windows support" ON IF WIN32 ) OCV_OPTION(WITH_FFMPEG "Include FFMPEG support" ON IF (NOT ANDROID AND NOT IOS)) -OCV_OPTION(WITH_GSTREAMER "Include Gstreamer support" ON IF (UNIX AND NOT APPLE AND NOT ANDROID) ) +OCV_OPTION(WITH_GSTREAMER "Include Gstreamer support" ON IF (UNIX AND NOT ANDROID) ) OCV_OPTION(WITH_GSTREAMER_0_10 "Enable Gstreamer 0.10 support (instead of 1.x)" OFF ) OCV_OPTION(WITH_GTK "Include GTK support" ON IF (UNIX AND NOT APPLE AND NOT ANDROID) ) OCV_OPTION(WITH_IMAGEIO "ImageIO support for OS X" OFF IF APPLE )
require 'semverly' require 'open3' require 'bundler' require_relative '../base/engine' require_relative 'ruby_helper' module CapsuleCD module Ruby class RubyEngine < Engine def build_step super gemspec_path = CapsuleCD::Ruby::RubyHelper.get_gemspec_path(@source_git_local_path) # check for/create required VERSION file gemspec_data = CapsuleCD::Ruby::RubyHelper.load_gemspec_data(gemspec_path) if !gemspec_data || !File.exist?(CapsuleCD::Ruby::RubyHelper.version_filepath(@source_git_local_path, gemspec_data.name)) fail CapsuleCD::Error::BuildPackageInvalid, 'version.rb file is required to process Ruby gem' end # bump up the version here. # since there's no standardized way to bump up the version in the *.gemspec file, we're going to assume that the version # is specified in a version file in the lib/<gem_name>/ directory, similar to how the bundler gem does it. # ie. bundle gem <gem_name> will create a file: my_gem/lib/my_gem/version.rb with the following contents # module MyGem # VERSION = "0.1.0" # end # # Jeweler and Hoe both do something similar. # http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/ # http://timelessrepo.com/making-ruby-gems # http://guides.rubygems.org/make-your-own-gem/ version_str = CapsuleCD::Ruby::RubyHelper.read_version_file(@source_git_local_path, gemspec_data.name) next_version = bump_version(SemVer.parse(gemspec_data.version.to_s)) new_version_str = version_str.gsub(/(VERSION\s*=\s*['"])[0-9\.]+(['"])/, "\\1#{next_version}\\2") CapsuleCD::Ruby::RubyHelper.write_version_file(@source_git_local_path, gemspec_data.name, new_version_str) # check for/create any required missing folders/files unless File.exist?(@source_git_local_path + '/Gemfile') File.open(@source_git_local_path + '/Gemfile', 'w') { |file| file.puts("source 'https://rubygems.org'") file.puts('gemspec') } end unless File.exist?(@source_git_local_path + '/Rakefile') File.open(@source_git_local_path + '/Rakefile', 'w') { |file| file.write('task :default => :spec') } end unless File.exist?(@source_git_local_path + '/spec') FileUtils.mkdir(@source_git_local_path + '/spec') end unless File.exist?(@source_git_local_path + '/.gitignore') CapsuleCD::GitUtils.create_gitignore(@source_git_local_path, ['Ruby']) end # package the gem, make sure it builds correctly Open3.popen3('gem build '+ File.basename(gemspec_path), chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::BuildPackageFailed, 'gem build failed. Check gemspec file and dependencies' end end end def test_step super gems = Dir.glob(@source_git_local_path + '/*.gem') if gems.empty? fail CapsuleCD::Error::TestDependenciesError, 'Ruby gem file could not be found' end gem_path = gems.first # lets install the gem, and any dependencies # http://guides.rubygems.org/make-your-own-gem/ Bundler.with_clean_env do Open3.popen3('gem install ./' + File.basename(gem_path) + ' --ignore-dependencies', chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::TestDependenciesError, 'gem install failed. Check gemspec and gem dependencies' end end Open3.popen3('bundle install', chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::TestDependenciesError, 'bundle install failed. Check Gemfile' end end # run test command test_cmd = @config.engine_cmd_test || 'rake spec' Open3.popen3(test_cmd, chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::TestRunnerError, test_cmd + ' failed. Check log for exact error' end end unless @config.engine_disable_test end end # run npm publish def package_step super # commit changes to the cookbook. (test run occurs before this, and it should clean up any instrumentation files, created, # as they will be included in the commmit and any release artifacts) gemspec_data = CapsuleCD::Ruby::RubyHelper.get_gemspec_data(@source_git_local_path) next_version = SemVer.parse(gemspec_data.version.to_s) CapsuleCD::GitUtils.commit(@source_git_local_path, "(v#{next_version}) Automated packaging of release by CapsuleCD") @source_release_commit = CapsuleCD::GitUtils.tag(@source_git_local_path, "v#{next_version}") end # this step should push the release to the package repository (ie. npm, chef supermarket, rubygems) def release_step super unless @config.rubygems_api_key fail CapsuleCD::Error::ReleaseCredentialsMissing, 'cannot deploy package to rubygems, credentials missing' return end # write the config file. rubygems_cred_path = File.expand_path('~/.gem') FileUtils.mkdir_p(rubygems_cred_path) File.open(rubygems_cred_path + '/credentials', 'w+', 0600) do |file| file.write(<<-EOT.gsub(/^\s+/, '') --- :rubygems_api_key: #{@config.rubygems_api_key} EOT ) end # run gem push *.gem gems = Dir.glob(@source_git_local_path + '/*.gem') if gems.empty? fail CapsuleCD::Error::TestDependenciesError, 'Ruby gem file could not be found' end gem_path = gems.first Open3.popen3('gem push ' + File.basename(gem_path), chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::ReleasePackageError, 'Pushing gem to RubyGems.org using `gem push` failed. Check log for exact error' end end end end end end validate that the gem build command creates the correct gem version. require 'semverly' require 'open3' require 'bundler' require_relative '../base/engine' require_relative 'ruby_helper' module CapsuleCD module Ruby class RubyEngine < Engine def build_step super gemspec_path = CapsuleCD::Ruby::RubyHelper.get_gemspec_path(@source_git_local_path) # check for/create required VERSION file gemspec_data = CapsuleCD::Ruby::RubyHelper.load_gemspec_data(gemspec_path) if !gemspec_data || !File.exist?(CapsuleCD::Ruby::RubyHelper.version_filepath(@source_git_local_path, gemspec_data.name)) fail CapsuleCD::Error::BuildPackageInvalid, 'version.rb file is required to process Ruby gem' end # bump up the version here. # since there's no standardized way to bump up the version in the *.gemspec file, we're going to assume that the version # is specified in a version file in the lib/<gem_name>/ directory, similar to how the bundler gem does it. # ie. bundle gem <gem_name> will create a file: my_gem/lib/my_gem/version.rb with the following contents # module MyGem # VERSION = "0.1.0" # end # # Jeweler and Hoe both do something similar. # http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/ # http://timelessrepo.com/making-ruby-gems # http://guides.rubygems.org/make-your-own-gem/ version_str = CapsuleCD::Ruby::RubyHelper.read_version_file(@source_git_local_path, gemspec_data.name) next_version = bump_version(SemVer.parse(gemspec_data.version.to_s)) new_version_str = version_str.gsub(/(VERSION\s*=\s*['"])[0-9\.]+(['"])/, "\\1#{next_version}\\2") CapsuleCD::Ruby::RubyHelper.write_version_file(@source_git_local_path, gemspec_data.name, new_version_str) # check for/create any required missing folders/files unless File.exist?(@source_git_local_path + '/Gemfile') File.open(@source_git_local_path + '/Gemfile', 'w') { |file| file.puts("source 'https://rubygems.org'") file.puts('gemspec') } end unless File.exist?(@source_git_local_path + '/Rakefile') File.open(@source_git_local_path + '/Rakefile', 'w') { |file| file.write('task :default => :spec') } end unless File.exist?(@source_git_local_path + '/spec') FileUtils.mkdir(@source_git_local_path + '/spec') end unless File.exist?(@source_git_local_path + '/.gitignore') CapsuleCD::GitUtils.create_gitignore(@source_git_local_path, ['Ruby']) end # package the gem, make sure it builds correctly Open3.popen3('gem build '+ File.basename(gemspec_path), chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::BuildPackageFailed, 'gem build failed. Check gemspec file and dependencies' end unless File.exist?(@source_git_local_path + "/#{gemspec_data.name}-#{next_version.to_s}.gem") fail CapsuleCD::Error::BuildPackageFailed, "gem build failed. #{gemspec_data.name}-#{next_version.to_s}.gem not found" end end end def test_step super gems = Dir.glob(@source_git_local_path + '/*.gem') if gems.empty? fail CapsuleCD::Error::TestDependenciesError, 'Ruby gem file could not be found' end gem_path = gems.first # lets install the gem, and any dependencies # http://guides.rubygems.org/make-your-own-gem/ Bundler.with_clean_env do Open3.popen3('gem install ./' + File.basename(gem_path) + ' --ignore-dependencies', chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::TestDependenciesError, 'gem install failed. Check gemspec and gem dependencies' end end Open3.popen3('bundle install', chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::TestDependenciesError, 'bundle install failed. Check Gemfile' end end # run test command test_cmd = @config.engine_cmd_test || 'rake spec' Open3.popen3(test_cmd, chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::TestRunnerError, test_cmd + ' failed. Check log for exact error' end end unless @config.engine_disable_test end end # run npm publish def package_step super # commit changes to the cookbook. (test run occurs before this, and it should clean up any instrumentation files, created, # as they will be included in the commmit and any release artifacts) gemspec_data = CapsuleCD::Ruby::RubyHelper.get_gemspec_data(@source_git_local_path) next_version = SemVer.parse(gemspec_data.version.to_s) CapsuleCD::GitUtils.commit(@source_git_local_path, "(v#{next_version}) Automated packaging of release by CapsuleCD") @source_release_commit = CapsuleCD::GitUtils.tag(@source_git_local_path, "v#{next_version}") end # this step should push the release to the package repository (ie. npm, chef supermarket, rubygems) def release_step super unless @config.rubygems_api_key fail CapsuleCD::Error::ReleaseCredentialsMissing, 'cannot deploy package to rubygems, credentials missing' return end # write the config file. rubygems_cred_path = File.expand_path('~/.gem') FileUtils.mkdir_p(rubygems_cred_path) File.open(rubygems_cred_path + '/credentials', 'w+', 0600) do |file| file.write(<<-EOT.gsub(/^\s+/, '') --- :rubygems_api_key: #{@config.rubygems_api_key} EOT ) end # run gem push *.gem gems = Dir.glob(@source_git_local_path + '/*.gem') if gems.empty? fail CapsuleCD::Error::TestDependenciesError, 'Ruby gem file could not be found' end gem_path = gems.first Open3.popen3('gem push ' + File.basename(gem_path), chdir: @source_git_local_path) do |_stdin, stdout, stderr, external| { stdout: stdout, stderr: stderr }. each do |name, stream_buffer| Thread.new do until (line = stream_buffer.gets).nil? puts "#{name} -> #{line}" end end end # wait for process external.join unless external.value.success? fail CapsuleCD::Error::ReleasePackageError, 'Pushing gem to RubyGems.org using `gem push` failed. Check log for exact error' end end end end end end
class Capybara::RackTest::Browser include ::Rack::Test::Methods attr_reader :driver attr_accessor :current_host def initialize(driver) @driver = driver end def app driver.app end def options driver.options end def visit(path, attributes = {}) reset_host! process(:get, path, attributes) follow_redirects! end def submit(method, path, attributes) path = request_path if not path or path.empty? process(method, path, attributes) follow_redirects! end def follow(method, path, attributes = {}) return if path.gsub(/^#{request_path}/, '').start_with?('#') process(method, path, attributes) follow_redirects! end def follow_redirects! 5.times do process(:get, last_response["Location"]) if last_response.redirect? end raise Capybara::InfiniteRedirectError, "redirected more than 5 times, check for infinite redirects." if last_response.redirect? end def process(method, path, attributes = {}) new_uri = URI.parse(path) current_uri = URI.parse(current_url) method.downcase! unless method.is_a? Symbol if new_uri.host @current_host = new_uri.scheme + '://' + new_uri.host if new_uri.port != 80 @current_host << ":#{new_uri.port}" end end if new_uri.relative? if path.start_with?('?') path = request_path + path elsif not path.start_with?('/') path = request_path.sub(%r(/[^/]*$), '/') + path end path = current_host + path end reset_cache! send(method, path, attributes, env) end def current_url last_request.url rescue Rack::Test::Error "" end def reset_host! @current_host = (Capybara.app_host || Capybara.default_host) end def reset_cache! @dom = nil end def body dom.to_xml end def dom @dom ||= Nokogiri::HTML(source) end def find(selector) dom.xpath(selector).map { |node| Capybara::RackTest::Node.new(self, node) } end def source last_response.body rescue Rack::Test::Error "" end protected def build_rack_mock_session reset_host! unless current_host Rack::MockSession.new(app, URI.parse(current_host).host) end def request_path last_request.path rescue Rack::Test::Error "" end def env env = {} begin env["HTTP_REFERER"] = last_request.url rescue Rack::Test::Error # no request yet end env.merge!(options[:headers]) if options[:headers] env end end suppress a warning: lib/capybara/rack_test/browser.rb:46: warning: assigned but unused variable - current_uri class Capybara::RackTest::Browser include ::Rack::Test::Methods attr_reader :driver attr_accessor :current_host def initialize(driver) @driver = driver end def app driver.app end def options driver.options end def visit(path, attributes = {}) reset_host! process(:get, path, attributes) follow_redirects! end def submit(method, path, attributes) path = request_path if not path or path.empty? process(method, path, attributes) follow_redirects! end def follow(method, path, attributes = {}) return if path.gsub(/^#{request_path}/, '').start_with?('#') process(method, path, attributes) follow_redirects! end def follow_redirects! 5.times do process(:get, last_response["Location"]) if last_response.redirect? end raise Capybara::InfiniteRedirectError, "redirected more than 5 times, check for infinite redirects." if last_response.redirect? end def process(method, path, attributes = {}) new_uri = URI.parse(path) method.downcase! unless method.is_a? Symbol if new_uri.host @current_host = new_uri.scheme + '://' + new_uri.host if new_uri.port != 80 @current_host << ":#{new_uri.port}" end end if new_uri.relative? if path.start_with?('?') path = request_path + path elsif not path.start_with?('/') path = request_path.sub(%r(/[^/]*$), '/') + path end path = current_host + path end reset_cache! send(method, path, attributes, env) end def current_url last_request.url rescue Rack::Test::Error "" end def reset_host! @current_host = (Capybara.app_host || Capybara.default_host) end def reset_cache! @dom = nil end def body dom.to_xml end def dom @dom ||= Nokogiri::HTML(source) end def find(selector) dom.xpath(selector).map { |node| Capybara::RackTest::Node.new(self, node) } end def source last_response.body rescue Rack::Test::Error "" end protected def build_rack_mock_session reset_host! unless current_host Rack::MockSession.new(app, URI.parse(current_host).host) end def request_path last_request.path rescue Rack::Test::Error "" end def env env = {} begin env["HTTP_REFERER"] = last_request.url rescue Rack::Test::Error # no request yet end env.merge!(options[:headers]) if options[:headers] env end end
# encoding utf-8 require_relative 'bolt.rb' module Carto class GhostTablesManager MUTEX_REDIS_KEY = 'ghost_tables_working'.freeze MUTEX_TTL_MS = 60000 def initialize(user_id) @user = ::User.where(id: user_id).first end def link_ghost_tables return if user_tables_synced_with_db? if safe_async? ::Resque.enqueue(::Resque::UserJobs::SyncTables::LinkGhostTables, @user.id) else link_ghost_tables_synchronously end end def link_ghost_tables_synchronously sync_user_tables_with_db unless user_tables_synced_with_db? end private # determine linked tables vs cartodbfied tables consistency; i.e.: needs to run sync def user_tables_synced_with_db? fetch_cartodbfied_tables == fetch_user_tables end # Check if any unsafe stale (dropped or renamed) tables will be shown to the user def safe_async?(cartodbfied_tables) find_dropped_tables(cartodbfied_tables).empty? && find_stale_tables(cartodbfied_tables).empty? end def sync_user_tables_with_db bolt = Carto::Bolt.new("#{@user.username}:#{MUTEX_REDIS_KEY}", ttl_ms: MUTEX_TTL_MS) got_locked = bolt.run_locked { sync } CartoDB::Logger.info(message: 'Ghost table race condition avoided', user: @user) unless got_locked end def sync cartodbfied_tables = fetch_cartodbfied_tables # Update table_id on UserTables with physical tables with changed oid. Should go first. find_regenerated_tables(cartodbfied_tables).each(&:regenerate_user_table) # Relink tables that have been renamed through the SQL API find_renamed_tables(cartodbfied_tables).each(&:rename_user_table_vis) # Create UserTables for non linked Tables find_new_tables(cartodbfied_tables).each(&:create_user_table) # Unlink tables that have been created trhought the SQL API. Should go last. find_dropped_tables(cartodbfied_tables).each(&:drop_user_table) end def find_stale_tables(cartodbfied_tables) find_regenerated_tables(cartodbfied_tables) | find_renamed_tables(cartodbfied_tables) | find_dropped_tables(cartodbfied_tables) end def find_unaltered_tables(cartodbfied_tables) cartodbfied_tables - (find_regenerated_tables(cartodbfied_tables) | find_renamed_tables(cartodbfied_tables) | find_new_tables(cartodbfied_tables)) end def find_renamed_tables(cartodbfied_tables) user_tables = fetch_user_tables cartodbfied_tables.select do |cartodbfied_table| user_tables.map(&:id).include?(cartodbfied_table.id) && !user_tables.map(&:name).include?(cartodbfied_table.name) end end def find_regenerated_tables(cartodbfied_tables) user_tables = fetch_user_tables cartodbfied_tables.select do |cartodbfied_table| user_tables.map(&:name).include?(cartodbfied_table.name) && !user_tables.map(&:id).include?(cartodbfied_table.id) end end def find_new_tables(cartodbfied_tables) cartodbfied_tables - fetch_user_tables - find_stale_tables(cartodbfied_tables) end # Tables that have been dropped via API but have an old UserTable def find_dropped_tables(cartodbfied_tables) fetch_user_tables - cartodbfied_tables end # Fetches all currently linked user tables def fetch_user_tables results = Carto::UserTable.select([:name, :table_id]).where(user_id: @user.id) results.map do |record| Carto::TableFacade.new(record[:table_id], record[:name], @user) end end # Fetches all linkable tables: non raster cartodbfied + raster def fetch_cartodbfied_tables fetch_non_raster_cartodbfied_tables + fetch_raster_tables end # this method searchs for tables with all the columns needed in a cartodb table. # it does not check column types, and only the latest cartodbfication trigger attached (test_quota_per_row) def fetch_non_raster_cartodbfied_tables cartodb_columns = (Table::CARTODB_REQUIRED_COLUMNS + [Table::THE_GEOM_WEBMERCATOR]).map { |col| "'#{col}'" } .join(',') sql = %{ WITH cartodbfied_tables as ( SELECT c.table_name, tg.tgrelid reloid, count(column_name::text) cdb_columns_count FROM information_schema.columns c, pg_tables t, pg_trigger tg WHERE t.tablename = c.table_name AND t.schemaname = c.table_schema AND c.table_schema = '#{@user.database_schema}' AND t.tableowner = '#{@user.database_username}' AND column_name IN (#{cartodb_columns}) AND tg.tgrelid = (quote_ident(t.schemaname) || '.' || quote_ident(t.tablename))::regclass::oid AND tg.tgname = 'test_quota_per_row' GROUP BY reloid, 1) SELECT table_name, reloid FROM cartodbfied_tables WHERE cdb_columns_count = #{cartodb_columns.split(',').length} } @user.in_database(as: :superuser)[sql].all.map do |record| Carto::TableFacade.new(record[:reloid], record[:table_name], @user) end end # Find raster tables which won't appear as cartodbfied but MUST be linked def fetch_raster_tables sql = %{ WITH cartodbfied_tables as ( SELECT c.table_name, tg.tgrelid reloid, count(column_name::text) cdb_columns_count FROM information_schema.columns c, pg_tables t, pg_trigger tg WHERE t.tablename = c.table_name AND t.schemaname = c.table_schema AND c.table_schema = '#{@user.database_schema}' AND t.tableowner = '#{@user.database_username}' AND column_name IN ('cartodb_id', 'the_raster_webmercator') AND tg.tgrelid = (quote_ident(t.schemaname) || '.' || quote_ident(t.tablename))::regclass::oid AND tg.tgname = 'test_quota_per_row' GROUP BY reloid, 1) SELECT table_name, reloid FROM cartodbfied_tables WHERE cdb_columns_count = 2; } @user.in_database(as: :superuser)[sql].all.map do |record| Carto::TableFacade.new(record[:reloid], record[:table_name], @user) end end end class TableFacade attr_reader :id, :name, :user def initialize(id, name, user) @id = id @name = name @user = user end def user_table_with_matching_id user.tables.where(table_id: id).first end def user_table_with_matching_name user.tables.where(name: name).first end def create_user_table CartoDB::Logger.debug(message: 'ghost tables', action: 'linking new table', user: @user, table_name: name, table_id: id) # TODO: Use Carto::UserTable when it's ready and stop the Table <-> ::UserTable madness new_table = ::Table.new(user_table: ::UserTable.new.set_fields({ user_id: @user.id, table_id: id, name: name }, [:user_id, :table_id, :name])) new_table.register_table_only = true new_table.keep_user_database_table = true new_table.save rescue => exception CartoDB::Logger.error(message: 'Ghost tables: Error creating UserTable', exception: exception, user: @user, table_name: name, table_id: id) end def rename_user_table_vis CartoDB::Logger.debug(message: 'ghost tables', action: 'relinking renamed table', user: @user, table_name: name, table_id: id) user_table_vis = user_table_with_matching_id.table_visualization user_table_vis.register_table_only = true user_table_vis.name = name user_table_vis.store rescue => exception CartoDB::Logger.error(message: 'Ghost tables: Error renaming Visualization', exception: exception, user: @user, table_name: name, table_id: id) end def drop_user_table CartoDB::Logger.debug(message: 'ghost tables', action: 'unlinking dropped table', user: @user, table_name: name, table_id: id) # TODO: Use Carto::UserTable when it's ready and stop the Table <-> ::UserTable madness table_to_drop = ::Table.new(user_table: @user.tables.where(table_id: id, name: name).first) table_to_drop.keep_user_database_table = true table_to_drop.destroy rescue => exception CartoDB::Logger.error(message: 'Ghost tables: Error dropping Table', exception: exception, user: @user, table_name: name, table_id: id) end def regenerate_user_table CartoDB::Logger.debug(message: 'ghost tables', action: 'regenerating table_id', user: @user, table_name: name, table_id: id) user_table_to_regenerate = user_table_with_matching_name user_table_to_regenerate.table_id = id user_table_to_regenerate.save rescue => exception CartoDB::Logger.error(message: 'Ghost tables: Error syncing table_id for UserTable', exception: exception, user: @user, table_name: name, table_id: id) end def eql?(other) id.eql?(other.id) && name.eql?(other.name) && user.id.eql?(other.user.id) end def ==(other) eql?(other) end def hash [id, name, user.id].hash end end end delayed user instancing on TableFacade to avoid unnecessary loads # encoding utf-8 require_relative 'bolt.rb' module Carto class GhostTablesManager MUTEX_REDIS_KEY = 'ghost_tables_working'.freeze MUTEX_TTL_MS = 60000 def initialize(user_id) @user = ::User[user_id] end def link_ghost_tables return if user_tables_synced_with_db? if safe_async? ::Resque.enqueue(::Resque::UserJobs::SyncTables::LinkGhostTables, @user.id) else link_ghost_tables_synchronously end end def link_ghost_tables_synchronously sync_user_tables_with_db unless user_tables_synced_with_db? end private # determine linked tables vs cartodbfied tables consistency; i.e.: needs to run sync def user_tables_synced_with_db? fetch_cartodbfied_tables == fetch_user_tables end # Check if any unsafe stale (dropped or renamed) tables will be shown to the user def safe_async?(cartodbfied_tables) find_dropped_tables(cartodbfied_tables).empty? && find_stale_tables(cartodbfied_tables).empty? end def sync_user_tables_with_db bolt = Carto::Bolt.new("#{@user.username}:#{MUTEX_REDIS_KEY}", ttl_ms: MUTEX_TTL_MS) got_locked = bolt.run_locked { sync } CartoDB::Logger.info(message: 'Ghost table race condition avoided', user: @user) unless got_locked end def sync cartodbfied_tables = fetch_cartodbfied_tables # Update table_id on UserTables with physical tables with changed oid. Should go first. find_regenerated_tables(cartodbfied_tables).each(&:regenerate_user_table) # Relink tables that have been renamed through the SQL API find_renamed_tables(cartodbfied_tables).each(&:rename_user_table_vis) # Create UserTables for non linked Tables find_new_tables(cartodbfied_tables).each(&:create_user_table) # Unlink tables that have been created trhought the SQL API. Should go last. find_dropped_tables(cartodbfied_tables).each(&:drop_user_table) end def find_stale_tables(cartodbfied_tables) find_regenerated_tables(cartodbfied_tables) | find_renamed_tables(cartodbfied_tables) | find_dropped_tables(cartodbfied_tables) end def find_unaltered_tables(cartodbfied_tables) cartodbfied_tables - (find_regenerated_tables(cartodbfied_tables) | find_renamed_tables(cartodbfied_tables) | find_new_tables(cartodbfied_tables)) end def find_renamed_tables(cartodbfied_tables) user_tables = fetch_user_tables cartodbfied_tables.select do |cartodbfied_table| user_tables.map(&:id).include?(cartodbfied_table.id) && !user_tables.map(&:name).include?(cartodbfied_table.name) end end def find_regenerated_tables(cartodbfied_tables) user_tables = fetch_user_tables cartodbfied_tables.select do |cartodbfied_table| user_tables.map(&:name).include?(cartodbfied_table.name) && !user_tables.map(&:id).include?(cartodbfied_table.id) end end def find_new_tables(cartodbfied_tables) cartodbfied_tables - fetch_user_tables - find_stale_tables(cartodbfied_tables) end # Tables that have been dropped via API but have an old UserTable def find_dropped_tables(cartodbfied_tables) fetch_user_tables - cartodbfied_tables end # Fetches all currently linked user tables def fetch_user_tables results = Carto::UserTable.select([:name, :table_id]).where(user_id: @user.id) results.map do |record| Carto::TableFacade.new(record[:table_id], record[:name], @user.id) end end # Fetches all linkable tables: non raster cartodbfied + raster def fetch_cartodbfied_tables fetch_non_raster_cartodbfied_tables + fetch_raster_tables end # this method searchs for tables with all the columns needed in a cartodb table. # it does not check column types, and only the latest cartodbfication trigger attached (test_quota_per_row) def fetch_non_raster_cartodbfied_tables cartodb_columns = (Table::CARTODB_REQUIRED_COLUMNS + [Table::THE_GEOM_WEBMERCATOR]).map { |col| "'#{col}'" } .join(',') sql = %{ WITH cartodbfied_tables as ( SELECT c.table_name, tg.tgrelid reloid, count(column_name::text) cdb_columns_count FROM information_schema.columns c, pg_tables t, pg_trigger tg WHERE t.tablename = c.table_name AND t.schemaname = c.table_schema AND c.table_schema = '#{@user.database_schema}' AND t.tableowner = '#{@user.database_username}' AND column_name IN (#{cartodb_columns}) AND tg.tgrelid = (quote_ident(t.schemaname) || '.' || quote_ident(t.tablename))::regclass::oid AND tg.tgname = 'test_quota_per_row' GROUP BY reloid, 1) SELECT table_name, reloid FROM cartodbfied_tables WHERE cdb_columns_count = #{cartodb_columns.split(',').length} } @user.in_database(as: :superuser)[sql].all.map do |record| Carto::TableFacade.new(record[:reloid], record[:table_name], @user.id) end end # Find raster tables which won't appear as cartodbfied but MUST be linked def fetch_raster_tables sql = %{ WITH cartodbfied_tables as ( SELECT c.table_name, tg.tgrelid reloid, count(column_name::text) cdb_columns_count FROM information_schema.columns c, pg_tables t, pg_trigger tg WHERE t.tablename = c.table_name AND t.schemaname = c.table_schema AND c.table_schema = '#{@user.database_schema}' AND t.tableowner = '#{@user.database_username}' AND column_name IN ('cartodb_id', 'the_raster_webmercator') AND tg.tgrelid = (quote_ident(t.schemaname) || '.' || quote_ident(t.tablename))::regclass::oid AND tg.tgname = 'test_quota_per_row' GROUP BY reloid, 1) SELECT table_name, reloid FROM cartodbfied_tables WHERE cdb_columns_count = 2; } @user.in_database(as: :superuser)[sql].all.map do |record| Carto::TableFacade.new(record[:reloid], record[:table_name], @user.id) end end end class TableFacade attr_reader :id, :name, :user_id def initialize(id, name, user_id) @id = id @name = name @user_id = user_id end def user @user ||= ::User[@user_id] end def user_table_with_matching_id user.tables.where(table_id: id).first end def user_table_with_matching_name user.tables.where(name: name).first end def create_user_table CartoDB::Logger.debug(message: 'ghost tables', action: 'linking new table', user: user, table_name: name, table_id: id) # TODO: Use Carto::UserTable when it's ready and stop the Table <-> ::UserTable madness new_table = ::Table.new(user_table: ::UserTable.new.set_fields({ user_id: user.id, table_id: id, name: name }, [:user_id, :table_id, :name])) new_table.register_table_only = true new_table.keep_user_database_table = true new_table.save rescue => exception CartoDB::Logger.error(message: 'Ghost tables: Error creating UserTable', exception: exception, user: user, table_name: name, table_id: id) end def rename_user_table_vis CartoDB::Logger.debug(message: 'ghost tables', action: 'relinking renamed table', user: user, table_name: name, table_id: id) user_table_vis = user_table_with_matching_id.table_visualization user_table_vis.register_table_only = true user_table_vis.name = name user_table_vis.store rescue => exception CartoDB::Logger.error(message: 'Ghost tables: Error renaming Visualization', exception: exception, user: user, table_name: name, table_id: id) end def drop_user_table CartoDB::Logger.debug(message: 'ghost tables', action: 'unlinking dropped table', user: user, table_name: name, table_id: id) # TODO: Use Carto::UserTable when it's ready and stop the Table <-> ::UserTable madness table_to_drop = ::Table.new(user_table: user.tables.where(table_id: id, name: name).first) table_to_drop.keep_user_database_table = true table_to_drop.destroy rescue => exception CartoDB::Logger.error(message: 'Ghost tables: Error dropping Table', exception: exception, user: user, table_name: name, table_id: id) end def regenerate_user_table CartoDB::Logger.debug(message: 'ghost tables', action: 'regenerating table_id', user: user, table_name: name, table_id: id) user_table_to_regenerate = user_table_with_matching_name user_table_to_regenerate.table_id = id user_table_to_regenerate.save rescue => exception CartoDB::Logger.error(message: 'Ghost tables: Error syncing table_id for UserTable', exception: exception, user: user, table_name: name, table_id: id) end def eql?(other) id.eql?(other.id) && name.eql?(other.name) && user.id.eql?(other.user_id) end def ==(other) eql?(other) end def hash [id, name, user_id].hash end end end
# # Author:: Adam Jacob (<adam@opscode.com>) # Author:: Seth Chisamore (<schisamo@opscode.com>) # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/knife/ec2_base' class Chef class Knife class Ec2ServerList < Knife include Knife::Ec2Base banner "knife ec2 server list (options)" def run $stdout.sync = true validate! server_list = [ ui.color('Instance ID', :bold), ui.color('Public IP', :bold), ui.color('Private IP', :bold), ui.color('Flavor', :bold), ui.color('Image', :bold), ui.color('SSH Key', :bold), ui.color('Security Groups', :bold), ui.color('State', :bold) ] connection.servers.all.each do |server| server_list << server.id.to_s server_list << server.public_ip_address.to_s server_list << server.private_ip_address.to_s server_list << server.flavor_id.to_s server_list << server.image_id.to_s server_list << server.key_name.to_s server_list << server.groups.join(", ") server_list << begin state = server.state.to_s.downcase case state when 'shutting-down','terminated','stopping','stopped' ui.color(state, :red) when 'pending' ui.color(state, :yellow) else ui.color(state, :green) end end end puts ui.list(server_list, :columns_across, 8) end end end end switch to uneven_columns_across for prettier output # # Author:: Adam Jacob (<adam@opscode.com>) # Author:: Seth Chisamore (<schisamo@opscode.com>) # Copyright:: Copyright (c) 2010-2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/knife/ec2_base' class Chef class Knife class Ec2ServerList < Knife include Knife::Ec2Base banner "knife ec2 server list (options)" def run $stdout.sync = true validate! server_list = [ ui.color('Instance ID', :bold), ui.color('Public IP', :bold), ui.color('Private IP', :bold), ui.color('Flavor', :bold), ui.color('Image', :bold), ui.color('SSH Key', :bold), ui.color('Security Groups', :bold), ui.color('State', :bold) ] connection.servers.all.each do |server| server_list << server.id.to_s server_list << server.public_ip_address.to_s server_list << server.private_ip_address.to_s server_list << server.flavor_id.to_s server_list << server.image_id.to_s server_list << server.key_name.to_s server_list << server.groups.join(", ") server_list << begin state = server.state.to_s.downcase case state when 'shutting-down','terminated','stopping','stopped' ui.color(state, :red) when 'pending' ui.color(state, :yellow) else ui.color(state, :green) end end end puts ui.list(server_list, :uneven_columns_across, 8) end end end end
# # Author:: Ezra Pagel (<ezra@cpan.org>) # License:: Apache License, Version 2.0 # require 'chef/knife' require 'chef/knife/BaseVsphereCommand' # Lists all known virtual machines in the configured datacenter class Chef::Knife::VsphereVmList < Chef::Knife::BaseVsphereCommand banner "knife vsphere vm list" get_common_options option :recursive, :long => "--recursive", :short => "-r", :description => "Recurse down through sub-folders" option :only_folders, :long => "--only-folders", :description => "Print only sub-folders" def traverse_folders(folder) puts "#{ui.color("Folder", :cyan)}: "+(folder.path[3..-1].map{|x| x[1]}.*'/') print_vms_in_folder(folder) unless config[:only_folders] folders = find_all_in_folder(folder, RbVmomi::VIM::Folder) folders.each do |child| traverse_folders(child) end end def print_vms_in_folder(folder) vms = find_all_in_folder(folder, RbVmomi::VIM::VirtualMachine) vms.each do |vm| puts "#{ui.color("VM Name", :cyan)}: #{vm.name}" end end def run $stdout.sync = true vim = get_vim_connection baseFolder = find_folder(config[:folder]); if config[:recursive] traverse_folders(baseFolder) else print_vms_in_folder(baseFolder) end end end vm_list: show subfolder list when not recursing them # # Author:: Ezra Pagel (<ezra@cpan.org>) # License:: Apache License, Version 2.0 # require 'chef/knife' require 'chef/knife/BaseVsphereCommand' # Lists all known virtual machines in the configured datacenter class Chef::Knife::VsphereVmList < Chef::Knife::BaseVsphereCommand banner "knife vsphere vm list" get_common_options option :recursive, :long => "--recursive", :short => "-r", :description => "Recurse down through sub-folders" option :only_folders, :long => "--only-folders", :description => "Print only sub-folders" def traverse_folders(folder) puts "#{ui.color("Folder", :cyan)}: "+(folder.path[3..-1].map{|x| x[1]}.*'/') print_vms_in_folder(folder) unless config[:only_folders] folders = find_all_in_folder(folder, RbVmomi::VIM::Folder) folders.each do |child| traverse_folders(child) end end def print_vms_in_folder(folder) vms = find_all_in_folder(folder, RbVmomi::VIM::VirtualMachine) vms.each do |vm| puts "#{ui.color("VM Name", :cyan)}: #{vm.name}" end end def print_subfolders(folder) folders = find_all_in_folder(folder, RbVmomi::VIM::Folder) folders.each do |subfolder| puts "#{ui.color("Folder Name", :cyan)}: #{subfolder.name}" end end def run $stdout.sync = true vim = get_vim_connection baseFolder = find_folder(config[:folder]); if config[:recursive] traverse_folders(baseFolder) else print_subfolders(baseFolder) print_vms_in_folder(baseFolder) end end end
added stub version command module Cloudkick::Command class Version < Base def index end end end
require 'contracts' require 'moneta' require 'securerandom' require_relative 'amazon' require_relative 'config' require_relative 'errors' require_relative 'hdp/bootstrap_properties' require_relative 'ssh' module Cloudstrap class BootstrapAgent include ::Contracts::Core include ::Contracts::Builtin Contract None => BootstrapAgent def initialize validate_configuration! self end Contract None => Any def validate_configuration! # TODO: Does this really belong in BootstrapAgent? return if ec2.valid_region?(config.region) raise ::Cloudstrap::ConfigurationError, "Region #{config.region} is not valid" end Contract None => String def create_vpc cache.store(:vpc_id, ec2.create_vpc.vpc_id).tap do |vpc_id| ec2.assign_name(bootstrap_tag, vpc_id) end end Contract None => Maybe[String] def find_vpc ENV.fetch('BOOTSTRAP_VPC_ID') do cache.fetch(:vpc_id) do cache.store :vpc_id, ec2 .tagged(type: 'vpc', value: bootstrap_tag) .map(&:resource_id) .first end end end Contract None => String def internet_gateway find_internet_gateway || create_internet_gateway end Contract None => String def create_internet_gateway cache.store(:internet_gateway_id, ec2.create_internet_gateway.internet_gateway_id ).tap { |internet_gateway_id| ec2.assign_name bootstrap_tag, internet_gateway_id } end Contract None => String def nat_gateway_ip_allocation ENV.fetch('BOOTSTRAP_NAT_GATEWAY_ALLOCATION_ID') do cache.fetch(:nat_gateway_allocation_id) do # TODO: Simplify this. id = ec2 .nat_gateways .select { |nat_gateway| nat_gateway.vpc_id == vpc } .flat_map { |nat_gateway| nat_gateway.nat_gateway_addresses.map { |address| address.allocation_id } } .first || ec2.unassociated_address || ec2.create_address cache.store(:nat_gateway_allocation_id, id) end end end Contract None => Maybe[String] def find_nat_gateway ec2 .nat_gateways .select { |nat_gateway| nat_gateway.vpc_id == vpc } .reject { |nat_gateway| %w(failed deleted).include? nat_gateway.state } .map { |nat_gateway| nat_gateway.nat_gateway_id } .first end Contract None => String def create_nat_gateway attach_gateway unless ec2.internet_gateway_attached?(internet_gateway, vpc) ec2.create_nat_gateway(public_subnet, nat_gateway_ip_allocation).nat_gateway_id end Contract None => String def nat_gateway ENV.fetch('BOOTSTRAP_NAT_GATEWAY_ID') do cache.fetch(:nat_gateway_id) do cache.store(:nat_gateway_id, (find_nat_gateway || create_nat_gateway)) end end end Contract None => Maybe[String] def find_internet_gateway ENV.fetch('BOOTSTRAP_INTERNET_GATEWAY_ID') do cache.fetch(:internet_gateway_id) do find_tagged_internet_gateway || find_internet_gateway_for_vpc end end end Contract None => Maybe[String] def find_tagged_internet_gateway ec2 .tagged(type: 'internet-gateway', value: bootstrap_tag) .map { |resource| resource.resource.id } .first end Contract None => Maybe[String] def find_internet_gateway_for_vpc ec2 .internet_gateways .select { |gateway| gateway.attachments.any? { |attachment| attachment.vpc_id == vpc } } .map { |gateway| gateway.internet_gateway_id } .first end Contract None => String def create_jumpbox_security_group cache.store(:jumpbox_security_group, ec2.create_security_group(:jumpbox, vpc)).tap do |sg| ec2.assign_name(bootstrap_tag, sg) end end Contract None => Maybe[String] def find_jumpbox_security_group @jumpbox_security_group ||= ENV.fetch('BOOTSTRAP_JUMPBOX_SECURITY_GROUP') do cache.fetch(:jumpbox_security_group) do cache.store :jumpbox_security_group, ec2 .tagged(type: 'security-group', value: bootstrap_tag) .map(&:resource_id) .first end end end Contract None => Bool def allow_ssh ec2.authorize_security_group_ingress :tcp, 22, '0.0.0.0/0', jumpbox_security_group end Contract None => String def jumpbox_security_group find_jumpbox_security_group || create_jumpbox_security_group end Contract None => String def private_subnet @private_subnet ||= ENV.fetch('BOOTSTRAP_PRIVATE_SUBNET_ID') do cache.fetch(:private_subnet_id) do properties = { vpc_id: vpc, cidr_block: config.private_cidr_block } cache.store(:private_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet| ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag| tag.key == 'Name' && tag.value = bootstrap_tag end end.subnet_id) end end end Contract None => String def public_subnet @public_subnet ||= ENV.fetch('BOOTSTRAP_PUBLIC_SUBNET_ID') do cache.fetch(:public_subnet_id) do properties = { vpc_id: vpc, cidr_block: config.public_cidr_block } cache.store(:public_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet| ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag| tag.key == 'Name' && tag.value = bootstrap_tag end end.subnet_id) end end end Contract None => String def route_table @route_table ||= ENV.fetch('BOOTSTRAP_ROUTE_TABLE_ID') do cache.fetch(:route_table_id) do cache.store(:route_table_id, ec2 .route_tables .select { |route_table| route_table.vpc_id == vpc } .select { |route_table| route_table.associations.any? { |association| association.main } } .map { |route_table| route_table.route_table_id } .first).tap do |route_table_id| ec2.assign_name bootstrap_tag, route_table_id end end end end Contract None => String def private_route_table @private_route_table ||= ENV.fetch('BOOTSTRAP_PRIVATE_ROUTE_TABLE_ID') do cache.fetch(:private_route_table_id) do id = ec2 .route_tables .select { |route_table| route_table.vpc_id == vpc } .reject { |route_table| route_table.associations.any? { |association| association.main } } .map { |route_table| route_table.route_table_id } .first || ec2.create_route_table(vpc).route_table_id cache.store(:private_route_table_id, id).tap do |private_route_table_id| ec2.assign_name bootstrap_tag, private_route_table_id end end end end Contract None => Bool def attach_gateway ec2.attach_internet_gateway internet_gateway, vpc # TODO: Cache this end Contract None => Bool def default_route ec2.create_route('0.0.0.0/0', internet_gateway, route_table) # TODO: Cache this end Contract None => Bool def nat_route ec2.create_route('0.0.0.0/0', nat_gateway, private_route_table) # TODO: Cache this end Contract None => String def nat_route_association @nat_route_association || ENV.fetch('BOOTSTRAP_NAT_ROUTE_ASSOCIATION_ID') do cache.fetch(:nat_route_association_id) do cache.store(:nat_route_association_id, ec2.associate_route_table(private_route_table, private_subnet)) end end end Contract None => ArrayOf[String] def subnets [public_subnet, private_subnet] end Contract None => Bool def enable_public_ips ec2.map_public_ip_on_launch?(public_subnet) || ec2.map_public_ip_on_launch(public_subnet, true) end Contract None => String def vpc find_vpc || create_vpc end Contract None => Bool def enable_dns_support ec2.vpc_supports_dns?(vpc) || ec2.enable_dns_support(vpc) end Contract None => Bool def enable_dns_hostnames ec2.vpc_supports_dns_hostnames?(vpc) || ec2.enable_dns_hostnames(vpc) end Contract None => String def create_jumpbox upload_ssh_key cache.store(:jumpbox_id, ec2.create_instance( image_id: ami, instance_type: config.instance_type, key_name: bootstrap_tag, client_token: Digest::SHA256.hexdigest(bootstrap_tag), network_interfaces: [{ device_index: 0, subnet_id: public_subnet, associate_public_ip_address: true, groups: [jumpbox_security_group] }] ).instance_id).tap do |instance_id| ec2.assign_name bootstrap_tag, instance_id end end Contract None => Maybe[String] def find_jumpbox ENV.fetch('BOOTSTRAP_JUMPBOX_ID') do cache.fetch(:jumpbox_id) do ec2 .tagged(type: 'instance', value: bootstrap_tag) .map(&:resource_id) .first end end end Contract None => String def jumpbox find_jumpbox || create_jumpbox end Contract None => Bool def tag_jumpbox ec2.create_tags([jumpbox], [{ key: 'Cloudstrapped', value: 'true' }]) end Contract None => String def ami @ami ||= ENV.fetch('BOOTSTRAP_AMI') do cache.fetch(:ami_id) do cache.store :ami_id, ec2.latest_ubuntu(config.ubuntu_release).image_id end end end Contract None => String def upload_ssh_key ec2.import_key_pair bootstrap_tag, ssh_key.to_s # TODO: Cache this. end Contract None => SSH::Key def ssh_key @ssh_key ||= SSH::Key.new bootstrap_tag end Contract None => String def bootstrap_tag @bootstrap_tag ||= ENV.fetch('BOOTSTRAP_TAG') do "lkg@#{username}/#{uuid}" end end Contract None => String def username @username ||= ENV.fetch('BOOTSTRAP_USERNAME') do cache.fetch(:username) do cache.store(:username, iam.user.user_name) end end end Contract None => String def uuid @uuid ||= ENV.fetch('BOOTSTRAP_UUID') do cache.fetch(:uuid) do cache.store(:uuid, SecureRandom.uuid) end end end Contract None => String def public_availability_zone @public_availability_zone ||= ENV.fetch('BOOTSTRAP_PUBLIC_AVAILABILITY_ZONE') do cache.fetch(:public_availability_zone) do cache.store(:public_availability_zone, ec2 .subnets .select { |subnet| subnet.subnet_id == public_subnet } .map { |subnet| subnet.availability_zone } .first) end end end Contract None => String def private_availability_zone @private_availability_zone ||= ENV.fetch('BOOTSTRAP_PRIVATE_AVAILABILITY_ZONE') do cache.fetch(:private_availability_zone) do cache.store(:private_availability_zone, ec2 .subnets .select { |subnet| subnet.subnet_id == private_subnet } .map { |subnet| subnet.availability_zone } .first) end end end Contract None => String def jumpbox_ip @jumpbox_ip ||= ENV.fetch('BOOTSTRAP_JUMPBOX_IP') do cache.fetch(:jumpbox_ip) do cache.store(:jumpbox_ip, ec2 .instances .select { |instance| instance.instance_id == jumpbox } .flat_map(&:network_interfaces) .map(&:association) .map(&:public_ip) .first) end end end Contract None => Bool def configure_hdp bootstrap_properties .update('Provider', 'AWS') .update('AWS.Region', config.region) .update('AWS.AvailabilityZones', public_availability_zone) .update('AWS.PublicSubnetIDsAndAZ', [public_subnet, public_availability_zone].join(':')) .update('AWS.PrivateSubnetIDsAndAZ', [private_subnet, private_availability_zone].join(':')) .update('AWS.Keypair', bootstrap_tag) .update('AWS.KeypairFile', '/home/ubuntu/.ssh/id_rsa') .update('AWS.JumpboxCIDR', '0.0.0.0/0') .update('AWS.VPCID', vpc) .update('AWS.LinuxAMI', ami) .upcase('HCPDomainName', config.domain_name) .save! end Contract None => Bool def jumpbox_running? ec2 .instances .select { |instance| instance.instance_id == jumpbox } .map { |instance| instance.state.name } .first == 'running' end Contract None => Any def configure_jumpbox private_key = ssh_key.private_file properties = bootstrap_properties.file package = config.hdp_package_url ssh.to(jumpbox_ip) do '/home/ubuntu/.ssh/id_rsa'.tap do |target| execute :rm, '-f', target upload! private_key, target execute :chmod, '-w', target end upload! properties, '/home/ubuntu/bootstrap.properties' as :root do execute :apt, *%w(install --assume-yes genisoimage aria2) execute :rm, '-f', '/opt/bootstrap.deb' execute :aria2c, '--continue=true', '--dir=/opt', '--out=bootstrap.deb', package execute :dpkg, *%w(--install /opt/bootstrap.deb) end end end Contract None => Bool def requires_human_oversight? ['false', 'nil', nil].include? ENV['BOOTSTRAP_WITHOUT_HUMAN_OVERSIGHT'] end Contract None => Any def launch return false if requires_human_oversight? access_key_id = ec2.api.config.credentials.credentials.access_key_id secret_access_key = ec2.api.config.credentials.credentials.secret_access_key ssh.to(jumpbox_ip) do with(aws_access_key_id: access_key_id, aws_secret_access_key: secret_access_key) do execute :bootstrap, *%w(install bootstrap.properties) end end end private Contract None => SSH::Client def ssh @ssh ||= SSH::Client.new(ssh_key.private_file) end Contract None => HDP::BootstrapProperties def bootstrap_properties @hdp ||= HDP::BootstrapProperties.new end Contract None => Amazon::EC2 def ec2 @ec2 ||= Amazon::EC2.new end Contract None => Amazon::IAM def iam @iam ||= Amazon::IAM.new end Contract None => Config def config @config ||= Config.new end Contract None => Moneta::Proxy def cache @cache ||= Moneta.new :File, dir: config.cache_path end end end ... upcase and update are not the same method. Derp. require 'contracts' require 'moneta' require 'securerandom' require_relative 'amazon' require_relative 'config' require_relative 'errors' require_relative 'hdp/bootstrap_properties' require_relative 'ssh' module Cloudstrap class BootstrapAgent include ::Contracts::Core include ::Contracts::Builtin Contract None => BootstrapAgent def initialize validate_configuration! self end Contract None => Any def validate_configuration! # TODO: Does this really belong in BootstrapAgent? return if ec2.valid_region?(config.region) raise ::Cloudstrap::ConfigurationError, "Region #{config.region} is not valid" end Contract None => String def create_vpc cache.store(:vpc_id, ec2.create_vpc.vpc_id).tap do |vpc_id| ec2.assign_name(bootstrap_tag, vpc_id) end end Contract None => Maybe[String] def find_vpc ENV.fetch('BOOTSTRAP_VPC_ID') do cache.fetch(:vpc_id) do cache.store :vpc_id, ec2 .tagged(type: 'vpc', value: bootstrap_tag) .map(&:resource_id) .first end end end Contract None => String def internet_gateway find_internet_gateway || create_internet_gateway end Contract None => String def create_internet_gateway cache.store(:internet_gateway_id, ec2.create_internet_gateway.internet_gateway_id ).tap { |internet_gateway_id| ec2.assign_name bootstrap_tag, internet_gateway_id } end Contract None => String def nat_gateway_ip_allocation ENV.fetch('BOOTSTRAP_NAT_GATEWAY_ALLOCATION_ID') do cache.fetch(:nat_gateway_allocation_id) do # TODO: Simplify this. id = ec2 .nat_gateways .select { |nat_gateway| nat_gateway.vpc_id == vpc } .flat_map { |nat_gateway| nat_gateway.nat_gateway_addresses.map { |address| address.allocation_id } } .first || ec2.unassociated_address || ec2.create_address cache.store(:nat_gateway_allocation_id, id) end end end Contract None => Maybe[String] def find_nat_gateway ec2 .nat_gateways .select { |nat_gateway| nat_gateway.vpc_id == vpc } .reject { |nat_gateway| %w(failed deleted).include? nat_gateway.state } .map { |nat_gateway| nat_gateway.nat_gateway_id } .first end Contract None => String def create_nat_gateway attach_gateway unless ec2.internet_gateway_attached?(internet_gateway, vpc) ec2.create_nat_gateway(public_subnet, nat_gateway_ip_allocation).nat_gateway_id end Contract None => String def nat_gateway ENV.fetch('BOOTSTRAP_NAT_GATEWAY_ID') do cache.fetch(:nat_gateway_id) do cache.store(:nat_gateway_id, (find_nat_gateway || create_nat_gateway)) end end end Contract None => Maybe[String] def find_internet_gateway ENV.fetch('BOOTSTRAP_INTERNET_GATEWAY_ID') do cache.fetch(:internet_gateway_id) do find_tagged_internet_gateway || find_internet_gateway_for_vpc end end end Contract None => Maybe[String] def find_tagged_internet_gateway ec2 .tagged(type: 'internet-gateway', value: bootstrap_tag) .map { |resource| resource.resource.id } .first end Contract None => Maybe[String] def find_internet_gateway_for_vpc ec2 .internet_gateways .select { |gateway| gateway.attachments.any? { |attachment| attachment.vpc_id == vpc } } .map { |gateway| gateway.internet_gateway_id } .first end Contract None => String def create_jumpbox_security_group cache.store(:jumpbox_security_group, ec2.create_security_group(:jumpbox, vpc)).tap do |sg| ec2.assign_name(bootstrap_tag, sg) end end Contract None => Maybe[String] def find_jumpbox_security_group @jumpbox_security_group ||= ENV.fetch('BOOTSTRAP_JUMPBOX_SECURITY_GROUP') do cache.fetch(:jumpbox_security_group) do cache.store :jumpbox_security_group, ec2 .tagged(type: 'security-group', value: bootstrap_tag) .map(&:resource_id) .first end end end Contract None => Bool def allow_ssh ec2.authorize_security_group_ingress :tcp, 22, '0.0.0.0/0', jumpbox_security_group end Contract None => String def jumpbox_security_group find_jumpbox_security_group || create_jumpbox_security_group end Contract None => String def private_subnet @private_subnet ||= ENV.fetch('BOOTSTRAP_PRIVATE_SUBNET_ID') do cache.fetch(:private_subnet_id) do properties = { vpc_id: vpc, cidr_block: config.private_cidr_block } cache.store(:private_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet| ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag| tag.key == 'Name' && tag.value = bootstrap_tag end end.subnet_id) end end end Contract None => String def public_subnet @public_subnet ||= ENV.fetch('BOOTSTRAP_PUBLIC_SUBNET_ID') do cache.fetch(:public_subnet_id) do properties = { vpc_id: vpc, cidr_block: config.public_cidr_block } cache.store(:public_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet| ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag| tag.key == 'Name' && tag.value = bootstrap_tag end end.subnet_id) end end end Contract None => String def route_table @route_table ||= ENV.fetch('BOOTSTRAP_ROUTE_TABLE_ID') do cache.fetch(:route_table_id) do cache.store(:route_table_id, ec2 .route_tables .select { |route_table| route_table.vpc_id == vpc } .select { |route_table| route_table.associations.any? { |association| association.main } } .map { |route_table| route_table.route_table_id } .first).tap do |route_table_id| ec2.assign_name bootstrap_tag, route_table_id end end end end Contract None => String def private_route_table @private_route_table ||= ENV.fetch('BOOTSTRAP_PRIVATE_ROUTE_TABLE_ID') do cache.fetch(:private_route_table_id) do id = ec2 .route_tables .select { |route_table| route_table.vpc_id == vpc } .reject { |route_table| route_table.associations.any? { |association| association.main } } .map { |route_table| route_table.route_table_id } .first || ec2.create_route_table(vpc).route_table_id cache.store(:private_route_table_id, id).tap do |private_route_table_id| ec2.assign_name bootstrap_tag, private_route_table_id end end end end Contract None => Bool def attach_gateway ec2.attach_internet_gateway internet_gateway, vpc # TODO: Cache this end Contract None => Bool def default_route ec2.create_route('0.0.0.0/0', internet_gateway, route_table) # TODO: Cache this end Contract None => Bool def nat_route ec2.create_route('0.0.0.0/0', nat_gateway, private_route_table) # TODO: Cache this end Contract None => String def nat_route_association @nat_route_association || ENV.fetch('BOOTSTRAP_NAT_ROUTE_ASSOCIATION_ID') do cache.fetch(:nat_route_association_id) do cache.store(:nat_route_association_id, ec2.associate_route_table(private_route_table, private_subnet)) end end end Contract None => ArrayOf[String] def subnets [public_subnet, private_subnet] end Contract None => Bool def enable_public_ips ec2.map_public_ip_on_launch?(public_subnet) || ec2.map_public_ip_on_launch(public_subnet, true) end Contract None => String def vpc find_vpc || create_vpc end Contract None => Bool def enable_dns_support ec2.vpc_supports_dns?(vpc) || ec2.enable_dns_support(vpc) end Contract None => Bool def enable_dns_hostnames ec2.vpc_supports_dns_hostnames?(vpc) || ec2.enable_dns_hostnames(vpc) end Contract None => String def create_jumpbox upload_ssh_key cache.store(:jumpbox_id, ec2.create_instance( image_id: ami, instance_type: config.instance_type, key_name: bootstrap_tag, client_token: Digest::SHA256.hexdigest(bootstrap_tag), network_interfaces: [{ device_index: 0, subnet_id: public_subnet, associate_public_ip_address: true, groups: [jumpbox_security_group] }] ).instance_id).tap do |instance_id| ec2.assign_name bootstrap_tag, instance_id end end Contract None => Maybe[String] def find_jumpbox ENV.fetch('BOOTSTRAP_JUMPBOX_ID') do cache.fetch(:jumpbox_id) do ec2 .tagged(type: 'instance', value: bootstrap_tag) .map(&:resource_id) .first end end end Contract None => String def jumpbox find_jumpbox || create_jumpbox end Contract None => Bool def tag_jumpbox ec2.create_tags([jumpbox], [{ key: 'Cloudstrapped', value: 'true' }]) end Contract None => String def ami @ami ||= ENV.fetch('BOOTSTRAP_AMI') do cache.fetch(:ami_id) do cache.store :ami_id, ec2.latest_ubuntu(config.ubuntu_release).image_id end end end Contract None => String def upload_ssh_key ec2.import_key_pair bootstrap_tag, ssh_key.to_s # TODO: Cache this. end Contract None => SSH::Key def ssh_key @ssh_key ||= SSH::Key.new bootstrap_tag end Contract None => String def bootstrap_tag @bootstrap_tag ||= ENV.fetch('BOOTSTRAP_TAG') do "lkg@#{username}/#{uuid}" end end Contract None => String def username @username ||= ENV.fetch('BOOTSTRAP_USERNAME') do cache.fetch(:username) do cache.store(:username, iam.user.user_name) end end end Contract None => String def uuid @uuid ||= ENV.fetch('BOOTSTRAP_UUID') do cache.fetch(:uuid) do cache.store(:uuid, SecureRandom.uuid) end end end Contract None => String def public_availability_zone @public_availability_zone ||= ENV.fetch('BOOTSTRAP_PUBLIC_AVAILABILITY_ZONE') do cache.fetch(:public_availability_zone) do cache.store(:public_availability_zone, ec2 .subnets .select { |subnet| subnet.subnet_id == public_subnet } .map { |subnet| subnet.availability_zone } .first) end end end Contract None => String def private_availability_zone @private_availability_zone ||= ENV.fetch('BOOTSTRAP_PRIVATE_AVAILABILITY_ZONE') do cache.fetch(:private_availability_zone) do cache.store(:private_availability_zone, ec2 .subnets .select { |subnet| subnet.subnet_id == private_subnet } .map { |subnet| subnet.availability_zone } .first) end end end Contract None => String def jumpbox_ip @jumpbox_ip ||= ENV.fetch('BOOTSTRAP_JUMPBOX_IP') do cache.fetch(:jumpbox_ip) do cache.store(:jumpbox_ip, ec2 .instances .select { |instance| instance.instance_id == jumpbox } .flat_map(&:network_interfaces) .map(&:association) .map(&:public_ip) .first) end end end Contract None => Bool def configure_hdp bootstrap_properties .update('Provider', 'AWS') .update('AWS.Region', config.region) .update('AWS.AvailabilityZones', public_availability_zone) .update('AWS.PublicSubnetIDsAndAZ', [public_subnet, public_availability_zone].join(':')) .update('AWS.PrivateSubnetIDsAndAZ', [private_subnet, private_availability_zone].join(':')) .update('AWS.Keypair', bootstrap_tag) .update('AWS.KeypairFile', '/home/ubuntu/.ssh/id_rsa') .update('AWS.JumpboxCIDR', '0.0.0.0/0') .update('AWS.VPCID', vpc) .update('AWS.LinuxAMI', ami) .update('HCPDomainName', config.domain_name) .save! end Contract None => Bool def jumpbox_running? ec2 .instances .select { |instance| instance.instance_id == jumpbox } .map { |instance| instance.state.name } .first == 'running' end Contract None => Any def configure_jumpbox private_key = ssh_key.private_file properties = bootstrap_properties.file package = config.hdp_package_url ssh.to(jumpbox_ip) do '/home/ubuntu/.ssh/id_rsa'.tap do |target| execute :rm, '-f', target upload! private_key, target execute :chmod, '-w', target end upload! properties, '/home/ubuntu/bootstrap.properties' as :root do execute :apt, *%w(install --assume-yes genisoimage aria2) execute :rm, '-f', '/opt/bootstrap.deb' execute :aria2c, '--continue=true', '--dir=/opt', '--out=bootstrap.deb', package execute :dpkg, *%w(--install /opt/bootstrap.deb) end end end Contract None => Bool def requires_human_oversight? ['false', 'nil', nil].include? ENV['BOOTSTRAP_WITHOUT_HUMAN_OVERSIGHT'] end Contract None => Any def launch return false if requires_human_oversight? access_key_id = ec2.api.config.credentials.credentials.access_key_id secret_access_key = ec2.api.config.credentials.credentials.secret_access_key ssh.to(jumpbox_ip) do with(aws_access_key_id: access_key_id, aws_secret_access_key: secret_access_key) do execute :bootstrap, *%w(install bootstrap.properties) end end end private Contract None => SSH::Client def ssh @ssh ||= SSH::Client.new(ssh_key.private_file) end Contract None => HDP::BootstrapProperties def bootstrap_properties @hdp ||= HDP::BootstrapProperties.new end Contract None => Amazon::EC2 def ec2 @ec2 ||= Amazon::EC2.new end Contract None => Amazon::IAM def iam @iam ||= Amazon::IAM.new end Contract None => Config def config @config ||= Config.new end Contract None => Moneta::Proxy def cache @cache ||= Moneta.new :File, dir: config.cache_path end end end
# Copyright © Mapotempo, 2018 # # This file is part of Mapotempo. # # Mapotempo is free software. You can redistribute it and/or # modify since you respect the terms of the GNU Affero General # Public License as published by the Free Software Foundation, # either version 3 of the License, or (at your option) any later version. # # Mapotempo is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the Licenses for more details. # # You should have received a copy of the GNU Affero General Public License # along with Mapotempo. If not, see: # <http://www.gnu.org/licenses/agpl.html> # require 'ai4r' require './lib/helper.rb' module Ai4r module Clusterers class BalancedKmeans < KMeans attr_reader :cluster_metrics parameters_info max_iterations: 'Maximum number of iterations to ' \ 'build the clusterer. By default it is uncapped.', centroid_function: 'Custom implementation to calculate the ' \ 'centroid of a cluster. It must be a closure receiving an array of ' \ 'data sets, and return an array of data items, representing the ' \ 'centroids of for each data set. ' \ 'By default, this algorithm returns a data items using the mode '\ 'or mean of each attribute on each data set.', centroid_indices: 'Indices of data items (indexed from 0) to be ' \ 'the initial centroids. Otherwise, the initial centroids will be ' \ 'assigned randomly from the data set.', on_empty: 'Action to take if a cluster becomes empty, with values ' \ "'eliminate' (the default action, eliminate the empty cluster), " \ "'terminate' (terminate with error), 'random' (relocate the " \ "empty cluster to a random point) ", expected_caracteristics: 'Expected sets of caracteristics for generated clusters', possible_caracteristics_combination: 'Set of skills we can combine in the same cluster.', impossible_day_combination: 'Maximum set of conflicting days.' # Build a new clusterer, using data examples found in data_set. # Items will be clustered in "number_of_clusters" different # clusters. def build(data_set, unit_symbols, number_of_clusters, cut_symbol, cut_limit, output_centroids, options = {}) @data_set = data_set reduced_number_of_clusters = [number_of_clusters, data_set.data_items.collect{ |data_item| [data_item[0], data_item[1]] }.uniq.size].min unless reduced_number_of_clusters == number_of_clusters || @centroid_indices.empty? @centroid_indices = @centroid_indices.collect{ |centroid_index| [@data_set.data_items[centroid_index], centroid_index] }.uniq{ |item| [item.first[0], item.first[1]] }.collect(&:last) end @number_of_clusters = reduced_number_of_clusters @cut_limit = cut_limit @cut_symbol = cut_symbol @output_centroids = output_centroids @unit_symbols = unit_symbols @centroid_function = lambda do |clusters| clusters.collect{ |cluster_data_points| get_mean_or_mode(cluster_data_points) } end raise ArgumentError, 'Length of centroid indices array differs from the specified number of clusters' unless @centroid_indices.empty? || @centroid_indices.length == @number_of_clusters raise ArgumentError, 'Invalid value for on_empty' unless @on_empty == 'eliminate' || @on_empty == 'terminate' || @on_empty == 'random' || @on_empty == 'outlier' @iterations = 0 if @cut_symbol @total_cut_load = @data_set.data_items.inject(0) { |sum, d| sum + d[3][@cut_symbol] } if @total_cut_load.zero? @cut_symbol = nil # Disable balanacing because there is no point else @data_set.data_items.sort_by!{ |x| x[3][@cut_symbol] ? -x[3][@cut_symbol] : 0 } data_length = @data_set.data_items.size @data_set.data_items[(data_length * 0.1).to_i..(data_length * 0.90).to_i] = @data_set.data_items[(data_length * 0.1).to_i..(data_length * 0.90).to_i].shuffle! end end calc_initial_centroids @rate_balance = 0.0 until stop_criteria_met @rate_balance = 1.0 - (0.2 * @iterations / @max_iterations) if @cut_symbol update_cut_limit calculate_membership_clusters #sort_clusters recompute_centroids end if options[:last_iteration_balance_rate] @rate_balance = options[:last_iteration_balance_rate] update_cut_limit calculate_membership_clusters #sort_clusters recompute_centroids end puts "Clustering converged after #{@iterations} iterations.\n" self end def num_attributes(data_items) return (data_items.empty?) ? 0 : data_items.first.size end # Get the sample mean def mean(data_items, index) sum = 0.0 data_items.each { |item| sum += item[index] } return sum / data_items.length end # Get the sample mode. def mode(data_items, index) count = Hash.new {0} max_count = 0 mode = nil data_items.each do |data_item| attr_value = data_item[index] attr_count = (count[attr_value] += 1) if attr_count > max_count mode = attr_value max_count = attr_count end end return mode end def mode_not_nil(data_items, index) count = Hash.new {0} max_count = 0 mode = nil data_items.each do |data_item| attr_value = data_item[index] attr_count = (count[attr_value] += attr_value.nil? ? 0 : 1) if attr_count > max_count mode = attr_value max_count = attr_count end end return mode end def get_mean_or_mode(data_set) data_items = data_set.data_items mean = [] num_attributes(data_items).times do |i| mean[i] = if data_items.first[i].is_a?(Numeric) mean(data_items, i) elsif i == 4 mode_not_nil(data_items, i) else mode(data_items, i) end end return mean end def recompute_centroids @old_centroids = @centroids data_sticky = @centroids.collect{ |data| data[4] } data_skill = @centroids.collect{ |data| data[5] } data_size = @centroids.collect{ |data| data[6] } @centroids.collect!{ |centroid| centroid[4] = nil centroid[5] = [] centroid[6] = 0 centroid.compact } @iterations += 1 @centroids = @centroid_function.call(@clusters) if @cut_symbol #if there is balancing. @centroids.each_with_index { |centroid, index| #move the data_points closest to the centroid centers so that balancing can start early point_closest_to_centroid_center = clusters[index].data_items.min_by{ |data_point| Helper::flying_distance(centroid, data_point) } @data_set.data_items.insert(0, @data_set.data_items.delete(point_closest_to_centroid_center)) #move it to the top #correct the distance_from_and_to_depot info of the new cluster with the average of the points centroid[3][:duration_from_and_to_depot] = @clusters[index].data_items.map { |d| d[3][:duration_from_and_to_depot] }.sum / @clusters[index].data_items.size } end @old_centroids.collect!.with_index{ |data, index| data_item = @data_set.data_items.find{ |data_item| data_item[2] == data[2] } data_item[4] = data_sticky[index] data_item[5] = data_skill[index] data_item[6] = data_size[index] data_item } @centroids.each_with_index{ |data, index| data[4] = data_sticky[index] data[5] = data_skill[index] data[6] = data_size[index] } @centroids.each_with_index{ |centroid, index| @centroid_indices[index] = @data_set.data_items.find_index{ |data| data[2] == centroid[2] } } end # Classifies the given data item, returning the cluster index it belongs # to (0-based). def eval(data_item) get_min_index(@centroids.collect.with_index{ |centroid, cluster_index| distance(data_item, centroid, cluster_index) }) end protected def compute_compatibility(caracteristics_a, caracteristics_b, cluster_index) # TODO : not differenciate day skills and skills and simplify hard_violation = false non_common_number = 0 if !(caracteristics_a - caracteristics_b).empty? # all required skills are not available in centroid new_day_caracteristics = (caracteristics_a + caracteristics_b).select{ |car| car.include?('not_day') }.uniq if new_day_caracteristics.uniq.size == @impossible_day_combination.size hard_violation = true else non_common_number += (new_day_caracteristics - caracteristics_b).size end new_caracteristics = (caracteristics_a + caracteristics_b).reject{ |car| car.include?('not_day') }.uniq if !@possible_caracteristics_combination.any?{ |combination| new_caracteristics.all?{ |car| combination.include?(car) } } hard_violation = true else non_common_number += (new_caracteristics - caracteristics_b).size end end if @expected_caracteristics conflicting_caracteristics = caracteristics_a.select{ |c| @expected_caracteristics.include?(c) && !@centroids[cluster_index][5].include?(c) } hard_violation = conflicting_caracteristics.any?{ |c| @centroids.select{ |centroid| centroid[5].include?(c) }.size == @expected_caracteristics.count(c) } if !hard_violation end [hard_violation, non_common_number] end def distance(a, b, cluster_index) # TODO : rename a & b ? fly_distance = Helper.flying_distance(a, b) cut_value = @cluster_metrics[cluster_index][@cut_symbol].to_f limit = if @cut_limit.is_a? Array @cut_limit[cluster_index][:limit] else @cut_limit[:limit] end # caracteristics compatibility hard_violation, non_common_number = a[5].empty? ? [false, 0] : compute_compatibility(a[5], b[5], cluster_index) compatibility = if a[4] && b[4] && (b[4] & a[4]).empty? || # if service sticky or skills are different than centroids sticky/skills, hard_violation # or if services skills have no match 2**32 elsif non_common_number > 0 # if services skills have no intersection but could have one fly_distance * non_common_number else 0 end # balance between clusters computation balance = 1.0 if @apply_balancing # At this "stage" of the clustering we would expect this limit to be met expected_cut_limit = limit * @percent_assigned_cut_load # Compare "expected_cut_limit to the current cut_value # and penalize (or favorise) if cut_value/expected_cut_limit greater (or less) than 1. balance = if @percent_assigned_cut_load < 0.95 # First down-play the effect of balance (i.e., **power < 1) # After then make it more pronounced (i.e., **power > 1) (cut_value / expected_cut_limit)**((2 + @rate_balance) * @percent_assigned_cut_load) else # If at the end of the clustering, do not take the power (cut_value / expected_cut_limit) end end if @rate_balance (1.0 - @rate_balance) * (fly_distance + compatibility) + @rate_balance * (fly_distance + compatibility) * balance else (fly_distance + compatibility) * balance end end def calculate_membership_clusters @cluster_metrics = Array.new(@number_of_clusters) { Hash.new(0) } @clusters = Array.new(@number_of_clusters) do Ai4r::Data::DataSet.new :data_labels => @data_set.data_labels end @cluster_indices = Array.new(@number_of_clusters) {[]} @total_assigned_cut_load = 0 @percent_assigned_cut_load = 0 @apply_balancing = false @data_set.data_items.each_with_index do |data_item, data_index| cluster_index = eval(data_item) @clusters[cluster_index] << data_item @cluster_indices[cluster_index] << data_index if @on_empty == 'outlier' @unit_symbols.each{ |unit| @cluster_metrics[cluster_index][unit] += data_item[3][unit] next if unit != @cut_symbol @total_assigned_cut_load += data_item[3][unit] @percent_assigned_cut_load = @total_assigned_cut_load / @total_cut_load.to_f if !@apply_balancing && @cluster_metrics.all?{ |cm| cm[@cut_symbol] > 0 } @apply_balancing = true end } update_centroid_properties(cluster_index, data_item) # TODO : only if missing caracteristics. Returned through eval ? end manage_empty_clusters if has_empty_cluster? end def calc_initial_centroids @centroid_indices = [] # TODO : move or remove @centroids, @old_centroids = [], nil if @centroid_indices.empty? populate_centroids('random') else populate_centroids('indices') end end def populate_centroids(populate_method, number_of_clusters=@number_of_clusters) tried_indexes = [] case populate_method when 'random' # for initial assignment (without the :centroid_indices option) and for reassignment of empty cluster centroids (with :on_empty option 'random') tried_ids = [] while @centroids.length < number_of_clusters && tried_ids.length < @data_set.data_items.length random_index = rand(@data_set.data_items.length) next if tried_ids.include?(@data_set.data_items[random_index][2]) tried_ids << @data_set.data_items[random_index][2] if !@centroids.include? @data_set.data_items[random_index] @centroids << @data_set.data_items[random_index] @data_set.data_items.insert(0, @data_set.data_items.delete_at(random_index)) end end if @output_centroids puts "[DEBUG] kmeans_centroids : #{tried_ids}" end when 'indices' # for initial assignment only (with the :centroid_indices option) @centroid_indices.each do |index| raise ArgumentError, "Invalid centroid index #{index}" unless (index.is_a? Integer) && index >=0 && index < @data_set.data_items.length if !tried_indexes.include?(index) tried_indexes << index if !@centroids.include? @data_set.data_items[index] @centroids << @data_set.data_items[index] end end end end @number_of_clusters = @centroids.length end def eliminate_empty_clusters old_clusters, old_centroids, old_cluster_indices = @clusters, @centroids, @cluster_indices @clusters, @centroids, @cluster_indices = [], [], [] @number_of_clusters.times do |i| next if old_clusters[i].data_items.empty? @clusters << old_clusters[i] @cluster_indices << old_cluster_indices[i] @centroids << old_centroids[i] end @number_of_clusters = @centroids.length end def stop_criteria_met @old_centroids == @centroids || same_centroid_distance_moving_average(Math.sqrt(@iterations).to_i) || #Check if there is a loop of size Math.sqrt(@iterations) (@max_iterations && (@max_iterations <= @iterations)) end def sort_clusters if @cut_limit.is_a? Array @limit_sorted_indices ||= @cut_limit.map.with_index{ |v, i| [i, v] }.sort_by{ |a| a[1] }.map{ |a| a[0] } cluster_sorted_indices = @cluster_metrics.map.with_index{ |v, i| [i, v[@cut_symbol]] }.sort_by{ |a| a[1] }.map{ |a| a[0] } if cluster_sorted_indices != @cluster_sorted_indices @cluster_sorted_indices = cluster_sorted_indices old_clusters = @clusters.dup old_centroids = @centroids.dup old_centroid_indices = @centroid_indices.dup old_cluster_metrics = @cluster_metrics.dup cluster_sorted_indices.each_with_index{ |i, j| @clusters[@limit_sorted_indices[j]] = old_clusters[i] @centroids[@limit_sorted_indices[j]] = old_centroids[i] @centroid_indices[@limit_sorted_indices[j]] = old_centroid_indices[i] @cluster_metrics[@limit_sorted_indices[j]] = old_cluster_metrics[i] } end end end private def update_cut_limit return if @rate_balance == 0.0 || @cut_symbol.nil? || @cut_symbol != :duration || !@cut_limit.is_a?(Array) #TODO: This functionality is implemented only for duration cut_symbol. Make sure it doesn't interfere with other cut_symbols vehicle_work_time = @centroids.map.with_index{ |centroid, index| @cut_limit[index][:total_work_time] - 1.5 * centroid[3][:duration_from_and_to_depot] * @cut_limit[index][:total_work_days] # !!!!!!!!!!!!!!!!!!!! 1.5 } total_vehicle_work_times = vehicle_work_time.sum.to_f @centroids.size.times{ |index| @cut_limit[index][:limit] = @total_cut_load * vehicle_work_time[index] / total_vehicle_work_times } end def same_centroid_distance_moving_average(last_n_iterations) if @iterations.zero? # Initialize the array stats array @last_n_average_diffs = [0.0] * (2 * last_n_iterations + 1) return false end # Calculate total absolute centroid movement in meters total_movement_meter = 0 @number_of_clusters.times { |i| total_movement_meter += Helper.euclidean_distance(@old_centroids[i], @centroids[i]) } # If convereged, we can stop return true if total_movement_meter.to_f < 1 @last_n_average_diffs.push total_movement_meter.to_f # Check if there is a centroid loop of size n (1..last_n_iterations).each{ |n| last_n_iter_average_curr = @last_n_average_diffs[-n..-1].reduce(:+) last_n_iter_average_prev = @last_n_average_diffs[-(n + n)..-(1 + n)].reduce(:+) # If we make exact same moves again and again, we can stop return true if (last_n_iter_average_curr - last_n_iter_average_prev).abs < 1e-5 } # Clean old stats @last_n_average_diffs.shift if @last_n_average_diffs.size > (2 * last_n_iterations + 1) return false end def update_centroid_properties(centroid_index, new_item) @centroids[centroid_index][5] |= new_item[5] end end end end Use a custom distance func if given in k-means # Copyright © Mapotempo, 2018 # # This file is part of Mapotempo. # # Mapotempo is free software. You can redistribute it and/or # modify since you respect the terms of the GNU Affero General # Public License as published by the Free Software Foundation, # either version 3 of the License, or (at your option) any later version. # # Mapotempo is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the Licenses for more details. # # You should have received a copy of the GNU Affero General Public License # along with Mapotempo. If not, see: # <http://www.gnu.org/licenses/agpl.html> # require 'ai4r' require './lib/helper.rb' module Ai4r module Clusterers class BalancedKmeans < KMeans attr_reader :cluster_metrics parameters_info max_iterations: 'Maximum number of iterations to ' \ 'build the clusterer. By default it is uncapped.', centroid_function: 'Custom implementation to calculate the ' \ 'centroid of a cluster. It must be a closure receiving an array of ' \ 'data sets, and return an array of data items, representing the ' \ 'centroids of for each data set. ' \ 'By default, this algorithm returns a data items using the mode '\ 'or mean of each attribute on each data set.', centroid_indices: 'Indices of data items (indexed from 0) to be ' \ 'the initial centroids. Otherwise, the initial centroids will be ' \ 'assigned randomly from the data set.', on_empty: 'Action to take if a cluster becomes empty, with values ' \ "'eliminate' (the default action, eliminate the empty cluster), " \ "'terminate' (terminate with error), 'random' (relocate the " \ "empty cluster to a random point) ", expected_caracteristics: 'Expected sets of caracteristics for generated clusters', possible_caracteristics_combination: 'Set of skills we can combine in the same cluster.', impossible_day_combination: 'Maximum set of conflicting days.' # Build a new clusterer, using data examples found in data_set. # Items will be clustered in "number_of_clusters" different # clusters. def build(data_set, unit_symbols, number_of_clusters, cut_symbol, cut_limit, output_centroids, options = {}) @data_set = data_set reduced_number_of_clusters = [number_of_clusters, data_set.data_items.collect{ |data_item| [data_item[0], data_item[1]] }.uniq.size].min unless reduced_number_of_clusters == number_of_clusters || @centroid_indices.empty? @centroid_indices = @centroid_indices.collect{ |centroid_index| [@data_set.data_items[centroid_index], centroid_index] }.uniq{ |item| [item.first[0], item.first[1]] }.collect(&:last) end @number_of_clusters = reduced_number_of_clusters @cut_limit = cut_limit @cut_symbol = cut_symbol @output_centroids = output_centroids @unit_symbols = unit_symbols @centroid_function = lambda do |clusters| clusters.collect{ |cluster_data_points| get_mean_or_mode(cluster_data_points) } end @distance_function ||= lambda do |a, b| Helper.flying_distance(a, b) end raise ArgumentError, 'Length of centroid indices array differs from the specified number of clusters' unless @centroid_indices.empty? || @centroid_indices.length == @number_of_clusters raise ArgumentError, 'Invalid value for on_empty' unless @on_empty == 'eliminate' || @on_empty == 'terminate' || @on_empty == 'random' || @on_empty == 'outlier' @iterations = 0 if @cut_symbol @total_cut_load = @data_set.data_items.inject(0) { |sum, d| sum + d[3][@cut_symbol] } if @total_cut_load.zero? @cut_symbol = nil # Disable balanacing because there is no point else @data_set.data_items.sort_by!{ |x| x[3][@cut_symbol] ? -x[3][@cut_symbol] : 0 } data_length = @data_set.data_items.size @data_set.data_items[(data_length * 0.1).to_i..(data_length * 0.90).to_i] = @data_set.data_items[(data_length * 0.1).to_i..(data_length * 0.90).to_i].shuffle! end end calc_initial_centroids @rate_balance = 0.0 until stop_criteria_met @rate_balance = 1.0 - (0.2 * @iterations / @max_iterations) if @cut_symbol update_cut_limit calculate_membership_clusters #sort_clusters recompute_centroids end if options[:last_iteration_balance_rate] @rate_balance = options[:last_iteration_balance_rate] update_cut_limit calculate_membership_clusters #sort_clusters recompute_centroids end puts "Clustering converged after #{@iterations} iterations.\n" self end def num_attributes(data_items) return (data_items.empty?) ? 0 : data_items.first.size end # Get the sample mean def mean(data_items, index) sum = 0.0 data_items.each { |item| sum += item[index] } return sum / data_items.length end # Get the sample mode. def mode(data_items, index) count = Hash.new {0} max_count = 0 mode = nil data_items.each do |data_item| attr_value = data_item[index] attr_count = (count[attr_value] += 1) if attr_count > max_count mode = attr_value max_count = attr_count end end return mode end def mode_not_nil(data_items, index) count = Hash.new {0} max_count = 0 mode = nil data_items.each do |data_item| attr_value = data_item[index] attr_count = (count[attr_value] += attr_value.nil? ? 0 : 1) if attr_count > max_count mode = attr_value max_count = attr_count end end return mode end def get_mean_or_mode(data_set) data_items = data_set.data_items mean = [] num_attributes(data_items).times do |i| mean[i] = if data_items.first[i].is_a?(Numeric) mean(data_items, i) elsif i == 4 mode_not_nil(data_items, i) else mode(data_items, i) end end return mean end def recompute_centroids @old_centroids = @centroids data_sticky = @centroids.collect{ |data| data[4] } data_skill = @centroids.collect{ |data| data[5] } data_size = @centroids.collect{ |data| data[6] } @centroids.collect!{ |centroid| centroid[4] = nil centroid[5] = [] centroid[6] = 0 centroid.compact } @iterations += 1 @centroids = @centroid_function.call(@clusters) if @cut_symbol #if there is balancing. @centroids.each_with_index { |centroid, index| #move the data_points closest to the centroid centers to the top of the data_items list so that balancing can start early point_closest_to_centroid_center = clusters[index].data_items.min_by{ |data_point| Helper::flying_distance(centroid, data_point) } @data_set.data_items.insert(0, @data_set.data_items.delete(point_closest_to_centroid_center)) #move it to the top #correct the matrix_index of the centroid with the index of the point_closest_to_centroid_center centroid[3][:matrix_index] = point_closest_to_centroid_center[3][:matrix_index] if centroid[3][:matrix_index] #correct the distance_from_and_to_depot info of the new cluster with the average of the points centroid[3][:duration_from_and_to_depot] = @clusters[index].data_items.map { |d| d[3][:duration_from_and_to_depot] }.sum / @clusters[index].data_items.size.to_f } end @old_centroids.collect!.with_index{ |data, index| data_item = @data_set.data_items.find{ |data_item| data_item[2] == data[2] } data_item[4] = data_sticky[index] data_item[5] = data_skill[index] data_item[6] = data_size[index] data_item } @centroids.each_with_index{ |data, index| data[4] = data_sticky[index] data[5] = data_skill[index] data[6] = data_size[index] } @centroids.each_with_index{ |centroid, index| @centroid_indices[index] = @data_set.data_items.find_index{ |data| data[2] == centroid[2] } } end # Classifies the given data item, returning the cluster index it belongs # to (0-based). def eval(data_item) get_min_index(@centroids.collect.with_index{ |centroid, cluster_index| distance(data_item, centroid, cluster_index) }) end protected def compute_compatibility(caracteristics_a, caracteristics_b, cluster_index) # TODO : not differenciate day skills and skills and simplify hard_violation = false non_common_number = 0 if !(caracteristics_a - caracteristics_b).empty? # all required skills are not available in centroid new_day_caracteristics = (caracteristics_a + caracteristics_b).select{ |car| car.include?('not_day') }.uniq if new_day_caracteristics.uniq.size == @impossible_day_combination.size hard_violation = true else non_common_number += (new_day_caracteristics - caracteristics_b).size end new_caracteristics = (caracteristics_a + caracteristics_b).reject{ |car| car.include?('not_day') }.uniq if !@possible_caracteristics_combination.any?{ |combination| new_caracteristics.all?{ |car| combination.include?(car) } } hard_violation = true else non_common_number += (new_caracteristics - caracteristics_b).size end end if @expected_caracteristics conflicting_caracteristics = caracteristics_a.select{ |c| @expected_caracteristics.include?(c) && !@centroids[cluster_index][5].include?(c) } hard_violation = conflicting_caracteristics.any?{ |c| @centroids.select{ |centroid| centroid[5].include?(c) }.size == @expected_caracteristics.count(c) } if !hard_violation end [hard_violation, non_common_number] end def distance(a, b, cluster_index) # TODO : rename a & b ? # TODO: Move extra logic outside of the distance function. # The user should be able to overload 'distance' function witoud losing any functionality fly_distance = @distance_function.call(a, b) # TODO: Left renaming the variable after the merge to avoid conflicts in the merge. flying_distance => distance cut_value = @cluster_metrics[cluster_index][@cut_symbol].to_f limit = if @cut_limit.is_a? Array @cut_limit[cluster_index][:limit] else @cut_limit[:limit] end # caracteristics compatibility hard_violation, non_common_number = a[5].empty? ? [false, 0] : compute_compatibility(a[5], b[5], cluster_index) compatibility = if a[4] && b[4] && (b[4] & a[4]).empty? || # if service sticky or skills are different than centroids sticky/skills, hard_violation # or if services skills have no match 2**32 elsif non_common_number > 0 # if services skills have no intersection but could have one fly_distance * non_common_number else 0 end # balance between clusters computation balance = 1.0 if @apply_balancing # At this "stage" of the clustering we would expect this limit to be met expected_cut_limit = limit * @percent_assigned_cut_load # Compare "expected_cut_limit to the current cut_value # and penalize (or favorise) if cut_value/expected_cut_limit greater (or less) than 1. balance = if @percent_assigned_cut_load < 0.95 # First down-play the effect of balance (i.e., **power < 1) # After then make it more pronounced (i.e., **power > 1) (cut_value / expected_cut_limit)**((2 + @rate_balance) * @percent_assigned_cut_load) else # If at the end of the clustering, do not take the power (cut_value / expected_cut_limit) end end if @rate_balance (1.0 - @rate_balance) * (fly_distance + compatibility) + @rate_balance * (fly_distance + compatibility) * balance else (fly_distance + compatibility) * balance end end def calculate_membership_clusters @cluster_metrics = Array.new(@number_of_clusters) { Hash.new(0) } @clusters = Array.new(@number_of_clusters) do Ai4r::Data::DataSet.new :data_labels => @data_set.data_labels end @cluster_indices = Array.new(@number_of_clusters) {[]} @total_assigned_cut_load = 0 @percent_assigned_cut_load = 0 @apply_balancing = false @data_set.data_items.each_with_index do |data_item, data_index| cluster_index = eval(data_item) @clusters[cluster_index] << data_item @cluster_indices[cluster_index] << data_index if @on_empty == 'outlier' @unit_symbols.each{ |unit| @cluster_metrics[cluster_index][unit] += data_item[3][unit] next if unit != @cut_symbol @total_assigned_cut_load += data_item[3][unit] @percent_assigned_cut_load = @total_assigned_cut_load / @total_cut_load.to_f if !@apply_balancing && @cluster_metrics.all?{ |cm| cm[@cut_symbol] > 0 } @apply_balancing = true end } update_centroid_properties(cluster_index, data_item) # TODO : only if missing caracteristics. Returned through eval ? end manage_empty_clusters if has_empty_cluster? end def calc_initial_centroids @centroid_indices = [] # TODO : move or remove @centroids, @old_centroids = [], nil if @centroid_indices.empty? populate_centroids('random') else populate_centroids('indices') end end def populate_centroids(populate_method, number_of_clusters=@number_of_clusters) tried_indexes = [] case populate_method when 'random' # for initial assignment (without the :centroid_indices option) and for reassignment of empty cluster centroids (with :on_empty option 'random') tried_ids = [] while @centroids.length < number_of_clusters && tried_ids.length < @data_set.data_items.length random_index = rand(@data_set.data_items.length) next if tried_ids.include?(@data_set.data_items[random_index][2]) tried_ids << @data_set.data_items[random_index][2] if !@centroids.include? @data_set.data_items[random_index] @centroids << @data_set.data_items[random_index] @data_set.data_items.insert(0, @data_set.data_items.delete_at(random_index)) end end if @output_centroids puts "[DEBUG] kmeans_centroids : #{tried_ids}" end when 'indices' # for initial assignment only (with the :centroid_indices option) @centroid_indices.each do |index| raise ArgumentError, "Invalid centroid index #{index}" unless (index.is_a? Integer) && index >=0 && index < @data_set.data_items.length if !tried_indexes.include?(index) tried_indexes << index if !@centroids.include? @data_set.data_items[index] @centroids << @data_set.data_items[index] end end end end @number_of_clusters = @centroids.length end def eliminate_empty_clusters old_clusters, old_centroids, old_cluster_indices = @clusters, @centroids, @cluster_indices @clusters, @centroids, @cluster_indices = [], [], [] @number_of_clusters.times do |i| next if old_clusters[i].data_items.empty? @clusters << old_clusters[i] @cluster_indices << old_cluster_indices[i] @centroids << old_centroids[i] end @number_of_clusters = @centroids.length end def stop_criteria_met @old_centroids == @centroids || same_centroid_distance_moving_average(Math.sqrt(@iterations).to_i) || #Check if there is a loop of size Math.sqrt(@iterations) (@max_iterations && (@max_iterations <= @iterations)) end def sort_clusters if @cut_limit.is_a? Array @limit_sorted_indices ||= @cut_limit.map.with_index{ |v, i| [i, v] }.sort_by{ |a| a[1] }.map{ |a| a[0] } cluster_sorted_indices = @cluster_metrics.map.with_index{ |v, i| [i, v[@cut_symbol]] }.sort_by{ |a| a[1] }.map{ |a| a[0] } if cluster_sorted_indices != @cluster_sorted_indices @cluster_sorted_indices = cluster_sorted_indices old_clusters = @clusters.dup old_centroids = @centroids.dup old_centroid_indices = @centroid_indices.dup old_cluster_metrics = @cluster_metrics.dup cluster_sorted_indices.each_with_index{ |i, j| @clusters[@limit_sorted_indices[j]] = old_clusters[i] @centroids[@limit_sorted_indices[j]] = old_centroids[i] @centroid_indices[@limit_sorted_indices[j]] = old_centroid_indices[i] @cluster_metrics[@limit_sorted_indices[j]] = old_cluster_metrics[i] } end end end private def update_cut_limit return if @rate_balance == 0.0 || @cut_symbol.nil? || @cut_symbol != :duration || !@cut_limit.is_a?(Array) #TODO: This functionality is implemented only for duration cut_symbol. Make sure it doesn't interfere with other cut_symbols vehicle_work_time = @centroids.map.with_index{ |centroid, index| @cut_limit[index][:total_work_time] - 1.5 * centroid[3][:duration_from_and_to_depot] * @cut_limit[index][:total_work_days] # !!!!!!!!!!!!!!!!!!!! 1.5 } total_vehicle_work_times = vehicle_work_time.sum.to_f @centroids.size.times{ |index| @cut_limit[index][:limit] = @total_cut_load * vehicle_work_time[index] / total_vehicle_work_times } end def same_centroid_distance_moving_average(last_n_iterations) if @iterations.zero? # Initialize the array stats array @last_n_average_diffs = [0.0] * (2 * last_n_iterations + 1) return false end # Calculate total absolute centroid movement in meters total_movement_meter = 0 @number_of_clusters.times { |i| total_movement_meter += Helper.euclidean_distance(@old_centroids[i], @centroids[i]) } # If convereged, we can stop return true if total_movement_meter.to_f < 1 @last_n_average_diffs.push total_movement_meter.to_f # Check if there is a centroid loop of size n (1..last_n_iterations).each{ |n| last_n_iter_average_curr = @last_n_average_diffs[-n..-1].reduce(:+) last_n_iter_average_prev = @last_n_average_diffs[-(n + n)..-(1 + n)].reduce(:+) # If we make exact same moves again and again, we can stop return true if (last_n_iter_average_curr - last_n_iter_average_prev).abs < 1e-5 } # Clean old stats @last_n_average_diffs.shift if @last_n_average_diffs.size > (2 * last_n_iterations + 1) return false end def update_centroid_properties(centroid_index, new_item) @centroids[centroid_index][5] |= new_item[5] end end end end
require "compact_index/version" require "compact_index/versions_file" module CompactIndex def self.names(gem_names) "---\n" << gem_names.join("\n") << "\n" end def self.versions(versions_file, gems, args) versions_file.contents(gems, args) end def self.info(params) output = "---\n" params.each do |version| output << version_line(version) << "\n" end output end private def self.version_line(version) if version[:dependencies] version[:dependencies] deps = version[:dependencies].map do |d| [ d[:gem], number_and_platform(d[:version],d[:platform]).gsub(/, /, "&") ].join(':') end else deps = [] end line = number_and_platform(version[:number], version[:platform]) line << " " line << deps.join(",") line << "|" line << "checksum:#{version[:checksum]}" line << ",ruby:#{version[:ruby_version]}" if version[:ruby_version] line << ",rubygems:#{version[:rubygems_version]}" if version[:rubygems_version] line end def self.number_and_platform(number, platform) if platform.nil? || platform == 'ruby' number.dup else "#{number}-#{platform}" end end end Fix missing default parameter require "compact_index/version" require "compact_index/versions_file" module CompactIndex def self.names(gem_names) "---\n" << gem_names.join("\n") << "\n" end def self.versions(versions_file, gems, args = {}) versions_file.contents(gems, args) end def self.info(params) output = "---\n" params.each do |version| output << version_line(version) << "\n" end output end private def self.version_line(version) if version[:dependencies] version[:dependencies] deps = version[:dependencies].map do |d| [ d[:gem], number_and_platform(d[:version],d[:platform]).gsub(/, /, "&") ].join(':') end else deps = [] end line = number_and_platform(version[:number], version[:platform]) line << " " line << deps.join(",") line << "|" line << "checksum:#{version[:checksum]}" line << ",ruby:#{version[:ruby_version]}" if version[:ruby_version] line << ",rubygems:#{version[:rubygems_version]}" if version[:rubygems_version] line end def self.number_and_platform(number, platform) if platform.nil? || platform == 'ruby' number.dup else "#{number}-#{platform}" end end end
require 'compass' require "compass-rails/version" require "compass-rails/configuration" module CompassRails RAILS_4 = %r{^4.[0|1]} RAILS_32 = %r{^3.2} RAILS_31 = %r{^3.1} RAILS_3 = %r{^3.0} extend self def load_rails return true if rails_loaded? return if defined?(::Rails) && ::Rails.respond_to?(:application) && !::Rails.application.nil? rails_config_path = Dir.pwd until File.exists?(File.join(rails_config_path, 'config', 'application.rb')) do raise 'Rails application not found' if rails_config_path == '/' rails_config_path = File.join(rails_config_path, '..') end #load the rails config require "#{rails_config_path}/config/application.rb" if rails31? || rails32? || rails4? require 'sass-rails' require 'sprockets/railtie' require 'rails/engine' @app ||= ::Rails.application.initialize! end end def setup_fake_rails_env_paths(sprockets_env) return unless rails_loaded? keys = ['app/assets', 'lib/assets', 'vendor/assets'] local = keys.map {|path| ::Rails.root.join(path) }.map { |path| [File.join(path, 'images'), File.join(path, 'stylesheets')] }.flatten! sprockets_env.send(:trail).paths.unshift(*local) paths = [] ::Rails::Engine.subclasses.each do |subclass| paths = subclass.paths keys.each do |key| sprockets_env.send(:trail).paths.unshift(*paths[key].existent_directories) end end end def sass_config load_rails ::Rails.application.config.sass end def sprockets load_rails @sprockets ||= ::Rails.application.assets end def context load_rails @context ||= begin sprockets.version = ::Rails.env + "-#{sprockets.version}" setup_fake_rails_env_paths(sprockets) context = ::Rails.application.assets.context_class context.extend(::Sprockets::Helpers::IsolatedHelper) context.extend(::Sprockets::Helpers::RailsHelper) context.extend(::Sass::Rails::Railtie::SassContext) context.sass_config = sass_config context end end def installer(*args) CompassRails::Installer.new(*args) end def rails_loaded? defined?(::Rails) end def rails_version rails_spec = (Gem.loaded_specs["railties"] || Gem.loaded_specs["rails"]) raise "You have to require Rails before compass" unless rails_spec rails_spec.version.to_s end def rails3? return false unless defined?(::Rails) version_match RAILS_3 end def rails31? return false unless defined?(::Rails) version_match RAILS_31 end def rails32? return false unless defined?(::Rails) version_match RAILS_32 end def rails4? return false unless defined?(::Rails) version_match RAILS_4 end def version_match(version) if (rails_version =~ version).nil? return false end true end def booted! CompassRails.const_set(:BOOTED, true) end def booted? defined?(CompassRails::BOOTED) && CompassRails::BOOTED end def configuration load_rails config = Compass::Configuration::Data.new('rails') config.extend(Configuration::Default) if asset_pipeline_enabled? require "compass-rails/configuration/asset_pipeline" config.extend(Configuration::AssetPipeline) end config end def env env_production? ? :production : :development end def prefix ::Rails.application.config.assets.prefix end def env_production? if defined?(::Rails) && ::Rails.respond_to?(:env) ::Rails.env.production? elsif defined?(RAILS_ENV) RAILS_ENV == "production" end end def root @root ||= begin if defined?(::Rails) && ::Rails.respond_to?(:root) ::Rails.root elsif defined?(RAILS_ROOT) Pathname.new(RAILS_ROOT) else Pathname.new(Dir.pwd) end end end def check_for_double_boot! if booted? Compass::Util.compass_warn("Warning: Compass was booted twice. Compass-rails has got your back; please remove your compass initializer.") else booted! end end def sass_plugin_enabled? unless rails31? defined?(Sass::Plugin) && !Sass::Plugin.options[:never_update] end end # Rails projects without asset pipeline use this in their compass initializer. def initialize!(config = nil) check_for_double_boot! config ||= Compass.detect_configuration_file(root) Compass.add_project_configuration(config, :project_type => :rails) Compass.discover_extensions! Compass.configure_sass_plugin! Compass.handle_configuration_change! if sass_plugin_enabled? end def configure_rails!(app) return unless app.config.respond_to?(:sass) sass_config = app.config.sass compass_config = app.config.compass sass_config.load_paths.concat(compass_config.sass_load_paths) { :output_style => :style, :line_comments => :line_comments, :cache => :cache, :disable_warnings => :quiet, :preferred_syntax => :preferred_syntax }.each do |compass_option, sass_option| set_maybe sass_config, compass_config, sass_option, compass_option end if compass_config.sass_options compass_config.sass_options.each do |config, value| sass_config.send("#{config}=", value) end end end def boot_config config = if (config_file = Compass.detect_configuration_file) && (config_data = Compass.configuration_for(config_file)) config_data else Compass::Configuration::Data.new("compass_rails_boot") end config.top_level.project_type = :rails config end def asset_pipeline_enabled? return false unless rails_loaded? && ::Rails.respond_to?(:application) && !::Rails.application.nil? rails_config = ::Rails.application.config if rails_config.respond_to?(:assets) rails_config.assets.enabled != false else false end end private # sets the sass config value only if the corresponding compass-based setting # has been explicitly set by the user. def set_maybe(sass_config, compass_config, sass_option, compass_option) if compass_value = compass_config.send(:"#{compass_option}_without_default") sass_config.send(:"#{sass_option}=", compass_value) end end end Compass::AppIntegration.register(:rails, "::CompassRails") Compass.add_configuration(CompassRails.boot_config) require "compass-rails/patches" require "compass-rails/railties" require "compass-rails/installer" support for rails 4.2 require 'compass' require "compass-rails/version" require "compass-rails/configuration" module CompassRails RAILS_4 = %r{^4.[0|1|2]} RAILS_32 = %r{^3.2} RAILS_31 = %r{^3.1} RAILS_3 = %r{^3.0} extend self def load_rails return true if rails_loaded? return if defined?(::Rails) && ::Rails.respond_to?(:application) && !::Rails.application.nil? rails_config_path = Dir.pwd until File.exists?(File.join(rails_config_path, 'config', 'application.rb')) do raise 'Rails application not found' if rails_config_path == '/' rails_config_path = File.join(rails_config_path, '..') end #load the rails config require "#{rails_config_path}/config/application.rb" if rails31? || rails32? || rails4? require 'sass-rails' require 'sprockets/railtie' require 'rails/engine' @app ||= ::Rails.application.initialize! end end def setup_fake_rails_env_paths(sprockets_env) return unless rails_loaded? keys = ['app/assets', 'lib/assets', 'vendor/assets'] local = keys.map {|path| ::Rails.root.join(path) }.map { |path| [File.join(path, 'images'), File.join(path, 'stylesheets')] }.flatten! sprockets_env.send(:trail).paths.unshift(*local) paths = [] ::Rails::Engine.subclasses.each do |subclass| paths = subclass.paths keys.each do |key| sprockets_env.send(:trail).paths.unshift(*paths[key].existent_directories) end end end def sass_config load_rails ::Rails.application.config.sass end def sprockets load_rails @sprockets ||= ::Rails.application.assets end def context load_rails @context ||= begin sprockets.version = ::Rails.env + "-#{sprockets.version}" setup_fake_rails_env_paths(sprockets) context = ::Rails.application.assets.context_class context.extend(::Sprockets::Helpers::IsolatedHelper) context.extend(::Sprockets::Helpers::RailsHelper) context.extend(::Sass::Rails::Railtie::SassContext) context.sass_config = sass_config context end end def installer(*args) CompassRails::Installer.new(*args) end def rails_loaded? defined?(::Rails) end def rails_version rails_spec = (Gem.loaded_specs["railties"] || Gem.loaded_specs["rails"]) raise "You have to require Rails before compass" unless rails_spec rails_spec.version.to_s end def rails3? return false unless defined?(::Rails) version_match RAILS_3 end def rails31? return false unless defined?(::Rails) version_match RAILS_31 end def rails32? return false unless defined?(::Rails) version_match RAILS_32 end def rails4? return false unless defined?(::Rails) version_match RAILS_4 end def version_match(version) if (rails_version =~ version).nil? return false end true end def booted! CompassRails.const_set(:BOOTED, true) end def booted? defined?(CompassRails::BOOTED) && CompassRails::BOOTED end def configuration load_rails config = Compass::Configuration::Data.new('rails') config.extend(Configuration::Default) if asset_pipeline_enabled? require "compass-rails/configuration/asset_pipeline" config.extend(Configuration::AssetPipeline) end config end def env env_production? ? :production : :development end def prefix ::Rails.application.config.assets.prefix end def env_production? if defined?(::Rails) && ::Rails.respond_to?(:env) ::Rails.env.production? elsif defined?(RAILS_ENV) RAILS_ENV == "production" end end def root @root ||= begin if defined?(::Rails) && ::Rails.respond_to?(:root) ::Rails.root elsif defined?(RAILS_ROOT) Pathname.new(RAILS_ROOT) else Pathname.new(Dir.pwd) end end end def check_for_double_boot! if booted? Compass::Util.compass_warn("Warning: Compass was booted twice. Compass-rails has got your back; please remove your compass initializer.") else booted! end end def sass_plugin_enabled? unless rails31? defined?(Sass::Plugin) && !Sass::Plugin.options[:never_update] end end # Rails projects without asset pipeline use this in their compass initializer. def initialize!(config = nil) check_for_double_boot! config ||= Compass.detect_configuration_file(root) Compass.add_project_configuration(config, :project_type => :rails) Compass.discover_extensions! Compass.configure_sass_plugin! Compass.handle_configuration_change! if sass_plugin_enabled? end def configure_rails!(app) return unless app.config.respond_to?(:sass) sass_config = app.config.sass compass_config = app.config.compass sass_config.load_paths.concat(compass_config.sass_load_paths) { :output_style => :style, :line_comments => :line_comments, :cache => :cache, :disable_warnings => :quiet, :preferred_syntax => :preferred_syntax }.each do |compass_option, sass_option| set_maybe sass_config, compass_config, sass_option, compass_option end if compass_config.sass_options compass_config.sass_options.each do |config, value| sass_config.send("#{config}=", value) end end end def boot_config config = if (config_file = Compass.detect_configuration_file) && (config_data = Compass.configuration_for(config_file)) config_data else Compass::Configuration::Data.new("compass_rails_boot") end config.top_level.project_type = :rails config end def asset_pipeline_enabled? return false unless rails_loaded? && ::Rails.respond_to?(:application) && !::Rails.application.nil? rails_config = ::Rails.application.config if rails_config.respond_to?(:assets) rails_config.assets.enabled != false else false end end private # sets the sass config value only if the corresponding compass-based setting # has been explicitly set by the user. def set_maybe(sass_config, compass_config, sass_option, compass_option) if compass_value = compass_config.send(:"#{compass_option}_without_default") sass_config.send(:"#{sass_option}=", compass_value) end end end Compass::AppIntegration.register(:rails, "::CompassRails") Compass.add_configuration(CompassRails.boot_config) require "compass-rails/patches" require "compass-rails/railties" require "compass-rails/installer"
require 'lazydoc' require 'configurable/config_hash' require 'configurable/conversions' module Configurable # Hash of default config types (bool, integer, float, string). DEFAULT_CONFIG_TYPES = { :bool => ConfigTypes::BooleanType, :integer => ConfigTypes::IntegerType, :float => ConfigTypes::FloatType, :string => ConfigTypes::StringType, :nest => ConfigTypes::NestType, :obj => ConfigTypes::ObjectType } # ClassMethods extends classes that include Configurable and provides methods # for declaring configurations. module ClassMethods include ConfigClasses include ConfigTypes # A hash of (key, Config) pairs tracking configs defined on self. See the # configs method for all configs declared across all ancestors. attr_reader :config_registry # A hash of (key, ConfigType) pairs tracking config_types defined on self. # See the config_types method for all config_types declared across all # ancestors. attr_reader :config_type_registry def self.initialize(base) # :nodoc: base.reset_configs unless base.instance_variable_defined?(:@config_registry) base.instance_variable_set(:@config_registry, {}) end base.reset_config_types unless base.instance_variable_defined?(:@config_type_registry) base.instance_variable_set(:@config_type_registry, {}) end unless base.instance_variable_defined?(:@config_type_context) base.instance_variable_set(:@config_type_context, base) end end # A hash of (key, Config) pairs representing all configs defined on this # class or inherited from ancestors. The configs hash is memoized for # performance. Call reset_configs if configs needs to be recalculated for # any reason. # # Configs is extended with the Conversions module. def configs @configs ||= begin configs = {} ancestors.reverse.each do |ancestor| next unless ancestor.kind_of?(ClassMethods) ancestor.config_registry.each_pair do |key, value| if value.nil? configs.delete(key) else configs[key] = value end end end configs.extend Conversions configs end end # Resets configs such that they will be recalculated. def reset_configs @configs = nil end # A hash of (key, ConfigType) pairs representing all config_types defined # on this class or inherited from ancestors. The config_types hash is # memoized for performance. Call reset_config_types if config_types needs # to be recalculated for any reason. def config_types @config_types ||= begin config_types = {} registries = [] each_registry do |ancestor, registry| registries.unshift(registry) end registries.each do |registry| registry.each_pair do |key, value| if value.nil? config_types.delete(key) else config_types[key] = value end end end config_types end end # Resets config_types such that they will be recalculated. def reset_config_types @config_types = nil end protected attr_accessor :config_type_context # Defines and registers an instance of config_class with the specified key # and attrs. Unless attrs specifies a :reader or :writer, the # corresponding attr accessors will be defined for the config name (which # by default is the key). def define_config(key, attrs={}, config_class=ScalarConfig) reader = attrs[:reader] writer = attrs[:writer] config = config_class.new(key, attrs) attr_reader(config.name) unless reader attr_writer(config.name) unless writer config_registry[config.key] = config reset_configs config end # Defines a config after guessing or setting some standard values into # attrs. Specifically: # # * :default is the default # * :caster is the caster block (if provided) # * :desc is set using Lazydoc (unless already set) # * :list is set to true for array defaults (unless already set) # # In addition config also guesses the type of a config (if not manually # specified by :type) and merges in any attributes for the corresponding # config_type. The class of the config is guessed from the attrs, based # on the :list and :options attributes using this logic: # # :list :otions config_class # --------------------------- # false false Config # true false List # false true Select # true true ListSelect # # == Usage Note # # Config is meant to be a convenience method. It gets most things right # but if the attrs logic is too convoluted (and at times it is) then # define configs manually with the define_config method. def config(key, default=nil, attrs={}, &block) orig_attrs = attrs.dup if nest_class = guess_nest_class(default, block) default = nest_class.new end if default.kind_of?(Configurable) attrs[:configurable] = default default = default.config.to_hash end attrs[:default] = default attrs[:type] = guess_config_type(attrs).new(attrs) attrs[:metadata] = guess_config_metadata(Lazydoc.register_caller).merge!(orig_attrs) config_class = guess_config_class(attrs) config = define_config(key, attrs, config_class) if nest_class const_name = attrs[:const_name] || guess_nest_const_name(config) unless const_defined?(const_name) const_set(const_name, nest_class) end end config end # Removes a config much like remove_method removes a method. The reader # and writer for the config are likewise removed. Nested configs can be # removed using this method. # # Setting :reader or :writer to false in the options prevents those # methods from being removed. def remove_config(key, options={}) unless config_registry.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = config_registry.delete(key) reset_configs remove_method(config.reader) if options[:reader] remove_method(config.writer) if options[:writer] config end # Undefines a config much like undef_method undefines a method. The # reader and writer for the config are likewise undefined. Nested configs # can be undefined using this method. # # Setting :reader or :writer to false in the options prevents those # methods from being undefined. # # ==== Implementation Note # # Configurations are undefined by setting the key to nil in the registry. # Deleting the config is not sufficient because the registry needs to # convey to self and subclasses to not inherit the config from ancestors. # # This is unlike remove_config where the config is simply deleted from the # config_registry. def undef_config(key, options={}) unless configs.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = configs[key] config_registry[key] = nil reset_configs undef_method(config.reader) if options[:reader] undef_method(config.writer) if options[:writer] config end def define_config_type(name, config_type) config_type_registry[name] = config_type reset_config_types config_type end def config_type(name, *matchers, &caster) config_type = StringType.subclass(*matchers).cast(&caster) const_name = guess_config_type_const_name(name) unless const_defined?(const_name) const_set(const_name, config_type) end define_config_type(name, config_type) end # Removes a config_type much like remove_method removes a method. def remove_config_type(name) unless config_type_registry.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry.delete(name) reset_config_types config_type end # Undefines a config_type much like undef_method undefines a method. # # ==== Implementation Note # # ConfigClasses are undefined by setting the key to nil in the registry. # Deleting the config_type is not sufficient because the registry needs to # convey to self and subclasses to not inherit the config_type from # ancestors. # # This is unlike remove_config_type where the config_type is simply # deleted from the config_type_registry. def undef_config_type(name) unless config_types.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry[name] config_type_registry[name] = nil reset_config_types config_type end private def inherited(base) # :nodoc: ClassMethods.initialize(base) super end def guess_nest_class(base, block) # :nodoc: unless base.kind_of?(Hash) || block return nil end nest_class = Class.new { include Configurable } nest_class.config_type_context = self if base.kind_of?(Hash) base.each_pair do |key, value| nest_class.send(:config, key, value) end end if block nest_class.class_eval(&block) end check_infinite_nest(nest_class) nest_class end # helper to recursively check for an infinite nest def check_infinite_nest(klass) # :nodoc: raise "infinite nest detected" if klass == self klass.configs.each_value do |config| if config.type.kind_of?(NestType) check_infinite_nest(config.type.configurable.class) end end end def each_registry # :nodoc: # yield the registry for self first to take account of times when # config_type_context.ancestors does not include self (otherwise # config types defined on self are missed) yield self, config_type_registry config_type_context.ancestors.each do |ancestor| case when ancestor == self next when ancestor.kind_of?(ClassMethods) yield ancestor, ancestor.config_type_registry when ancestor == Configurable yield ancestor, Configurable::DEFAULT_CONFIG_TYPES break else next end end end def guess_config_type_by_name(name) # :nodoc: return name if name.nil? each_registry do |ancestor, registry| if registry.has_key?(name) return registry[name] end end raise "no such config type: #{type.inspect}" end def guess_config_type_by_value(value) # :nodoc: each_registry do |ancestor, registry| guesses = registry.values.select {|config_type| config_type.matches?(value) } case guesses.length when 0 then next when 1 then return guesses.at(0) else raise "multiple guesses for config type: #{guesses.inspect} (in: #{ancestor} default: #{default.inspect})" end end ObjectType end def guess_config_type(attrs) # :nodoc: if attrs.has_key?(:type) guess_config_type_by_name attrs[:type] else value = attrs[:default] value = value.at(0) if value.kind_of?(Array) guess_config_type_by_value value end end def guess_config_class(attrs) # :nodoc: if attrs.has_key?(:class) attrs[:class] else case attrs[:default] when Array then ListConfig when Hash then NestConfig else ScalarConfig end end end def guess_config_metadata(comment) # :nodoc: Hash.new do |hash, key| comment.resolve if trailer = comment.trailer flags, desc = trailer.split(':', 2) if desc.nil? flags, desc = '', flags elsif flags.strip.empty? hash[:hidden] = true else hash[:long] = nil hash[:short] = nil hash[:arg_name] = nil end argv = flags.split(',').collect! {|arg| arg.strip } argv << desc.strip comment_attrs = ConfigParser::Utils.parse_attrs(argv) comment_attrs.each_pair do |attr_key, attr_value| hash[attr_key] = attr_value end end hash[:help] = comment.content hash.has_key?(key) ? hash[key] : nil end end def guess_nest_const_name(config) # :nodoc: config.name.gsub(/(?:^|_)(.)/) { $1.upcase } end def guess_config_type_const_name(name) # :nodoc: "#{name}Type".gsub(/(?:^|_)(.)/) { $1.upcase } end end end make define_config specifically set attr accessors as public for 1.9.2 require 'lazydoc' require 'configurable/config_hash' require 'configurable/conversions' module Configurable # Hash of default config types (bool, integer, float, string). DEFAULT_CONFIG_TYPES = { :bool => ConfigTypes::BooleanType, :integer => ConfigTypes::IntegerType, :float => ConfigTypes::FloatType, :string => ConfigTypes::StringType, :nest => ConfigTypes::NestType, :obj => ConfigTypes::ObjectType } # ClassMethods extends classes that include Configurable and provides methods # for declaring configurations. module ClassMethods include ConfigClasses include ConfigTypes # A hash of (key, Config) pairs tracking configs defined on self. See the # configs method for all configs declared across all ancestors. attr_reader :config_registry # A hash of (key, ConfigType) pairs tracking config_types defined on self. # See the config_types method for all config_types declared across all # ancestors. attr_reader :config_type_registry def self.initialize(base) # :nodoc: base.reset_configs unless base.instance_variable_defined?(:@config_registry) base.instance_variable_set(:@config_registry, {}) end base.reset_config_types unless base.instance_variable_defined?(:@config_type_registry) base.instance_variable_set(:@config_type_registry, {}) end unless base.instance_variable_defined?(:@config_type_context) base.instance_variable_set(:@config_type_context, base) end end # A hash of (key, Config) pairs representing all configs defined on this # class or inherited from ancestors. The configs hash is memoized for # performance. Call reset_configs if configs needs to be recalculated for # any reason. # # Configs is extended with the Conversions module. def configs @configs ||= begin configs = {} ancestors.reverse.each do |ancestor| next unless ancestor.kind_of?(ClassMethods) ancestor.config_registry.each_pair do |key, value| if value.nil? configs.delete(key) else configs[key] = value end end end configs.extend Conversions configs end end # Resets configs such that they will be recalculated. def reset_configs @configs = nil end # A hash of (key, ConfigType) pairs representing all config_types defined # on this class or inherited from ancestors. The config_types hash is # memoized for performance. Call reset_config_types if config_types needs # to be recalculated for any reason. def config_types @config_types ||= begin config_types = {} registries = [] each_registry do |ancestor, registry| registries.unshift(registry) end registries.each do |registry| registry.each_pair do |key, value| if value.nil? config_types.delete(key) else config_types[key] = value end end end config_types end end # Resets config_types such that they will be recalculated. def reset_config_types @config_types = nil end protected attr_accessor :config_type_context # Defines and registers an instance of config_class with the specified key # and attrs. Unless attrs specifies a :reader or :writer, the # corresponding attr accessors will be defined for the config name (which # by default is the key). def define_config(key, attrs={}, config_class=ScalarConfig) reader = attrs[:reader] writer = attrs[:writer] config = config_class.new(key, attrs) unless reader attr_reader(config.name) public(config.name) end unless writer attr_writer(config.name) public("#{config.name}=") end config_registry[config.key] = config reset_configs config end # Defines a config after guessing or setting some standard values into # attrs. Specifically: # # * :default is the default # * :caster is the caster block (if provided) # * :desc is set using Lazydoc (unless already set) # * :list is set to true for array defaults (unless already set) # # In addition config also guesses the type of a config (if not manually # specified by :type) and merges in any attributes for the corresponding # config_type. The class of the config is guessed from the attrs, based # on the :list and :options attributes using this logic: # # :list :otions config_class # --------------------------- # false false Config # true false List # false true Select # true true ListSelect # # == Usage Note # # Config is meant to be a convenience method. It gets most things right # but if the attrs logic is too convoluted (and at times it is) then # define configs manually with the define_config method. def config(key, default=nil, attrs={}, &block) orig_attrs = attrs.dup if nest_class = guess_nest_class(default, block) default = nest_class.new end if default.kind_of?(Configurable) attrs[:configurable] = default default = default.config.to_hash end attrs[:default] = default attrs[:type] = guess_config_type(attrs).new(attrs) attrs[:metadata] = guess_config_metadata(Lazydoc.register_caller).merge!(orig_attrs) config_class = guess_config_class(attrs) config = define_config(key, attrs, config_class) if nest_class const_name = attrs[:const_name] || guess_nest_const_name(config) unless const_defined?(const_name) const_set(const_name, nest_class) end end config end # Removes a config much like remove_method removes a method. The reader # and writer for the config are likewise removed. Nested configs can be # removed using this method. # # Setting :reader or :writer to false in the options prevents those # methods from being removed. def remove_config(key, options={}) unless config_registry.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = config_registry.delete(key) reset_configs remove_method(config.reader) if options[:reader] remove_method(config.writer) if options[:writer] config end # Undefines a config much like undef_method undefines a method. The # reader and writer for the config are likewise undefined. Nested configs # can be undefined using this method. # # Setting :reader or :writer to false in the options prevents those # methods from being undefined. # # ==== Implementation Note # # Configurations are undefined by setting the key to nil in the registry. # Deleting the config is not sufficient because the registry needs to # convey to self and subclasses to not inherit the config from ancestors. # # This is unlike remove_config where the config is simply deleted from the # config_registry. def undef_config(key, options={}) unless configs.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = configs[key] config_registry[key] = nil reset_configs undef_method(config.reader) if options[:reader] undef_method(config.writer) if options[:writer] config end def define_config_type(name, config_type) config_type_registry[name] = config_type reset_config_types config_type end def config_type(name, *matchers, &caster) config_type = StringType.subclass(*matchers).cast(&caster) const_name = guess_config_type_const_name(name) unless const_defined?(const_name) const_set(const_name, config_type) end define_config_type(name, config_type) end # Removes a config_type much like remove_method removes a method. def remove_config_type(name) unless config_type_registry.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry.delete(name) reset_config_types config_type end # Undefines a config_type much like undef_method undefines a method. # # ==== Implementation Note # # ConfigClasses are undefined by setting the key to nil in the registry. # Deleting the config_type is not sufficient because the registry needs to # convey to self and subclasses to not inherit the config_type from # ancestors. # # This is unlike remove_config_type where the config_type is simply # deleted from the config_type_registry. def undef_config_type(name) unless config_types.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry[name] config_type_registry[name] = nil reset_config_types config_type end private def inherited(base) # :nodoc: ClassMethods.initialize(base) super end def guess_nest_class(base, block) # :nodoc: unless base.kind_of?(Hash) || block return nil end nest_class = Class.new { include Configurable } nest_class.config_type_context = self if base.kind_of?(Hash) base.each_pair do |key, value| nest_class.send(:config, key, value) end end if block nest_class.class_eval(&block) end check_infinite_nest(nest_class) nest_class end # helper to recursively check for an infinite nest def check_infinite_nest(klass) # :nodoc: raise "infinite nest detected" if klass == self klass.configs.each_value do |config| if config.type.kind_of?(NestType) check_infinite_nest(config.type.configurable.class) end end end def each_registry # :nodoc: # yield the registry for self first to take account of times when # config_type_context.ancestors does not include self (otherwise # config types defined on self are missed) yield self, config_type_registry config_type_context.ancestors.each do |ancestor| case when ancestor == self next when ancestor.kind_of?(ClassMethods) yield ancestor, ancestor.config_type_registry when ancestor == Configurable yield ancestor, Configurable::DEFAULT_CONFIG_TYPES break else next end end end def guess_config_type_by_name(name) # :nodoc: return name if name.nil? each_registry do |ancestor, registry| if registry.has_key?(name) return registry[name] end end raise "no such config type: #{type.inspect}" end def guess_config_type_by_value(value) # :nodoc: each_registry do |ancestor, registry| guesses = registry.values.select {|config_type| config_type.matches?(value) } case guesses.length when 0 then next when 1 then return guesses.at(0) else raise "multiple guesses for config type: #{guesses.inspect} (in: #{ancestor} default: #{default.inspect})" end end ObjectType end def guess_config_type(attrs) # :nodoc: if attrs.has_key?(:type) guess_config_type_by_name attrs[:type] else value = attrs[:default] value = value.at(0) if value.kind_of?(Array) guess_config_type_by_value value end end def guess_config_class(attrs) # :nodoc: if attrs.has_key?(:class) attrs[:class] else case attrs[:default] when Array then ListConfig when Hash then NestConfig else ScalarConfig end end end def guess_config_metadata(comment) # :nodoc: Hash.new do |hash, key| comment.resolve if trailer = comment.trailer flags, desc = trailer.split(':', 2) if desc.nil? flags, desc = '', flags elsif flags.strip.empty? hash[:hidden] = true else hash[:long] = nil hash[:short] = nil hash[:arg_name] = nil end argv = flags.split(',').collect! {|arg| arg.strip } argv << desc.strip comment_attrs = ConfigParser::Utils.parse_attrs(argv) comment_attrs.each_pair do |attr_key, attr_value| hash[attr_key] = attr_value end end hash[:help] = comment.content hash.has_key?(key) ? hash[key] : nil end end def guess_nest_const_name(config) # :nodoc: config.name.gsub(/(?:^|_)(.)/) { $1.upcase } end def guess_config_type_const_name(name) # :nodoc: "#{name}Type".gsub(/(?:^|_)(.)/) { $1.upcase } end end end
# frozen_string_literal: true require_relative "boot" require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" # require "active_storage/engine" require "action_controller/railtie" require "action_mailer/railtie" # require "action_mailbox/engine" # require "action_text/engine" require "action_view/railtie" # require "action_cable/engine" require "rails/test_unit/railtie" require "good_job/engine" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. # # Assets should be precompiled for production (so we don't need the gems loaded then) Bundler.require(*Rails.groups(assets: %w[development test])) module Openmensa class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 7.0 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. config.autoload_paths << Rails.root.join("lib") config.eager_load_paths << Rails.root.join("lib") # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. config.time_zone = "Berlin" # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. config.i18n.load_path += Dir[Rails.root.join("app/locales/**/*.{rb,yml}").to_s] config.i18n.default_locale = :de # Loaded OmniAuth services will be stored here config.omniauth_services = [] # Configure parameter filtering for logging config.filter_parameters += %i[password passw secret token _key crypt salt certificate otp ssn] # Session store config.session_store :cookie_store, key: "_openmensa_session", secure: Rails.env.production? config.action_dispatch.cookies_serializer = :hybrid config.action_dispatch.cookies_same_site_protection = :lax # Version of your assets, change this if you want to expire all your assets. config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path # Add Yarn node_modules folder to the asset load path. config.assets.paths << Rails.root.join("node_modules") # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # config.assets.precompile += %w( admin.js admin.css ) # Default URL for mails config.action_mailer.default_url_options = {host: "openmensa.org", protocol: "https"} config.middleware.use Rack::Cors do allow do origins "*" resource "/api/*", headers: :any, expose: %w[Link X-OM-Api-Version X-Total-Pages], methods: :get, credentials: false end end config.content_security_policy do |policy| policy.default_src :self policy.font_src :self, :https, :data policy.img_src :self, :https, :data, "https://openmensa.org" policy.object_src :none policy.script_src :self policy.style_src :self end config.permissions_policy do |f| f.camera :none f.gyroscope :none f.microphone :none f.usb :none f.fullscreen :self f.payment :none end end end fix: Allow YAML db columns to decode symbols They are needed in the `data` column from `Message`. # frozen_string_literal: true require_relative "boot" require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" # require "active_storage/engine" require "action_controller/railtie" require "action_mailer/railtie" # require "action_mailbox/engine" # require "action_text/engine" require "action_view/railtie" # require "action_cable/engine" require "rails/test_unit/railtie" require "good_job/engine" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. # # Assets should be precompiled for production (so we don't need the gems loaded then) Bundler.require(*Rails.groups(assets: %w[development test])) module Openmensa class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 7.0 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. config.autoload_paths << Rails.root.join("lib") config.eager_load_paths << Rails.root.join("lib") # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. config.time_zone = "Berlin" # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. config.i18n.load_path += Dir[Rails.root.join("app/locales/**/*.{rb,yml}").to_s] config.i18n.default_locale = :de # Loaded OmniAuth services will be stored here config.omniauth_services = [] # Configure parameter filtering for logging config.filter_parameters += %i[password passw secret token _key crypt salt certificate otp ssn] # Session store config.session_store :cookie_store, key: "_openmensa_session", secure: Rails.env.production? config.action_dispatch.cookies_serializer = :hybrid config.action_dispatch.cookies_same_site_protection = :lax # Version of your assets, change this if you want to expire all your assets. config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path # Add Yarn node_modules folder to the asset load path. config.assets.paths << Rails.root.join("node_modules") # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # config.assets.precompile += %w( admin.js admin.css ) # Default URL for mails config.action_mailer.default_url_options = {host: "openmensa.org", protocol: "https"} # Allowed classes to be deserialized in YAML-encoded database # columns config.active_record.yaml_column_permitted_classes = [Symbol] config.middleware.use Rack::Cors do allow do origins "*" resource "/api/*", headers: :any, expose: %w[Link X-OM-Api-Version X-Total-Pages], methods: :get, credentials: false end end config.content_security_policy do |policy| policy.default_src :self policy.font_src :self, :https, :data policy.img_src :self, :https, :data, "https://openmensa.org" policy.object_src :none policy.script_src :self policy.style_src :self end config.permissions_policy do |f| f.camera :none f.gyroscope :none f.microphone :none f.usb :none f.fullscreen :self f.payment :none end end end
require File.expand_path('../boot', __FILE__) require 'rails/all' require 'securerandom' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Theoj class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de config.i18n.enforce_available_locales = true end end preferred stylesheet syntax sass require File.expand_path('../boot', __FILE__) require 'rails/all' require 'securerandom' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Theoj class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de config.sass.preferred_syntax = :sass config.i18n.enforce_available_locales = true end end
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module ProconistNet class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. end end Set timezone to JST require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module ProconistNet class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. config.time_zone = 'Tokyo' end end
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module KnowPlaceApi class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end Add CORS, allowing get, post, put, and patch from the KNOWN_HOSTS variable require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module KnowPlaceApi class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true # In production, only the client should be able to POST data to the server. # Set the KNOWN_HOSTS environment variable to '*' in the development and staging environments. # to allow any host to connect to it. In production, set it to a comma-separated list of # domains where the client application is known to be hosted. # # => KNOWN_HOSTS=clientside.knowplace.com,another.pla.ce KNOWN_HOSTS = ENV.fetch('KNOWN_HOSTS') { 'todo.productionsi.te' } DEBUG_CORS = ENV.fetch('DEBUG_CORS') { false } config.middleware.insert_before 0, "Rack::Cors", debug: DEBUG_CORS, logger: (-> { Rails.logger }) do allow do origins KNOWN_HOSTS.split(',') resource '*', headers: :any, methods: [:get, :post, :put, :patch] end end end end
# Copyright (c) 2010-2011, Diaspora Inc. This file is # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. require 'pathname' require Pathname.new(__FILE__).expand_path.dirname.join('boot') # Needed for versions of ruby 1.9.2 that were compiled with libyaml. # They use psych by default which doesn't handle having a default set of parameters. # See bug #1120. require 'yaml' if RUBY_VERSION.include? '1.9' YAML::ENGINE.yamler= 'syck' end require 'rails/all' # Sanitize groups to make matching :assets easier RAILS_GROUPS = Rails.groups(:assets => %w(development test)).map { |group| group.to_sym } if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*RAILS_GROUPS) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module Diaspora class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs config.autoload_paths += %W{#{config.root}/app/presenters} config.autoload_once_paths += %W{#{config.root}/lib} # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure generators values. Many other options are available, be sure to check the documentation. config.generators do |g| g.template_engine :haml g.test_framework :rspec end # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] config.filter_parameters += [:xml] config.filter_parameters += [:message] config.filter_parameters += [:text] config.filter_parameters += [:bio] # Enable the asset pipeline config.assets.enabled = true config.assets.initialize_on_precompile = false # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # Javascripts config.assets.precompile += [ "aspect-contacts.js", "contact-list.js", "finder.js", "home.js", "ie.js", "inbox.js", "jquery.js", "jquery_ujs.js", "jquery.textchange.js", "login.js", "mailchimp.js", "main.js", "mobile.js", "profile.js", "people.js", "photos.js", "profile.js", "publisher.js", "templates.js", "validation.js" ] # Stylesheets config.assets.precompile += [ "blueprint.css", "bootstrap.css", "bootstrap-complete.css", "bootstrap-responsive.css", "default.css", "error_pages.css", "login.css", "mobile.css", "new-templates.css", "rtl.css" ] # Rails Admin - these assets need to be added here since the Engine initializer # doesn't run with initialize_on_precompile disabled. This list is taken # directly from the Rails Admin Engine initializer. config.assets.precompile += ['rails_admin/rails_admin.js', 'rails_admin/rails_admin.css', 'rails_admin/jquery.colorpicker.js', 'rails_admin/jquery.colorpicker.css'] # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end add app directory to the autoload paths so that the worker files are loaded in development mode too # Copyright (c) 2010-2011, Diaspora Inc. This file is # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. require 'pathname' require Pathname.new(__FILE__).expand_path.dirname.join('boot') # Needed for versions of ruby 1.9.2 that were compiled with libyaml. # They use psych by default which doesn't handle having a default set of parameters. # See bug #1120. require 'yaml' if RUBY_VERSION.include? '1.9' YAML::ENGINE.yamler= 'syck' end require 'rails/all' # Sanitize groups to make matching :assets easier RAILS_GROUPS = Rails.groups(:assets => %w(development test)).map { |group| group.to_sym } if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*RAILS_GROUPS) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module Diaspora class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs config.autoload_paths += %W{#{config.root}/app/presenters #{config.root}/app} config.autoload_once_paths += %W{#{config.root}/lib} # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure generators values. Many other options are available, be sure to check the documentation. config.generators do |g| g.template_engine :haml g.test_framework :rspec end # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] config.filter_parameters += [:xml] config.filter_parameters += [:message] config.filter_parameters += [:text] config.filter_parameters += [:bio] # Enable the asset pipeline config.assets.enabled = true config.assets.initialize_on_precompile = false # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # Javascripts config.assets.precompile += [ "aspect-contacts.js", "contact-list.js", "finder.js", "home.js", "ie.js", "inbox.js", "jquery.js", "jquery_ujs.js", "jquery.textchange.js", "login.js", "mailchimp.js", "main.js", "mobile.js", "profile.js", "people.js", "photos.js", "profile.js", "publisher.js", "templates.js", "validation.js" ] # Stylesheets config.assets.precompile += [ "blueprint.css", "bootstrap.css", "bootstrap-complete.css", "bootstrap-responsive.css", "default.css", "error_pages.css", "login.css", "mobile.css", "new-templates.css", "rtl.css" ] # Rails Admin - these assets need to be added here since the Engine initializer # doesn't run with initialize_on_precompile disabled. This list is taken # directly from the Rails Admin Engine initializer. config.assets.precompile += ['rails_admin/rails_admin.js', 'rails_admin/rails_admin.css', 'rails_admin/jquery.colorpicker.js', 'rails_admin/jquery.colorpicker.css'] # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end
module Cornerstone module Source VERSION = "0.1.11" end end 0.1.12 module Cornerstone module Source VERSION = "0.1.12" end end
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Mowoli class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true # Here we're storing our worklist (XML) files for dcm4che's dcmof. config.worklist_dir = ENV['MWL_DIR'] || File.join(Rails.root, 'worklist') end end Switch time zone to Berlin. require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Mowoli class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' config.time_zone = 'Berlin' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true # Here we're storing our worklist (XML) files for dcm4che's dcmof. config.worklist_dir = ENV['MWL_DIR'] || File.join(Rails.root, 'worklist') end end
# coding: utf-8 module UIAutoMonkey require 'fileutils' require 'timeout' require 'rexml/document' require 'erubis' require 'json' class MonkeyRunner TRACE_TEMPLATE='/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate' RESULT_BASE_PATH = File.expand_path('crash_monkey_result') RESULT_DETAIL_EVENT_NUM = 20 TIME_LIMIT_SEC = 100 include UIAutoMonkey::CommandHelper def run(opts) @options = opts if @options[:show_config] show_config return true end log @options.inspect FileUtils.remove_dir(result_base_dir, true) FileUtils.makedirs(result_base_dir) generate_ui_auto_monkey ########### start_time = Time.now result_list = [] total_test_count.times do |times| @times = times setup_running result = run_a_case finish_running(result) result_list << result end # create_index_html({ :start_time => start_time, :end_time => Time.now, :result_list => result_list, }) all_tests_ok?(result_list) end def setup_running kill_all('iPhone Simulator') FileUtils.remove_dir(result_dir, true) ENV['UIARESULTSPATH'] = result_dir @crashed = false end def run_a_case log "=================================== Start Test (#{@times+1}/#{total_test_count}) =======================================" cr_list = crash_report_list start_time = Time.now watch_syslog do begin Timeout.timeout(time_limit_sec + 5) do run_process(%W(instruments -l #{time_limit} -t #{TRACE_TEMPLATE} #{app_path} -e UIASCRIPT #{ui_auto_monkey_path} -e UIARESULTSPATH #{result_base_dir})) end rescue Timeout::Error log 'killall -9 instruments' kill_all('instruments', '9') end end new_cr_list = crash_report_list # increase crash report? unless cr_list[0] == new_cr_list[0] @crashed = true log "Find new crash report: #{new_cr_list[0]}" FileUtils.copy(new_cr_list[0], result_dir) end # output result create_result_html(parse_results) { :start_time => start_time, :end_time => Time.now, :times => @times, :ok => !@crashed, :result_dir => File.basename(result_history_dir(@times)), :message => nil } end def finish_running(result) FileUtils.remove_dir(result_history_dir(@times), true) FileUtils.move(result_dir, result_history_dir(@times)) kill_all('iPhone Simulator') end def create_index_html(result_hash) er = Erubis::Eruby.new(File.read(template_path('index.html.erb'))) result_hash[:test_count] = result_hash[:result_list].size result_hash[:ok_count] = result_hash[:result_list].select {|r| r[:ok]}.size result_hash[:ng_count] = result_hash[:test_count] - result_hash[:ok_count] open("#{result_base_dir}/index.html", 'w') {|f| f.write er.result(result_hash)} copy_html_resources end def copy_html_resources bootstrap_dir = File.expand_path('../../bootstrap', __FILE__) FileUtils.copy("#{bootstrap_dir}/css/bootstrap.css", result_base_dir) FileUtils.copy("#{bootstrap_dir}/js/bootstrap.js", result_base_dir) end def all_tests_ok?(result_list) result_list.select {|r| !r[:ok]}.empty? end def show_config puts File.read(config_json_path) end def log(msg) puts msg end def total_test_count (@options[:run_count] || 2) end def app_path @app_path ||= find_app_path(@options) end def app_name File.basename(app_path).gsub(/\.app$/, '') end def time_limit time_limit_sec * 1000 end def time_limit_sec (@options[:time_limit_sec] || TIME_LIMIT_SEC).to_i end def ui_auto_monkey_original_path File.expand_path('../../ui-auto-monkey/UIAutoMonkey.js', __FILE__) end def ui_auto_monkey_path "#{result_base_dir}/UIAutoMonkey.js" end def result_base_dir @options[:result_base_dir] || RESULT_BASE_PATH end def result_dir "#{result_base_dir}/Run 1" end def result_history_dir(times) "#{result_base_dir}/result_#{sprintf('%03d', times)}" end def crash_report_dir "#{ENV['HOME']}/Library/Logs/DiagnosticReports" end def find_apps(app) `"ls" -dt #{ENV['HOME']}/Library/Developer/Xcode/DerivedData/*/Build/Products/*/#{app}`.strip.split(/\n/) end def crash_report_list `ls -t #{crash_report_dir}/#{app_name}_*.crash`.strip.split(/\n/) end def grep_syslog 'tail -n 0 -f /var/log/system.log' end def console_log_path "#{result_dir}/console.log" end def template_path(name) File.expand_path("../templates/#{name}", __FILE__) end def generate_ui_auto_monkey orig = File.read(ui_auto_monkey_original_path) config = JSON.parse(File.read(config_json_path)) replace_str = " config: #{JSON.pretty_generate(config, :indent => ' '*6)}, \n" js = replace_text(orig, replace_str, '__UIAutoMonkey Configuration Begin__', '__UIAutoMonkey Configuration End__') File.open(ui_auto_monkey_path, 'w') {|f| f.write(js)} end def config_json_path @options[:config_path] || template_path('config.json') end def replace_text(orig, replace_str, marker_begin_line, marker_end_line) results = [] status = 1 orig.each_line do |line| if status == 1 && line =~ /#{marker_begin_line}/ status = 2 results << line results << replace_str elsif status == 2 && line =~/#{marker_end_line}/ status = 3 end results << line unless status == 2 end results.join('') end def find_app_path(opts) app_path = nil if opts[:app_path].include?('/') app_path = opts[:app_path] elsif opts[:app_path] =~ /\.app$/ apps = find_apps(opts[:app_path]) app_path = apps[0] log "#{apps.size} apps are found, USE NEWEST APP: #{app_path}" if apps.size > 1 end unless app_path raise 'Invalid AppName' end app_path end def parse_results filename = "#{result_dir}/Automation Results.plist" log_list = [] if File.exists?(filename) doc = REXML::Document.new(open(filename)) doc.elements.each('plist/dict/array/dict') do |record| ary = record.elements.to_a.map{|a| a.text} log_list << Hash[*ary] end @crashed = true if log_list[-1][LOG_TYPE] == 'Fail' end log_list end def create_result_html(log_list) latest_list = LogDecoder.new(log_list).decode_latest(RESULT_DETAIL_EVENT_NUM) hash = {} hash[:log_list] = latest_list.reverse hash[:log_list_json] = JSON.dump(hash[:log_list]) crash_report = Dir.glob("#{result_dir}/*.crash")[0] hash[:crash_report] = crash_report ? File.basename(crash_report) : nil hash[:crashed] = @crashed er = Erubis::Eruby.new(File.read(template_path('result.html.erb'))) open("#{result_dir}/result.html", 'w') do |f| f.write(er.result(hash)) end FileUtils.copy(template_path('result_view.js'), "#{result_dir}/result_view.js") end def watch_syslog STDOUT.sync = true stdin, stdout, stderr = Open3.popen3(grep_syslog) log_filename = "#{result_base_dir}/console.log" thread = Thread.new do File.open(log_filename, 'a') do |output| begin while true line = stdout.readline output.write(line) if line.include?(app_name) end rescue IOError log 'tail finished: system.log' end end end yield sleep 3 stdout.close; stderr.close; stdin.close thread.join FileUtils.makedirs(result_dir) unless File.exists?(result_dir) if File.exists?(log_filename) FileUtils.move(log_filename, console_log_path) end end end LOG_TYPE = 'LogType' MESSAGE = 'Message' TIMESTAMP = 'Timestamp' SCREENSHOT = 'Screenshot' class LogDecoder def initialize(log_list) @log_list = log_list end def decode_latest(num=10) hash = {} ret = [] @log_list.reverse.each do |log| break if num == 0 if log[LOG_TYPE] == 'Screenshot' if log[MESSAGE] =~ /^action/ hash[:action_image] = log[MESSAGE] elsif log[MESSAGE] =~ /^screen/ hash[:screen_image] = log[MESSAGE] hash[:timestamp] = log[TIMESTAMP] # emit and init if block_given? yield(hash) else ret << hash end hash = {} num -= 1 end elsif log[LOG_TYPE] == 'Debug' && log[MESSAGE] =~ /^target./ hash[:message] = log[MESSAGE] unless log[MESSAGE] =~ /^target.captureRectWithName/ && log[MESSAGE] =~ /switcherScrollView/ end end ret end end end File.expand_path to opts[:app_path] # coding: utf-8 module UIAutoMonkey require 'fileutils' require 'timeout' require 'rexml/document' require 'erubis' require 'json' class MonkeyRunner TRACE_TEMPLATE='/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate' RESULT_BASE_PATH = File.expand_path('crash_monkey_result') RESULT_DETAIL_EVENT_NUM = 20 TIME_LIMIT_SEC = 100 include UIAutoMonkey::CommandHelper def run(opts) @options = opts if @options[:show_config] show_config return true end log @options.inspect FileUtils.remove_dir(result_base_dir, true) FileUtils.makedirs(result_base_dir) generate_ui_auto_monkey ########### start_time = Time.now result_list = [] total_test_count.times do |times| @times = times setup_running result = run_a_case finish_running(result) result_list << result end # create_index_html({ :start_time => start_time, :end_time => Time.now, :result_list => result_list, }) all_tests_ok?(result_list) end def setup_running # kill_all('iPhone Simulator') FileUtils.remove_dir(result_dir, true) ENV['UIARESULTSPATH'] = result_dir @crashed = false end def run_a_case log "=================================== Start Test (#{@times+1}/#{total_test_count}) =======================================" cr_list = crash_report_list start_time = Time.now watch_syslog do begin Timeout.timeout(time_limit_sec + 5) do run_process(%W(instruments -l #{time_limit} -t #{TRACE_TEMPLATE} #{app_path} -e UIASCRIPT #{ui_auto_monkey_path} -e UIARESULTSPATH #{result_base_dir})) end rescue Timeout::Error log 'killall -9 instruments' kill_all('instruments', '9') end end new_cr_list = crash_report_list # increase crash report? unless cr_list[0] == new_cr_list[0] @crashed = true log "Find new crash report: #{new_cr_list[0]}" FileUtils.copy(new_cr_list[0], result_dir) end # output result create_result_html(parse_results) { :start_time => start_time, :end_time => Time.now, :times => @times, :ok => !@crashed, :result_dir => File.basename(result_history_dir(@times)), :message => nil } end def finish_running(result) FileUtils.remove_dir(result_history_dir(@times), true) FileUtils.move(result_dir, result_history_dir(@times)) kill_all('iPhone Simulator') end def create_index_html(result_hash) er = Erubis::Eruby.new(File.read(template_path('index.html.erb'))) result_hash[:test_count] = result_hash[:result_list].size result_hash[:ok_count] = result_hash[:result_list].select {|r| r[:ok]}.size result_hash[:ng_count] = result_hash[:test_count] - result_hash[:ok_count] open("#{result_base_dir}/index.html", 'w') {|f| f.write er.result(result_hash)} copy_html_resources end def copy_html_resources bootstrap_dir = File.expand_path('../../bootstrap', __FILE__) FileUtils.copy("#{bootstrap_dir}/css/bootstrap.css", result_base_dir) FileUtils.copy("#{bootstrap_dir}/js/bootstrap.js", result_base_dir) end def all_tests_ok?(result_list) result_list.select {|r| !r[:ok]}.empty? end def show_config puts File.read(config_json_path) end def log(msg) puts msg end def total_test_count (@options[:run_count] || 2) end def app_path @app_path ||= find_app_path(@options) end def app_name File.basename(app_path).gsub(/\.app$/, '') end def find_apps(app) `"ls" -dt #{ENV['HOME']}/Library/Developer/Xcode/DerivedData/*/Build/Products/*/#{app}`.strip.split(/\n/) end def find_app_path(opts) app_path = nil if opts[:app_path].include?('/') app_path = File.expand_path(opts[:app_path]) elsif opts[:app_path] =~ /\.app$/ apps = find_apps(opts[:app_path]) app_path = apps[0] log "#{apps.size} apps are found, USE NEWEST APP: #{app_path}" if apps.size > 1 end unless app_path raise 'Invalid AppName' end app_path end def time_limit time_limit_sec * 1000 end def time_limit_sec (@options[:time_limit_sec] || TIME_LIMIT_SEC).to_i end def ui_auto_monkey_original_path File.expand_path('../../ui-auto-monkey/UIAutoMonkey.js', __FILE__) end def ui_auto_monkey_path "#{result_base_dir}/UIAutoMonkey.js" end def result_base_dir @options[:result_base_dir] || RESULT_BASE_PATH end def result_dir "#{result_base_dir}/Run 1" end def result_history_dir(times) "#{result_base_dir}/result_#{sprintf('%03d', times)}" end def crash_report_dir "#{ENV['HOME']}/Library/Logs/DiagnosticReports" end def crash_report_list `ls -t #{crash_report_dir}/#{app_name}_*.crash`.strip.split(/\n/) end def grep_syslog 'tail -n 0 -f /var/log/system.log' end def console_log_path "#{result_dir}/console.log" end def template_path(name) File.expand_path("../templates/#{name}", __FILE__) end def generate_ui_auto_monkey orig = File.read(ui_auto_monkey_original_path) config = JSON.parse(File.read(config_json_path)) replace_str = " config: #{JSON.pretty_generate(config, :indent => ' '*6)}, \n" js = replace_text(orig, replace_str, '__UIAutoMonkey Configuration Begin__', '__UIAutoMonkey Configuration End__') File.open(ui_auto_monkey_path, 'w') {|f| f.write(js)} end def config_json_path @options[:config_path] || template_path('config.json') end def replace_text(orig, replace_str, marker_begin_line, marker_end_line) results = [] status = 1 orig.each_line do |line| if status == 1 && line =~ /#{marker_begin_line}/ status = 2 results << line results << replace_str elsif status == 2 && line =~/#{marker_end_line}/ status = 3 end results << line unless status == 2 end results.join('') end def parse_results filename = "#{result_dir}/Automation Results.plist" log_list = [] if File.exists?(filename) doc = REXML::Document.new(open(filename)) doc.elements.each('plist/dict/array/dict') do |record| ary = record.elements.to_a.map{|a| a.text} log_list << Hash[*ary] end @crashed = true if log_list[-1][LOG_TYPE] == 'Fail' end log_list end def create_result_html(log_list) latest_list = LogDecoder.new(log_list).decode_latest(RESULT_DETAIL_EVENT_NUM) hash = {} hash[:log_list] = latest_list.reverse hash[:log_list_json] = JSON.dump(hash[:log_list]) crash_report = Dir.glob("#{result_dir}/*.crash")[0] hash[:crash_report] = crash_report ? File.basename(crash_report) : nil hash[:crashed] = @crashed er = Erubis::Eruby.new(File.read(template_path('result.html.erb'))) open("#{result_dir}/result.html", 'w') do |f| f.write(er.result(hash)) end FileUtils.copy(template_path('result_view.js'), "#{result_dir}/result_view.js") end def watch_syslog STDOUT.sync = true stdin, stdout, stderr = Open3.popen3(grep_syslog) log_filename = "#{result_base_dir}/console.log" thread = Thread.new do File.open(log_filename, 'a') do |output| begin while true line = stdout.readline output.write(line) if line.include?(app_name) end rescue IOError log 'tail finished: system.log' end end end yield sleep 3 stdout.close; stderr.close; stdin.close thread.join FileUtils.makedirs(result_dir) unless File.exists?(result_dir) if File.exists?(log_filename) FileUtils.move(log_filename, console_log_path) end end end LOG_TYPE = 'LogType' MESSAGE = 'Message' TIMESTAMP = 'Timestamp' SCREENSHOT = 'Screenshot' class LogDecoder def initialize(log_list) @log_list = log_list end def decode_latest(num=10) hash = {} ret = [] @log_list.reverse.each do |log| break if num == 0 if log[LOG_TYPE] == 'Screenshot' if log[MESSAGE] =~ /^action/ hash[:action_image] = log[MESSAGE] elsif log[MESSAGE] =~ /^screen/ hash[:screen_image] = log[MESSAGE] hash[:timestamp] = log[TIMESTAMP] # emit and init if block_given? yield(hash) else ret << hash end hash = {} num -= 1 end elsif log[LOG_TYPE] == 'Debug' && log[MESSAGE] =~ /^target./ hash[:message] = log[MESSAGE] unless log[MESSAGE] =~ /^target.captureRectWithName/ && log[MESSAGE] =~ /switcherScrollView/ end end ret end end end
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "active_resource/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module Openmensa class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. config.autoload_paths += %W(#{config.root}/lib) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. config.time_zone = 'Berlin' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. config.i18n.load_path += Dir[Rails.root.join('app', 'locales', '**', '*.{rb,yml}').to_s] config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enforce whitelist mode for mass assignment. # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. config.active_record.whitelist_attributes = true # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end Rename crfs token name. require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "active_resource/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module Openmensa class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. config.autoload_paths += %W(#{config.root}/lib) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. config.time_zone = 'Berlin' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. config.i18n.load_path += Dir[Rails.root.join('app', 'locales', '**', '*.{rb,yml}').to_s] config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enforce whitelist mode for mass assignment. # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. config.active_record.whitelist_attributes = true # Change csrf token name config.action_controller.request_forgery_protection_token = '_xsrf_token' # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end
require 'spec_helper' describe Anpan::An do let(:conf) { {} } let(:anpan) { Anpan::An.new(conf) } let(:consonant) { Anpan::Consonant.new(input: :c, output: :k) } let(:vowel) { Anpan::Vowel.new({input: :a}) } describe 'config files' do let(:render) { anpan.render } config_files = { 'anpan.txt': Anpan::An::CONF, 'google_japanese_input.txt': Anpan::An::GOOGLE_JAPANESE, } config_files.each do |table, config| context 'when anpan conf given' do let(:conf) { config } let(:lines) { File.readlines("spec/table/#{table}").map(&:chomp) } describe "render covers #{table}" do File.open("spec/table/#{table}") do |file| file.each_line do |line| it "should contain '#{line}'" do expect(render.split("\n")).to include line.chomp end end end end describe "anpan.txt covers rendered" do Anpan::An.new(config).render.split("\n").each do |pattern| it "should not contain '#{pattern}' if it's not on the table file" do expect(lines).to include pattern end end end end end end describe '#render' do let(:render) { anpan.render } context 'conf one consonant and one vowel added' do before do anpan.add_consonants(consonant) anpan.add_vowels(vowel) end it 'should renter "ca\tか"' do expect(render).to eq "ca\tか" end end end describe '#patterns' do let(:conf) { Anpan::An::CONF } it 'should have no alphabets in output_jp' do anpan.patterns.each do |pattern| expect(pattern.output_jp).not_to match(/[a-z]+/) end end end describe '#consonant_list' do let(:list) { anpan.consonant_list } before do anpan.add_consonants(consonant) anpan.add_vowels(vowel) end it 'should be an Array' do expect(list).to be_a Array end it 'should have one consonant' do expect(list.size).to be 1 end it 'should output "k"' do expect(list.first.output).to eq :k end end describe '#load_consonants' do let(:list) { anpan.consonant_list } before do conf = [ { input: :c, output: :k, vowel_filter: %i(a u o) }, { input: :s }, { input: :t } ] anpan.load_consonant conf end context 'when conf size == 3' do it 'should return 3 consonants' do expect(list.size).to be 3 end it 'should output "k"' do expect(list.first.output).to eq :k end end end describe '#vowel_list' do let(:list) { anpan.vowel_list } before do anpan.load_vowel([{input: :a}]) end it 'should be an Array' do expect(list).to be_a Array end it 'should have one vowel' do expect(list.first).to be_a Anpan::Vowel end it 'should have one object' do expect(list.size).to be 1 end it 'should have output "a"' do expect(list.first.output).to be :a end end describe '#table' do let(:table) { anpan.table } it 'should return an Array' do expect(table).to be_a Array end end describe '.table' do let(:table) { Anpan::An.table } it 'should return an Array' do expect(table).to be_a Array end it 'should return an Array' do expect(table.first).to be_a Hash end it 'should return hash with input, output, and addition keys' do expect(table.first.keys).to include(*%i(input output addition)) end end end Add dvorakjp test require 'spec_helper' describe Anpan::An do let(:conf) { {} } let(:anpan) { Anpan::An.new(conf) } let(:consonant) { Anpan::Consonant.new(input: :c, output: :k) } let(:vowel) { Anpan::Vowel.new({input: :a}) } describe 'config files' do let(:render) { anpan.render } config_files = { 'anpan.txt': Anpan::An::CONF, 'google_japanese_input.txt': Anpan::An::GOOGLE_JAPANESE, 'dvorakjp_prime.txt': Anpan::An::DVORAKJP, } config_files.each do |table, config| context 'when anpan conf given' do let(:conf) { config } let(:lines) { File.readlines("spec/table/#{table}").map(&:chomp) } describe "render covers #{table}" do File.open("spec/table/#{table}") do |file| file.each_line do |line| it "should contain '#{line}'" do expect(render.split("\n")).to include line.chomp end end end end describe "anpan.txt covers rendered" do Anpan::An.new(config).render.split("\n").each do |pattern| it "should not contain '#{pattern}' if it's not on the table file" do expect(lines).to include pattern end end end end end end describe '#render' do let(:render) { anpan.render } context 'conf one consonant and one vowel added' do before do anpan.add_consonants(consonant) anpan.add_vowels(vowel) end it 'should renter "ca\tか"' do expect(render).to eq "ca\tか" end end end describe '#patterns' do let(:conf) { Anpan::An::CONF } it 'should have no alphabets in output_jp' do anpan.patterns.each do |pattern| expect(pattern.output_jp).not_to match(/[a-z]+/) end end end describe '#consonant_list' do let(:list) { anpan.consonant_list } before do anpan.add_consonants(consonant) anpan.add_vowels(vowel) end it 'should be an Array' do expect(list).to be_a Array end it 'should have one consonant' do expect(list.size).to be 1 end it 'should output "k"' do expect(list.first.output).to eq :k end end describe '#load_consonants' do let(:list) { anpan.consonant_list } before do conf = [ { input: :c, output: :k, vowel_filter: %i(a u o) }, { input: :s }, { input: :t } ] anpan.load_consonant conf end context 'when conf size == 3' do it 'should return 3 consonants' do expect(list.size).to be 3 end it 'should output "k"' do expect(list.first.output).to eq :k end end end describe '#vowel_list' do let(:list) { anpan.vowel_list } before do anpan.load_vowel([{input: :a}]) end it 'should be an Array' do expect(list).to be_a Array end it 'should have one vowel' do expect(list.first).to be_a Anpan::Vowel end it 'should have one object' do expect(list.size).to be 1 end it 'should have output "a"' do expect(list.first.output).to be :a end end describe '#table' do let(:table) { anpan.table } it 'should return an Array' do expect(table).to be_a Array end end describe '.table' do let(:table) { Anpan::An.table } it 'should return an Array' do expect(table).to be_a Array end it 'should return an Array' do expect(table.first).to be_a Hash end it 'should return hash with input, output, and addition keys' do expect(table.first.keys).to include(*%i(input output addition)) end end end
module CursedConsole class MainWindow < Curses::Window QUIT_MENU_ITEM = 'Quit' attr_reader :menu_list, :plugin_manager, :web_service_client attr_accessor :current_position def initialize(plugin_manager, web_service_client) super(0, 0, 0, 0) @current_position = -1 @plugin_manager = plugin_manager @web_service_client = web_service_client @menu_list = @plugin_manager.plugins Curses::curs_set(0) color_set(1) keypad(true) render_menu write_status_message end def main_loop while ch = getch case ch when Curses::Key::RIGHT self.current_position += 1 when Curses::Key::LEFT self.current_position -= 1 when 13, Curses::Key::ENTER return current_position if current_position == menu_list.size submenu_select = render_sub_menu(current_position) if submenu_select.present? # This is where we should invoke the form invoke_action(plugin_manager.plugins[current_position], submenu_select.first, submenu_select.last) # return [ current_position ] + submenu_select end else next if ch.is_a?(Fixnum) mlist = menu_list + [ QUIT_MENU_ITEM ] selected_item = mlist.detect { |item| item.downcase.start_with?(ch.downcase) } self.current_position = mlist.index(selected_item) unless selected_item.nil? end self.current_position = 0 if current_position < 0 self.current_position = menu_list.size if current_position > menu_list.size render_menu(self.current_position) update_status_bar end end def render_menu(item_selected=-1) setpos(0, 1) (menu_list + [ QUIT_MENU_ITEM ]).map { | i | i.capitalize }.each_with_index do | item, index | addstr(" ") if index > 0 first_char = item.slice(0, 1) remainder = item.slice(1..-1) attron(Curses::A_STANDOUT) if index == item_selected attron(Curses::A_UNDERLINE) addstr(first_char) attroff(Curses::A_UNDERLINE) addstr(remainder) attroff(Curses::A_STANDOUT) if index == item_selected end end def update_status_bar # write_status_message(menu_list[menu_list[current_position]]) unless current_position < 0 end def write_status_message(message=nil, offset=0) # %x{ echo "Line: #{lines - 1}, Message: #{message}" >> log.txt} # Clear the status line setpos(maxy - 1, 0) attron(Curses::A_STANDOUT) addstr(" " * maxx) attroff(Curses::A_STANDOUT) if ! message.nil? setpos(maxy - 1, 1) attron(Curses::A_STANDOUT) addstr(message) attroff(Curses::A_STANDOUT) end end def position_for_submenu(selected_menu_item) pos = 2 plugin_manager.plugins.each_with_index do | item, index | break if selected_menu_item >= index pos += (item.length + 1) end pos end def render_sub_menu(position) sub_path = plugin_manager.plugins[position] plugins = plugin_manager.resources_for(sub_path) plugin_menu = plugins.map do | plugin | { id: plugin, display: plugin.capitalize } end submenu = DropDownMenu.new(plugin_menu, sub_path, plugin_manager, 1, position_for_submenu(position)) submenu.select_menu_item.tap do | selection | submenu.clear submenu.refresh submenu.close end end def invoke_action(sub_path, plugin, action) # Instantiate the plugin... plugin = plugin_manager.instantiate_resource(sub_path, plugin) if plugin.requires_input_for?(action.to_sym) form = PluginForm.new(plugin, action.to_sym, self, 20, 80, 2, 2) form.handle_form(web_service_client) form.clear form.refresh form.close else # No input required. Don't need no stinkin' form the_form = plugin.send(action.to_sym) uri = the_form[:result] list = plugin.send(the_form[:result_formatter], web_service_client, uri, {}) data_list = DataList.new(list) #submenu = DropDownMenu.new(list, #nil, # sub_path #nil, # plugin_manager #1, #1, #self) # status_bar selected = data_list.handle_list.tap do | selection | data_list.clear data_list.refresh data_list.close Curses::curs_set(1) end #selected = submenu.select_menu_item.tap do | selection | #submenu.clear #submenu.refresh #submenu.close #Curses::curs_set(1) ## render_fields #end refresh end end end end Cleaned and refactored main window. module CursedConsole class MainWindow < Curses::Window QUIT_MENU_ITEM = 'Quit' attr_reader :menu_list, :plugin_manager, :web_service_client attr_accessor :current_position def initialize(plugin_manager, web_service_client) super(0, 0, 0, 0) @current_position = -1 @plugin_manager = plugin_manager @web_service_client = web_service_client @menu_list = @plugin_manager.plugins Curses::curs_set(0) color_set(1) keypad(true) render_menu end def main_loop while ch = getch case ch when Curses::Key::RIGHT self.current_position += 1 when Curses::Key::LEFT self.current_position -= 1 when 13, Curses::Key::ENTER next if current_position < 0 # Don't do anything if nothing selected return current_position if current_position == menu_list.size submenu_select = render_sub_menu(current_position) if submenu_select.present? # This is where we should invoke the form invoke_action(plugin_manager.plugins[current_position], submenu_select.first, submenu_select.last) end else next if ch.is_a?(Fixnum) mlist = menu_list + [ QUIT_MENU_ITEM ] selected_item = mlist.detect { |item| item.downcase.start_with?(ch.downcase) } self.current_position = mlist.index(selected_item) unless selected_item.nil? end self.current_position = 0 if current_position < 0 self.current_position = menu_list.size if current_position > menu_list.size render_menu(self.current_position) end end def render_menu(item_selected=-1) setpos(0, 1) (menu_list + [ QUIT_MENU_ITEM ]).map { | i | i.capitalize }.each_with_index do | item, index | addstr(" ") if index > 0 first_char = item.slice(0, 1) remainder = item.slice(1..-1) attron(Curses::A_STANDOUT) if index == item_selected attron(Curses::A_UNDERLINE) addstr(first_char) attroff(Curses::A_UNDERLINE) addstr(remainder) attroff(Curses::A_STANDOUT) if index == item_selected end end def position_for_submenu(selected_menu_item) pos = 1 menu_list.each_with_index do | item, index | break if selected_menu_item <= index pos += (item.length + 1) end pos end def render_sub_menu(position) plugin = menu_list[position] resources = plugin_manager.resources_for(plugin) resource_menu = resources.map do | resource | { id: resource, display: resource.capitalize } end submenu = DropDownMenu.new(resource_menu, plugin, plugin_manager, 1, position_for_submenu(position)) submenu.select_menu_item.tap do | selection | submenu.clear submenu.refresh submenu.close end end def invoke_action(plugin, resource, action) # Instantiate the resource... rsrc = plugin_manager.instantiate_resource(plugin, resource) if rsrc.requires_input_for?(action.to_sym) handle_form(rsrc, action) else # No input required. Don't need no stinkin' form handle_results(rsrc, action) end end def handle_form(rsrc, action) form = PluginForm.new(rsrc, action.to_sym, self, 20, 80, 2, 2) form.handle_form(web_service_client) form.clear form.refresh form.close end def handle_results(rsrc, action) the_form = rsrc.send(action.to_sym) uri = the_form[:result] list = rsrc.send(the_form[:result_formatter], web_service_client, uri, {}) data_list = DataList.new(list) selected = data_list.handle_list.tap do | selection | data_list.clear data_list.refresh data_list.close Curses::curs_set(1) end refresh end end end
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Kubh class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. ActionMailer::Base.smtp_settings = { address: 'smtp.gmail.com', port: 587, domain: '103.253.146.220:80', user_name: 'bloggervista@gmail.com', password: 'lovegod757', authentication: :plain, enable_starttls_auto: true } end end gmail username and password require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Kubh class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. ActionMailer::Base.smtp_settings = { address: 'smtp.gmail.com', port: 587, domain: 'chatounce.com', user_name: 'chatounce98@gmail.com', password: 'chatounce@', authentication: :plain, enable_starttls_auto: true } end end
=begin This file is part of ViewpointSPWS; the Ruby library for Microsoft Sharepoint Web Services. Copyright © 2011 Dan Wanek <dan.wanek@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =end require 'kconv' if(RUBY_VERSION.start_with? '1.9') # bug in rubyntlm with ruby 1.9.x require 'base64' require 'httpclient' require 'uri' require 'nokogiri' require 'logging' require 'pathname' # This is the base module for all other classes module Viewpoint module SPWS attr_reader :logger Logging.logger.root.level = :info Logging.logger.root.appenders = Logging.appenders.stdout def self.root_logger Logging.logger.root end def self.set_log_level(level) Logging.logger.root.level = level end end end # ----- Monkey Patches ----- require 'extensions/string' # ----- Library Files ----- require 'spws/connection' require 'spws/websvc/web_service_base' # Copy Web Service require 'spws/websvc/copy' # Lists Web Service require 'spws/websvc/lists' module Viewpoint::SPWS::Types; end require 'spws/types/list' require 'spws/types/tasks_list' require 'spws/types/list_item' # User and Groups Web Service require 'spws/websvc/user_group' require 'spws/types/user' require 'spws/spws_client' remove Bundler created files and fix version include =begin This file is part of ViewpointSPWS; the Ruby library for Microsoft Sharepoint Web Services. Copyright © 2011 Dan Wanek <dan.wanek@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =end require 'kconv' if(RUBY_VERSION.start_with? '1.9') # bug in rubyntlm with ruby 1.9.x require 'base64' require 'httpclient' require 'uri' require 'nokogiri' require 'logging' require 'pathname' # This is the base module for all other classes module Viewpoint module SPWS attr_reader :logger Logging.logger.root.level = :info Logging.logger.root.appenders = Logging.appenders.stdout def self.root_logger Logging.logger.root end def self.set_log_level(level) Logging.logger.root.level = level end end end require 'spws/version' # ----- Monkey Patches ----- require 'extensions/string' # ----- Library Files ----- require 'spws/connection' require 'spws/websvc/web_service_base' # Copy Web Service require 'spws/websvc/copy' # Lists Web Service require 'spws/websvc/lists' module Viewpoint::SPWS::Types; end require 'spws/types/list' require 'spws/types/tasks_list' require 'spws/types/list_item' # User and Groups Web Service require 'spws/websvc/user_group' require 'spws/types/user' require 'spws/spws_client'
require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "action_cable/engine" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module SendgridStatsApiConsumer class Application < Rails::Application config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :options] end end end end moved email url host require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "action_cable/engine" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module SendgridStatsApiConsumer class Application < Rails::Application config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :options] end end end end Rails.application.configure do config.action_mailer.perform_deliveries = true config.action_mailer.default_url_options = { host: 'simplymailstatistics.com' } config.action_mailer.delivery_method = :smtp config.active_job.queue_adapter = :delayed_job end
# frozen_string_literal: true require_relative "klass_determination" module Delfos module MethodLogging class Code extend Forwardable delegate [:object, :method_type, :method_name, :line_number, :method_definition_file, :method_definition_line] => :code_location attr_reader :code_location def initialize(code_location) @code_location = code_location end def self.from_caller(stack, caller_binding) location = CodeLocation.from_caller(stack, caller_binding) return unless location new location end def self.from_called(object, called_method, class_method) location = CodeLocation.from_called(object, called_method, class_method) return unless location new location end def file file = code_location.file.to_s if file Delfos.application_directories.map do |d| file = relative_path(file, d) end end file end def relative_path(file, dir) match = dir.to_s.split("/")[0..-2].join("/") if file[match] file = file.gsub(match, ""). gsub(%r{^/}, "") end file end def klass name = code_location.klass.name || "__AnonymousClass" name.tr ":", "_" end end # This magic number is determined based on the specific implementation now # E.g. if the line # where we call this `caller_binding.of_caller(stack_index + STACK_OFFSET).eval('self')` # is to be extracted into another method we will get a failing test and have to increment # the value STACK_OFFSET = 4 class CodeLocation include KlassDetermination class << self def from_caller(stack, caller_binding) current = stack.detect do |s| file = s.split(":")[0] Delfos::MethodLogging.include_file_in_logging?(file) end return unless current stack_index = stack.index { |c| c == current } object = caller_binding.of_caller(stack_index + STACK_OFFSET).eval("self") class_method = object.kind_of? Module file, line_number, rest = current.split(":") method_name = rest[/`.*'$/] method_name = method_name.gsub("`", "").gsub("'", "") new(object, method_name.to_s, class_method, file, line_number.to_i) end def from_called(object, called_method, class_method) file, line_number = called_method.source_location new(object, called_method.name.to_s, class_method, file, line_number) end def method_type_from(class_method) class_method ? "ClassMethod" : "InstanceMethod" end def method_definition_for(klass, class_method, method_name) key = key_from(class_method, method_name) Delfos::Patching.added_methods[klass][key] end private def key_from(class_method, name) "#{method_type_from(class_method)}_#{name}" end end attr_reader :object, :method_name, :class_method, :method_type, :file, :line_number def initialize(object, method_name, class_method, file, line_number) @object = object @method_name = method_name @class_method = class_method @method_type = self.class.method_type_from class_method @file = file @line_number = line_number end def method_definition_file method_definition[0] end def method_definition_line method_definition[1] end def klass klass_for(object) end private def method_key "#{method_type}_#{method_name}" end def method_definition @method_definition ||= self.class.method_definition_for(klass, class_method, method_name) end end end end refactor # frozen_string_literal: true require_relative "klass_determination" module Delfos module MethodLogging class Code extend Forwardable delegate [:object, :method_type, :method_name, :line_number, :method_definition_file, :method_definition_line] => :code_location attr_reader :code_location def initialize(code_location) @code_location = code_location end def self.from_caller(stack, caller_binding) location = CodeLocation.from_caller(stack, caller_binding) return unless location new location end def self.from_called(object, called_method, class_method) location = CodeLocation.from_called(object, called_method, class_method) return unless location new location end def file file = code_location.file.to_s if file Delfos.application_directories.map do |d| file = relative_path(file, d) end end file end def relative_path(file, dir) match = dir.to_s.split("/")[0..-2].join("/") if file[match] file = file.gsub(match, ""). gsub(%r{^/}, "") end file end def klass name = code_location.klass.name || "__AnonymousClass" name.tr ":", "_" end end # This magic number is determined based on the specific implementation now # E.g. if the line # where we call this `caller_binding.of_caller(stack_index + STACK_OFFSET).eval('self')` # is to be extracted into another method we will get a failing test and have to increment # the value STACK_OFFSET = 5 class CodeLocation include KlassDetermination class << self def from_caller(stack, caller_binding) current = current_from(stack) return unless current object = object_from(stack, current, caller_binding) class_method = object.kind_of? Module file, line_number, method_name = method_details_from(current) new(object, method_name.to_s, class_method, file, line_number) end def from_called(object, called_method, class_method) file, line_number = called_method.source_location new(object, called_method.name.to_s, class_method, file, line_number) end def method_type_from(class_method) class_method ? "ClassMethod" : "InstanceMethod" end def method_definition_for(klass, class_method, method_name) key = key_from(class_method, method_name) Delfos::Patching.added_methods[klass][key] end private def current_from(stack) stack.detect do |s| file = s.split(":")[0] Delfos::MethodLogging.include_file_in_logging?(file) end end def object_from(stack, current, caller_binding) stack_index = stack.index { |c| c == current } caller_binding.of_caller(stack_index + STACK_OFFSET).eval("self") end def method_details_from(current) current.split(":") file, line_number, rest = current.split(":") method_name = rest[/`.*'$/] method_name.gsub!("`", "").gsub!("'", "") [file, line_number.to_i, method_name] end def key_from(class_method, name) "#{method_type_from(class_method)}_#{name}" end end attr_reader :object, :method_name, :class_method, :method_type, :file, :line_number def initialize(object, method_name, class_method, file, line_number) @object = object @method_name = method_name @class_method = class_method @method_type = self.class.method_type_from class_method @file = file @line_number = line_number end def method_definition_file method_definition[0] end def method_definition_line method_definition[1] end def klass klass_for(object) end private def method_key "#{method_type}_#{method_name}" end def method_definition @method_definition ||= self.class.method_definition_for(klass, class_method, method_name) end end end end
module Vultr class Resource attr_reader :client def initialize(client) @client = client end private def get_request(url, params: {}, headers: {}) handle_response client.connection.get(url, params, default_headers.merge(headers)) end def post_request(url, body:, headers: {}) handle_response client.connection.post(url, body, default_headers.merge(headers)) end def patch_request(url, body:, headers: {}) handle_response client.connection.patch(url, body, default_headers.merge(headers)) end def put_request(url, body:, headers: {}) handle_response client.connection.put(url, body, default_headers.merge(headers)) end def delete_request(url, params: {}, headers: {}) handle_response client.connection.delete(url, params, default_headers.merge(headers)) end def default_headers {Authorization: "Bearer #{client.api_key}"} end def handle_response(response) case response.status when 400 raise Error, "Your request was malformed. #{response.body["error"]}" when 401 raise Error, "You did not supply valid authentication credentials. #{response.body["error"]}" when 403 raise Error, "You are not allowed to perform that action. #{response.body["error"]}" when 404 raise Error, "No results were found for your request. #{response.body["error"]}" when 429 raise Error, "Your request exceeded the API rate limit. #{response.body["error"]}" when 500 raise Error, "We were unable to perform the request due to server-side problems. #{response.body["error"]}" end response end end end Add rate limit status handling module Vultr class Resource attr_reader :client def initialize(client) @client = client end private def get_request(url, params: {}, headers: {}) handle_response client.connection.get(url, params, default_headers.merge(headers)) end def post_request(url, body:, headers: {}) handle_response client.connection.post(url, body, default_headers.merge(headers)) end def patch_request(url, body:, headers: {}) handle_response client.connection.patch(url, body, default_headers.merge(headers)) end def put_request(url, body:, headers: {}) handle_response client.connection.put(url, body, default_headers.merge(headers)) end def delete_request(url, params: {}, headers: {}) handle_response client.connection.delete(url, params, default_headers.merge(headers)) end def default_headers {Authorization: "Bearer #{client.api_key}"} end def handle_response(response) case response.status when 400 raise Error, "Your request was malformed. #{response.body["error"]}" when 401 raise Error, "You did not supply valid authentication credentials. #{response.body["error"]}" when 403 raise Error, "You are not allowed to perform that action. #{response.body["error"]}" when 404 raise Error, "No results were found for your request. #{response.body["error"]}" when 429 raise Error, "Your request exceeded the API rate limit. #{response.body["error"]}" when 500 raise Error, "We were unable to perform the request due to server-side problems. #{response.body["error"]}" when 503 raise Error, "You have been rate limited for sending more than 20 requests per second. #{response.body["error"]}" end response end end end
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) Dotenv::Railtie.load require 'yelp' Yelp.client.configure do |config| config.consumer_key = ENV['YELP_CONSUMER_KEY'] config.consumer_secret = ENV['YELP_CONSUMER_SECRET'] config.token = ENV['YELP_TOKEN_KEY'] config.token_secret = ENV['YELP_TOKEN_SECRET'] end module MealetteBackend class Application < Rails::Application config.middleware.insert_before 0, "Rack::Cors" do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :options] end end # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end Remove dotenv for deploy require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) # Dotenv::Railtie.load require 'yelp' Yelp.client.configure do |config| config.consumer_key = ENV['YELP_CONSUMER_KEY'] config.consumer_secret = ENV['YELP_CONSUMER_SECRET'] config.token = ENV['YELP_TOKEN_KEY'] config.token_secret = ENV['YELP_TOKEN_SECRET'] end module MealetteBackend class Application < Rails::Application config.middleware.insert_before 0, "Rack::Cors" do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :options] end end # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end
module Weeler VERSION = "0.0.4" end bump to 0.1.0 module Weeler VERSION = "0.1.0" end
# encoding: UTF-8 require 'ext/highlighter' module Wingtips PHOTO_CREDIT_SIZE = 18 CODE_SIZE = 30 BULLET_POINT_SIZE = 40 HEADLINE_SIZE = 65 VERY_BIG_SIZE = 80 ENORMOUS_SIZE = 140 class Slide include HH::Markup IMAGES_DIRECTORY = 'images/' CODE_DIRECTORY = 'code/' attr_reader :app def initialize(app) @app = app @effects = [] after_initialize end def content # implemented by subclasses end def show @main_slot = stack height: app.height do content end end def append(&blk) @main_slot.append &blk end # copied from the URL implementation... weird but I want to have # classes not methods for this def method_missing(method, *args, &blk) if app_should_handle_method? method app.send(method, *args, &blk) else super end end def code(string, demo_as_effect = false, &block) source = source_from string source = source.split("\n").map{|line| ' ' + line}.join("\n") highlighted_code = para *highlight(source), size: CODE_SIZE add_demo_as_effect(source, &block) if demo_as_effect highlighted_code end def demo(string, &block) source = source_from string eval source last_app = Shoes.apps.last last_app.keypress do |key| last_app.quit if key == :control_w end yield last_app if block_given? end def source_from(string) file_path = find_file_in(string, [CODE_DIRECTORY]) if file_path File.read file_path else string end end def add_demo_as_effect(string, &block) add_effect do demo(string, &block) end end def add_effect(&effect) @effects << effect end def headline(string) text = title ' ' + string, size: HEADLINE_SIZE empty_line text end def bullet(string) para ' • ' + string, size: BULLET_POINT_SIZE end def empty_line para ' ', size: BULLET_POINT_SIZE end def image(path, *args) app.image(image_path(path), *args) end def image_path(path) path = find_file_in(path, [IMAGES_DIRECTORY]) File.expand_path(path) end def fullscreen_image(path) img = image path height_ratio = height.to_r/img.height width_ratio = width.to_r/img.width scale_image_by img, [width_ratio, height_ratio].max img end def fully_shown_image(path, additional_height = 0) img = image path height_ratio = (height - additional_height).to_r/img.height width_ratio = width.to_r/img.width scale_image_by img, [width_ratio, height_ratio].min img end def scale_image_by(img, ratio) img.width = (img.width * ratio).to_i img.height = (img.height * ratio).to_i end def centered_title(string, opts={}) para string, defaulted_options(opts, align: 'center', size: VERY_BIG_SIZE, margin_top: 50) end def centered_subtitle(string, opts={}) para string, defaulted_options(opts, align: 'center', size: BULLET_POINT_SIZE, margin_top: 50) end def centered_huge_text(string, opts={}) para string, defaulted_options(opts, align: 'center', size: VERY_BIG_SIZE, margin_top: 50) end def centered_enormous_text(string, opts={}) para string, defaulted_options(opts, align: 'center', size: ENORMOUS_SIZE, margin_top: 50) end def defaulted_options(passed, defaults={}) results = defaults.merge(passed) if results[:vertical_align] == 'center' results[:margin_top] = height/2 - 100 end results end def after_initialize # subclasses if an after hook is needed end def effects_left? !@effects.empty? end def trigger_effect effect = @effects.shift @main_slot.append &effect end private def find_file_in(file_path, locations) candidate_locations = locations.map {|location| location + file_path} candidate_locations << file_path candidate_locations.find do |candidate_path| is_file_path? candidate_path end end def is_file_path?(file_path) File.exist? file_path end def app_should_handle_method? method_name !self.respond_to?(method_name) && app.respond_to?(method_name) end end end center_horizontally method to center any element (like images) # encoding: UTF-8 require 'ext/highlighter' module Wingtips PHOTO_CREDIT_SIZE = 18 CODE_SIZE = 30 BULLET_POINT_SIZE = 40 HEADLINE_SIZE = 65 VERY_BIG_SIZE = 80 ENORMOUS_SIZE = 140 class Slide include HH::Markup IMAGES_DIRECTORY = 'images/' CODE_DIRECTORY = 'code/' attr_reader :app def initialize(app) @app = app @effects = [] after_initialize end def content # implemented by subclasses end def show @main_slot = stack height: app.height do content end end def append(&blk) @main_slot.append &blk end # copied from the URL implementation... weird but I want to have # classes not methods for this def method_missing(method, *args, &blk) if app_should_handle_method? method app.send(method, *args, &blk) else super end end def code(string, demo_as_effect = false, &block) source = source_from string source = source.split("\n").map{|line| ' ' + line}.join("\n") highlighted_code = para *highlight(source), size: CODE_SIZE add_demo_as_effect(source, &block) if demo_as_effect highlighted_code end def demo(string, &block) source = source_from string eval source last_app = Shoes.apps.last last_app.keypress do |key| last_app.quit if key == :control_w end yield last_app if block_given? end def source_from(string) file_path = find_file_in(string, [CODE_DIRECTORY]) if file_path File.read file_path else string end end def add_demo_as_effect(string, &block) add_effect do demo(string, &block) end end def add_effect(&effect) @effects << effect end def headline(string) text = title ' ' + string, size: HEADLINE_SIZE empty_line text end def bullet(string) para ' • ' + string, size: BULLET_POINT_SIZE end def empty_line para ' ', size: BULLET_POINT_SIZE end def image(path, *args) app.image(image_path(path), *args) end def image_path(path) path = find_file_in(path, [IMAGES_DIRECTORY]) File.expand_path(path) end def fullscreen_image(path) img = image path height_ratio = height.to_r/img.height width_ratio = width.to_r/img.width scale_image_by img, [width_ratio, height_ratio].max img end def fully_shown_image(path, additional_height = 0) img = image path height_ratio = (height - additional_height).to_r/img.height width_ratio = width.to_r/img.width scale_image_by img, [width_ratio, height_ratio].min img end def scale_image_by(img, ratio) img.width = (img.width * ratio).to_i img.height = (img.height * ratio).to_i end def centered_title(string, opts={}) para string, defaulted_options(opts, align: 'center', size: VERY_BIG_SIZE, margin_top: 50) end def centered_subtitle(string, opts={}) para string, defaulted_options(opts, align: 'center', size: BULLET_POINT_SIZE, margin_top: 50) end def centered_huge_text(string, opts={}) para string, defaulted_options(opts, align: 'center', size: VERY_BIG_SIZE, margin_top: 50) end def centered_enormous_text(string, opts={}) para string, defaulted_options(opts, align: 'center', size: ENORMOUS_SIZE, margin_top: 50) end def center_horizontally(element) element.left = @app.width / 2 - element.width / 2 end def defaulted_options(passed, defaults={}) results = defaults.merge(passed) if results[:vertical_align] == 'center' results[:margin_top] = height/2 - 100 end results end def after_initialize # subclasses if an after hook is needed end def effects_left? !@effects.empty? end def trigger_effect effect = @effects.shift @main_slot.append &effect end private def find_file_in(file_path, locations) candidate_locations = locations.map {|location| location + file_path} candidate_locations << file_path candidate_locations.find do |candidate_path| is_file_path? candidate_path end end def is_file_path?(file_path) File.exist? file_path end def app_should_handle_method? method_name !self.respond_to?(method_name) && app.respond_to?(method_name) end end end
require File.expand_path('../boot', __FILE__) require 'rails/all' if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module Dinesafe class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # See "6 Schema Dumping and You": http://guides.rubyonrails.org/migrations.html # This will dump the database to a schema.sql file instead of schema.rb # Needed because the ruby dump doesn't support Postgres-specific column # types, i.e. "point". config.active_record.schema_format = :sql # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end Add asset precompile list require File.expand_path('../boot', __FILE__) require 'rails/all' if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module Dinesafe class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # See "6 Schema Dumping and You": http://guides.rubyonrails.org/migrations.html # This will dump the database to a schema.sql file instead of schema.rb # Needed because the ruby dump doesn't support Postgres-specific column # types, i.e. "point". config.active_record.schema_format = :sql # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' config.assets.precompile += %w( application_mobile.css ) end end
require File.expand_path('../boot', __FILE__) require 'rails' # Pick the frameworks you want: require 'active_model/railtie' require 'active_job/railtie' require 'active_record/railtie' require 'action_controller/railtie' require 'action_mailer/railtie' require 'action_view/railtie' require 'sprockets/railtie' # require 'rails/test_unit/railtie' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Cms class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true # Raises error for missing translations config.action_view.raise_on_missing_translations = true config.i18n.enforce_available_locales = true # Lograge options config.lograge.custom_options = lambda do |event| { host: event.payload[:host], remote_ip: event.payload[:remote_ip], request_id: event.payload[:request_id], user_agent: "\"#{event.payload[:user_agent]}\"", user_id: event.payload[:user_id] } end # Customer middleware config.middleware.use Rack::Protection end end Remove active_job as not used require File.expand_path('../boot', __FILE__) require 'rails' # Pick the frameworks you want: require 'active_model/railtie' # require 'active_job/railtie' require 'active_record/railtie' require 'action_controller/railtie' require 'action_mailer/railtie' require 'action_view/railtie' require 'sprockets/railtie' # require 'rails/test_unit/railtie' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Cms class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true # Raises error for missing translations config.action_view.raise_on_missing_translations = true config.i18n.enforce_available_locales = true # Lograge options config.lograge.custom_options = lambda do |event| { host: event.payload[:host], remote_ip: event.payload[:remote_ip], request_id: event.payload[:request_id], user_agent: "\"#{event.payload[:user_agent]}\"", user_id: event.payload[:user_id] } end # Customer middleware config.middleware.use Rack::Protection end end
module Devise module Controllers # Those helpers are convenience methods added to ApplicationController. module Helpers extend ActiveSupport::Concern include Devise::Controllers::SignInOut include Devise::Controllers::StoreLocation included do if respond_to?(:helper_method) helper_method :warden, :signed_in?, :devise_controller? end end module ClassMethods # Define authentication filters and accessor helpers for a group of mappings. # These methods are useful when you are working with multiple mappings that # share some functionality. They are pretty much the same as the ones # defined for normal mappings. # # Example: # # inside BlogsController (or any other controller, it doesn't matter which): # devise_group :blogger, contains: [:user, :admin] # # Generated methods: # authenticate_blogger! # Redirects unless user or admin are signed in # blogger_signed_in? # Checks whether there is either a user or an admin signed in # current_blogger # Currently signed in user or admin # current_bloggers # Currently signed in user and admin # # Use: # before_action :authenticate_blogger! # Redirects unless either a user or an admin are authenticated # before_action ->{ authenticate_blogger! :admin } # Redirects to the admin login page # current_blogger :user # Preferably returns a User if one is signed in # def devise_group(group_name, opts={}) mappings = "[#{ opts[:contains].map { |m| ":#{m}" }.join(',') }]" class_eval <<-METHODS, __FILE__, __LINE__ + 1 def authenticate_#{group_name}!(favourite=nil, opts={}) unless #{group_name}_signed_in? mappings = #{mappings} mappings.unshift mappings.delete(favourite.to_sym) if favourite mappings.each do |mapping| opts[:scope] = mapping warden.authenticate!(opts) if !devise_controller? || opts.delete(:force) end end end def #{group_name}_signed_in? #{mappings}.any? do |mapping| warden.authenticate?(scope: mapping) end end def current_#{group_name}(favourite=nil) mappings = #{mappings} mappings.unshift mappings.delete(favourite.to_sym) if favourite mappings.each do |mapping| current = warden.authenticate(scope: mapping) return current if current end nil end def current_#{group_name.to_s.pluralize} #{mappings}.map do |mapping| warden.authenticate(scope: mapping) end.compact end if respond_to?(:helper_method) helper_method "current_#{group_name}", "current_#{group_name.to_s.pluralize}", "#{group_name}_signed_in?" end METHODS end def log_process_action(payload) payload[:status] ||= 401 unless payload[:exception] super end end # Define authentication filters and accessor helpers based on mappings. # These filters should be used inside the controllers as before_actions, # so you can control the scope of the user who should be signed in to # access that specific controller/action. # Example: # # Roles: # User # Admin # # Generated methods: # authenticate_user! # Signs user in or redirect # authenticate_admin! # Signs admin in or redirect # user_signed_in? # Checks whether there is a user signed in or not # admin_signed_in? # Checks whether there is an admin signed in or not # current_user # Current signed in user # current_admin # Current signed in admin # user_session # Session data available only to the user scope # admin_session # Session data available only to the admin scope # # Use: # before_action :authenticate_user! # Tell devise to use :user map # before_action :authenticate_admin! # Tell devise to use :admin map # def self.define_helpers(mapping) #:nodoc: mapping = mapping.name class_eval <<-METHODS, __FILE__, __LINE__ + 1 def authenticate_#{mapping}!(opts={}) opts[:scope] = :#{mapping} warden.authenticate!(opts) if !devise_controller? || opts.delete(:force) end def #{mapping}_signed_in? !!current_#{mapping} end def current_#{mapping} @current_#{mapping} ||= warden.authenticate(scope: :#{mapping}) end def #{mapping}_session current_#{mapping} && warden.session(:#{mapping}) end METHODS ActiveSupport.on_load(:action_controller) do if respond_to?(:helper_method) helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session" end end end # The main accessor for the warden proxy instance def warden request.env['warden'] end # Return true if it's a devise_controller. false to all controllers unless # the controllers defined inside devise. Useful if you want to apply a before # filter to all controllers, except the ones in devise: # # before_action :my_filter, unless: :devise_controller? def devise_controller? is_a?(::DeviseController) end # Set up a param sanitizer to filter parameters using strong_parameters. See # lib/devise/parameter_sanitizer.rb for more info. Override this # method in your application controller to use your own parameter sanitizer. def devise_parameter_sanitizer @devise_parameter_sanitizer ||= Devise::ParameterSanitizer.new(resource_class, resource_name, params) end # Tell warden that params authentication is allowed for that specific page. def allow_params_authentication! request.env["devise.allow_params_authentication"] = true end # The scope root url to be used when they're signed in. By default, it first # tries to find a resource_root_path, otherwise it uses the root_path. def signed_in_root_path(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) router_name = Devise.mappings[scope].router_name home_path = "#{scope}_root_path" context = router_name ? send(router_name) : self if context.respond_to?(home_path, true) context.send(home_path) elsif context.respond_to?(:root_path) context.root_path elsif respond_to?(:root_path) root_path else "/" end end # The default url to be used after signing in. This is used by all Devise # controllers and you can overwrite it in your ApplicationController to # provide a custom hook for a custom resource. # # By default, it first tries to find a valid resource_return_to key in the # session, then it fallbacks to resource_root_path, otherwise it uses the # root path. For a user scope, you can define the default url in # the following way: # # get '/users' => 'users#index', as: :user_root # creates user_root_path # # namespace :user do # root 'users#index' # creates user_root_path # end # # If the resource root path is not defined, root_path is used. However, # if this default is not enough, you can customize it, for example: # # def after_sign_in_path_for(resource) # stored_location_for(resource) || # if resource.is_a?(User) && resource.can_publish? # publisher_url # else # super # end # end # def after_sign_in_path_for(resource_or_scope) stored_location_for(resource_or_scope) || signed_in_root_path(resource_or_scope) end # Method used by sessions controller to sign out a user. You can overwrite # it in your ApplicationController to provide a custom hook for a custom # scope. Notice that differently from +after_sign_in_path_for+ this method # receives a symbol with the scope, and not the resource. # # By default it is the root_path. def after_sign_out_path_for(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) router_name = Devise.mappings[scope].router_name context = router_name ? send(router_name) : self context.respond_to?(:root_path) ? context.root_path : "/" end # Sign in a user and tries to redirect first to the stored location and # then to the url specified by after_sign_in_path_for. It accepts the same # parameters as the sign_in method. def sign_in_and_redirect(resource_or_scope, *args) options = args.extract_options! scope = Devise::Mapping.find_scope!(resource_or_scope) resource = args.last || resource_or_scope sign_in(scope, resource, options) redirect_to after_sign_in_path_for(resource) end # Sign out a user and tries to redirect to the url specified by # after_sign_out_path_for. def sign_out_and_redirect(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) redirect_path = after_sign_out_path_for(scope) Devise.sign_out_all_scopes ? sign_out : sign_out(scope) redirect_to redirect_path end # Overwrite Rails' handle unverified request to sign out all scopes, # clear run strategies and remove cached variables. def handle_unverified_request super # call the default behaviour which resets/nullifies/raises request.env["devise.skip_storage"] = true sign_out_all_scopes(false) end def request_format @request_format ||= request.format.try(:ref) end def is_navigational_format? Devise.navigational_formats.include?(request_format) end # Check if flash messages should be emitted. Default is to do it on # navigational formats def is_flashing_format? is_navigational_format? end private def expire_data_after_sign_out! Devise.mappings.each { |_,m| instance_variable_set("@current_#{m.name}", nil) } super end end end end Raise a more informative error when `request.env['warden']` is `nil`. Previously, a `NoMethodError` exception would be raised from here when the middleware stack isn't present and Warden wasn't injected as expected (like in a controller test). To foolproof ourselves, we now raise a more informative error when `request.env['warden']` is `nil` so developers can figure this out on their own instead of reaching to the issue tracker for guidance. module Devise module Controllers # Those helpers are convenience methods added to ApplicationController. module Helpers extend ActiveSupport::Concern include Devise::Controllers::SignInOut include Devise::Controllers::StoreLocation included do if respond_to?(:helper_method) helper_method :warden, :signed_in?, :devise_controller? end end module ClassMethods # Define authentication filters and accessor helpers for a group of mappings. # These methods are useful when you are working with multiple mappings that # share some functionality. They are pretty much the same as the ones # defined for normal mappings. # # Example: # # inside BlogsController (or any other controller, it doesn't matter which): # devise_group :blogger, contains: [:user, :admin] # # Generated methods: # authenticate_blogger! # Redirects unless user or admin are signed in # blogger_signed_in? # Checks whether there is either a user or an admin signed in # current_blogger # Currently signed in user or admin # current_bloggers # Currently signed in user and admin # # Use: # before_action :authenticate_blogger! # Redirects unless either a user or an admin are authenticated # before_action ->{ authenticate_blogger! :admin } # Redirects to the admin login page # current_blogger :user # Preferably returns a User if one is signed in # def devise_group(group_name, opts={}) mappings = "[#{ opts[:contains].map { |m| ":#{m}" }.join(',') }]" class_eval <<-METHODS, __FILE__, __LINE__ + 1 def authenticate_#{group_name}!(favourite=nil, opts={}) unless #{group_name}_signed_in? mappings = #{mappings} mappings.unshift mappings.delete(favourite.to_sym) if favourite mappings.each do |mapping| opts[:scope] = mapping warden.authenticate!(opts) if !devise_controller? || opts.delete(:force) end end end def #{group_name}_signed_in? #{mappings}.any? do |mapping| warden.authenticate?(scope: mapping) end end def current_#{group_name}(favourite=nil) mappings = #{mappings} mappings.unshift mappings.delete(favourite.to_sym) if favourite mappings.each do |mapping| current = warden.authenticate(scope: mapping) return current if current end nil end def current_#{group_name.to_s.pluralize} #{mappings}.map do |mapping| warden.authenticate(scope: mapping) end.compact end if respond_to?(:helper_method) helper_method "current_#{group_name}", "current_#{group_name.to_s.pluralize}", "#{group_name}_signed_in?" end METHODS end def log_process_action(payload) payload[:status] ||= 401 unless payload[:exception] super end end # Define authentication filters and accessor helpers based on mappings. # These filters should be used inside the controllers as before_actions, # so you can control the scope of the user who should be signed in to # access that specific controller/action. # Example: # # Roles: # User # Admin # # Generated methods: # authenticate_user! # Signs user in or redirect # authenticate_admin! # Signs admin in or redirect # user_signed_in? # Checks whether there is a user signed in or not # admin_signed_in? # Checks whether there is an admin signed in or not # current_user # Current signed in user # current_admin # Current signed in admin # user_session # Session data available only to the user scope # admin_session # Session data available only to the admin scope # # Use: # before_action :authenticate_user! # Tell devise to use :user map # before_action :authenticate_admin! # Tell devise to use :admin map # def self.define_helpers(mapping) #:nodoc: mapping = mapping.name class_eval <<-METHODS, __FILE__, __LINE__ + 1 def authenticate_#{mapping}!(opts={}) opts[:scope] = :#{mapping} warden.authenticate!(opts) if !devise_controller? || opts.delete(:force) end def #{mapping}_signed_in? !!current_#{mapping} end def current_#{mapping} @current_#{mapping} ||= warden.authenticate(scope: :#{mapping}) end def #{mapping}_session current_#{mapping} && warden.session(:#{mapping}) end METHODS ActiveSupport.on_load(:action_controller) do if respond_to?(:helper_method) helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session" end end end # The main accessor for the warden proxy instance def warden request.env['warden'] or raise MissingWarden end # Return true if it's a devise_controller. false to all controllers unless # the controllers defined inside devise. Useful if you want to apply a before # filter to all controllers, except the ones in devise: # # before_action :my_filter, unless: :devise_controller? def devise_controller? is_a?(::DeviseController) end # Set up a param sanitizer to filter parameters using strong_parameters. See # lib/devise/parameter_sanitizer.rb for more info. Override this # method in your application controller to use your own parameter sanitizer. def devise_parameter_sanitizer @devise_parameter_sanitizer ||= Devise::ParameterSanitizer.new(resource_class, resource_name, params) end # Tell warden that params authentication is allowed for that specific page. def allow_params_authentication! request.env["devise.allow_params_authentication"] = true end # The scope root url to be used when they're signed in. By default, it first # tries to find a resource_root_path, otherwise it uses the root_path. def signed_in_root_path(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) router_name = Devise.mappings[scope].router_name home_path = "#{scope}_root_path" context = router_name ? send(router_name) : self if context.respond_to?(home_path, true) context.send(home_path) elsif context.respond_to?(:root_path) context.root_path elsif respond_to?(:root_path) root_path else "/" end end # The default url to be used after signing in. This is used by all Devise # controllers and you can overwrite it in your ApplicationController to # provide a custom hook for a custom resource. # # By default, it first tries to find a valid resource_return_to key in the # session, then it fallbacks to resource_root_path, otherwise it uses the # root path. For a user scope, you can define the default url in # the following way: # # get '/users' => 'users#index', as: :user_root # creates user_root_path # # namespace :user do # root 'users#index' # creates user_root_path # end # # If the resource root path is not defined, root_path is used. However, # if this default is not enough, you can customize it, for example: # # def after_sign_in_path_for(resource) # stored_location_for(resource) || # if resource.is_a?(User) && resource.can_publish? # publisher_url # else # super # end # end # def after_sign_in_path_for(resource_or_scope) stored_location_for(resource_or_scope) || signed_in_root_path(resource_or_scope) end # Method used by sessions controller to sign out a user. You can overwrite # it in your ApplicationController to provide a custom hook for a custom # scope. Notice that differently from +after_sign_in_path_for+ this method # receives a symbol with the scope, and not the resource. # # By default it is the root_path. def after_sign_out_path_for(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) router_name = Devise.mappings[scope].router_name context = router_name ? send(router_name) : self context.respond_to?(:root_path) ? context.root_path : "/" end # Sign in a user and tries to redirect first to the stored location and # then to the url specified by after_sign_in_path_for. It accepts the same # parameters as the sign_in method. def sign_in_and_redirect(resource_or_scope, *args) options = args.extract_options! scope = Devise::Mapping.find_scope!(resource_or_scope) resource = args.last || resource_or_scope sign_in(scope, resource, options) redirect_to after_sign_in_path_for(resource) end # Sign out a user and tries to redirect to the url specified by # after_sign_out_path_for. def sign_out_and_redirect(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) redirect_path = after_sign_out_path_for(scope) Devise.sign_out_all_scopes ? sign_out : sign_out(scope) redirect_to redirect_path end # Overwrite Rails' handle unverified request to sign out all scopes, # clear run strategies and remove cached variables. def handle_unverified_request super # call the default behaviour which resets/nullifies/raises request.env["devise.skip_storage"] = true sign_out_all_scopes(false) end def request_format @request_format ||= request.format.try(:ref) end def is_navigational_format? Devise.navigational_formats.include?(request_format) end # Check if flash messages should be emitted. Default is to do it on # navigational formats def is_flashing_format? is_navigational_format? end private def expire_data_after_sign_out! Devise.mappings.each { |_,m| instance_variable_set("@current_#{m.name}", nil) } super end end end class MissingWarden < StandardError def initialize super "Devise could not find the `Warden::Proxy` instance on your request environment.\n" + \ "Make sure that your application is loading Devise and Warden as expected and that " + \ "the `Warden::Manager` middleware is present in your middleware stack.\n" + \ "If you are seeing this on one of your tests, ensure that your tests are either " + \ "executing the Rails middleware stack or that your tests are using the `Devise::Test::ControllerHelpers` " + \ "module to inject the `request.env['warden']` object for you." end end end
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Incense class Application < Rails::Application config.assets.initialize_on_precompile = false # required for rails 3.1 only? # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end config/application: secures AJAX requests against CSRF * config.action_view.embed_authenticity_token_in_remote_forms = true require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Incense class Application < Rails::Application config.assets.initialize_on_precompile = false # required for rails 3.1 only? # secure AJAX forms against CSRF config.action_view.embed_authenticity_token_in_remote_forms = true # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
module DirectiveRecord module Query class SQL def initialize(base) @base = base end def to_sql(*args) options = to_options(args) validate_options! options original_options = options.deep_dup original_options.reject!{|k, v| v.nil?} check_path_delimiter! options optimize_query! options prepare_options! options normalize_options! options, original_options parse_joins! options prepend_base_alias! options finalize_options! options flatten_options! options compose_sql options end def to_trend_sql(q1, q2, join_column_count, options) i = join_column_count + 1 select = "q1.*, q2.c#{i}, (((q1.c#{i} - q2.c#{i}) / ABS(q2.c#{i})) * 100) AS trend" on = (1..join_column_count).to_a.collect{|x| "q1.c#{x} = q2.c#{x}"}.join(" AND ") order = "\nORDER BY #{options[:order]}" if options[:order] limit = "\nLIMIT #{options[:limit]}" if options[:limit] offset = "\nOFFSET #{options[:offset]}" if options[:offset] <<-SQL SELECT #{select} FROM (\n#{q1}\n) q1 INNER JOIN (\n#{q2}\n) q2 ON #{on}#{order}#{limit}#{offset} SQL end protected def path_delimiter; end def aggregate_delimiter raise NotImplementedError end def select_aggregate_sql(method, path) "#{method.to_s.upcase}(#{path})" end def select_aggregate_sql_alias(method, path) quote_alias("#{method}#{aggregate_delimiter}#{path}") end def base @base end def base_alias @base_alias ||= quote_alias(base.table_name.split("_").collect{|x| x[0]}.join("")) end def quote_alias(sql_alias) sql_alias end def to_options(args) options = args.extract_options!.deep_dup options.reverse_merge! :select => (args.empty? ? "*" : args) [:select, :where, :group_by, :order_by].each do |key| if value = options[key] options[key] = [value].flatten end end options end def validate_options!(options) options.assert_valid_keys :connection, :select, :subselect, :where, :ignore_where, :group_by, :order_by, :limit, :offset, :aggregates, :numerize_aliases, :dataset, :period, :optimize end def optimize_query!(options) select = options[:select] if options[:optimize] && (select != %w(id)) && select.any?{|x| x.match(/^\w+(\.\w+)+$/)} order_by = options[:order_by] || [] select = ["id"] + select.select{|x| x.match(/ AS (\w+)$/) && order_by.any?{|y| y.include?(quote_alias($1))}} ids = base.connection.select_values(to_sql(options.merge(:select => select))).uniq + [0] options[:where] = ["id IN (#{ids.join(", ")})"] options.delete :limit options.delete :offset end end def check_path_delimiter!(options) unless path_delimiter [:select, :where, :having, :group_by, :order_by].each do |key| if value = options[key] value.collect! do |val| base.reflections.keys.inject(val) do |v, association| v.gsub(/\b#{association}\.([a-z_\.]+)/) { "#{association}_#{$1.gsub(".", "_")}" } end end end end end end def prepare_options!(options); end def normalize_options!(options, original_options) normalize_select!(options) normalize_subselect!(options, original_options) normalize_from!(options) normalize_group_by!(options) normalize_where!(options) normalize_order_by!(options) options.reject!{|k, v| v.blank?} end def normalize_select!(options) options[:select].uniq! options[:scales] = options[:select].inject({}) do |hash, sql| if scale = column_for(sql).try(:scale) hash[sql] = scale end hash end options[:aggregated] = {} options[:aliases] = {} options[:select] = options[:select].inject([]) do |array, path| sql, sql_alias = ((path == ".*") ? "#{base_alias}.*" : path), nil if aggregate_method = (options[:aggregates] || {})[path] sql = select_aggregate_sql(aggregate_method, path) sql_alias = options[:aggregated][path] = select_aggregate_sql_alias(aggregate_method, path) end if scale = options[:scales][path] sql = "ROUND(#{sql}, #{scale})" sql_alias ||= quote_alias(path) end unless sql_alias sql.match(/^(.*) AS (.*)$/) sql = $1 if $1 sql_alias = $2 end if options[:numerize_aliases] c_alias = "c#{array.size + 1}" options[:aggregated][sql_alias] = c_alias if !aggregate_method && sql_alias sql_alias = options[:aliases][prepend_base_alias(sql_alias || sql)] = c_alias end sql.gsub!(/sub:(\w+)\./) { "#{quote_alias($1)}." } if sql.is_a?(String) options[:aliases][sql] = sql_alias if sql_alias array << [sql, sql_alias].compact.join(" AS ") array end end def normalize_subselect!(options, original_options) options[:subselect] = options[:subselect].sort_by{|name, (klass, opts)| opts[:join] ? 0 : 1}.collect do |name, (klass, opts)| qry_options = original_options.deep_dup qry_options.reject!{|k, v| [:subselect, :numerize_aliases, :limit, :offset, :order_by, :join, :flatten].include?(k)} opts.each do |key, value| value = [value].flatten if key == :select qry_options[key] = value elsif [:join, :flatten].include?(key) # do nothing elsif key.to_s.match(/include_(\w+)/) (qry_options[$1.to_sym] || []).select!{|x| value.any?{|y| x.include?(y)}} elsif key.to_s.match(/exclude_(\w+)/) (qry_options[$1.to_sym] || []).reject!{|x| value.any?{|y| x.include?(y)}} else qry_options[key].concat value end end base_alias = quote_alias(klass.table_name.split("_").collect{|x| x[0]}.join("")) query_alias = quote_alias(name) if opts[:join] && !qry_options[:group_by].blank? joins = qry_options[:group_by].collect do |path| column = path.gsub(/\.\w+$/, "_id").strip column.match(/(.*) AS (\w+)$/) select_sql, select_alias = $1, $2 qry_options[:select].unshift(column) "#{query_alias}.#{select_alias || column} = #{select_sql || "#{base_alias}.#{column}"}" end prefix = "LEFT JOIN\n " postfix = " ON #{joins.join(" AND ")}" else prefix = " , " end query = klass.to_qry(qry_options).gsub(/\n\s*/, " ").gsub(/#{base_alias}[\s\.]/, "") if opts[:flatten] qry_alias = quote_alias("_#{name}") dup_options = qry_options.deep_dup normalize_select!(dup_options) prepend_base_alias!(dup_options) select = dup_options[:select].collect do |sql| sql_alias = sql.match(/ AS (.*?)$/).captures[0] "SUM(#{qry_alias}.#{sql_alias}) AS #{sql_alias}" end query = "SELECT #{select.join(", ")} FROM (#{query}) #{qry_alias}" end "#{prefix}(#{query}) #{query_alias}#{postfix}" end if options[:subselect] end def normalize_from!(options) options[:from] = "#{base.table_name} #{base_alias}" end def normalize_group_by!(options) options[:group_by].collect! do |x| if x.match(/^(.*?) AS (\w+)$/) if options[:select].any?{|x| x.include?("#{$1} AS ")} $1 else options[:select] << x options[:aliases][$1] = $2 $2 end else x end end if options[:group_by] end def normalize_where!(options) regexp, aliases = /^\S+/, options[:aliases].to_a.flatten.uniq.sort where, having = (options[:where] || []).partition do |statement| !options[:aggregated].keys.include?(statement.strip.match(regexp).to_s) && statement.gsub(/(["'])(?:(?=(\\?))\2.)*?\1/, " ") .split(/\b(and|or)\b/i).reject{|sql| %w(and or).include? sql.downcase} .collect{|sql| sql = sql.strip; (sql[0] == "(" && sql[-1] == ")" ? sql[1..-1] : sql)} .all? do |sql| sql.match /(.*?)\s*(=|<=>|>=|>|<=|<|<>|!=|is|like|rlike|regexp|in|between|not|sounds|soundex)(\b|\s|$)/i path = $1.strip if (options[:aggregates] || {})[path] normalize_select!(opts = options.deep_dup.merge(:select => [path])) options[:select].concat(opts[:select]).uniq! options[:aggregated].merge!(opts[:aggregated]) false else !(aliases.include?(path) || path.match(/\b(count|sum|min|max|avg)\(/i)) end end end unless (attrs = base.scope_attributes).blank? sql = base.send(:sanitize_sql_for_conditions, attrs, "").gsub(/``.`(\w+)`/) { $1 } where << sql end options[:where], options[:having] = where, having.collect do |statement| statement.strip.gsub(regexp){|path| options[:aggregated][path] || path} end [:where, :having].each do |key| if options[key].empty? options.delete key end end end def normalize_order_by!(options) return unless options[:order_by] options[:order_by].collect! do |x| segments = x.split " " direction = segments.pop if %w(asc desc).include?(segments[-1].downcase) path = segments.join " " scale = options[:scales][path] select = begin if aggregate_method = (options[:aggregates] || {})[path] select_aggregate_sql(aggregate_method, path) else path end end "#{scale ? "ROUND(#{select}, #{scale})" : select} #{direction.upcase if direction}".strip end options[:order_by].compact! end def column_for(path) segments = path.split(".") column = segments.pop model = segments.inject(base) do |klass, association| klass.reflect_on_association(association.to_sym).klass end model.columns_hash[column] rescue nil end def parse_joins!(options) return if (paths = extract_paths(options)).empty? regexp = /INNER JOIN `([^`]+)`( `[^`]+`)? ON `[^`]+`.`([^`]+)` = `[^`]+`.`([^`]+)`( AND .*)?/ options[:joins] = paths.collect do |path| joins, associations = [], [] path.split(".").inject(base) do |klass, association| association = association.to_sym table_joins = klass.joins(association).to_sql.scan regexp concerns_bridge_table = table_joins.size == 2 bridge_table_as = nil table_joins.each_with_index do |table_join, index| concerns_bridge_table_join = concerns_bridge_table && index == 0 join_table, possible_alias, join_table_column, table_column, conditions = table_join table_as = (klass == base) ? base_alias : quote_alias(associations.join(path_delimiter)) join_table_as = quote_alias((associations + [association]).join(path_delimiter)) if concerns_bridge_table if concerns_bridge_table_join join_table_as = bridge_table_as = quote_alias("#{(associations + [association]).join(path_delimiter)}_bridge_table") else table_as = bridge_table_as end end if conditions sql = self.class.new(klass.reflect_on_association(association).klass) conditions = sql.prepend_base_alias(conditions).gsub(sql.base_alias, join_table_as) end joins.push "LEFT JOIN #{join_table} #{join_table_as} ON #{join_table_as}.#{join_table_column} = #{table_as}.#{table_column}#{conditions}" end associations << association klass.reflect_on_association(association).klass end joins end.flatten.uniq.join("\n") end def extract_paths(options) [:select, :where, :group_by, :having, :order_by].inject([]) do |paths, key| if value = options[key] value = value.join " " if value.is_a?(Array) paths.concat value.gsub(/(["'])(?:(?=(\\?))\2.)*?\1/, " ").gsub(/sub:[a-zA-Z_]+\.[a-zA-Z_\.]+/, " ").scan(/[a-zA-Z_]+\.[a-zA-Z_\.]+/).collect{|x| x.split(".")[0..-2].join "."} else paths end end.uniq end def prepend_base_alias!(options) [:select, :where, :group_by, :having, :order_by].each do |key| if value = options[key] value.collect! do |sql| prepend_base_alias sql, options[:aliases] end end end end def prepend_base_alias(sql, aliases = {}) return sql if sql.include?("SELECT") columns = base.columns_hash.keys sql.gsub(/("[^"]*"|'[^']*'|`[^`]*`|[a-zA-Z_#{aggregate_delimiter}]+(\.[a-zA-Z_\*]+)*)/) do columns.include?($1) ? "#{base_alias}.#{$1}" : begin if (string = $1).match /^([a-zA-Z_\.]+)\.([a-zA-Z_\*]+)$/ path, column = $1, $2 "#{quote_alias path.gsub(".", path_delimiter)}.#{column}" else string end end end end def finalize_options!(options); end def flatten_options!(options) options[:select] = if options[:select].size <= 3 " " + options[:select].join(", ") else "\n " + options[:select].join(",\n ") end [:group_by, :order_by].each do |key| if value = options[key] options[key] = value.join(", ") if value.is_a?(Array) end end [:where, :having].each do |key| if value = options[key] options[key] = value.collect{|x| "(#{x})"}.join(" AND ") if value.is_a?(Array) end end end def compose_sql(options) sql = ["SELECT#{options[:select]}", "FROM #{options[:from]}", options[:joins], options[:subselect]].compact [:where, :group_by, :having, :order_by, :limit, :offset].each do |key| unless (value = options[key]).blank? keyword = key.to_s.upcase.gsub("_", " ") sql << "#{keyword} #{value}" end end sql.join "\n" end end end end fix unrequired duplication of connection module DirectiveRecord module Query class SQL def initialize(base) @base = base end def to_sql(*args) options = to_options(args) validate_options! options original_options = options.deep_dup original_options.reject!{|k, v| v.nil?} check_path_delimiter! options optimize_query! options prepare_options! options normalize_options! options, original_options parse_joins! options prepend_base_alias! options finalize_options! options flatten_options! options compose_sql options end def to_trend_sql(q1, q2, join_column_count, options) i = join_column_count + 1 select = "q1.*, q2.c#{i}, (((q1.c#{i} - q2.c#{i}) / ABS(q2.c#{i})) * 100) AS trend" on = (1..join_column_count).to_a.collect{|x| "q1.c#{x} = q2.c#{x}"}.join(" AND ") order = "\nORDER BY #{options[:order]}" if options[:order] limit = "\nLIMIT #{options[:limit]}" if options[:limit] offset = "\nOFFSET #{options[:offset]}" if options[:offset] <<-SQL SELECT #{select} FROM (\n#{q1}\n) q1 INNER JOIN (\n#{q2}\n) q2 ON #{on}#{order}#{limit}#{offset} SQL end protected def path_delimiter; end def aggregate_delimiter raise NotImplementedError end def select_aggregate_sql(method, path) "#{method.to_s.upcase}(#{path})" end def select_aggregate_sql_alias(method, path) quote_alias("#{method}#{aggregate_delimiter}#{path}") end def base @base end def base_alias @base_alias ||= quote_alias(base.table_name.split("_").collect{|x| x[0]}.join("")) end def quote_alias(sql_alias) sql_alias end def to_options(args) args_without_connection = [args[0].except(:connection)] options = args_without_connection.extract_options!.deep_dup options.reverse_merge! :select => (args.empty? ? "*" : args) [:select, :where, :group_by, :order_by].each do |key| if value = options[key] options[key] = [value].flatten end end options end def validate_options!(options) options.assert_valid_keys :connection, :select, :subselect, :where, :ignore_where, :group_by, :order_by, :limit, :offset, :aggregates, :numerize_aliases, :dataset, :period, :optimize end def optimize_query!(options) select = options[:select] if options[:optimize] && (select != %w(id)) && select.any?{|x| x.match(/^\w+(\.\w+)+$/)} order_by = options[:order_by] || [] select = ["id"] + select.select{|x| x.match(/ AS (\w+)$/) && order_by.any?{|y| y.include?(quote_alias($1))}} ids = base.connection.select_values(to_sql(options.merge(:select => select))).uniq + [0] options[:where] = ["id IN (#{ids.join(", ")})"] options.delete :limit options.delete :offset end end def check_path_delimiter!(options) unless path_delimiter [:select, :where, :having, :group_by, :order_by].each do |key| if value = options[key] value.collect! do |val| base.reflections.keys.inject(val) do |v, association| v.gsub(/\b#{association}\.([a-z_\.]+)/) { "#{association}_#{$1.gsub(".", "_")}" } end end end end end end def prepare_options!(options); end def normalize_options!(options, original_options) normalize_select!(options) normalize_subselect!(options, original_options) normalize_from!(options) normalize_group_by!(options) normalize_where!(options) normalize_order_by!(options) options.reject!{|k, v| v.blank?} end def normalize_select!(options) options[:select].uniq! options[:scales] = options[:select].inject({}) do |hash, sql| if scale = column_for(sql).try(:scale) hash[sql] = scale end hash end options[:aggregated] = {} options[:aliases] = {} options[:select] = options[:select].inject([]) do |array, path| sql, sql_alias = ((path == ".*") ? "#{base_alias}.*" : path), nil if aggregate_method = (options[:aggregates] || {})[path] sql = select_aggregate_sql(aggregate_method, path) sql_alias = options[:aggregated][path] = select_aggregate_sql_alias(aggregate_method, path) end if scale = options[:scales][path] sql = "ROUND(#{sql}, #{scale})" sql_alias ||= quote_alias(path) end unless sql_alias sql.match(/^(.*) AS (.*)$/) sql = $1 if $1 sql_alias = $2 end if options[:numerize_aliases] c_alias = "c#{array.size + 1}" options[:aggregated][sql_alias] = c_alias if !aggregate_method && sql_alias sql_alias = options[:aliases][prepend_base_alias(sql_alias || sql)] = c_alias end sql.gsub!(/sub:(\w+)\./) { "#{quote_alias($1)}." } if sql.is_a?(String) options[:aliases][sql] = sql_alias if sql_alias array << [sql, sql_alias].compact.join(" AS ") array end end def normalize_subselect!(options, original_options) options[:subselect] = options[:subselect].sort_by{|name, (klass, opts)| opts[:join] ? 0 : 1}.collect do |name, (klass, opts)| qry_options = original_options.deep_dup qry_options.reject!{|k, v| [:subselect, :numerize_aliases, :limit, :offset, :order_by, :join, :flatten].include?(k)} opts.each do |key, value| value = [value].flatten if key == :select qry_options[key] = value elsif [:join, :flatten].include?(key) # do nothing elsif key.to_s.match(/include_(\w+)/) (qry_options[$1.to_sym] || []).select!{|x| value.any?{|y| x.include?(y)}} elsif key.to_s.match(/exclude_(\w+)/) (qry_options[$1.to_sym] || []).reject!{|x| value.any?{|y| x.include?(y)}} else qry_options[key].concat value end end base_alias = quote_alias(klass.table_name.split("_").collect{|x| x[0]}.join("")) query_alias = quote_alias(name) if opts[:join] && !qry_options[:group_by].blank? joins = qry_options[:group_by].collect do |path| column = path.gsub(/\.\w+$/, "_id").strip column.match(/(.*) AS (\w+)$/) select_sql, select_alias = $1, $2 qry_options[:select].unshift(column) "#{query_alias}.#{select_alias || column} = #{select_sql || "#{base_alias}.#{column}"}" end prefix = "LEFT JOIN\n " postfix = " ON #{joins.join(" AND ")}" else prefix = " , " end query = klass.to_qry(qry_options).gsub(/\n\s*/, " ").gsub(/#{base_alias}[\s\.]/, "") if opts[:flatten] qry_alias = quote_alias("_#{name}") dup_options = qry_options.deep_dup normalize_select!(dup_options) prepend_base_alias!(dup_options) select = dup_options[:select].collect do |sql| sql_alias = sql.match(/ AS (.*?)$/).captures[0] "SUM(#{qry_alias}.#{sql_alias}) AS #{sql_alias}" end query = "SELECT #{select.join(", ")} FROM (#{query}) #{qry_alias}" end "#{prefix}(#{query}) #{query_alias}#{postfix}" end if options[:subselect] end def normalize_from!(options) options[:from] = "#{base.table_name} #{base_alias}" end def normalize_group_by!(options) options[:group_by].collect! do |x| if x.match(/^(.*?) AS (\w+)$/) if options[:select].any?{|x| x.include?("#{$1} AS ")} $1 else options[:select] << x options[:aliases][$1] = $2 $2 end else x end end if options[:group_by] end def normalize_where!(options) regexp, aliases = /^\S+/, options[:aliases].to_a.flatten.uniq.sort where, having = (options[:where] || []).partition do |statement| !options[:aggregated].keys.include?(statement.strip.match(regexp).to_s) && statement.gsub(/(["'])(?:(?=(\\?))\2.)*?\1/, " ") .split(/\b(and|or)\b/i).reject{|sql| %w(and or).include? sql.downcase} .collect{|sql| sql = sql.strip; (sql[0] == "(" && sql[-1] == ")" ? sql[1..-1] : sql)} .all? do |sql| sql.match /(.*?)\s*(=|<=>|>=|>|<=|<|<>|!=|is|like|rlike|regexp|in|between|not|sounds|soundex)(\b|\s|$)/i path = $1.strip if (options[:aggregates] || {})[path] normalize_select!(opts = options.deep_dup.merge(:select => [path])) options[:select].concat(opts[:select]).uniq! options[:aggregated].merge!(opts[:aggregated]) false else !(aliases.include?(path) || path.match(/\b(count|sum|min|max|avg)\(/i)) end end end unless (attrs = base.scope_attributes).blank? sql = base.send(:sanitize_sql_for_conditions, attrs, "").gsub(/``.`(\w+)`/) { $1 } where << sql end options[:where], options[:having] = where, having.collect do |statement| statement.strip.gsub(regexp){|path| options[:aggregated][path] || path} end [:where, :having].each do |key| if options[key].empty? options.delete key end end end def normalize_order_by!(options) return unless options[:order_by] options[:order_by].collect! do |x| segments = x.split " " direction = segments.pop if %w(asc desc).include?(segments[-1].downcase) path = segments.join " " scale = options[:scales][path] select = begin if aggregate_method = (options[:aggregates] || {})[path] select_aggregate_sql(aggregate_method, path) else path end end "#{scale ? "ROUND(#{select}, #{scale})" : select} #{direction.upcase if direction}".strip end options[:order_by].compact! end def column_for(path) segments = path.split(".") column = segments.pop model = segments.inject(base) do |klass, association| klass.reflect_on_association(association.to_sym).klass end model.columns_hash[column] rescue nil end def parse_joins!(options) return if (paths = extract_paths(options)).empty? regexp = /INNER JOIN `([^`]+)`( `[^`]+`)? ON `[^`]+`.`([^`]+)` = `[^`]+`.`([^`]+)`( AND .*)?/ options[:joins] = paths.collect do |path| joins, associations = [], [] path.split(".").inject(base) do |klass, association| association = association.to_sym table_joins = klass.joins(association).to_sql.scan regexp concerns_bridge_table = table_joins.size == 2 bridge_table_as = nil table_joins.each_with_index do |table_join, index| concerns_bridge_table_join = concerns_bridge_table && index == 0 join_table, possible_alias, join_table_column, table_column, conditions = table_join table_as = (klass == base) ? base_alias : quote_alias(associations.join(path_delimiter)) join_table_as = quote_alias((associations + [association]).join(path_delimiter)) if concerns_bridge_table if concerns_bridge_table_join join_table_as = bridge_table_as = quote_alias("#{(associations + [association]).join(path_delimiter)}_bridge_table") else table_as = bridge_table_as end end if conditions sql = self.class.new(klass.reflect_on_association(association).klass) conditions = sql.prepend_base_alias(conditions).gsub(sql.base_alias, join_table_as) end joins.push "LEFT JOIN #{join_table} #{join_table_as} ON #{join_table_as}.#{join_table_column} = #{table_as}.#{table_column}#{conditions}" end associations << association klass.reflect_on_association(association).klass end joins end.flatten.uniq.join("\n") end def extract_paths(options) [:select, :where, :group_by, :having, :order_by].inject([]) do |paths, key| if value = options[key] value = value.join " " if value.is_a?(Array) paths.concat value.gsub(/(["'])(?:(?=(\\?))\2.)*?\1/, " ").gsub(/sub:[a-zA-Z_]+\.[a-zA-Z_\.]+/, " ").scan(/[a-zA-Z_]+\.[a-zA-Z_\.]+/).collect{|x| x.split(".")[0..-2].join "."} else paths end end.uniq end def prepend_base_alias!(options) [:select, :where, :group_by, :having, :order_by].each do |key| if value = options[key] value.collect! do |sql| prepend_base_alias sql, options[:aliases] end end end end def prepend_base_alias(sql, aliases = {}) return sql if sql.include?("SELECT") columns = base.columns_hash.keys sql.gsub(/("[^"]*"|'[^']*'|`[^`]*`|[a-zA-Z_#{aggregate_delimiter}]+(\.[a-zA-Z_\*]+)*)/) do columns.include?($1) ? "#{base_alias}.#{$1}" : begin if (string = $1).match /^([a-zA-Z_\.]+)\.([a-zA-Z_\*]+)$/ path, column = $1, $2 "#{quote_alias path.gsub(".", path_delimiter)}.#{column}" else string end end end end def finalize_options!(options); end def flatten_options!(options) options[:select] = if options[:select].size <= 3 " " + options[:select].join(", ") else "\n " + options[:select].join(",\n ") end [:group_by, :order_by].each do |key| if value = options[key] options[key] = value.join(", ") if value.is_a?(Array) end end [:where, :having].each do |key| if value = options[key] options[key] = value.collect{|x| "(#{x})"}.join(" AND ") if value.is_a?(Array) end end end def compose_sql(options) sql = ["SELECT#{options[:select]}", "FROM #{options[:from]}", options[:joins], options[:subselect]].compact [:where, :group_by, :having, :order_by, :limit, :offset].each do |key| unless (value = options[key]).blank? keyword = key.to_s.upcase.gsub("_", " ") sql << "#{keyword} #{value}" end end sql.join "\n" end end end end
require "conjur/debify/version" require 'docker' require 'fileutils' require 'gli' include GLI::App Docker.options[:read_timeout] = 300 # This is used to turn on DEBUG notices for the test case operation. For instance, # messages from "evoke configure" module DebugMixin DEBUG = ENV['DEBUG'].nil? ? true : ENV['DEBUG'].downcase == 'true' def debug *a DebugMixin.debug *a end def self.debug *a $stderr.puts *a if DEBUG end def debug_write *a DebugMixin.debug_write *a end def self.debug_write *a $stderr.write *a if DEBUG end # you can give this to various docker methods to print output if debug is on def self.docker_debug *a if a.length == 2 && a[0].is_a?(Symbol) debug a.last else a.each do |line| line = JSON.parse(line) line.keys.each do |k| debug line[k] end end end end DOCKER = method :docker_debug end program_desc 'Utility commands for building and testing Conjur appliance Debian packages' version Conjur::Debify::VERSION subcommand_option_handling :normal arguments :strict def detect_version `git describe --long --tags --abbrev=7 | sed -e 's/^v//'`.strip.tap do |version| raise "No Git version (tag) for project" if version.empty? end end def git_files (`git ls-files -z`.split("\x0") + ['Gemfile.lock']).uniq end desc "Clean current working directory of non-Git-managed files" long_desc <<DESC Reliable builds depend on having a clean working directory. Because debify runs some commands in volume-mounted Docker containers, it is capable of creating root-owned files. This command will delete all files in the working directory that are not git-managed. The command is designed to run in Jenkins. Therefore, it will only perform file deletion if: * The current user, as provided by Etc.getlogin, is 'jenkins' * The BUILD_NUMBER environment variable is set File deletion can be compelled using the "force" option. DESC arg_name "project-name -- <fpm-arguments>" command "clean" do |c| c.desc "Set the current working directory" c.flag [ :d, "dir" ] c.desc "Ignore (don't delete) a file or directory" c.flag [ :i, :ignore ] c.desc "Force file deletion even if if this doesn't look like a Jenkins environment" c.switch [ :force ] c.action do |global_options,cmd_options,args| def looks_like_jenkins? require 'etc' Etc.getlogin == 'jenkins' && ENV['BUILD_NUMBER'] end require 'set' perform_deletion = cmd_options[:force] || looks_like_jenkins? if !perform_deletion $stderr.puts "No --force, and this doesn't look like Jenkins. I won't actually delete anything" end @ignore_list = Array(cmd_options[:ignore]) + [ '.', '..', '.git' ] def ignore_file? f @ignore_list.find{|ignore| f.index(ignore) == 0} end dir = cmd_options[:dir] || '.' dir = File.expand_path(dir) Dir.chdir dir do require 'find' find_files = [] Find.find('.').each do |p| find_files.push p[2..-1] end find_files.compact! delete_files = (find_files - git_files) delete_files.delete_if{|file| File.directory?(file) || ignore_file?(file) } if perform_deletion image = Docker::Image.create 'fromImage' => "alpine:3.3" options = { 'Cmd' => [ "sh", "-c", "while true; do sleep 1; done" ], 'Image' => image.id, 'Binds' => [ [ dir, "/src" ].join(':'), ] } container = Docker::Container.create options begin container.start delete_files.each do |file| puts file file = "/src/#{file}" cmd = [ "rm", "-f", file ] stdout, stderr, status = container.exec cmd, &DebugMixin::DOCKER $stderr.puts "Failed to delete #{file}" unless status == 0 end ensure container.delete force: true end else delete_files.each do |file| puts file end end end end end desc "Build a debian package for a project" long_desc <<DESC The package is built using fpm (https://github.com/jordansissel/fpm). The project directory is required to contain: * A Gemfile and Gemfile.lock * A shell script called debify.sh debify.sh is invoked by the package build process to create any custom files, other than the project source tree. For example, config files can be created in /opt/conjur/etc. The distrib folder in the project source tree is intended to create scripts for package pre-install, post-install etc. The distrib folder is not included in the deb package, so its contents should be copied to the file system or packaged using fpm arguments. All arguments to this command which follow the double-dash are propagated to the fpm command. DESC arg_name "project-name -- <fpm-arguments>" command "package" do |c| c.desc "Set the current working directory" c.flag [ :d, "dir" ] c.desc "Specify the deb version; by default, it's computed from the Git tag" c.flag [ :v, :version ] c.desc "Specify a custom Dockerfile.fpm" c.flag [ :dockerfile] c.action do |global_options,cmd_options,args| raise "project-name is required" unless project_name = args.shift fpm_args = [] if (delimeter = args.shift) == '--' fpm_args = args.dup else raise "Unexpected argument '#{delimiter}'" end dir = cmd_options[:dir] || '.' pwd = File.dirname(__FILE__) fpm_image = Docker::Image.build_from_dir File.expand_path('fpm', File.dirname(__FILE__)), tag: "debify-fpm", &DebugMixin::DOCKER DebugMixin.debug_write "Built base fpm image '#{fpm_image.id}'\n" dir = File.expand_path(dir) Dir.chdir dir do version = cmd_options[:version] || detect_version dockerfile_path = cmd_options[:dockerfile] || File.expand_path("debify/Dockerfile.fpm", pwd) dockerfile = File.read(dockerfile_path) package_name = "conjur-#{project_name}_#{version}_amd64.deb" output = StringIO.new Gem::Package::TarWriter.new(output) do |tar| git_files.each do |fname| stat = File.stat(fname) tar.add_file(fname, stat.mode) { |tar_file| tar_file.write(File.read(fname)) } end tar.add_file('Dockerfile', 0640) { |tar_file| tar_file.write dockerfile.gsub("@@image@@", fpm_image.id) } end output.rewind image = Docker::Image.build_from_tar output, &DebugMixin::DOCKER DebugMixin.debug_write "Built fpm image '#{image.id}' for project #{project_name}\n" options = { 'Cmd' => [ project_name, version ] + fpm_args, 'Image' => image.id } container = Docker::Container.create options begin DebugMixin.debug_write "Packaging #{project_name} in container #{container.id}\n" container.tap(&:start).attach { |stream, chunk| $stderr.puts chunk } status = container.wait raise "Failed to package #{project_name}" unless status['StatusCode'] == 0 require 'rubygems/package' deb = StringIO.new container.copy("/src/#{package_name}") { |chunk| deb.write(chunk) } deb.rewind tar = Gem::Package::TarReader.new deb tar.first.tap do |entry| open(entry.full_name, 'wb') {|f| f.write(entry.read)} puts entry.full_name end ensure container.delete(force: true) end end end end desc "Test a Conjur debian package in a Conjur appliance container" long_desc <<DESC First, a Conjur appliance container is created and started. By default, the container image is registry.tld/conjur-appliance-cuke-master. An image tag MUST be supplied. This image is configured with all the CONJUR_ environment variables setup for the local environment (appliance URL, cert path, admin username and password, etc). The project source tree is also mounted into the container, at /src/<project-name>. This command then waits for Conjur to initialize and be healthy. It proceeds by installing the conjur-<project-name>_<version>_amd64.deb from the project working directory. Then the evoke "test-install" command is used to install the test code in the /src/<project-name>. Basically, the development bundle is installed and the database configuration (if any) is setup. Finally, a test script from the project source tree is run, again with the container id as the program argument. Then the Conjur container is deleted (use --keep to leave it running). DESC arg_name "project-name test-script" command "test" do |c| c.desc "Set the current working directory" c.flag [ :d, :dir ] c.desc "Keep the Conjur appliance container after the command finishes" c.default_value false c.switch [ :k, :keep ] c.desc "Image name" c.default_value "registry.tld/conjur-appliance-cuke-master" c.flag [ :i, :image ] c.desc "Image tag, e.g. 4.5-stable, 4.6-stable" c.flag [ :t, "image-tag"] c.desc "'docker pull' the Conjur container image" c.default_value true c.switch [ :pull ] c.desc "Specify the deb version; by default, it's computed from the Git tag" c.flag [ :v, :version ] c.action do |global_options,cmd_options,args| raise "project-name is required" unless project_name = args.shift raise "test-script is required" unless test_script = args.shift raise "Receive extra command-line arguments" if args.shift dir = cmd_options[:dir] || '.' dir = File.expand_path(dir) raise "Directory #{dir} does not exist or is not a directory" unless File.directory?(dir) raise "Directory #{dir} does not contain a .deb file" unless Dir["#{dir}/*.deb"].length >= 1 Dir.chdir dir do image_tag = cmd_options["image-tag"] or raise "image-tag is required" appliance_image_id = [ cmd_options[:image], image_tag ].join(":") version = cmd_options[:version] || detect_version package_name = "conjur-#{project_name}_#{version}_amd64.deb" raise "#{test_script} does not exist or is not a file" unless File.file?(test_script) Docker::Image.create 'fromImage' => appliance_image_id, &DebugMixin::DOCKER if cmd_options[:pull] def build_test_image(appliance_image_id, project_name, package_name) dockerfile = <<-DOCKERFILE FROM #{appliance_image_id} COPY #{package_name} /tmp/ RUN if dpkg --list | grep conjur-#{project_name}; then dpkg --force all --purge conjur-#{project_name}; fi RUN if [ -f /opt/conjur/etc/#{project_name}.conf ]; then rm /opt/conjur/etc/#{project_name}.conf; fi RUN dpkg --install /tmp/#{package_name} RUN touch /etc/service/conjur/down DOCKERFILE Dir.mktmpdir do |tmpdir| tmpfile = Tempfile.new('Dockerfile', tmpdir) File.write(tmpfile, dockerfile) dockerfile_name = File.basename(tmpfile.path) tar_cmd = "tar -cvzh -C #{tmpdir} #{dockerfile_name} -C #{Dir.pwd} #{package_name}" tar = open("| #{tar_cmd}") begin Docker::Image.build_from_tar(tar, :dockerfile => dockerfile_name, &DebugMixin::DOCKER) ensure tar.close end end end appliance_image = build_test_image(appliance_image_id, project_name, package_name) vendor_dir = File.expand_path("tmp/debify/#{project_name}/vendor", ENV['HOME']) dot_bundle_dir = File.expand_path("tmp/debify/#{project_name}/.bundle", ENV['HOME']) FileUtils.mkdir_p vendor_dir FileUtils.mkdir_p dot_bundle_dir options = { 'Image' => appliance_image.id, 'Env' => [ "CONJUR_AUTHN_LOGIN=admin", "CONJUR_ENV=appliance", "CONJUR_AUTHN_API_KEY=secret", "CONJUR_ADMIN_PASSWORD=secret", ], 'Binds' => [ [ dir, "/src/#{project_name}" ].join(':'), [ vendor_dir, "/src/#{project_name}/vendor" ].join(':'), [ dot_bundle_dir, "/src/#{project_name}/.bundle" ].join(':') ] } container = Docker::Container.create(options) def wait_for_conjur appliance_image, container wait_options = { 'Image' => appliance_image.id, 'Entrypoint' => '/opt/conjur/evoke/bin/wait_for_conjur', 'HostConfig' => { 'Links' => [ [ container.id, 'conjur' ].join(":") ] } } wait_container = Docker::Container.create wait_options begin spawn("docker logs -f #{wait_container.id}", [ :out, :err ] => $stderr).tap do |pid| Process.detach pid end wait_container.start status = wait_container.wait raise "wait_for_conjur failed" unless status['StatusCode'] == 0 ensure wait_container.delete(force: true) end end def command container, *args stdout, stderr, exitcode = container.exec args, &DebugMixin::DOCKER exit_now! "Command failed : #{args.join(' ')}", exitcode unless exitcode == 0 stdout end begin DebugMixin.debug_write "Testing #{project_name} in container #{container.id}\n" spawn("docker logs -f #{container.id}", [ :out, :err ] => $stderr).tap do |pid| Process.detach pid end container.start # Wait for pg/main so that migrations can run 30.times do stdout, stderr, exitcode = container.exec %w(sv status pg/main), &DebugMixin::DOCKER status = stdout.join break if exitcode == 0 && status =~ /^run\:/ sleep 1 end command container, "/opt/conjur/evoke/bin/test-install", project_name DebugMixin.debug_write "Starting conjur\n" command container, "rm", "/etc/service/conjur/down" command container, "sv", "start", "conjur" wait_for_conjur appliance_image, container system "./#{test_script} #{container.id}" exit_now! "#{test_script} failed with exit code #{$?.exitstatus}", $?.exitstatus unless $?.exitstatus == 0 ensure container.delete(force: true) unless cmd_options[:keep] end end end end desc "Publish a debian package to apt repository" long_desc <<DESC Publishes a deb created with `debify package` to our private apt repository. "distribution" should match the major/minor version of the Conjur appliance you want to install to. The package name is a required option. The package version can be specified as a CLI option, or it will be auto-detected from Git. --component should be 'stable' if run after package tests pass or 'testing' if the package is not yet ready for release. If you don't specify the component, it will be set to 'testing' unless the current git branch is 'master' or 'origin/master'. The git branch is first detected from the env var GIT_BRANCH, and then by checking `git rev-parse --abbrev-ref HEAD` (which won't give you the answer you want when detached). DESC arg_name "distribution project-name" command "publish" do |c| c.desc "Set the current working directory" c.flag [ :d, :dir ] c.desc "Specify the deb package version; by default, it's computed from the Git tag" c.flag [ :v, :version ] c.desc "Maturity stage of the package, 'testing' or 'stable'" c.flag [ :c, :component ] c.action do |global_options,cmd_options,args| raise "distribution is required" unless distribution = args.shift raise "project-name is required" unless project_name = args.shift raise "Receive extra command-line arguments" if args.shift def detect_component branch = ENV['GIT_BRANCH'] || `git rev-parse --abbrev-ref HEAD`.strip if %w(master origin/master).include?(branch) 'stable' else 'testing' end end dir = cmd_options[:dir] || '.' dir = File.expand_path(dir) raise "Directory #{dir} does not exist or is not a directory" unless File.directory?(dir) Dir.chdir dir do version = cmd_options[:version] || detect_version component = cmd_options[:component] || detect_component package_name = "conjur-#{project_name}_#{version}_amd64.deb" publish_image = Docker::Image.build_from_dir File.expand_path('publish', File.dirname(__FILE__)), tag: "debify-publish", &DebugMixin::DOCKER DebugMixin.debug_write "Built base publish image '#{publish_image.id}'\n" require 'conjur/cli' require 'conjur/authn' Conjur::Config.load Conjur::Config.apply conjur = Conjur::Authn.connect nil, noask: true art_username = conjur.variable('artifactory/users/jenkins/username').value art_password = conjur.variable('artifactory/users/jenkins/password').value options = { 'Image' => publish_image.id, 'Cmd' => [ "art", "upload", "--url", "https://conjurinc.artifactoryonline.com/conjurinc", "--user", art_username, "--password", art_password, "--deb", "#{distribution}/#{component}/amd64", package_name, "debian-local/" ], 'Binds' => [ [ dir, "/src" ].join(':') ] } container = Docker::Container.create(options) begin container.tap(&:start).streaming_logs(follow: true, stdout: true, stderr: true) { |stream, chunk| puts "#{chunk}" } status = container.wait raise "Failed to publish #{package_name}" unless status['StatusCode'] == 0 ensure container.delete(force: true) end end end end pre do |global,command,options,args| # Pre logic here # Return true to proceed; false to abort and not call the # chosen command # Use skips_pre before a command to skip this block # on that command only true end post do |global,command,options,args| # Post logic here # Use skips_post before a command to skip this # block on that command only end on_error do |exception| # Error logic here # return false to skip default error handling true end Pipe stdout/stderr from container to user during packaging require "conjur/debify/version" require 'docker' require 'fileutils' require 'gli' include GLI::App Docker.options[:read_timeout] = 300 # This is used to turn on DEBUG notices for the test case operation. For instance, # messages from "evoke configure" module DebugMixin DEBUG = ENV['DEBUG'].nil? ? true : ENV['DEBUG'].downcase == 'true' def debug *a DebugMixin.debug *a end def self.debug *a $stderr.puts *a if DEBUG end def debug_write *a DebugMixin.debug_write *a end def self.debug_write *a $stderr.write *a if DEBUG end # you can give this to various docker methods to print output if debug is on def self.docker_debug *a if a.length == 2 && a[0].is_a?(Symbol) debug a.last else a.each do |line| line = JSON.parse(line) line.keys.each do |k| debug line[k] end end end end DOCKER = method :docker_debug end program_desc 'Utility commands for building and testing Conjur appliance Debian packages' version Conjur::Debify::VERSION subcommand_option_handling :normal arguments :strict def detect_version `git describe --long --tags --abbrev=7 | sed -e 's/^v//'`.strip.tap do |version| raise "No Git version (tag) for project" if version.empty? end end def git_files (`git ls-files -z`.split("\x0") + ['Gemfile.lock']).uniq end desc "Clean current working directory of non-Git-managed files" long_desc <<DESC Reliable builds depend on having a clean working directory. Because debify runs some commands in volume-mounted Docker containers, it is capable of creating root-owned files. This command will delete all files in the working directory that are not git-managed. The command is designed to run in Jenkins. Therefore, it will only perform file deletion if: * The current user, as provided by Etc.getlogin, is 'jenkins' * The BUILD_NUMBER environment variable is set File deletion can be compelled using the "force" option. DESC arg_name "project-name -- <fpm-arguments>" command "clean" do |c| c.desc "Set the current working directory" c.flag [ :d, "dir" ] c.desc "Ignore (don't delete) a file or directory" c.flag [ :i, :ignore ] c.desc "Force file deletion even if if this doesn't look like a Jenkins environment" c.switch [ :force ] c.action do |global_options,cmd_options,args| def looks_like_jenkins? require 'etc' Etc.getlogin == 'jenkins' && ENV['BUILD_NUMBER'] end require 'set' perform_deletion = cmd_options[:force] || looks_like_jenkins? if !perform_deletion $stderr.puts "No --force, and this doesn't look like Jenkins. I won't actually delete anything" end @ignore_list = Array(cmd_options[:ignore]) + [ '.', '..', '.git' ] def ignore_file? f @ignore_list.find{|ignore| f.index(ignore) == 0} end dir = cmd_options[:dir] || '.' dir = File.expand_path(dir) Dir.chdir dir do require 'find' find_files = [] Find.find('.').each do |p| find_files.push p[2..-1] end find_files.compact! delete_files = (find_files - git_files) delete_files.delete_if{|file| File.directory?(file) || ignore_file?(file) } if perform_deletion image = Docker::Image.create 'fromImage' => "alpine:3.3" options = { 'Cmd' => [ "sh", "-c", "while true; do sleep 1; done" ], 'Image' => image.id, 'Binds' => [ [ dir, "/src" ].join(':'), ] } container = Docker::Container.create options begin container.start delete_files.each do |file| puts file file = "/src/#{file}" cmd = [ "rm", "-f", file ] stdout, stderr, status = container.exec cmd, &DebugMixin::DOCKER $stderr.puts "Failed to delete #{file}" unless status == 0 end ensure container.delete force: true end else delete_files.each do |file| puts file end end end end end desc "Build a debian package for a project" long_desc <<DESC The package is built using fpm (https://github.com/jordansissel/fpm). The project directory is required to contain: * A Gemfile and Gemfile.lock * A shell script called debify.sh debify.sh is invoked by the package build process to create any custom files, other than the project source tree. For example, config files can be created in /opt/conjur/etc. The distrib folder in the project source tree is intended to create scripts for package pre-install, post-install etc. The distrib folder is not included in the deb package, so its contents should be copied to the file system or packaged using fpm arguments. All arguments to this command which follow the double-dash are propagated to the fpm command. DESC arg_name "project-name -- <fpm-arguments>" command "package" do |c| c.desc "Set the current working directory" c.flag [ :d, "dir" ] c.desc "Specify the deb version; by default, it's computed from the Git tag" c.flag [ :v, :version ] c.desc "Specify a custom Dockerfile.fpm" c.flag [ :dockerfile] c.action do |global_options,cmd_options,args| raise "project-name is required" unless project_name = args.shift fpm_args = [] if (delimeter = args.shift) == '--' fpm_args = args.dup else raise "Unexpected argument '#{delimiter}'" end dir = cmd_options[:dir] || '.' pwd = File.dirname(__FILE__) fpm_image = Docker::Image.build_from_dir File.expand_path('fpm', File.dirname(__FILE__)), tag: "debify-fpm", &DebugMixin::DOCKER DebugMixin.debug_write "Built base fpm image '#{fpm_image.id}'\n" dir = File.expand_path(dir) Dir.chdir dir do version = cmd_options[:version] || detect_version dockerfile_path = cmd_options[:dockerfile] || File.expand_path("debify/Dockerfile.fpm", pwd) dockerfile = File.read(dockerfile_path) package_name = "conjur-#{project_name}_#{version}_amd64.deb" output = StringIO.new Gem::Package::TarWriter.new(output) do |tar| git_files.each do |fname| stat = File.stat(fname) tar.add_file(fname, stat.mode) { |tar_file| tar_file.write(File.read(fname)) } end tar.add_file('Dockerfile', 0640) { |tar_file| tar_file.write dockerfile.gsub("@@image@@", fpm_image.id) } end output.rewind image = Docker::Image.build_from_tar output, &DebugMixin::DOCKER DebugMixin.debug_write "Built fpm image '#{image.id}' for project #{project_name}\n" options = { 'Cmd' => [ project_name, version ] + fpm_args, 'Image' => image.id } container = Docker::Container.create options begin DebugMixin.debug_write "Packaging #{project_name} in container #{container.id}\n" container.tap(&:start).streaming_logs(follow: true, stdout: true, stderr: true) { |stream, chunk| puts "#{chunk}" } status = container.wait raise "Failed to package #{project_name}" unless status['StatusCode'] == 0 require 'rubygems/package' deb = StringIO.new container.copy("/src/#{package_name}") { |chunk| deb.write(chunk) } deb.rewind tar = Gem::Package::TarReader.new deb tar.first.tap do |entry| open(entry.full_name, 'wb') {|f| f.write(entry.read)} puts entry.full_name end ensure container.delete(force: true) end end end end desc "Test a Conjur debian package in a Conjur appliance container" long_desc <<DESC First, a Conjur appliance container is created and started. By default, the container image is registry.tld/conjur-appliance-cuke-master. An image tag MUST be supplied. This image is configured with all the CONJUR_ environment variables setup for the local environment (appliance URL, cert path, admin username and password, etc). The project source tree is also mounted into the container, at /src/<project-name>. This command then waits for Conjur to initialize and be healthy. It proceeds by installing the conjur-<project-name>_<version>_amd64.deb from the project working directory. Then the evoke "test-install" command is used to install the test code in the /src/<project-name>. Basically, the development bundle is installed and the database configuration (if any) is setup. Finally, a test script from the project source tree is run, again with the container id as the program argument. Then the Conjur container is deleted (use --keep to leave it running). DESC arg_name "project-name test-script" command "test" do |c| c.desc "Set the current working directory" c.flag [ :d, :dir ] c.desc "Keep the Conjur appliance container after the command finishes" c.default_value false c.switch [ :k, :keep ] c.desc "Image name" c.default_value "registry.tld/conjur-appliance-cuke-master" c.flag [ :i, :image ] c.desc "Image tag, e.g. 4.5-stable, 4.6-stable" c.flag [ :t, "image-tag"] c.desc "'docker pull' the Conjur container image" c.default_value true c.switch [ :pull ] c.desc "Specify the deb version; by default, it's computed from the Git tag" c.flag [ :v, :version ] c.action do |global_options,cmd_options,args| raise "project-name is required" unless project_name = args.shift raise "test-script is required" unless test_script = args.shift raise "Receive extra command-line arguments" if args.shift dir = cmd_options[:dir] || '.' dir = File.expand_path(dir) raise "Directory #{dir} does not exist or is not a directory" unless File.directory?(dir) raise "Directory #{dir} does not contain a .deb file" unless Dir["#{dir}/*.deb"].length >= 1 Dir.chdir dir do image_tag = cmd_options["image-tag"] or raise "image-tag is required" appliance_image_id = [ cmd_options[:image], image_tag ].join(":") version = cmd_options[:version] || detect_version package_name = "conjur-#{project_name}_#{version}_amd64.deb" raise "#{test_script} does not exist or is not a file" unless File.file?(test_script) Docker::Image.create 'fromImage' => appliance_image_id, &DebugMixin::DOCKER if cmd_options[:pull] def build_test_image(appliance_image_id, project_name, package_name) dockerfile = <<-DOCKERFILE FROM #{appliance_image_id} COPY #{package_name} /tmp/ RUN if dpkg --list | grep conjur-#{project_name}; then dpkg --force all --purge conjur-#{project_name}; fi RUN if [ -f /opt/conjur/etc/#{project_name}.conf ]; then rm /opt/conjur/etc/#{project_name}.conf; fi RUN dpkg --install /tmp/#{package_name} RUN touch /etc/service/conjur/down DOCKERFILE Dir.mktmpdir do |tmpdir| tmpfile = Tempfile.new('Dockerfile', tmpdir) File.write(tmpfile, dockerfile) dockerfile_name = File.basename(tmpfile.path) tar_cmd = "tar -cvzh -C #{tmpdir} #{dockerfile_name} -C #{Dir.pwd} #{package_name}" tar = open("| #{tar_cmd}") begin Docker::Image.build_from_tar(tar, :dockerfile => dockerfile_name, &DebugMixin::DOCKER) ensure tar.close end end end appliance_image = build_test_image(appliance_image_id, project_name, package_name) vendor_dir = File.expand_path("tmp/debify/#{project_name}/vendor", ENV['HOME']) dot_bundle_dir = File.expand_path("tmp/debify/#{project_name}/.bundle", ENV['HOME']) FileUtils.mkdir_p vendor_dir FileUtils.mkdir_p dot_bundle_dir options = { 'Image' => appliance_image.id, 'Env' => [ "CONJUR_AUTHN_LOGIN=admin", "CONJUR_ENV=appliance", "CONJUR_AUTHN_API_KEY=secret", "CONJUR_ADMIN_PASSWORD=secret", ], 'Binds' => [ [ dir, "/src/#{project_name}" ].join(':'), [ vendor_dir, "/src/#{project_name}/vendor" ].join(':'), [ dot_bundle_dir, "/src/#{project_name}/.bundle" ].join(':') ] } container = Docker::Container.create(options) def wait_for_conjur appliance_image, container wait_options = { 'Image' => appliance_image.id, 'Entrypoint' => '/opt/conjur/evoke/bin/wait_for_conjur', 'HostConfig' => { 'Links' => [ [ container.id, 'conjur' ].join(":") ] } } wait_container = Docker::Container.create wait_options begin spawn("docker logs -f #{wait_container.id}", [ :out, :err ] => $stderr).tap do |pid| Process.detach pid end wait_container.start status = wait_container.wait raise "wait_for_conjur failed" unless status['StatusCode'] == 0 ensure wait_container.delete(force: true) end end def command container, *args stdout, stderr, exitcode = container.exec args, &DebugMixin::DOCKER exit_now! "Command failed : #{args.join(' ')}", exitcode unless exitcode == 0 stdout end begin DebugMixin.debug_write "Testing #{project_name} in container #{container.id}\n" spawn("docker logs -f #{container.id}", [ :out, :err ] => $stderr).tap do |pid| Process.detach pid end container.start # Wait for pg/main so that migrations can run 30.times do stdout, stderr, exitcode = container.exec %w(sv status pg/main), &DebugMixin::DOCKER status = stdout.join break if exitcode == 0 && status =~ /^run\:/ sleep 1 end command container, "/opt/conjur/evoke/bin/test-install", project_name DebugMixin.debug_write "Starting conjur\n" command container, "rm", "/etc/service/conjur/down" command container, "sv", "start", "conjur" wait_for_conjur appliance_image, container system "./#{test_script} #{container.id}" exit_now! "#{test_script} failed with exit code #{$?.exitstatus}", $?.exitstatus unless $?.exitstatus == 0 ensure container.delete(force: true) unless cmd_options[:keep] end end end end desc "Publish a debian package to apt repository" long_desc <<DESC Publishes a deb created with `debify package` to our private apt repository. "distribution" should match the major/minor version of the Conjur appliance you want to install to. The package name is a required option. The package version can be specified as a CLI option, or it will be auto-detected from Git. --component should be 'stable' if run after package tests pass or 'testing' if the package is not yet ready for release. If you don't specify the component, it will be set to 'testing' unless the current git branch is 'master' or 'origin/master'. The git branch is first detected from the env var GIT_BRANCH, and then by checking `git rev-parse --abbrev-ref HEAD` (which won't give you the answer you want when detached). DESC arg_name "distribution project-name" command "publish" do |c| c.desc "Set the current working directory" c.flag [ :d, :dir ] c.desc "Specify the deb package version; by default, it's computed from the Git tag" c.flag [ :v, :version ] c.desc "Maturity stage of the package, 'testing' or 'stable'" c.flag [ :c, :component ] c.action do |global_options,cmd_options,args| raise "distribution is required" unless distribution = args.shift raise "project-name is required" unless project_name = args.shift raise "Receive extra command-line arguments" if args.shift def detect_component branch = ENV['GIT_BRANCH'] || `git rev-parse --abbrev-ref HEAD`.strip if %w(master origin/master).include?(branch) 'stable' else 'testing' end end dir = cmd_options[:dir] || '.' dir = File.expand_path(dir) raise "Directory #{dir} does not exist or is not a directory" unless File.directory?(dir) Dir.chdir dir do version = cmd_options[:version] || detect_version component = cmd_options[:component] || detect_component package_name = "conjur-#{project_name}_#{version}_amd64.deb" publish_image = Docker::Image.build_from_dir File.expand_path('publish', File.dirname(__FILE__)), tag: "debify-publish", &DebugMixin::DOCKER DebugMixin.debug_write "Built base publish image '#{publish_image.id}'\n" require 'conjur/cli' require 'conjur/authn' Conjur::Config.load Conjur::Config.apply conjur = Conjur::Authn.connect nil, noask: true art_username = conjur.variable('artifactory/users/jenkins/username').value art_password = conjur.variable('artifactory/users/jenkins/password').value options = { 'Image' => publish_image.id, 'Cmd' => [ "art", "upload", "--url", "https://conjurinc.artifactoryonline.com/conjurinc", "--user", art_username, "--password", art_password, "--deb", "#{distribution}/#{component}/amd64", package_name, "debian-local/" ], 'Binds' => [ [ dir, "/src" ].join(':') ] } container = Docker::Container.create(options) begin container.tap(&:start).streaming_logs(follow: true, stdout: true, stderr: true) { |stream, chunk| puts "#{chunk}" } status = container.wait raise "Failed to publish #{package_name}" unless status['StatusCode'] == 0 ensure container.delete(force: true) end end end end pre do |global,command,options,args| # Pre logic here # Return true to proceed; false to abort and not call the # chosen command # Use skips_pre before a command to skip this block # on that command only true end post do |global,command,options,args| # Post logic here # Use skips_post before a command to skip this # block on that command only end on_error do |exception| # Error logic here # return false to skip default error handling true end
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module RailsRectTest class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s] config.i18n.default_locale = :es config.i18n.available_locales = [:en, :es] # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true # ActionMailer config config.action_mailer.default_url_options = { host: ENV['HOST'] } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'smtp.sendgrid.net', port: 587, domain: ENV['MAILER_DOMAIN'], authentication: 'plain', enable_starttls_auto: true, user_name: ENV['MAILER_USERNAME'], password: ENV['MAILER_PASSWORD'] } # Webpack integrations config.webpack.dev_server.enabled = false config.webpack.output_dir = "#{Rails.root}/public/webpack" config.webpack.manifest_filename = "manifest.json" end end Disable IP spoofing check To avoid ActionDispatch::RemoteIp::IpSpoofAttackError exceptions when clients are forwarded through more than one differente proxies. Seems to be common for some media outlets with embedded visualizations, like www.postandcourier.com. require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module RailsRectTest class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s] config.i18n.default_locale = :es config.i18n.available_locales = [:en, :es] # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true # ActionMailer config config.action_mailer.default_url_options = { host: ENV['HOST'] } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'smtp.sendgrid.net', port: 587, domain: ENV['MAILER_DOMAIN'], authentication: 'plain', enable_starttls_auto: true, user_name: ENV['MAILER_USERNAME'], password: ENV['MAILER_PASSWORD'] } # Webpack integrations config.webpack.dev_server.enabled = false config.webpack.output_dir = "#{Rails.root}/public/webpack" config.webpack.manifest_filename = "manifest.json" # Disable IP spoofing check config.action_dispatch.ip_spoofing_check = false end end
require 'yaml' require 'active_record' require 'fresh_connection' system("mysql -uroot < spec/db_schema.sql") module ActiveRecord class Base self.configurations = YAML.load_file(File.join(File.dirname(__FILE__), "database.yml")) establish_connection(configurations["test"]) establish_fresh_connection :slave1 end end class Parent < ActiveRecord::Base self.abstract_class = true end class Slave2 < ActiveRecord::Base self.abstract_class = true establish_fresh_connection :slave2 end class User < ActiveRecord::Base has_one :address has_many :tels end class Address < ActiveRecord::Base belongs_to :user end class Tel < Slave2 belongs_to :user end add prepare fresh_connection require 'yaml' require 'active_record' require 'fresh_connection' FreshConnection::Initializer.extend_active_record system("mysql -uroot < spec/db_schema.sql") module ActiveRecord class Base self.configurations = YAML.load_file(File.join(File.dirname(__FILE__), "database.yml")) establish_connection(configurations["test"]) establish_fresh_connection :slave1 end end class Parent < ActiveRecord::Base self.abstract_class = true end class Slave2 < ActiveRecord::Base self.abstract_class = true establish_fresh_connection :slave2 end class User < ActiveRecord::Base has_one :address has_many :tels end class Address < ActiveRecord::Base belongs_to :user end class Tel < Slave2 belongs_to :user end
require 'thor' module WorkGuide class CLI < Thor desc "add [guide description]", "Add a new guide" def add(description) Guide.create(description: description) end desc "list", "List guides" def list Guide.all.each_with_index do |guide, index| puts "[#{index}]#{guide}" end end desc "delete [index]", "Delete a guide" def delete(index) guide = Guide.all.delete_at(index.to_i) Guide.save puts "Deleted [#{index}]#{guide}" end end end Add cycle option for guide require 'thor' module WorkGuide class CLI < Thor desc "add [guide description]", "Add a new guide" option :cycle, default: 'daily', banner: '[hourly|daily|weekly|monthly]', aliases: :c def add(description) Guide.create( description: description, cycle: options[:cycle] ) end desc "list", "List guides" def list Guide.all.each_with_index do |guide, index| puts "[#{index}]#{guide}" end end desc "delete [index]", "Delete a guide" def delete(index) guide = Guide.all.delete_at(index.to_i) Guide.save puts "Deleted [#{index}]#{guide}" end end end