CombinedText
stringlengths
4
3.42M
# # Cookbook Name:: cassandra # Recipe:: setup_repos # # Copyright 2011, DataStax # # Apache License # ################################################### # # Setup Repositories # ################################################### case node[:platform] when "ubuntu", "debian" include_recipe "apt" # Adds the Cassandra repo: if node[:setup][:deployment] == "08x" or node[:setup][:deployment] == "07x" or node[:setup][:deployment] == "10x" or node[:setup][:deployment] == "11x" apt_repository "cassandra-repo" do uri "http://www.apache.org/dist/cassandra/debian" components [node[:setup][:deployment], "main"] keyserver "keys.gnupg.net" key "2B5C1B00" action :add end end when "centos", "redhat", "fedora" if node[:platform] == "fedora" distribution="Fedora" else distribution="EL" end # Install EPEL (Extra Packages for Enterprise Linux) repository platformMajor = node[:platform_version].split(".")[0] epelInstalled = File::exists?("/etc/yum.repos.d/epel.repo") or File::exists?("/etc/yum.repos.d/epel-testing.repo") if !epelInstalled case platformMajor when "6" execute "rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-7.noarch.rpm" when "5" execute "rpm -Uvh http://dl.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm" when "4" execute "rpm -Uvh http://dl.fedoraproject.org/pub/epel/4/x86_64/epel-release-4-10.noarch.rpm" end end execute "yum clean all" end added rpm for cass # # Cookbook Name:: cassandra # Recipe:: setup_repos # # Copyright 2011, DataStax # # Apache License # ################################################### # # Setup Repositories # ################################################### case node[:platform] when "ubuntu", "debian" include_recipe "apt" # Adds the Cassandra repo: if node[:setup][:deployment] == "08x" or node[:setup][:deployment] == "07x" or node[:setup][:deployment] == "10x" or node[:setup][:deployment] == "11x" apt_repository "cassandra-repo" do uri "http://www.apache.org/dist/cassandra/debian" components [node[:setup][:deployment], "main"] keyserver "keys.gnupg.net" key "2B5C1B00" action :add end end when "centos", "redhat", "fedora" if node[:platform] == "fedora" distribution="Fedora" else distribution="EL" end # Install EPEL (Extra Packages for Enterprise Linux) repository platformMajor = node[:platform_version].split(".")[0] epelInstalled = File::exists?("/etc/yum.repos.d/epel.repo") or File::exists?("/etc/yum.repos.d/epel-testing.repo") if !epelInstalled case platformMajor when "6" execute "rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-7.noarch.rpm" when "5" execute "rpm -Uvh http://dl.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm" when "4" execute "rpm -Uvh http://dl.fedoraproject.org/pub/epel/4/x86_64/epel-release-4-10.noarch.rpm" end end # Download cassandra rpm based on OS choice.. (hard set to 8 for the time being) execute "rpm -Uvh http://cassandra-rpm.googlecode.com/files/apache-cassandra-0.8.5-0.el5.noarch.rpm" execute "yum clean all" end
# Copyright (c) 2011 RightScale Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. include RightScale::Database::PostgreSQL::Helper action :stop do @db = init(new_resource) @db.stop end action :start do @db = init(new_resource) @db.start end action :status do @db = init(new_resource) status = @db.status log "Database Status:\n#{status}" end action :lock do @db = init(new_resource) @db.lock end action :unlock do @db = init(new_resource) @db.unlock end action :move_data_dir do @db = init(new_resource) @db.move_datadir end action :reset do @db = init(new_resource) @db.reset end action :firewall_update_request do sys_firewall "Request database open port 5432 (PostgreSQL) to this server" do machine_tag new_resource.machine_tag port 5432 enable new_resource.enable ip_addr new_resource.ip_addr action :update_request end end action :firewall_update do sys_firewall "Request database open port 5432 (PostgrSQL) to this server" do machine_tag new_resource.machine_tag port 5432 enable new_resource.enable action :update end end action :write_backup_info do masterstatus = node[:db][:current_master_ip] if node[:db][:this_is_master] Chef::Log.info "Backing up Master info" else Chef::Log.info "Backing up slave replication status" end Chef::Log.info "Saving master info...:\n#{masterstatus.to_yaml}" ::File.open(::File.join(node[:db][:data_dir], RightScale::Database::PostgreSQL::Helper::SNAPSHOT_POSITION_FILENAME), ::File::CREAT|::File::TRUNC|::File::RDWR) do |out| YAML.dump(masterstatus, out) end end action :pre_restore_check do @db = init(new_resource) @db.pre_restore_sanity_check end action :post_restore_cleanup do @db = init(new_resource) @db.restore_snapshot # @db.post_restore_sanity_check end action :pre_backup_check do @db = init(new_resource) @db.pre_backup_check end action :post_backup_cleanup do @db = init(new_resource) @db.post_backup_steps end action :set_privileges do priv = new_resource.privilege priv_username = new_resource.privilege_username priv_password = new_resource.privilege_password priv_database = new_resource.privilege_database db_postgres_set_privileges "setup db privileges" do preset priv username priv_username password priv_password database priv_database end end action :install_client do # Install PostgreSQL 9.1.1 package(s) if node[:platform] == "centos" arch = node[:kernel][:machine] arch = "x86_64" if arch == "i386" # Install PostgreSQL GPG Key (http://yum.postgresql.org/9.1/redhat/rhel-5-(arch)/pgdg-centos91-9.1-4.noarch.rpm) pgreporpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "pgdg-centos91-9.1-4.noarch.rpm") `rpm -ihv #{pgreporpm}` #Installing Libxslt package for postgresql-9.1 dependancy package "libxslt" do action :install end # Packages from cookbook files as attachment for PostgreSQL 9.1.1 # Install PostgreSQL client rpm pgdevelrpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "postgresql91-devel-9.1.1-1PGDG.rhel5.#{arch}.rpm") pglibrpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "postgresql91-libs-9.1.1-1PGDG.rhel5.#{arch}.rpm") pgrpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "postgresql91-9.1.1-1PGDG.rhel5.#{arch}.rpm") `rpm -ivh --nodeps #{pgrpm}` package "#{pglibrpm}" do action :install source "#{pglibrpm}" provider Chef::Provider::Package::Rpm end package "#{pgdevelrpm}" do action :install source "#{pgdevelrpm}" provider Chef::Provider::Package::Rpm end else # Currently supports CentOS in future will support others end # == Install PostgreSQL client gem # # Also installs in compile phase # execute "install pg gem" do command "/opt/rightscale/sandbox/bin/gem install pg -- --with-pg-config=/usr/pgsql-9.1/bin/pg_config" end end action :install_server do # PostgreSQL server depends on PostgreSQL client action_install_client arch = node[:kernel][:machine] arch = "x86_64" if arch == "i386" # Install PostgreSQL 9.1 server rpm pgserverrpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "postgresql91-server-9.1.1-1PGDG.rhel5.#{arch}.rpm") # Install PostgreSQL contrib rpm pgcontribpkg = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "postgresql91-contrib-9.1.1-1PGDG.rhel5.#{arch}.rpm") # Install uuid package to resolve postgresql-contrib package uuidrpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "uuid-1.5.1-4.rhel5.#{arch}.rpm") package "#{pgserverrpm}" do action :install source "#{pgserverrpm}" provider Chef::Provider::Package::Rpm end package "#{uuidrpm}" do action :install source "#{uuidrpm}" provider Chef::Provider::Package::Rpm end package "#{pgcontribpkg}" do action :install source "#{pgcontribpkg}" provider Chef::Provider::Package::Rpm end service "postgresql-9.1" do supports :status => true, :restart => true, :reload => true action :stop end # Initialize PostgreSQL server and create system tables touchfile = ::File.expand_path "~/.postgresql_installed" execute "/etc/init.d/postgresql-9.1 initdb" do creates touchfile end # == Configure system for PostgreSQL # # Stop PostgreSQL service "postgresql-9.1" do supports :status => true, :restart => true, :reload => true action :stop end # Create the Socket directory # directory "/var/run/postgresql" do directory "#{node[:db_postgres][:socket]}" do owner "postgres" group "postgres" mode 0770 recursive true end # Setup postgresql.conf template "#{node[:db_postgres][:confdir]}/postgresql.conf" do source "postgresql.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end # Setup pg_hba.conf template "#{node[:db_postgres][:confdir]}/pg_hba.conf" do source "pg_hba.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end # == Setup PostgreSQL user limits # # Set the postgres and root users max open files to a really large number. # 1/3 of the overall system file max should be large enough. The percentage can be # adjusted if necessary. # postgres_file_ulimit = `sysctl -n fs.file-max`.to_i/33 template "/etc/security/limits.d/postgres.limits.conf" do source "postgres.limits.conf.erb" variables({ :ulimit => postgres_file_ulimit }) cookbook 'db_postgres' end # Change root's limitations for THIS shell. The entry in the limits.d will be # used for future logins. # The setting needs to be in place before postgresql-9 is started. # execute "ulimit -n #{postgres_file_ulimit}" # == Start PostgreSQL # service "postgresql-9.1" do supports :status => true, :restart => true, :reload => true action :start end end action :grant_replication_slave do require 'rubygems' Gem.clear_paths require 'pg' Chef::Log.info "GRANT REPLICATION SLAVE to #{node[:db][:replication][:user]}" # Opening connection for pg operation conn = PGconn.open("localhost", nil, nil, nil, nil, "postgres", nil) # Enable admin/replication user conn.exec("CREATE USER #{node[:db][:replication][:user]} SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN ENCRYPTED PASSWORD '#{node[:db][:replication][:password]}'") conn.close # Setup pg_hba.conf for replication user allow RightScale::Database::PostgreSQL::Helper.configure_pg_hba(node) # Reload postgresql to read new updated pg_hba.conf RightScale::Database::PostgreSQL::Helper.do_query('select pg_reload_conf()') end action :enable_replication do newmaster = node[:db][:current_master_ip] ruby_block "reconfigure_replication" do block do master_info = RightScale::Database::PostgreSQL::Helper.load_replication_info(node) newmaster_host = master_info['Master_IP'] # RightScale::Database::PostgreSQL::Helper.reconfigure_replication(node, 'localhost', newmaster_host, newmaster_logfile, newmaster_position) end end # Sync to Master data #@db.rsync_db(newmaster) RightScale::Database::PostgreSQL::Helper.rsync_db(newmaster) # Setup recovery conf #@db.reconfigure_replication_info(newmaster) RightScale::Database::PostgreSQL::Helper.reconfigure_replication_info(newmaster) # Stopping postgresql action_stop ruby_block "wipe_existing_runtime_config" do block do Chef::Log.info "Wiping existing runtime config files" data_dir = ::File.join(node[:db][:data_dir], 'pg_xlog') files_to_delete = [ "*"] files_to_delete.each do |file| expand = Dir.glob(::File.join(data_dir,file)) unless expand.empty? expand.each do |exp_file| FileUtils.rm_rf(exp_file) end end end end end # @db.ensure_db_started # service provider uses the status command to decide if it # has to run the start command again. 5.times do action_start end ruby_block "validate_backup" do block do master_info = RightScale::Database::PostgreSQL::Helper.load_replication_info(node) raise "Position and file not saved!" unless master_info['Master_instance_uuid'] # Check that the snapshot is from the current master or a slave associated with the current master if master_info['Master_instance_uuid'] != node[:db][:current_master_uuid] raise "FATAL: snapshot was taken from a different master! snap_master was:#{master_info['Master_instance_uuid']} != current master: #{node[:db][:current_master_uuid]}" end end end end action :promote do # stopping postgresql action_stop # Setup postgresql.conf template "#{node[:db_postgres][:confdir]}/postgresql.conf" do source "postgresql.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end # Setup pg_hba.conf template "#{node[:db_postgres][:confdir]}/pg_hba.conf" do source "pg_hba.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end previous_master = node[:db][:current_master_ip] raise "FATAL: could not determine master host from slave status" if previous_master.nil? Chef::Log.info "host: #{previous_master}}" # PHASE1: contains non-critical old master operations, if a timeout or # error occurs we continue promotion assuming the old master is dead. begin # Critical operations on newmaster, if a failure occurs here we allow it to halt promote operations # <Ravi - Do your stuff here> ### INITIAL CHECKS # Perform an initial connection forcing to accept the keys...to avoid interaction. db.accept_ssh_key(newmaster) # Ensure that that the newmaster DB is up action_start # Promote the slave into the new master Chef::Log.info "Promoting slave.." #db.write_trigger(node) RightScale::Database::PostgreSQL::Helper.write_trigger(node) # Let the new slave loose and thus let him become the new master Chef::Log.info "New master is ReadWrite." rescue => e Chef::Log.info "WARNING: caught exception #{e} during critical operations on the MASTER" end end action :setup_monitoring do service "collectd" do action :nothing end arch = node[:kernel][:machine] arch = "i386" if arch == "i686" if node[:platform] == 'centos' TMP_FILE = "/tmp/collectd.rpm" remote_file TMP_FILE do source "collectd-postgresql-4.10.0-4.el5.#{arch}.rpm" cookbook 'db_postgres' end package TMP_FILE do source TMP_FILE end template ::File.join(node[:rs_utils][:collectd_plugin_dir], 'postgresql.conf') do backup false source "postgresql_collectd_plugin.conf.erb" notifies :restart, resources(:service => "collectd") cookbook 'db_postgres' end # install the postgres_ps collectd script into the collectd library plugins directory remote_file ::File.join(node[:rs_utils][:collectd_lib], "plugins", 'postgres_ps') do source "postgres_ps" mode "0755" cookbook 'db_postgres' end # add a collectd config file for the postgres_ps script with the exec plugin and restart collectd if necessary template ::File.join(node[:rs_utils][:collectd_plugin_dir], 'postgres_ps.conf') do source "postgres_collectd_exec.erb" notifies :restart, resources(:service => "collectd") cookbook 'db_postgres' end else log "WARNING: attempting to install collectd-postgresql on unsupported platform #{node[:platform]}, continuing.." do level :warn end end end action :generate_dump_file do db_name = new_resource.db_name dumpfile = new_resource.dumpfile bash "Write the postgres DB backup file" do user 'postgres' code <<-EOH pg_dump -h /var/run/postgresql #{db_name} | gzip -c > #{dumpfile} EOH end end action :restore_from_dump_file do db_name = new_resource.db_name dumpfile = new_resource.dumpfile log " Check if DB already exists" ruby_block "checking existing db" do block do db_check = `echo "select datname from pg_database" | psql -U postgres -h /var/run/postgresql | grep -q "#{db_name}"` if ! db_check.empty? raise "ERROR: database '#{db_name}' already exists" end end end bash "Import PostgreSQL dump file: #{dumpfile}" do user "postgres" code <<-EOH set -e if [ ! -f #{dumpfile} ] then echo "ERROR: PostgreSQL dumpfile not found! File: '#{dumpfile}'" exit 1 fi createdb -U postgres -h /var/run/postgresql #{db_name} gunzip < #{dumpfile} | psql -U postgres -h /var/run/postgresql #{db_name} EOH end end updated enable-promote # Copyright (c) 2011 RightScale Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. include RightScale::Database::PostgreSQL::Helper action :stop do @db = init(new_resource) @db.stop end action :start do @db = init(new_resource) @db.start end action :status do @db = init(new_resource) status = @db.status log "Database Status:\n#{status}" end action :lock do @db = init(new_resource) @db.lock end action :unlock do @db = init(new_resource) @db.unlock end action :move_data_dir do @db = init(new_resource) @db.move_datadir end action :reset do @db = init(new_resource) @db.reset end action :firewall_update_request do sys_firewall "Request database open port 5432 (PostgreSQL) to this server" do machine_tag new_resource.machine_tag port 5432 enable new_resource.enable ip_addr new_resource.ip_addr action :update_request end end action :firewall_update do sys_firewall "Request database open port 5432 (PostgrSQL) to this server" do machine_tag new_resource.machine_tag port 5432 enable new_resource.enable action :update end end action :write_backup_info do masterstatus = node[:db][:current_master_ip] if node[:db][:this_is_master] Chef::Log.info "Backing up Master info" else Chef::Log.info "Backing up slave replication status" end Chef::Log.info "Saving master info...:\n#{masterstatus.to_yaml}" ::File.open(::File.join(node[:db][:data_dir], RightScale::Database::PostgreSQL::Helper::SNAPSHOT_POSITION_FILENAME), ::File::CREAT|::File::TRUNC|::File::RDWR) do |out| YAML.dump(masterstatus, out) end end action :pre_restore_check do @db = init(new_resource) @db.pre_restore_sanity_check end action :post_restore_cleanup do @db = init(new_resource) @db.restore_snapshot # @db.post_restore_sanity_check end action :pre_backup_check do @db = init(new_resource) @db.pre_backup_check end action :post_backup_cleanup do @db = init(new_resource) @db.post_backup_steps end action :set_privileges do priv = new_resource.privilege priv_username = new_resource.privilege_username priv_password = new_resource.privilege_password priv_database = new_resource.privilege_database db_postgres_set_privileges "setup db privileges" do preset priv username priv_username password priv_password database priv_database end end action :install_client do # Install PostgreSQL 9.1.1 package(s) if node[:platform] == "centos" arch = node[:kernel][:machine] arch = "x86_64" if arch == "i386" # Install PostgreSQL GPG Key (http://yum.postgresql.org/9.1/redhat/rhel-5-(arch)/pgdg-centos91-9.1-4.noarch.rpm) pgreporpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "pgdg-centos91-9.1-4.noarch.rpm") `rpm -ihv #{pgreporpm}` #Installing Libxslt package for postgresql-9.1 dependancy package "libxslt" do action :install end # Packages from cookbook files as attachment for PostgreSQL 9.1.1 # Install PostgreSQL client rpm pgdevelrpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "postgresql91-devel-9.1.1-1PGDG.rhel5.#{arch}.rpm") pglibrpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "postgresql91-libs-9.1.1-1PGDG.rhel5.#{arch}.rpm") pgrpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "postgresql91-9.1.1-1PGDG.rhel5.#{arch}.rpm") `rpm -ivh --nodeps #{pgrpm}` package "#{pglibrpm}" do action :install source "#{pglibrpm}" provider Chef::Provider::Package::Rpm end package "#{pgdevelrpm}" do action :install source "#{pgdevelrpm}" provider Chef::Provider::Package::Rpm end else # Currently supports CentOS in future will support others end # == Install PostgreSQL client gem # # Also installs in compile phase # execute "install pg gem" do command "/opt/rightscale/sandbox/bin/gem install pg -- --with-pg-config=/usr/pgsql-9.1/bin/pg_config" end end action :install_server do # PostgreSQL server depends on PostgreSQL client action_install_client arch = node[:kernel][:machine] arch = "x86_64" if arch == "i386" # Install PostgreSQL 9.1 server rpm pgserverrpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "postgresql91-server-9.1.1-1PGDG.rhel5.#{arch}.rpm") # Install PostgreSQL contrib rpm pgcontribpkg = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "postgresql91-contrib-9.1.1-1PGDG.rhel5.#{arch}.rpm") # Install uuid package to resolve postgresql-contrib package uuidrpm = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "uuid-1.5.1-4.rhel5.#{arch}.rpm") package "#{pgserverrpm}" do action :install source "#{pgserverrpm}" provider Chef::Provider::Package::Rpm end package "#{uuidrpm}" do action :install source "#{uuidrpm}" provider Chef::Provider::Package::Rpm end package "#{pgcontribpkg}" do action :install source "#{pgcontribpkg}" provider Chef::Provider::Package::Rpm end service "postgresql-9.1" do supports :status => true, :restart => true, :reload => true action :stop end # Initialize PostgreSQL server and create system tables touchfile = ::File.expand_path "~/.postgresql_installed" execute "/etc/init.d/postgresql-9.1 initdb" do creates touchfile end # == Configure system for PostgreSQL # # Stop PostgreSQL service "postgresql-9.1" do supports :status => true, :restart => true, :reload => true action :stop end # Create the Socket directory # directory "/var/run/postgresql" do directory "#{node[:db_postgres][:socket]}" do owner "postgres" group "postgres" mode 0770 recursive true end # Setup postgresql.conf template "#{node[:db_postgres][:confdir]}/postgresql.conf" do source "postgresql.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end # Setup pg_hba.conf template "#{node[:db_postgres][:confdir]}/pg_hba.conf" do source "pg_hba.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end # == Setup PostgreSQL user limits # # Set the postgres and root users max open files to a really large number. # 1/3 of the overall system file max should be large enough. The percentage can be # adjusted if necessary. # postgres_file_ulimit = `sysctl -n fs.file-max`.to_i/33 template "/etc/security/limits.d/postgres.limits.conf" do source "postgres.limits.conf.erb" variables({ :ulimit => postgres_file_ulimit }) cookbook 'db_postgres' end # Change root's limitations for THIS shell. The entry in the limits.d will be # used for future logins. # The setting needs to be in place before postgresql-9 is started. # execute "ulimit -n #{postgres_file_ulimit}" # == Start PostgreSQL # service "postgresql-9.1" do supports :status => true, :restart => true, :reload => true action :start end end action :grant_replication_slave do require 'rubygems' Gem.clear_paths require 'pg' Chef::Log.info "GRANT REPLICATION SLAVE to #{node[:db][:replication][:user]}" # Opening connection for pg operation conn = PGconn.open("localhost", nil, nil, nil, nil, "postgres", nil) # Enable admin/replication user conn.exec("CREATE USER #{node[:db][:replication][:user]} SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN ENCRYPTED PASSWORD '#{node[:db][:replication][:password]}'") conn.close # Setup pg_hba.conf for replication user allow RightScale::Database::PostgreSQL::Helper.configure_pg_hba(node) # Reload postgresql to read new updated pg_hba.conf RightScale::Database::PostgreSQL::Helper.do_query('select pg_reload_conf()') end action :enable_replication do newmaster = node[:db][:current_master_ip] master_info = RightScale::Database::PostgreSQL::Helper.load_replication_info(node) newmaster_host = master_info['Master_IP'] # Sync to Master data #@db.rsync_db(newmaster) RightScale::Database::PostgreSQL::Helper.rsync_db(newmaster) # Setup recovery conf #@db.reconfigure_replication_info(newmaster) RightScale::Database::PostgreSQL::Helper.reconfigure_replication_info(newmaster) # Stopping postgresql action_stop ruby_block "wipe_existing_runtime_config" do block do Chef::Log.info "Wiping existing runtime config files" data_dir = ::File.join(node[:db][:data_dir], 'pg_xlog') files_to_delete = [ "*"] files_to_delete.each do |file| expand = Dir.glob(::File.join(data_dir,file)) unless expand.empty? expand.each do |exp_file| FileUtils.rm_rf(exp_file) end end end end end # @db.ensure_db_started # service provider uses the status command to decide if it # has to run the start command again. 5.times do action_start end ruby_block "validate_backup" do block do master_info = RightScale::Database::PostgreSQL::Helper.load_replication_info(node) raise "Position and file not saved!" unless master_info['Master_instance_uuid'] # Check that the snapshot is from the current master or a slave associated with the current master if master_info['Master_instance_uuid'] != node[:db][:current_master_uuid] raise "FATAL: snapshot was taken from a different master! snap_master was:#{master_info['Master_instance_uuid']} != current master: #{node[:db][:current_master_uuid]}" end end end end action :promote do # stopping postgresql action_stop # Setup postgresql.conf template "#{node[:db_postgres][:confdir]}/postgresql.conf" do source "postgresql.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end # Setup pg_hba.conf template "#{node[:db_postgres][:confdir]}/pg_hba.conf" do source "pg_hba.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end previous_master = node[:db][:current_master_ip] raise "FATAL: could not determine master host from slave status" if previous_master.nil? Chef::Log.info "host: #{previous_master}}" # PHASE1: contains non-critical old master operations, if a timeout or # error occurs we continue promotion assuming the old master is dead. begin # Critical operations on newmaster, if a failure occurs here we allow it to halt promote operations # <Ravi - Do your stuff here> ### INITIAL CHECKS # Perform an initial connection forcing to accept the keys...to avoid interaction. db.accept_ssh_key(newmaster) # Ensure that that the newmaster DB is up action_start # Promote the slave into the new master Chef::Log.info "Promoting slave.." #db.write_trigger(node) RightScale::Database::PostgreSQL::Helper.write_trigger(node) # Let the new slave loose and thus let him become the new master Chef::Log.info "New master is ReadWrite." rescue => e Chef::Log.info "WARNING: caught exception #{e} during critical operations on the MASTER" end end action :setup_monitoring do service "collectd" do action :nothing end arch = node[:kernel][:machine] arch = "i386" if arch == "i686" if node[:platform] == 'centos' TMP_FILE = "/tmp/collectd.rpm" remote_file TMP_FILE do source "collectd-postgresql-4.10.0-4.el5.#{arch}.rpm" cookbook 'db_postgres' end package TMP_FILE do source TMP_FILE end template ::File.join(node[:rs_utils][:collectd_plugin_dir], 'postgresql.conf') do backup false source "postgresql_collectd_plugin.conf.erb" notifies :restart, resources(:service => "collectd") cookbook 'db_postgres' end # install the postgres_ps collectd script into the collectd library plugins directory remote_file ::File.join(node[:rs_utils][:collectd_lib], "plugins", 'postgres_ps') do source "postgres_ps" mode "0755" cookbook 'db_postgres' end # add a collectd config file for the postgres_ps script with the exec plugin and restart collectd if necessary template ::File.join(node[:rs_utils][:collectd_plugin_dir], 'postgres_ps.conf') do source "postgres_collectd_exec.erb" notifies :restart, resources(:service => "collectd") cookbook 'db_postgres' end else log "WARNING: attempting to install collectd-postgresql on unsupported platform #{node[:platform]}, continuing.." do level :warn end end end action :generate_dump_file do db_name = new_resource.db_name dumpfile = new_resource.dumpfile bash "Write the postgres DB backup file" do user 'postgres' code <<-EOH pg_dump -h /var/run/postgresql #{db_name} | gzip -c > #{dumpfile} EOH end end action :restore_from_dump_file do db_name = new_resource.db_name dumpfile = new_resource.dumpfile log " Check if DB already exists" ruby_block "checking existing db" do block do db_check = `echo "select datname from pg_database" | psql -U postgres -h /var/run/postgresql | grep -q "#{db_name}"` if ! db_check.empty? raise "ERROR: database '#{db_name}' already exists" end end end bash "Import PostgreSQL dump file: #{dumpfile}" do user "postgres" code <<-EOH set -e if [ ! -f #{dumpfile} ] then echo "ERROR: PostgreSQL dumpfile not found! File: '#{dumpfile}'" exit 1 fi createdb -U postgres -h /var/run/postgresql #{db_name} gunzip < #{dumpfile} | psql -U postgres -h /var/run/postgresql #{db_name} EOH end end
# Copyright (c) 2011 RightScale Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. include RightScale::Database::PostgreSQL::Helper action :stop do @db = init(new_resource) @db.stop end action :start do @db = init(new_resource) @db.start end action :status do @db = init(new_resource) status = @db.status log "Database Status:\n#{status}" end action :lock do @db = init(new_resource) @db.lock end action :unlock do @db = init(new_resource) @db.unlock end action :move_data_dir do @db = init(new_resource) @db.move_datadir end action :reset do @db = init(new_resource) @db.reset end action :firewall_update_request do sys_firewall "Request database open port 5432 (PostgreSQL) to this server" do machine_tag new_resource.machine_tag port 5432 enable new_resource.enable ip_addr new_resource.ip_addr action :update_request end end action :firewall_update do sys_firewall "Request database open port 5432 (PostgrSQL) to this server" do machine_tag new_resource.machine_tag port 5432 enable new_resource.enable action :update end end action :write_backup_info do File_position = `/usr/pgsql-9.1/bin/pg_controldata /var/lib/pgsql/9.1/data/ | grep "Latest checkpoint location:" | awk '{print $NF}'` masterstatus = Hash.new masterstatus['Master_IP'] = node[:db][:current_master_ip] masterstatus['Master_instance_uuid'] = node[:db][:current_master_uuid] slavestatus ||= Hash.new slavestatus['File_position'] = File_position if node[:db][:this_is_master] Chef::Log.info "Backing up Master info" else Chef::Log.info "Backing up slave replication status" masterstatus['File_position'] = slavestatus['File_position'] end Chef::Log.info "Saving master info...:\n#{masterstatus.to_yaml}" ::File.open(::File.join(node[:db][:data_dir], RightScale::Database::PostgreSQL::Helper::SNAPSHOT_POSITION_FILENAME), ::File::CREAT|::File::TRUNC|::File::RDWR) do |out| YAML.dump(masterstatus, out) end end action :pre_restore_check do @db = init(new_resource) @db.pre_restore_sanity_check end action :post_restore_cleanup do @db = init(new_resource) @db.restore_snapshot # @db.post_restore_sanity_check end action :pre_backup_check do @db = init(new_resource) @db.pre_backup_check end action :post_backup_cleanup do @db = init(new_resource) @db.post_backup_steps end action :set_privileges do priv = new_resource.privilege priv_username = new_resource.privilege_username priv_password = new_resource.privilege_password priv_database = new_resource.privilege_database db_postgres_set_privileges "setup db privileges" do preset priv username priv_username password priv_password database priv_database end end action :install_client do # Install PostgreSQL 9.1.1 package(s) if node[:platform] == "centos" arch = node[:kernel][:machine] arch = "x86_64" if arch == "i386" # Install PostgreSQL GPG Key (http://yum.postgresql.org/9.1/redhat/rhel-5-(arch)/pgdg-centos91-9.1-4.noarch.rpm) package "libxslt" do action :install end packages = ["postgresql91-libs", "postgresql91", "postgresql91-devel" ] Chef::Log.info("Packages to install: #{packages.join(",")}") packages.each do |p| pkg = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "#{p}-9.1.1-1PGDG.rhel5.#{arch}.rpm") package p do action :install source "#{pkg}" provider Chef::Provider::Package::Rpm end end else # Currently supports CentOS in future will support others end # == Install PostgreSQL client gem # # Also installs in compile phase gem_package("pg") do gem_binary("/opt/rightscale/sandbox/bin/gem") options("-- --with-pg-config=/usr/pgsql-9.1/bin/pg_config") end end action :install_server do # PostgreSQL server depends on PostgreSQL client action_install_client arch = node[:kernel][:machine] arch = "x86_64" if arch == "i386" package "uuid" do action :install end node[:db_postgres][:packages_install].each do |p| pkg = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "#{p}-9.1.1-1PGDG.rhel5.#{arch}.rpm") package p do action :install source "#{pkg}" provider Chef::Provider::Package::Rpm end end service "postgresql-9.1" do #service_name value_for_platform([ "centos", "redhat", "suse" ] => {"default" => "postgresql-9.1"}, "default" => "postgresql-9.1") supports :status => true, :restart => true, :reload => true action :stop end # Initialize PostgreSQL server and create system tables touchfile = ::File.expand_path "~/.postgresql_installed" execute "/etc/init.d/postgresql-9.1 initdb" do creates touchfile end # == Configure system for PostgreSQL # # Stop PostgreSQL service "postgresql-9.1" do supports :status => true, :restart => true, :reload => true action :stop end # Create the Socket directory # directory "/var/run/postgresql" do directory "#{node[:db_postgres][:socket]}" do owner "postgres" group "postgres" mode 0770 recursive true end # Setup postgresql.conf # template_source = "postgresql.conf.erb" template value_for_platform([ "centos", "redhat", "suse" ] => {"default" => "#{node[:db_postgres][:confdir]}/postgresql.conf"}, "default" => "#{node[:db_postgres][:confdir]}/postgresql.conf") do source "postgresql.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end # Setup pg_hba.conf # pg_hba_source = "pg_hba.conf.erb" template value_for_platform([ "centos", "redhat", "suse" ] => {"default" => "#{node[:db_postgres][:confdir]}/pg_hba.conf"}, "default" => "#{node[:db_postgres][:confdir]}/pg_hba.conf") do source "pg_hba.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end # == Setup PostgreSQL user limits # # Set the postgres and root users max open files to a really large number. # 1/3 of the overall system file max should be large enough. The percentage can be # adjusted if necessary. # postgres_file_ulimit = `sysctl -n fs.file-max`.to_i/33 template "/etc/security/limits.d/postgres.limits.conf" do source "postgres.limits.conf.erb" variables({ :ulimit => postgres_file_ulimit }) cookbook 'db_postgres' end # Change root's limitations for THIS shell. The entry in the limits.d will be # used for future logins. # The setting needs to be in place before postgresql-9 is started. # execute "ulimit -n #{postgres_file_ulimit}" # == Start PostgreSQL # service "postgresql-9.1" do # supports :status => true, :restart => true, :reload => true action :start end end action :grant_replication_slave do require 'rubygems' Gem.clear_paths require 'pg' Chef::Log.info "GRANT REPLICATION SLAVE to user #{node[:db][:replication][:user]}" # Opening connection for pg operation conn = PGconn.open("localhost", nil, nil, nil, nil, "postgres", nil) # Enable admin/replication user # Check if server is in read_only mode, if found skip this... res = conn.exec("show transaction_read_only") slavestatus = res.getvalue(0,0) if ( slavestatus == 'off' ) Chef::Log.info "Detected Master server." result = conn.exec("SELECT COUNT(*) FROM pg_user WHERE usename='#{node[:db][:replication][:user]}'") userstat = result.getvalue(0,0) if ( userstat == '1' ) Chef::Log.info "User #{node[:db][:replication][:user]} already exists, updating user using current inputs" conn.exec("ALTER USER #{node[:db][:replication][:user]} SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN ENCRYPTED PASSWORD '#{node[:db][:replication][:password]}'") else Chef::Log.info "creating replication user #{node[:db][:replication][:user]}" conn.exec("CREATE USER #{node[:db][:replication][:user]} SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN ENCRYPTED PASSWORD '#{node[:db][:replication][:password]}'") # Setup pg_hba.conf for replication user allow RightScale::Database::PostgreSQL::Helper.configure_pg_hba(node) # Reload postgresql to read new updated pg_hba.conf RightScale::Database::PostgreSQL::Helper.do_query('select pg_reload_conf()') end else Chef::Log.info "Skipping 'create replication user', Detected read_only db or slave mode" end conn.finish end action :enable_replication do newmaster_host = node[:db][:current_master_ip] rep_user = node[:db][:replication][:user] rep_pass = node[:db][:replication][:password] app_name = node[:rightscale][:instance_uuid] master_info = RightScale::Database::PostgreSQL::Helper.load_replication_info(node) # == Set slave state # log "Setting up slave state..." ruby_block "set slave state" do block do node[:db][:this_is_master] = false end end # Stopping postgresql action_stop # Sync to Master data RightScale::Database::PostgreSQL::Helper.rsync_db(newmaster_host, rep_user) # Setup recovery conf RightScale::Database::PostgreSQL::Helper.reconfigure_replication_info(newmaster_host, rep_user, rep_pass, app_name) # Removing existing_runtime_log_files Chef::Log.info "Removing existing runtime log files" `rm -rf "#{node[:db][:datadir]}/pg_xlog/*"` # @db.ensure_db_started # service provider uses the status command to decide if it # has to run the start command again. 5.times do action_start end ruby_block "validate_backup" do block do master_info = RightScale::Database::MySQL::Helper.load_replication_info(node) raise "Position and file not saved!" unless master_info['Master_instance_uuid'] # Check that the snapshot is from the current master or a slave associated with the current master if master_info['Master_instance_uuid'] != node[:db][:current_master_uuid] raise "FATAL: snapshot was taken from a different master! snap_master was:#{master_info['Master_instance_uuid']} != current master: #{node[:db][:current_master_uuid]}" end end end end action :promote do previous_master = node[:db][:current_master_ip] raise "FATAL: could not determine master host from slave status" if previous_master.nil? Chef::Log.info "host: #{previous_master}}" # PHASE1: contains non-critical old master operations, if a timeout or # error occurs we continue promotion assuming the old master is dead. begin # Critical operations on newmaster, if a failure occurs here we allow it to halt promote operations # <Ravi - Do your stuff here> # Promote the slave into the new master Chef::Log.info "Promoting slave.." RightScale::Database::PostgreSQL::Helper.write_trigger(node) sleep 10 # Let the new slave loose and thus let him become the new master Chef::Log.info "New master is ReadWrite." rescue => e Chef::Log.info "WARNING: caught exception #{e} during critical operations on the MASTER" end end action :setup_monitoring do service "collectd" do action :nothing end arch = node[:kernel][:machine] arch = "i386" if arch == "i686" if node[:platform] == 'centos' TMP_FILE = "/tmp/collectd.rpm" remote_file TMP_FILE do source "collectd-postgresql-4.10.0-4.el5.#{arch}.rpm" cookbook 'db_postgres' end package TMP_FILE do source TMP_FILE end template ::File.join(node[:rs_utils][:collectd_plugin_dir], 'postgresql.conf') do backup false source "postgresql_collectd_plugin.conf.erb" notifies :restart, resources(:service => "collectd") cookbook 'db_postgres' end # install the postgres_ps collectd script into the collectd library plugins directory remote_file ::File.join(node[:rs_utils][:collectd_lib], "plugins", 'postgres_ps') do source "postgres_ps" mode "0755" cookbook 'db_postgres' end # add a collectd config file for the postgres_ps script with the exec plugin and restart collectd if necessary template ::File.join(node[:rs_utils][:collectd_plugin_dir], 'postgres_ps.conf') do source "postgres_collectd_exec.erb" notifies :restart, resources(:service => "collectd") cookbook 'db_postgres' end else log "WARNING: attempting to install collectd-postgresql on unsupported platform #{node[:platform]}, continuing.." do level :warn end end end action :generate_dump_file do db_name = new_resource.db_name dumpfile = new_resource.dumpfile bash "Write the postgres DB backup file" do user 'postgres' code <<-EOH pg_dump -h /var/run/postgresql #{db_name} | gzip -c > #{dumpfile} EOH end end action :restore_from_dump_file do db_name = new_resource.db_name dumpfile = new_resource.dumpfile log " Check if DB already exists" ruby_block "checking existing db" do block do db_check = `echo "select datname from pg_database" | psql -U postgres -h /var/run/postgresql | grep -q "#{db_name}"` if ! db_check.empty? raise "ERROR: database '#{db_name}' already exists" end end end bash "Import PostgreSQL dump file: #{dumpfile}" do user "postgres" code <<-EOH set -e if [ ! -f #{dumpfile} ] then echo "ERROR: PostgreSQL dumpfile not found! File: '#{dumpfile}'" exit 1 fi createdb -U postgres -h /var/run/postgresql #{db_name} gunzip < #{dumpfile} | psql -U postgres -h /var/run/postgresql #{db_name} EOH end end updates validate backup # Copyright (c) 2011 RightScale Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. include RightScale::Database::PostgreSQL::Helper action :stop do @db = init(new_resource) @db.stop end action :start do @db = init(new_resource) @db.start end action :status do @db = init(new_resource) status = @db.status log "Database Status:\n#{status}" end action :lock do @db = init(new_resource) @db.lock end action :unlock do @db = init(new_resource) @db.unlock end action :move_data_dir do @db = init(new_resource) @db.move_datadir end action :reset do @db = init(new_resource) @db.reset end action :firewall_update_request do sys_firewall "Request database open port 5432 (PostgreSQL) to this server" do machine_tag new_resource.machine_tag port 5432 enable new_resource.enable ip_addr new_resource.ip_addr action :update_request end end action :firewall_update do sys_firewall "Request database open port 5432 (PostgrSQL) to this server" do machine_tag new_resource.machine_tag port 5432 enable new_resource.enable action :update end end action :write_backup_info do File_position = `/usr/pgsql-9.1/bin/pg_controldata /var/lib/pgsql/9.1/data/ | grep "Latest checkpoint location:" | awk '{print $NF}'` masterstatus = Hash.new masterstatus['Master_IP'] = node[:db][:current_master_ip] masterstatus['Master_instance_uuid'] = node[:db][:current_master_uuid] slavestatus ||= Hash.new slavestatus['File_position'] = File_position if node[:db][:this_is_master] Chef::Log.info "Backing up Master info" else Chef::Log.info "Backing up slave replication status" masterstatus['File_position'] = slavestatus['File_position'] end Chef::Log.info "Saving master info...:\n#{masterstatus.to_yaml}" ::File.open(::File.join(node[:db][:data_dir], RightScale::Database::PostgreSQL::Helper::SNAPSHOT_POSITION_FILENAME), ::File::CREAT|::File::TRUNC|::File::RDWR) do |out| YAML.dump(masterstatus, out) end end action :pre_restore_check do @db = init(new_resource) @db.pre_restore_sanity_check end action :post_restore_cleanup do @db = init(new_resource) @db.restore_snapshot # @db.post_restore_sanity_check end action :pre_backup_check do @db = init(new_resource) @db.pre_backup_check end action :post_backup_cleanup do @db = init(new_resource) @db.post_backup_steps end action :set_privileges do priv = new_resource.privilege priv_username = new_resource.privilege_username priv_password = new_resource.privilege_password priv_database = new_resource.privilege_database db_postgres_set_privileges "setup db privileges" do preset priv username priv_username password priv_password database priv_database end end action :install_client do # Install PostgreSQL 9.1.1 package(s) if node[:platform] == "centos" arch = node[:kernel][:machine] arch = "x86_64" if arch == "i386" # Install PostgreSQL GPG Key (http://yum.postgresql.org/9.1/redhat/rhel-5-(arch)/pgdg-centos91-9.1-4.noarch.rpm) package "libxslt" do action :install end packages = ["postgresql91-libs", "postgresql91", "postgresql91-devel" ] Chef::Log.info("Packages to install: #{packages.join(",")}") packages.each do |p| pkg = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "#{p}-9.1.1-1PGDG.rhel5.#{arch}.rpm") package p do action :install source "#{pkg}" provider Chef::Provider::Package::Rpm end end else # Currently supports CentOS in future will support others end # == Install PostgreSQL client gem # # Also installs in compile phase gem_package("pg") do gem_binary("/opt/rightscale/sandbox/bin/gem") options("-- --with-pg-config=/usr/pgsql-9.1/bin/pg_config") end end action :install_server do # PostgreSQL server depends on PostgreSQL client action_install_client arch = node[:kernel][:machine] arch = "x86_64" if arch == "i386" package "uuid" do action :install end node[:db_postgres][:packages_install].each do |p| pkg = ::File.join(::File.dirname(__FILE__), "..", "files", "centos", "#{p}-9.1.1-1PGDG.rhel5.#{arch}.rpm") package p do action :install source "#{pkg}" provider Chef::Provider::Package::Rpm end end service "postgresql-9.1" do #service_name value_for_platform([ "centos", "redhat", "suse" ] => {"default" => "postgresql-9.1"}, "default" => "postgresql-9.1") supports :status => true, :restart => true, :reload => true action :stop end # Initialize PostgreSQL server and create system tables touchfile = ::File.expand_path "~/.postgresql_installed" execute "/etc/init.d/postgresql-9.1 initdb" do creates touchfile end # == Configure system for PostgreSQL # # Stop PostgreSQL service "postgresql-9.1" do supports :status => true, :restart => true, :reload => true action :stop end # Create the Socket directory # directory "/var/run/postgresql" do directory "#{node[:db_postgres][:socket]}" do owner "postgres" group "postgres" mode 0770 recursive true end # Setup postgresql.conf # template_source = "postgresql.conf.erb" template value_for_platform([ "centos", "redhat", "suse" ] => {"default" => "#{node[:db_postgres][:confdir]}/postgresql.conf"}, "default" => "#{node[:db_postgres][:confdir]}/postgresql.conf") do source "postgresql.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end # Setup pg_hba.conf # pg_hba_source = "pg_hba.conf.erb" template value_for_platform([ "centos", "redhat", "suse" ] => {"default" => "#{node[:db_postgres][:confdir]}/pg_hba.conf"}, "default" => "#{node[:db_postgres][:confdir]}/pg_hba.conf") do source "pg_hba.conf.erb" owner "postgres" group "postgres" mode "0644" cookbook 'db_postgres' end # == Setup PostgreSQL user limits # # Set the postgres and root users max open files to a really large number. # 1/3 of the overall system file max should be large enough. The percentage can be # adjusted if necessary. # postgres_file_ulimit = `sysctl -n fs.file-max`.to_i/33 template "/etc/security/limits.d/postgres.limits.conf" do source "postgres.limits.conf.erb" variables({ :ulimit => postgres_file_ulimit }) cookbook 'db_postgres' end # Change root's limitations for THIS shell. The entry in the limits.d will be # used for future logins. # The setting needs to be in place before postgresql-9 is started. # execute "ulimit -n #{postgres_file_ulimit}" # == Start PostgreSQL # service "postgresql-9.1" do # supports :status => true, :restart => true, :reload => true action :start end end action :grant_replication_slave do require 'rubygems' Gem.clear_paths require 'pg' Chef::Log.info "GRANT REPLICATION SLAVE to user #{node[:db][:replication][:user]}" # Opening connection for pg operation conn = PGconn.open("localhost", nil, nil, nil, nil, "postgres", nil) # Enable admin/replication user # Check if server is in read_only mode, if found skip this... res = conn.exec("show transaction_read_only") slavestatus = res.getvalue(0,0) if ( slavestatus == 'off' ) Chef::Log.info "Detected Master server." result = conn.exec("SELECT COUNT(*) FROM pg_user WHERE usename='#{node[:db][:replication][:user]}'") userstat = result.getvalue(0,0) if ( userstat == '1' ) Chef::Log.info "User #{node[:db][:replication][:user]} already exists, updating user using current inputs" conn.exec("ALTER USER #{node[:db][:replication][:user]} SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN ENCRYPTED PASSWORD '#{node[:db][:replication][:password]}'") else Chef::Log.info "creating replication user #{node[:db][:replication][:user]}" conn.exec("CREATE USER #{node[:db][:replication][:user]} SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN ENCRYPTED PASSWORD '#{node[:db][:replication][:password]}'") # Setup pg_hba.conf for replication user allow RightScale::Database::PostgreSQL::Helper.configure_pg_hba(node) # Reload postgresql to read new updated pg_hba.conf RightScale::Database::PostgreSQL::Helper.do_query('select pg_reload_conf()') end else Chef::Log.info "Skipping 'create replication user', Detected read_only db or slave mode" end conn.finish end action :enable_replication do newmaster_host = node[:db][:current_master_ip] rep_user = node[:db][:replication][:user] rep_pass = node[:db][:replication][:password] app_name = node[:rightscale][:instance_uuid] master_info = RightScale::Database::PostgreSQL::Helper.load_replication_info(node) # == Set slave state # log "Setting up slave state..." ruby_block "set slave state" do block do node[:db][:this_is_master] = false end end # Stopping postgresql action_stop # Sync to Master data RightScale::Database::PostgreSQL::Helper.rsync_db(newmaster_host, rep_user) # Setup recovery conf RightScale::Database::PostgreSQL::Helper.reconfigure_replication_info(newmaster_host, rep_user, rep_pass, app_name) # Removing existing_runtime_log_files Chef::Log.info "Removing existing runtime log files" `rm -rf "#{node[:db][:datadir]}/pg_xlog/*"` # @db.ensure_db_started # service provider uses the status command to decide if it # has to run the start command again. 5.times do action_start end ruby_block "validate_backup" do block do master_info = RightScale::Database::PostgreSQL::Helper.load_replication_info(node) raise "Position and file not saved!" unless master_info['Master_instance_uuid'] # Check that the snapshot is from the current master or a slave associated with the current master if master_info['Master_instance_uuid'] != node[:db][:current_master_uuid] raise "FATAL: snapshot was taken from a different master! snap_master was:#{master_info['Master_instance_uuid']} != current master: #{node[:db][:current_master_uuid]}" end end end end action :promote do previous_master = node[:db][:current_master_ip] raise "FATAL: could not determine master host from slave status" if previous_master.nil? Chef::Log.info "host: #{previous_master}}" # PHASE1: contains non-critical old master operations, if a timeout or # error occurs we continue promotion assuming the old master is dead. begin # Critical operations on newmaster, if a failure occurs here we allow it to halt promote operations # <Ravi - Do your stuff here> # Promote the slave into the new master Chef::Log.info "Promoting slave.." RightScale::Database::PostgreSQL::Helper.write_trigger(node) sleep 10 # Let the new slave loose and thus let him become the new master Chef::Log.info "New master is ReadWrite." rescue => e Chef::Log.info "WARNING: caught exception #{e} during critical operations on the MASTER" end end action :setup_monitoring do service "collectd" do action :nothing end arch = node[:kernel][:machine] arch = "i386" if arch == "i686" if node[:platform] == 'centos' TMP_FILE = "/tmp/collectd.rpm" remote_file TMP_FILE do source "collectd-postgresql-4.10.0-4.el5.#{arch}.rpm" cookbook 'db_postgres' end package TMP_FILE do source TMP_FILE end template ::File.join(node[:rs_utils][:collectd_plugin_dir], 'postgresql.conf') do backup false source "postgresql_collectd_plugin.conf.erb" notifies :restart, resources(:service => "collectd") cookbook 'db_postgres' end # install the postgres_ps collectd script into the collectd library plugins directory remote_file ::File.join(node[:rs_utils][:collectd_lib], "plugins", 'postgres_ps') do source "postgres_ps" mode "0755" cookbook 'db_postgres' end # add a collectd config file for the postgres_ps script with the exec plugin and restart collectd if necessary template ::File.join(node[:rs_utils][:collectd_plugin_dir], 'postgres_ps.conf') do source "postgres_collectd_exec.erb" notifies :restart, resources(:service => "collectd") cookbook 'db_postgres' end else log "WARNING: attempting to install collectd-postgresql on unsupported platform #{node[:platform]}, continuing.." do level :warn end end end action :generate_dump_file do db_name = new_resource.db_name dumpfile = new_resource.dumpfile bash "Write the postgres DB backup file" do user 'postgres' code <<-EOH pg_dump -h /var/run/postgresql #{db_name} | gzip -c > #{dumpfile} EOH end end action :restore_from_dump_file do db_name = new_resource.db_name dumpfile = new_resource.dumpfile log " Check if DB already exists" ruby_block "checking existing db" do block do db_check = `echo "select datname from pg_database" | psql -U postgres -h /var/run/postgresql | grep -q "#{db_name}"` if ! db_check.empty? raise "ERROR: database '#{db_name}' already exists" end end end bash "Import PostgreSQL dump file: #{dumpfile}" do user "postgres" code <<-EOH set -e if [ ! -f #{dumpfile} ] then echo "ERROR: PostgreSQL dumpfile not found! File: '#{dumpfile}'" exit 1 fi createdb -U postgres -h /var/run/postgresql #{db_name} gunzip < #{dumpfile} | psql -U postgres -h /var/run/postgresql #{db_name} EOH end end
default[:prometheus][:addresses] = {} default[:prometheus][:exporters] = {} default[:prometheus][:snmp] = {} default[:prometheus][:metrics] = {} default[:prometheus][:files] = [] default[:prometheus][:promscale] = false if node[:recipes].include?("prometheus::server") default[:apt][:sources] |= ["grafana"] end Enable promscale default[:prometheus][:addresses] = {} default[:prometheus][:exporters] = {} default[:prometheus][:snmp] = {} default[:prometheus][:metrics] = {} default[:prometheus][:files] = [] default[:prometheus][:promscale] = true if node[:recipes].include?("prometheus::server") default[:apt][:sources] |= ["grafana"] end
# Cookbook Name:: travis_groovy # Recipe:: default # # Copyright 2015, Travis CI GmbH ark 'groovy' do url node['travis_groovy']['url'] version node['travis_groovy']['version'] checksum node['travis_groovy']['checksum'] path node['travis_groovy']['installation_dir'] owner 'root' end Ensuring groovy executables are symlinked to /usr/local/bin # Cookbook Name:: travis_groovy # Recipe:: default # # Copyright 2015, Travis CI GmbH ark 'groovy' do url node['travis_groovy']['url'] version node['travis_groovy']['version'] checksum node['travis_groovy']['checksum'] path node['travis_groovy']['installation_dir'] has_binaries %w( grape groovy groovyc groovyConsole groovydoc groovysh java2groovy startGroovy ).map { |exe| "bin/#{exe}" } owner 'root' end
default['travis_php']['multi']['packages'] = %w( bison libbison-dev libreadline6-dev ) default['travis_php']['multi']['prerequisite_recipes'] = %w( travis_phpenv travis_phpbuild ) default['travis_php']['multi']['postrequisite_recipes'] = %w( travis_php::extensions travis_php::hhvm travis_php::hhvm-nightly phpunit composer ) default['travis_php']['multi']['versions'] = %w( 5.4.45 5.5.30 5.6.15 ) default['travis_php']['multi']['aliases'] = { '5.4' => '5.4.45', '5.5' => '5.5.30', '5.6' => '5.6.15' } default['travis_php']['multi']['extensions'] = { 'apc' => { 'versions' => default['travis_php']['multi']['versions'].select { |version| version.start_with?('5.4') } }, 'memcached' => { 'before_packages' => %w(libevent-dev libcloog-ppl1), 'before_script' => <<-EOF, wget https://launchpad.net/libmemcached/1.0/1.0.18/+download/libmemcached-1.0.18.tar.gz tar xzf libmemcached-1.0.18.tar.gz cd libmemcached-1.0.18 ./configure && make && make install EOF 'script' => <<-EOF, pecl download memcached-2.2.0 tar zxvf memcached*.tgz && cd memcached* make clean phpize ./configure --with-libmemcached-dir=/usr/local && make && make install EOF 'versions' => default['travis_php']['multi']['versions'] }, 'mongo' => {}, 'amqp' => { 'before_script' => <<-EOF git clone git://github.com/alanxz/rabbitmq-c.git cd rabbitmq-c git checkout tags/v0.5.2 git submodule init git submodule update autoreconf -i && ./configure && make && make install EOF }, 'zmq-beta' => { 'versions' => default['travis_php']['multi']['versions'], 'before_recipes' => %w(zeromq::ppa), 'before_packages' => %w(libzmq3-dev) }, 'redis' => {} } Ensure freetype2 is installed default['travis_php']['multi']['packages'] = %w( bison libbison-dev libfreetype6-dev libreadline6-dev ) default['travis_php']['multi']['prerequisite_recipes'] = %w( travis_phpenv travis_phpbuild ) default['travis_php']['multi']['postrequisite_recipes'] = %w( travis_php::extensions travis_php::hhvm travis_php::hhvm-nightly phpunit composer ) default['travis_php']['multi']['versions'] = %w( 5.4.45 5.5.30 5.6.15 ) default['travis_php']['multi']['aliases'] = { '5.4' => '5.4.45', '5.5' => '5.5.30', '5.6' => '5.6.15' } default['travis_php']['multi']['extensions'] = { 'apc' => { 'versions' => default['travis_php']['multi']['versions'].select { |version| version.start_with?('5.4') } }, 'memcached' => { 'before_packages' => %w(libevent-dev libcloog-ppl1), 'before_script' => <<-EOF, wget https://launchpad.net/libmemcached/1.0/1.0.18/+download/libmemcached-1.0.18.tar.gz tar xzf libmemcached-1.0.18.tar.gz cd libmemcached-1.0.18 ./configure && make && make install EOF 'script' => <<-EOF, pecl download memcached-2.2.0 tar zxvf memcached*.tgz && cd memcached* make clean phpize ./configure --with-libmemcached-dir=/usr/local && make && make install EOF 'versions' => default['travis_php']['multi']['versions'] }, 'mongo' => {}, 'amqp' => { 'before_script' => <<-EOF git clone git://github.com/alanxz/rabbitmq-c.git cd rabbitmq-c git checkout tags/v0.5.2 git submodule init git submodule update autoreconf -i && ./configure && make && make install EOF }, 'zmq-beta' => { 'versions' => default['travis_php']['multi']['versions'], 'before_recipes' => %w(zeromq::ppa), 'before_packages' => %w(libzmq3-dev) }, 'redis' => {} }
name "wt_portfolio_harness" maintainer "Webtrends, Inc." maintainer_email "michael.parsons@webtrends.com" license "All rights reserved" description "Installs/Configures Webtrends Portfolio Edge Service" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "1.0.2" depends "java" depends "runit" changing version Former-commit-id: 127b6e7e5b93afb0acc2836dfef6901f4b132883 [formerly 892b8365e4f4eff3afb5f84d436def9debc79751] [formerly 9bf4821008bf0c852f6350e14531cf9c75b42784 [formerly 79dbd904446154f07e3bb2557362702fb4011def [formerly ac78f948321ba843b951f6046ffda4798aab9846]]] Former-commit-id: 21cac8c3df4338c7d145ee95f953f2b01a639859 [formerly c6aaf942da3d55531d9d10020ea68ddec4c21cad] Former-commit-id: 836179d6e6193d5a3be9b0628122433dc94f7f4a Former-commit-id: 305eb0130f877b6596cfd4ac8b05aca94001737f name "wt_portfolio_harness" maintainer "Webtrends, Inc." maintainer_email "michael.parsons@webtrends.com" license "All rights reserved" description "Installs/Configures Webtrends Portfolio Edge Service" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "1.0.0" depends "java" depends "runit"
# # Cookbook Name:: wt_publishver # Provider:: linux # Author:: David Dvorak(<david.dvorakd@webtrends.com>) # # Copyright 2013, Webtrends Inc. # # All rights reserved - Do Not Redistribute # action :deploy_prereqs do # working directories wdir = ::File.join(Chef::Config[:file_cache_path], 'wt_publishver') gdir = ::File.join(wdir, 'gems') idir = ::File.join(wdir, 'include') ldir = ::File.join(wdir, 'lib') ENV['GEM_HOME'] = gdir remote_directory wdir do source 'prereqs' overwrite true action :nothing end.run_action :create gem_package 'nokogiri' do gem_binary 'gem' source ::File.join(wdir, 'nokogiri-1.5.6.gem') options "--install-dir #{gdir} -- --with-xml2-lib=#{ldir} --with-xml2-include=#{idir}/libxml2 --with-xslt-lib=#{ldir} --with-xslt-include=#{idir} --with-dldflags='-Wl,-rpath,#{ldir}'" action :nothing end.run_action :install gem_list = ['little-plugger-1.1.3', 'multi_json-1.5.0', 'logging-1.6.1', 'httpclient-2.2.4', 'rubyntlm-0.1.2', 'viewpoint-spws-0.5.0.wt', 'manifest-1.0.0'] gem_list.each do |gem| gem_package gem[/^(.*)-[\d\.wt]+?/, 1] do gem_binary 'gem' source ::File.join(wdir, "#{gem}.gem") options "--install-dir #{gdir} --ignore-dependencies" action :nothing end.run_action :install end ::Gem.clear_paths require 'viewpoint/spws' require 'manifest' end action :update do Chef::Log.debug("Running #{@new_resource.name} in #{@new_resource.provider} from #{@new_resource.cookbook_name}::#{@new_resource.recipe_name}") unless ::File.exists? @new_resource.key_file log("key_file: #{@new_resource.key_file} not found") { level :warn } next end # gets teamcity data pub = ::WtPublishver::Publisher.new @new_resource.download_url # set values for sp_query pub.hostname = node['hostname'] pub.pod = node.chef_environment pub.role = @new_resource.role pub.selectver = @new_resource.select_version # query sharepoint items = pub.sp_query if items.count == 0 log("No records found: hostname => #{pub.hostname}, pod => #{pub.pod}, role => #{pub.role}") { level :warn } log('No publish version update performed') { level :warn } return end if items.count > 1 log("More than 1 record found for: hostname => #{pub.hostname}, pod => #{pub.pod}, role => #{pub.role}") { level :warn } log('Please refine criteria. No publish version update performed') { level :warn } return end pub.oitem = ::WtPublishver::PublisherItem.new items.first pub.nitem = ::WtPublishver::PublisherItem.new items.first # # get new data to publish # # version (should start with a digit) pub.nitem.version = ENV['wtver'] if ENV['wtver'] =~ /^\d/ # branch if pub.is_tc? pub.nitem.branch = "#{pub.project_name}_#{pub.buildtype_name}".gsub(/ /, '_') else pub.nitem.branch = pub.download_server end # build number (should be derived from key_file and not TC) case @new_resource.key_file when /\.jar$/ pub.nitem.build = pub.jar_build @new_resource.key_file else log('key_file type not supported') { level :warn } pub.nitem.build = pub.build_number.to_s end # set status case @new_resource.status when :up pub.nitem.status = 'Up' when :down pub.nitem.status = 'Down' when :pending pub.nitem.status = 'Pending' when :unknown pub.nitem.status = 'Unknown' end if pub.changed? puts "\nPod Details: BEFORE\n" puts pub.oitem.formatted pub.sp_update puts "\nPod Details: AFTER\n" puts ( ::WtPublishver::PublisherItem.new pub.sp_query.first ).formatted puts "\n" else log 'Pod Detail field values are the same. No update performed.' end end enable wildcard support for key_file Former-commit-id: c2fedd4ef448da7a210f9efae41fbb875a20591d [formerly 54bb7901301d06db17b9f78ea063445a06a5e865] [formerly 5726b798eb24b25c2caf67ce30c7fe9338c151ac [formerly 9400a2a5443ec3ebd3a29e45f460f54475660dd9 [formerly 2ef2cccbb49f899cbbc70c11ac2712f87d734752]]] Former-commit-id: 029eac9b15946a17790ffdc1cfe51676ef315f2f [formerly b10447a6d88dca5e32ea6748104f825328f6d33e] Former-commit-id: 28a89469af1ef6badb37f66fc821715b1b49e8c7 Former-commit-id: 856e9a6e18f1f524f0d346690a8c1dd77e862ba5 # # Cookbook Name:: wt_publishver # Provider:: linux # Author:: David Dvorak(<david.dvorakd@webtrends.com>) # # Copyright 2013, Webtrends Inc. # # All rights reserved - Do Not Redistribute # action :deploy_prereqs do # working directories wdir = ::File.join(Chef::Config[:file_cache_path], 'wt_publishver') gdir = ::File.join(wdir, 'gems') idir = ::File.join(wdir, 'include') ldir = ::File.join(wdir, 'lib') ENV['GEM_HOME'] = gdir remote_directory wdir do source 'prereqs' overwrite true action :nothing end.run_action :create gem_package 'nokogiri' do gem_binary 'gem' source ::File.join(wdir, 'nokogiri-1.5.6.gem') options "--install-dir #{gdir} -- --with-xml2-lib=#{ldir} --with-xml2-include=#{idir}/libxml2 --with-xslt-lib=#{ldir} --with-xslt-include=#{idir} --with-dldflags='-Wl,-rpath,#{ldir}'" action :nothing end.run_action :install gem_list = ['little-plugger-1.1.3', 'multi_json-1.5.0', 'logging-1.6.1', 'httpclient-2.2.4', 'rubyntlm-0.1.2', 'viewpoint-spws-0.5.0.wt', 'manifest-1.0.0'] gem_list.each do |gem| gem_package gem[/^(.*)-[\d\.wt]+?/, 1] do gem_binary 'gem' source ::File.join(wdir, "#{gem}.gem") options "--install-dir #{gdir} --ignore-dependencies" action :nothing end.run_action :install end ::Gem.clear_paths require 'viewpoint/spws' require 'manifest' end action :update do Chef::Log.debug("Running #{@new_resource.name} in #{@new_resource.provider} from #{@new_resource.cookbook_name}::#{@new_resource.recipe_name}") # expand wildcards key_file = Dir[@new_resource.key_file].sort.first if key_file.nil? log("key_file: #{@new_resource.key_file} not found") { level :warn } next end # gets teamcity data pub = ::WtPublishver::Publisher.new @new_resource.download_url # set values for sp_query pub.hostname = node['hostname'] pub.pod = node.chef_environment pub.role = @new_resource.role pub.selectver = @new_resource.select_version # query sharepoint items = pub.sp_query if items.count == 0 log("No records found: hostname => #{pub.hostname}, pod => #{pub.pod}, role => #{pub.role}") { level :warn } log('No publish version update performed') { level :warn } next end if items.count > 1 log("More than 1 record found for: hostname => #{pub.hostname}, pod => #{pub.pod}, role => #{pub.role}") { level :warn } log('Please refine criteria. No publish version update performed') { level :warn } next end pub.oitem = ::WtPublishver::PublisherItem.new items.first pub.nitem = ::WtPublishver::PublisherItem.new items.first # # get new data to publish # # version (should start with a digit) pub.nitem.version = ENV['wtver'] if ENV['wtver'] =~ /^\d/ # branch if pub.is_tc? pub.nitem.branch = "#{pub.project_name}_#{pub.buildtype_name}".gsub(/ /, '_') else pub.nitem.branch = pub.download_server end # build number (should be derived from key_file and not TC) case key_file when /\.jar$/ pub.nitem.build = pub.jar_build key_file else log('key_file type not supported') { level :warn } pub.nitem.build = pub.build_number.to_s end # set status case @new_resource.status when :up pub.nitem.status = 'Up' when :down pub.nitem.status = 'Down' when :pending pub.nitem.status = 'Pending' when :unknown pub.nitem.status = 'Unknown' end if pub.changed? puts "\nPod Details: BEFORE\n" puts pub.oitem.formatted pub.sp_update puts "\nPod Details: AFTER\n" puts ( ::WtPublishver::PublisherItem.new pub.sp_query.first ).formatted puts "\n" else log 'Pod Detail field values are the same. No update performed.' end end
Pod::Spec.new do |spec| spec.name = 'ZRTusKit' spec.version = '0.0.1' spec.license = { :type => 'MIT' } spec.homepage = 'https://github.com/itszero/ZRTusKit' spec.authors = { 'Zero Cho' => 'itszero@gmail.com' } spec.summary = 'Work-in-progress. Tus 1.0 protocol implementation.' spec.source = { :git => 'https://github.com/itszeor/ZRTusKit.git', :tag => spec.version } spec.source_files = 'ZRTusKit/*.swift' spec.ios.deployment_target = '8.0' spec.osx.deployment_target = '10.10' spec.dependency 'BrightFutures', '~> 1.0-beta' spec.dependency 'ReactKit', '~> 0.9' end remove unused ReactKit Pod::Spec.new do |spec| spec.name = 'ZRTusKit' spec.version = '0.0.1' spec.license = { :type => 'MIT' } spec.homepage = 'https://github.com/itszero/ZRTusKit' spec.authors = { 'Zero Cho' => 'itszero@gmail.com' } spec.summary = 'Work-in-progress. Tus 1.0 protocol implementation.' spec.source = { :git => 'https://github.com/itszeor/ZRTusKit.git', :tag => spec.version } spec.source_files = 'ZRTusKit/*.swift' spec.ios.deployment_target = '8.0' spec.osx.deployment_target = '10.10' spec.dependency 'BrightFutures', '~> 1.0-beta' end
require File.expand_path('../../spec_helper', __FILE__) # Language-level method behaviour describe "Redefining a method" do it "replaces the original method" do def barfoo; 100; end barfoo.should == 100 def barfoo; 200; end barfoo.should == 200 end end describe "Defining an 'initialize' method" do it "sets the method's visibility to private" do class DefInitializeSpec def initialize end end DefInitializeSpec.should have_private_instance_method(:initialize, false) end end describe "Defining an 'initialize_copy' method" do it "sets the method's visibility to private" do class DefInitializeCopySpec def initialize_copy end end DefInitializeCopySpec.should have_private_instance_method(:initialize_copy, false) end end describe "An instance method definition with a splat" do it "accepts an unnamed '*' argument" do def foo(*); end; foo.should == nil foo(1, 2).should == nil foo(1, 2, 3, 4, :a, :b, 'c', 'd').should == nil end it "accepts a named * argument" do def foo(*a); a; end; foo.should == [] foo(1, 2).should == [1, 2] foo([:a]).should == [[:a]] end it "accepts non-* arguments before the * argument" do def foo(a, b, c, d, e, *f); [a, b, c, d, e, f]; end foo(1, 2, 3, 4, 5, 6, 7, 8).should == [1, 2, 3, 4, 5, [6, 7, 8]] end it "allows only a single * argument" do lambda { eval 'def foo(a, *b, *c); end' }.should raise_error(SyntaxError) end it "requires the presence of any arguments that precede the *" do def foo(a, b, *c); end lambda { foo 1 }.should raise_error(ArgumentError) end end describe "An instance method with a default argument" do it "evaluates the default when no arguments are passed" do def foo(a = 1) a end foo.should == 1 foo(2).should == 2 end it "evaluates the default empty expression when no arguments are passed" do def foo(a = ()) a end foo.should == nil foo(2).should == 2 end it "assigns an empty Array to an unused splat argument" do def foo(a = 1, *b) [a,b] end foo.should == [1, []] foo(2).should == [2, []] end it "evaluates the default when required arguments precede it" do def foo(a, b = 2) [a,b] end lambda { foo }.should raise_error(ArgumentError) foo(1).should == [1, 2] end it "prefers to assign to a default argument before a splat argument" do def foo(a, b = 2, *c) [a,b,c] end lambda { foo }.should raise_error(ArgumentError) foo(1).should == [1,2,[]] end it "prefers to assign to a default argument when there are no required arguments" do def foo(a = 1, *args) [a,args] end foo(2,2).should == [2,[2]] end it "does not evaluate the default when passed a value and a * argument" do def foo(a, b = 2, *args) [a,b,args] end foo(2,3,3).should == [2,3,[3]] end end describe "A singleton method definition" do after :all do Object.__send__(:remove_class_variable, :@@a) end it "can be declared for a local variable" do a = "hi" def a.foo 5 end a.foo.should == 5 end it "can be declared for an instance variable" do @a = "hi" def @a.foo 6 end @a.foo.should == 6 end it "can be declared for a global variable" do $__a__ = "hi" def $__a__.foo 7 end $__a__.foo.should == 7 end it "can be declared for a class variable" do @@a = "hi" def @@a.foo 8 end @@a.foo.should == 8 end it "can be declared with an empty method body" do class DefSpec def self.foo;end end DefSpec.foo.should == nil end it "can be redefined" do obj = Object.new def obj.==(other) 1 end (obj==1).should == 1 def obj.==(other) 2 end (obj==2).should == 2 end ruby_version_is ""..."1.9" do it "raises TypeError if frozen" do obj = Object.new obj.freeze lambda { def obj.foo; end }.should raise_error(TypeError) end end ruby_version_is "1.9" do it "raises RuntimeError if frozen" do obj = Object.new obj.freeze lambda { def obj.foo; end }.should raise_error(RuntimeError) end end end describe "Redefining a singleton method" do it "does not inherit a previously set visibility " do o = Object.new class << o; private; def foo; end; end; class << o; should have_private_instance_method(:foo); end class << o; def foo; end; end; class << o; should_not have_private_instance_method(:foo); end class << o; should have_instance_method(:foo); end end end describe "Redefining a singleton method" do it "does not inherit a previously set visibility " do o = Object.new class << o; private; def foo; end; end; class << o; should have_private_instance_method(:foo); end class << o; def foo; end; end; class << o; should_not have_private_instance_method(:foo); end class << o; should have_instance_method(:foo); end end end describe "A method defined with extreme default arguments" do it "can redefine itself when the default is evaluated" do class DefSpecs def foo(x = (def foo; "hello"; end;1));x;end end d = DefSpecs.new d.foo(42).should == 42 d.foo.should == 1 d.foo.should == 'hello' end it "may use an fcall as a default" do def foo(x = caller()) x end foo.shift.should be_kind_of(String) end it "evaluates the defaults in the method's scope" do def foo(x = ($foo_self = self; nil)); end foo $foo_self.should == self end it "may use preceding arguments as defaults" do def foo(obj, width=obj.length) width end foo('abcde').should == 5 end it "may use a lambda as a default" do def foo(output = 'a', prc = lambda {|n| output * n}) prc.call(5) end foo.should == 'aaaaa' end end describe "A singleton method defined with extreme default arguments" do it "may use a method definition as a default" do $__a = "hi" def $__a.foo(x = (def $__a.foo; "hello"; end;1));x;end $__a.foo(42).should == 42 $__a.foo.should == 1 $__a.foo.should == 'hello' end it "may use an fcall as a default" do a = "hi" def a.foo(x = caller()) x end a.foo.shift.should be_kind_of(String) end it "evaluates the defaults in the singleton scope" do a = "hi" def a.foo(x = ($foo_self = self; nil)); 5 ;end a.foo $foo_self.should == a end it "may use preceding arguments as defaults" do a = 'hi' def a.foo(obj, width=obj.length) width end a.foo('abcde').should == 5 end it "may use a lambda as a default" do a = 'hi' def a.foo(output = 'a', prc = lambda {|n| output * n}) prc.call(5) end a.foo.should == 'aaaaa' end end describe "A method definition inside a metaclass scope" do it "can create a class method" do class DefSpecSingleton class << self def a_class_method;self;end end end DefSpecSingleton.a_class_method.should == DefSpecSingleton lambda { Object.a_class_method }.should raise_error(NoMethodError) end it "can create a singleton method" do obj = Object.new class << obj def a_singleton_method;self;end end obj.a_singleton_method.should == obj lambda { Object.new.a_singleton_method }.should raise_error(NoMethodError) end ruby_version_is ""..."1.9" do it "raises TypeError if frozen" do obj = Object.new obj.freeze class << obj lambda { def foo; end }.should raise_error(TypeError) end end end ruby_version_is "1.9" do it "raises RuntimeError if frozen" do obj = Object.new obj.freeze class << obj lambda { def foo; end }.should raise_error(RuntimeError) end end end end describe "A nested method definition" do it "creates an instance method when evaluated in an instance method" do class DefSpecNested def create_instance_method def an_instance_method;self;end an_instance_method end end obj = DefSpecNested.new obj.create_instance_method.should == obj obj.an_instance_method.should == obj other = DefSpecNested.new other.an_instance_method.should == other DefSpecNested.should have_instance_method(:an_instance_method) end it "creates a class method when evaluated in a class method" do class DefSpecNested class << self def create_class_method def a_class_method;self;end a_class_method end end end lambda { DefSpecNested.a_class_method }.should raise_error(NoMethodError) DefSpecNested.create_class_method.should == DefSpecNested DefSpecNested.a_class_method.should == DefSpecNested lambda { Object.a_class_method }.should raise_error(NoMethodError) lambda { DefSpecNested.new.a_class_method }.should raise_error(NoMethodError) end it "creates a singleton method when evaluated in the metaclass of an instance" do class DefSpecNested def create_singleton_method class << self def a_singleton_method;self;end end a_singleton_method end end obj = DefSpecNested.new obj.create_singleton_method.should == obj obj.a_singleton_method.should == obj other = DefSpecNested.new lambda { other.a_singleton_method }.should raise_error(NoMethodError) end end describe "A method definition inside an instance_eval" do it "creates a singleton method" do obj = Object.new obj.instance_eval do def an_instance_eval_method;self;end end obj.an_instance_eval_method.should == obj other = Object.new lambda { other.an_instance_eval_method }.should raise_error(NoMethodError) end it "creates a singleton method when evaluated inside a metaclass" do obj = Object.new obj.instance_eval do class << self def a_metaclass_eval_method;self;end end end obj.a_metaclass_eval_method.should == obj other = Object.new lambda { other.a_metaclass_eval_method }.should raise_error(NoMethodError) end it "creates a class method when the receiver is a class" do DefSpecNested.instance_eval do def an_instance_eval_class_method;self;end end DefSpecNested.an_instance_eval_class_method.should == DefSpecNested lambda { Object.an_instance_eval_class_method }.should raise_error(NoMethodError) end end describe "A method definition in an eval" do it "creates an instance method" do class DefSpecNested def eval_instance_method eval "def an_eval_instance_method;self;end", binding an_eval_instance_method end end obj = DefSpecNested.new obj.eval_instance_method.should == obj obj.an_eval_instance_method.should == obj other = DefSpecNested.new other.an_eval_instance_method.should == other lambda { Object.new.an_eval_instance_method }.should raise_error(NoMethodError) end it "creates a class method" do class DefSpecNestedB class << self def eval_class_method eval "def an_eval_class_method;self;end" #, binding an_eval_class_method end end end DefSpecNestedB.eval_class_method.should == DefSpecNestedB DefSpecNestedB.an_eval_class_method.should == DefSpecNestedB lambda { Object.an_eval_class_method }.should raise_error(NoMethodError) lambda { DefSpecNestedB.new.an_eval_class_method}.should raise_error(NoMethodError) end it "creates a singleton method" do class DefSpecNested def eval_singleton_method class << self eval "def an_eval_singleton_method;self;end", binding end an_eval_singleton_method end end obj = DefSpecNested.new obj.eval_singleton_method.should == obj obj.an_eval_singleton_method.should == obj other = DefSpecNested.new lambda { other.an_eval_singleton_method }.should raise_error(NoMethodError) end end describe "a method definition that sets more than one default parameter all to the same value" do def foo(a=b=c={}) [a,b,c] end it "assigns them all the same object by default" do foo.should == [{},{},{}] a, b, c = foo a.should eql(b) a.should eql(c) end it "allows the first argument to be given, and sets the rest to null" do foo(1).should == [1,nil,nil] end it "assigns the parameters different objects across different default calls" do a, b, c = foo d, e, f = foo a.should_not equal(d) end it "only allows overriding the default value of the first such parameter in each set" do lambda { foo(1,2) }.should raise_error(ArgumentError) end def bar(a=b=c=1,d=2) [a,b,c,d] end it "treats the argument after the multi-parameter normally" do bar.should == [1,1,1,2] bar(3).should == [3,nil,nil,2] bar(3,4).should == [3,nil,nil,4] lambda { bar(3,4,5) }.should raise_error(ArgumentError) end end describe "The def keyword" do describe "within a closure" do it "looks outside the closure for the visibility" do module DefSpecsLambdaVisibility private lambda { def some_method; end }.call end DefSpecsLambdaVisibility.should have_private_instance_method("some_method") end end end language_version __FILE__, "def" ruby_version_is "2.0" do require File.expand_path('../versions/def_2.0.rb', __FILE__) end Add a spec for defining `initialize_dup` from 2.0 require File.expand_path('../../spec_helper', __FILE__) # Language-level method behaviour describe "Redefining a method" do it "replaces the original method" do def barfoo; 100; end barfoo.should == 100 def barfoo; 200; end barfoo.should == 200 end end describe "Defining an 'initialize' method" do it "sets the method's visibility to private" do class DefInitializeSpec def initialize end end DefInitializeSpec.should have_private_instance_method(:initialize, false) end end describe "Defining an 'initialize_copy' method" do it "sets the method's visibility to private" do class DefInitializeCopySpec def initialize_copy end end DefInitializeCopySpec.should have_private_instance_method(:initialize_copy, false) end end ruby_version_is "2.0" do describe "Defining an 'initialize_dup' method" do it "sets the method's visibility to private" do class DefInitializeDupSpec def initialize_dup end end DefInitializeDupSpec.should have_private_instance_method(:initialize_dup, false) end end end describe "An instance method definition with a splat" do it "accepts an unnamed '*' argument" do def foo(*); end; foo.should == nil foo(1, 2).should == nil foo(1, 2, 3, 4, :a, :b, 'c', 'd').should == nil end it "accepts a named * argument" do def foo(*a); a; end; foo.should == [] foo(1, 2).should == [1, 2] foo([:a]).should == [[:a]] end it "accepts non-* arguments before the * argument" do def foo(a, b, c, d, e, *f); [a, b, c, d, e, f]; end foo(1, 2, 3, 4, 5, 6, 7, 8).should == [1, 2, 3, 4, 5, [6, 7, 8]] end it "allows only a single * argument" do lambda { eval 'def foo(a, *b, *c); end' }.should raise_error(SyntaxError) end it "requires the presence of any arguments that precede the *" do def foo(a, b, *c); end lambda { foo 1 }.should raise_error(ArgumentError) end end describe "An instance method with a default argument" do it "evaluates the default when no arguments are passed" do def foo(a = 1) a end foo.should == 1 foo(2).should == 2 end it "evaluates the default empty expression when no arguments are passed" do def foo(a = ()) a end foo.should == nil foo(2).should == 2 end it "assigns an empty Array to an unused splat argument" do def foo(a = 1, *b) [a,b] end foo.should == [1, []] foo(2).should == [2, []] end it "evaluates the default when required arguments precede it" do def foo(a, b = 2) [a,b] end lambda { foo }.should raise_error(ArgumentError) foo(1).should == [1, 2] end it "prefers to assign to a default argument before a splat argument" do def foo(a, b = 2, *c) [a,b,c] end lambda { foo }.should raise_error(ArgumentError) foo(1).should == [1,2,[]] end it "prefers to assign to a default argument when there are no required arguments" do def foo(a = 1, *args) [a,args] end foo(2,2).should == [2,[2]] end it "does not evaluate the default when passed a value and a * argument" do def foo(a, b = 2, *args) [a,b,args] end foo(2,3,3).should == [2,3,[3]] end end describe "A singleton method definition" do after :all do Object.__send__(:remove_class_variable, :@@a) end it "can be declared for a local variable" do a = "hi" def a.foo 5 end a.foo.should == 5 end it "can be declared for an instance variable" do @a = "hi" def @a.foo 6 end @a.foo.should == 6 end it "can be declared for a global variable" do $__a__ = "hi" def $__a__.foo 7 end $__a__.foo.should == 7 end it "can be declared for a class variable" do @@a = "hi" def @@a.foo 8 end @@a.foo.should == 8 end it "can be declared with an empty method body" do class DefSpec def self.foo;end end DefSpec.foo.should == nil end it "can be redefined" do obj = Object.new def obj.==(other) 1 end (obj==1).should == 1 def obj.==(other) 2 end (obj==2).should == 2 end ruby_version_is ""..."1.9" do it "raises TypeError if frozen" do obj = Object.new obj.freeze lambda { def obj.foo; end }.should raise_error(TypeError) end end ruby_version_is "1.9" do it "raises RuntimeError if frozen" do obj = Object.new obj.freeze lambda { def obj.foo; end }.should raise_error(RuntimeError) end end end describe "Redefining a singleton method" do it "does not inherit a previously set visibility " do o = Object.new class << o; private; def foo; end; end; class << o; should have_private_instance_method(:foo); end class << o; def foo; end; end; class << o; should_not have_private_instance_method(:foo); end class << o; should have_instance_method(:foo); end end end describe "Redefining a singleton method" do it "does not inherit a previously set visibility " do o = Object.new class << o; private; def foo; end; end; class << o; should have_private_instance_method(:foo); end class << o; def foo; end; end; class << o; should_not have_private_instance_method(:foo); end class << o; should have_instance_method(:foo); end end end describe "A method defined with extreme default arguments" do it "can redefine itself when the default is evaluated" do class DefSpecs def foo(x = (def foo; "hello"; end;1));x;end end d = DefSpecs.new d.foo(42).should == 42 d.foo.should == 1 d.foo.should == 'hello' end it "may use an fcall as a default" do def foo(x = caller()) x end foo.shift.should be_kind_of(String) end it "evaluates the defaults in the method's scope" do def foo(x = ($foo_self = self; nil)); end foo $foo_self.should == self end it "may use preceding arguments as defaults" do def foo(obj, width=obj.length) width end foo('abcde').should == 5 end it "may use a lambda as a default" do def foo(output = 'a', prc = lambda {|n| output * n}) prc.call(5) end foo.should == 'aaaaa' end end describe "A singleton method defined with extreme default arguments" do it "may use a method definition as a default" do $__a = "hi" def $__a.foo(x = (def $__a.foo; "hello"; end;1));x;end $__a.foo(42).should == 42 $__a.foo.should == 1 $__a.foo.should == 'hello' end it "may use an fcall as a default" do a = "hi" def a.foo(x = caller()) x end a.foo.shift.should be_kind_of(String) end it "evaluates the defaults in the singleton scope" do a = "hi" def a.foo(x = ($foo_self = self; nil)); 5 ;end a.foo $foo_self.should == a end it "may use preceding arguments as defaults" do a = 'hi' def a.foo(obj, width=obj.length) width end a.foo('abcde').should == 5 end it "may use a lambda as a default" do a = 'hi' def a.foo(output = 'a', prc = lambda {|n| output * n}) prc.call(5) end a.foo.should == 'aaaaa' end end describe "A method definition inside a metaclass scope" do it "can create a class method" do class DefSpecSingleton class << self def a_class_method;self;end end end DefSpecSingleton.a_class_method.should == DefSpecSingleton lambda { Object.a_class_method }.should raise_error(NoMethodError) end it "can create a singleton method" do obj = Object.new class << obj def a_singleton_method;self;end end obj.a_singleton_method.should == obj lambda { Object.new.a_singleton_method }.should raise_error(NoMethodError) end ruby_version_is ""..."1.9" do it "raises TypeError if frozen" do obj = Object.new obj.freeze class << obj lambda { def foo; end }.should raise_error(TypeError) end end end ruby_version_is "1.9" do it "raises RuntimeError if frozen" do obj = Object.new obj.freeze class << obj lambda { def foo; end }.should raise_error(RuntimeError) end end end end describe "A nested method definition" do it "creates an instance method when evaluated in an instance method" do class DefSpecNested def create_instance_method def an_instance_method;self;end an_instance_method end end obj = DefSpecNested.new obj.create_instance_method.should == obj obj.an_instance_method.should == obj other = DefSpecNested.new other.an_instance_method.should == other DefSpecNested.should have_instance_method(:an_instance_method) end it "creates a class method when evaluated in a class method" do class DefSpecNested class << self def create_class_method def a_class_method;self;end a_class_method end end end lambda { DefSpecNested.a_class_method }.should raise_error(NoMethodError) DefSpecNested.create_class_method.should == DefSpecNested DefSpecNested.a_class_method.should == DefSpecNested lambda { Object.a_class_method }.should raise_error(NoMethodError) lambda { DefSpecNested.new.a_class_method }.should raise_error(NoMethodError) end it "creates a singleton method when evaluated in the metaclass of an instance" do class DefSpecNested def create_singleton_method class << self def a_singleton_method;self;end end a_singleton_method end end obj = DefSpecNested.new obj.create_singleton_method.should == obj obj.a_singleton_method.should == obj other = DefSpecNested.new lambda { other.a_singleton_method }.should raise_error(NoMethodError) end end describe "A method definition inside an instance_eval" do it "creates a singleton method" do obj = Object.new obj.instance_eval do def an_instance_eval_method;self;end end obj.an_instance_eval_method.should == obj other = Object.new lambda { other.an_instance_eval_method }.should raise_error(NoMethodError) end it "creates a singleton method when evaluated inside a metaclass" do obj = Object.new obj.instance_eval do class << self def a_metaclass_eval_method;self;end end end obj.a_metaclass_eval_method.should == obj other = Object.new lambda { other.a_metaclass_eval_method }.should raise_error(NoMethodError) end it "creates a class method when the receiver is a class" do DefSpecNested.instance_eval do def an_instance_eval_class_method;self;end end DefSpecNested.an_instance_eval_class_method.should == DefSpecNested lambda { Object.an_instance_eval_class_method }.should raise_error(NoMethodError) end end describe "A method definition in an eval" do it "creates an instance method" do class DefSpecNested def eval_instance_method eval "def an_eval_instance_method;self;end", binding an_eval_instance_method end end obj = DefSpecNested.new obj.eval_instance_method.should == obj obj.an_eval_instance_method.should == obj other = DefSpecNested.new other.an_eval_instance_method.should == other lambda { Object.new.an_eval_instance_method }.should raise_error(NoMethodError) end it "creates a class method" do class DefSpecNestedB class << self def eval_class_method eval "def an_eval_class_method;self;end" #, binding an_eval_class_method end end end DefSpecNestedB.eval_class_method.should == DefSpecNestedB DefSpecNestedB.an_eval_class_method.should == DefSpecNestedB lambda { Object.an_eval_class_method }.should raise_error(NoMethodError) lambda { DefSpecNestedB.new.an_eval_class_method}.should raise_error(NoMethodError) end it "creates a singleton method" do class DefSpecNested def eval_singleton_method class << self eval "def an_eval_singleton_method;self;end", binding end an_eval_singleton_method end end obj = DefSpecNested.new obj.eval_singleton_method.should == obj obj.an_eval_singleton_method.should == obj other = DefSpecNested.new lambda { other.an_eval_singleton_method }.should raise_error(NoMethodError) end end describe "a method definition that sets more than one default parameter all to the same value" do def foo(a=b=c={}) [a,b,c] end it "assigns them all the same object by default" do foo.should == [{},{},{}] a, b, c = foo a.should eql(b) a.should eql(c) end it "allows the first argument to be given, and sets the rest to null" do foo(1).should == [1,nil,nil] end it "assigns the parameters different objects across different default calls" do a, b, c = foo d, e, f = foo a.should_not equal(d) end it "only allows overriding the default value of the first such parameter in each set" do lambda { foo(1,2) }.should raise_error(ArgumentError) end def bar(a=b=c=1,d=2) [a,b,c,d] end it "treats the argument after the multi-parameter normally" do bar.should == [1,1,1,2] bar(3).should == [3,nil,nil,2] bar(3,4).should == [3,nil,nil,4] lambda { bar(3,4,5) }.should raise_error(ArgumentError) end end describe "The def keyword" do describe "within a closure" do it "looks outside the closure for the visibility" do module DefSpecsLambdaVisibility private lambda { def some_method; end }.call end DefSpecsLambdaVisibility.should have_private_instance_method("some_method") end end end language_version __FILE__, "def" ruby_version_is "2.0" do require File.expand_path('../versions/def_2.0.rb', __FILE__) end
class Bcalm < Formula desc "de Bruijn CompAction in Low Memory" homepage "https://github.com/Malfoy/bcalm" # doi "10.1007/978-3-319-05269-4_4" # tag "bioinformatics" url "https://github.com/Malfoy/bcalm/archive/2.tar.gz" sha256 "dc50883d2b24bcd13abbc731211ea28f0eef4bd45a91bb24c0641b1ece80c9ce" head "https://github.com/Malfoy/bcalm.git" bottle do cellar :any_skip_relocation sha256 "275e8b52ba361c7b709bea9ad8d321cd72c3771d76fabe86054cea9c7dfbf9a9" => :el_capitan sha256 "6850356f860b9e9a52f97303b64fa8d63c32d9448df7961ccce17decbd383c8a" => :yosemite sha256 "35e0e2996bb345741d4c74165664df68e10507d9b007afd41e5a886a08f845ce" => :mavericks sha256 "d7dcaebe036421cac51f91f5962d13b442b5b9afb52605c4e48ff2212fe2bdbd" => :x86_64_linux end def install ENV.libcxx system "make" bin.install "bcalm" doc.install "README.md" end end bcalm 2.0.0 Closes #3797. Signed-off-by: Shaun Jackman <b580dab3251a9622aba3803114310c23fdb42900@gmail.com> class Bcalm < Formula desc "de Bruijn graph compaction in low memory" homepage "https://github.com/GATB/bcalm" # doi "10.1093/bioinformatics/btw279" # tag "bioinformatics" url "https://github.com/GATB/bcalm/releases/download/v2.0.0/bcalm-2.0.0.zip" sha256 "6d1d1d8b3339fff7cd0ec04b954a30e49138c1470efbcbcbf7b7e91f3c5b6d18" head "https://github.com/GATB/bcalm.git" bottle do cellar :any_skip_relocation sha256 "275e8b52ba361c7b709bea9ad8d321cd72c3771d76fabe86054cea9c7dfbf9a9" => :el_capitan sha256 "6850356f860b9e9a52f97303b64fa8d63c32d9448df7961ccce17decbd383c8a" => :yosemite sha256 "35e0e2996bb345741d4c74165664df68e10507d9b007afd41e5a886a08f845ce" => :mavericks sha256 "d7dcaebe036421cac51f91f5962d13b442b5b9afb52605c4e48ff2212fe2bdbd" => :x86_64_linux end depends_on "cmake" => :build def install mkdir "build" do system "cmake", "..", *std_cmake_args system "make" bin.install "bcalm", "bglue" end doc.install "README.md" end test do system bin/"bcalm" system bin/"bglue" end end
class Beast < Formula desc "Bayesian Evolutionary Analysis Sampling Trees" homepage "http://beast.bio.ed.ac.uk/" # doi "10.1093/molbev/mss075" # tag "bioinformatics" url "http://tree.bio.ed.ac.uk/download.php?id=92&num=3" version "1.8.2" sha256 "233ca5e06d98c5e7f8fb6a68fe5dd5448bb36d7d801117f7f6f11ac9f6b6ecc9" bottle do cellar :any sha256 "e1357fad70b3a51ce734a705667f2e9d16bdddf480bf340559cdad0bbcaacb65" => :yosemite sha256 "c411831dc26441e4b5bd92dc1926fbd8171d5c8d26d17239f2ce1e9604f67f8b" => :mavericks sha256 "c3974c08c01dfa26db9407b070b4302a109043725fef586b4d82290603f2dfee" => :mountain_lion end head do url "https://github.com/beast-dev/beast-mcmc.git" depends_on :ant end def install system "ant", "linux" if build.head? # Move jars to libexec inreplace Dir["bin/*"] do |s| s["$BEAST/lib"] = "$BEAST/libexec" end mv "lib", "libexec" prefix.install Dir[build.head? ? "release/Linux/BEASTv*/*" : "*"] end def caveats; <<-EOS.undent Examples are installed in: #{opt_prefix}/examples/ EOS end test do system "#{bin}/beast", "-help" end end beast 1.8.3 Also add better tests and fix up the build system. Closes #3636. Signed-off-by: Dominique Orban <b6b12199b0ff1342bf41262c4fcd3a561907b571@gmail.com> class Beast < Formula desc "Bayesian Evolutionary Analysis Sampling Trees" homepage "http://beast.bio.ed.ac.uk/" # doi "10.1093/molbev/mss075" # tag "bioinformatics" url "https://github.com/beast-dev/beast-mcmc/archive/v1.8.3.tar.gz" sha256 "1b03318e77064f8d556a0859aadd3c81036b41e56e323364fb278a56a00aff44" head "https://github.com/beast-dev/beast-mcmc.git" bottle do cellar :any sha256 "e1357fad70b3a51ce734a705667f2e9d16bdddf480bf340559cdad0bbcaacb65" => :yosemite sha256 "c411831dc26441e4b5bd92dc1926fbd8171d5c8d26d17239f2ce1e9604f67f8b" => :mavericks sha256 "c3974c08c01dfa26db9407b070b4302a109043725fef586b4d82290603f2dfee" => :mountain_lion end depends_on :ant => :build def install system "ant", "linux" prefix.install Dir["release/Linux/BEASTv*/*"] # Move installed JARs to libexec mv lib, libexec # Point wrapper scripts to libexec inreplace Dir[bin/"*"] do |s| s["$BEAST/lib"] = "$BEAST/libexec" end end def caveats; <<-EOS.undent Examples are installed in: #{opt_prefix}/examples/ EOS end test do cp (opt_prefix/"examples"/"clockModels"/"testUCRelaxedClockLogNormal.xml"), testpath # Run fewer generations to speed up tests inreplace "testUCRelaxedClockLogNormal.xml" do |s| s['chainLength="10000000"'] = 'chainLength="500000"' end system "#{bin}/beast", "-beagle_off", "testUCRelaxedClockLogNormal.xml" %W[ops log trees].each do |ext| assert File.exist? "testUCRelaxedClockLogNormal." + ext end end end
require 'spec_helper' describe Spree::Gateway::Braintree do before(:each) do Spree::Gateway.update_all :active => false @gateway = Spree::Gateway::Braintree.create!(:name => "Braintree Gateway", :environment => "test", :active => true) @gateway.set_preference(:merchant_id, "zbn5yzq9t7wmwx42" ) @gateway.set_preference(:public_key, "ym9djwqpkxbv3xzt") @gateway.set_preference(:private_key, "4ghghkyp2yy6yqc8") @gateway.save! with_payment_profiles_off do @country = Factory(:country, :name => "United States", :iso_name => "UNITED STATES", :iso3 => "USA", :iso => "US", :numcode => 840) @state = Factory(:state, :name => "Maryland", :abbr => "MD", :country => @country) @address = Factory(:address, :firstname => 'John', :lastname => 'Doe', :address1 => '1234 My Street', :address2 => 'Apt 1', :city => 'Washington DC', :zipcode => '20123', :phone => '(555)555-5555', :state => @state, :country => @country ) @order = Factory(:order_with_totals, :bill_address => @address, :ship_address => @address) @order.update! @creditcard = Factory(:creditcard, :verification_value => '123', :number => '5105105105105100', :month => 9, :year => Time.now.year + 1, :first_name => 'John', :last_name => 'Doe') @payment = Factory(:payment, :source => @creditcard, :order => @order, :payment_method => @gateway, :amount => @order.total) end end pending "should be braintree gateway" do @gateway.provider_class.should == ::ActiveMerchant::Billing::BraintreeGateway end pending "should be the Blue Braintree" do @gateway.provider.class.should == ::ActiveMerchant::Billing::BraintreeBlueGateway end describe "authorize" do pending "should return a success response with an authorization code" do result = @gateway.authorize(500, @creditcard, {:server=>"test", :test =>true, :merchant_id=>"zbn5yzq9t7wmwx42", :public_key=> "ym9djwqpkxbv3xzt", :private_key=> "4ghghkyp2yy6yqc8"}) result.success?.should be_true result.authorization.should match(/\A\w{6}\z/) Braintree::Transaction::Status::Authorized.should == Braintree::Transaction.find(result.authorization).status end pending 'should work through the spree payment interface' do Spree::Config.set :auto_capture => false @payment.log_entries.size.should == 0 @payment.process! @payment.log_entries.size.should == 1 @payment.response_code.should match /\A\w{6}\z/ @payment.state.should == 'pending' transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.status.should == Braintree::Transaction::Status::Authorized transaction.credit_card_details.masked_number.should == "510510******5100" transaction.credit_card_details.expiration_date.should == "09/#{Time.now.year + 1}" transaction.customer_details.first_name.should == 'John' transaction.customer_details.last_name.should == 'Doe' end end describe "capture" do pending " should capture a previous authorization" do @payment.process! assert_equal 1, @payment.log_entries.size assert_match /\A\w{6}\z/, @payment.response_code transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.status.should == Braintree::Transaction::Status::Authorized capture_result = @gateway.capture(@payment,:ignored_arg_creditcard, :ignored_arg_options) capture_result.success?.should be_true transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement end pending "raise an error if capture fails using spree interface" do Spree::Config.set :auto_capture => false @payment.log_entries.size.should == 0 @payment.process! @payment.log_entries.size.should == 1 transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.status.should == Braintree::Transaction::Status::Authorized @payment.payment_source.capture(@payment) # as done in PaymentsController#fire # transaction = ::Braintree::Transaction.find(@payment.response_code) # transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement # lambda do # @payment.payment_source.capture(@payment) # end.should raise_error(Spree::GatewayError, "Cannot submit for settlement unless status is authorized. (91507)") end end describe 'purchase' do pending 'should return a success response with an authorization code' do result = @gateway.purchase(500, @creditcard) result.success?.should be_true result.authorization.should match(/\A\w{6}\z/) Braintree::Transaction::Status::SubmittedForSettlement.should == Braintree::Transaction.find(result.authorization).status end pending 'should work through the spree payment interface with payment profiles' do purchase_using_spree_interface transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.credit_card_details.token.should_not be_nil end pending 'should work through the spree payment interface without payment profiles' do with_payment_profiles_off do purchase_using_spree_interface(false) transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.credit_card_details.token.should be_nil end end end describe "credit" do pending "should work through the spree interface" do @payment.amount += 100.00 purchase_using_spree_interface credit_using_spree_interface end end describe "void" do pending "should work through the spree creditcard / payment interface" do assert_equal 0, @payment.log_entries.size @payment.process! assert_equal 1, @payment.log_entries.size @payment.response_code.should match(/\A\w{6}\z/) transaction = Braintree::Transaction.find(@payment.response_code) transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement @creditcard.void(@payment) transaction = Braintree::Transaction.find(transaction.id) transaction.status.should == Braintree::Transaction::Status::Voided end end def credit_using_spree_interface @payment.log_entries.size.should == 1 @payment.source.credit(@payment) # as done in PaymentsController#fire @payment.log_entries.size.should == 2 #Let's get the payment record associated with the credit @payment = @order.payments.last @payment.response_code.should match(/\A\w{6}\z/) transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.type.should == Braintree::Transaction::Type::Credit transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement transaction.credit_card_details.masked_number.should == "510510******5100" transaction.credit_card_details.expiration_date.should == "09/#{Time.now.year + 1}" transaction.customer_details.first_name.should == "John" transaction.customer_details.last_name.should == "Doe" end def purchase_using_spree_interface(profile=true) Spree::Config.set :auto_capture => true @payment.send(:create_payment_profile) if profile @payment.log_entries.size == 0 @payment.process! # as done in PaymentsController#create @payment.log_entries.size == 1 @payment.response_code.should match /\A\w{6}\z/ @payment.state.should == 'completed' transaction = ::Braintree::Transaction.find(@payment.response_code) Braintree::Transaction::Status::SubmittedForSettlement.should == transaction.status transaction.credit_card_details.masked_number.should == "510510******5100" transaction.credit_card_details.expiration_date.should == "09/#{Time.now.year + 1}" transaction.customer_details.first_name.should == 'John' transaction.customer_details.last_name.should == 'Doe' end def with_payment_profiles_off(&block) Gateway::Braintree.class_eval do def payment_profiles_supported? false end end yield ensure Gateway::Braintree.class_eval do def payment_profiles_supported? true end end end end Namespace one more occurrences of GatewayError require 'spec_helper' describe Spree::Gateway::Braintree do before(:each) do Spree::Gateway.update_all :active => false @gateway = Spree::Gateway::Braintree.create!(:name => "Braintree Gateway", :environment => "test", :active => true) @gateway.set_preference(:merchant_id, "zbn5yzq9t7wmwx42" ) @gateway.set_preference(:public_key, "ym9djwqpkxbv3xzt") @gateway.set_preference(:private_key, "4ghghkyp2yy6yqc8") @gateway.save! with_payment_profiles_off do @country = Factory(:country, :name => "United States", :iso_name => "UNITED STATES", :iso3 => "USA", :iso => "US", :numcode => 840) @state = Factory(:state, :name => "Maryland", :abbr => "MD", :country => @country) @address = Factory(:address, :firstname => 'John', :lastname => 'Doe', :address1 => '1234 My Street', :address2 => 'Apt 1', :city => 'Washington DC', :zipcode => '20123', :phone => '(555)555-5555', :state => @state, :country => @country ) @order = Factory(:order_with_totals, :bill_address => @address, :ship_address => @address) @order.update! @creditcard = Factory(:creditcard, :verification_value => '123', :number => '5105105105105100', :month => 9, :year => Time.now.year + 1, :first_name => 'John', :last_name => 'Doe') @payment = Factory(:payment, :source => @creditcard, :order => @order, :payment_method => @gateway, :amount => @order.total) end end pending "should be braintree gateway" do @gateway.provider_class.should == ::ActiveMerchant::Billing::BraintreeGateway end pending "should be the Blue Braintree" do @gateway.provider.class.should == ::ActiveMerchant::Billing::BraintreeBlueGateway end describe "authorize" do pending "should return a success response with an authorization code" do result = @gateway.authorize(500, @creditcard, {:server=>"test", :test =>true, :merchant_id=>"zbn5yzq9t7wmwx42", :public_key=> "ym9djwqpkxbv3xzt", :private_key=> "4ghghkyp2yy6yqc8"}) result.success?.should be_true result.authorization.should match(/\A\w{6}\z/) Braintree::Transaction::Status::Authorized.should == Braintree::Transaction.find(result.authorization).status end pending 'should work through the spree payment interface' do Spree::Config.set :auto_capture => false @payment.log_entries.size.should == 0 @payment.process! @payment.log_entries.size.should == 1 @payment.response_code.should match /\A\w{6}\z/ @payment.state.should == 'pending' transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.status.should == Braintree::Transaction::Status::Authorized transaction.credit_card_details.masked_number.should == "510510******5100" transaction.credit_card_details.expiration_date.should == "09/#{Time.now.year + 1}" transaction.customer_details.first_name.should == 'John' transaction.customer_details.last_name.should == 'Doe' end end describe "capture" do pending " should capture a previous authorization" do @payment.process! assert_equal 1, @payment.log_entries.size assert_match /\A\w{6}\z/, @payment.response_code transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.status.should == Braintree::Transaction::Status::Authorized capture_result = @gateway.capture(@payment,:ignored_arg_creditcard, :ignored_arg_options) capture_result.success?.should be_true transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement end pending "raise an error if capture fails using spree interface" do Spree::Config.set :auto_capture => false @payment.log_entries.size.should == 0 @payment.process! @payment.log_entries.size.should == 1 transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.status.should == Braintree::Transaction::Status::Authorized @payment.payment_source.capture(@payment) # as done in PaymentsController#fire # transaction = ::Braintree::Transaction.find(@payment.response_code) # transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement # lambda do # @payment.payment_source.capture(@payment) # end.should raise_error(Spree::Core::GatewayError, "Cannot submit for settlement unless status is authorized. (91507)") end end describe 'purchase' do pending 'should return a success response with an authorization code' do result = @gateway.purchase(500, @creditcard) result.success?.should be_true result.authorization.should match(/\A\w{6}\z/) Braintree::Transaction::Status::SubmittedForSettlement.should == Braintree::Transaction.find(result.authorization).status end pending 'should work through the spree payment interface with payment profiles' do purchase_using_spree_interface transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.credit_card_details.token.should_not be_nil end pending 'should work through the spree payment interface without payment profiles' do with_payment_profiles_off do purchase_using_spree_interface(false) transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.credit_card_details.token.should be_nil end end end describe "credit" do pending "should work through the spree interface" do @payment.amount += 100.00 purchase_using_spree_interface credit_using_spree_interface end end describe "void" do pending "should work through the spree creditcard / payment interface" do assert_equal 0, @payment.log_entries.size @payment.process! assert_equal 1, @payment.log_entries.size @payment.response_code.should match(/\A\w{6}\z/) transaction = Braintree::Transaction.find(@payment.response_code) transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement @creditcard.void(@payment) transaction = Braintree::Transaction.find(transaction.id) transaction.status.should == Braintree::Transaction::Status::Voided end end def credit_using_spree_interface @payment.log_entries.size.should == 1 @payment.source.credit(@payment) # as done in PaymentsController#fire @payment.log_entries.size.should == 2 #Let's get the payment record associated with the credit @payment = @order.payments.last @payment.response_code.should match(/\A\w{6}\z/) transaction = ::Braintree::Transaction.find(@payment.response_code) transaction.type.should == Braintree::Transaction::Type::Credit transaction.status.should == Braintree::Transaction::Status::SubmittedForSettlement transaction.credit_card_details.masked_number.should == "510510******5100" transaction.credit_card_details.expiration_date.should == "09/#{Time.now.year + 1}" transaction.customer_details.first_name.should == "John" transaction.customer_details.last_name.should == "Doe" end def purchase_using_spree_interface(profile=true) Spree::Config.set :auto_capture => true @payment.send(:create_payment_profile) if profile @payment.log_entries.size == 0 @payment.process! # as done in PaymentsController#create @payment.log_entries.size == 1 @payment.response_code.should match /\A\w{6}\z/ @payment.state.should == 'completed' transaction = ::Braintree::Transaction.find(@payment.response_code) Braintree::Transaction::Status::SubmittedForSettlement.should == transaction.status transaction.credit_card_details.masked_number.should == "510510******5100" transaction.credit_card_details.expiration_date.should == "09/#{Time.now.year + 1}" transaction.customer_details.first_name.should == 'John' transaction.customer_details.last_name.should == 'Doe' end def with_payment_profiles_off(&block) Gateway::Braintree.class_eval do def payment_profiles_supported? false end end yield ensure Gateway::Braintree.class_eval do def payment_profiles_supported? true end end end end
# frozen_string_literal: true require 'rom/struct_compiler' RSpec.describe ROM::StructCompiler, '#call' do subject(:struct_compiler) { ROM::StructCompiler.new } def attr_ast(name, type, **opts) [name, ROM::Types.const_get(type).to_ast, alias: false, wrapped: false] end let(:input) do [:users, [[:attribute, attr_ast(:id, :Integer)], [:attribute, attr_ast(:name, :String)]]] end context 'ROM::Struct' do it 'generates valid class name in the default namespace' do ast = [ :statuses, [ [:attribute, attr_ast(:id, :Integer)], [:attribute, attr_ast(:name, :String)] ] ] struct = struct_compiler[*ast, ROM::Struct] expect(struct.name).to eql('ROM::Struct::Status') end it 'generates a struct for a given relation name and columns' do struct = struct_compiler[*input, ROM::Struct] user = struct.new(id: 1, name: 'Jane') expect(user.id).to be(1) expect(user.name).to eql('Jane') expect(user[:id]).to be(1) expect(user[:name]).to eql('Jane') expect(Hash[user]).to eql(id: 1, name: 'Jane') expect(user.inspect).to eql('#<ROM::Struct::User id=1 name="Jane">') expect(user.to_s).to match(/\A#<ROM::Struct::User:0x[0-9a-f]+>\z/) end it 'stores struct in the cache' do expect(struct_compiler[*input, ROM::Struct]).to be(struct_compiler[*input, ROM::Struct]) end context 'with reserved keywords as attribute names' do let(:input) do [:users, [[:attribute, attr_ast(:id, :Integer)], [:attribute, attr_ast(:name, :String)], [:attribute, attr_ast(:alias, :String)], [:attribute, attr_ast(:until, :Time)]]] end it 'allows to build a struct class without complaining' do struct = struct_compiler[*input, ROM::Struct] user = struct.new(id: 1, name: 'Jane', alias: 'JD', until: Time.new(2030)) expect(user.id).to be(1) expect(user.name).to eql('Jane') expect(user.alias).to eql('JD') expect(user.until).to eql(Time.new(2030)) end end it 'raise a friendly error on missing keys' do struct = struct_compiler[*input, ROM::Struct] expect { struct.new(id: 1) }.to raise_error(Dry::Struct::Error, /:name is missing/) end end context 'with constrained types' do let(:input) do [:posts, [[:attribute, [:id, ROM::Types::Strict::Integer.to_ast, alias: false, wrapped: false]], [:attribute, [:status, ROM::Types::Strict::String.enum(%(Foo Bar)).to_ast, alias: false, wrapped: false]]]] end let(:struct) do struct_compiler[*input, ROM::Struct] end it 'reduces a constrained type to plain definition' do expect(struct.schema.key(:id).type).to_not be_constrained end it 'reduces an enum type to plain definition' do expect(struct.schema.key(:status).type).to_not be_constrained end end context 'custom entity container' do before do module Test module Custom end end end let(:struct) { struct_compiler[*input, Test::Custom] } it 'generates a struct class inside a given module' do expect(struct.name).to eql('Test::Custom::User') user = struct.new(id: 1, name: 'Jane') expect(user.inspect).to eql(%q(#<Test::Custom::User id=1 name="Jane">)) end it 'uses the existing class as a parent' do class Test::Custom::User < ROM::Struct def upcased_name name.upcase end end user = struct.new(id: 1, name: 'Jane') expect(user.upcased_name).to eql('JANE') end it 'raises a nice error on missing attributes' do class Test::Custom::User < ROM::Struct def upcased_middle_name middle_name.upcase end end user = struct.new(id: 1, name: 'Jane') expect { user.upcased_middle_name }.to raise_error(ROM::Struct::MissingAttribute, /attribute not loaded\?/) end it 'works with implicit coercions' do user = struct.new(id: 1, name: 'Jane') expect([user].flatten).to eql([user]) end it 'generates a proper error if with overridden getters and a missing method in them' do class Test::Custom::User < ROM::Struct def name first_name end end user = struct.new(id: 1, name: 'Jane') expect { user.name }.to raise_error(ROM::Struct::MissingAttribute, /attribute not loaded\?/) end end end rubocop -a --only Style/UnneededPercentQ # frozen_string_literal: true require 'rom/struct_compiler' RSpec.describe ROM::StructCompiler, '#call' do subject(:struct_compiler) { ROM::StructCompiler.new } def attr_ast(name, type, **opts) [name, ROM::Types.const_get(type).to_ast, alias: false, wrapped: false] end let(:input) do [:users, [[:attribute, attr_ast(:id, :Integer)], [:attribute, attr_ast(:name, :String)]]] end context 'ROM::Struct' do it 'generates valid class name in the default namespace' do ast = [ :statuses, [ [:attribute, attr_ast(:id, :Integer)], [:attribute, attr_ast(:name, :String)] ] ] struct = struct_compiler[*ast, ROM::Struct] expect(struct.name).to eql('ROM::Struct::Status') end it 'generates a struct for a given relation name and columns' do struct = struct_compiler[*input, ROM::Struct] user = struct.new(id: 1, name: 'Jane') expect(user.id).to be(1) expect(user.name).to eql('Jane') expect(user[:id]).to be(1) expect(user[:name]).to eql('Jane') expect(Hash[user]).to eql(id: 1, name: 'Jane') expect(user.inspect).to eql('#<ROM::Struct::User id=1 name="Jane">') expect(user.to_s).to match(/\A#<ROM::Struct::User:0x[0-9a-f]+>\z/) end it 'stores struct in the cache' do expect(struct_compiler[*input, ROM::Struct]).to be(struct_compiler[*input, ROM::Struct]) end context 'with reserved keywords as attribute names' do let(:input) do [:users, [[:attribute, attr_ast(:id, :Integer)], [:attribute, attr_ast(:name, :String)], [:attribute, attr_ast(:alias, :String)], [:attribute, attr_ast(:until, :Time)]]] end it 'allows to build a struct class without complaining' do struct = struct_compiler[*input, ROM::Struct] user = struct.new(id: 1, name: 'Jane', alias: 'JD', until: Time.new(2030)) expect(user.id).to be(1) expect(user.name).to eql('Jane') expect(user.alias).to eql('JD') expect(user.until).to eql(Time.new(2030)) end end it 'raise a friendly error on missing keys' do struct = struct_compiler[*input, ROM::Struct] expect { struct.new(id: 1) }.to raise_error(Dry::Struct::Error, /:name is missing/) end end context 'with constrained types' do let(:input) do [:posts, [[:attribute, [:id, ROM::Types::Strict::Integer.to_ast, alias: false, wrapped: false]], [:attribute, [:status, ROM::Types::Strict::String.enum(%(Foo Bar)).to_ast, alias: false, wrapped: false]]]] end let(:struct) do struct_compiler[*input, ROM::Struct] end it 'reduces a constrained type to plain definition' do expect(struct.schema.key(:id).type).to_not be_constrained end it 'reduces an enum type to plain definition' do expect(struct.schema.key(:status).type).to_not be_constrained end end context 'custom entity container' do before do module Test module Custom end end end let(:struct) { struct_compiler[*input, Test::Custom] } it 'generates a struct class inside a given module' do expect(struct.name).to eql('Test::Custom::User') user = struct.new(id: 1, name: 'Jane') expect(user.inspect).to eql('#<Test::Custom::User id=1 name="Jane">') end it 'uses the existing class as a parent' do class Test::Custom::User < ROM::Struct def upcased_name name.upcase end end user = struct.new(id: 1, name: 'Jane') expect(user.upcased_name).to eql('JANE') end it 'raises a nice error on missing attributes' do class Test::Custom::User < ROM::Struct def upcased_middle_name middle_name.upcase end end user = struct.new(id: 1, name: 'Jane') expect { user.upcased_middle_name }.to raise_error(ROM::Struct::MissingAttribute, /attribute not loaded\?/) end it 'works with implicit coercions' do user = struct.new(id: 1, name: 'Jane') expect([user].flatten).to eql([user]) end it 'generates a proper error if with overridden getters and a missing method in them' do class Test::Custom::User < ROM::Struct def name first_name end end user = struct.new(id: 1, name: 'Jane') expect { user.name }.to raise_error(ROM::Struct::MissingAttribute, /attribute not loaded\?/) end end end
StaffMember.create!( email: 'taro@example.com', family_name: '山田', given_name: '太郎', family_name_kana: 'ヤマダ', given_name_kana: 'タロウ', password: 'password', start_date: Date.today, ) suspended true user StaffMember.create!( email: 'taro@example.com', family_name: '山田', given_name: '太郎', family_name_kana: 'ヤマダ', given_name_kana: 'タロウ', password: 'password', start_date: Date.today, ) StaffMember.create!( email: 'test@example.com', family_name: '山田', given_name: '太郎', family_name_kana: 'ヤマダ', given_name_kana: 'タロウ', password: 'password', suspended: true, start_date: Date.today, )
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- # stub: minimum_viable_product 0.6.3 ruby lib Gem::Specification.new do |s| s.name = "minimum_viable_product" s.version = "0.6.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Ian Hunter"] s.date = "2016-12-08" s.description = "Built for Developers. Ideal for MVPs, product ideation and validation." s.email = "ianhunter@gmail.com" s.executables = ["mvp", "rails"] s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ "Gemfile", "Gemfile.lock", "LICENSE.txt", "MIT-LICENSE", "README.md", "Rakefile", "VERSION", "app/assets/javascripts/mvp/application.js", "app/assets/stylesheets/mvp/application.scss", "app/controllers/concerns/minimum_viable_product/analytics_concern.rb", "app/controllers/concerns/minimum_viable_product/seo_concern.rb", "app/controllers/concerns/minimum_viable_product/session_concern.rb", "app/controllers/minimum_viable_product/analytics_controller.rb", "app/controllers/minimum_viable_product/seo_controller.rb", "app/controllers/minimum_viable_product/styleguide_controller.rb", "app/helpers/minimum_viable_product/body_helper.rb", "app/helpers/minimum_viable_product/bootstrap_helper.rb", "app/helpers/minimum_viable_product/styleguide_helper.rb", "app/models/concerns/minimum_viable_product/slugification.rb", "app/views/layouts/minimum_viable_product/_instrumentation.html.erb", "app/views/layouts/minimum_viable_product/_meta.html.erb", "app/views/layouts/minimum_viable_product/application.html.erb", "app/views/minimum_viable_product/styleguide/_example.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_buttons.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_forms.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_header.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_panels.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_tables.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_typography.html.erb", "app/views/minimum_viable_product/styleguide/elements/_grouping.html.erb", "app/views/minimum_viable_product/styleguide/elements/partials/_row_groups_of.html.erb", "app/views/minimum_viable_product/styleguide/index.html.erb", "app/views/minimum_viable_product/styleguide/layouts/basic.html.erb", "app/views/minimum_viable_product/styleguide/layouts/carousel.html.erb", "app/views/minimum_viable_product/styleguide/layouts/cover.html.erb", "assets/js/application.js", "assets/js/init/controllers.js", "assets/js/init/forms.js", "bin/mvp", "bin/rails", "config/initializers/assets.rb", "config/initializers/canonical_host.rb", "config/initializers/cloudinary.rb", "config/initializers/geocoder.rb", "config/initializers/iteration.rb", "config/initializers/project.rb", "config/initializers/rollbar.rb", "config/initializers/routing.rb", "config/initializers/segment.rb", "config/initializers/spoof_ip.rb", "config/initializers/ssl.rb", "config/routes.rb", "lib/minimum_viable_product.rb", "lib/minimum_viable_product/engine.rb", "lib/minimum_viable_product/ext/nil.rb", "lib/minimum_viable_product/ext/string.rb", "lib/tasks/sitemap.rake", "minimum_viable_product.gemspec", "mvp.gemspec", "package.json", "test/helper.rb", "test/test_minimum_viable_product.rb" ] s.homepage = "http://github.com/ian/minimum_viable_product" s.licenses = ["MIT"] s.rubygems_version = "2.4.6" s.summary = "The start-to-finish 3 minute product platform" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<analytics-ruby>, [">= 0"]) s.add_runtime_dependency(%q<carrierwave>, [">= 0"]) s.add_runtime_dependency(%q<cloudinary>, [">= 0"]) s.add_runtime_dependency(%q<geocoder>, [">= 0"]) s.add_runtime_dependency(%q<faraday>, [">= 0"]) s.add_runtime_dependency(%q<fog>, [">= 0"]) s.add_runtime_dependency(%q<fog-aws>, [">= 0"]) s.add_runtime_dependency(%q<hashie>, [">= 0"]) s.add_runtime_dependency(%q<rack-canonical-host>, [">= 0"]) s.add_runtime_dependency(%q<rack-ssl-enforcer>, [">= 0"]) s.add_runtime_dependency(%q<rails>, ["~> 4.2.3"]) s.add_runtime_dependency(%q<rollbar>, [">= 0"]) s.add_runtime_dependency(%q<sass-rails>, ["~> 5.0"]) s.add_runtime_dependency(%q<sitemap_generator>, [">= 0"]) s.add_runtime_dependency(%q<slack-notifier>, [">= 0"]) s.add_development_dependency(%q<byebug>, [">= 0"]) s.add_development_dependency(%q<better_errors>, [">= 0"]) s.add_development_dependency(%q<binding_of_caller>, [">= 0"]) s.add_development_dependency(%q<bullet>, [">= 0"]) s.add_development_dependency(%q<semantic>, [">= 0"]) s.add_development_dependency(%q<web-console>, ["~> 2.0"]) s.add_development_dependency(%q<spring>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, ["~> 1.0"]) s.add_development_dependency(%q<jeweler>, ["~> 2.0.1"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) else s.add_dependency(%q<analytics-ruby>, [">= 0"]) s.add_dependency(%q<carrierwave>, [">= 0"]) s.add_dependency(%q<cloudinary>, [">= 0"]) s.add_dependency(%q<geocoder>, [">= 0"]) s.add_dependency(%q<faraday>, [">= 0"]) s.add_dependency(%q<fog>, [">= 0"]) s.add_dependency(%q<fog-aws>, [">= 0"]) s.add_dependency(%q<hashie>, [">= 0"]) s.add_dependency(%q<rack-canonical-host>, [">= 0"]) s.add_dependency(%q<rack-ssl-enforcer>, [">= 0"]) s.add_dependency(%q<rails>, ["~> 4.2.3"]) s.add_dependency(%q<rollbar>, [">= 0"]) s.add_dependency(%q<sass-rails>, ["~> 5.0"]) s.add_dependency(%q<sitemap_generator>, [">= 0"]) s.add_dependency(%q<slack-notifier>, [">= 0"]) s.add_dependency(%q<byebug>, [">= 0"]) s.add_dependency(%q<better_errors>, [">= 0"]) s.add_dependency(%q<binding_of_caller>, [">= 0"]) s.add_dependency(%q<bullet>, [">= 0"]) s.add_dependency(%q<semantic>, [">= 0"]) s.add_dependency(%q<web-console>, ["~> 2.0"]) s.add_dependency(%q<spring>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.0.1"]) s.add_dependency(%q<simplecov>, [">= 0"]) end else s.add_dependency(%q<analytics-ruby>, [">= 0"]) s.add_dependency(%q<carrierwave>, [">= 0"]) s.add_dependency(%q<cloudinary>, [">= 0"]) s.add_dependency(%q<geocoder>, [">= 0"]) s.add_dependency(%q<faraday>, [">= 0"]) s.add_dependency(%q<fog>, [">= 0"]) s.add_dependency(%q<fog-aws>, [">= 0"]) s.add_dependency(%q<hashie>, [">= 0"]) s.add_dependency(%q<rack-canonical-host>, [">= 0"]) s.add_dependency(%q<rack-ssl-enforcer>, [">= 0"]) s.add_dependency(%q<rails>, ["~> 4.2.3"]) s.add_dependency(%q<rollbar>, [">= 0"]) s.add_dependency(%q<sass-rails>, ["~> 5.0"]) s.add_dependency(%q<sitemap_generator>, [">= 0"]) s.add_dependency(%q<slack-notifier>, [">= 0"]) s.add_dependency(%q<byebug>, [">= 0"]) s.add_dependency(%q<better_errors>, [">= 0"]) s.add_dependency(%q<binding_of_caller>, [">= 0"]) s.add_dependency(%q<bullet>, [">= 0"]) s.add_dependency(%q<semantic>, [">= 0"]) s.add_dependency(%q<web-console>, ["~> 2.0"]) s.add_dependency(%q<spring>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.0.1"]) s.add_dependency(%q<simplecov>, [">= 0"]) end end Regenerate gemspec for version 0.6.4 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- # stub: minimum_viable_product 0.6.4 ruby lib Gem::Specification.new do |s| s.name = "minimum_viable_product" s.version = "0.6.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Ian Hunter"] s.date = "2016-12-08" s.description = "Built for Developers. Ideal for MVPs, product ideation and validation." s.email = "ianhunter@gmail.com" s.executables = ["mvp", "rails"] s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ "Gemfile", "Gemfile.lock", "LICENSE.txt", "MIT-LICENSE", "README.md", "Rakefile", "VERSION", "app/assets/javascripts/mvp/application.js", "app/assets/stylesheets/mvp/application.scss", "app/controllers/concerns/minimum_viable_product/analytics_concern.rb", "app/controllers/concerns/minimum_viable_product/seo_concern.rb", "app/controllers/concerns/minimum_viable_product/session_concern.rb", "app/controllers/minimum_viable_product/analytics_controller.rb", "app/controllers/minimum_viable_product/seo_controller.rb", "app/controllers/minimum_viable_product/styleguide_controller.rb", "app/helpers/minimum_viable_product/body_helper.rb", "app/helpers/minimum_viable_product/bootstrap_helper.rb", "app/helpers/minimum_viable_product/styleguide_helper.rb", "app/models/concerns/minimum_viable_product/slugification.rb", "app/views/layouts/minimum_viable_product/_instrumentation.html.erb", "app/views/layouts/minimum_viable_product/_meta.html.erb", "app/views/layouts/minimum_viable_product/application.html.erb", "app/views/minimum_viable_product/styleguide/_example.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_buttons.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_forms.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_header.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_panels.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_tables.html.erb", "app/views/minimum_viable_product/styleguide/bootstrap/_typography.html.erb", "app/views/minimum_viable_product/styleguide/elements/_grouping.html.erb", "app/views/minimum_viable_product/styleguide/elements/partials/_row_groups_of.html.erb", "app/views/minimum_viable_product/styleguide/index.html.erb", "app/views/minimum_viable_product/styleguide/layouts/basic.html.erb", "app/views/minimum_viable_product/styleguide/layouts/carousel.html.erb", "app/views/minimum_viable_product/styleguide/layouts/cover.html.erb", "assets/js/application.js", "assets/js/init/controllers.js", "assets/js/init/forms.js", "bin/mvp", "bin/rails", "config/initializers/assets.rb", "config/initializers/canonical_host.rb", "config/initializers/cloudinary.rb", "config/initializers/geocoder.rb", "config/initializers/iteration.rb", "config/initializers/project.rb", "config/initializers/rollbar.rb", "config/initializers/routing.rb", "config/initializers/segment.rb", "config/initializers/spoof_ip.rb", "config/initializers/ssl.rb", "config/routes.rb", "lib/minimum_viable_product.rb", "lib/minimum_viable_product/engine.rb", "lib/minimum_viable_product/ext/nil.rb", "lib/minimum_viable_product/ext/string.rb", "lib/tasks/sitemap.rake", "minimum_viable_product.gemspec", "mvp.gemspec", "package.json", "test/helper.rb", "test/test_minimum_viable_product.rb" ] s.homepage = "http://github.com/ian/minimum_viable_product" s.licenses = ["MIT"] s.rubygems_version = "2.4.6" s.summary = "The start-to-finish 3 minute product platform" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<analytics-ruby>, [">= 0"]) s.add_runtime_dependency(%q<carrierwave>, [">= 0"]) s.add_runtime_dependency(%q<cloudinary>, [">= 0"]) s.add_runtime_dependency(%q<geocoder>, [">= 0"]) s.add_runtime_dependency(%q<faraday>, [">= 0"]) s.add_runtime_dependency(%q<fog>, [">= 0"]) s.add_runtime_dependency(%q<fog-aws>, [">= 0"]) s.add_runtime_dependency(%q<hashie>, [">= 0"]) s.add_runtime_dependency(%q<rack-canonical-host>, [">= 0"]) s.add_runtime_dependency(%q<rack-ssl-enforcer>, [">= 0"]) s.add_runtime_dependency(%q<rollbar>, [">= 0"]) s.add_runtime_dependency(%q<sass-rails>, ["~> 5.0"]) s.add_runtime_dependency(%q<sitemap_generator>, [">= 0"]) s.add_runtime_dependency(%q<slack-notifier>, [">= 0"]) s.add_development_dependency(%q<byebug>, [">= 0"]) s.add_development_dependency(%q<better_errors>, [">= 0"]) s.add_development_dependency(%q<binding_of_caller>, [">= 0"]) s.add_development_dependency(%q<bullet>, [">= 0"]) s.add_development_dependency(%q<semantic>, [">= 0"]) s.add_development_dependency(%q<web-console>, ["~> 2.0"]) s.add_development_dependency(%q<spring>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, ["~> 1.0"]) s.add_development_dependency(%q<jeweler>, ["~> 2.0.1"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) else s.add_dependency(%q<analytics-ruby>, [">= 0"]) s.add_dependency(%q<carrierwave>, [">= 0"]) s.add_dependency(%q<cloudinary>, [">= 0"]) s.add_dependency(%q<geocoder>, [">= 0"]) s.add_dependency(%q<faraday>, [">= 0"]) s.add_dependency(%q<fog>, [">= 0"]) s.add_dependency(%q<fog-aws>, [">= 0"]) s.add_dependency(%q<hashie>, [">= 0"]) s.add_dependency(%q<rack-canonical-host>, [">= 0"]) s.add_dependency(%q<rack-ssl-enforcer>, [">= 0"]) s.add_dependency(%q<rollbar>, [">= 0"]) s.add_dependency(%q<sass-rails>, ["~> 5.0"]) s.add_dependency(%q<sitemap_generator>, [">= 0"]) s.add_dependency(%q<slack-notifier>, [">= 0"]) s.add_dependency(%q<byebug>, [">= 0"]) s.add_dependency(%q<better_errors>, [">= 0"]) s.add_dependency(%q<binding_of_caller>, [">= 0"]) s.add_dependency(%q<bullet>, [">= 0"]) s.add_dependency(%q<semantic>, [">= 0"]) s.add_dependency(%q<web-console>, ["~> 2.0"]) s.add_dependency(%q<spring>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.0.1"]) s.add_dependency(%q<simplecov>, [">= 0"]) end else s.add_dependency(%q<analytics-ruby>, [">= 0"]) s.add_dependency(%q<carrierwave>, [">= 0"]) s.add_dependency(%q<cloudinary>, [">= 0"]) s.add_dependency(%q<geocoder>, [">= 0"]) s.add_dependency(%q<faraday>, [">= 0"]) s.add_dependency(%q<fog>, [">= 0"]) s.add_dependency(%q<fog-aws>, [">= 0"]) s.add_dependency(%q<hashie>, [">= 0"]) s.add_dependency(%q<rack-canonical-host>, [">= 0"]) s.add_dependency(%q<rack-ssl-enforcer>, [">= 0"]) s.add_dependency(%q<rollbar>, [">= 0"]) s.add_dependency(%q<sass-rails>, ["~> 5.0"]) s.add_dependency(%q<sitemap_generator>, [">= 0"]) s.add_dependency(%q<slack-notifier>, [">= 0"]) s.add_dependency(%q<byebug>, [">= 0"]) s.add_dependency(%q<better_errors>, [">= 0"]) s.add_dependency(%q<binding_of_caller>, [">= 0"]) s.add_dependency(%q<bullet>, [">= 0"]) s.add_dependency(%q<semantic>, [">= 0"]) s.add_dependency(%q<web-console>, ["~> 2.0"]) s.add_dependency(%q<spring>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.0.1"]) s.add_dependency(%q<simplecov>, [">= 0"]) end end
Gem::Specification.new do |s| s.name = 'string_hound' s.version = '0.1.0' s.platform = Gem::Platform::RUBY s.summary = "string_hound" s.description = "Bark! hunts for strings." s.authors = ["Noel Dellofano"] s.email = 'noel@zendesk.com' s.homepage = 'http://github.com/pinkvelociraptor/string_hound' s.files = [ "README", "Rakefile", "string_hound.gemspec", "lib/string_hound.rb", "lib/string_hound/tasks.rb", "test/string_hound_test.rb" ] s.test_files = ["test/string_hound_test.rb"] s.require_paths = [".", 'lib'] end version bump Gem::Specification.new do |s| s.name = 'string_hound' s.version = '0.1.1' s.platform = Gem::Platform::RUBY s.summary = "string_hound" s.description = "Bark! hunts for strings." s.authors = ["Noel Dellofano"] s.email = 'noel@zendesk.com' s.homepage = 'http://github.com/pinkvelociraptor/string_hound' s.files = [ "README", "Rakefile", "string_hound.gemspec", "lib/string_hound.rb", "lib/string_hound/tasks.rb", "test/string_hound_test.rb" ] s.test_files = ["test/string_hound_test.rb"] s.require_paths = [".", 'lib'] end
require 'ort' require 'matrix_job' class Optimizer def self.optimize(customer, planning, route) if Mapotempo::Application.config.delayed_job_use if customer.job_matrix # Customer already run an optimization false else customer.job_matrix = Delayed::Job.enqueue(MatrixJob.new(planning.id, route.id)) end else optimum = Ort.optimize(route.vehicle.capacity, route.matrix) if optimum route.order(optimum) route.save && route.reload # Refresh stops order planning.compute planning.save else false end end end end Skip optimization when there is nothing to optimize require 'ort' require 'matrix_job' class Optimizer def self.optimize(customer, planning, route) if route.size <= 3 # Nothing to optimize true elsif Mapotempo::Application.config.delayed_job_use if customer.job_matrix # Customer already run an optimization false else customer.job_matrix = Delayed::Job.enqueue(MatrixJob.new(planning.id, route.id)) end else optimum = Ort.optimize(route.vehicle.capacity, route.matrix) if optimum route.order(optimum) route.save && route.reload # Refresh stops order planning.compute planning.save else false end end end end
#!/usr/bin/env ruby require 'sinatra' require 'json' class StubApi < Sinatra::Base post '/api/session' do status 201 post_to_api(JSON.parse(request.body.read)['relayState']) end get '/api/session/:session_id/idp-list' do '[{ "simpleId":"stub-idp-one-doc-question", "entityId":"http://example.com/stub-idp-one-doc-question", "levelsOfAssurance": ["LEVEL_2"] }]' end put '/api/session/:session_id/select-idp' do '{ "encryptedEntityId":"not-blank" }' end get '/api/session/:session_id/country-authn-request' do '{ "location":"http://localhost:50300/test-saml", "samlRequest":"blah", "relayState":"whatever", "registration":false }' end get '/api/session/:session_id/idp-authn-request' do '{ "location":"http://localhost:50300/test-saml", "samlRequest":"blah", "relayState":"whatever", "registration":false }' end put '/api/session/:session_id/idp-authn-response' do '{ "idpResult":"blah", "isRegistration":false }' end get '/api/transactions' do '{ "public":[{ "simpleId":"test-rp", "entityId":"http://example.com/test-rp", "homepage":"http://example.com/test-rp", "loaList":["LEVEL_2"] }], "private":[], "transactions":[{ "simpleId":"test-rp", "entityId":"http://example.com/test-rp", "homepage":"http://example.com/test-rp", "loaList":["LEVEL_2"] }, { "simpleId": "loa1-test-rp", "entityId": "http://example.com/test-rp-loa1", "homepage":"http://example.com/test-rp-loa1", "loaList":["LEVEL_1","LEVEL_2"] } ] }' end get '/api/countries/blah' do '[{ "entityId":"http://nl-proxy-node-demo.cloudapps.digital/ServiceMetadata", "simpleId":"NL", "enabled":true }, { "entityId":"http://se-eidas.redsara.es/EidasNode/ServiceMetadata", "simpleId":"ES", "enabled":true }, { "entityId":"http://eunode.eidastest.se/EidasNode/ServiceMetadata", "simpleId":"SE", "enabled":false } ]' end post '/api/countries/:session_id/:countryCode' do status 200 '' end private def post_to_api(relay_state) level_of_assurance = relay_state == 'my-loa1-relay-state' ? 'LEVEL_1' : 'LEVEL_2' return "{ \"sessionId\":\"blah\", \"sessionStartTime\":32503680000000, \"transactionSimpleId\":\"test-rp\", \"levelsOfAssurance\":[\"#{level_of_assurance}\"], \"transactionSupportsEidas\": true }" end end TT-721 Reverting stub-api.rb Changing stub-api.rb so that it again uses stub-idp-one Authors: da39a3ee5e6b4b0d3255bfef95601890afd80709@kgarwood #!/usr/bin/env ruby require 'sinatra' require 'json' class StubApi < Sinatra::Base post '/api/session' do status 201 post_to_api(JSON.parse(request.body.read)['relayState']) end get '/api/session/:session_id/idp-list' do '[{ "simpleId":"stub-idp-one", "entityId":"http://example.com/stub-idp-one", "levelsOfAssurance": ["LEVEL_2"] }]' end put '/api/session/:session_id/select-idp' do '{ "encryptedEntityId":"not-blank" }' end get '/api/session/:session_id/country-authn-request' do '{ "location":"http://localhost:50300/test-saml", "samlRequest":"blah", "relayState":"whatever", "registration":false }' end get '/api/session/:session_id/idp-authn-request' do '{ "location":"http://localhost:50300/test-saml", "samlRequest":"blah", "relayState":"whatever", "registration":false }' end put '/api/session/:session_id/idp-authn-response' do '{ "idpResult":"blah", "isRegistration":false }' end get '/api/transactions' do '{ "public":[{ "simpleId":"test-rp", "entityId":"http://example.com/test-rp", "homepage":"http://example.com/test-rp", "loaList":["LEVEL_2"] }], "private":[], "transactions":[{ "simpleId":"test-rp", "entityId":"http://example.com/test-rp", "homepage":"http://example.com/test-rp", "loaList":["LEVEL_2"] }, { "simpleId": "loa1-test-rp", "entityId": "http://example.com/test-rp-loa1", "homepage":"http://example.com/test-rp-loa1", "loaList":["LEVEL_1","LEVEL_2"] } ] }' end get '/api/countries/blah' do '[{ "entityId":"http://nl-proxy-node-demo.cloudapps.digital/ServiceMetadata", "simpleId":"NL", "enabled":true }, { "entityId":"http://se-eidas.redsara.es/EidasNode/ServiceMetadata", "simpleId":"ES", "enabled":true }, { "entityId":"http://eunode.eidastest.se/EidasNode/ServiceMetadata", "simpleId":"SE", "enabled":false } ]' end post '/api/countries/:session_id/:countryCode' do status 200 '' end private def post_to_api(relay_state) level_of_assurance = relay_state == 'my-loa1-relay-state' ? 'LEVEL_1' : 'LEVEL_2' return "{ \"sessionId\":\"blah\", \"sessionStartTime\":32503680000000, \"transactionSimpleId\":\"test-rp\", \"levelsOfAssurance\":[\"#{level_of_assurance}\"], \"transactionSupportsEidas\": true }" end end
# # Cookbook Name:: monit # Resource:: check # require 'chef/resource' class Chef class Resource class MonitCheck < Chef::Resource identity_attr :name def initialize(name, run_context = nil) super @resource_name = :monit_check @provider = Chef::Provider::MonitCheck @action = :create @allowed_actions = [:create, :remove] @name = name end def cookbook(arg = nil) set_or_return( :cookbook, arg, :kind_of => String, :default => 'monit', ) end def check_type(arg = nil) set_or_return( :check_type, arg, :kind_of => String, :equal_to => check_pairs.keys, :default => 'process', ) end def check_id(arg = nil) set_or_return( :check_id, arg, :kind_of => String, :required => true, ) end def id_type(arg = nil) set_or_return( :id_type, arg, :kind_of => String, :equal_to => check_pairs.values, :default => check_pairs[check_type], :callbacks => { 'is a valid id type for the check type' => lambda do |spec| spec == check_pairs[check_type] end, }, ) end def start_as(arg = nil) set_or_return( :start_as, arg, :kind_of => String, ) end def start(arg = nil) set_or_return( :start, arg, :kind_of => String, :callbacks => { 'should not exceed max arg length' => lambda do |spec| spec.length < 127 end, }, ) end def stop(arg = nil) set_or_return( :stop, arg, :kind_of => String, :callbacks => { 'should not exceed max arg length' => lambda do |spec| spec.length < 127 end, }, ) end def group(arg = nil) set_or_return( :group, arg, :kind_of => String, ) end def tests(arg = nil) set_or_return( :tests, arg, :kind_of => Array, :default => [], ) end def every(arg = nil) set_or_return( :every, arg, :kind_of => String, ) end private def check_pairs { 'process' => 'pidfile', 'procmatch' => 'matching', 'file' => 'path', 'fifo' => 'path', 'filesystem' => 'path', 'directory' => 'path', 'host' => 'address', 'system' => nil, 'program' => 'path', } end end end end add cop exceptions # # Cookbook Name:: monit # Resource:: check # require 'chef/resource' class Chef class Resource # rubocop: disable ClassLength class MonitCheck < Chef::Resource identity_attr :name def initialize(name, run_context = nil) super @resource_name = :monit_check @provider = Chef::Provider::MonitCheck @action = :create @allowed_actions = [:create, :remove] @name = name end def cookbook(arg = nil) set_or_return( :cookbook, arg, :kind_of => String, :default => 'monit', ) end def check_type(arg = nil) set_or_return( :check_type, arg, :kind_of => String, :equal_to => check_pairs.keys, :default => 'process', ) end def check_id(arg = nil) set_or_return( :check_id, arg, :kind_of => String, :required => true, ) end # rubocop: disable MethodLength def id_type(arg = nil) set_or_return( :id_type, arg, :kind_of => String, :equal_to => check_pairs.values, :default => check_pairs[check_type], :callbacks => { 'is a valid id type for the check type' => lambda do |spec| spec == check_pairs[check_type] end, }, ) end # rubocop: enable MethodLength def start_as(arg = nil) set_or_return( :start_as, arg, :kind_of => String, ) end def start(arg = nil) set_or_return( :start, arg, :kind_of => String, :callbacks => { 'should not exceed max arg length' => lambda do |spec| spec.length < 127 end, }, ) end def stop(arg = nil) set_or_return( :stop, arg, :kind_of => String, :callbacks => { 'should not exceed max arg length' => lambda do |spec| spec.length < 127 end, }, ) end def group(arg = nil) set_or_return( :group, arg, :kind_of => String, ) end def tests(arg = nil) set_or_return( :tests, arg, :kind_of => Array, :default => [], ) end def every(arg = nil) set_or_return( :every, arg, :kind_of => String, ) end private def check_pairs { 'process' => 'pidfile', 'procmatch' => 'matching', 'file' => 'path', 'fifo' => 'path', 'filesystem' => 'path', 'directory' => 'path', 'host' => 'address', 'system' => nil, 'program' => 'path', } end end # rubocop: enable ClassLength end end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{mailchimp_ses} s.version = "1.0.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["David Balatero"] s.date = %q{2011-02-14} s.description = %q{Allows you to call MailChimp <-> Amazon SES integration methods.} s.email = %q{dbalatero@gmail.com} s.extra_rdoc_files = [ "LICENSE.txt", "README.md", "README.md.html" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.md", "Rakefile", "VERSION", "lib/mailchimp_ses.rb", "mailchimp_ses.gemspec", "spec/fixtures/vcr_cassettes/send_email.yml", "spec/mailchimp_ses_spec.rb", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/dbalatero/mailchimp_ses} s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{Gives API methods for MailChimp SES.} s.test_files = [ "spec/mailchimp_ses_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<monster_mash>, [">= 0.2.1"]) s.add_runtime_dependency(%q<json>, [">= 0"]) s.add_development_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<rcov>, [">= 0"]) s.add_development_dependency(%q<vcr>, [">= 0"]) s.add_development_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<vcr>, [">= 0"]) s.add_runtime_dependency(%q<monster_mash>, [">= 0.2.0"]) s.add_runtime_dependency(%q<json>, [">= 0"]) else s.add_dependency(%q<monster_mash>, [">= 0.2.1"]) s.add_dependency(%q<json>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<vcr>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<vcr>, [">= 0"]) s.add_dependency(%q<monster_mash>, [">= 0.2.0"]) s.add_dependency(%q<json>, [">= 0"]) end else s.add_dependency(%q<monster_mash>, [">= 0.2.1"]) s.add_dependency(%q<json>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<vcr>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<vcr>, [">= 0"]) s.add_dependency(%q<monster_mash>, [">= 0.2.0"]) s.add_dependency(%q<json>, [">= 0"]) end end gemspec 1.0.2 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{mailchimp_ses} s.version = "1.0.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["David Balatero"] s.date = %q{2011-02-19} s.description = %q{Allows you to call MailChimp <-> Amazon SES integration methods.} s.email = %q{dbalatero@gmail.com} s.extra_rdoc_files = [ "LICENSE.txt", "README.md", "README.md.html" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.md", "Rakefile", "VERSION", "lib/mailchimp_ses.rb", "mailchimp_ses.gemspec", "spec/fixtures/vcr_cassettes/send_email.yml", "spec/mailchimp_ses_spec.rb", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/dbalatero/mailchimp_ses} s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{Gives API methods for MailChimp SES.} s.test_files = [ "spec/mailchimp_ses_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<monster_mash>, [">= 0.2.2"]) s.add_runtime_dependency(%q<json>, [">= 0"]) s.add_development_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<rcov>, [">= 0"]) s.add_development_dependency(%q<vcr>, [">= 0"]) s.add_development_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<vcr>, [">= 0"]) s.add_runtime_dependency(%q<monster_mash>, [">= 0.2.2"]) s.add_runtime_dependency(%q<json>, [">= 0"]) else s.add_dependency(%q<monster_mash>, [">= 0.2.2"]) s.add_dependency(%q<json>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<vcr>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<vcr>, [">= 0"]) s.add_dependency(%q<monster_mash>, [">= 0.2.2"]) s.add_dependency(%q<json>, [">= 0"]) end else s.add_dependency(%q<monster_mash>, [">= 0.2.2"]) s.add_dependency(%q<json>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<vcr>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<vcr>, [">= 0"]) s.add_dependency(%q<monster_mash>, [">= 0.2.2"]) s.add_dependency(%q<json>, [">= 0"]) end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'gitlab_mr_release/version' Gem::Specification.new do |spec| spec.name = "gitlab_mr_release" spec.version = GitlabMrRelease::VERSION spec.authors = ["sue445"] spec.email = ["sue445@sue445.net"] spec.summary = %q{Release MergeRequest generator for GitLab} spec.description = %q{Release MergeRequest generator for GitLab} spec.homepage = "https://github.com/sue445/gitlab_mr_release" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_dependency "dotenv" spec.add_dependency "gitlab" spec.add_dependency "thor" spec.add_development_dependency "activesupport" spec.add_development_dependency "bundler", "~> 1.10" spec.add_development_dependency "coveralls" spec.add_development_dependency "codeclimate-test-reporter", "~> 1.0.0" spec.add_development_dependency "pry-byebug" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec" spec.add_development_dependency "simplecov" spec.add_development_dependency "webmock" end Use webmock 3.0.0+ # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'gitlab_mr_release/version' Gem::Specification.new do |spec| spec.name = "gitlab_mr_release" spec.version = GitlabMrRelease::VERSION spec.authors = ["sue445"] spec.email = ["sue445@sue445.net"] spec.summary = %q{Release MergeRequest generator for GitLab} spec.description = %q{Release MergeRequest generator for GitLab} spec.homepage = "https://github.com/sue445/gitlab_mr_release" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_dependency "dotenv" spec.add_dependency "gitlab" spec.add_dependency "thor" spec.add_development_dependency "activesupport" spec.add_development_dependency "bundler", "~> 1.10" spec.add_development_dependency "coveralls" spec.add_development_dependency "codeclimate-test-reporter", "~> 1.0.0" spec.add_development_dependency "pry-byebug" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec" spec.add_development_dependency "simplecov" spec.add_development_dependency "webmock", ">= 3.0.0" end
require 'json' require 'date' Pakyow::App.routes(:api) do include SharedRoutes expand :restful, :api, '/api' do collection do expand :restful, :v1, '/v1' do collection do expand :restful, :groups, '/groups' do member do expand :restful, :events, '/events' do action :list do if request.xhr? # respond to Ajax request nextThursday = Date.parse('Thursday') delta = nextThursday > Date.today ? 0 : 7 nextThursday = nextThursday + delta people = People[cookies[:people]] if people.nil? == false && people.admin time_limit = DateTime.now.utc else time_limit = if (nextThursday - Date.today) < 4 then nextThursday else DateTime.now.utc end end group_events = Event.where("group_id = ? AND start_datetime > ?", params[:groups_id], time_limit).all parent_group = Group.where("id = ?", params[:groups_id]).first unless parent_group.parent_id.nil? group_events.concat(Event.where("group_id = ? AND start_datetime > ?", parent_group.parent_id, time_limit).all) end response.write(group_events.to_json) else # respond to normal request redirect '/errors/403' end end end # expand :restful, :events, '/events' do end # member do end # expand :restful, :groups, '/groups' do get 'cwn_flyer' do # "approved":true, # "cwn":88, # "timestamp":"2017-01-09T20:27:22.161Z", # "group":"Designer's Corner", # "title":"CoWorking Night Tshirt Competition", # "description":"Come in to get some last minute ideas for your entry to the CoWorking Night Tshirt competition! ", # "date":"2017-01-11T06:00:00.000Z", # "time_req_form":"8:00 PM", # "time_req":"1899-12-31T01:48:52.000Z", # "room_req":"Milky Way Row", # "start_time":"2017-01-12T02:00:00.000Z", # "end_time":"2017-01-12T03:00:00.000Z", # "category":"Programming", # "icon":"terminal" #For now, we'll keep this only exposed for cwn cwn = Group.where("name = 'CoWorking Night'").first if cwn.nil? redirect '/errors/403' end #Now lets get all the events for this group. This means all of this group's events and its event's children next_cwn_event = Event.where("approved = true AND start_datetime > ? AND group_id = ?", DateTime.now.utc, cwn.id).order(:start_datetime).first events = get_child_events_for_event(next_cwn_event) response.write('[') first_time = true events.each { |event| if first_time == true first_time = false else response.write(',') end json = { "approved" => event.approved, "cwn" => next_cwn_event.instance_number, "timestamp" => event.created_at.utc, "group" => Group.where("id = ?", event.group_id).first.name, "title" => event.name, "description" => event.summary, "date" => event.start_datetime.utc, "time_req_form" => event.start_datetime.utc, "time_req" => event.start_datetime.utc, "room_req" => Venue.where("id = ?", event.venue_id).first.name, "start_time" => event.start_datetime.utc, "end_time" => (event.start_datetime.to_time + event.duration.hours).utc, "category" => event.flyer_category, "icon" => event.flyer_fa_icon } response.write(json.to_json) } response.write(']') end # get 'cwn_flyer' end # collection do end # expand :restful, :v1, '/v1' do end # collection do end # expand :restful, :api, '/api' do end # Pakyow::App.routes(:api) do Expose api endpoint to retrieve a specific cwn_flyer Expose api endpoint to retrieve a specific cwn_flyer require 'json' require 'date' Pakyow::App.routes(:api) do include SharedRoutes expand :restful, :api, '/api' do collection do expand :restful, :v1, '/v1' do collection do expand :restful, :groups, '/groups' do member do expand :restful, :events, '/events' do action :list do if request.xhr? # respond to Ajax request nextThursday = Date.parse('Thursday') delta = nextThursday > Date.today ? 0 : 7 nextThursday = nextThursday + delta people = People[cookies[:people]] if people.nil? == false && people.admin time_limit = DateTime.now.utc else time_limit = if (nextThursday - Date.today) < 4 then nextThursday else DateTime.now.utc end end group_events = Event.where("group_id = ? AND start_datetime > ?", params[:groups_id], time_limit).all parent_group = Group.where("id = ?", params[:groups_id]).first unless parent_group.parent_id.nil? group_events.concat(Event.where("group_id = ? AND start_datetime > ?", parent_group.parent_id, time_limit).all) end response.write(group_events.to_json) else # respond to normal request redirect '/errors/403' end end end # expand :restful, :events, '/events' do end # member do end # expand :restful, :groups, '/groups' do get 'cwn_flyer' do # "approved":true, # "cwn":88, # "timestamp":"2017-01-09T20:27:22.161Z", # "group":"Designer's Corner", # "title":"CoWorking Night Tshirt Competition", # "description":"Come in to get some last minute ideas for your entry to the CoWorking Night Tshirt competition! ", # "date":"2017-01-11T06:00:00.000Z", # "time_req_form":"8:00 PM", # "time_req":"1899-12-31T01:48:52.000Z", # "room_req":"Milky Way Row", # "start_time":"2017-01-12T02:00:00.000Z", # "end_time":"2017-01-12T03:00:00.000Z", # "category":"Programming", # "icon":"terminal" #For now, we'll keep this only exposed for cwn cwn = Group.where("name = 'CoWorking Night'").first if cwn.nil? redirect '/errors/403' end #Now lets get all the events for this group. This means all of this group's events and its event's children next_cwn_event = Event.where("approved = true AND start_datetime > ? AND group_id = ?", DateTime.now.utc, cwn.id).order(:start_datetime).first events = get_child_events_for_event(next_cwn_event) response.write('[') first_time = true events.each { |event| if first_time == true first_time = false else response.write(',') end json = { "approved" => event.approved, "cwn" => next_cwn_event.instance_number, "timestamp" => event.created_at.utc, "group" => Group.where("id = ?", event.group_id).first.name, "title" => event.name, "description" => event.summary, "date" => event.start_datetime.utc, "time_req_form" => event.start_datetime.utc, "time_req" => event.start_datetime.utc, "room_req" => Venue.where("id = ?", event.venue_id).first.name, "start_time" => event.start_datetime.utc, "end_time" => (event.start_datetime.to_time + event.duration.hours).utc, "category" => event.flyer_category, "icon" => event.flyer_fa_icon } response.write(json.to_json) } response.write(']') end # get 'cwn_flyer' get 'cwn_flyer/:cwn_instance_number' do # "approved":true, # "cwn":88, # "timestamp":"2017-01-09T20:27:22.161Z", # "group":"Designer's Corner", # "title":"CoWorking Night Tshirt Competition", # "description":"Come in to get some last minute ideas for your entry to the CoWorking Night Tshirt competition! ", # "date":"2017-01-11T06:00:00.000Z", # "time_req_form":"8:00 PM", # "time_req":"1899-12-31T01:48:52.000Z", # "room_req":"Milky Way Row", # "start_time":"2017-01-12T02:00:00.000Z", # "end_time":"2017-01-12T03:00:00.000Z", # "category":"Programming", # "icon":"terminal" #For now, we'll keep this only exposed for cwn cwn = Group.where("name = 'CoWorking Night'").first if cwn.nil? redirect '/errors/403' end #Now lets get all the events for this group. This means all of this group's events and its event's children cwn_event = Event.where("approved = true AND start_datetime > ? AND group_id = ? AND instance_number = ?", DateTime.now.utc, cwn.id, params[:cwn_instance_number]).order(:start_datetime).first events = get_child_events_for_event(cwn_event) response.write('[') first_time = true events.each { |event| if first_time == true first_time = false else response.write(',') end json = { "approved" => event.approved, "cwn" => cwn_event.instance_number, "timestamp" => event.created_at.utc, "group" => Group.where("id = ?", event.group_id).first.name, "title" => event.name, "description" => event.summary, "date" => event.start_datetime.utc, "time_req_form" => event.start_datetime.utc, "time_req" => event.start_datetime.utc, "room_req" => Venue.where("id = ?", event.venue_id).first.name, "start_time" => event.start_datetime.utc, "end_time" => (event.start_datetime.to_time + event.duration.hours).utc, "category" => event.flyer_category, "icon" => event.flyer_fa_icon } response.write(json.to_json) } response.write(']') end #get 'cwn_flyer/:cwn_instance_num' end # collection do end # expand :restful, :v1, '/v1' do end # collection do end # expand :restful, :api, '/api' do end # Pakyow::App.routes(:api) do
[DEMAD-145] Prueba correo subsanacion
class Notify < ActionMailer::Base include Emails::Issues include Emails::MergeRequests include Emails::Notes include Emails::Projects include Emails::Profile include Emails::Groups add_template_helper ApplicationHelper add_template_helper GitlabMarkdownHelper add_template_helper MergeRequestsHelper default_url_options[:host] = Gitlab.config.gitlab.host default_url_options[:protocol] = Gitlab.config.gitlab.protocol default_url_options[:port] = Gitlab.config.gitlab.port unless Gitlab.config.gitlab_on_standard_port? default_url_options[:script_name] = Gitlab.config.gitlab.relative_url_root default from: Gitlab.config.gitlab.email_from default reply_to: "noreply@#{Gitlab.config.gitlab.host}" # Just send email with 3 seconds delay def self.delay delay_for(2.seconds) end private # Look up a User by their ID and return their email address # # recipient_id - User ID # # Returns a String containing the User's email address. def recipient(recipient_id) if recipient = User.find(recipient_id) recipient.email end end # Formats arguments into a String suitable for use as an email subject # # extra - Extra Strings to be inserted into the subject # # Examples # # >> subject('Lorem ipsum') # => "GitLab | Lorem ipsum" # # # Automatically inserts Project name when @project is set # >> @project = Project.last # => #<Project id: 1, name: "Ruby on Rails", path: "ruby_on_rails", ...> # >> subject('Lorem ipsum') # => "GitLab | Ruby on Rails | Lorem ipsum " # # # Accepts multiple arguments # >> subject('Lorem ipsum', 'Dolor sit amet') # => "GitLab | Lorem ipsum | Dolor sit amet" def subject(*extra) subject = "GitLab" subject << (@project ? " | #{@project.name_with_namespace}" : "") subject << " | " + extra.join(' | ') if extra.present? subject end end Fix misleading comment class Notify < ActionMailer::Base include Emails::Issues include Emails::MergeRequests include Emails::Notes include Emails::Projects include Emails::Profile include Emails::Groups add_template_helper ApplicationHelper add_template_helper GitlabMarkdownHelper add_template_helper MergeRequestsHelper default_url_options[:host] = Gitlab.config.gitlab.host default_url_options[:protocol] = Gitlab.config.gitlab.protocol default_url_options[:port] = Gitlab.config.gitlab.port unless Gitlab.config.gitlab_on_standard_port? default_url_options[:script_name] = Gitlab.config.gitlab.relative_url_root default from: Gitlab.config.gitlab.email_from default reply_to: "noreply@#{Gitlab.config.gitlab.host}" # Just send email with 2 seconds delay def self.delay delay_for(2.seconds) end private # Look up a User by their ID and return their email address # # recipient_id - User ID # # Returns a String containing the User's email address. def recipient(recipient_id) if recipient = User.find(recipient_id) recipient.email end end # Formats arguments into a String suitable for use as an email subject # # extra - Extra Strings to be inserted into the subject # # Examples # # >> subject('Lorem ipsum') # => "GitLab | Lorem ipsum" # # # Automatically inserts Project name when @project is set # >> @project = Project.last # => #<Project id: 1, name: "Ruby on Rails", path: "ruby_on_rails", ...> # >> subject('Lorem ipsum') # => "GitLab | Ruby on Rails | Lorem ipsum " # # # Accepts multiple arguments # >> subject('Lorem ipsum', 'Dolor sit amet') # => "GitLab | Lorem ipsum | Dolor sit amet" def subject(*extra) subject = "GitLab" subject << (@project ? " | #{@project.name_with_namespace}" : "") subject << " | " + extra.join(' | ') if extra.present? subject end end
# # Cookbook Name:: mongodb # Definition:: mongodb # # Copyright 2011, edelight GmbH # Authors: # Markus Korn <markus.korn@edelight.de> # # 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. # define :mongodb_instance, :mongodb_type => "mongod" , :action => [:enable, :start], :bind_ip => nil, :port => 27017 , :logpath => "/var/log/mongodb", :dbpath => "/data", :configfile => nil, :configserver => [], :replicaset => nil, :enable_rest => false, :notifies => [] do include_recipe "mongodb::default" name = params[:name] type = params[:mongodb_type] service_action = params[:action] service_notifies = params[:notifies] bind_ip = params[:bind_ip] port = params[:port] logpath = params[:logpath] logfile = "#{logpath}/#{name}.log" dbpath = params[:dbpath] configfile = params[:configfile] configserver_nodes = params[:configserver] replicaset = params[:replicaset] nojournal = node['mongodb']['nojournal'] if type == "shard" if replicaset.nil? replicaset_name = nil else # for replicated shards we autogenerate the replicaset name for each shard replicaset_name = "rs_#{replicaset['mongodb']['shard_name']}" end else # if there is a predefined replicaset name we use it, # otherwise we try to generate one using 'rs_$SHARD_NAME' begin replicaset_name = replicaset['mongodb']['replicaset_name'] rescue replicaset_name = nil end if replicaset_name.nil? begin replicaset_name = "rs_#{replicaset['mongodb']['shard_name']}" rescue replicaset_name = nil end end end if !["mongod", "shard", "configserver", "mongos"].include?(type) raise "Unknown mongodb type '#{type}'" end if type != "mongos" daemon = "/usr/bin/mongod" configserver = nil else daemon = "/usr/bin/mongos" dbpath = nil configserver = configserver_nodes.collect{|n| "#{n['fqdn']}:#{n['mongodb']['port']}" }.join(",") end # default file template "#{node['mongodb']['defaults_dir']}/#{name}" do action :create source "mongodb.default.erb" group node['mongodb']['root_group'] owner "root" mode "0644" variables( "daemon_path" => daemon, "name" => name, "config" => configfile, "configdb" => configserver, "bind_ip" => bind_ip, "port" => port, "logpath" => logfile, "dbpath" => dbpath, "replicaset_name" => replicaset_name, "configsrv" => false, #type == "configserver", this might change the port "shardsrv" => false, #type == "shard", dito. "nojournal" => nojournal, "enable_rest" => params[:enable_rest] ) notifies :restart, "service[#{name}]" end # log dir [make sure it exists] directory logpath do owner node[:mongodb][:user] group node[:mongodb][:group] mode "0755" action :create recursive true end if type != "mongos" # dbpath dir [make sure it exists] directory dbpath do owner node[:mongodb][:user] group node[:mongodb][:group] mode "0755" action :create recursive true end end # init script template "#{node['mongodb']['init_dir']}/#{name}" do action :create source node[:mongodb][:init_script_template] group node['mongodb']['root_group'] owner "root" mode "0755" variables :provides => name notifies :restart, "service[#{name}]" end # service service name do supports :status => true, :restart => true action service_action service_notifies.each do |service_notify| notifies :run, service_notify end if !replicaset_name.nil? && node['mongodb']['auto_configure']['replicaset'] notifies :create, "ruby_block[config_replicaset]" end if type == "mongos" && node['mongodb']['auto_configure']['sharding'] notifies :create, "ruby_block[config_sharding]", :immediately end if name == "mongodb" # we don't care about a running mongodb service in these cases, all we need is stopping it ignore_failure true end end # replicaset if !replicaset_name.nil? && node['mongodb']['auto_configure']['replicaset'] rs_nodes = search( :node, "mongodb_cluster_name:#{replicaset['mongodb']['cluster_name']} AND \ recipes:mongodb\\:\\:replicaset AND \ mongodb_shard_name:#{replicaset['mongodb']['shard_name']} AND \ chef_environment:#{replicaset.chef_environment}" ) ruby_block "config_replicaset" do block do if not replicaset.nil? MongoDB.configure_replicaset(replicaset, replicaset_name, rs_nodes) end end action :nothing end end # sharding if type == "mongos" && node['mongodb']['auto_configure']['sharding'] # add all shards # configure the sharded collections shard_nodes = search( :node, "mongodb_cluster_name:#{node['mongodb']['cluster_name']} AND \ recipes:mongodb\\:\\:shard AND \ chef_environment:#{node.chef_environment}" ) ruby_block "config_sharding" do block do if type == "mongos" MongoDB.configure_shards(node, shard_nodes) MongoDB.configure_sharded_collections(node, node['mongodb']['sharded_collections']) end end action :nothing end end end sort config servers to mitigate MongoDB bug SERVER-5960 # # Cookbook Name:: mongodb # Definition:: mongodb # # Copyright 2011, edelight GmbH # Authors: # Markus Korn <markus.korn@edelight.de> # # 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. # define :mongodb_instance, :mongodb_type => "mongod" , :action => [:enable, :start], :bind_ip => nil, :port => 27017 , :logpath => "/var/log/mongodb", :dbpath => "/data", :configfile => nil, :configserver => [], :replicaset => nil, :enable_rest => false, :notifies => [] do include_recipe "mongodb::default" name = params[:name] type = params[:mongodb_type] service_action = params[:action] service_notifies = params[:notifies] bind_ip = params[:bind_ip] port = params[:port] logpath = params[:logpath] logfile = "#{logpath}/#{name}.log" dbpath = params[:dbpath] configfile = params[:configfile] configserver_nodes = params[:configserver] replicaset = params[:replicaset] nojournal = node['mongodb']['nojournal'] if type == "shard" if replicaset.nil? replicaset_name = nil else # for replicated shards we autogenerate the replicaset name for each shard replicaset_name = "rs_#{replicaset['mongodb']['shard_name']}" end else # if there is a predefined replicaset name we use it, # otherwise we try to generate one using 'rs_$SHARD_NAME' begin replicaset_name = replicaset['mongodb']['replicaset_name'] rescue replicaset_name = nil end if replicaset_name.nil? begin replicaset_name = "rs_#{replicaset['mongodb']['shard_name']}" rescue replicaset_name = nil end end end if !["mongod", "shard", "configserver", "mongos"].include?(type) raise "Unknown mongodb type '#{type}'" end if type != "mongos" daemon = "/usr/bin/mongod" configserver = nil else daemon = "/usr/bin/mongos" dbpath = nil configserver = configserver_nodes.collect{|n| "#{n['fqdn']}:#{n['mongodb']['port']}" }.sort.join(",") end # default file template "#{node['mongodb']['defaults_dir']}/#{name}" do action :create source "mongodb.default.erb" group node['mongodb']['root_group'] owner "root" mode "0644" variables( "daemon_path" => daemon, "name" => name, "config" => configfile, "configdb" => configserver, "bind_ip" => bind_ip, "port" => port, "logpath" => logfile, "dbpath" => dbpath, "replicaset_name" => replicaset_name, "configsrv" => false, #type == "configserver", this might change the port "shardsrv" => false, #type == "shard", dito. "nojournal" => nojournal, "enable_rest" => params[:enable_rest] ) notifies :restart, "service[#{name}]" end # log dir [make sure it exists] directory logpath do owner node[:mongodb][:user] group node[:mongodb][:group] mode "0755" action :create recursive true end if type != "mongos" # dbpath dir [make sure it exists] directory dbpath do owner node[:mongodb][:user] group node[:mongodb][:group] mode "0755" action :create recursive true end end # init script template "#{node['mongodb']['init_dir']}/#{name}" do action :create source node[:mongodb][:init_script_template] group node['mongodb']['root_group'] owner "root" mode "0755" variables :provides => name notifies :restart, "service[#{name}]" end # service service name do supports :status => true, :restart => true action service_action service_notifies.each do |service_notify| notifies :run, service_notify end if !replicaset_name.nil? && node['mongodb']['auto_configure']['replicaset'] notifies :create, "ruby_block[config_replicaset]" end if type == "mongos" && node['mongodb']['auto_configure']['sharding'] notifies :create, "ruby_block[config_sharding]", :immediately end if name == "mongodb" # we don't care about a running mongodb service in these cases, all we need is stopping it ignore_failure true end end # replicaset if !replicaset_name.nil? && node['mongodb']['auto_configure']['replicaset'] rs_nodes = search( :node, "mongodb_cluster_name:#{replicaset['mongodb']['cluster_name']} AND \ recipes:mongodb\\:\\:replicaset AND \ mongodb_shard_name:#{replicaset['mongodb']['shard_name']} AND \ chef_environment:#{replicaset.chef_environment}" ) ruby_block "config_replicaset" do block do if not replicaset.nil? MongoDB.configure_replicaset(replicaset, replicaset_name, rs_nodes) end end action :nothing end end # sharding if type == "mongos" && node['mongodb']['auto_configure']['sharding'] # add all shards # configure the sharded collections shard_nodes = search( :node, "mongodb_cluster_name:#{node['mongodb']['cluster_name']} AND \ recipes:mongodb\\:\\:shard AND \ chef_environment:#{node.chef_environment}" ) ruby_block "config_sharding" do block do if type == "mongos" MongoDB.configure_shards(node, shard_nodes) MongoDB.configure_sharded_collections(node, node['mongodb']['sharded_collections']) end end action :nothing end end end
# # Cookbook Name:: jenkins # Attributes:: server # # Author:: Doug MacEachern <dougm@vmware.com> # Author:: Fletcher Nichol <fnichol@nichol.ca> # Author:: Seth Chisamore <schisamo@opscode.com> # # Copyright 2010, VMware, Inc. # Copyright 2012, Opscode, Inc. # # 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. # default['jenkins']['server']['home'] = "/var/lib/jenkins" default['jenkins']['server']['data_dir'] = File.join(node['jenkins']['server']['home'], "jenkins-data") default['jenkins']['server']['log_dir'] = "/var/log/jenkins" default['jenkins']['server']['user'] = "jenkins" case node['platform_family'] when "debian" default['jenkins']['server']['group'] = "nogroup" else default['jenkins']['server']['group'] = node['jenkins']['server']['user'] end default['jenkins']['server']['version'] = :latest default['jenkins']['server']['war_checksum'] = nil default['jenkins']['server']['port'] = 8080 default['jenkins']['server']['host'] = node['fqdn'] default['jenkins']['server']['url'] = "http://#{node['jenkins']['server']['host']}:#{node['jenkins']['server']['port']}" default['jenkins']['server']['plugins'] = [] default['jenkins']['server']['jvm_options'] = nil default['jenkins']['http_proxy']['variant'] = nil default['jenkins']['http_proxy']['www_redirect'] = "disable" default['jenkins']['http_proxy']['listen_ports'] = [ 80 ] default['jenkins']['http_proxy']['host_name'] = nil default['jenkins']['http_proxy']['host_aliases'] = [] default['jenkins']['http_proxy']['client_max_body_size'] = "1024m" default['jenkins']['http_proxy']['basic_auth_username'] = "jenkins" default['jenkins']['http_proxy']['basic_auth_password'] = "jenkins" add set of default plugins to install # # Cookbook Name:: jenkins # Attributes:: server # # Author:: Doug MacEachern <dougm@vmware.com> # Author:: Fletcher Nichol <fnichol@nichol.ca> # Author:: Seth Chisamore <schisamo@opscode.com> # # Copyright 2010, VMware, Inc. # Copyright 2012, Opscode, Inc. # # 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. # default['jenkins']['server']['home'] = "/var/lib/jenkins" default['jenkins']['server']['data_dir'] = File.join(node['jenkins']['server']['home'], "jenkins-data") default['jenkins']['server']['log_dir'] = "/var/log/jenkins" default['jenkins']['server']['user'] = "jenkins" case node['platform_family'] when "debian" default['jenkins']['server']['group'] = "nogroup" else default['jenkins']['server']['group'] = node['jenkins']['server']['user'] end default['jenkins']['server']['version'] = :latest default['jenkins']['server']['war_checksum'] = nil default['jenkins']['server']['port'] = 8080 default['jenkins']['server']['host'] = node['fqdn'] default['jenkins']['server']['url'] = "http://#{node['jenkins']['server']['host']}:#{node['jenkins']['server']['port']}" default['jenkins']['server']['plugins'] = [ 'git', 'build-pipeline-plugin' ] default['jenkins']['server']['jvm_options'] = nil default['jenkins']['http_proxy']['variant'] = nil default['jenkins']['http_proxy']['www_redirect'] = "disable" default['jenkins']['http_proxy']['listen_ports'] = [ 80 ] default['jenkins']['http_proxy']['host_name'] = nil default['jenkins']['http_proxy']['host_aliases'] = [] default['jenkins']['http_proxy']['client_max_body_size'] = "1024m" default['jenkins']['http_proxy']['basic_auth_username'] = "jenkins" default['jenkins']['http_proxy']['basic_auth_password'] = "jenkins"
require "AllAboutFiles/version" module AllAboutFiles # Your code goes here... def AllAboutFiles.open file=ARGV[0] puts "Opening file:#{file}" myFile=File.open(file) puts myFile.read() end end opens files from local require "AllAboutFiles/version" module AllAboutFiles # Your code goes here... def AllAboutFiles.open file=ARGV[0] puts "Opening file:#{file}" myFile=File.open(file) puts myFile.read() end end
# Generated by jeweler # DO NOT EDIT THIS FILE # Instead, edit Jeweler::Tasks in Rakefile, and run `rake gemspec` # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{chatterbox} s.version = "0.3.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Rob Sanheim"] s.date = %q{2009-09-06} s.email = %q{rsanheim@gmail.com} s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".gitignore", ".treasure_map.rb", "LICENSE", "README.markdown", "Rakefile", "chatterbox.gemspec", "examples/chatterbox_example.rb", "examples/example_helper.rb", "examples/lib/chatterbox/consumers/email_consumer_example.rb", "examples/lib/chatterbox/notification_example.rb", "examples/lib/chatterbox/rails_catcher_example.rb", "init.rb", "lib/chatterbox.rb", "lib/chatterbox/notification.rb", "lib/chatterbox/rails_catcher.rb", "lib/consumers.rb", "lib/consumers/email_consumer.rb", "rails/init.rb", "todo.markdown", "version.yml", "views/chatterbox/mailer/exception_notification.erb" ] s.homepage = %q{http://github.com/relevance/chatterbox} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.5} s.summary = %q{TODO} s.test_files = [ "examples/chatterbox_example.rb", "examples/example_helper.rb", "examples/lib/chatterbox/consumers/email_consumer_example.rb", "examples/lib/chatterbox/notification_example.rb", "examples/lib/chatterbox/rails_catcher_example.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<mocha>, [">= 0"]) s.add_development_dependency(%q<actioncontroller>, [">= 0"]) s.add_development_dependency(%q<spicycode-micronaut>, [">= 0"]) s.add_development_dependency(%q<spicycode-micronaut-rails>, [">= 0"]) else s.add_dependency(%q<mocha>, [">= 0"]) s.add_dependency(%q<actioncontroller>, [">= 0"]) s.add_dependency(%q<spicycode-micronaut>, [">= 0"]) s.add_dependency(%q<spicycode-micronaut-rails>, [">= 0"]) end else s.add_dependency(%q<mocha>, [">= 0"]) s.add_dependency(%q<actioncontroller>, [">= 0"]) s.add_dependency(%q<spicycode-micronaut>, [">= 0"]) s.add_dependency(%q<spicycode-micronaut-rails>, [">= 0"]) end end Regenerated gemspec for version 0.3.3 # Generated by jeweler # DO NOT EDIT THIS FILE # Instead, edit Jeweler::Tasks in Rakefile, and run `rake gemspec` # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{chatterbox} s.version = "0.3.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Rob Sanheim"] s.date = %q{2009-10-05} s.email = %q{rsanheim@gmail.com} s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".gitignore", ".treasure_map.rb", "LICENSE", "README.markdown", "Rakefile", "chatterbox.gemspec", "examples/chatterbox_example.rb", "examples/example_helper.rb", "examples/lib/chatterbox/consumers/email_consumer_example.rb", "examples/lib/chatterbox/notification_example.rb", "examples/lib/chatterbox/rails_catcher_example.rb", "init.rb", "lib/chatterbox.rb", "lib/chatterbox/notification.rb", "lib/chatterbox/rails_catcher.rb", "lib/consumers.rb", "lib/consumers/email_consumer.rb", "rails/init.rb", "todo.markdown", "version.yml", "views/chatterbox/mailer/exception_notification.erb" ] s.homepage = %q{http://github.com/rsanheim/chatterbox} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.5} s.summary = %q{Notifications and messages} s.test_files = [ "examples/chatterbox_example.rb", "examples/example_helper.rb", "examples/lib/chatterbox/consumers/email_consumer_example.rb", "examples/lib/chatterbox/notification_example.rb", "examples/lib/chatterbox/rails_catcher_example.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<mocha>, [">= 0"]) s.add_development_dependency(%q<actioncontroller>, [">= 0"]) s.add_development_dependency(%q<spicycode-micronaut>, [">= 0"]) s.add_development_dependency(%q<spicycode-micronaut-rails>, [">= 0"]) else s.add_dependency(%q<mocha>, [">= 0"]) s.add_dependency(%q<actioncontroller>, [">= 0"]) s.add_dependency(%q<spicycode-micronaut>, [">= 0"]) s.add_dependency(%q<spicycode-micronaut-rails>, [">= 0"]) end else s.add_dependency(%q<mocha>, [">= 0"]) s.add_dependency(%q<actioncontroller>, [">= 0"]) s.add_dependency(%q<spicycode-micronaut>, [">= 0"]) s.add_dependency(%q<spicycode-micronaut-rails>, [">= 0"]) end end
# # Copyright 2008 Appcelerator, Inc. # # 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. # merge titanium config into the mainline config for SDK TITANIUM_CONFIG = YAML::load_file(File.join(TITANIUM_DIR,'config.yml')) TITANIUM_TRANSPORT = S3Transport.new(DISTRO_BUCKET, TITANIUM_CONFIG) TITANIUM_MANIFEST = TITANIUM_TRANSPORT.manifest TITANIUM_CONFIG[:releases] = build_config(TITANIUM_CONFIG,TITANIUM_MANIFEST) merge_config(TITANIUM_CONFIG) namespace :titanium do namespace :runtime do require File.join(TITANIUM_DIR,'runtime','build.rb') end require File.join(TITANIUM_DIR,'project','build.rb') end added dev target: titanium:dev # # Copyright 2008 Appcelerator, Inc. # # 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. # merge titanium config into the mainline config for SDK TITANIUM_CONFIG = YAML::load_file(File.join(TITANIUM_DIR,'config.yml')) TITANIUM_TRANSPORT = S3Transport.new(DISTRO_BUCKET, TITANIUM_CONFIG) TITANIUM_MANIFEST = TITANIUM_TRANSPORT.manifest TITANIUM_CONFIG[:releases] = build_config(TITANIUM_CONFIG,TITANIUM_MANIFEST) merge_config(TITANIUM_CONFIG) namespace :titanium do namespace :runtime do require File.join(TITANIUM_DIR,'runtime','build.rb') end require File.join(TITANIUM_DIR,'project','build.rb') task :dev do Rake::Task["service:titanium"].invoke Rake::Task["titanium:runtime:#{platform_string}"].invoke Rake::Task["titanium:project"].invoke ts = get_config(:service,:titanium) system "app install:service #{ts[:output_filename]} --force" tp = get_config(:titanium,:project) system "app install:titanium #{tp[:output_filename]} --force" tr = get_config(:titanium,platform_string.to_sym) system "app install:titanium #{tr[:output_filename]} --force" end end
module RubyMotionQuery class RMQ # @return [Device] def device Device end # @return [Device] def self.device Device end end class Device class << self # @return [UIScreen] def screen UIScreen.mainScreen end # @return [Numeric] def width @_width ||= Device.screen.bounds.size.width end # @return [Numeric] def height @_height ||= Device.screen.bounds.size.height end def screen_width portrait? ? screen.bounds.size.width : screen.bounds.size.height end def screen_height portrait? ? screen.bounds.size.height : screen.bounds.size.width end def ipad? @_ipad = (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) if @_ipad.nil? @_ipad end def iphone? @_iphone = (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPhone) if @_iphone.nil? @_iphone end def simulator? @_simulator = !(UIDevice.currentDevice.model =~ /simulator/i).nil? if @_simulator.nil? @_simulator end def three_point_five_inch? @_three_point_five_inch = (Device.height == 480.0) if @_three_point_five_inch.nil? @_three_point_five_inch end def four_inch? @_four_inch = (Device.height == 568.0) if @_four_inch.nil? @_four_inch end def four_point_seven_inch? @_four_point_seven_inch = (Device.height == 667.0) if @_four_point_seven_inch.nil? @_four_point_seven_inch end def five_point_five_inch? @_five_point_five_inch = (Device.height == 736.0) if @_five_point_five_inch.nil? @_five_point_five_inch end def retina? if @_retina.nil? main_screen = Device.screen @_retina = !!(main_screen.respondsToSelector('displayLinkWithTarget:selector:') && main_screen.scale == 2.0) end @_retina end # @return :unknown or from ORIENTATIONS def orientation orientation = UIApplication.sharedApplication.statusBarOrientation ORIENTATIONS[orientation] || :unknown end def landscape? Device.orientation == :landscape_left || Device.orientation == :landscape_right end def portrait? Device.orientation == :portrait || Device.orientation == :unknown end def orientations ORIENTATIONS end ORIENTATIONS = { UIDeviceOrientationUnknown => :unknown, UIDeviceOrientationPortrait => :portrait, UIDeviceOrientationPortraitUpsideDown => :portrait_upside_down, UIDeviceOrientationLandscapeLeft => :landscape_left, UIDeviceOrientationLandscapeRight => :landscape_right, UIDeviceOrientationFaceUp => :face_up, UIDeviceOrientationFaceDown => :face_down } end end end Added rmq.device.ios_eight? I didn't test it, not sure how I'd do that module RubyMotionQuery class RMQ # @return [Device] def device Device end # @return [Device] def self.device Device end end class Device class << self def ios_eight? @_ios_eight ||= screen.respond_to?(:coordinateSpace) end # @return [UIScreen] def screen UIScreen.mainScreen end # Width is the width of the device, regardless of its orientation. # This is static. If you want the width with the correct orientation, use # screen_width # # @return [Numeric] def width @_width ||= Device.screen.bounds.size.width end # Height is the height of the device, regardless of its orientation. # This is static. If you want the height with the correct orientation, use # screen_height # # @return [Numeric] def height @_height ||= Device.screen.bounds.size.height end # @return [Numeric] def screen_width portrait? ? screen.bounds.size.width : screen.bounds.size.height end # @return [Numeric] def screen_height portrait? ? screen.bounds.size.height : screen.bounds.size.width end def ipad? @_ipad = (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) if @_ipad.nil? @_ipad end def iphone? @_iphone = (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPhone) if @_iphone.nil? @_iphone end def simulator? @_simulator = !(UIDevice.currentDevice.model =~ /simulator/i).nil? if @_simulator.nil? @_simulator end def three_point_five_inch? @_three_point_five_inch = (Device.height == 480.0) if @_three_point_five_inch.nil? @_three_point_five_inch end def four_inch? @_four_inch = (Device.height == 568.0) if @_four_inch.nil? @_four_inch end def four_point_seven_inch? @_four_point_seven_inch = (Device.height == 667.0) if @_four_point_seven_inch.nil? @_four_point_seven_inch end def five_point_five_inch? @_five_point_five_inch = (Device.height == 736.0) if @_five_point_five_inch.nil? @_five_point_five_inch end def retina? if @_retina.nil? main_screen = Device.screen @_retina = !!(main_screen.respondsToSelector('displayLinkWithTarget:selector:') && main_screen.scale == 2.0) end @_retina end # @return :unknown or from ORIENTATIONS def orientation orientation = UIApplication.sharedApplication.statusBarOrientation ORIENTATIONS[orientation] || :unknown end def landscape? Device.orientation == :landscape_left || Device.orientation == :landscape_right end def portrait? Device.orientation == :portrait || Device.orientation == :unknown end def orientations ORIENTATIONS end ORIENTATIONS = { UIDeviceOrientationUnknown => :unknown, UIDeviceOrientationPortrait => :portrait, UIDeviceOrientationPortraitUpsideDown => :portrait_upside_down, UIDeviceOrientationLandscapeLeft => :landscape_left, UIDeviceOrientationLandscapeRight => :landscape_right, UIDeviceOrientationFaceUp => :face_up, UIDeviceOrientationFaceDown => :face_down } end end end
# Last Modified: 2017.07.01 /coding: utf-8 # frozen_string_literal: true # Copyright © 2016-2017 Exosite LLC. # License: MIT. See LICENSE.txt. # vim:tw=0:ts=2:sw=2:et:ai require 'certified' if Gem.win_platform? require 'date' require 'json' require 'net/http' require 'uri' # 2017-06-07: [lb] getting "execution expired (Net::OpenTimeout)" on http.start. # Suggestions online say to load the pure-Ruby DNS implementation, resolv.rb. require 'resolv-replace' module MrMurano module Http def token return @token unless @token.nil? acc = Account.new @token = acc.token raise 'Not logged in!' if @token.nil? # MAYBE: Check that ADC is enabled on the business. If not, tell # user to run Murano 2.x. See adc_compat_check for comments. #acc.adc_compat_check @token end def json_opts return @json_opts unless not defined?(@json_opts) or @json_opts.nil? @json_opts = { :allow_nan => true, :symbolize_names => true, :create_additions => false } end def curldebug(request) if $cfg['tool.curldebug'] formp = (request.content_type =~ %r{multipart/form-data}) a = [] a << %{curl -s} if request.key?('Authorization') a << %{-H 'Authorization: #{request['Authorization']}'} end a << %{-H 'User-Agent: #{request['User-Agent']}'} a << %{-H 'Content-Type: #{request.content_type}'} unless formp a << %{-X #{request.method}} a << %{'#{request.uri.to_s}'} unless request.body.nil? if formp m = request.body.match(%r{form-data;\s+name="(?<name>[^"]+)";\s+filename="(?<filename>[^"]+)"}) a << %{-F #{m[:name]}=@#{m[:filename]}} unless m.nil? else a << %{-d '#{request.body}'} end end if $cfg['tool.curlfile_f'].nil? puts a.join(' ') else $cfg['tool.curlfile_f'] << a.join(' ') + "\n\n" $cfg['tool.curlfile_f'].flush end end end # Default endpoint unless Class overrides it. def endPoint(path) URI('https://' + $cfg['net.host'] + '/api:1/' + path.to_s) end def http uri = URI('https://' + $cfg['net.host']) if not defined?(@http) or @http.nil? @http = Net::HTTP.new(uri.host, uri.port) @http.use_ssl = true @http.start end @http end def http_reset @http = nil end def set_def_headers(request) request.content_type = 'application/json' request['Authorization'] = 'token ' + token request['User-Agent'] = "MrMurano/#{MrMurano::VERSION}" request end def isJSON(data) begin [true, JSON.parse(data, json_opts)] rescue [false, data] end end def showHttpError(request, response) if $cfg['tool.debug'] puts "Sent #{request.method} #{request.uri.to_s}" request.each_capitalized{|k,v| puts "> #{k}: #{v}"} if request.body.nil? else puts ">> #{request.body[0..156]}" end puts "Got #{response.code} #{response.message}" response.each_capitalized{|k,v| puts "< #{k}: #{v}"} end isj, jsn = isJSON(response.body) resp = "Request Failed: #{response.code}: " if isj if $cfg['tool.fullerror'] resp << JSON.pretty_generate(jsn) elsif jsn.kind_of? Hash resp << "[#{jsn[:statusCode]}] " if jsn.has_key? :statusCode resp << jsn[:message] if jsn.has_key? :message else resp << jsn.to_s end else resp << (jsn or 'nil') end # assuming verbosing was included. error resp end def workit(request, no_error: false, &block) curldebug(request) if block_given? yield request, http() else response = http().request(request) case response when Net::HTTPSuccess workit_response(response) else unless @suppress_error || no_error showHttpError(request, response) end nil end end end def workit_response(response) return {} if response.body.nil? begin JSON.parse(response.body, json_opts) rescue response.body end end def get(path='', query=nil, no_error: false, &block) uri = endPoint(path) uri.query = URI.encode_www_form(query) unless query.nil? workit(set_def_headers(Net::HTTP::Get.new(uri)), no_error: no_error, &block) end def post(path='', body={}, &block) uri = endPoint(path) req = Net::HTTP::Post.new(uri) set_def_headers(req) req.body = JSON.generate(body) workit(req, &block) end def postf(path='', form={}, &block) uri = endPoint(path) req = Net::HTTP::Post.new(uri) set_def_headers(req) req.content_type = 'application/x-www-form-urlencoded; charset=utf-8' req.form_data = form workit(req, &block) end def put(path='', body={}, &block) uri = endPoint(path) req = Net::HTTP::Put.new(uri) set_def_headers(req) req.body = JSON.generate(body) workit(req, &block) end def patch(path='', body={}, &block) uri = endPoint(path) req = Net::HTTP::Patch.new(uri) set_def_headers(req) req.body = JSON.generate(body) workit(req, &block) end def delete(path='', &block) uri = endPoint(path) workit(set_def_headers(Net::HTTP::Delete.new(uri)), &block) end end end # There is a bug were not having TCP_NODELAY set causes connection issues with # Murano. While ultimatily the bug is up there, we need to work around it down # here. As for Ruby, setting TCP_NODELAY was added in 2.1. But since the default # version installed on macos is 2.0.0 we hit it. # # So, if the current version of Ruby is 2.0.0, then use this bit of code I copied # from Ruby 2.1. if RUBY_VERSION == '2.0.0' module Net class HTTP def connect if proxy? conn_address = proxy_address conn_port = proxy_port else conn_address = address conn_port = port end D "opening connection to #{conn_address}:#{conn_port}..." s = Timeout.timeout(@open_timeout, Net::OpenTimeout) { TCPSocket.open(conn_address, conn_port, @local_host, @local_port) } s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) D "opened" if use_ssl? ssl_parameters = Hash.new iv_list = instance_variables SSL_IVNAMES.each_with_index do |ivname, i| if iv_list.include?(ivname) and value = instance_variable_get(ivname) ssl_parameters[SSL_ATTRIBUTES[i]] = value if value end end @ssl_context = OpenSSL::SSL::SSLContext.new @ssl_context.set_params(ssl_parameters) D "starting SSL for #{conn_address}:#{conn_port}..." s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context) s.sync_close = true D "SSL established" end @socket = BufferedIO.new(s) @socket.read_timeout = @read_timeout @socket.continue_timeout = @continue_timeout @socket.debug_output = @debug_output if use_ssl? begin if proxy? buf = "CONNECT #{@address}:#{@port} HTTP/#{HTTPVersion}\r\n" buf << "Host: #{@address}:#{@port}\r\n" if proxy_user credential = ["#{proxy_user}:#{proxy_pass}"].pack('m') credential.delete!("\r\n") buf << "Proxy-Authorization: Basic #{credential}\r\n" end buf << "\r\n" @socket.write(buf) HTTPResponse.read_new(@socket).value end # Server Name Indication (SNI) RFC 3546 s.hostname = @address if s.respond_to? :hostname= if @ssl_session and Time.now < @ssl_session.time + @ssl_session.timeout s.session = @ssl_session if @ssl_session end Timeout.timeout(@open_timeout, Net::OpenTimeout) { s.connect } if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE s.post_connection_check(@address) end @ssl_session = s.session rescue => exception D "Conn close because of connect error #{exception}" @socket.close if @socket and not @socket.closed? raise exception end end on_connect end end end end Rewrap long comment. # Last Modified: 2017.07.01 /coding: utf-8 # frozen_string_literal: true # Copyright © 2016-2017 Exosite LLC. # License: MIT. See LICENSE.txt. # vim:tw=0:ts=2:sw=2:et:ai require 'certified' if Gem.win_platform? require 'date' require 'json' require 'net/http' require 'uri' # 2017-06-07: [lb] getting "execution expired (Net::OpenTimeout)" on http.start. # Suggestions online say to load the pure-Ruby DNS implementation, resolv.rb. require 'resolv-replace' module MrMurano module Http def token return @token unless @token.nil? acc = Account.new @token = acc.token raise 'Not logged in!' if @token.nil? # MAYBE: Check that ADC is enabled on the business. If not, tell # user to run Murano 2.x. See adc_compat_check for comments. #acc.adc_compat_check @token end def json_opts return @json_opts unless not defined?(@json_opts) or @json_opts.nil? @json_opts = { :allow_nan => true, :symbolize_names => true, :create_additions => false } end def curldebug(request) if $cfg['tool.curldebug'] formp = (request.content_type =~ %r{multipart/form-data}) a = [] a << %{curl -s} if request.key?('Authorization') a << %{-H 'Authorization: #{request['Authorization']}'} end a << %{-H 'User-Agent: #{request['User-Agent']}'} a << %{-H 'Content-Type: #{request.content_type}'} unless formp a << %{-X #{request.method}} a << %{'#{request.uri.to_s}'} unless request.body.nil? if formp m = request.body.match(%r{form-data;\s+name="(?<name>[^"]+)";\s+filename="(?<filename>[^"]+)"}) a << %{-F #{m[:name]}=@#{m[:filename]}} unless m.nil? else a << %{-d '#{request.body}'} end end if $cfg['tool.curlfile_f'].nil? puts a.join(' ') else $cfg['tool.curlfile_f'] << a.join(' ') + "\n\n" $cfg['tool.curlfile_f'].flush end end end # Default endpoint unless Class overrides it. def endPoint(path) URI('https://' + $cfg['net.host'] + '/api:1/' + path.to_s) end def http uri = URI('https://' + $cfg['net.host']) if not defined?(@http) or @http.nil? @http = Net::HTTP.new(uri.host, uri.port) @http.use_ssl = true @http.start end @http end def http_reset @http = nil end def set_def_headers(request) request.content_type = 'application/json' request['Authorization'] = 'token ' + token request['User-Agent'] = "MrMurano/#{MrMurano::VERSION}" request end def isJSON(data) begin [true, JSON.parse(data, json_opts)] rescue [false, data] end end def showHttpError(request, response) if $cfg['tool.debug'] puts "Sent #{request.method} #{request.uri.to_s}" request.each_capitalized{|k,v| puts "> #{k}: #{v}"} if request.body.nil? else puts ">> #{request.body[0..156]}" end puts "Got #{response.code} #{response.message}" response.each_capitalized{|k,v| puts "< #{k}: #{v}"} end isj, jsn = isJSON(response.body) resp = "Request Failed: #{response.code}: " if isj if $cfg['tool.fullerror'] resp << JSON.pretty_generate(jsn) elsif jsn.kind_of? Hash resp << "[#{jsn[:statusCode]}] " if jsn.has_key? :statusCode resp << jsn[:message] if jsn.has_key? :message else resp << jsn.to_s end else resp << (jsn or 'nil') end # assuming verbosing was included. error resp end def workit(request, no_error: false, &block) curldebug(request) if block_given? yield request, http() else response = http().request(request) case response when Net::HTTPSuccess workit_response(response) else unless @suppress_error || no_error showHttpError(request, response) end nil end end end def workit_response(response) return {} if response.body.nil? begin JSON.parse(response.body, json_opts) rescue response.body end end def get(path='', query=nil, no_error: false, &block) uri = endPoint(path) uri.query = URI.encode_www_form(query) unless query.nil? workit(set_def_headers(Net::HTTP::Get.new(uri)), no_error: no_error, &block) end def post(path='', body={}, &block) uri = endPoint(path) req = Net::HTTP::Post.new(uri) set_def_headers(req) req.body = JSON.generate(body) workit(req, &block) end def postf(path='', form={}, &block) uri = endPoint(path) req = Net::HTTP::Post.new(uri) set_def_headers(req) req.content_type = 'application/x-www-form-urlencoded; charset=utf-8' req.form_data = form workit(req, &block) end def put(path='', body={}, &block) uri = endPoint(path) req = Net::HTTP::Put.new(uri) set_def_headers(req) req.body = JSON.generate(body) workit(req, &block) end def patch(path='', body={}, &block) uri = endPoint(path) req = Net::HTTP::Patch.new(uri) set_def_headers(req) req.body = JSON.generate(body) workit(req, &block) end def delete(path='', &block) uri = endPoint(path) workit(set_def_headers(Net::HTTP::Delete.new(uri)), &block) end end end # There is a bug where having TCP_NODELAY disabled causes connection issues # with Murano. While ultimately the bug is Murano's, we need to work around # here. As for Ruby, setting TCP_NODELAY was added in 2.1. But since the # default version installed on MacOS is 2.0.0, we oftentimes hit it. # # So, if the current version of Ruby is 2.0.0, then use this bit of code # copied from Ruby 2.1 (lib/net/http.rb, at line 868). if RUBY_VERSION == '2.0.0' module Net class HTTP def connect if proxy? conn_address = proxy_address conn_port = proxy_port else conn_address = address conn_port = port end D "opening connection to #{conn_address}:#{conn_port}..." s = Timeout.timeout(@open_timeout, Net::OpenTimeout) { TCPSocket.open(conn_address, conn_port, @local_host, @local_port) } s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) D "opened" if use_ssl? ssl_parameters = Hash.new iv_list = instance_variables SSL_IVNAMES.each_with_index do |ivname, i| if iv_list.include?(ivname) and value = instance_variable_get(ivname) ssl_parameters[SSL_ATTRIBUTES[i]] = value if value end end @ssl_context = OpenSSL::SSL::SSLContext.new @ssl_context.set_params(ssl_parameters) D "starting SSL for #{conn_address}:#{conn_port}..." s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context) s.sync_close = true D "SSL established" end @socket = BufferedIO.new(s) @socket.read_timeout = @read_timeout @socket.continue_timeout = @continue_timeout @socket.debug_output = @debug_output if use_ssl? begin if proxy? buf = "CONNECT #{@address}:#{@port} HTTP/#{HTTPVersion}\r\n" buf << "Host: #{@address}:#{@port}\r\n" if proxy_user credential = ["#{proxy_user}:#{proxy_pass}"].pack('m') credential.delete!("\r\n") buf << "Proxy-Authorization: Basic #{credential}\r\n" end buf << "\r\n" @socket.write(buf) HTTPResponse.read_new(@socket).value end # Server Name Indication (SNI) RFC 3546 s.hostname = @address if s.respond_to? :hostname= if @ssl_session and Time.now < @ssl_session.time + @ssl_session.timeout s.session = @ssl_session if @ssl_session end Timeout.timeout(@open_timeout, Net::OpenTimeout) { s.connect } if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE s.post_connection_check(@address) end @ssl_session = s.session rescue => exception D "Conn close because of connect error #{exception}" @socket.close if @socket and not @socket.closed? raise exception end end on_connect end end end end
class Tree::TreeNode def remove_range!(range) self.children[range].each do |child| self.remove!(child) end end def leaf_nodes [].tap do |leaves| each_leaf do |leaf| leaves << leaf if leaf.is_leaf? end end.compact end def str leaf_nodes.map(&:content) end def node_list each { |n| n }.map { |n| n } end def contains?(leaf) leaf_nodes.map(&:name).include? leaf end def index_at_parent return 0 unless self.parent self.parent.children.index(self) end def child_names self.children.map(&:content) end def match(component) if component[:regex] !(component[:regex] =~ self.content).nil? else self.content == component[:string] end end def scan(pattern, verb) component_matches = matches_for_pattern_components(pattern) valid_sequences = valid_component_sequences(component_matches) matches = sequences_to_matches(component_matches, valid_sequences) scores = scores_sequences(valid_sequences) matches = matches.each_with_index.to_a.map do |match, index| component_matches = [] match.each_with_index do |sub_match, index| component_matches << { pattern: pattern.components[index], tree: sub_match } end { string: match_string(component_matches), frame: pattern.pattern_string, verb: verb, score: scores[index], component_matches: component_matches } end matches.select! { |m| m[:string].include? verb[:text] } return matches end private def match_string(component_matches) component_matches.map do |component_match| component_match[:tree].str end.flatten.join(" ") end # array of hashes, keys link indexes to trees def matches_for_pattern_components(pattern) tree_index = node_list [].tap do |component_matches| pattern.components.each do |component| nodes = Hash.new tree_index.each_with_index do |node, index| range = node.leaf_nodes.map { |n| tree_index.index(n) }.sort nodes[range] = node if node.match(component) end component_matches << nodes end end end # generates valid sequences of component indexes # additional complexity due to removal of invalid combinations # invalid if: not ordered, not correct type at pattern index def valid_component_sequences(component_matches) indexes = component_matches.map(&:keys) all_matches_for_indexes = indexes.reduce(:+).combination(indexes.size).to_a [].tap do |valid_sequences| all_matches_for_indexes.to_a.each do |c| next unless c == c.sort_by { |x| x.last } next unless c == c.sort_by { |x| x.first } valid = true indexes.each_with_index do |component_match, index| valid = false unless component_match.include? c[index] end valid_sequences << c if valid end end.reject { |m| m.flatten.uniq != m.flatten }.uniq end # take sequences and get the components for the index values def sequences_to_matches(components, sequences) sequences.map do |sequence| [].tap do |match| sequence.each_with_index do |key, index| match << components[index][key] end end end end def scores_sequences(sequence_list) leaf_map = each { |n| n }.map { |n| n }.map {|n| n.is_leaf? } sequence_list.map do |m| distances = [] m.each_with_index do |c, i| break unless m[i+1] range = c.last+1...m[i+1].first distances << leaf_map[range].count(true) end 1 - (distances.reduce(:+).to_f / m.size) end end end Correct indexing of tree nodes in matching Motivation: -"I am fat and I like cats" wasn't working correctly as only the first 'I' was ever detected. Change Explanation: -now the indexing is done on the object_id since I think having a duplicate node name results in a match. class Tree::TreeNode def remove_range!(range) self.children[range].each do |child| self.remove!(child) end end def leaf_nodes [].tap do |leaves| each_leaf do |leaf| leaves << leaf if leaf.is_leaf? end end.compact end def str leaf_nodes.map(&:content) end def node_list each { |n| n }.map { |n| n } end def contains?(leaf) leaf_nodes.map(&:name).include? leaf end def index_at_parent return 0 unless self.parent self.parent.children.index(self) end def child_names self.children.map(&:content) end def match(component) if component[:regex] !(component[:regex] =~ self.content).nil? else self.content == component[:string] end end def scan(pattern, verb) component_matches = matches_for_pattern_components(pattern) valid_sequences = valid_component_sequences(component_matches) matches = sequences_to_matches(component_matches, valid_sequences) scores = scores_sequences(valid_sequences) matches = matches.each_with_index.to_a.map do |match, index| component_matches = [] match.each_with_index do |sub_match, index| component_matches << { pattern: pattern.components[index], tree: sub_match } end { string: match_string(component_matches), frame: pattern.pattern_string, verb: verb, score: scores[index], component_matches: component_matches } end matches.select! { |m| m[:string].include? verb[:text] } return matches end private def match_string(component_matches) component_matches.map do |component_match| component_match[:tree].str end.flatten.join(" ") end # array of hashes, keys link indexes to trees def matches_for_pattern_components(pattern) tree_index = node_list [].tap do |component_matches| pattern.components.each do |component| nodes = Hash.new tree_index.each_with_index do |node, index| range = node.leaf_nodes.map do |n| tree_index.map(&:object_id).index(n.object_id) end.sort nodes[range] = node if node.match(component) end component_matches << nodes end end end # generates valid sequences of component indexes # additional complexity due to removal of invalid combinations # invalid if: not ordered, not correct type at pattern index def valid_component_sequences(component_matches) indexes = component_matches.map(&:keys) all_matches_for_indexes = indexes.reduce(:+).combination(indexes.size).to_a [].tap do |valid_sequences| all_matches_for_indexes.to_a.each do |c| next unless c == c.sort_by { |x| x.last } next unless c == c.sort_by { |x| x.first } valid = true indexes.each_with_index do |component_match, index| valid = false unless component_match.include? c[index] end valid_sequences << c if valid end end.reject { |m| m.flatten.uniq != m.flatten }.uniq end # take sequences and get the components for the index values def sequences_to_matches(components, sequences) sequences.map do |sequence| [].tap do |match| sequence.each_with_index do |key, index| match << components[index][key] end end end end def scores_sequences(sequence_list) leaf_map = each { |n| n }.map { |n| n }.map {|n| n.is_leaf? } sequence_list.map do |m| distances = [] m.each_with_index do |c, i| break unless m[i+1] range = c.last+1...m[i+1].first distances << leaf_map[range].count(true) end 1 - (distances.reduce(:+).to_f / m.size) end end end
class CreateStuffs < ActiveRecord::Migration def self.up enable_extension 'hstore' unless extension_enable?('json') enable_extension 'json' unless extension_enable?('json') create_table :stuffs do |t| t.integer :location_id, null: true t.integer :category_jd, null: true t.text :name, null: false t.decimal :price, null: false t.integer :quantity, null: false t.json :categories, null: true t.timestamps null: false end add_index :location_id, :category_id end def self.down drop_table :stuffs end end update migration class CreateStuffs < ActiveRecord::Migration def self.up enable_extension 'hstore' unless extension_enable?('hstore') enable_extension 'json' unless extension_enable?('json') create_table :stuffs do |t| t.integer :location_id, null: true t.integer :category_jd, null: true t.text :name, null: false t.decimal :price, null: false t.integer :quantity, null: false t.json :categories, null: true t.timestamps null: false end add_index :location_id, :category_id end def self.down drop_table :stuffs end end
class CreateSipity < ActiveRecord::Migration def change create_table "sipity_notification_recipients" do |t| t.integer "notification_id", null: false t.integer "role_id", null: false t.string "recipient_strategy", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_notification_recipients", ["notification_id", "role_id", "recipient_strategy"], name: "sipity_notifications_recipients_surrogate" add_index "sipity_notification_recipients", ["notification_id"], name: "sipity_notification_recipients_notification" add_index "sipity_notification_recipients", ["recipient_strategy"], name: "sipity_notification_recipients_recipient_strategy" add_index "sipity_notification_recipients", ["role_id"], name: "sipity_notification_recipients_role" create_table "sipity_notifications" do |t| t.string "name", null: false t.string "notification_type", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_notifications", ["name"], name: "index_sipity_notifications_on_name", unique: true add_index "sipity_notifications", ["notification_type"], name: "index_sipity_notifications_on_notification_type" create_table "sipity_notifiable_contexts" do |t| t.integer "scope_for_notification_id", null: false t.string "scope_for_notification_type", null: false t.string "reason_for_notification", null: false t.integer "notification_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_notifiable_contexts", ["notification_id"], name: "sipity_notifiable_contexts_notification_id" add_index "sipity_notifiable_contexts", ["scope_for_notification_id", "scope_for_notification_type", "reason_for_notification", "notification_id"], name: "sipity_notifiable_contexts_concern_surrogate", unique: true add_index "sipity_notifiable_contexts", ["scope_for_notification_id", "scope_for_notification_type", "reason_for_notification"], name: "sipity_notifiable_contexts_concern_context" add_index "sipity_notifiable_contexts", ["scope_for_notification_id", "scope_for_notification_type"], name: "sipity_notifiable_contexts_concern" create_table "sipity_agents" do |t| t.string "proxy_for_id", null: false t.string "proxy_for_type", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_agents", ["proxy_for_id", "proxy_for_type"], name: "sipity_agents_proxy_for", unique: true create_table "sipity_comments" do |t| t.integer "entity_id", null: false t.integer "agent_id", null: false t.text "comment" t.integer "originating_workflow_action_id", null: false t.integer "originating_workflow_state_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.boolean "stale", default: false end add_index "sipity_comments", ["agent_id"], name: "index_sipity_comments_on_agent_id" add_index "sipity_comments", ["created_at"], name: "index_sipity_comments_on_created_at" add_index "sipity_comments", ["entity_id"], name: "index_sipity_comments_on_entity_id" add_index "sipity_comments", ["originating_workflow_action_id"], name: "sipity_comments_action_index" add_index "sipity_comments", ["originating_workflow_state_id"], name: "sipity_comments_state_index" create_table "sipity_entities" do |t| t.string "proxy_for_global_id", null: false t.integer "workflow_id", null: false t.integer "workflow_state_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_entities", ["proxy_for_global_id"], name: "sipity_entities_proxy_for_global_id", unique: true add_index "sipity_entities", ["workflow_id"], name: "index_sipity_entities_on_workflow_id" add_index "sipity_entities", ["workflow_state_id"], name: "index_sipity_entities_on_workflow_state_id" create_table "sipity_entity_specific_responsibilities" do |t| t.integer "workflow_role_id", null: false t.string "entity_id", null: false t.integer "agent_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_entity_specific_responsibilities", ["agent_id"], name: "sipity_entity_specific_responsibilities_agent" add_index "sipity_entity_specific_responsibilities", ["entity_id"], name: "sipity_entity_specific_responsibilities_entity" add_index "sipity_entity_specific_responsibilities", ["workflow_role_id", "entity_id", "agent_id"], name: "sipity_entity_specific_responsibilities_aggregate", unique: true add_index "sipity_entity_specific_responsibilities", ["workflow_role_id"], name: "sipity_entity_specific_responsibilities_role" create_table "sipity_workflows" do |t| t.string "name", null: false t.text "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflows", ["name"], name: "index_sipity_workflows_on_name", unique: true create_table "sipity_workflow_actions" do |t| t.integer "workflow_id", null: false t.integer "resulting_workflow_state_id" t.string "name", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_actions", ["resulting_workflow_state_id"], name: "sipity_workflow_actions_resulting_workflow_state" add_index "sipity_workflow_actions", ["workflow_id", "name"], name: "sipity_workflow_actions_aggregate", unique: true add_index "sipity_workflow_actions", ["workflow_id"], name: "sipity_workflow_actions_workflow" create_table "sipity_workflow_responsibilities" do |t| t.integer "agent_id", null: false t.integer "workflow_role_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_responsibilities", ["agent_id", "workflow_role_id"], name: "sipity_workflow_responsibilities_aggregate", unique: true create_table "sipity_workflow_roles" do |t| t.integer "workflow_id", null: false t.integer "role_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_roles", ["workflow_id", "role_id"], name: "sipity_workflow_roles_aggregate", unique: true create_table "sipity_workflow_state_action_permissions" do |t| t.integer "workflow_role_id", null: false t.integer "workflow_state_action_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_state_action_permissions", ["workflow_role_id", "workflow_state_action_id"], name: "sipity_workflow_state_action_permissions_aggregate", unique: true create_table "sipity_workflow_state_actions" do |t| t.integer "originating_workflow_state_id", null: false t.integer "workflow_action_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_state_actions", ["originating_workflow_state_id", "workflow_action_id"], name: "sipity_workflow_state_actions_aggregate", unique: true create_table "sipity_workflow_states" do |t| t.integer "workflow_id", null: false t.string "name", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_states", ["name"], name: "index_sipity_workflow_states_on_name" add_index "sipity_workflow_states", ["workflow_id", "name"], name: "sipity_type_state_aggregate", unique: true create_table "sipity_roles" do |t| t.string "name", null: false t.text "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_roles", ["name"], name: "index_sipity_roles_on_name", unique: true end end Updating data migration to remove unneeded fields These were a requirement of Sipity to show comments for certain stages. We have opted to instead continue to show comments throughout the entire lifecycle of the workflow. class CreateSipity < ActiveRecord::Migration def change create_table "sipity_notification_recipients" do |t| t.integer "notification_id", null: false t.integer "role_id", null: false t.string "recipient_strategy", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_notification_recipients", ["notification_id", "role_id", "recipient_strategy"], name: "sipity_notifications_recipients_surrogate" add_index "sipity_notification_recipients", ["notification_id"], name: "sipity_notification_recipients_notification" add_index "sipity_notification_recipients", ["recipient_strategy"], name: "sipity_notification_recipients_recipient_strategy" add_index "sipity_notification_recipients", ["role_id"], name: "sipity_notification_recipients_role" create_table "sipity_notifications" do |t| t.string "name", null: false t.string "notification_type", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_notifications", ["name"], name: "index_sipity_notifications_on_name", unique: true add_index "sipity_notifications", ["notification_type"], name: "index_sipity_notifications_on_notification_type" create_table "sipity_notifiable_contexts" do |t| t.integer "scope_for_notification_id", null: false t.string "scope_for_notification_type", null: false t.string "reason_for_notification", null: false t.integer "notification_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_notifiable_contexts", ["notification_id"], name: "sipity_notifiable_contexts_notification_id" add_index "sipity_notifiable_contexts", ["scope_for_notification_id", "scope_for_notification_type", "reason_for_notification", "notification_id"], name: "sipity_notifiable_contexts_concern_surrogate", unique: true add_index "sipity_notifiable_contexts", ["scope_for_notification_id", "scope_for_notification_type", "reason_for_notification"], name: "sipity_notifiable_contexts_concern_context" add_index "sipity_notifiable_contexts", ["scope_for_notification_id", "scope_for_notification_type"], name: "sipity_notifiable_contexts_concern" create_table "sipity_agents" do |t| t.string "proxy_for_id", null: false t.string "proxy_for_type", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_agents", ["proxy_for_id", "proxy_for_type"], name: "sipity_agents_proxy_for", unique: true create_table "sipity_comments" do |t| t.integer "entity_id", null: false t.integer "agent_id", null: false t.text "comment" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_comments", ["agent_id"], name: "index_sipity_comments_on_agent_id" add_index "sipity_comments", ["created_at"], name: "index_sipity_comments_on_created_at" add_index "sipity_comments", ["entity_id"], name: "index_sipity_comments_on_entity_id" create_table "sipity_entities" do |t| t.string "proxy_for_global_id", null: false t.integer "workflow_id", null: false t.integer "workflow_state_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_entities", ["proxy_for_global_id"], name: "sipity_entities_proxy_for_global_id", unique: true add_index "sipity_entities", ["workflow_id"], name: "index_sipity_entities_on_workflow_id" add_index "sipity_entities", ["workflow_state_id"], name: "index_sipity_entities_on_workflow_state_id" create_table "sipity_entity_specific_responsibilities" do |t| t.integer "workflow_role_id", null: false t.string "entity_id", null: false t.integer "agent_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_entity_specific_responsibilities", ["agent_id"], name: "sipity_entity_specific_responsibilities_agent" add_index "sipity_entity_specific_responsibilities", ["entity_id"], name: "sipity_entity_specific_responsibilities_entity" add_index "sipity_entity_specific_responsibilities", ["workflow_role_id", "entity_id", "agent_id"], name: "sipity_entity_specific_responsibilities_aggregate", unique: true add_index "sipity_entity_specific_responsibilities", ["workflow_role_id"], name: "sipity_entity_specific_responsibilities_role" create_table "sipity_workflows" do |t| t.string "name", null: false t.text "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflows", ["name"], name: "index_sipity_workflows_on_name", unique: true create_table "sipity_workflow_actions" do |t| t.integer "workflow_id", null: false t.integer "resulting_workflow_state_id" t.string "name", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_actions", ["resulting_workflow_state_id"], name: "sipity_workflow_actions_resulting_workflow_state" add_index "sipity_workflow_actions", ["workflow_id", "name"], name: "sipity_workflow_actions_aggregate", unique: true add_index "sipity_workflow_actions", ["workflow_id"], name: "sipity_workflow_actions_workflow" create_table "sipity_workflow_responsibilities" do |t| t.integer "agent_id", null: false t.integer "workflow_role_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_responsibilities", ["agent_id", "workflow_role_id"], name: "sipity_workflow_responsibilities_aggregate", unique: true create_table "sipity_workflow_roles" do |t| t.integer "workflow_id", null: false t.integer "role_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_roles", ["workflow_id", "role_id"], name: "sipity_workflow_roles_aggregate", unique: true create_table "sipity_workflow_state_action_permissions" do |t| t.integer "workflow_role_id", null: false t.integer "workflow_state_action_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_state_action_permissions", ["workflow_role_id", "workflow_state_action_id"], name: "sipity_workflow_state_action_permissions_aggregate", unique: true create_table "sipity_workflow_state_actions" do |t| t.integer "originating_workflow_state_id", null: false t.integer "workflow_action_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_state_actions", ["originating_workflow_state_id", "workflow_action_id"], name: "sipity_workflow_state_actions_aggregate", unique: true create_table "sipity_workflow_states" do |t| t.integer "workflow_id", null: false t.string "name", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_workflow_states", ["name"], name: "index_sipity_workflow_states_on_name" add_index "sipity_workflow_states", ["workflow_id", "name"], name: "sipity_type_state_aggregate", unique: true create_table "sipity_roles" do |t| t.string "name", null: false t.text "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "sipity_roles", ["name"], name: "index_sipity_roles_on_name", unique: true end end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "google-api-client" s.version = "0.7.0.rc2" s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version= s.authors = ["Bob Aman", "Steve Bazyl"] s.date = "2013-09-09" s.description = "The Google API Ruby Client makes it trivial to discover and access supported\nAPIs.\n" s.email = "sbazyl@google.com" s.executables = ["google-api"] s.extra_rdoc_files = ["README.md"] s.files = ["lib/cacerts.pem", "lib/compat", "lib/compat/multi_json.rb", "lib/google", "lib/google/api_client", "lib/google/api_client.rb", "lib/google/api_client/auth", "lib/google/api_client/auth/compute_service_account.rb", "lib/google/api_client/auth/storage.rb", "lib/google/api_client/file_storage.rb" "lib/google/api_client/auth/storages/file_store.rb", "lib/google/api_client/auth/storages/redis_store.rb", "lib/google/api_client/auth/installed_app.rb", "lib/google/api_client/auth/jwt_asserter.rb", "lib/google/api_client/auth/key_utils.rb", "lib/google/api_client/auth/pkcs12.rb", "lib/google/api_client/batch.rb", "lib/google/api_client/client_secrets.rb", "lib/google/api_client/discovery", "lib/google/api_client/discovery.rb", "lib/google/api_client/discovery/api.rb", "lib/google/api_client/discovery/media.rb", "lib/google/api_client/discovery/method.rb", "lib/google/api_client/discovery/resource.rb", "lib/google/api_client/discovery/schema.rb", "lib/google/api_client/environment.rb", "lib/google/api_client/errors.rb", "lib/google/api_client/gzip.rb", "lib/google/api_client/logging.rb", "lib/google/api_client/media.rb", "lib/google/api_client/railtie.rb", "lib/google/api_client/reference.rb", "lib/google/api_client/request.rb", "lib/google/api_client/result.rb", "lib/google/api_client/service_account.rb", "lib/google/api_client/version.rb", "lib/google/inflection.rb", "spec/fixtures", "spec/fixtures/files", "spec/fixtures/files/privatekey.p12", "spec/fixtures/files/sample.txt", "spec/fixtures/files/secret.pem", "spec/google", "spec/google/api_client", "spec/google/api_client/batch_spec.rb", "spec/google/api_client/discovery_spec.rb", "spec/google/api_client/gzip_spec.rb", "spec/google/api_client/media_spec.rb", "spec/google/api_client/request_spec.rb", "spec/google/api_client/result_spec.rb", "spec/google/api_client/service_account_spec.rb", "spec/google/api_client_spec.rb", "spec/spec_helper.rb", "tasks/gem.rake", "tasks/git.rake", "tasks/metrics.rake", "tasks/spec.rake", "tasks/wiki.rake", "tasks/yard.rake", "CHANGELOG.md", "CONTRIBUTING.md", "Gemfile", "LICENSE", "README.md", "Rakefile", "bin/google-api"] s.homepage = "http://code.google.com/p/google-api-ruby-client/" s.licenses = ["Apache 2.0"] s.rdoc_options = ["--main", "README.md"] s.require_paths = ["lib"] s.rubygems_version = "2.0.7" s.summary = "Package Summary" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<signet>, [">= 0.5.0"]) s.add_runtime_dependency(%q<addressable>, [">= 2.3.2"]) s.add_runtime_dependency(%q<uuidtools>, [">= 2.1.0"]) s.add_runtime_dependency(%q<autoparse>, [">= 0.3.3"]) s.add_runtime_dependency(%q<faraday>, [">= 0.9.0.rc5"]) s.add_runtime_dependency(%q<multi_json>, [">= 1.0.0"]) s.add_runtime_dependency(%q<extlib>, [">= 0.9.15"]) s.add_runtime_dependency(%q<jwt>, [">= 0.1.5"]) s.add_runtime_dependency(%q<launchy>, [">= 2.1.1"]) s.add_development_dependency(%q<rake>, [">= 0.9.0"]) s.add_development_dependency(%q<rspec>, [">= 2.11.0"]) else s.add_dependency(%q<signet>, [">= 0.5.0"]) s.add_dependency(%q<addressable>, [">= 2.3.2"]) s.add_dependency(%q<uuidtools>, [">= 2.1.0"]) s.add_dependency(%q<autoparse>, [">= 0.3.3"]) s.add_dependency(%q<faraday>, [">= 0.9.0.rc5"]) s.add_dependency(%q<multi_json>, [">= 1.0.0"]) s.add_dependency(%q<extlib>, [">= 0.9.15"]) s.add_dependency(%q<jwt>, [">= 0.1.5"]) s.add_dependency(%q<launchy>, [">= 2.1.1"]) s.add_dependency(%q<rake>, [">= 0.9.0"]) s.add_dependency(%q<rspec>, [">= 2.11.0"]) end else s.add_dependency(%q<signet>, [">= 0.5.0"]) s.add_dependency(%q<addressable>, [">= 2.3.2"]) s.add_dependency(%q<uuidtools>, [">= 2.1.0"]) s.add_dependency(%q<autoparse>, [">= 0.3.3"]) s.add_dependency(%q<faraday>, [">= 0.9.0.rc5"]) s.add_dependency(%q<multi_json>, [">= 1.0.0"]) s.add_dependency(%q<extlib>, [">= 0.9.15"]) s.add_dependency(%q<jwt>, [">= 0.1.5"]) s.add_dependency(%q<launchy>, [">= 2.1.1"]) s.add_dependency(%q<rake>, [">= 0.9.0"]) s.add_dependency(%q<rspec>, [">= 2.11.0"]) end end include all git added files to prevent inclusion errors # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "google-api-client" s.version = "0.7.0.rc2" s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version= s.authors = ["Bob Aman", "Steve Bazyl"] s.date = "2013-09-09" s.description = "The Google API Ruby Client makes it trivial to discover and access supported\nAPIs.\n" s.email = "sbazyl@google.com" s.executables = ["google-api"] s.extra_rdoc_files = ["README.md"] s.files = `git ls-files`.split($/) s.homepage = "http://code.google.com/p/google-api-ruby-client/" s.licenses = ["Apache 2.0"] s.rdoc_options = ["--main", "README.md"] s.require_paths = ["lib"] s.rubygems_version = "2.0.7" s.summary = "Package Summary" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<signet>, [">= 0.5.0"]) s.add_runtime_dependency(%q<addressable>, [">= 2.3.2"]) s.add_runtime_dependency(%q<uuidtools>, [">= 2.1.0"]) s.add_runtime_dependency(%q<autoparse>, [">= 0.3.3"]) s.add_runtime_dependency(%q<faraday>, [">= 0.9.0.rc5"]) s.add_runtime_dependency(%q<multi_json>, [">= 1.0.0"]) s.add_runtime_dependency(%q<extlib>, [">= 0.9.15"]) s.add_runtime_dependency(%q<jwt>, [">= 0.1.5"]) s.add_runtime_dependency(%q<launchy>, [">= 2.1.1"]) s.add_development_dependency(%q<rake>, [">= 0.9.0"]) s.add_development_dependency(%q<rspec>, [">= 2.11.0"]) else s.add_dependency(%q<signet>, [">= 0.5.0"]) s.add_dependency(%q<addressable>, [">= 2.3.2"]) s.add_dependency(%q<uuidtools>, [">= 2.1.0"]) s.add_dependency(%q<autoparse>, [">= 0.3.3"]) s.add_dependency(%q<faraday>, [">= 0.9.0.rc5"]) s.add_dependency(%q<multi_json>, [">= 1.0.0"]) s.add_dependency(%q<extlib>, [">= 0.9.15"]) s.add_dependency(%q<jwt>, [">= 0.1.5"]) s.add_dependency(%q<launchy>, [">= 2.1.1"]) s.add_dependency(%q<rake>, [">= 0.9.0"]) s.add_dependency(%q<rspec>, [">= 2.11.0"]) end else s.add_dependency(%q<signet>, [">= 0.5.0"]) s.add_dependency(%q<addressable>, [">= 2.3.2"]) s.add_dependency(%q<uuidtools>, [">= 2.1.0"]) s.add_dependency(%q<autoparse>, [">= 0.3.3"]) s.add_dependency(%q<faraday>, [">= 0.9.0.rc5"]) s.add_dependency(%q<multi_json>, [">= 1.0.0"]) s.add_dependency(%q<extlib>, [">= 0.9.15"]) s.add_dependency(%q<jwt>, [">= 0.1.5"]) s.add_dependency(%q<launchy>, [">= 2.1.1"]) s.add_dependency(%q<rake>, [">= 0.9.0"]) s.add_dependency(%q<rspec>, [">= 2.11.0"]) end end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "fullcalendar_engine/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "fullcalendar_engine" s.version = FullcalendarEngine::VERSION s.authors = ["TODO: Your name"] s.email = ["TODO: Your email"] s.homepage = "TODO" s.summary = "TODO: Summary of FullcalendarEngine." s.description = "TODO: Description of FullcalendarEngine." s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.0.1" s.add_development_dependency "sqlite3" end update Gemspec $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "fullcalendar_engine/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "fullcalendar_engine" s.version = FullcalendarEngine::VERSION s.authors = ["Team Vinsol"] s.email = ["info@vinsol.com"] s.homepage = "http://vinsol.com" s.summary = "Engine Implementation of jQuery Full Calendar" s.description = "Engine Implementation of jQuery Full Calendar" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.0.1" s.add_development_dependency "sqlite3" end
# See https://github.com/openminds/apache_config. module Apache autoload :Node, 'apache_config/node' autoload :VirtualHost, 'apache_config/virtual_host' autoload :WriteBackArray, 'apache_config/write_back_array' class Config TabSize = " " Comment = /^\s*#\s?(.*?)\s*$/ Blank = /^\s+$/ Directive = /^\s*(\w+)(?:\s+(.*?)|)$/ SectionOpen = /^\s*<\s*(\w+)(?:\s+([^>]+)|\s*)>$/ SectionClose = /^\s*<\/\s*(\w+)\s*>$/ attr_reader :path def initialize(path) @path = path @config = parse_config(path) end def virtual_hosts @config.children.map { |vh| VirtualHost.new(vh) } end def save! File.open(@path, 'w') do |f| f.write to_config end end def to_config(root = nil, indent = "") element = root || @config content = "" case when element.isRoot? element.children.map { |c| to_config(c) }.join when element.hasChildren? "#{indent}<#{element.name} #{element.content}>\n" + element.children.map {|c| to_config(c, indent + TabSize) }.join + "#{indent}</#{element.name}>\n" when element.name == :comment "#{indent}# #{element.content}\n" when element.name == :blank "#{indent}\n" else "#{indent}#{element.name} #{element.content}\n" end end private def parse_config(path) current_child = Node.new("ROOT") File.open(path).read.split(/\n/).each do |line| case line when Comment current_child << Node.new(:comment, $1) when Blank current_child << Node.new(:blank) when Directive current_child << Node.new($1, $2) when SectionOpen current_child = current_child << Node.new($1, $2) when SectionClose current_child = current_child.parent end end current_child end end end Update apache_config.rb # See https://github.com/glebm/apache_config. module Apache autoload :Node, 'apache_config/node' autoload :VirtualHost, 'apache_config/virtual_host' autoload :WriteBackArray, 'apache_config/write_back_array' class Config TabSize = " " Comment = /^\s*#\s?(.*?)\s*$/ Blank = /^\s+$/ Directive = /^\s*(\w+)(?:\s+(.*?)|)$/ SectionOpen = /^\s*<\s*(\w+)(?:\s+([^>]+)|\s*)>$/ SectionClose = /^\s*<\/\s*(\w+)\s*>$/ attr_reader :path def initialize(path) @path = path @config = parse_config(path) end def virtual_hosts @config.children.map { |vh| VirtualHost.new(vh) } end def save! File.open(@path, 'w') do |f| f.write to_config end end def to_config(root = nil, indent = "") element = root || @config content = "" case when element.isRoot? element.children.map { |c| to_config(c) }.join when element.hasChildren? "#{indent}<#{element.name} #{element.content}>\n" + element.children.map {|c| to_config(c, indent + TabSize) }.join + "#{indent}</#{element.name}>\n" when element.name == :comment "#{indent}# #{element.content}\n" when element.name == :blank "#{indent}\n" else "#{indent}#{element.name} #{element.content}\n" end end private def parse_config(path) current_child = Node.new("ROOT") File.open(path).read.split(/\n/).each do |line| case line when Comment current_child << Node.new(:comment, $1) when Blank current_child << Node.new(:blank) when Directive current_child << Node.new($1, $2) when SectionOpen current_child = current_child << Node.new($1, $2) when SectionClose current_child = current_child.parent end end current_child end end end
module Arena VERSION = "0.1.2" def self.version VERSION end end Bumps version module Arena VERSION = "0.1.3" def self.version VERSION end end
#:nodoc: module Asana # Public: Version of the gem. VERSION = '0.9.1' end Bump version #:nodoc: module Asana # Public: Version of the gem. VERSION = '0.9.2' end
module Asset # The Router class is a small Rack middleware that matches the asset URLs # and serves the content, compressed if you are in production mode. class Router # Mime types for responses MIME = {'js' => 'application/javascript;charset=utf-8', 'css' => 'text/css;charset=utf-8', 'txt' => 'text/plain;charset=utf-8'} # Init def initialize(app) @app = app end # Call def call(env) # Setting up request @request = Rack::Request.new(env) # The routes case @request.path_info # Match /assets?/:type/path when /^(\/assets)?\/(js|css)\/(.+)/ # Extract type and path type, path = $2, $3 # Extract digest key and remove from path path.gsub!("-#{@key = $1}", '') if path =~ /-([a-f0-9]{32})\.(css|js)$/ # Find the item item = ::Asset.manifest.find{|i| i.path == path and i.type == type} # Return the content or not found item ? found(item) : not_found # Bounce favicon requests when (::Asset.favicon and /^\/favicon\.ico$/) not_found # Return a standard robots.txt when (::Asset.robots and /^\/robots\.txt$/) robots else # No routes found, pass down the middleware stack @app.call(env) end end private # Found def found(item) content = item.content(!!@key) [ 200, {'Content-Type' => MIME[item.type], 'Content-Length' => content.size, 'Cache-Control' => 'public, max-age=86400', 'Expires' => (Time.now.utc + (86400 * 30)).httpdate, 'Last-Modified' => item.modified.httpdate, }, [content]] end # Not found def not_found(path = '@') [404, {'Content-Type' => MIME['txt'], 'Content-Length' => 0}, []] end # Robots def robots s = %{Sitemap: #{@request.scheme}://#{@request.host}/sitemap.xml} [200, {'Content-Type' => MIME['txt'],'Content-Length' => s.size}, [s]] end end end Removed unused parameter module Asset # The Router class is a small Rack middleware that matches the asset URLs # and serves the content, compressed if you are in production mode. class Router # Mime types for responses MIME = {'js' => 'application/javascript;charset=utf-8', 'css' => 'text/css;charset=utf-8', 'txt' => 'text/plain;charset=utf-8'} # Init def initialize(app) @app = app end # Call def call(env) # Setting up request @request = Rack::Request.new(env) # The routes case @request.path_info # Match /assets?/:type/path when /^(\/assets)?\/(js|css)\/(.+)/ # Extract type and path type, path = $2, $3 # Extract digest key and remove from path path.gsub!("-#{@key = $1}", '') if path =~ /-([a-f0-9]{32})\.(css|js)$/ # Find the item item = ::Asset.manifest.find{|i| i.path == path and i.type == type} # Return the content or not found item ? found(item) : not_found # Bounce favicon requests when (::Asset.favicon and /^\/favicon\.ico$/) not_found # Return a standard robots.txt when (::Asset.robots and /^\/robots\.txt$/) robots else # No routes found, pass down the middleware stack @app.call(env) end end private # Found def found(item) content = item.content(!!@key) [ 200, {'Content-Type' => MIME[item.type], 'Content-Length' => content.size, 'Cache-Control' => 'public, max-age=86400', 'Expires' => (Time.now.utc + (86400 * 30)).httpdate, 'Last-Modified' => item.modified.httpdate, }, [content]] end # Not found def not_found [404, {'Content-Type' => MIME['txt'], 'Content-Length' => 0}, []] end # Robots def robots s = %{Sitemap: #{@request.scheme}://#{@request.host}/sitemap.xml} [200, {'Content-Type' => MIME['txt'],'Content-Length' => s.size}, [s]] end end end
module Astar VERSION = "0.0.1" end Bump patch version module Astar VERSION = "0.0.2" end
module Auger VERSION = "1.0.5" end bump ver module Auger VERSION = "1.0.6" end
module Auger VERSION = "1.0.4" end bump ver module Auger VERSION = "1.0.5" end
$:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |spec| spec.name = 'validates_phone_format_of' spec.version = '2.0.0' spec.authors = ['Jonathan VUKOVICH-TRIBOUHARET'] spec.email = ['jonathan.tribouharet@gmail.com'] spec.summary = 'Validate phone numbers against E.164 format with this Ruby on Rails gem' spec.description = 'Validate phone numbers against E.164 format with this Ruby on Rails gem' spec.homepage = 'https://github.com/jonathantribouharet/validates_phone_format_of' spec.license = 'MIT' spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0") end spec.require_paths = ['lib'] spec.platform = Gem::Platform::RUBY spec.required_ruby_version = '>= 1.9.3' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rake' end Fix test $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |spec| spec.name = 'validates_phone_format_of' spec.version = '2.0.0' spec.authors = ['Jonathan VUKOVICH-TRIBOUHARET'] spec.email = ['jonathan.tribouharet@gmail.com'] spec.summary = 'Validate phone numbers against E.164 format with this Ruby on Rails gem' spec.description = 'Validate phone numbers against E.164 format with this Ruby on Rails gem' spec.homepage = 'https://github.com/jonathantribouharet/validates_phone_format_of' spec.license = 'MIT' spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0") end spec.require_paths = ['lib'] spec.platform = Gem::Platform::RUBY spec.required_ruby_version = '>= 1.9.3' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rake' spec.add_development_dependency 'rspec', '~> 3.6' end
module AuthN module Session def self.included(object) object.extend ClassMethods end module ClassMethods def login(identifiers, klass = AuthN.config.account_klass) generate_session_and_instance_from find_instance_klass(klass).authenticate identifiers end def auto_login(instance) instance_and_session instance end def logged_in?(instance = nil, klass = AuthN.config.account_klass) klass = instance.class if instance klass = find_instance_klass klass unless instance check_session klass end def logout(instance = nil, klass = AuthN.config.account_klass) klass = instance.class if instance klass = find_instance_klass klass unless instance destroy_session klass end private def find_instance_klass(klass) const_get klass.capitalize end def klass_as_name(klass) klass.name.downcase end def generate_session_and_instance_from(instance) instance.tap { instance_and_session instance if instance } end def instance_and_session(instance) instance.tap { |instance| create_session instance.class, instance } end def create_session(klass, instance) session[:"session_#{klass_as_name(klass)}_id"] = instance.id end def destroy_session(klass) session.delete :"session_#{klass_as_name(klass)}_id" end def check_session(klass) session[:"session_#{klass}_id"].present? end end end end Creating a method to grab the session if given a klass module AuthN module Session def self.included(object) object.extend ClassMethods end module ClassMethods def login(identifiers, klass = AuthN.config.account_klass) generate_session_and_instance_from find_instance_klass(klass).authenticate identifiers end def auto_login(instance) instance_and_session instance end def logged_in?(instance = nil, klass = AuthN.config.account_klass) klass = instance.class if instance klass = find_instance_klass klass unless instance check_session klass end def logout(instance = nil, klass = AuthN.config.account_klass) klass = instance.class if instance klass = find_instance_klass klass unless instance destroy_session klass end private def find_instance_klass(klass) const_get klass.capitalize end def klass_as_name(klass) klass.name.downcase end def generate_session_and_instance_from(instance) instance.tap { instance_and_session instance if instance } end def instance_and_session(instance) instance.tap { |instance| create_session instance.class, instance } end def create_session(klass, instance) session[:"session_#{klass_as_name(klass)}_id"] = instance.id end def destroy_session(klass) session.delete :"session_#{klass_as_name(klass)}_id" end def check_session(klass) get_session(klass).present? end def get_session(klass) session[:"session_#{klass_as_name(klass)}_id"] end end end end
module Awful VERSION = "0.0.41" end bump 0.0.42 module Awful VERSION = "0.0.42" end
require 'spec_helper' describe command('sleep 2') do it { should return_exit_status 0 } end describe command('java -version') do it { should return_exit_status 0 } end describe command('ls -d /usr/lib/jvm/java-6-openjdk*') do it { should return_exit_status 0 } its(:stderr) { should match /java-6-openjdk/ } end Removed sleep time require 'spec_helper' describe command('java -version') do it { should return_exit_status 0 } end describe command('ls -d /usr/lib/jvm/java-6-openjdk*') do it { should return_exit_status 0 } its(:stderr) { should match /java-6-openjdk/ } end
require 'badger/packet' require 'badger/request' require 'badger/response' require 'badger/service' require 'badger/services' require 'ffi-rzmq' module Badger class Client KNOWN_SERVICES = { :sys => Services::Sys } attr_reader :uri def initialize @uri = nil @request_id = Request::ID_MIN @services = {} @decoder = nil @encoder = nil @context = nil @socket = nil end def connect(uri) @uri = uri @context = ZMQ::Context.new(1, 1, 0) @socket = @context.socket(ZMQ::PAIR) @socket.connect(@uri) return true end def listen(uri) @uri = uri @context = ZMQ::Context.new(1, 1, 0) @socket = @context.socket(ZMQ::PAIR) @socket.bind(@uri) return true end def ping push [@request_id, Request::PING] t1 = Time.now payload = pull t2 = Time.now return (t2 - t1) end def load_services push [@request_id, Request::SERVICES] payload = pull unless payload[2].kind_of?(Array) raise(CorruptedPacket,"the received badger packet did not contain an Array of Service names",caller) end @services = {} payload[2].each do |name| name = name.to_sym @services[name] = Service.new(self,name) end return @services end def services if @services.empty? load_services else @services end end def functions(service) push [@request_id, Request::FUNCTIONS, service] payload = pull unless payload[2].kind_of?(Array) raise(CorruptedPacket,"the received badger packet did not contain an Array of Function names",caller) end return payload[2] end def call(service,name,*args) push [@request_id, Request::CALL, service, name, args] loop do payload = pull case payload[1] when Response::YIELD yield payload[2] if block_given? when Response::RETURN return payload[2] when Response::ERROR raise(RuntimeError,payload[3],caller) end end end def close @context.terminate @socket = nil @context = nil return true end def to_s @uri end protected def push(payload) packet = Packet.pack(payload) if @encoder packet = @encoder.call(packet) end @socket.send_string(packet,0) @request_id += 1 if @request_id > Request::ID_MAX @request_id = Request::ID_MIN end end def pull packet = @socket.recv_string(0) if packet.length < Packet::MIN_SIZE raise(CorruptedPacket,"the received badger packet was below the minimum required size",caller) end if @decoder packet = @decoder.call(packet) end return Packet.unpack(packet) end def method_missing(name,*args) if args.empty? unless @services.has_key?(name) service_class = (KNOWN_SERVICES[name] || Service) @services[name] = service_class.new(self,name) end return @services[name] end super(name,*args) end end end Recognize known services in Client#load_services. require 'badger/packet' require 'badger/request' require 'badger/response' require 'badger/service' require 'badger/services' require 'ffi-rzmq' module Badger class Client KNOWN_SERVICES = { :sys => Services::Sys } attr_reader :uri def initialize @uri = nil @request_id = Request::ID_MIN @services = {} @decoder = nil @encoder = nil @context = nil @socket = nil end def connect(uri) @uri = uri @context = ZMQ::Context.new(1, 1, 0) @socket = @context.socket(ZMQ::PAIR) @socket.connect(@uri) return true end def listen(uri) @uri = uri @context = ZMQ::Context.new(1, 1, 0) @socket = @context.socket(ZMQ::PAIR) @socket.bind(@uri) return true end def ping push [@request_id, Request::PING] t1 = Time.now payload = pull t2 = Time.now return (t2 - t1) end def load_services push [@request_id, Request::SERVICES] payload = pull unless payload[2].kind_of?(Array) raise(CorruptedPacket,"the received badger packet did not contain an Array of Service names",caller) end @services = {} payload[2].each do |name| name = name.to_sym server_class = (KNOWN_SERVICES[name] || Service) @services[name] = service_class.new(self,name) end return @services end def services if @services.empty? load_services else @services end end def functions(service) push [@request_id, Request::FUNCTIONS, service] payload = pull unless payload[2].kind_of?(Array) raise(CorruptedPacket,"the received badger packet did not contain an Array of Function names",caller) end return payload[2] end def call(service,name,*args) push [@request_id, Request::CALL, service, name, args] loop do payload = pull case payload[1] when Response::YIELD yield payload[2] if block_given? when Response::RETURN return payload[2] when Response::ERROR raise(RuntimeError,payload[3],caller) end end end def close @context.terminate @socket = nil @context = nil return true end def to_s @uri end protected def push(payload) packet = Packet.pack(payload) if @encoder packet = @encoder.call(packet) end @socket.send_string(packet,0) @request_id += 1 if @request_id > Request::ID_MAX @request_id = Request::ID_MIN end end def pull packet = @socket.recv_string(0) if packet.length < Packet::MIN_SIZE raise(CorruptedPacket,"the received badger packet was below the minimum required size",caller) end if @decoder packet = @decoder.call(packet) end return Packet.unpack(packet) end def method_missing(name,*args) if args.empty? unless @services.has_key?(name) service_class = (KNOWN_SERVICES[name] || Service) @services[name] = service_class.new(self,name) end return @services[name] end super(name,*args) end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'markdown-ui/version' Gem::Specification.new do |spec| spec.name = "markdown-ui" spec.version = MarkdownUI::VERSION spec.authors = ["Joel Bryan Juliano"] spec.email = ["joelbryan.juliano@gmail.com"] spec.summary = %q{Responsive User Interfaces in Markdown} spec.description = %q{Create responsive UI/UX for mobile and web using Markdown Syntax} spec.homepage = "https://github.com/jjuliano/markdown-ui" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or # delete this section to allow pushing this gem to any host. if spec.respond_to?(:metadata) spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'" else raise "RubyGems 2.0 or newer is required to protect against public gem pushes." end spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.9" spec.add_development_dependency "rake", "~> 10.0" spec.add_dependency "redcarpet", "~> 3.2" spec.add_dependency "nokogiri", "~> 1.6" spec.add_development_dependency "test-unit", "~> 3.0" spec.add_development_dependency "simplecov", "~> 0.10" end updated markdown-ui.gemspec # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'markdown-ui/version' Gem::Specification.new do |spec| spec.name = "markdown-ui" spec.version = MarkdownUI::VERSION spec.authors = ["Joel Bryan Juliano"] spec.email = ["joelbryan.juliano@gmail.com"] spec.summary = %q{Responsive User Interfaces in Markdown} spec.description = %q{Create responsive UI/UX for mobile and web using Markdown Syntax} spec.homepage = "https://github.com/jjuliano/markdown-ui" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or # delete this section to allow pushing this gem to any host. if spec.respond_to?(:metadata) spec.metadata['allowed_push_host'] = "https://rubygems.org" else raise "RubyGems 2.0 or newer is required to protect against public gem pushes." end spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.9" spec.add_development_dependency "rake", "~> 10.0" spec.add_dependency "redcarpet", "~> 3.2" spec.add_dependency "nokogiri", "~> 1.6" spec.add_development_dependency "test-unit", "~> 3.0" spec.add_development_dependency "simplecov", "~> 0.10" end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- # stub: maestrano-connector-rails 1.4.0 ruby lib Gem::Specification.new do |s| s.name = "maestrano-connector-rails" s.version = "1.4.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Maestrano", "Pierre Berard", "Marco Bagnasco"] s.date = "2016-08-24" s.description = "Maestrano is the next generation marketplace for SME applications. See https://maestrano.com for details." s.email = "developers@maestrano.com" s.executables = ["rails"] s.extra_rdoc_files = [ "LICENSE", "README.md" ] s.files = [ ".rspec", ".rubocop.yml", ".rubocop_todo.yml", ".ruby-version", "CODESHIP.md", "DEVELOPER.md", "Gemfile", "LICENSE", "README.md", "Rakefile", "VERSION", "app/controllers/maestrano/account/group_users_controller.rb", "app/controllers/maestrano/account/groups_controller.rb", "app/controllers/maestrano/application_controller.rb", "app/controllers/maestrano/auth/saml_controller.rb", "app/controllers/maestrano/connec_controller.rb", "app/controllers/maestrano/dependancies_controller.rb", "app/controllers/maestrano/sessions_controller.rb", "app/controllers/maestrano/synchronizations_controller.rb", "app/controllers/version_controller.rb", "app/helpers/maestrano/connector/rails/session_helper.rb", "app/jobs/maestrano/connector/rails/all_synchronizations_job.rb", "app/jobs/maestrano/connector/rails/push_to_connec_job.rb", "app/jobs/maestrano/connector/rails/push_to_connec_worker.rb", "app/jobs/maestrano/connector/rails/synchronization_job.rb", "app/models/maestrano/connector/rails/complex_entity.rb", "app/models/maestrano/connector/rails/concerns/complex_entity.rb", "app/models/maestrano/connector/rails/concerns/connec_helper.rb", "app/models/maestrano/connector/rails/concerns/connector_logger.rb", "app/models/maestrano/connector/rails/concerns/entity.rb", "app/models/maestrano/connector/rails/concerns/entity_base.rb", "app/models/maestrano/connector/rails/concerns/external.rb", "app/models/maestrano/connector/rails/concerns/sub_entity_base.rb", "app/models/maestrano/connector/rails/connec_helper.rb", "app/models/maestrano/connector/rails/connector_logger.rb", "app/models/maestrano/connector/rails/entity.rb", "app/models/maestrano/connector/rails/entity_base.rb", "app/models/maestrano/connector/rails/exceptions/entity_not_found_error.rb", "app/models/maestrano/connector/rails/external.rb", "app/models/maestrano/connector/rails/id_map.rb", "app/models/maestrano/connector/rails/organization.rb", "app/models/maestrano/connector/rails/sub_entity_base.rb", "app/models/maestrano/connector/rails/synchronization.rb", "app/models/maestrano/connector/rails/user.rb", "app/models/maestrano/connector/rails/user_organization_rel.rb", "bin/rails", "config/routes.rb", "db/migrate/20151122162100_create_users.rb", "db/migrate/20151122162414_create_organizations.rb", "db/migrate/20151122162613_create_user_organization_rels.rb", "db/migrate/20151122163325_create_synchronizations.rb", "db/migrate/20151122163449_create_id_maps.rb", "db/migrate/20160205132857_add_sync_enabled_to_organizations.rb", "db/migrate/20160215103120_add_name_to_id_map.rb", "db/migrate/20160427112250_add_inactive_to_idmaps.rb", "db/migrate/20160614114401_add_date_filtering_limit_to_organization.rb", "db/migrate/20160614160654_add_encryption_on_oauth_keys.rb", "lib/generators/connector/USAGE", "lib/generators/connector/complex_entity_generator.rb", "lib/generators/connector/install_generator.rb", "lib/generators/connector/templates/complex_entity_example/contact.rb", "lib/generators/connector/templates/complex_entity_example/contact_and_lead.rb", "lib/generators/connector/templates/complex_entity_example/contact_mapper.rb", "lib/generators/connector/templates/complex_entity_example/lead.rb", "lib/generators/connector/templates/complex_entity_example/lead_mapper.rb", "lib/generators/connector/templates/complex_entity_example/person.rb", "lib/generators/connector/templates/entity.rb", "lib/generators/connector/templates/example_entity.rb", "lib/generators/connector/templates/example_entity_spec.rb", "lib/generators/connector/templates/external.rb", "lib/generators/connector/templates/home.js", "lib/generators/connector/templates/home_controller.rb", "lib/generators/connector/templates/home_controller_spec.rb", "lib/generators/connector/templates/home_index.haml", "lib/generators/connector/templates/layouts.haml", "lib/generators/connector/templates/oauth_controller.rb", "lib/generators/connector/templates/shared_entities_controller.rb", "lib/generators/connector/templates/shared_entities_controller_spec.rb", "lib/generators/connector/templates/shared_entities_index.haml", "lib/generators/connector/templates/stylesheets/application.sass", "lib/generators/connector/templates/stylesheets/home.sass", "lib/generators/connector/templates/stylesheets/layout.sass", "lib/generators/connector/templates/stylesheets/spacers.sass", "lib/generators/connector/templates/stylesheets/variables.sass", "lib/generators/connector/templates/synchronizations_controller.rb", "lib/generators/connector/templates/synchronizations_controller_spec.rb", "lib/generators/connector/templates/synchronizations_index.haml", "lib/maestrano/connector/rails.rb", "lib/maestrano_connector_rails.rb", "maestrano-connector-rails.gemspec", "maestrano.png", "release_notes.md", "spec/controllers/connec_controller_spec.rb", "spec/controllers/dependancies_controller_spec.rb", "spec/controllers/group_users_controller_spec.rb", "spec/controllers/groups_controller_spec.rb", "spec/controllers/synchronizations_controller_spec.rb", "spec/controllers/version_controller_spec.rb", "spec/dummy/README.md", "spec/dummy/Rakefile", "spec/dummy/app/assets/images/.keep", "spec/dummy/app/assets/javascripts/application.js", "spec/dummy/app/assets/stylesheets/application.css", "spec/dummy/app/controllers/application_controller.rb", "spec/dummy/app/controllers/concerns/.keep", "spec/dummy/app/helpers/application_helper.rb", "spec/dummy/app/mailers/.keep", "spec/dummy/app/models/.keep", "spec/dummy/app/models/concerns/.keep", "spec/dummy/app/models/entities/.keep", "spec/dummy/app/views/home/index.html.erb", "spec/dummy/app/views/layouts/application.html.erb", "spec/dummy/bin/bundle", "spec/dummy/bin/rails", "spec/dummy/bin/rake", "spec/dummy/bin/setup", "spec/dummy/config.ru", "spec/dummy/config/application.rb", "spec/dummy/config/boot.rb", "spec/dummy/config/database.yml", "spec/dummy/config/environment.rb", "spec/dummy/config/environments/development.rb", "spec/dummy/config/environments/production.rb", "spec/dummy/config/environments/test.rb", "spec/dummy/config/initializers/assets.rb", "spec/dummy/config/initializers/backtrace_silencers.rb", "spec/dummy/config/initializers/cookies_serializer.rb", "spec/dummy/config/initializers/filter_parameter_logging.rb", "spec/dummy/config/initializers/inflections.rb", "spec/dummy/config/initializers/maestrano.rb", "spec/dummy/config/initializers/mime_types.rb", "spec/dummy/config/initializers/session_store.rb", "spec/dummy/config/initializers/wrap_parameters.rb", "spec/dummy/config/locales/en.yml", "spec/dummy/config/routes.rb", "spec/dummy/config/secrets.yml", "spec/dummy/config/settings.yml", "spec/dummy/config/settings/development.yml", "spec/dummy/config/settings/production.yml", "spec/dummy/config/settings/test.yml", "spec/dummy/config/settings/uat.yml", "spec/dummy/db/schema.rb", "spec/dummy/lib/assets/.keep", "spec/dummy/log/.keep", "spec/dummy/public/404.html", "spec/dummy/public/422.html", "spec/dummy/public/500.html", "spec/dummy/public/favicon.ico", "spec/dummy/tmp/cache/.keep", "spec/factories.rb", "spec/integration/complex_id_references_spec.rb", "spec/integration/complex_naming_spec.rb", "spec/integration/complex_spec.rb", "spec/integration/connec_to_external_spec.rb", "spec/integration/external_to_connec_spec.rb", "spec/integration/id_references_spec.rb", "spec/integration/singleton_spec.rb", "spec/jobs/all_synchronizations_job_spec.rb", "spec/jobs/push_to_connec_job_spec.rb", "spec/jobs/push_to_connec_worker_spec.rb", "spec/jobs/synchronization_job_spec.rb", "spec/models/complex_entity_spec.rb", "spec/models/connec_helper_spec.rb", "spec/models/connector_logger_spec.rb", "spec/models/entity_base_spec.rb", "spec/models/entity_spec.rb", "spec/models/external_spec.rb", "spec/models/id_map_spec.rb", "spec/models/organization_spec.rb", "spec/models/sub_entity_base_spec.rb", "spec/models/synchronization_spec.rb", "spec/models/user_organization_rel_spec.rb", "spec/models/user_spec.rb", "spec/routing/connec_routing_spec.rb", "spec/spec_helper.rb", "template/Procfile", "template/application-sample.yml", "template/database.yml", "template/factories.rb", "template/gitignore", "template/maestrano.rb", "template/maestrano_connector_template.rb", "template/routes.rb", "template/rubocop.yml", "template/settings/development.yml", "template/settings/production.yml", "template/settings/settings.yml", "template/settings/test.yml", "template/settings/uat.yml", "template/sidekiq.rb", "template/sidekiq.yml", "template/spec_helper.rb" ] s.homepage = "http://github.com/maestrano/maestrano-connector-rails" s.licenses = ["MIT"] s.rubygems_version = "2.5.1" s.summary = "Rails framework to build connector with Maestrano" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rails>, ["~> 4.2"]) s.add_runtime_dependency(%q<maestrano-rails>, [">= 0"]) s.add_runtime_dependency(%q<hash_mapper>, [">= 0.2.2"]) s.add_runtime_dependency(%q<haml-rails>, [">= 0"]) s.add_runtime_dependency(%q<bootstrap-sass>, [">= 0"]) s.add_runtime_dependency(%q<autoprefixer-rails>, [">= 0"]) s.add_runtime_dependency(%q<attr_encrypted>, ["~> 1.4.0"]) s.add_runtime_dependency(%q<config>, [">= 0"]) s.add_runtime_dependency(%q<figaro>, [">= 0"]) s.add_runtime_dependency(%q<sidekiq>, [">= 0"]) s.add_runtime_dependency(%q<sidekiq-unique-jobs>, [">= 0"]) s.add_runtime_dependency(%q<sinatra>, [">= 0"]) s.add_runtime_dependency(%q<sidekiq-cron>, [">= 0"]) s.add_runtime_dependency(%q<slim>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, ["~> 1.0"]) s.add_development_dependency(%q<jeweler>, ["~> 2.1.1"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) s.add_development_dependency(%q<rspec-rails>, [">= 0"]) s.add_development_dependency(%q<factory_girl_rails>, [">= 0"]) s.add_development_dependency(%q<sqlite3>, [">= 0"]) s.add_development_dependency(%q<shoulda-matchers>, [">= 0"]) s.add_development_dependency(%q<rubocop>, [">= 0"]) s.add_development_dependency(%q<timecop>, [">= 0"]) else s.add_dependency(%q<rails>, ["~> 4.2"]) s.add_dependency(%q<maestrano-rails>, [">= 0"]) s.add_dependency(%q<hash_mapper>, [">= 0.2.2"]) s.add_dependency(%q<haml-rails>, [">= 0"]) s.add_dependency(%q<bootstrap-sass>, [">= 0"]) s.add_dependency(%q<autoprefixer-rails>, [">= 0"]) s.add_dependency(%q<attr_encrypted>, ["~> 1.4.0"]) s.add_dependency(%q<config>, [">= 0"]) s.add_dependency(%q<figaro>, [">= 0"]) s.add_dependency(%q<sidekiq>, [">= 0"]) s.add_dependency(%q<sidekiq-unique-jobs>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<sidekiq-cron>, [">= 0"]) s.add_dependency(%q<slim>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.1.1"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<rspec-rails>, [">= 0"]) s.add_dependency(%q<factory_girl_rails>, [">= 0"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<shoulda-matchers>, [">= 0"]) s.add_dependency(%q<rubocop>, [">= 0"]) s.add_dependency(%q<timecop>, [">= 0"]) end else s.add_dependency(%q<rails>, ["~> 4.2"]) s.add_dependency(%q<maestrano-rails>, [">= 0"]) s.add_dependency(%q<hash_mapper>, [">= 0.2.2"]) s.add_dependency(%q<haml-rails>, [">= 0"]) s.add_dependency(%q<bootstrap-sass>, [">= 0"]) s.add_dependency(%q<autoprefixer-rails>, [">= 0"]) s.add_dependency(%q<attr_encrypted>, ["~> 1.4.0"]) s.add_dependency(%q<config>, [">= 0"]) s.add_dependency(%q<figaro>, [">= 0"]) s.add_dependency(%q<sidekiq>, [">= 0"]) s.add_dependency(%q<sidekiq-unique-jobs>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<sidekiq-cron>, [">= 0"]) s.add_dependency(%q<slim>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.1.1"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<rspec-rails>, [">= 0"]) s.add_dependency(%q<factory_girl_rails>, [">= 0"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<shoulda-matchers>, [">= 0"]) s.add_dependency(%q<rubocop>, [">= 0"]) s.add_dependency(%q<timecop>, [">= 0"]) end end Regenerate gemspec for version 1.4.0 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- # stub: maestrano-connector-rails 1.4.0 ruby lib Gem::Specification.new do |s| s.name = "maestrano-connector-rails" s.version = "1.4.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Maestrano", "Pierre Berard", "Marco Bagnasco"] s.date = "2016-09-01" s.description = "Maestrano is the next generation marketplace for SME applications. See https://maestrano.com for details." s.email = "developers@maestrano.com" s.executables = ["rails"] s.extra_rdoc_files = [ "LICENSE", "README.md" ] s.files = [ ".rspec", ".rubocop.yml", ".rubocop_todo.yml", ".ruby-version", "CODESHIP.md", "DEVELOPER.md", "Gemfile", "LICENSE", "README.md", "Rakefile", "VERSION", "app/controllers/maestrano/account/group_users_controller.rb", "app/controllers/maestrano/account/groups_controller.rb", "app/controllers/maestrano/application_controller.rb", "app/controllers/maestrano/auth/saml_controller.rb", "app/controllers/maestrano/connec_controller.rb", "app/controllers/maestrano/dependancies_controller.rb", "app/controllers/maestrano/sessions_controller.rb", "app/controllers/maestrano/synchronizations_controller.rb", "app/controllers/version_controller.rb", "app/helpers/maestrano/connector/rails/session_helper.rb", "app/jobs/maestrano/connector/rails/all_synchronizations_job.rb", "app/jobs/maestrano/connector/rails/push_to_connec_job.rb", "app/jobs/maestrano/connector/rails/push_to_connec_worker.rb", "app/jobs/maestrano/connector/rails/synchronization_job.rb", "app/models/maestrano/connector/rails/complex_entity.rb", "app/models/maestrano/connector/rails/concerns/complex_entity.rb", "app/models/maestrano/connector/rails/concerns/connec_helper.rb", "app/models/maestrano/connector/rails/concerns/connector_logger.rb", "app/models/maestrano/connector/rails/concerns/entity.rb", "app/models/maestrano/connector/rails/concerns/entity_base.rb", "app/models/maestrano/connector/rails/concerns/external.rb", "app/models/maestrano/connector/rails/concerns/sub_entity_base.rb", "app/models/maestrano/connector/rails/connec_helper.rb", "app/models/maestrano/connector/rails/connector_logger.rb", "app/models/maestrano/connector/rails/entity.rb", "app/models/maestrano/connector/rails/entity_base.rb", "app/models/maestrano/connector/rails/exceptions/entity_not_found_error.rb", "app/models/maestrano/connector/rails/external.rb", "app/models/maestrano/connector/rails/id_map.rb", "app/models/maestrano/connector/rails/organization.rb", "app/models/maestrano/connector/rails/sub_entity_base.rb", "app/models/maestrano/connector/rails/synchronization.rb", "app/models/maestrano/connector/rails/user.rb", "app/models/maestrano/connector/rails/user_organization_rel.rb", "bin/rails", "config/routes.rb", "db/migrate/20151122162100_create_users.rb", "db/migrate/20151122162414_create_organizations.rb", "db/migrate/20151122162613_create_user_organization_rels.rb", "db/migrate/20151122163325_create_synchronizations.rb", "db/migrate/20151122163449_create_id_maps.rb", "db/migrate/20160205132857_add_sync_enabled_to_organizations.rb", "db/migrate/20160215103120_add_name_to_id_map.rb", "db/migrate/20160427112250_add_inactive_to_idmaps.rb", "db/migrate/20160614114401_add_date_filtering_limit_to_organization.rb", "db/migrate/20160614160654_add_encryption_on_oauth_keys.rb", "lib/generators/connector/USAGE", "lib/generators/connector/complex_entity_generator.rb", "lib/generators/connector/install_generator.rb", "lib/generators/connector/templates/complex_entity_example/contact.rb", "lib/generators/connector/templates/complex_entity_example/contact_and_lead.rb", "lib/generators/connector/templates/complex_entity_example/contact_mapper.rb", "lib/generators/connector/templates/complex_entity_example/lead.rb", "lib/generators/connector/templates/complex_entity_example/lead_mapper.rb", "lib/generators/connector/templates/complex_entity_example/person.rb", "lib/generators/connector/templates/entity.rb", "lib/generators/connector/templates/example_entity.rb", "lib/generators/connector/templates/example_entity_spec.rb", "lib/generators/connector/templates/external.rb", "lib/generators/connector/templates/home.js", "lib/generators/connector/templates/home_controller.rb", "lib/generators/connector/templates/home_controller_spec.rb", "lib/generators/connector/templates/home_index.haml", "lib/generators/connector/templates/layouts.haml", "lib/generators/connector/templates/oauth_controller.rb", "lib/generators/connector/templates/shared_entities_controller.rb", "lib/generators/connector/templates/shared_entities_controller_spec.rb", "lib/generators/connector/templates/shared_entities_index.haml", "lib/generators/connector/templates/stylesheets/application.sass", "lib/generators/connector/templates/stylesheets/home.sass", "lib/generators/connector/templates/stylesheets/layout.sass", "lib/generators/connector/templates/stylesheets/spacers.sass", "lib/generators/connector/templates/stylesheets/variables.sass", "lib/generators/connector/templates/synchronizations_controller.rb", "lib/generators/connector/templates/synchronizations_controller_spec.rb", "lib/generators/connector/templates/synchronizations_index.haml", "lib/maestrano/connector/rails.rb", "lib/maestrano_connector_rails.rb", "maestrano-connector-rails.gemspec", "maestrano.png", "release_notes.md", "spec/controllers/connec_controller_spec.rb", "spec/controllers/dependancies_controller_spec.rb", "spec/controllers/group_users_controller_spec.rb", "spec/controllers/groups_controller_spec.rb", "spec/controllers/synchronizations_controller_spec.rb", "spec/controllers/version_controller_spec.rb", "spec/dummy/README.md", "spec/dummy/Rakefile", "spec/dummy/app/assets/images/.keep", "spec/dummy/app/assets/javascripts/application.js", "spec/dummy/app/assets/stylesheets/application.css", "spec/dummy/app/controllers/application_controller.rb", "spec/dummy/app/controllers/concerns/.keep", "spec/dummy/app/helpers/application_helper.rb", "spec/dummy/app/mailers/.keep", "spec/dummy/app/models/.keep", "spec/dummy/app/models/concerns/.keep", "spec/dummy/app/models/entities/.keep", "spec/dummy/app/views/home/index.html.erb", "spec/dummy/app/views/layouts/application.html.erb", "spec/dummy/bin/bundle", "spec/dummy/bin/rails", "spec/dummy/bin/rake", "spec/dummy/bin/setup", "spec/dummy/config.ru", "spec/dummy/config/application.rb", "spec/dummy/config/boot.rb", "spec/dummy/config/database.yml", "spec/dummy/config/environment.rb", "spec/dummy/config/environments/development.rb", "spec/dummy/config/environments/production.rb", "spec/dummy/config/environments/test.rb", "spec/dummy/config/initializers/assets.rb", "spec/dummy/config/initializers/backtrace_silencers.rb", "spec/dummy/config/initializers/cookies_serializer.rb", "spec/dummy/config/initializers/filter_parameter_logging.rb", "spec/dummy/config/initializers/inflections.rb", "spec/dummy/config/initializers/maestrano.rb", "spec/dummy/config/initializers/mime_types.rb", "spec/dummy/config/initializers/session_store.rb", "spec/dummy/config/initializers/wrap_parameters.rb", "spec/dummy/config/locales/en.yml", "spec/dummy/config/routes.rb", "spec/dummy/config/secrets.yml", "spec/dummy/config/settings.yml", "spec/dummy/config/settings/development.yml", "spec/dummy/config/settings/production.yml", "spec/dummy/config/settings/test.yml", "spec/dummy/config/settings/uat.yml", "spec/dummy/db/schema.rb", "spec/dummy/lib/assets/.keep", "spec/dummy/log/.keep", "spec/dummy/public/404.html", "spec/dummy/public/422.html", "spec/dummy/public/500.html", "spec/dummy/public/favicon.ico", "spec/dummy/tmp/cache/.keep", "spec/factories.rb", "spec/integration/complex_id_references_spec.rb", "spec/integration/complex_naming_spec.rb", "spec/integration/complex_spec.rb", "spec/integration/connec_to_external_spec.rb", "spec/integration/external_to_connec_spec.rb", "spec/integration/id_references_spec.rb", "spec/integration/singleton_spec.rb", "spec/jobs/all_synchronizations_job_spec.rb", "spec/jobs/push_to_connec_job_spec.rb", "spec/jobs/push_to_connec_worker_spec.rb", "spec/jobs/synchronization_job_spec.rb", "spec/models/complex_entity_spec.rb", "spec/models/connec_helper_spec.rb", "spec/models/connector_logger_spec.rb", "spec/models/entity_base_spec.rb", "spec/models/entity_spec.rb", "spec/models/external_spec.rb", "spec/models/id_map_spec.rb", "spec/models/organization_spec.rb", "spec/models/sub_entity_base_spec.rb", "spec/models/synchronization_spec.rb", "spec/models/user_organization_rel_spec.rb", "spec/models/user_spec.rb", "spec/routing/connec_routing_spec.rb", "spec/spec_helper.rb", "template/Procfile", "template/application-sample.yml", "template/database.yml", "template/factories.rb", "template/gitignore", "template/maestrano.rb", "template/maestrano_connector_template.rb", "template/routes.rb", "template/rubocop.yml", "template/settings/development.yml", "template/settings/production.yml", "template/settings/settings.yml", "template/settings/test.yml", "template/settings/uat.yml", "template/sidekiq.rb", "template/sidekiq.yml", "template/spec_helper.rb" ] s.homepage = "http://github.com/maestrano/maestrano-connector-rails" s.licenses = ["MIT"] s.rubygems_version = "2.5.1" s.summary = "Rails framework to build connector with Maestrano" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rails>, ["~> 4.2"]) s.add_runtime_dependency(%q<maestrano-rails>, [">= 0"]) s.add_runtime_dependency(%q<hash_mapper>, [">= 0.2.2"]) s.add_runtime_dependency(%q<haml-rails>, [">= 0"]) s.add_runtime_dependency(%q<bootstrap-sass>, [">= 0"]) s.add_runtime_dependency(%q<autoprefixer-rails>, [">= 0"]) s.add_runtime_dependency(%q<attr_encrypted>, ["~> 1.4.0"]) s.add_runtime_dependency(%q<config>, [">= 0"]) s.add_runtime_dependency(%q<figaro>, [">= 0"]) s.add_runtime_dependency(%q<sidekiq>, [">= 0"]) s.add_runtime_dependency(%q<sidekiq-unique-jobs>, [">= 0"]) s.add_runtime_dependency(%q<sinatra>, [">= 0"]) s.add_runtime_dependency(%q<sidekiq-cron>, [">= 0"]) s.add_runtime_dependency(%q<slim>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, ["~> 1.0"]) s.add_development_dependency(%q<jeweler>, ["~> 2.1.1"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) s.add_development_dependency(%q<rspec-rails>, [">= 0"]) s.add_development_dependency(%q<factory_girl_rails>, [">= 0"]) s.add_development_dependency(%q<sqlite3>, [">= 0"]) s.add_development_dependency(%q<shoulda-matchers>, [">= 0"]) s.add_development_dependency(%q<rubocop>, [">= 0"]) s.add_development_dependency(%q<timecop>, [">= 0"]) else s.add_dependency(%q<rails>, ["~> 4.2"]) s.add_dependency(%q<maestrano-rails>, [">= 0"]) s.add_dependency(%q<hash_mapper>, [">= 0.2.2"]) s.add_dependency(%q<haml-rails>, [">= 0"]) s.add_dependency(%q<bootstrap-sass>, [">= 0"]) s.add_dependency(%q<autoprefixer-rails>, [">= 0"]) s.add_dependency(%q<attr_encrypted>, ["~> 1.4.0"]) s.add_dependency(%q<config>, [">= 0"]) s.add_dependency(%q<figaro>, [">= 0"]) s.add_dependency(%q<sidekiq>, [">= 0"]) s.add_dependency(%q<sidekiq-unique-jobs>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<sidekiq-cron>, [">= 0"]) s.add_dependency(%q<slim>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.1.1"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<rspec-rails>, [">= 0"]) s.add_dependency(%q<factory_girl_rails>, [">= 0"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<shoulda-matchers>, [">= 0"]) s.add_dependency(%q<rubocop>, [">= 0"]) s.add_dependency(%q<timecop>, [">= 0"]) end else s.add_dependency(%q<rails>, ["~> 4.2"]) s.add_dependency(%q<maestrano-rails>, [">= 0"]) s.add_dependency(%q<hash_mapper>, [">= 0.2.2"]) s.add_dependency(%q<haml-rails>, [">= 0"]) s.add_dependency(%q<bootstrap-sass>, [">= 0"]) s.add_dependency(%q<autoprefixer-rails>, [">= 0"]) s.add_dependency(%q<attr_encrypted>, ["~> 1.4.0"]) s.add_dependency(%q<config>, [">= 0"]) s.add_dependency(%q<figaro>, [">= 0"]) s.add_dependency(%q<sidekiq>, [">= 0"]) s.add_dependency(%q<sidekiq-unique-jobs>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<sidekiq-cron>, [">= 0"]) s.add_dependency(%q<slim>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.1.1"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<rspec-rails>, [">= 0"]) s.add_dependency(%q<factory_girl_rails>, [">= 0"]) s.add_dependency(%q<sqlite3>, [">= 0"]) s.add_dependency(%q<shoulda-matchers>, [">= 0"]) s.add_dependency(%q<rubocop>, [">= 0"]) s.add_dependency(%q<timecop>, [">= 0"]) end end
module Billy VERSION = '0.6.3' end Revert version change module Billy VERSION = '0.6.2' end
module Bouncer class NoInheritanceAllowedError < StandardError; end class Store # Implement a simple Singleton pattern private_class_method :new @@listeners = [] @@mutex = Mutex.new class << self def inherited(subclass) raise NoInheritanceAllowedError.new("#{self.class.to_s} is meant to be a singleton class and to not be inherited") end def register(objects, options) mutex.synchronize do objects.each { |object| @@listeners << Bouncer::Listener.new(object, options) } end end def unregister(objects) mutex.synchronize do objects.each { |object| listeners.delete_if { |listener| listener.object == object } } end end def clear mutex.synchronize do @@listeners = [] end end def notify(scope, event, args) return if listeners.empty? listeners.select { |listener| listener.for?(scope) }.each do |listener| klass = listener.object klass.public_send(event, *args) if klass.respond_to?(event) # Serves as callback yield if block_given? unregister([klass]) if listener.single? end end def listeners @@listeners end def mutex @@mutex end end end end add proper removal of listener if single module Bouncer class NoInheritanceAllowedError < StandardError; end class Store # Implement a simple Singleton pattern private_class_method :new @@listeners = [] @@mutex = Mutex.new class << self def inherited(subclass) raise NoInheritanceAllowedError.new("#{self.class.to_s} is meant to be a singleton class and to not be inherited") end def register(objects, options) mutex.synchronize do objects.each { |object| @@listeners << Bouncer::Listener.new(object, options) } end end def unregister(objects) mutex.synchronize do [*objects].each { |object| listeners.delete_if { |listener| listener.object == object } } end end def clear mutex.synchronize do @@listeners = [] end end def notify(scope, event, args) return if listeners.empty? listeners.select { |listener| listener.for?(scope) }.each do |listener| klass = listener.object klass.public_send(event, *args) if klass.respond_to?(event) # Serves as callback yield if block_given? unregister(klass) if listener.single? end end def listeners @@listeners end def mutex @@mutex end end end end
require 'sexp_processor' require 'set' require 'active_support/inflector' #This is a mixin containing utility methods. module Brakeman::Util QUERY_PARAMETERS = Sexp.new(:call, Sexp.new(:call, nil, :request, Sexp.new(:arglist)), :query_parameters, Sexp.new(:arglist)) PATH_PARAMETERS = Sexp.new(:call, Sexp.new(:call, nil, :request, Sexp.new(:arglist)), :path_parameters, Sexp.new(:arglist)) REQUEST_PARAMETERS = Sexp.new(:call, Sexp.new(:call, nil, :request, Sexp.new(:arglist)), :request_parameters, Sexp.new(:arglist)) PARAMETERS = Sexp.new(:call, nil, :params, Sexp.new(:arglist)) COOKIES = Sexp.new(:call, nil, :cookies, Sexp.new(:arglist)) SESSION = Sexp.new(:call, nil, :session, Sexp.new(:arglist)) ALL_PARAMETERS = Set.new([PARAMETERS, QUERY_PARAMETERS, PATH_PARAMETERS, REQUEST_PARAMETERS]) #Convert a string from "something_like_this" to "SomethingLikeThis" # #Taken from ActiveSupport. def camelize lower_case_and_underscored_word lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } end #Convert a string from "Something::LikeThis" to "something/like_this" # #Taken from ActiveSupport. def underscore camel_cased_word camel_cased_word.to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end #Use ActiveSupport::Inflector to pluralize a word. def pluralize word ActiveSupport::Inflector.pluralize word end #Takes an Sexp like # (:hash, (:lit, :key), (:str, "value")) #and yields the key and value pairs to the given block. # #For example: # # h = Sexp.new(:hash, (:lit, :name), (:str, "bob"), (:lit, :name), (:str, "jane")) # names = [] # hash_iterate(h) do |key, value| # if symbol? key and key[1] == :name # names << value[1] # end # end # names #["bob"] def hash_iterate hash 1.step(hash.length - 1, 2) do |i| yield hash[i], hash[i + 1] end end #Insert value into Hash Sexp def hash_insert hash, key, value index = 1 hash_iterate hash.dup do |k,v| if k == key hash[index + 1] = value return hash end index += 2 end hash << key << value hash end #Adds params, session, and cookies to environment #so they can be replaced by their respective Sexps. def set_env_defaults @env[PARAMETERS] = Sexp.new(:params) @env[SESSION] = Sexp.new(:session) @env[COOKIES] = Sexp.new(:cookies) end #Check if _exp_ represents a hash: s(:hash, {...}) #This also includes pseudo hashes params, session, and cookies. def hash? exp exp.is_a? Sexp and (exp.node_type == :hash or exp.node_type == :params or exp.node_type == :session or exp.node_type == :cookies) end #Check if _exp_ represents an array: s(:array, [...]) def array? exp exp.is_a? Sexp and exp.node_type == :array end #Check if _exp_ represents a String: s(:str, "...") def string? exp exp.is_a? Sexp and exp.node_type == :str end #Check if _exp_ represents a Symbol: s(:lit, :...) def symbol? exp exp.is_a? Sexp and exp.node_type == :lit and exp[1].is_a? Symbol end #Check if _exp_ represents a method call: s(:call, ...) def call? exp exp.is_a? Sexp and exp.node_type == :call end #Check if _exp_ represents a Regexp: s(:lit, /.../) def regexp? exp exp.is_a? Sexp and exp.node_type == :lit and exp[1].is_a? Regexp end #Check if _exp_ represents an Integer: s(:lit, ...) def integer? exp exp.is_a? Sexp and exp.node_type == :lit and exp[1].is_a? Integer end #Check if _exp_ is a params hash def params? exp if exp.is_a? Sexp return true if exp.node_type == :params or ALL_PARAMETERS.include? exp if exp.node_type == :call if params? exp[1] return true elsif exp[2] == :[] return params? exp[1] end end end false end def cookies? exp if exp.is_a? Sexp return true if exp.node_type == :cookies or exp == COOKIES if exp.node_type == :call if cookies? exp[1] return true elsif exp[2] == :[] return cookies? exp[1] end end end false end #Check if _exp_ is a Sexp. def sexp? exp exp.is_a? Sexp end end Add Util.result? require 'sexp_processor' require 'set' require 'active_support/inflector' #This is a mixin containing utility methods. module Brakeman::Util QUERY_PARAMETERS = Sexp.new(:call, Sexp.new(:call, nil, :request, Sexp.new(:arglist)), :query_parameters, Sexp.new(:arglist)) PATH_PARAMETERS = Sexp.new(:call, Sexp.new(:call, nil, :request, Sexp.new(:arglist)), :path_parameters, Sexp.new(:arglist)) REQUEST_PARAMETERS = Sexp.new(:call, Sexp.new(:call, nil, :request, Sexp.new(:arglist)), :request_parameters, Sexp.new(:arglist)) PARAMETERS = Sexp.new(:call, nil, :params, Sexp.new(:arglist)) COOKIES = Sexp.new(:call, nil, :cookies, Sexp.new(:arglist)) SESSION = Sexp.new(:call, nil, :session, Sexp.new(:arglist)) ALL_PARAMETERS = Set.new([PARAMETERS, QUERY_PARAMETERS, PATH_PARAMETERS, REQUEST_PARAMETERS]) #Convert a string from "something_like_this" to "SomethingLikeThis" # #Taken from ActiveSupport. def camelize lower_case_and_underscored_word lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } end #Convert a string from "Something::LikeThis" to "something/like_this" # #Taken from ActiveSupport. def underscore camel_cased_word camel_cased_word.to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end #Use ActiveSupport::Inflector to pluralize a word. def pluralize word ActiveSupport::Inflector.pluralize word end #Takes an Sexp like # (:hash, (:lit, :key), (:str, "value")) #and yields the key and value pairs to the given block. # #For example: # # h = Sexp.new(:hash, (:lit, :name), (:str, "bob"), (:lit, :name), (:str, "jane")) # names = [] # hash_iterate(h) do |key, value| # if symbol? key and key[1] == :name # names << value[1] # end # end # names #["bob"] def hash_iterate hash 1.step(hash.length - 1, 2) do |i| yield hash[i], hash[i + 1] end end #Insert value into Hash Sexp def hash_insert hash, key, value index = 1 hash_iterate hash.dup do |k,v| if k == key hash[index + 1] = value return hash end index += 2 end hash << key << value hash end #Adds params, session, and cookies to environment #so they can be replaced by their respective Sexps. def set_env_defaults @env[PARAMETERS] = Sexp.new(:params) @env[SESSION] = Sexp.new(:session) @env[COOKIES] = Sexp.new(:cookies) end #Check if _exp_ represents a hash: s(:hash, {...}) #This also includes pseudo hashes params, session, and cookies. def hash? exp exp.is_a? Sexp and (exp.node_type == :hash or exp.node_type == :params or exp.node_type == :session or exp.node_type == :cookies) end #Check if _exp_ represents an array: s(:array, [...]) def array? exp exp.is_a? Sexp and exp.node_type == :array end #Check if _exp_ represents a String: s(:str, "...") def string? exp exp.is_a? Sexp and exp.node_type == :str end #Check if _exp_ represents a Symbol: s(:lit, :...) def symbol? exp exp.is_a? Sexp and exp.node_type == :lit and exp[1].is_a? Symbol end #Check if _exp_ represents a method call: s(:call, ...) def call? exp exp.is_a? Sexp and exp.node_type == :call end #Check if _exp_ represents a Regexp: s(:lit, /.../) def regexp? exp exp.is_a? Sexp and exp.node_type == :lit and exp[1].is_a? Regexp end #Check if _exp_ represents an Integer: s(:lit, ...) def integer? exp exp.is_a? Sexp and exp.node_type == :lit and exp[1].is_a? Integer end #Check if _exp_ represents a result: s(:result, ...) def result? exp exp.is_a? Sexp and exp.node_type == :result end #Check if _exp_ is a params hash def params? exp if exp.is_a? Sexp return true if exp.node_type == :params or ALL_PARAMETERS.include? exp if exp.node_type == :call if params? exp[1] return true elsif exp[2] == :[] return params? exp[1] end end end false end def cookies? exp if exp.is_a? Sexp return true if exp.node_type == :cookies or exp == COOKIES if exp.node_type == :call if cookies? exp[1] return true elsif exp[2] == :[] return cookies? exp[1] end end end false end #Check if _exp_ is a Sexp. def sexp? exp exp.is_a? Sexp end end
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/..")) require 'ftools' require 'fileutils' require 'buffet/campfire' require 'buffet/master' require 'buffet/settings' require 'buffet/status_message' require 'buffet/setup' require 'buffet/regression' require 'memoize' PID_FILE = "/tmp/#{Buffet::Settings.root_dir_name}-buffet.pid" SETTINGS_FILE = File.expand_path('../../settings.yml', File.join(File.dirname(__FILE__))) module Buffet # This is the core Buffet class. It uses Setup and Master to bring the working # directory up to sync and to run tests remotely, respectively. It exposes # some helpful methods to give immediate information about the state of the # tests and other relevant information. class Buffet include Memoize ################ # CORE METHODS # ################ # Initialize sets up preliminary data, and will clone the repository # specified in settings.yml into working-directory if necessary. Also # verifies that all hosts are able to run Buffet. # # Initialize will NOT begin testing. def initialize repo, kwargs @status = StatusMessage.new kwargs[:verbose] @repo = repo @state = :not_running @threads = [] check_hosts end # Run sets up and tests the working directory. # # Run takes keyword arguments. # # :skip_setup => Don't do any preliminary setup with the working directory. # This is more helpful for testing then actually running Buffet, since # in theory you should have changed SOMETHING in Buffet between tests. # # :dont_run_migrations => Don't run the database migrations. def run branch, kwargs={} initialize_chat @branch = branch ensure_only_one do @status.set "Buffet is starting..." chat "Buffet is running on #{@repo} : #{branch}." if not kwargs[:skip_setup] @state = :setup @setup = Setup.new Settings.working_dir, hosts, @status, @repo @setup.run kwargs[:dont_run_migrations], @branch end @state = :testing @master = Master.new Settings.working_dir, hosts, @status @master.run if @master.failures.length == 0 chat "All tests pass!" else rev = `cd working-directory && git rev-parse HEAD`.chomp nice_output = @master.failures.map do |fail| "#{fail[:header]} FAILED.\nLocation: #{fail[:location]}\n\n" end.join "" nice_output = "On revision #{rev}:\n\n" + nice_output chat "#{nice_output}" end @state = :finding_regressions @status.set "Looking for regressions..." @regression_finder = Regression.new(@master.passes, @master.failures) puts @regression_finder.regressions @state = :not_running @status.set "Done" end end ##################### # CHAT INTEGRATION # ##################### def initialize_chat @using_chat = Settings.get["use_campfire"] if @using_chat Campfire.connect_and_login end end # This is like a higher priority @status.set. It's currently reserved for # starting and finishing a test run. def chat(message) if @using_chat if message.include? "\n" Campfire.paste message else Campfire.speak message end else @status.set message end end ###################### # HOST SETUP # ###################### def check_hosts if not File.exists? "#{Settings.home_dir}/.ssh/id_rsa.pub" puts "You should create a ssh public/private key pair before running" puts "Buffet." end # Running ssh-agent? if `ps -ef | grep ssh-agent | grep $USER | grep -v 'grep'`.length == 0 puts "You should run ssh-agent so you don't see so many password prompts." end shown_error = false # Create a buffet user on each uninitialized host. Settings.get["hosts"].each do |host| if not `ssh buffet@#{host} 'echo aaaaa'`.include? "aaaaa" if not shown_error puts "#############################################################" puts "Buffet user not found on #{host}." puts "" puts "Buffet will need the root password to every machine you plan" puts "to use as a host. This will be the only time the password is" puts "needed." puts "" puts "Buffet needs root access only on the first run, as it needs" puts "to create buffet users on each machine." puts "#############################################################" shown_error = true end `scp ~/.ssh/id_rsa.pub root@#{host}:id_rsa_buffet.pub` `ssh root@#{host} 'adduser buffet && mkdir -p ~buffet/.ssh && cat ~/id_rsa_buffet.pub >> ~buffet/.ssh/authorized_keys && chmod 644 ~buffet/.ssh/authorized_keys'` end end end ###################### # ENSURE EXCLUSIVITY # ###################### # Ensure that only one instance of the block passed in runs at any time, # across the entire machine. def ensure_only_one # We ensure exclusivity by writing a file to /tmp, and checking to see if it # exists before we start testing. def write_pid File.open(PID_FILE, 'w') do |fh| fh.write(Process.pid) end end def clear_pid if File.read(PID_FILE).to_i == Process.pid File.delete(PID_FILE) end end if File.exists?(PID_FILE) if `ps aux | grep buffet | grep -v grep | grep #{File.open(PID_FILE).read}`.length == 0 # Buffet isn't running, but the PID_FILE exists. # Get rid of it. FileUtils.rm(PID_FILE) else puts "Buffet is already running. Hold your horses." return end end begin write_pid yield ensure clear_pid end end ################## # TESTING STATUS # ################## # What is Buffet currently doing? # This method is only meaningful when called from a separate thread then # the one running Buffet. def get_status @status end # An array of failed test cases. def get_failures @master ? @master.failures : [] end # The URL of the respository. def repo @repo end # Is Buffet running (where running is either testing or setting up)? def running? @state != :not_running end # Is Buffet testing? def testing? @state == :testing end # List all the hosts (found in settings.yml) def hosts Settings.get['hosts'] end # List all branches (found by asking the working directory) def list_branches Dir.chdir(Settings.working_dir) do `git branch -a` end end memoize :list_branches # Count the number of tests. Uses a heuristic that is not 100% accurate. def num_tests # This is RSpec specific. `grep -r " it" #{Settings.working_dir}/spec/ | wc`.to_i end memoize :num_tests end end Rewrite host checking code. Remove host from list if access fails. $LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/..")) require 'ftools' require 'fileutils' require 'buffet/campfire' require 'buffet/master' require 'buffet/settings' require 'buffet/status_message' require 'buffet/setup' require 'buffet/regression' require 'memoize' PID_FILE = "/tmp/#{Buffet::Settings.root_dir_name}-buffet.pid" SETTINGS_FILE = File.expand_path('../../settings.yml', File.join(File.dirname(__FILE__))) module Buffet # This is the core Buffet class. It uses Setup and Master to bring the working # directory up to sync and to run tests remotely, respectively. It exposes # some helpful methods to give immediate information about the state of the # tests and other relevant information. class Buffet include Memoize ################ # CORE METHODS # ################ # Initialize sets up preliminary data, and will clone the repository # specified in settings.yml into working-directory if necessary. Also # verifies that all hosts are able to run Buffet. # # Initialize will NOT begin testing. def initialize repo, kwargs @status = StatusMessage.new kwargs[:verbose] @repo = repo @state = :not_running @threads = [] check_hosts end # Run sets up and tests the working directory. # # Run takes keyword arguments. # # :skip_setup => Don't do any preliminary setup with the working directory. # This is more helpful for testing then actually running Buffet, since # in theory you should have changed SOMETHING in Buffet between tests. # # :dont_run_migrations => Don't run the database migrations. def run branch, kwargs={} initialize_chat @branch = branch ensure_only_one do @status.set "Buffet is starting..." chat "Buffet is running on #{@repo} : #{branch}." if not kwargs[:skip_setup] @state = :setup @setup = Setup.new Settings.working_dir, hosts, @status, @repo @setup.run kwargs[:dont_run_migrations], @branch end @state = :testing @master = Master.new Settings.working_dir, hosts, @status @master.run if @master.failures.length == 0 chat "All tests pass!" else rev = `cd working-directory && git rev-parse HEAD`.chomp nice_output = @master.failures.map do |fail| "#{fail[:header]} FAILED.\nLocation: #{fail[:location]}\n\n" end.join "" nice_output = "On revision #{rev}:\n\n" + nice_output chat "#{nice_output}" end @state = :finding_regressions @status.set "Looking for regressions..." @regression_finder = Regression.new(@master.passes, @master.failures) puts @regression_finder.regressions @state = :not_running @status.set "Done" end end ##################### # CHAT INTEGRATION # ##################### def initialize_chat @using_chat = Settings.get["use_campfire"] if @using_chat Campfire.connect_and_login end end # This is like a higher priority @status.set. It's currently reserved for # starting and finishing a test run. def chat(message) if @using_chat if message.include? "\n" Campfire.paste message else Campfire.speak message end else @status.set message end end ###################### # HOST SETUP # ###################### def check_hosts if not File.exists? "#{Settings.home_dir}/.ssh/id_rsa.pub" puts "You should create a ssh public/private key pair before running" puts "Buffet." end # Running ssh-agent? if `ps -ef | grep ssh-agent | grep $USER | grep -v 'grep'`.length == 0 puts "You should run ssh-agent so you don't see so many password prompts." end # Have access to each host? Settings.get["hosts"].each do |host| next if `ssh buffet@#{host} -o PasswordAuthentication=no 'echo aaaaa'`.include? "aaaaa" puts "Unable to access #{host}." Settings.get["hosts"].delete host end end ###################### # ENSURE EXCLUSIVITY # ###################### # Ensure that only one instance of the block passed in runs at any time, # across the entire machine. def ensure_only_one # We ensure exclusivity by writing a file to /tmp, and checking to see if it # exists before we start testing. def write_pid File.open(PID_FILE, 'w') do |fh| fh.write(Process.pid) end end def clear_pid if File.read(PID_FILE).to_i == Process.pid File.delete(PID_FILE) end end if File.exists?(PID_FILE) if `ps aux | grep buffet | grep -v grep | grep #{File.open(PID_FILE).read}`.length == 0 # Buffet isn't running, but the PID_FILE exists. # Get rid of it. FileUtils.rm(PID_FILE) else puts "Buffet is already running. Hold your horses." return end end begin write_pid yield ensure clear_pid end end ################## # TESTING STATUS # ################## # What is Buffet currently doing? # This method is only meaningful when called from a separate thread then # the one running Buffet. def get_status @status end # An array of failed test cases. def get_failures @master ? @master.failures : [] end # The URL of the respository. def repo @repo end # Is Buffet running (where running is either testing or setting up)? def running? @state != :not_running end # Is Buffet testing? def testing? @state == :testing end # List all the hosts (found in settings.yml) def hosts Settings.get['hosts'] end # List all branches (found by asking the working directory) def list_branches Dir.chdir(Settings.working_dir) do `git branch -a` end end memoize :list_branches # Count the number of tests. Uses a heuristic that is not 100% accurate. def num_tests # This is RSpec specific. `grep -r " it" #{Settings.working_dir}/spec/ | wc`.to_i end memoize :num_tests end end
# frozen_string_literal: true require "tap" require "os" require "development_tools" module Bundle module Locker module_function def lockfile Brewfile.path.dirname/"Brewfile.lock.json" end def write_lockfile? !ARGV.include?("--no-lock") && ENV["HOMEBREW_BUNDLE_NO_LOCK"].nil? end def lock(entries) return false unless write_lockfile? lock = JSON.parse(lockfile.read) if lockfile.exist? lock ||= {} lock["entries"] ||= {} lock["system"] ||= {} entries.each do |entry| next if Bundle::Skipper.skip?(entry, silent: true) entry_type_key = entry.type.to_s options = entry.options lock["entries"][entry_type_key] ||= {} lock["entries"][entry_type_key][entry.name] = case entry.type when :brew brew_list_info[entry.name] when :cask options.delete(:args) if options[:args].blank? { version: cask_list[entry.name] } when :mas options.delete(:id) mas_list[entry.name] when :tap options.delete(:clone_target) if options[:clone_target].blank? options.delete(:pin) if options[:pin] == false { revision: Tap.fetch(entry.name).git_head } end if options.present? lock["entries"][entry_type_key][entry.name]["options"] = options.deep_stringify_keys end end if OS.mac? lock["system"]["macos"] ||= {} version, hash = system_macos lock["system"]["macos"][version] = hash elsif OS.linux? lock["system"]["linux"] ||= {} version, hash = system_linux lock["system"]["linux"][version] = hash end json = JSON.pretty_generate(lock) begin lockfile.unlink if lockfile.exist? lockfile.write(json) rescue Errno::EPERM, Errno::EACCES, Errno::ENOTEMPTY => e opoo "Could not write to #{lockfile}!" return false end true end def brew_list_info @brew_list_info ||= begin name_bottles = JSON.parse(`brew info --json=v1 --installed`) .inject({}) do |name_bottles, f| bottle = f["bottle"]["stable"] bottle&.delete("rebuild") bottle&.delete("root_url") bottle ||= false name_bottles[f["name"]] = bottle name_bottles end `brew list --versions`.lines .inject({}) do |name_versions_bottles, line| name, version, = line.split name_versions_bottles[name] = { version: version, bottle: name_bottles[name], } name_versions_bottles end end end def cask_list @cask_list ||= begin `brew cask list --versions`.lines .inject({}) do |name_versions, line| name, version, = line.split name_versions[name] = version name_versions end end end def mas_list @mas_list ||= begin `mas list`.lines .inject({}) do |name_id_versions, line| line = line.split id = line.shift version = line.pop.delete("()") name = line.join(" ") name_id_versions[name] = { id: id, version: version, } name_id_versions end end end def system_macos [MacOS.version.to_sym.to_s, { "HOMEBREW_VERSION" => HOMEBREW_VERSION, "HOMEBREW_PREFIX" => HOMEBREW_PREFIX.to_s, "Homebrew/homebrew-core" => CoreTap.instance.git_head, "CLT" => MacOS::CLT.version.to_s, "Xcode" => MacOS::Xcode.version.to_s, "macOS" => MacOS.full_version.to_s, }] end def system_linux [OS::Linux.os_version, { "HOMEBREW_VERSION" => HOMEBREW_VERSION, "HOMEBREW_PREFIX" => HOMEBREW_PREFIX.to_s, "Homebrew/linuxbrew-core" => CoreTap.instance.git_head, "GCC" => DevelopmentTools.non_apple_gcc_version("gcc"), }] end end end locker: handle nil error. Fixes https://github.com/Homebrew/homebrew-bundle/issues/583 # frozen_string_literal: true require "tap" require "os" require "development_tools" module Bundle module Locker module_function def lockfile Brewfile.path.dirname/"Brewfile.lock.json" end def write_lockfile? !ARGV.include?("--no-lock") && ENV["HOMEBREW_BUNDLE_NO_LOCK"].nil? end def lock(entries) return false unless write_lockfile? lock = JSON.parse(lockfile.read) if lockfile.exist? lock ||= {} lock["entries"] ||= {} lock["system"] ||= {} entries.each do |entry| next if Bundle::Skipper.skip?(entry, silent: true) entry_type_key = entry.type.to_s options = entry.options lock["entries"][entry_type_key] ||= {} lock["entries"][entry_type_key][entry.name] = case entry.type when :brew brew_list_info[entry.name] when :cask options.delete(:args) if options[:args].blank? { version: cask_list[entry.name] } when :mas options.delete(:id) mas_list[entry.name] when :tap options.delete(:clone_target) if options[:clone_target].blank? options.delete(:pin) if options[:pin] == false { revision: Tap.fetch(entry.name).git_head } end if options.present? lock["entries"][entry_type_key][entry.name] ||= {} lock["entries"][entry_type_key][entry.name]["options"] = options.deep_stringify_keys end end if OS.mac? lock["system"]["macos"] ||= {} version, hash = system_macos lock["system"]["macos"][version] = hash elsif OS.linux? lock["system"]["linux"] ||= {} version, hash = system_linux lock["system"]["linux"][version] = hash end json = JSON.pretty_generate(lock) begin lockfile.unlink if lockfile.exist? lockfile.write(json) rescue Errno::EPERM, Errno::EACCES, Errno::ENOTEMPTY => e opoo "Could not write to #{lockfile}!" return false end true end def brew_list_info @brew_list_info ||= begin name_bottles = JSON.parse(`brew info --json=v1 --installed`) .inject({}) do |name_bottles, f| bottle = f["bottle"]["stable"] bottle&.delete("rebuild") bottle&.delete("root_url") bottle ||= false name_bottles[f["name"]] = bottle name_bottles end `brew list --versions`.lines .inject({}) do |name_versions_bottles, line| name, version, = line.split name_versions_bottles[name] = { version: version, bottle: name_bottles[name], } name_versions_bottles end end end def cask_list @cask_list ||= begin `brew cask list --versions`.lines .inject({}) do |name_versions, line| name, version, = line.split name_versions[name] = version name_versions end end end def mas_list @mas_list ||= begin `mas list`.lines .inject({}) do |name_id_versions, line| line = line.split id = line.shift version = line.pop.delete("()") name = line.join(" ") name_id_versions[name] = { id: id, version: version, } name_id_versions end end end def system_macos [MacOS.version.to_sym.to_s, { "HOMEBREW_VERSION" => HOMEBREW_VERSION, "HOMEBREW_PREFIX" => HOMEBREW_PREFIX.to_s, "Homebrew/homebrew-core" => CoreTap.instance.git_head, "CLT" => MacOS::CLT.version.to_s, "Xcode" => MacOS::Xcode.version.to_s, "macOS" => MacOS.full_version.to_s, }] end def system_linux [OS::Linux.os_version, { "HOMEBREW_VERSION" => HOMEBREW_VERSION, "HOMEBREW_PREFIX" => HOMEBREW_PREFIX.to_s, "Homebrew/linuxbrew-core" => CoreTap.instance.git_head, "GCC" => DevelopmentTools.non_apple_gcc_version("gcc"), }] end end 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 (connection to RabbitMQ). # @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 }, :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 [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 Timeout for client operations that expect a response (e.g. {Bunny::Queue#get}), in seconds. Default is 4. # # @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) self.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 self end # @return [Boolean] true if this connection is still not fully open def connecting? status == :connecting end def closed? status == :closed end 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 # # 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 # @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 connection_tune = frame.decode_payload @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 @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) @logger = ::Logger.new(@logfile) @logger.level = normalize_log_level(level) @logger.progname = self.to_s @logger 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 Document :network_recovery_interval 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 (connection to RabbitMQ). # @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 }, :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 Timeout for client operations that expect a response (e.g. {Bunny::Queue#get}), in seconds. Default is 4. # # @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) self.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 self end # @return [Boolean] true if this connection is still not fully open def connecting? status == :connecting end def closed? status == :closed end 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 # # 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 # @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 connection_tune = frame.decode_payload @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 @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) @logger = ::Logger.new(@logfile) @logger.level = normalize_log_level(level) @logger.progname = self.to_s @logger 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
# encoding: utf-8 module Bunny # @return [String] Version of the library VERSION = "1.0.0.rc3wip" end 1.0.0.rc3 # encoding: utf-8 module Bunny # @return [String] Version of the library VERSION = "1.0.0.rc3" end
require 'rubygame' require 'c64' require 'c64/scaled_screen' class C64::Prototype attr_accessor :frame include C64::Math def self.attributes { :title => nil, :scale => 2, :border => :light_blue, :screen => :blue, :fps => 50, :framedump => nil } end attributes.keys.each do |attr| define_singleton_method attr do |value = nil, &block| instance_variable_set "@#{attr}", block || value end end # Wrap and delegate methods for ScaledScreen C64::ScaledScreen.instance_methods(false).each do |method| define_method(method) do |*args| @surface.send(method, *args) end end def initialize(options = {}) self.class.attributes.each do |key, default| value = options[key] value = self.class.instance_variable_get("@#{key}") if value.nil? value = (default.is_a?(Proc) ? default.call : default) if value.nil? instance_variable_set "@#{key}", value end init if respond_to? :init end def self.run @title ||= name new.run end def run setup_screen setup_event_queue setup_clock @frame = 0 @pause = false loop do @queue.each { |event| handle_event(event) } if !@pause || @step update if @step @step = false end end @clock.tick end end def update @surface.clear true draw if respond_to? :draw @surface.flip if @framedump && @frame < @framedump[:count] @surface.savebmp "#{@framedump[:path]}/frame-#{'%04d' % @frame}.bmp" end @frame += 1 end def handle_event(event) case event when Rubygame::Events::KeyPressed case event.key when :escape quit when :p @pause = !@pause when :space @step = true end when Rubygame::Events::QuitRequested quit end end def quit Rubygame.quit exit end private def setup_screen color = {:screen => @screen, :border => @border} @surface = C64::ScaledScreen.new(:scale => @scale, :title => @title, :color => color, :border => !!@border) end def setup_event_queue @queue = Rubygame::EventQueue.new @queue.enable_new_style_events end def setup_clock @clock = Rubygame::Clock.new @clock.target_framerate = @fps end end Added :every parameter to framedump, for dumping selected frames only. require 'rubygame' require 'c64' require 'c64/scaled_screen' class C64::Prototype attr_accessor :frame include C64::Math def self.attributes { :title => nil, :scale => 2, :border => :light_blue, :screen => :blue, :fps => 50, :framedump => nil } end attributes.keys.each do |attr| define_singleton_method attr do |value = nil, &block| instance_variable_set "@#{attr}", block || value end end # Wrap and delegate methods for ScaledScreen C64::ScaledScreen.instance_methods(false).each do |method| define_method(method) do |*args| @surface.send(method, *args) end end def initialize(options = {}) self.class.attributes.each do |key, default| value = options[key] value = self.class.instance_variable_get("@#{key}") if value.nil? value = (default.is_a?(Proc) ? default.call : default) if value.nil? instance_variable_set "@#{key}", value end init if respond_to? :init end def self.run @title ||= name new.run end def run setup_screen setup_event_queue setup_clock @frame = 0 @pause = false loop do @queue.each { |event| handle_event(event) } if !@pause || @step update if @step @step = false end end @clock.tick end end def update @surface.clear true draw if respond_to? :draw @surface.flip if @framedump && @frame < @framedump[:count] if @framedump[:every].nil? || (@frame % @framedump[:every] == 0) @surface.savebmp "#{@framedump[:path]}/frame-#{'%04d' % @frame}.bmp" end end @frame += 1 end def handle_event(event) case event when Rubygame::Events::KeyPressed case event.key when :escape quit when :p @pause = !@pause when :space @step = true end when Rubygame::Events::QuitRequested quit end end def quit Rubygame.quit exit end private def setup_screen color = {:screen => @screen, :border => @border} @surface = C64::ScaledScreen.new(:scale => @scale, :title => @title, :color => color, :border => !!@border) end def setup_event_queue @queue = Rubygame::EventQueue.new @queue.enable_new_style_events end def setup_clock @clock = Rubygame::Clock.new @clock.target_framerate = @fps end end
module CakeLang module CLI class << self # Handle unavailable methods # @param [String] name [called Methodname] # @param [Array] *args [Available args] def method_missing(name, *args) puts "Command #{name} not available" print "Available Commands are: \n\n" self.methods(false).each do |method| print "\t #{method}\n" unless method == :method_missing end print "\n" end def compile(args) file = args[0] option = args[1] input = "" input_array = [] tokens = [] File.open(file, "r") do |f| input = f.read end tokens = CakeLang::Lexer.new.lex(input.strip) ast = CakeLang::Parser.new.parse(tokens.dup) code = CakeLang::CodeGenerator::C.compile(ast) if option.eql?('--debug') puts "Tokenized input:\n" puts "#{tokens.inspect}\n\n" puts "Abstract Syntax Tree:\n" puts "#{ast.inspect}\n\n" puts "Generated Code:\n" puts "#{code.inspect}\n\n" end @filename = file.split('.')[0] system("echo '#{code}' > #{@filename}.c") system("gcc -o #{@filename} #{@filename}.c") end def run(args) compile(args) system("./#{@filename}") end end end end output each part after generation (tokens, ast, code) module CakeLang module CLI class << self # Handle unavailable methods # @param [String] name [called Methodname] # @param [Array] *args [Available args] def method_missing(name, *args) puts "Command #{name} not available" print "Available Commands are: \n\n" self.methods(false).each do |method| print "\t #{method}\n" unless method == :method_missing end print "\n" end def compile(args) file = args[0] option = args[1] input = "" input_array = [] tokens = [] File.open(file, "r") do |f| input = f.read end tokens = CakeLang::Lexer.new.lex(input.strip) if option.eql?('--debug') puts "Tokenized input:\n" puts "#{tokens.inspect}\n\n" end ast = CakeLang::Parser.new.parse(tokens.dup) if option.eql?('--debug') puts "Abstract Syntax Tree:\n" puts "#{ast.inspect}\n\n" end code = CakeLang::CodeGenerator::C.compile(ast) if option.eql?('--debug') puts "Generated Code:\n" puts "#{code.inspect}\n\n" end @filename = file.split('.')[0] system("echo '#{code}' > #{@filename}.c") system("gcc -o #{@filename} #{@filename}.c") end def run(args) compile(args) system("./#{@filename}") end end end end
module Calyx VERSION = '0.9.0'.freeze end Bump version to 0.9.1 module Calyx VERSION = '0.9.1'.freeze end
module Chars # chars version VERSION = '0.2.2' end Version bump to 0.2.3. module Chars # chars version VERSION = '0.2.3' end
module Chiizu class Runner NEEDED_PERMISSIONS = [ 'android.permission.READ_EXTERNAL_STORAGE', 'android.permission.WRITE_EXTERNAL_STORAGE', 'android.permission.CHANGE_CONFIGURATION' ].freeze attr_accessor :number_of_retries def initialize @executor = FastlaneCore::CommandExecutor @config = Chiizu.config @android_env = Chiizu.android_environment end def run FastlaneCore::PrintTable.print_values(config: @config, hide_keys: [], title: "Summary for chiizu #{Chiizu::VERSION}") app_apk_path = @config.fetch(:app_apk_path, ask: false) tests_apk_path = @config.fetch(:tests_apk_path, ask: false) discovered_apk_paths = Dir[File.join('**', '*.apk')] apk_paths_provided = app_apk_path && !app_apk_path.empty? && tests_apk_path && !tests_apk_path.empty? unless apk_paths_provided || discovered_apk_paths.any? UI.error 'No APK paths were provided and no APKs could be found' UI.error "Please provide APK paths with 'app_apk_path' and 'tests_apk_path' and make sure you have assembled APKs prior to running this command." return end test_classes_to_use = @config[:use_tests_in_classes] test_packages_to_use = @config[:use_tests_in_packages] if test_classes_to_use && test_classes_to_use.any? && test_packages_to_use && test_packages_to_use.any? UI.error "'use_tests_in_classes' and 'use_tests_in_packages' can not be combined. Please use one or the other." return end clear_local_previous_screenshots device_serial = select_device device_screenshots_path = determine_device_screenshots_path(device_serial) clear_device_previous_screenshots(device_serial, device_screenshots_path) app_apk_path ||= select_app_apk(discovered_apk_paths) tests_apk_path ||= select_tests_apk(discovered_apk_paths) validate_apk(app_apk_path) install_apks(device_serial, app_apk_path, tests_apk_path) grant_permissions(device_serial) run_tests(device_serial, test_classes_to_use, test_packages_to_use) pull_screenshots_from_device(device_serial, device_screenshots_path) open_screenshots_summary UI.success 'Your screenshots are ready! 📷✨' end def select_device devices = @executor.execute(command: "adb devices -l", print_all: true, print_command: true).split("\n") # the first output by adb devices is "List of devices attached" so remove that devices = devices.drop(1) UI.user_error! 'There are no connected devices or emulators' if devices.empty? devices.select! { |d| d.include?(@config[:specific_device]) } if @config[:specific_device] UI.user_error! "No connected devices matched your criteria: #{@config[:specific_device]}" if devices.empty? if devices.length > 1 UI.important "Multiple connected devices, selecting the first one" UI.important "To specify which connected device to use, use the -s (specific_device) config option" end # grab the serial number. the lines of output can look like these: # 00c22d4d84aec525 device usb:2148663295X product:bullhead model:Nexus_5X device:bullhead # 192.168.1.100:5555 device usb:2148663295X product:bullhead model:Nexus_5X device:genymotion # emulator-5554 device usb:2148663295X product:bullhead model:Nexus_5X device:emulator devices[0].match(/^\S+/)[0] end def select_app_apk(discovered_apk_paths) UI.important "To not be asked about this value, you can specify it using 'app_apk_path'" UI.select('Select your debug app APK', discovered_apk_paths) end def select_tests_apk(discovered_apk_paths) UI.important "To not be asked about this value, you can specify it using 'tests_apk_path'" UI.select('Select your debug tests APK', discovered_apk_paths) end def clear_local_previous_screenshots if @config[:clear_previous_screenshots] UI.message "Clearing output directory of screenshots at #{@config[:output_directory]}" files = Dir.glob(File.join('.', @config[:output_directory], '**', '*.png')) File.delete(*files) end end def determine_device_screenshots_path(device_serial) device_ext_storage = @executor.execute(command: "adb -s #{device_serial} shell echo \\$EXTERNAL_STORAGE", print_all: true, print_command: true) File.join(device_ext_storage, @config[:app_package_name]) end def clear_device_previous_screenshots(device_serial, device_screenshots_path) UI.message 'Cleaning screenshots directory on device' @executor.execute(command: "adb -s #{device_serial} shell rm -rf #{device_screenshots_path}", print_all: true, print_command: true) end def validate_apk(app_apk_path) unless @android_env.aapt_path UI.important "The `aapt` command could not be found on your system, so your app APK could not be validated" return end UI.message 'Validating app APK' apk_permissions = @executor.execute(command: "#{@android_env.aapt_path} dump permissions #{app_apk_path}", print_all: true, print_command: true) missing_permissions = NEEDED_PERMISSIONS.reject { |needed| apk_permissions.include?(needed) } if missing_permissions.any? UI.user_error! "The needed permission(s) #{missing_permissions.join(', ')} could not be found in your app APK" end end def install_apks(device_serial, app_apk_path, tests_apk_path) UI.message 'Installing app APK' apk_install_output = @executor.execute(command: "adb -s #{device_serial} install -r #{app_apk_path}", print_all: true, print_command: true) UI.user_error! "App APK could not be installed" if apk_install_output.include?("Failure [") UI.message 'Installing tests APK' apk_install_output = @executor.execute(command: "adb -s #{device_serial} install -r #{tests_apk_path}", print_all: true, print_command: true) UI.user_error! "Tests APK could not be installed" if apk_install_output.include?("Failure [") end def grant_permissions(device_serial) UI.message 'Granting the permission necessary to change locales on the device' @executor.execute(command: "adb -s #{device_serial} shell pm grant #{@config[:app_package_name]} android.permission.CHANGE_CONFIGURATION", print_all: true, print_command: true) device_api_version = @executor.execute(command: "adb -s #{device_serial} shell getprop ro.build.version.sdk", print_all: true, print_command: true).to_i if device_api_version >= 23 UI.message 'Granting the permissions necessary to access device external storage' @executor.execute(command: "adb -s #{device_serial} shell pm grant #{@config[:app_package_name]} android.permission.WRITE_EXTERNAL_STORAGE", print_all: true, print_command: true) @executor.execute(command: "adb -s #{device_serial} shell pm grant #{@config[:app_package_name]} android.permission.READ_EXTERNAL_STORAGE", print_all: true, print_command: true) end end def run_tests(device_serial, test_classes_to_use, test_packages_to_use) @config[:locales].each do |locale| UI.message "Running tests for locale: #{locale}" instrument_command = ["adb -s #{device_serial} shell am instrument --no-window-animation -w", "-e testLocale #{locale.tr('-', '_')}", "-e endingLocale #{@config[:ending_locale].tr('-', '_')}"] instrument_command << "-e class #{test_classes_to_use.join(',')}" if test_classes_to_use instrument_command << "-e package #{test_packages_to_use.join(',')}" if test_packages_to_use instrument_command << "#{@config[:tests_package_name]}/#{@config[:test_instrumentation_runner]}" test_output = @executor.execute(command: instrument_command.join(" \\\n"), print_all: true, print_command: true) UI.user_error! "Tests failed" if test_output.include?("FAILURES!!!") end end def pull_screenshots_from_device(device_serial, device_screenshots_path) UI.message "Pulling captured screenshots from the device" @executor.execute(command: "adb -s #{device_serial} pull #{device_screenshots_path}/app_lens #{@config[:output_directory]}", print_all: true, print_command: true, error: proc do |error_output| UI.error "Make sure you've used Lens.screenshot() in your tests and that your expected tests are being run." UI.user_error! "No screenshots were detected 📷❌" end) end def open_screenshots_summary unless @config[:skip_open_summary] UI.message "Opening screenshots summary" # MCF: this isn't OK on any platform except Mac @executor.execute(command: "open #{@config[:output_directory]}/*/*.png", print_all: false, print_command: true) end end end end Warn when running all tests without specifying a class or package module Chiizu class Runner NEEDED_PERMISSIONS = [ 'android.permission.READ_EXTERNAL_STORAGE', 'android.permission.WRITE_EXTERNAL_STORAGE', 'android.permission.CHANGE_CONFIGURATION' ].freeze attr_accessor :number_of_retries def initialize @executor = FastlaneCore::CommandExecutor @config = Chiizu.config @android_env = Chiizu.android_environment end def run FastlaneCore::PrintTable.print_values(config: @config, hide_keys: [], title: "Summary for chiizu #{Chiizu::VERSION}") app_apk_path = @config.fetch(:app_apk_path, ask: false) tests_apk_path = @config.fetch(:tests_apk_path, ask: false) discovered_apk_paths = Dir[File.join('**', '*.apk')] apk_paths_provided = app_apk_path && !app_apk_path.empty? && tests_apk_path && !tests_apk_path.empty? unless apk_paths_provided || discovered_apk_paths.any? UI.error 'No APK paths were provided and no APKs could be found' UI.error "Please provide APK paths with 'app_apk_path' and 'tests_apk_path' and make sure you have assembled APKs prior to running this command." return end test_classes_to_use = @config[:use_tests_in_classes] test_packages_to_use = @config[:use_tests_in_packages] if test_classes_to_use && test_classes_to_use.any? && test_packages_to_use && test_packages_to_use.any? UI.error "'use_tests_in_classes' and 'use_tests_in_packages' can not be combined. Please use one or the other." return end if (test_classes_to_use.nil? || test_classes_to_use.empty?) && (test_packages_to_use.nil? || test_packages_to_use.empty?) UI.important 'Limiting the test classes run by `chiizu` to just those that generate screenshots can make runs faster.' UI.important 'Consider using the :use_tests_in_classes or :use_tests_in_packages option, and organize your tests accordingly.' end clear_local_previous_screenshots device_serial = select_device device_screenshots_path = determine_device_screenshots_path(device_serial) clear_device_previous_screenshots(device_serial, device_screenshots_path) app_apk_path ||= select_app_apk(discovered_apk_paths) tests_apk_path ||= select_tests_apk(discovered_apk_paths) validate_apk(app_apk_path) install_apks(device_serial, app_apk_path, tests_apk_path) grant_permissions(device_serial) run_tests(device_serial, test_classes_to_use, test_packages_to_use) pull_screenshots_from_device(device_serial, device_screenshots_path) open_screenshots_summary UI.success 'Your screenshots are ready! 📷✨' end def select_device devices = @executor.execute(command: "adb devices -l", print_all: true, print_command: true).split("\n") # the first output by adb devices is "List of devices attached" so remove that devices = devices.drop(1) UI.user_error! 'There are no connected devices or emulators' if devices.empty? devices.select! { |d| d.include?(@config[:specific_device]) } if @config[:specific_device] UI.user_error! "No connected devices matched your criteria: #{@config[:specific_device]}" if devices.empty? if devices.length > 1 UI.important "Multiple connected devices, selecting the first one" UI.important "To specify which connected device to use, use the -s (specific_device) config option" end # grab the serial number. the lines of output can look like these: # 00c22d4d84aec525 device usb:2148663295X product:bullhead model:Nexus_5X device:bullhead # 192.168.1.100:5555 device usb:2148663295X product:bullhead model:Nexus_5X device:genymotion # emulator-5554 device usb:2148663295X product:bullhead model:Nexus_5X device:emulator devices[0].match(/^\S+/)[0] end def select_app_apk(discovered_apk_paths) UI.important "To not be asked about this value, you can specify it using 'app_apk_path'" UI.select('Select your debug app APK', discovered_apk_paths) end def select_tests_apk(discovered_apk_paths) UI.important "To not be asked about this value, you can specify it using 'tests_apk_path'" UI.select('Select your debug tests APK', discovered_apk_paths) end def clear_local_previous_screenshots if @config[:clear_previous_screenshots] UI.message "Clearing output directory of screenshots at #{@config[:output_directory]}" files = Dir.glob(File.join('.', @config[:output_directory], '**', '*.png')) File.delete(*files) end end def determine_device_screenshots_path(device_serial) device_ext_storage = @executor.execute(command: "adb -s #{device_serial} shell echo \\$EXTERNAL_STORAGE", print_all: true, print_command: true) File.join(device_ext_storage, @config[:app_package_name]) end def clear_device_previous_screenshots(device_serial, device_screenshots_path) UI.message 'Cleaning screenshots directory on device' @executor.execute(command: "adb -s #{device_serial} shell rm -rf #{device_screenshots_path}", print_all: true, print_command: true) end def validate_apk(app_apk_path) unless @android_env.aapt_path UI.important "The `aapt` command could not be found on your system, so your app APK could not be validated" return end UI.message 'Validating app APK' apk_permissions = @executor.execute(command: "#{@android_env.aapt_path} dump permissions #{app_apk_path}", print_all: true, print_command: true) missing_permissions = NEEDED_PERMISSIONS.reject { |needed| apk_permissions.include?(needed) } if missing_permissions.any? UI.user_error! "The needed permission(s) #{missing_permissions.join(', ')} could not be found in your app APK" end end def install_apks(device_serial, app_apk_path, tests_apk_path) UI.message 'Installing app APK' apk_install_output = @executor.execute(command: "adb -s #{device_serial} install -r #{app_apk_path}", print_all: true, print_command: true) UI.user_error! "App APK could not be installed" if apk_install_output.include?("Failure [") UI.message 'Installing tests APK' apk_install_output = @executor.execute(command: "adb -s #{device_serial} install -r #{tests_apk_path}", print_all: true, print_command: true) UI.user_error! "Tests APK could not be installed" if apk_install_output.include?("Failure [") end def grant_permissions(device_serial) UI.message 'Granting the permission necessary to change locales on the device' @executor.execute(command: "adb -s #{device_serial} shell pm grant #{@config[:app_package_name]} android.permission.CHANGE_CONFIGURATION", print_all: true, print_command: true) device_api_version = @executor.execute(command: "adb -s #{device_serial} shell getprop ro.build.version.sdk", print_all: true, print_command: true).to_i if device_api_version >= 23 UI.message 'Granting the permissions necessary to access device external storage' @executor.execute(command: "adb -s #{device_serial} shell pm grant #{@config[:app_package_name]} android.permission.WRITE_EXTERNAL_STORAGE", print_all: true, print_command: true) @executor.execute(command: "adb -s #{device_serial} shell pm grant #{@config[:app_package_name]} android.permission.READ_EXTERNAL_STORAGE", print_all: true, print_command: true) end end def run_tests(device_serial, test_classes_to_use, test_packages_to_use) @config[:locales].each do |locale| UI.message "Running tests for locale: #{locale}" instrument_command = ["adb -s #{device_serial} shell am instrument --no-window-animation -w", "-e testLocale #{locale.tr('-', '_')}", "-e endingLocale #{@config[:ending_locale].tr('-', '_')}"] instrument_command << "-e class #{test_classes_to_use.join(',')}" if test_classes_to_use instrument_command << "-e package #{test_packages_to_use.join(',')}" if test_packages_to_use instrument_command << "#{@config[:tests_package_name]}/#{@config[:test_instrumentation_runner]}" test_output = @executor.execute(command: instrument_command.join(" \\\n"), print_all: true, print_command: true) UI.user_error! "Tests failed" if test_output.include?("FAILURES!!!") end end def pull_screenshots_from_device(device_serial, device_screenshots_path) UI.message "Pulling captured screenshots from the device" @executor.execute(command: "adb -s #{device_serial} pull #{device_screenshots_path}/app_lens #{@config[:output_directory]}", print_all: true, print_command: true, error: proc do |error_output| UI.error "Make sure you've used Lens.screenshot() in your tests and that your expected tests are being run." UI.user_error! "No screenshots were detected 📷❌" end) end def open_screenshots_summary unless @config[:skip_open_summary] UI.message "Opening screenshots summary" # MCF: this isn't OK on any platform except Mac @executor.execute(command: "open #{@config[:output_directory]}/*/*.png", print_all: false, print_command: true) end end end end
require 'minitest/autorun' require_relative 'bowling' # Common test data version: 1.0.0 3cf5eb9 class BowlingTest < Minitest::Test def setup @game = Game.new end def record(rolls) rolls.each { |pins| @game.roll(pins) } end def test_should_be_able_to_score_a_game_with_all_zeros # skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 0, @game.score end def test_should_be_able_to_score_a_game_with_no_strikes_or_spares skip record([3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6]) assert_equal 90, @game.score end def test_a_spare_followed_by_zeros_is_worth_ten_points skip record([6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 10, @game.score end def test_points_scored_in_the_roll_after_a_spare_are_counted_twice skip record([6, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 16, @game.score end def test_consecutive_spares_each_get_a_one_roll_bonus skip record([5, 5, 3, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 31, @game.score end def test_a_spare_in_the_last_frame_gets_a_one_roll_bonus_that_is_counted_once skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 7]) assert_equal 17, @game.score end def test_a_strike_earns_ten_points_in_a_frame_with_a_single_roll skip record([10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 10, @game.score end def test_points_scored_in_the_two_rolls_after_a_strike_are_counted_twice_as_a_bonus skip record([10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 26, @game.score end def test_consecutive_strikes_each_get_the_two_roll_bonus skip record([10, 10, 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 81, @game.score end def test_a_strike_in_the_last_frame_gets_a_two_roll_bonus_that_is_counted_once skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 1]) assert_equal 18, @game.score end def test_rolling_a_spare_with_the_two_roll_bonus_does_not_get_a_bonus_roll skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 3]) assert_equal 20, @game.score end def test_strikes_with_the_two_roll_bonus_do_not_get_bonus_rolls skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10]) assert_equal 30, @game.score end def test_a_strike_with_the_one_roll_bonus_after_a_spare_in_the_last_frame_does_not_get_a_bonus skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 10]) assert_equal 20, @game.score end def test_all_strikes_is_a_perfect_game skip record([10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]) assert_equal 300, @game.score end def test_rolls_can_not_score_negative_points skip record([]) assert_raises Game::BowlingError do @game.roll(-1) end end def test_a_roll_can_not_score_more_than_10_points skip record([]) assert_raises Game::BowlingError do @game.roll(11) end end def test_two_rolls_in_a_frame_can_not_score_more_than_10_points skip record([5]) assert_raises Game::BowlingError do @game.roll(6) end end def test_bonus_roll_after_a_strike_in_the_last_frame_can_not_score_more_than_10_points skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10]) assert_raises Game::BowlingError do @game.roll(11) end end def test_two_bonus_rolls_after_a_strike_in_the_last_frame_can_not_score_more_than_10_points skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 5]) assert_raises Game::BowlingError do @game.roll(6) end end def test_two_bonus_rolls_after_a_strike_in_the_last_frame_can_score_more_than_10_points_if_one_is_a_strike skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 6]) assert_equal 26, @game.score end def test_the_second_bonus_rolls_after_a_strike_in_the_last_frame_can_not_be_a_strike_if_the_first_one_is_not_a_strike skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6]) assert_raises Game::BowlingError do @game.roll(10) end end def test_second_bonus_roll_after_a_strike_in_the_last_frame_can_not_score_than_10_points skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10]) assert_raises Game::BowlingError do @game.roll(11) end end def test_an_unstarted_game_can_not_be_scored skip record([]) assert_raises Game::BowlingError do @game.score end end def test_an_incomplete_game_can_not_be_scored skip record([0, 0]) assert_raises Game::BowlingError do @game.score end end def test_cannot_roll_if_game_already_has_ten_frames skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_raises Game::BowlingError do @game.roll(0) end end def test_bonus_rolls_for_a_strike_in_the_last_frame_must_be_rolled_before_score_can_be_calculated skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10]) assert_raises Game::BowlingError do @game.score end end def test_both_bonus_rolls_for_a_strike_in_the_last_frame_must_be_rolled_before_score_can_be_calculated skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10]) assert_raises Game::BowlingError do @game.score end end def test_bonus_roll_for_a_spare_in_the_last_frame_must_be_rolled_before_score_can_be_calculated skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3]) assert_raises Game::BowlingError do @game.score end end # Problems in exercism evolve over time, as we find better ways to ask # questions. # The version number refers to the version of the problem you solved, # not your solution. # # Define a constant named VERSION inside of the top level BookKeeping # module, which may be placed near the end of your file. # # In your file, it will look like this: # # module BookKeeping # VERSION = 1 # Where the version number matches the one in the test. # end # # If you are curious, read more about constants on RubyDoc: # http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html def test_bookkeeping skip assert_equal 3, BookKeeping::VERSION end end New descriptions from Canonical re: exercism/problem-specifications#832 require 'minitest/autorun' require_relative 'bowling' # Common test data version: 1.0.1 26e345e class BowlingTest < Minitest::Test def setup @game = Game.new end def record(rolls) rolls.each { |pins| @game.roll(pins) } end def test_should_be_able_to_score_a_game_with_all_zeros # skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 0, @game.score end def test_should_be_able_to_score_a_game_with_no_strikes_or_spares skip record([3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6]) assert_equal 90, @game.score end def test_a_spare_followed_by_zeros_is_worth_ten_points skip record([6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 10, @game.score end def test_points_scored_in_the_roll_after_a_spare_are_counted_twice skip record([6, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 16, @game.score end def test_consecutive_spares_each_get_a_one_roll_bonus skip record([5, 5, 3, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 31, @game.score end def test_a_spare_in_the_last_frame_gets_a_one_roll_bonus_that_is_counted_once skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 7]) assert_equal 17, @game.score end def test_a_strike_earns_ten_points_in_a_frame_with_a_single_roll skip record([10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 10, @game.score end def test_points_scored_in_the_two_rolls_after_a_strike_are_counted_twice_as_a_bonus skip record([10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 26, @game.score end def test_consecutive_strikes_each_get_the_two_roll_bonus skip record([10, 10, 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_equal 81, @game.score end def test_a_strike_in_the_last_frame_gets_a_two_roll_bonus_that_is_counted_once skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 1]) assert_equal 18, @game.score end def test_rolling_a_spare_with_the_two_roll_bonus_does_not_get_a_bonus_roll skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 3]) assert_equal 20, @game.score end def test_strikes_with_the_two_roll_bonus_do_not_get_bonus_rolls skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10]) assert_equal 30, @game.score end def test_a_strike_with_the_one_roll_bonus_after_a_spare_in_the_last_frame_does_not_get_a_bonus skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 10]) assert_equal 20, @game.score end def test_all_strikes_is_a_perfect_game skip record([10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]) assert_equal 300, @game.score end def test_rolls_cannot_score_negative_points skip record([]) assert_raises Game::BowlingError do @game.roll(-1) end end def test_a_roll_cannot_score_more_than_10_points skip record([]) assert_raises Game::BowlingError do @game.roll(11) end end def test_two_rolls_in_a_frame_cannot_score_more_than_10_points skip record([5]) assert_raises Game::BowlingError do @game.roll(6) end end def test_bonus_roll_after_a_strike_in_the_last_frame_cannot_score_more_than_10_points skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10]) assert_raises Game::BowlingError do @game.roll(11) end end def test_two_bonus_rolls_after_a_strike_in_the_last_frame_cannot_score_more_than_10_points skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 5]) assert_raises Game::BowlingError do @game.roll(6) end end def test_two_bonus_rolls_after_a_strike_in_the_last_frame_can_score_more_than_10_points_if_one_is_a_strike skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 6]) assert_equal 26, @game.score end def test_the_second_bonus_rolls_after_a_strike_in_the_last_frame_cannot_be_a_strike_if_the_first_one_is_not_a_strike skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6]) assert_raises Game::BowlingError do @game.roll(10) end end def test_second_bonus_roll_after_a_strike_in_the_last_frame_cannot_score_more_than_10_points skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10]) assert_raises Game::BowlingError do @game.roll(11) end end def test_an_unstarted_game_cannot_be_scored skip record([]) assert_raises Game::BowlingError do @game.score end end def test_an_incomplete_game_cannot_be_scored skip record([0, 0]) assert_raises Game::BowlingError do @game.score end end def test_cannot_roll_if_game_already_has_ten_frames skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_raises Game::BowlingError do @game.roll(0) end end def test_bonus_rolls_for_a_strike_in_the_last_frame_must_be_rolled_before_score_can_be_calculated skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10]) assert_raises Game::BowlingError do @game.score end end def test_both_bonus_rolls_for_a_strike_in_the_last_frame_must_be_rolled_before_score_can_be_calculated skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10]) assert_raises Game::BowlingError do @game.score end end def test_bonus_roll_for_a_spare_in_the_last_frame_must_be_rolled_before_score_can_be_calculated skip record([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3]) assert_raises Game::BowlingError do @game.score end end # Problems in exercism evolve over time, as we find better ways to ask # questions. # The version number refers to the version of the problem you solved, # not your solution. # # Define a constant named VERSION inside of the top level BookKeeping # module, which may be placed near the end of your file. # # In your file, it will look like this: # # module BookKeeping # VERSION = 1 # Where the version number matches the one in the test. # end # # If you are curious, read more about constants on RubyDoc: # http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html def test_bookkeeping skip assert_equal 3, BookKeeping::VERSION end end
############################################################################## # tpkg package management system library # Copyright 2009, 2010 AT&T Interactive # License: MIT (http://www.opensource.org/licenses/mit-license.php) ############################################################################## STDOUT.sync = STDERR.sync = true # All outputs/prompts to the kernel ASAP # When we build the tpkg packages we put this file in # /usr/lib/ruby/site_ruby/1.8/ or similar and then the rest of the ruby # files (versiontype.rb, deployer.rb, etc) into # /usr/lib/ruby/site_ruby/1.8/tpkg/ # We need to tell Ruby to search that tpkg subdirectory. # The alternative is to specify the subdirectory in the require # (require 'tpkg/versiontype' for example), but tpkg is also the name # of the executable script so we can't create a subdirectory here named # tpkg. If we put the subdir in the require lines then users couldn't # run tpkg directly from an svn working copy. tpkglibdir = File.join(File.dirname(__FILE__), 'tpkg') if File.directory?(tpkglibdir) $:.unshift(tpkglibdir) end # We store this gem in our thirdparty directory. So we need to add it # it to the search path # This one is for when everything is installed $:.unshift(File.join(File.dirname(__FILE__), 'thirdparty/kwalify-0.7.1/lib')) # And this one for when we're in the svn directory structure $:.unshift(File.join(File.dirname(File.dirname(__FILE__)), 'thirdparty/kwalify-0.7.1/lib')) begin # Try loading facter w/o gems first so that we don't introduce a # dependency on gems if it is not needed. require 'facter' # Facter rescue LoadError require 'rubygems' require 'facter' end require 'digest/sha2' # Digest::SHA256#hexdigest, etc. require 'uri' # URI require 'net/http' # Net::HTTP require 'net/https' # Net::HTTP#use_ssl, etc. require 'time' # Time#httpdate require 'rexml/document' # REXML::Document require 'fileutils' # FileUtils.cp, rm, etc. require 'tempfile' # Tempfile require 'find' # Find require 'etc' # Etc.getpwnam, getgrnam require 'openssl' # OpenSSL require 'open3' # Open3 require 'versiontype' # Version require 'deployer' require 'set' require 'metadata' require 'kwalify' # for validating yaml class Tpkg VERSION = 'trunk' CONFIGDIR = '/etc' GENERIC_ERR = 1 POSTINSTALL_ERR = 2 POSTREMOVE_ERR = 3 INITSCRIPT_ERR = 4 CONNECTION_TIMEOUT = 10 DEFAULT_OWNERSHIP_UID = 0 attr_reader :installed_directory # # Class methods # @@debug = false def self.set_debug(debug) @@debug = debug end @@prompt = true def self.set_prompt(prompt) @@prompt = prompt end # Find GNU tar or bsdtar in ENV['PATH'] # Raises an exception if a suitable tar cannot be found @@tar = nil @@taroptions = "" @@tarinfo = {:version => 'unknown'} TARNAMES = ['tar', 'gtar', 'gnutar', 'bsdtar'] def self.find_tar if !@@tar catch :tar_found do if !ENV['PATH'] raise "tpkg cannot run because the PATH env variable is not set." end ENV['PATH'].split(':').each do |path| TARNAMES.each do |tarname| if File.executable?(File.join(path, tarname)) IO.popen("#{File.join(path, tarname)} --version 2>/dev/null") do |pipe| pipe.each_line do |line| if line.include?('GNU tar') @@tarinfo[:type] = 'gnu' @@tar = File.join(path, tarname) elsif line.include?('bsdtar') @@tarinfo[:type] = 'bsd' @@tar = File.join(path, tarname) end if line =~ /(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)/ @@tarinfo[:version] = [$1, $2, $3].compact.join(".") end throw :tar_found if @@tar end end end end end # Raise an exception if we didn't find a suitable tar raise "Unable to find GNU tar or bsdtar in PATH" end end # bsdtar uses pax format by default. This format allows for vendor extensions, such # as the SCHILY.* extensions which were introduced by star). bsdtar actually uses # these extensions. These extension headers includde useful, but not vital information. # gnu tar should just ignore them and gives a warning. This is what the latest gnu tar # will do. However, on older gnu tar, it only threw an error at the end. The work # around is to explicitly tell gnu tar to ignore those extensions. if @@tarinfo[:type] == 'gnu' && @@tarinfo[:version] != 'unknown' && @@tarinfo[:version] >= '1.15.1' @@taroptions = "--pax-option='delete=SCHILY.*,delete=LIBARCHIVE.*'" end @@tar.dup end def self.clear_cached_tar @@tar = nil @@taroptions = "" @@tarinfo = {:version => 'unknown'} end # Encrypts the given file in-place (the plaintext file is replaced by the # encrypted file). The resulting file is compatible with openssl's 'enc' # utility. # Algorithm from http://www.ruby-forum.com/topic/101936#225585 MAGIC = 'Salted__' SALT_LEN = 8 @@passphrase = nil def self.encrypt(pkgname, filename, passphrase, cipher='aes-256-cbc') # passphrase can be a callback Proc, call it if that's the case pass = nil if @@passphrase pass = @@passphrase elsif passphrase.kind_of?(Proc) pass = passphrase.call(pkgname) @@passphrase = pass else pass = passphrase end # special handling for directory if File.directory?(filename) Find.find(filename) do |f| encrypt(pkgname, f, pass, cipher) if File.file?(f) end return end salt = OpenSSL::Random::random_bytes(SALT_LEN) c = OpenSSL::Cipher::Cipher.new(cipher) c.encrypt c.pkcs5_keyivgen(pass, salt, 1) tmpfile = Tempfile.new(File.basename(filename), File.dirname(filename)) # Match permissions and ownership of plaintext file st = File.stat(filename) File.chmod(st.mode & 07777, tmpfile.path) begin File.chown(st.uid, st.gid, tmpfile.path) rescue Errno::EPERM raise if Process.euid == 0 end tmpfile.write(MAGIC) tmpfile.write(salt) tmpfile.write(c.update(IO.read(filename)) + c.final) tmpfile.close File.rename(tmpfile.path, filename) end # Decrypt the given file in-place. def self.decrypt(pkgname, filename, passphrase, cipher='aes-256-cbc') # passphrase can be a callback Proc, call it if that's the case pass = nil if @@passphrase pass = @@passphrase elsif passphrase.kind_of?(Proc) pass = passphrase.call(pkgname) @@passphrase = pass else pass = passphrase end if File.directory?(filename) Find.find(filename) do |f| decrypt(pkgname, f, pass, cipher) if File.file?(f) end return end file = File.open(filename) if (buf = file.read(MAGIC.length)) != MAGIC raise "Unrecognized encrypted file #{filename}" end salt = file.read(SALT_LEN) c = OpenSSL::Cipher::Cipher.new(cipher) c.decrypt c.pkcs5_keyivgen(pass, salt, 1) tmpfile = Tempfile.new(File.basename(filename), File.dirname(filename)) # Match permissions and ownership of encrypted file st = File.stat(filename) File.chmod(st.mode & 07777, tmpfile.path) begin File.chown(st.uid, st.gid, tmpfile.path) rescue Errno::EPERM raise if Process.euid == 0 end tmpfile.write(c.update(file.read) + c.final) tmpfile.close File.rename(tmpfile.path, filename) end def self.verify_precrypt_file(filename) # This currently just verifies that the file seems to start with the # right bits. Any further verification would require the passphrase # and cipher so we could decrypt the file, but that would preclude # folks from including precrypt files for which they don't have the # passphrase in a package. In some environments it might be desirable # for folks to be able to build the package even if they couldn't # install it. file = File.open(filename) if (buf = file.read(MAGIC.length)) != MAGIC raise "Unrecognized encrypted file #{filename}" end true end # Makes a package from a directory containing the files to put into the package def self.make_package(pkgsrcdir, passphrase=nil, options = {}) pkgfile = nil # validate the output directory if the user has specified one outdir = options[:out] if outdir outdir = File.expand_path(outdir) if !File.directory?(outdir) raise "#{outdir} is not a valid directory" elsif !File.writable?(outdir) raise "#{outdir} is not writable" end end # Make a working directory workdir = nil # dirname('.') returns '.', which screws things up. So in cases # where the user passed us a directory that doesn't have enough # parts that we can get the parent directory we use a working # directory in the system's temp area. As an alternative we could # use Pathname.realpath to convert whatever the user passed us into # an absolute path. if File.dirname(pkgsrcdir) == pkgsrcdir workdir = tempdir('tpkg') else workdir = tempdir('tpkg', File.dirname(pkgsrcdir)) end begin # Make the 'tpkg' directory for storing the package contents tpkgdir = File.join(workdir, 'tpkg') Dir.mkdir(tpkgdir) # A package really shouldn't be partially relocatable, warn the user if # they're creating such a scourge. if (File.exist?(File.join(pkgsrcdir, 'root')) && File.exist?(File.join(pkgsrcdir, 'reloc'))) warn 'Warning: Your source directory should contain either a "root" or "reloc" directory, but not both.' end # Copy the package contents into that directory # I tried to use FileUtils.cp_r but it doesn't handle symlinks properly # And on further reflection it makes sense to only have one chunk of # code (tar) ever touch the user's files. system("#{find_tar} -C #{pkgsrcdir} -cf - . | #{find_tar} -C #{tpkgdir} -xpf -") || raise("Package content copy failed") # check metadata file errors = [] metadata = Metadata::instantiate_from_dir(tpkgdir) if !metadata raise 'Your source directory does not contain the metadata configuration file.' end # This is for when we're in developement mode or when installed as gem if File.exists?(File.join(File.dirname(File.dirname(__FILE__)), "schema")) schema_dir = File.join(File.dirname(File.dirname(__FILE__)), "schema") # This is the directory where we put our dtd/schema for validating # the metadata file elsif File.exist?(File.join(CONFIGDIR, 'tpkg', 'schema')) schema_dir = File.join(CONFIGDIR, 'tpkg', 'schema') else warn "Warning: unable to find schema for tpkg.yml" end errors = metadata.validate(schema_dir) if schema_dir if errors && !errors.empty? puts "Bad metadata file. Possible error(s):" errors.each {|e| puts e } raise "Failed to create package." unless options[:force] end # file_metadata hold information for files that are installed # by the package. For example, checksum, path, relocatable or not, etc. File.open(File.join(tpkgdir, "file_metadata.bin"), "w") do |file| filemetadata = get_filemetadata_from_directory(tpkgdir) filemetadata[:files].each do |file1| if metadata[:files] && metadata[:files][:files] && metadata[:files][:files].any?{|file2|file2[:path] == file1[:path] && file2[:config]} file1[:config] = true end end data = filemetadata.to_hash.recursively{|h| h.stringify_keys } Marshal::dump(data, file) end # Check all the files are there as specified in the metadata config file metadata[:files][:files].each do |tpkgfile| tpkg_path = tpkgfile[:path] working_path = nil if tpkg_path[0,1] == File::SEPARATOR working_path = File.join(tpkgdir, 'root', tpkg_path) else working_path = File.join(tpkgdir, 'reloc', tpkg_path) end # Raise an exception if any files listed in tpkg.yml can't be found if !File.exist?(working_path) && !File.symlink?(working_path) raise "File #{tpkg_path} referenced in tpkg.yml but not found" end # check permission/ownership of crontab files if tpkgfile[:crontab] data = {:actual_file => working_path, :metadata => metadata, :file_metadata => tpkgfile} perms, uid, gid = predict_file_perms_and_ownership(data) # crontab needs to be owned by root, and is not writable by group or others if uid != 0 warn "Warning: Your cron jobs in \"#{tpkgfile[:path]}\" might fail to run because the file is not owned by root." end if (perms & 0022) != 0 warn "Warning: Your cron jobs in \"#{tpkgfile[:path]}\" might fail to run because the file is writable by group and/or others." end end # Encrypt any files marked for encryption if tpkgfile[:encrypt] if tpkgfile[:encrypt][:precrypt] verify_precrypt_file(working_path) else if passphrase.nil? raise "Package requires encryption but supplied passphrase is nil" end encrypt(metadata[:name], working_path, passphrase, *([tpkgfile[:encrypt][:algorithm]].compact)) end end end unless metadata[:files].nil? or metadata[:files][:files].nil? package_filename = metadata.generate_package_filename package_directory = File.join(workdir, package_filename) Dir.mkdir(package_directory) if outdir pkgfile = File.join(outdir, package_filename + '.tpkg') else pkgfile = File.join(File.dirname(pkgsrcdir), package_filename + '.tpkg') end if File.exist?(pkgfile) || File.symlink?(pkgfile) if @@prompt print "Package file #{pkgfile} already exists, overwrite? [y/N]" response = $stdin.gets if response !~ /^y/i return end end File.delete(pkgfile) end # update metadata file with the tpkg version metadata.add_tpkg_version(VERSION) # Tar up the tpkg directory tpkgfile = File.join(package_directory, 'tpkg.tar') system("#{find_tar} -C #{workdir} -cf #{tpkgfile} tpkg") || raise("tpkg.tar creation failed") # Checksum the tarball # Older ruby version doesn't support this # digest = Digest::SHA256.file(tpkgfile).hexdigest digest = Digest::SHA256.hexdigest(File.read(tpkgfile)) # Create checksum.xml File.open(File.join(package_directory, 'checksum.xml'), 'w') do |csx| csx.puts('<tpkg_checksums>') csx.puts(' <checksum>') csx.puts(' <algorithm>SHA256</algorithm>') csx.puts(" <digest>#{digest}</digest>") csx.puts(' </checksum>') csx.puts('</tpkg_checksums>') end # compress if needed if options[:compress] tpkgfile = compress_file(tpkgfile, options[:compress]) end # Tar up checksum.xml and the main tarball system("#{find_tar} -C #{workdir} -cf #{pkgfile} #{package_filename}") || raise("Final package creation failed") ensure # Remove our working directory FileUtils.rm_rf(workdir) end # Return the filename of the package pkgfile end def self.package_toplevel_directory(package_file) # This assumes the first entry in the tarball is the top level directory. # I think that is a safe assumption. toplevel = nil # FIXME: This is so lame, to read the whole package to get the # first filename. Blech. IO.popen("#{find_tar} -tf #{package_file} #{@@taroptions}") do |pipe| toplevel = pipe.gets if toplevel.nil? raise "Package directory structure of #{package_file} unexpected. Unable to get top level." end toplevel.chomp! # Avoid SIGPIPE, if we don't sink the rest of the output from tar # then tar ends up getting SIGPIPE when it tries to write to the # closed pipe and exits with error, which causes us to throw an # exception down below here when we check the exit status. pipe.read end if !$?.success? raise "Error reading top level directory from #{package_file}" end # Strip off the trailing slash toplevel.sub!(Regexp.new("#{File::SEPARATOR}$"), '') if toplevel.include?(File::SEPARATOR) raise "Package directory structure of #{package_file} unexpected, top level is more than one directory deep" end toplevel end def self.get_filemetadata_from_directory(tpkgdir) filemetadata = {} root_dir = File.join(tpkgdir, "root") reloc_dir = File.join(tpkgdir, "reloc") files = [] Find.find(root_dir, reloc_dir) do |f| next if !File.exist?(f) relocatable = false # Append file separator at the end for directory if File.directory?(f) f += File::SEPARATOR end # check if it's from root dir or reloc dir if f =~ /^#{Regexp.escape(root_dir)}/ short_fn = f[root_dir.length ..-1] else short_fn = f[reloc_dir.length + 1..-1] relocatable = true end next if short_fn.nil? or short_fn.empty? file = {} file[:path] = short_fn file[:relocatable] = relocatable # only do checksum for file if File.file?(f) digest = Digest::SHA256.hexdigest(File.read(f)) file[:checksum] = {:algorithm => "SHA256", :digests => [{:value => digest}]} end files << file end filemetadata['files'] = files #return FileMetadata.new(YAML::dump(filemetadata),'yml') return FileMetadata.new(Marshal::dump(filemetadata),'bin') end def self.verify_package_checksum(package_file, options = {}) topleveldir = options[:topleveldir] || package_toplevel_directory(package_file) # Extract checksum.xml from the package checksum_xml = nil IO.popen("#{find_tar} #{@@taroptions} -xf #{package_file} -O #{File.join(topleveldir, 'checksum.xml')}") do |pipe| checksum_xml = REXML::Document.new(pipe.read) end if !$?.success? raise "Error extracting checksum.xml from #{package_file}" end # Verify checksum.xml checksum_xml.elements.each('/tpkg_checksums/checksum') do |checksum| digest = nil algorithm = checksum.elements['algorithm'].text digest_from_package = checksum.elements['digest'].text case algorithm when 'SHA224' digest = Digest::SHA224.new when 'SHA256' digest = Digest::SHA256.new when 'SHA384' digest = Digest::SHA384.new when 'SHA512' digest = Digest::SHA512.new else raise("Unrecognized checksum algorithm #{checksum.elements['algorithm']}") end # Extract tpkg.tar from the package and digest it extract_tpkg_tar_command = cmd_to_extract_tpkg_tar(package_file, topleveldir) IO.popen(extract_tpkg_tar_command) do |pipe| #IO.popen("#{find_tar} -xf #{package_file} -O #{File.join(topleveldir, 'tpkg.tar')} #{@@taroptions}") do |pipe| # Package files can be quite large, so we digest the package in # chunks. A survey of the Internet turns up someone who tested # various chunk sizes on various platforms and found 4k to be # consistently the best. I'm too lazy to do my own testing. # http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/721d304fc8a5cc71 while buf = pipe.read(4096) digest << buf end end if !$?.success? raise "Error extracting tpkg.tar from #{package_file}" end if digest != digest_from_package raise "Checksum mismatch for #{algorithm}, #{digest} != #{digest_from_package}" end end end # Extracts and returns the metadata from a package file def self.metadata_from_package(package_file, options = {}) topleveldir = options[:topleveldir] || package_toplevel_directory(package_file) # Verify checksum verify_package_checksum(package_file) # Extract and parse tpkg.xml metadata = nil ['yml','xml'].each do |format| file = File.join('tpkg', "tpkg.#{format}") # use popen3 instead of popen because popen display stderr when there's an error such as # tpkg.yml not being there, which is something we want to ignore since old tpkg doesn't # have tpkg.yml file extract_tpkg_tar_command = cmd_to_extract_tpkg_tar(package_file, topleveldir) stdin, stdout, stderr = Open3.popen3("#{extract_tpkg_tar_command} | #{find_tar} -xf - -O #{file}") filecontent = stdout.read if filecontent.nil? or filecontent.empty? next else metadata = Metadata.new(filecontent, format) break end end unless metadata raise "Failed to extract metadata from #{package_file}" end # Insert an attribute on the root element with the package filename metadata[:filename] = File.basename(package_file) return metadata end # Extracts and returns the metadata from a directory of package files def self.metadata_from_directory(directory) metadata = [] # if metadata.xml already exists, then go ahead and # parse it existing_metadata_file = File.join(directory, 'metadata.yml') existing_metadata = {} if File.exists?(existing_metadata_file) metadata_lists = File.read(File.join(directory, 'metadata.yml')).split("---") metadata_lists.each do | metadata_text | if metadata_text =~ /^:?filename:(.+)/ filename = $1.strip existing_metadata[filename] = Metadata.new(metadata_text,'yml') end end end # Populate the metadata array with metadata for all of the packages # in the given directory. Reuse existing metadata if possible. Dir.glob(File.join(directory, '*.tpkg')) do |pkg| if existing_metadata[File.basename(pkg)] metadata << existing_metadata[File.basename(pkg)] else metadata_yml = metadata_from_package(pkg) metadata << metadata_yml end end return metadata end # Extracts the metadata from a directory of package files and saves it # to metadata.xml in that directory def self.extract_metadata(directory, dest=nil) dest = directory if dest.nil? metadata = metadata_from_directory(directory) # And write that out to metadata.yml metadata_tmpfile = Tempfile.new('metadata.yml', dest) metadata.each do | metadata | YAML::dump(metadata.to_hash.recursively{|h| h.stringify_keys }, metadata_tmpfile) #YAML::dump(metadata.to_hash, metadata_tmpfile) end metadata_tmpfile.close File.chmod(0644, metadata_tmpfile.path) File.rename(metadata_tmpfile.path, File.join(dest, 'metadata.yml')) end # Haven't found a Ruby method for creating temporary directories, # so create a temporary file and replace it with a directory. def self.tempdir(basename, tmpdir=Dir::tmpdir) tmpfile = Tempfile.new(basename, tmpdir) tmpdir = tmpfile.path tmpfile.close! Dir.mkdir(tmpdir) tmpdir end @@arch = nil def self.get_arch if !@@arch Facter.loadfacts @@arch = Facter['hardwaremodel'].value end @@arch.dup end # Returns a string representing the OS of this box of the form: # "OSname-OSmajorversion". The OS name is currently whatever facter # returns for the 'operatingsystem' fact. The major version is a bit # messier, as we try on a per-OS basis to come up with something that # represents the major version number of the OS, where binaries are # expected to be compatible across all versions of the OS with that # same major version number. Examples include RedHat-5, CentOS-5, # FreeBSD-7, Darwin-10.5, and Solaris-5.10 @@os = nil def self.get_os if !@@os # Tell facter to load everything, otherwise it tries to dynamically # load the individual fact libraries using a very broken mechanism Facter.loadfacts operatingsystem = Facter['operatingsystem'].value osver = nil if Facter['lsbmajdistrelease'] && Facter['lsbmajdistrelease'].value && !Facter['lsbmajdistrelease'].value.empty? osver = Facter['lsbmajdistrelease'].value elsif operatingsystem == 'Ubuntu' # Work around lack of lsbmajdistrelease on older versions of Ubuntu # due to older version of facter. Support for lsbmajdistrelease on # Ubuntu was added in facter 1.5.3, but there's no good way to force # older Ubuntu systems to a newer version of facter. osver = Facter['lsbdistrelease'].value.split('.').first elsif Facter['kernel'] && Facter['kernel'].value == 'Darwin' && Facter['macosx_productversion'] && Facter['macosx_productversion'].value && !Facter['macosx_productversion'].value.empty? macver = Facter['macosx_productversion'].value # Extract 10.5 from 10.5.6, for example osver = macver.split('.')[0,2].join('.') elsif Facter['operatingsystem'] && Facter['operatingsystem'].value == 'FreeBSD' # Extract 7 from 7.1-RELEASE, for example fbver = Facter['operatingsystemrelease'].value osver = fbver.split('.').first elsif Facter['operatingsystemrelease'] && Facter['operatingsystemrelease'].value && !Facter['operatingsystemrelease'].value.empty? osver = Facter['operatingsystemrelease'].value else raise "Unable to determine proper OS value on this platform" end @@os = "#{operatingsystem}-#{osver}" end @@os.dup end # Given an array of pkgs. Determine if any of those package # satisfy the requirement specified by req def self.packages_meet_requirement?(pkgs, req) pkgs.each do | pkg | return true if Tpkg::package_meets_requirement?(pkg, req) end return false end # pkg is a standard Hash format used in the library to represent an # available package # req is a standard Hash format used in the library to represent package # requirements def self.package_meets_requirement?(pkg, req) result = true puts "pkg_meets_req checking #{pkg.inspect} against #{req.inspect}" if @@debug metadata = pkg[:metadata] if req[:type] == :native && pkg[:source] != :native_installed && pkg[:source] != :native_available # A req for a native package must be satisfied by a native package puts "Package fails native requirement" if @@debug result = false elsif req[:filename] result = false if req[:filename] != metadata[:filename] elsif req[:type] == :tpkg && (pkg[:source] == :native_installed || pkg[:source] == :native_available) # Likewise a req for a tpkg must be satisfied by a tpkg puts "Package fails non-native requirement" if @@debug result = false elsif metadata[:name] == req[:name] same_min_ver_req = false same_max_ver_req = false if req[:allowed_versions] version = metadata[:version] version = "#{version}-#{metadata[:package_version]}" if metadata[:package_version] if !File.fnmatch(req[:allowed_versions], version) puts "Package fails version requirement.)" if @@debug result = false end end if req[:minimum_version] pkgver = Version.new(metadata[:version]) reqver = Version.new(req[:minimum_version]) if pkgver < reqver puts "Package fails minimum_version (#{pkgver} < #{reqver})" if @@debug result = false elsif pkgver == reqver same_min_ver_req = true end end if req[:maximum_version] pkgver = Version.new(metadata[:version]) reqver = Version.new(req[:maximum_version]) if pkgver > reqver puts "Package fails maximum_version (#{pkgver} > #{reqver})" if @@debug result = false elsif pkgver == reqver same_max_ver_req = true end end if same_min_ver_req && req[:minimum_package_version] pkgver = Version.new(metadata[:package_version]) reqver = Version.new(req[:minimum_package_version]) if pkgver < reqver puts "Package fails minimum_package_version (#{pkgver} < #{reqver})" if @@debug result = false end end if same_max_ver_req && req[:maximum_package_version] pkgver = Version.new(metadata[:package_version]) reqver = Version.new(req[:maximum_package_version]) if pkgver > reqver puts "Package fails maximum_package_version (#{pkgver} > #{reqver})" if @@debug result = false end end # The empty? check ensures that a package with no operatingsystem # field matches all clients. if metadata[:operatingsystem] && !metadata[:operatingsystem].empty? && !metadata[:operatingsystem].include?(get_os) && !metadata[:operatingsystem].any?{|os| get_os =~ /#{os}/} puts "Package fails operatingsystem" if @@debug result = false end # Same deal with empty? here if metadata[:architecture] && !metadata[:architecture].empty? && !metadata[:architecture].include?(get_arch) && !metadata[:architecture].any?{|arch| get_arch =~ /#{arch}/} puts "Package fails architecture" if @@debug result = false end else puts "Package fails name" if @@debug result = false end if result puts "Package matches" if @@debug end result end # Define a block for sorting packages in order of desirability # Suitable for passing to Array#sort as array.sort(&SORT_PACKAGES) SORT_PACKAGES = lambda do |a,b| # # We first prepare all of the values we wish to compare # # Name aname = a[:metadata][:name] bname = b[:metadata][:name] # Currently installed # Conflicted about whether this belongs here or not, not sure if all # potential users of this sorting system would want to prefer currently # installed packages. acurrentinstall = 0 if (a[:source] == :currently_installed || a[:source] == :native_installed) && a[:prefer] == true acurrentinstall = 1 end bcurrentinstall = 0 if (b[:source] == :currently_installed || b[:source] == :native_installed) && b[:prefer] == true bcurrentinstall = 1 end # Version aversion = Version.new(a[:metadata][:version]) bversion = Version.new(b[:metadata][:version]) # Package version apkgver = Version.new(0) if a[:metadata][:package_version] apkgver = Version.new(a[:metadata][:package_version]) end bpkgver = Version.new(0) if b[:metadata][:package_version] bpkgver = Version.new(b[:metadata][:package_version]) end # OS # Fewer OSs is better, but zero is least desirable because zero means # the package works on all OSs (i.e. it is the most generic package). # We prefer packages tuned to a particular set of OSs over packages # that work everywhere on the assumption that the package that works # on only a few platforms was tuned more specifically for those # platforms. We remap 0 to a big number so that the sorting works # properly. aoslength = 0 aoslength = a[:metadata][:operatingsystem].length if a[:metadata][:operatingsystem] if aoslength == 0 # See comments above aoslength = 1000 end boslength = 0 boslength = b[:metadata][:operatingsystem].length if b[:metadata][:operatingsystem] if boslength == 0 boslength = 1000 end # Architecture # Same deal here, fewer architectures is better but zero is least desirable aarchlength = 0 aarchlength = a[:metadata][:architecture].length if a[:metadata][:architecture] if aarchlength == 0 aarchlength = 1000 end barchlength = 0 barchlength = b[:metadata][:architecture].length if b[:metadata][:architecture] if barchlength == 0 barchlength = 1000 end # Prefer a currently installed package over an otherwise identical # not installed package even if :prefer==false as a last deciding # factor. acurrentinstallnoprefer = 0 if a[:source] == :currently_installed || a[:source] == :native_installed acurrentinstallnoprefer = 1 end bcurrentinstallnoprefer = 0 if b[:source] == :currently_installed || b[:source] == :native_installed bcurrentinstallnoprefer = 1 end # # Then compare # # The mixture of a's and b's in these two arrays may seem odd at first, # but for some fields bigger is better (versions) but for other fields # smaller is better. [aname, bcurrentinstall, bversion, bpkgver, aoslength, aarchlength, bcurrentinstallnoprefer] <=> [bname, acurrentinstall, aversion, apkgver, boslength, barchlength, acurrentinstallnoprefer] end def self.files_in_package(package_file, options = {}) files = {:root => [], :reloc => []} # If the metadata_directory option is available, it means this package # has been installed and the file_metadata might be available in that directory. # If that's the case, then parse the file_metadata to get the file list. It's # much faster than extracting from the tar file if metadata_directory = options[:metadata_directory] package_name = File.basename(package_file, File.extname(package_file)) file_metadata = FileMetadata::instantiate_from_dir(File.join(metadata_directory, package_name)) end if file_metadata file_metadata[:files].each do |file| if file[:relocatable] files[:reloc] << file[:path] else files[:root] << file[:path] end end else file_lists = [] topleveldir = package_toplevel_directory(package_file) extract_tpkg_tar_cmd = cmd_to_extract_tpkg_tar(package_file, topleveldir) IO.popen("#{extract_tpkg_tar_cmd} | #{find_tar} #{@@taroptions} -tf -") do |pipe| pipe.each do |file| file_lists << file.chomp! end end if !$?.success? raise "Extracting file list from #{package_file} failed" end file_lists.each do |file| if file =~ Regexp.new(File.join('tpkg', 'root')) files[:root] << file.sub(Regexp.new(File.join('tpkg', 'root')), '') elsif file =~ Regexp.new(File.join('tpkg', 'reloc', '.')) files[:reloc] << file.sub(Regexp.new(File.join('tpkg', 'reloc', '')), '') end end end files end def self.lookup_uid(user) uid = nil if user =~ /^\d+$/ # If the user was specified as a numeric UID, use it directly. uid = user else # Otherwise attempt to look up the username to get a UID. # Default to UID 0 if the username can't be found. # TODO: Should we cache this info somewhere? begin pw = Etc.getpwnam(user) uid = pw.uid rescue ArgumentError puts "Package requests user #{user}, but that user can't be found. Using UID 0." uid = 0 end end uid.to_i end def self.lookup_gid(group) gid = nil if group =~ /^\d+$/ # If the group was specified as a numeric GID, use it directly. gid = group else # Otherwise attempt to look up the group to get a GID. Default # to GID 0 if the group can't be found. # TODO: Should we cache this info somewhere? begin gr = Etc.getgrnam(group) gid = gr.gid rescue ArgumentError puts "Package requests group #{group}, but that group can't be found. Using GID 0." gid = 0 end end gid.to_i end def self.gethttp(uri) if uri.scheme != 'http' && uri.scheme != 'https' # It would be possible to add support for FTP and possibly # other things if anyone cares raise "Only http/https URIs are supported, got: '#{uri}'" end http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == 'https' # Eliminate the OpenSSL "using default DH parameters" warning if File.exist?(File.join(CONFIGDIR, 'tpkg', 'dhparams')) dh = OpenSSL::PKey::DH.new(IO.read(File.join(CONFIGDIR, 'tpkg', 'dhparams'))) Net::HTTP.ssl_context_accessor(:tmp_dh_callback) http.tmp_dh_callback = proc { dh } end http.use_ssl = true if File.exist?(File.join(CONFIGDIR, 'tpkg', 'ca.pem')) http.ca_file = File.join(CONFIGDIR, 'tpkg', 'ca.pem') http.verify_mode = OpenSSL::SSL::VERIFY_PEER elsif File.directory?(File.join(CONFIGDIR, 'tpkg', 'ca')) http.ca_path = File.join(CONFIGDIR, 'tpkg', 'ca') http.verify_mode = OpenSSL::SSL::VERIFY_PEER end end http.start http end # foo # foo=1.0 # foo=1.0=1 # foo-1.0-1.tpkg def self.parse_request(request, installed_dir = nil) # FIXME: Add support for <, <=, >, >= req = {} parts = request.split('=') # upgrade/remove/query options could take package filenames # We're assuming that the filename ends in .tpkg and has a version number that starts # with a digit. For example: foo-1.0.tpkg, foo-bar-1.0-1.tpkg if request =~ /\.tpkg$/ req = {:filename => request, :name => request.split(/-\d/)[0]} elsif parts.length > 2 && parts[-2] =~ /^[\d\.]/ && parts[-1] =~ /^[\d\.]/ package_version = parts.pop version = parts.pop req[:name] = parts.join('-') req[:minimum_version] = version req[:maximum_version] = version req[:minimum_package_version] = package_version req[:maximum_package_version] = package_version elsif parts.length > 1 && parts[-1] =~ /^[\d\.]/ version = parts.pop req[:name] = parts.join('-') req[:minimum_version] = version req[:maximum_version] = version else req[:name] = parts.join('-') end req[:type] = :tpkg req end # deploy_options is used for configuration the deployer. It is a map of option_names => option_values. Possible # options are: use-ssh-key, deploy-as, worker-count, abort-on-fail # # deploy_params is an array that holds the list of paramters that is used when invoking tpkg on to the remote # servers where we want to deploy to. # # servers is an array, a filename or a callback that list the remote servers where we want to deploy to def self.deploy(deploy_params, deploy_options, servers) servers.uniq! deployer = Deployer.new(deploy_options) deployer.deploy(deploy_params, servers) end # Given a pid, check if it is running def self.process_running?(pid) return false if pid.nil? or pid == "" begin Process.kill(0, pid.to_i) rescue Errno::ESRCH return false rescue => e puts e return true end end # Prompt user to confirm yes or no. Default to yes if user just hit enter without any input. def self.confirm while true print "Confirm? [Y/n] " response = $stdin.gets if response =~ /^n/i return false elsif response =~ /^y|^\s$/i return true end end end def self.extract_tpkg_metadata_file(package_file) result = "" workdir = "" begin topleveldir = Tpkg::package_toplevel_directory(package_file) workdir = Tpkg::tempdir(topleveldir) extract_tpkg_tar_command = cmd_to_extract_tpkg_tar(package_file, topleveldir) system("#{extract_tpkg_tar_command} | #{find_tar} #{@@taroptions} -C #{workdir} -xpf -") if File.exist?(File.join(workdir,"tpkg", "tpkg.yml")) metadata_file = File.join(workdir,"tpkg", "tpkg.yml") elsif File.exist?(File.join(workdir,"tpkg", "tpkg.xml")) metadata_file = File.join(workdir,"tpkg", "tpkg.xml") else raise "#{package_file} does not contain metadata configuration file." end result = File.read(metadata_file) rescue puts "Failed to extract package." ensure FileUtils.rm_rf(workdir) if workdir end return result end # The only restriction right now is that the file doesn't begin with "." def self.valid_pkg_filename?(filename) return File.basename(filename) !~ /^\./ end # helper method for predicting the permissions and ownership of a file that # will be installed by tpkg. This is done by looking at: # 1) its current perms & ownership # 2) the file_defaults settings of the metadata file # 3) the explicitly defined settings in the corresponding file section of the metadata file def self.predict_file_perms_and_ownership(data) perms = uid = gid = nil # get current permission and ownership if data[:actual_file] stat = File.stat(data[:actual_file]) perms = stat.mode # This is what we set the ownership to by default uid = DEFAULT_OWNERSHIP_UID gid = DEFAULT_OWNERSHIP_UID end # get default permission and ownership metadata = data[:metadata] if (metadata && metadata[:files] && metadata[:files][:file_defaults] && metadata[:files][:file_defaults][:posix]) uid = Tpkg::lookup_uid(metadata[:files][:file_defaults][:posix][:owner]) if metadata[:files][:file_defaults][:posix][:owner] gid = Tpkg::lookup_gid(metadata[:files][:file_defaults][:posix][:group]) if metadata[:files][:file_defaults][:posix][:group] perms = metadata[:files][:file_defaults][:posix][:perms] if metadata[:files][:file_defaults][:posix][:perms] end # get explicitly defined permission and ownership file_metadata = data[:file_metadata] if file_metadata && file_metadata[:posix] uid = Tpkg::lookup_uid(file_metadata[:posix][:owner]) if file_metadata[:posix][:owner] gid = Tpkg::lookup_gid(file_metadata[:posix][:group]) if file_metadata[:posix][:group] perms = file_metadata[:posix][:perms] if file_metadata[:posix][:perms] end return perms, uid, gid end # Given a package file, figure out if tpkg.tar was compressed # Return what type of compression. If tpkg.tar wasn't compressed, then return nil. def self.get_compression(package_file) compression = nil IO.popen("#{find_tar} #{@@taroptions} -tf #{package_file}") do |pipe| pipe.each do |file| if file =~ /tpkg.tar.gz$/ compression = "gzip" elsif file =~ /tpkg.tar.bz2$/ compression = "bz2" end end end return compression end # Given a .tpkg file and the topleveldir, generate the command for # extracting tpkg.tar def self.cmd_to_extract_tpkg_tar(package_file, topleveldir) compression = get_compression(package_file) if compression == "gzip" cmd = "#{find_tar} #{@@taroptions} -xf #{package_file} -O #{File.join(topleveldir, 'tpkg.tar.gz')} | gunzip -c" elsif compression == "bz2" cmd = "#{find_tar} #{@@taroptions} -xf #{package_file} -O #{File.join(topleveldir, 'tpkg.tar.bz2')} | bunzip2 -c" else cmd = "#{find_tar} #{@@taroptions} -xf #{package_file} -O #{File.join(topleveldir, 'tpkg.tar')}" end end # Compresses the file using the compression type # specified by the compress flag # Returns the compressed file def self.compress_file(file, compress) if compress == true or compress == "gzip" result = "#{file}.gz" system("gzip #{file}") elsif compress == "bz2" result = "#{file}.bz2" system("bzip2 #{file}") else raise "Compression #{compress} is not supported" end if !$?.success? or !File.exists?(result) raise "Failed to compress the package" end return result end # Used where we wish to capture an exception and modify the message. This # method returns a new exception with desired message but with the backtrace # from the original exception so that the backtrace info is not lost. This # is necessary because Exception lacks a set_message method. def self.wrap_exception(e, message) eprime = e.exception(message) eprime.set_backtrace(e.backtrace) eprime end # # Instance methods # DEFAULT_BASE = '/opt/tpkg' def initialize(options) # Options @base = options[:base] # An array of filenames or URLs which point to individual package files # or directories containing packages and extracted metadata. @sources = [] if options[:sources] @sources = options[:sources] # Clean up any URI sources by ensuring they have a trailing slash # so that they are compatible with URI::join @sources.map! do |source| if !File.exist?(source) && source !~ %r{/$} source << '/' end source end end @report_server = nil if options[:report_server] @report_server = options[:report_server] end @lockforce = false if options.has_key?(:lockforce) @lockforce = options[:lockforce] end @force =false if options.has_key?(:force) @force = options[:force] end @sudo = true if options.has_key?(:sudo) @sudo = options[:sudo] end @file_system_root = '/' # Not sure if this needs to be more portable # This option is only intended for use by the test suite if options[:file_system_root] @file_system_root = options[:file_system_root] @base = File.join(@file_system_root, @base) end # Various external scripts that we run might need to adjust things for # relocatable packages based on the base directory. Set $TPKG_HOME so # those scripts know what base directory is being used. ENV['TPKG_HOME'] = @base # Other instance variables @metadata = {} @available_packages = {} @available_native_packages = {} @var_directory = File.join(@base, 'var', 'tpkg') if !File.exist?(@var_directory) begin FileUtils.mkdir_p(@var_directory) rescue Errno::EACCES raise if Process.euid == 0 rescue Errno::EIO => e if Tpkg::get_os =~ /Darwin/ # Try to help our Mac OS X users, otherwise this could be # rather confusing. warn "\nNote: /home is controlled by the automounter by default on Mac OS X.\n" + "You'll either need to disable that in /etc/auto_master or configure\n" + "tpkg to use a different base via tpkg.conf.\n" end raise e end end @installed_directory = File.join(@var_directory, 'installed') @metadata_directory = File.join(@installed_directory, 'metadata') @sources_directory = File.join(@var_directory, 'sources') @tmp_directory = File.join(@var_directory, 'tmp') @log_directory = File.join(@var_directory, 'logs') # It is important to create these dirs in correct order dirs_to_create = [@installed_directory, @metadata_directory, @sources_directory, @tmp_directory, @log_directory] dirs_to_create.each do |dir| if !File.exist?(dir) begin FileUtils.mkdir_p(dir) rescue Errno::EACCES raise if Process.euid == 0 end end end @tar = Tpkg::find_tar @external_directory = File.join(@file_system_root, 'usr', 'lib', 'tpkg', 'externals') @lock_directory = File.join(@var_directory, 'lock') @lock_pid_file = File.join(@lock_directory, 'pid') @locks = 0 @installed_metadata = {} @available_packages_cache = {} end attr_reader :base attr_reader :sources attr_reader :report_server attr_reader :lockforce attr_reader :force attr_reader :sudo attr_reader :file_system_root def source_to_local_directory(source) source_as_directory = source.gsub(/[^a-zA-Z0-9]/, '') File.join(@sources_directory, source_as_directory) end # One-time operations related to loading information about available # packages def prep_metadata if @metadata.empty? metadata = {} @sources.each do |source| if File.file?(source) metadata_yml = Tpkg::metadata_from_package(source) metadata_yml.source = source name = metadata_yml[:name] metadata[name] = [] if !metadata[name] metadata[name] << metadata_yml elsif File.directory?(source) if !File.exists?(File.join(source, 'metadata.yml')) warn "Warning: the source directory #{source} has no metadata.yml file. Try running tpkg -x #{source} first." next end metadata_contents = File.read(File.join(source, 'metadata.yml')) Metadata::get_pkgs_metadata_from_yml_doc(metadata_contents, metadata, source) else uri = http = localdate = remotedate = localdir = localpath = nil uri = URI.join(source, 'metadata.yml') http = Tpkg::gethttp(uri) # Calculate the path to the local copy of the metadata for this URI localdir = source_to_local_directory(source) localpath = File.join(localdir, 'metadata.yml') if File.exist?(localpath) localdate = File.mtime(localpath) end # get last modified time of the metadata file from the server response = http.head(uri.path) case response when Net::HTTPSuccess remotedate = Time.httpdate(response['Date']) else puts "Error fetching metadata from #{uri}: #{response.body}" response.error! # Throws an exception end # Fetch the metadata if necessary metadata_contents = nil if !localdate || remotedate != localdate response = http.get(uri.path) case response when Net::HTTPSuccess metadata_contents = response.body remotedate = Time.httpdate(response['Date']) # Attempt to save a local copy, might not work if we're not # running with sufficient privileges begin if !File.exist?(localdir) FileUtils.mkdir_p(localdir) end File.open(localpath, 'w') do |file| file.puts(response.body) end File.utime(remotedate, remotedate, localpath) rescue Errno::EACCES raise if Process.euid == 0 end else puts "Error fetching metadata from #{uri}: #{response.body}" response.error! # Throws an exception end else metadata_contents = IO.read(localpath) end # This method will parse the yml doc and populate the metadata variable # with list of pkgs' metadata Metadata::get_pkgs_metadata_from_yml_doc(metadata_contents, metadata, source) end end @metadata = metadata if @@debug @sources.each do |source| count = metadata.inject(0) do |memo,m| # metadata is a hash of pkgname => array of Metadata # objects. # Thus m is a 2 element array of [pkgname, array of # Metadata objects] And thus m[1] is the array of # Metadata objects. memo + m[1].select{|mo| mo.source == source}.length end puts "Found #{count} packages from #{source}" end end end end # Populate our list of available packages for a given package name def load_available_packages(name=nil) prep_metadata if name if !@available_packages[name] packages = [] if @metadata[name] @metadata[name].each do |metadata_obj| packages << { :metadata => metadata_obj, :source => metadata_obj.source } end end @available_packages[name] = packages if @@debug puts "Loaded #{@available_packages[name].size} available packages for #{name}" end end else # Load all packages @metadata.each do |pkgname, metadata_objs| if !@available_packages[pkgname] packages = [] metadata_objs.each do |metadata_obj| packages << { :metadata => metadata_obj, :source => metadata_obj.source } end @available_packages[pkgname] = packages end end end end # Used by load_available_native_packages to stuff all the info about a # native package into a hash to match the structure we pass around # internally for tpkgs def pkg_for_native_package(name, version, package_version, source) metadata = {} metadata[:name] = name metadata[:version] = version metadata[:package_version] = package_version if package_version pkg = { :metadata => metadata, :source => source } if source == :native_installed pkg[:prefer] = true end pkg end def load_available_native_packages(pkgname) if !@available_native_packages[pkgname] native_packages = [] if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ [ {:arg => 'installed', :header => 'Installed', :source => :native_installed}, {:arg => 'available', :header => 'Available', :source => :native_available} ].each do |yum| cmd = "yum info #{yum[:arg]} #{pkgname}" puts "available_native_packages running '#{cmd}'" if @@debug stderr_first_line = nil Open3.popen3(cmd) do |stdin, stdout, stderr| stdin.close read_packages = false name = version = package_version = nil stdout.each_line do |line| if line =~ /#{yum[:header]} Packages/ # Skip the header lines until we get to this line read_packages = true elsif read_packages if line =~ /^Name\s*:\s*(.+)/ name = $1.strip elsif line =~ /^Arch\s*:\s*(.+)/ arch = $1.strip elsif line =~ /^Version\s*:\s*(.+)/ version = $1.strip.to_s elsif line =~ /^Release\s*:\s*(.+)/ package_version = $1.strip.to_s elsif line =~ /^Repo\s*:\s*(.+)/ repo = $1.strip elsif line =~ /^\s*$/ pkg = pkg_for_native_package(name, version, package_version, yum[:source]) native_packages << pkg name = version = package_version = nil end # In the end we ignore the architecture. Anything that # shows up in yum should be installable on this box, and # the chance of a mismatch between facter's idea of the # architecture and RPM's idea is high. I.e. i386 vs i686 # or i32e vs x86_64 or whatever. end end stderr_first_line = stderr.gets end if !$?.success? # Ignore 'no matching packages', raise anything else if stderr_first_line != "Error: No matching Packages to list\n" raise "available_native_packages error running yum" end end end elsif Tpkg::get_os =~ /Debian|Ubuntu/ # The default 'dpkg -l' format has an optional third column for # errors, which makes it hard to parse reliably. puts "available_native_packages running dpkg-query -W -f='${Package} ${Version} ${Status}\n' #{pkgname}" if @@debug stderr_first_line = nil Open3.popen3("dpkg-query -W -f='${Package} ${Version} ${Status}\n' #{pkgname}") do |stdin, stdout, stderr| stdin.close stdout.each_line do |line| name, debversion, status = line.split(' ', 3) # Seems to be Debian convention that if the package has a # package version you seperate that from the upstream version # with a hyphen. version = nil package_version = nil if debversion =~ /-/ version, package_version = debversion.split('-', 2) else version = debversion end # We want packages with a state of "installed". However, # there's also a state of "not-installed", and the state # field contains several space-seperated values, so we have # to be somewhat careful to pick out "installed". if status.split(' ').include?('installed') pkg = pkg_for_native_package(name, version, package_version, :native_installed) native_packages << pkg end end stderr_first_line = stderr.gets end if !$?.success? # Ignore 'no matching packages', raise anything else if stderr_first_line !~ 'No packages found matching' raise "available_native_packages error running dpkg-query" end end puts "available_native_packages running 'apt-cache show #{pkgname}'" if @@debug IO.popen("apt-cache show #{pkgname}") do |pipe| name = nil version = nil package_version = nil pipe.each_line do |line| if line =~ /^Package: (.*)/ name = $1 version = nil package_version = nil elsif line =~ /^Version: (.*)/ debversion = $1 # Seems to be Debian convention that if the package has a # package version you seperate that from the upstream version # with a hyphen. if debversion =~ /-/ version, package_version = debversion.split('-', 2) else version = debversion end pkg = pkg_for_native_package(name, version, package_version, :native_available) native_packages << pkg end end end if !$?.success? raise "available_native_packages error running apt-cache" end elsif Tpkg::get_os =~ /Solaris/ # Example of pkginfo -x output: # SUNWzfsu ZFS (Usr) # (i386) 11.10.0,REV=2006.05.18.01.46 puts "available_native_packages running 'pkginfo -x #{pkgname}'" if @@debug IO.popen("pkginfo -x #{pkgname}") do |pipe| name = nil version = nil package_version = nil pipe.each_line do |line| if line =~ /^\w/ name = line.split(' ') version = nil package_version = nil else arch, solversion = line.split(' ') # Lots of Sun and some third party packages (including CSW) # seem to use this REV= convention in the version. I've # never seen it documented, but since it seems to be a # widely used convention we'll go with it. if solversion =~ /,REV=/ version, package_version = solversion.split(',REV=') else version = solversion end pkg = pkg_for_native_package(name, version, package_version, :native_installed) native_packages << pkg end end end if !$?.success? raise "available_native_packages error running pkginfo" end if File.exist?('/opt/csw/bin/pkg-get') puts "available_native_packages running '/opt/csw/bin/pkg-get -a'" if @@debug IO.popen('/opt/csw/bin/pkg-get -a') do |pipe| pipe.each_line do |line| next if line =~ /^#/ # Skip comments name, solversion = line.split # pkg-get doesn't have an option to only show available # packages matching a specific name, so we have to look over # all available packages and pick out the ones that match. next if name != pkgname # Lots of Sun and some third party packages (including CSW) # seem to use this REV= convention in the version. I've # never seen it documented, but since it seems to be a # widely used convention we'll go with it. version = nil package_version = nil if solversion =~ /,REV=/ version, package_version = solversion.split(',REV=') else version = solversion end pkg = pkg_for_native_package(name, version, package_version, :native_available) native_packages << pkg end end end elsif Tpkg::get_os =~ /FreeBSD/ puts "available_native_packages running 'pkg_info #{pkgname}'" if @@debug IO.popen("pkg_info #{pkgname}") do |pipe| pipe.each_line do |line| name_and_version = line.split(' ', 3) nameparts = name_and_version.split('-') fbversion = nameparts.pop name = nameparts.join('-') # Seems to be FreeBSD convention that if the package has a # package version you seperate that from the upstream version # with an underscore. version = nil package_version = nil if fbversion =~ /_/ version, package_version = fbversion.split('_', 2) else version = fbversion end pkg = pkg_for_native_package(name, version, package_version, :native_installed) package_version << pkg end end if !$?.success? raise "available_native_packages error running pkg_info" end # FIXME: FreeBSD available packages # We could either poke around in the ports tree (if installed), or # try to recreate the URL "pkg_add -r" would use and pull a # directory listing. elsif Tpkg::get_os =~ /Darwin/ if File.exist?('/opt/local/bin/port') puts "available_native_packages running '/opt/local/bin/port installed #{pkgname}'" if @@debug IO.popen("/opt/local/bin/port installed #{pkgname}") do |pipe| pipe.each_line do |line| next if line =~ /The following ports are currently installed/ next if line =~ /None of the specified ports are installed/ next if line !~ /\(active\)/ name, version = line.split(' ') version.sub!(/^@/, '') # Remove variant names version.sub!(/\+.*/, '') # Remove the _number that is always listed on installed ports, # presumably some sort of differentiator if multiple copies of # the same port version are installed. version.sub!(/_\d+$/, '') package_version = nil pkg = pkg_for_native_package(name, version, package_version, :native_installed) native_packages << pkg end end if !$?.success? raise "available_native_packages error running port" end puts "available_native_packages running '/opt/local/bin/port list #{pkgname}'" if @@debug IO.popen("/opt/local/bin/port list #{pkgname}") do |pipe| pipe.each_line do |line| name, version = line.split(' ') version.sub!(/^@/, '') package_version = nil pkg = pkg_for_native_package(name, version, package_version, :native_available) native_packages << pkg end end if !$?.success? raise "available_native_packages error running port" end else # Fink support would be nice raise "No supported native package tool available on #{Tpkg::get_os}" end else puts "Unknown value for OS: #{Tpkg::get_os}" end @available_native_packages[pkgname] = native_packages if @@debug nicount = native_packages.select{|pkg| pkg[:source] == :native_installed}.length nacount = native_packages.select{|pkg| pkg[:source] == :native_available}.length puts "Found #{nicount} installed native packages for #{pkgname}" puts "Found #{nacount} available native packages for #{pkgname}" end end end # Returns an array of metadata for installed packages def metadata_for_installed_packages metadata = {} if File.directory?(@installed_directory) Dir.foreach(@installed_directory) do |entry| next if entry == '.' || entry == '..' || entry == 'metadata' || !Tpkg::valid_pkg_filename?(entry) # Check the timestamp on the file to see if it is new or has # changed since we last loaded data timestamp = File.mtime(File.join(@installed_directory, entry)) if @installed_metadata[entry] && timestamp == @installed_metadata[entry][:timestamp] puts "Using cached installed metadata for #{entry}" if @@debug metadata[entry] = @installed_metadata[entry] else puts "Loading installed metadata from disk for #{entry}" if @@debug # Check to see if we already have a saved copy of the metadata # Originally tpkg just stored a copy of the package file in # @installed_directory and we had to extract the metadata # from the package file every time we needed it. That was # determined to be too slow, so we now cache a copy of the # metadata separately. However we may encounter installs by # old copies of tpkg and need to extract and cache the # metadata. package_metadata_dir = File.join(@metadata_directory, File.basename(entry, File.extname(entry))) metadata_file = File.join(package_metadata_dir, "tpkg.yml") m = Metadata::instantiate_from_dir(package_metadata_dir) # No cached metadata found, we have to extract it ourselves # and save it for next time if !m m = Tpkg::metadata_from_package( File.join(@installed_directory, entry)) begin FileUtils.mkdir_p(package_metadata_dir) File.open(metadata_file, "w") do |file| YAML::dump(m.to_hash, file) end rescue Errno::EACCES raise if Process.euid == 0 end end metadata[entry] = { :timestamp => timestamp, :metadata => m } unless m.nil? end end end @installed_metadata = metadata # FIXME: dup the array we return? @installed_metadata.collect { |im| im[1][:metadata] } end # Convert metadata_for_installed_packages into pkg hashes def installed_packages(pkgname=nil) instpkgs = [] metadata_for_installed_packages.each do |metadata| if !pkgname || metadata[:name] == pkgname instpkgs << { :metadata => metadata, :source => :currently_installed, # It seems reasonable for this to default to true :prefer => true } end end instpkgs end # Returns a hash of file_metadata for installed packages def file_metadata_for_installed_packages(package_files = nil) ret = {} if package_files package_files.collect!{|package_file| File.basename(package_file, File.extname(package_file))} end if File.directory?(@metadata_directory) Dir.foreach(@metadata_directory) do |entry| next if entry == '.' || entry == '..' next if package_files && !package_files.include?(entry) file_metadata = FileMetadata::instantiate_from_dir(File.join(@metadata_directory, entry)) ret[file_metadata[:package_file]] = file_metadata end end ret end # Returns an array of packages which meet the given requirement def available_packages_that_meet_requirement(req=nil) pkgs = nil puts "avail_pkgs_that_meet_req checking for #{req.inspect}" if @@debug if @available_packages_cache[req] puts "avail_pkgs_that_meet_req returning cached result" if @@debug pkgs = @available_packages_cache[req] else pkgs = [] if req req = req.clone # we're using req as the key for our cache, so it's important # that we clone it here. Otherwise, req can be changed later on from # the calling method and modify our cache inadvertently if req[:type] == :native load_available_native_packages(req[:name]) @available_native_packages[req[:name]].each do |pkg| if Tpkg::package_meets_requirement?(pkg, req) pkgs << pkg end end else load_available_packages(req[:name]) @available_packages[req[:name]].each do |pkg| if Tpkg::package_meets_requirement?(pkg, req) pkgs << pkg end end # There's a weird dicotomy here where @available_packages contains # available tpkg and native packages, and _installed_ native # packages, but not installed tpkgs. That's somewhat intentional, # as we don't want to cache the installed state since that might # change during a run. We probably should be consistent, and not # cache installed native packages either. However, we do have # some intelligent caching of the installed tpkg state which would # be hard to replicate for native packages, and this method gets # called a lot so re-running the native package query commands # frequently would not be acceptable. So maybe we have the right # design, and this just serves as a note that it is not obvious. pkgs.concat(installed_packages_that_meet_requirement(req)) end else # We return everything available if given a nil requirement # We do not include native packages load_available_packages # @available_packages is a hash of pkgname => array of pkgs # Thus m is a 2 element array of [pkgname, array of pkgs] # And thus m[1] is the array of packages pkgs = @available_packages.collect{|m| m[1]}.flatten end @available_packages_cache[req] = pkgs end pkgs end def installed_packages_that_meet_requirement(req=nil) pkgs = [] if req && req[:type] == :native load_available_native_packages(req[:name]) @available_native_packages[req[:name]].each do |pkg| if pkg[:source] == :native_installed && Tpkg::package_meets_requirement?(pkg, req) pkgs << pkg end end else pkgname = nil if req && req[:name] pkgname = req[:name] end # Passing a package name if we have one to installed_packages serves # primarily to make following the debugging output of dependency # resolution easier. The dependency resolution process makes frequent # calls to available_packages_that_meet_requirement, which in turn calls # this method. For available packages we're able to pre-filter based on # package name before calling package_meets_requirement? because we # store available packages hashed based on package name. # package_meets_requirement? is fairly verbose in its debugging output, # so the user sees each package it checks against a given requirement. # It is therefore a bit disconcerting when trying to follow the # debugging output to see the fairly clean process of checking available # packages which have already been filtered to match the desired name, # and then available_packages_that_meet_requirement calls this method, # and the user starts to see every installed package checked against the # same requirement. It is not obvious to the someone why all of a # sudden packages that aren't even remotely close to the requirement # start getting checked. Doing a pre-filter based on package name here # makes the process more consistent and easier to follow. installed_packages(pkgname).each do |pkg| if req if Tpkg::package_meets_requirement?(pkg, req) pkgs << pkg end else pkgs << pkg end end end pkgs end # Takes a files structure as returned by files_in_package. Inserts # a new entry in the structure with the combined relocatable and # non-relocatable file lists normalized to their full paths. def normalize_paths(files) files[:normalized] = [] files[:root].each do |rootfile| files[:normalized] << File.join(@file_system_root, rootfile) end files[:reloc].each do |relocfile| files[:normalized] << File.join(@base, relocfile) end end def normalize_path(path,root=nil,base=nil) root ||= @file_system_root base ||= @base if path[0,1] == File::SEPARATOR normalized_path = File.join(root, path) else normalized_path = File.join(base, path) end normalized_path end def files_for_installed_packages(package_files=nil) files = {} if !package_files package_files = [] metadata_for_installed_packages.each do |metadata| package_files << metadata[:filename] end end metadata_for_installed_packages.each do |metadata| package_file = metadata[:filename] if package_files.include?(package_file) fip = Tpkg::files_in_package(File.join(@installed_directory, package_file), {:metadata_directory => @metadata_directory}) normalize_paths(fip) fip[:metadata] = metadata files[package_file] = fip end end files end # Returns the best solution that meets the given requirements. Some or all # packages may be optionally pre-selected and specified via the packages # parameter, otherwise packages are picked from the set of available # packages. The requirements parameter is an array of package requirements. # The packages parameter is in the form of a hash with package names as keys # pointing to arrays of package specs (our standard hash of package metadata # and source). The core_packages parameter is an array of the names of # packages that should be considered core requirements, i.e. the user # specifically requested they be installed or upgraded. The return value # will be an array of package specs. MAX_POSSIBLE_SOLUTIONS_TO_CHECK = 10000 def best_solution(requirements, packages, core_packages) result = resolve_dependencies(requirements, {:tpkg => packages, :native => {}}, core_packages) if @@debug if result[:solution] puts "bestsol picks: #{result[:solution].inspect}" if @@debug else puts "bestsol checked #{result[:number_of_possible_solutions_checked]} possible solutions, none worked" end end result[:solution] end # Recursive method used by best_solution # Parameters mostly map from best_solution, but packages turns into a hash # with two possible keys, :tpkg and :native. The value for the :tpkg key # would be the packages parameter from best_solution. Native packages are # only installed due to dependencies, we don't let the user request them # directly, so callers of best_solution never need to pass in a package list # for native packages. Separating the two sets of packages allows us to # calculate a solution that contains both a tpkg and a native package with # the same name. This may be necessary if different dependencies of the # core packages end up needing both. def resolve_dependencies(requirements, packages, core_packages, number_of_possible_solutions_checked=0) # We're probably going to make changes to packages, dup it now so # that we don't mess up the caller's state. packages = {:tpkg => packages[:tpkg].dup, :native => packages[:native].dup} # Make sure we have populated package lists for all requirements. # Filter the package lists against the requirements and # ensure we can at least satisfy the initial requirements. requirements.each do |req| if !packages[req[:type]][req[:name]] puts "resolvedeps initializing packages for #{req.inspect}" if @@debug packages[req[:type]][req[:name]] = available_packages_that_meet_requirement(req) else # Loop over packages and eliminate ones that don't work for # this requirement puts "resolvedeps filtering packages for #{req.inspect}" if @@debug packages[req[:type]][req[:name]] = packages[req[:type]][req[:name]].select do |pkg| # When this method is called recursively there might be a # nil entry inserted into packages by the sorting code # below. We need to skip those. if pkg != nil Tpkg::package_meets_requirement?(pkg, req) end end end if packages[req[:type]][req[:name]].empty? if @@debug puts "No packages matching #{req.inspect}" end return {:number_of_possible_solutions_checked => number_of_possible_solutions_checked} end end # FIXME: Should we weed out any entries in packages that don't correspond # to something in requirements? We operate later on the assumption that # there are no such entries. Because we dup packages at the right points # I believe we'll never accidently end up with orphaned entries, but maybe # it would be worth the compute cycles to make sure? # Sort the packages [:tpkg, :native].each do |type| packages[type].each do |pkgname, pkgs| pkgs.sort!(&SORT_PACKAGES) # Only currently installed packages are allowed to score 0. # Anything else can score 1 at best. This ensures # that we prefer the solution which leaves the most # currently installed packages alone. if pkgs[0] && pkgs[0][:source] != :currently_installed && pkgs[0][:source] != :native_installed pkgs.unshift(nil) end end end if @@debug puts "Packages after initial population and filtering:" puts packages.inspect end # Here's an example of the possible solution sets we should come # up with and the proper ordering. Sets with identical averages # are equivalent, the order they appear in does not matter. # # packages: [a0, a1, a2], [b0, b1, b2], [c0, c1, c2] # core_packages: a, b # # [a0, b0, c0] (core avg 0) (avg 0) # [a0, b0, c1] (avg .33) # [a0, b0, c2] (avg .66) # [a0, b1, c0] (core avg .5) (avg .33) # [a1, b0, c0] # [a0, b1, c1] (avg .66) # [a1, b0, c1] # [a0, b1, c2] (avg 1) # [a1, b0, c2] # [a1, b1, c0] (core avg 1) (avg .66) # [a0, b2, c0] # [a2, b0, c0] # [a1, b1, c1] (avg 1) # [a0, b2, c1] # [a2, b0, c1] # [a1, b1, c2] (avg 1.33) # [a0, b2, c2] # [a2, b0, c2] # [a1, b2, c0] (core avg 1.5) (avg 1) # [a2, b1, c0] # [a1, b2, c1] (avg 1.33) # [a2, b1, c1] # [a1, b2, c2] (avg 1.67) # [a2, b1, c2] # [a2, b2, c0] (core avg 2) (avg 1.33) # [a2, b2, c1] (avg 1.67) # [a2, b2, c2] (avg 2) # Divide packages into core and non-core packages corepkgs = packages[:tpkg].reject{|pkgname, pkgs| !core_packages.include?(pkgname)} noncorepkgs = {} noncorepkgs[:tpkg] = packages[:tpkg].reject{|pkgname, pkgs| core_packages.include?(pkgname)} noncorepkgs[:native] = packages[:native] # Calculate total package depth, the sum of the lengths (or rather # the max array index) of each array of packages. coretotaldepth = corepkgs.inject(0) {|memo, pkgs| memo + pkgs[1].length - 1} noncoretotaldepth = noncorepkgs[:tpkg].inject(0) {|memo, pkgs| memo + pkgs[1].length - 1} + noncorepkgs[:native].inject(0) {|memo, pkgs| memo + pkgs[1].length - 1} if @@debug puts "resolvedeps coretotaldepth #{coretotaldepth}" puts "resolvedeps noncoretotaldepth #{noncoretotaldepth}" end # First pass, combinations of core packages (0..coretotaldepth).each do |coredepth| puts "resolvedeps checking coredepth: #{coredepth}" if @@debug core_solutions = [{:remaining_coredepth => coredepth, :pkgs => []}] corepkgs.each do |pkgname, pkgs| puts "resolvedeps corepkg #{pkgname}: #{pkgs.inspect}" if @@debug new_core_solutions = [] core_solutions.each do |core_solution| remaining_coredepth = core_solution[:remaining_coredepth] puts "resolvedeps :remaining_coredepth: #{remaining_coredepth}" if @@debug (0..[remaining_coredepth, pkgs.length-1].min).each do |corepkgdepth| puts "resolvedeps corepkgdepth: #{corepkgdepth}" if @@debug # We insert a nil entry in some situations (see the sort # step earlier), so skip nil entries in the pkgs array. if pkgs[corepkgdepth] != nil coresol = core_solution.dup # Hash#dup doesn't dup each key/value, so we need to # explicitly dup :pkgs so that each copy has an # independent array that we can modify. coresol[:pkgs] = core_solution[:pkgs].dup coresol[:remaining_coredepth] -= corepkgdepth coresol[:pkgs] << pkgs[corepkgdepth] new_core_solutions << coresol # If this is a complete combination of core packages then # proceed to the next step puts "resolvedeps coresol[:pkgs] #{coresol[:pkgs].inspect}" if @@debug if coresol[:pkgs].length == corepkgs.length puts "resolvedeps complete core pkg set: #{coresol.inspect}" if @@debug # Solutions with remaining depth are duplicates of # solutions we already checked at lower depth levels # I.e. at coredepth==0 we'd have: # {:pkgs=>{a0, b0}, :remaining_coredepth=0} # And at coredepth==1: # {:pkgs=>{a0,b0}, :remaining_coredepth=1} # Whereas at coredepth==1 this is new and needs to be checked: # {:pkgs=>{a1,b0}, :remaining_coredepth=0} if coresol[:remaining_coredepth] == 0 # Second pass, add combinations of non-core packages if noncorepkgs[:tpkg].empty? && noncorepkgs[:native].empty? puts "resolvedeps noncorepkgs empty, checking solution" if @@debug result = check_solution(coresol, requirements, packages, core_packages, number_of_possible_solutions_checked) if result[:solution] return result else number_of_possible_solutions_checked = result[:number_of_possible_solutions_checked] end else (0..noncoretotaldepth).each do |noncoredepth| puts "resolvedeps noncoredepth: #{noncoredepth}" if @@debug coresol[:remaining_noncoredepth] = noncoredepth solutions = [coresol] [:tpkg, :native].each do |nctype| noncorepkgs[nctype].each do |ncpkgname, ncpkgs| puts "resolvedeps noncorepkg #{nctype} #{ncpkgname}: #{ncpkgs.inspect}" if @@debug new_solutions = [] solutions.each do |solution| remaining_noncoredepth = solution[:remaining_noncoredepth] puts "resolvedeps :remaining_noncoredepth: #{remaining_noncoredepth}" if @@debug (0..[remaining_noncoredepth, ncpkgs.length-1].min).each do |ncpkgdepth| puts "resolvedeps ncpkgdepth: #{ncpkgdepth}" if @@debug # We insert a nil entry in some situations (see the sort # step earlier), so skip nil entries in the pkgs array. if ncpkgs[ncpkgdepth] != nil sol = solution.dup # Hash#dup doesn't dup each key/value, so we need to # explicitly dup :pkgs so that each copy has an # independent array that we can modify. sol[:pkgs] = solution[:pkgs].dup sol[:remaining_noncoredepth] -= ncpkgdepth sol[:pkgs] << ncpkgs[ncpkgdepth] new_solutions << sol # If this is a complete combination of packages then # proceed to the next step puts "resolvedeps sol[:pkgs] #{sol[:pkgs].inspect}" if @@debug if sol[:pkgs].length == packages[:tpkg].length + packages[:native].length puts "resolvedeps complete pkg set: #{sol.inspect}" if @@debug # Solutions with remaining depth are duplicates of # solutions we already checked at lower depth levels if sol[:remaining_noncoredepth] == 0 result = check_solution(sol, requirements, packages, core_packages, number_of_possible_solutions_checked) if result[:solution] puts "resolvdeps returning successful solution" if @@debug return result else number_of_possible_solutions_checked = result[:number_of_possible_solutions_checked] end end end end end end solutions = new_solutions end end end end end end end end end core_solutions = new_core_solutions end end # No solutions found puts "resolvedeps returning failure" if @@debug return {:number_of_possible_solutions_checked => number_of_possible_solutions_checked} end # Used by resolve_dependencies def check_solution(solution, requirements, packages, core_packages, number_of_possible_solutions_checked) number_of_possible_solutions_checked += 1 # Probably should give the user a way to override this if number_of_possible_solutions_checked > MAX_POSSIBLE_SOLUTIONS_TO_CHECK raise "Checked #{MAX_POSSIBLE_SOLUTIONS_TO_CHECK} possible solutions to requirements and dependencies, no solution found" end if @@debug puts "checksol checking sol #{solution.inspect}" end # Extract dependencies from each package in the solution newreqs = [] solution[:pkgs].each do |pkg| puts "checksol pkg #{pkg.inspect}" if @@debug if pkg[:metadata][:dependencies] pkg[:metadata][:dependencies].each do |depreq| if !requirements.include?(depreq) && !newreqs.include?(depreq) puts "checksol new depreq #{depreq.inspect}" if @@debug newreqs << depreq end end end end if newreqs.empty? # No additional requirements, this is a complete solution puts "checksol no newreqs, complete solution" if @@debug return {:solution => solution[:pkgs]} else newreqs_that_need_packages = [] newreqs.each do |newreq| puts "checksol checking newreq: #{newreq.inspect}" if @@debug if packages[newreq[:type]][newreq[:name]] pkg = solution[:pkgs].find{|solpkg| solpkg[:metadata][:name] == newreq[:name]} puts "checksol newreq pkg: #{pkg.inspect}" if @@debug if pkg && Tpkg::package_meets_requirement?(pkg, newreq) # No change to solution needed else # Solution no longer works puts "checksol solution no longer works" if @@debug return {:number_of_possible_solutions_checked => number_of_possible_solutions_checked} end else puts "checksol newreq needs packages" if @@debug newreqs_that_need_packages << newreq end end if newreqs_that_need_packages.empty? # None of the new requirements changed the solution, so the solution is complete puts "checksol no newreqs that need packages, complete solution" if @@debug return {:solution => solution[:pkgs]} else puts "checksol newreqs need packages, calling resolvedeps" if @@debug result = resolve_dependencies(requirements+newreqs_that_need_packages, packages, core_packages, number_of_possible_solutions_checked) if result[:solution] puts "checksol returning successful solution" if @@debug return result else number_of_possible_solutions_checked = result[:number_of_possible_solutions_checked] end end end puts "checksol returning failure" if @@debug return {:number_of_possible_solutions_checked => number_of_possible_solutions_checked} end def download(source, path, downloaddir = nil, use_cache = true) http = Tpkg::gethttp(URI.parse(source)) localdir = source_to_local_directory(source) localpath = File.join(localdir, File.basename(path)) # Don't download again if file is already there from previous installation # and still has valid checksum if File.file?(localpath) && use_cache begin Tpkg::verify_package_checksum(localpath) return localpath rescue RuntimeError, NoMethodError # Previous download is bad (which can happen for a variety of # reasons like an interrupted download or a bad package on the # server). Delete it and we'll try to grab it again. File.delete(localpath) end else # If downloaddir is specified, then download to that directory. Otherwise, # download to default source directory localdir = downloaddir || localdir if !File.exist?(localdir) FileUtils.mkdir_p(localdir) end localpath = File.join(localdir, File.basename(path)) end uri = URI.join(source, path) tmpfile = Tempfile.new(File.basename(localpath), File.dirname(localpath)) http.request_get(uri.path) do |response| # Package files can be quite large, so we transfer the package to a # local file in chunks response.read_body do |chunk| tmpfile.write(chunk) end remotedate = Time.httpdate(response['Date']) File.utime(remotedate, remotedate, tmpfile.path) end tmpfile.close begin Tpkg::verify_package_checksum(tmpfile.path) File.chmod(0644, tmpfile.path) File.rename(tmpfile.path, localpath) rescue raise "Unable to download and/or verify the package." end localpath end # Given a package's metadata return a hash of init scripts in the # package and the entry for that file from the metadata def init_scripts(metadata) init_scripts = {} # don't do anything unless we have to unless metadata[:files] && metadata[:files][:files] return init_scripts end metadata[:files][:files].each do |tpkgfile| if tpkgfile[:init] tpkg_path = tpkgfile[:path] installed_path = normalize_path(tpkg_path) init_scripts[installed_path] = tpkgfile end end init_scripts end # Given a package's metadata return a hash of init scripts in the # package and where they need to be linked to on the system def init_links(metadata) links = {} init_scripts(metadata).each do |installed_path, tpkgfile| # SysV-style init if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ || Tpkg::get_os =~ /Debian|Ubuntu/ || Tpkg::get_os =~ /Solaris/ start = '99' if tpkgfile[:init][:start] start = tpkgfile[:init][:start] end levels = nil if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ || Tpkg::get_os =~ /Debian|Ubuntu/ levels = ['2', '3', '4', '5'] elsif Tpkg::get_os =~ /Solaris/ levels = ['2', '3'] end if tpkgfile[:init][:levels] levels = tpkgfile[:init][:levels] end init_directory = nil if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ init_directory = File.join(@file_system_root, 'etc', 'rc.d') elsif Tpkg::get_os =~ /Debian|Ubuntu/ || Tpkg::get_os =~ /Solaris/ init_directory = File.join(@file_system_root, 'etc') end # in case user specify levels in yaml as string/integer instead of array if !levels.kind_of?(Array) levels = levels.to_s.split(//) end levels.each do |level| links[File.join(init_directory, "rc#{level}.d", 'S' + start.to_s + File.basename(installed_path))] = installed_path end elsif Tpkg::get_os =~ /FreeBSD/ init_directory = File.join(@file_system_root, 'usr', 'local', 'etc', 'rc.d') if tpkgfile[:init][:levels] && tpkgfile[:init][:levels].empty? # User doesn't want the init script linked in to auto-start else links[File.join(init_directory, File.basename(installed_path))] = installed_path end else warn "No init script support for #{Tpkg::get_os}" end end links end # Given a package's metadata return a hash of crontabs in the # package and where they need to be installed on the system def crontab_destinations(metadata) destinations = {} # Don't do anything unless we have to unless metadata[:files] && metadata[:files][:files] return destinations end metadata[:files][:files].each do |tpkgfile| if tpkgfile[:crontab] tpkg_path = tpkgfile[:path] installed_path = normalize_path(tpkg_path) destinations[installed_path] = {} # Decide whether we're going to add the file to a per-user # crontab or link it into a directory of misc. crontabs. If the # system only supports per-user crontabs we have to go the # per-user route. If the system supports both we decide based on # whether the package specifies a user for the crontab. # Systems that only support per-user style if Tpkg::get_os =~ /FreeBSD/ || Tpkg::get_os =~ /Solaris/ || Tpkg::get_os =~ /Darwin/ if tpkgfile[:crontab][:user] user = tpkgfile[:crontab][:user] if Tpkg::get_os =~ /FreeBSD/ destinations[installed_path][:file] = File.join(@file_system_root, 'var', 'cron', 'tabs', user) elsif Tpkg::get_os =~ /Solaris/ destinations[installed_path][:file] = File.join(@file_system_root, 'var', 'spool', 'cron', 'crontabs', user) elsif Tpkg::get_os =~ /Darwin/ destinations[installed_path][:file] = File.join(@file_system_root, 'usr', 'lib', 'cron', 'tabs', user) end else raise "No user specified for crontab in #{metadata[:filename]}" end # Systems that support cron.d style elsif Tpkg::get_os =~ /RedHat|CentOS|Fedora/ || Tpkg::get_os =~ /Debian|Ubuntu/ # If a user is specified go the per-user route if tpkgfile[:crontab][:user] user = tpkgfile[:crontab][:user] if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ destinations[installed_path][:file] = File.join(@file_system_root, 'var', 'spool', 'cron', user) elsif Tpkg::get_os =~ /Debian|Ubuntu/ destinations[installed_path][:file] = File.join(@file_system_root, 'var', 'spool', 'cron', 'crontabs', user) end # Otherwise go the cron.d route else destinations[installed_path][:link] = File.join(@file_system_root, 'etc', 'cron.d', File.basename(installed_path)) end else warn "No crontab support for #{Tpkg::get_os}" end end end destinations end def run_external(pkgfile, operation, name, data) externalpath = File.join(@external_directory, name) if !File.executable?(externalpath) raise "External #{externalpath} does not exist or is not executable" end case operation when :install begin IO.popen("#{externalpath} '#{pkgfile}' install", 'w') do |pipe| pipe.write(data) end if !$?.success? raise "Exit value #{$?.exitstatus}" end rescue => e # Tell the user which external and package were involved, otherwise # failures in externals are very hard to debug # FIXME: should we clean up the external request files? raise Tpkg.wrap_exception(e, "External #{name} #{operation} for #{File.basename(pkgfile)}: " + e.message) end when :remove begin IO.popen("#{externalpath} '#{pkgfile}' remove", 'w') do |pipe| pipe.write(data) end if !$?.success? raise "Exit value #{$?.exitstatus}" end rescue => e raise Tpkg.wrap_exception(e, "External #{name} #{operation} for #{File.basename(pkgfile)}: " + e.message) end else raise "Bug, unknown external operation #{operation}" end end # Unpack the files from a package into place, decrypt as necessary, set # permissions and ownership, etc. Does not check for conflicting # files or packages, etc. Those checks (if desired) must be done before # calling this method. def unpack(package_file, options={}) ret_val = 0 # set env variable to let pre/post install know whether this unpack # is part of an install or upgrade if options[:is_doing_upgrade] ENV['TPKG_ACTION'] = "upgrade" else ENV['TPKG_ACTION'] = "install" end # Unpack files in a temporary directory # I'd prefer to unpack on the fly so that the user doesn't need to # have disk space to hold three copies of the package (the package # file itself, this temporary unpack, and the final copy of the # files). However, I haven't figured out a way to get that to work, # since we need to strip several layers of directories out of the # directory structure in the package. topleveldir = Tpkg::package_toplevel_directory(package_file) workdir = Tpkg::tempdir(topleveldir, @tmp_directory) extract_tpkg_tar_cmd = Tpkg::cmd_to_extract_tpkg_tar(package_file, topleveldir) system("#{extract_tpkg_tar_cmd} | #{@tar} #{@@taroptions} -C #{workdir} -xpf -") files_info = {} # store perms, uid, gid, etc. for files checksums_of_decrypted_files = {} metadata = Tpkg::metadata_from_package(package_file, {:topleveldir => topleveldir}) # Get list of files/directories that already exist in the system. Store their perm/ownership. # That way, when we copy over the new files, we can set the new files to have the same perm/owernship. conflicting_files = {} fip = Tpkg::files_in_package(package_file) (fip[:root] | fip[:reloc]).each do |file| file_in_staging = normalize_path(file, File.join(workdir, 'tpkg', 'root'), File.join(workdir, 'tpkg', 'reloc')) file_in_system = normalize_path(file) if File.exists?(file_in_system) && !File.symlink?(file_in_system) conflicting_files[file] = {:normalized => file_in_staging, :stat => File.stat(file_in_system)} end end run_preinstall(package_file, workdir) run_externals_for_install(metadata, workdir, options[:externals_to_skip]) # Since we're stuck with unpacking to a temporary folder take # advantage of that to handle permissions, ownership and decryption # tasks before moving the files into their final location. # Handle any default permissions and ownership default_uid = DEFAULT_OWNERSHIP_UID default_gid = DEFAULT_OWNERSHIP_UID default_perms = nil if (metadata[:files][:file_defaults][:posix][:owner] rescue nil) default_uid = Tpkg::lookup_uid(metadata[:files][:file_defaults][:posix][:owner]) end if (metadata[:files][:file_defaults][:posix][:group] rescue nil) default_gid = Tpkg::lookup_gid(metadata[:files][:file_defaults][:posix][:group]) end if (metadata[:files][:file_defaults][:posix][:perms] rescue nil) default_perms = metadata[:files][:file_defaults][:posix][:perms] end # Set default dir uid/gid to be same as for file. default_dir_uid = default_uid default_dir_gid = default_gid default_dir_perms = 0755 if (metadata[:files][:dir_defaults][:posix][:owner] rescue nil) default_dir_uid = Tpkg::lookup_uid(metadata[:files][:dir_defaults][:posix][:owner]) end if (metadata[:files][:dir_defaults][:posix][:group] rescue nil) default_dir_gid = Tpkg::lookup_gid(metadata[:files][:dir_defaults][:posix][:group]) end if (metadata[:files][:dir_defaults][:posix][:perms] rescue nil) default_dir_perms = metadata[:files][:dir_defaults][:posix][:perms] end root_dir = File.join(workdir, 'tpkg', 'root') reloc_dir = File.join(workdir, 'tpkg', 'reloc') Find.find(root_dir, reloc_dir) do |f| # If the package doesn't contain either of the top level # directories we need to skip them, find will pass them to us # even if they don't exist. next if !File.exist?(f) begin if File.directory?(f) File.chown(default_dir_uid, default_dir_gid, f) else File.chown(default_uid, default_gid, f) end rescue Errno::EPERM raise if Process.euid == 0 end if File.file?(f) && !File.symlink?(f) if default_perms File.chmod(default_perms, f) end elsif File.directory?(f) && !File.symlink?(f) File.chmod(default_dir_perms, f) end end # Reset the permission/ownership of the conflicting files as how they were before. # This needs to be done after the default permission/ownership is applied, but before # the handling of ownership/permissions on specific files conflicting_files.each do | file, info | stat = info[:stat] file_path = info[:normalized] File.chmod(stat.mode, file_path) File.chown(stat.uid, stat.gid, file_path) end # Handle any decryption, ownership/permissions, and other issues for specific files metadata[:files][:files].each do |tpkgfile| tpkg_path = tpkgfile[:path] working_path = normalize_path(tpkg_path, File.join(workdir, 'tpkg', 'root'), File.join(workdir, 'tpkg', 'reloc')) if !File.exist?(working_path) && !File.symlink?(working_path) raise "tpkg.xml for #{File.basename(package_file)} references file #{tpkg_path} but that file is not in the package" end # Set permissions and ownership for specific files # We do this before the decryption stage so that permissions and # ownership designed to protect private file contents are in place # prior to decryption. The decrypt method preserves the permissions # and ownership of the encrypted file on the decrypted file. if tpkgfile[:posix] if tpkgfile[:posix][:owner] || tpkgfile[:posix][:group] uid = nil if tpkgfile[:posix][:owner] uid = Tpkg::lookup_uid(tpkgfile[:posix][:owner]) end gid = nil if tpkgfile[:posix][:group] gid = Tpkg::lookup_gid(tpkgfile[:posix][:group]) end begin File.chown(uid, gid, working_path) rescue Errno::EPERM raise if Process.euid == 0 end end if tpkgfile[:posix][:perms] perms = tpkgfile[:posix][:perms] File.chmod(perms, working_path) end end # Decrypt any files marked for decryption if tpkgfile[:encrypt] if !options[:passphrase] # If the user didn't supply a passphrase then just remove the # encrypted file. This allows users to install packages that # contain encrypted files for which they don't have the # passphrase. They end up with just the non-encrypted files, # potentially useful for development or QA environments. File.delete(working_path) else (1..3).each do | i | begin Tpkg::decrypt(metadata[:name], working_path, options[:passphrase], *([tpkgfile[:encrypt][:algorithm]].compact)) break rescue OpenSSL::CipherError @@passphrase = nil if i == 3 raise "Incorrect passphrase." else puts "Incorrect passphrase. Try again." end end end if File.file?(working_path) digest = Digest::SHA256.hexdigest(File.read(working_path)) # get checksum for the decrypted file. Will be used for creating file_metadata checksums_of_decrypted_files[File.expand_path(tpkg_path)] = digest end end end # If a conf file already exists on the file system, don't overwrite it. Rename # the new one with .tpkgnew file extension. if tpkgfile[:config] && conflicting_files[tpkgfile[:path]] FileUtils.mv(conflicting_files[tpkgfile[:path]][:normalized], "#{conflicting_files[tpkgfile[:path]][:normalized]}.tpkgnew") end end if metadata[:files] && metadata[:files][:files] # We should get the perms, gid, uid stuff here since all the files # have been set up correctly Find.find(root_dir, reloc_dir) do |f| # If the package doesn't contain either of the top level # directory we need to skip them, find will pass them to us # even if they don't exist. next if !File.exist?(f) next if File.symlink?(f) # check if it's from root dir or reloc dir if f =~ /^#{Regexp.escape(root_dir)}/ short_fn = f[root_dir.length ..-1] else short_fn = f[reloc_dir.length + 1..-1] relocatable = "true" end acl = {} acl["gid"] = File.stat(f).gid acl["uid"] = File.stat(f).uid acl["perms"] = File.stat(f).mode.to_s(8) files_info[short_fn] = acl end # Move files into place # If we implement any of the ACL permissions features we'll have to be # careful here that tar preserves those permissions. Otherwise we'll # need to apply them after moving the files into place. if File.directory?(File.join(workdir, 'tpkg', 'root')) system("#{@tar} -C #{File.join(workdir, 'tpkg', 'root')} -cf - . | #{@tar} -C #{@file_system_root} -xpf -") end if File.directory?(File.join(workdir, 'tpkg', 'reloc')) system("#{@tar} -C #{File.join(workdir, 'tpkg', 'reloc')} -cf - . | #{@tar} -C #{@base} -xpf -") end install_init_scripts(metadata) install_crontabs(metadata) ret_val = run_postinstall(package_file, workdir) save_package_metadata(package_file, workdir, metadata, files_info, checksums_of_decrypted_files) # Copy the package file to the directory for installed packages FileUtils.cp(package_file, @installed_directory) # Cleanup FileUtils.rm_rf(workdir) return ret_val end def install_init_scripts(metadata) init_links(metadata).each do |link, init_script| # We don't have to do anything if there's already symlink to our init # script. This can happen if the user removes a package manually without # removing the init symlink next if File.symlink?(link) && File.readlink(link) == init_script begin if !File.exist?(File.dirname(link)) FileUtils.mkdir_p(File.dirname(link)) end begin File.symlink(init_script, link) rescue Errno::EEXIST # The link name that init_links provides is not guaranteed to # be unique. It might collide with a base system init script # or an init script from another tpkg. If the link name # supplied by init_links results in EEXIST then try appending # a number to the end of the link name. catch :init_link_done do 1.upto(9) do |i| begin File.symlink(init_script, link + i.to_s) throw :init_link_done rescue Errno::EEXIST end end # If we get here (i.e. we never reached the throw) then we # failed to create any of the possible link names. raise "Failed to install init script #{init_script} -> #{link} for #{File.basename(metadata[:filename].to_s)}, too many overlapping filenames" end end # EACCES for file/directory permissions issues rescue Errno::EACCES => e # If creating the link fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to install init script for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end end end end def remove_init_scripts(metadata) init_links(metadata).each do |link, init_script| # The link we ended up making when we unpacked the package could be any # of a series (see the code in install_init_scripts for the reasoning), # we need to check them all. links = [link] links.concat((1..9).to_a.map { |i| link + i.to_s }) links.each do |l| if File.symlink?(l) && File.readlink(l) == init_script begin File.delete(l) # EACCES for file/directory permissions issues rescue Errno::EACCES => e # If removing the link fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to remove init script for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end end end end end end def install_crontabs(metadata) crontab_destinations(metadata).each do |crontab, destination| # FIXME: Besides the regex being ugly it is also only going to match on # Linux, need to figure out if there's a reason for that or if this can # be made more generic. if !@sudo && (destination[destination.keys.first] =~ /\/var\/spool\/cron/) install_crontab_bycmd(metadata, crontab, destination) next end begin if destination[:link] install_crontab_link(metadata, crontab, destination) elsif destination[:file] install_crontab_file(metadata, crontab, destination) end # EACCES for file/directory permissions issues rescue Errno::EACCES => e # If installing the crontab fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to install crontab for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end rescue RuntimeError => e if e.message.include?('cannot generate tempfile') && Process.euid != 0 warn "Failed to install crontab for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end end end end def install_crontab_link(metadata, crontab, destination) return if File.symlink?(destination[:link]) && File.readlink(destination[:link]) == crontab if !File.exist?(File.dirname(destination[:link])) FileUtils.mkdir_p(File.dirname(destination[:link])) end begin File.symlink(crontab, destination[:link]) rescue Errno::EEXIST # The link name that crontab_destinations provides is not # guaranteed to be unique. It might collide with a base # system crontab or a crontab from another tpkg. If the # link name supplied by crontab_destinations results in # EEXIST then try appending a number to the end of the link # name. catch :crontab_link_done do 1.upto(9) do |i| begin File.symlink(crontab, destination[:link] + i.to_s) throw :crontab_link_done rescue Errno::EEXIST end end # If we get here (i.e. we never reached the throw) then we # failed to create any of the possible link names. raise "Failed to install crontab #{crontab} -> #{destination[:link]} for #{File.basename(metadata[:filename].to_s)}, too many overlapping filenames" end end end # FIXME: Can this be replaced by install_crontab_bycmd? def install_crontab_file(metadata, crontab, destination) if !File.exist?(File.dirname(destination[:file])) FileUtils.mkdir_p(File.dirname(destination[:file])) end tmpfile = Tempfile.new(File.basename(destination[:file]), File.dirname(destination[:file])) if File.exist?(destination[:file]) # Match permissions and ownership of current crontab st = File.stat(destination[:file]) begin File.chmod(st.mode & 07777, tmpfile.path) File.chown(st.uid, st.gid, tmpfile.path) # EPERM for attempts to chown/chmod as non-root user rescue Errno::EPERM => e # If installing the crontab fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to install crontab for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end end # Insert the contents of the current crontab file File.open(destination[:file]) { |file| tmpfile.write(file.read) } end # Insert a header line so we can find this section to remove later tmpfile.puts "### TPKG START - #{@base} - #{File.basename(metadata[:filename].to_s)}" # Insert the package crontab contents crontab_contents = IO.read(crontab) tmpfile.write(crontab_contents) # Insert a newline if the crontab doesn't end with one if crontab_contents.chomp == crontab_contents tmpfile.puts end # Insert a footer line tmpfile.puts "### TPKG END - #{@base} - #{File.basename(metadata[:filename].to_s)}" tmpfile.close File.rename(tmpfile.path, destination[:file]) # FIXME: On Solaris we should bounce cron or use the crontab # command, otherwise cron won't pick up the changes end def install_crontab_bycmd(metadata, crontab, destination) oldcron = `crontab -l` tmpf = '/tmp/tpkg_cron.' + rand.to_s tmpfh = File.open(tmpf,'w') tmpfh.write(oldcron) unless oldcron.empty? tmpfh.puts "### TPKG START - #{@base} - #{File.basename(metadata[:filename].to_s)}" tmpfh.write File.readlines(crontab) tmpfh.puts "### TPKG END - #{@base} - #{File.basename(metadata[:filename].to_s)}" tmpfh.close `crontab #{tmpf}` FileUtils.rm(tmpf) end def remove_crontabs(metadata) crontab_destinations(metadata).each do |crontab, destination| # FIXME: Besides the regex being ugly it is also only going to match on # Linux, need to figure out if there's a reason for that or if this can # be made more generic. if !@sudo && (destination[destination.keys.first] =~ /\/var\/spool\/cron/) remove_crontab_bycmd(metadata, crontab, destination) next end begin if destination[:link] remove_crontab_link(metadata, crontab, destination) elsif destination[:file] remove_crontab_file(metadata, crontab, destination) end # EACCES for file/directory permissions issues rescue Errno::EACCES => e # If removing the crontab fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to remove crontab for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end end end end def remove_crontab_link(metadata, crontab, destination) # The link we ended up making when we unpacked the package could # be any of a series (see the code in unpack for the reasoning), # we need to check them all. links = [destination[:link]] links.concat((1..9).to_a.map { |i| destination[:link] + i.to_s }) links.each do |l| if File.symlink?(l) && File.readlink(l) == crontab File.delete(l) end end end # FIXME: Can this be replaced by remove_crontab_bycmd? def remove_crontab_file(metadata, crontab, destination) if File.exist?(destination[:file]) tmpfile = Tempfile.new(File.basename(destination[:file]), File.dirname(destination[:file])) # Match permissions and ownership of current crontab st = File.stat(destination[:file]) begin File.chmod(st.mode & 07777, tmpfile.path) File.chown(st.uid, st.gid, tmpfile.path) # EPERM for attempts to chown/chmod as non-root user rescue Errno::EPERM => e # If installing the crontab fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to install crontab for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise end end # Remove section associated with this package skip = false IO.foreach(destination[:file]) do |line| if line == "### TPKG START - #{@base} - #{File.basename(metadata[:filename].to_s)}\n" skip = true elsif line == "### TPKG END - #{@base} - #{File.basename(metadata[:filename].to_s)}\n" skip = false elsif !skip tmpfile.write(line) end end tmpfile.close File.rename(tmpfile.path, destination[:file]) # FIXME: On Solaris we should bounce cron or use the crontab # command, otherwise cron won't pick up the changes end end def remove_crontab_bycmd(metadata, crontab, destination) oldcron = `crontab -l` tmpf = '/tmp/tpkg_cron.' + rand.to_s tmpfh = File.open(tmpf,'w') skip = false oldcron.each do |line| if line == "### TPKG START - #{@base} - #{File.basename(metadata[:filename].to_s)}\n" skip = true elsif line == "### TPKG END - #{@base} - #{File.basename(metadata[:filename].to_s)}\n" skip = false elsif !skip tmpfh.write(line) end end tmpfh.close `crontab #{tmpf}` FileUtils.rm(tmpf) end def run_preinstall(package_file, workdir) if File.exist?(File.join(workdir, 'tpkg', 'preinstall')) pwd = Dir.pwd # chdir into the working directory so that the user can specify # relative paths to other files in the package. Dir.chdir(File.join(workdir, 'tpkg')) begin # Warn the user about non-executable files, as system will just # silently fail and exit if that's the case. if !File.executable?(File.join(workdir, 'tpkg', 'preinstall')) warn "Warning: preinstall script for #{File.basename(package_file)} is not executable, execution will likely fail" end if @force system(File.join(workdir, 'tpkg', 'preinstall')) || warn("Warning: preinstall for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") else system(File.join(workdir, 'tpkg', 'preinstall')) || raise("Error: preinstall for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") end ensure # Switch back to our previous directory Dir.chdir(pwd) end end end def run_postinstall(package_file, workdir) r = 0 if File.exist?(File.join(workdir, 'tpkg', 'postinstall')) pwd = Dir.pwd # chdir into the working directory so that the user can specify # relative paths to other files in the package. Dir.chdir(File.join(workdir, 'tpkg')) begin # Warn the user about non-executable files, as system will just # silently fail and exit if that's the case. if !File.executable?(File.join(workdir, 'tpkg', 'postinstall')) warn "Warning: postinstall script for #{File.basename(package_file)} is not executable, execution will likely fail" end # Note this only warns the user if the postinstall fails, it does # not raise an exception like we do if preinstall fails. Raising # an exception would leave the package's files installed but the # package not registered as installed, which does not seem # desirable. We could remove the package's files and raise an # exception, but this seems the best approach to me. system(File.join(workdir, 'tpkg', 'postinstall')) if !$?.success? warn("Warning: postinstall for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") r = POSTINSTALL_ERR end ensure # Switch back to our previous directory Dir.chdir(pwd) end end r end def run_externals_for_install(metadata, workdir, externals_to_skip=[]) metadata[:externals].each do |external| if !externals_to_skip || !externals_to_skip.include?(external) # If the external references a datafile or datascript then read/run it # now that we've unpacked the package contents and have the file/script # available. This will get us the data for the external. if external[:datafile] || external[:datascript] pwd = Dir.pwd # chdir into the working directory so that the user can specify a # relative path to their file/script. Dir.chdir(File.join(workdir, 'tpkg')) begin if external[:datafile] # Read the file external[:data] = IO.read(external[:datafile]) # Drop the datafile key so that we don't waste time re-reading the # datafile again in the future. external.delete(:datafile) elsif external[:datascript] # Run the script IO.popen(external[:datascript]) do |pipe| external[:data] = pipe.read end if !$?.success? raise "Datascript #{external[:datascript]} for package #{File.basename(metadata[:filename])} had exit value #{$?.exitstatus}" end # Drop the datascript key so that we don't waste time re-running the # datascript again in the future. external.delete(:datascript) end ensure # Switch back to our previous directory Dir.chdir(pwd) end end run_external(metadata[:filename], :install, external[:name], external[:data]) end end if metadata[:externals] end def save_package_metadata(package_file, workdir, metadata, files_info, checksums_of_decrypted_files) # Save metadata for this pkg package_name = File.basename(package_file, File.extname(package_file)) package_metadata_dir = File.join(@metadata_directory, package_name) FileUtils.mkdir_p(package_metadata_dir) metadata.write(package_metadata_dir) # Save file_metadata for this pkg file_metadata = FileMetadata::instantiate_from_dir(File.join(workdir, 'tpkg')) if file_metadata file_metadata[:package_file] = File.basename(package_file) file_metadata[:files].each do |file| # update file_metadata with user/group ownership and permission acl = files_info[file[:path]] file.merge!(acl) unless acl.nil? # update file_metadata with the checksums of decrypted files digest = checksums_of_decrypted_files[File.expand_path(file[:path])] if digest digests = file[:checksum][:digests] digests[0][:encrypted] = true digests[1] = {:decrypted => true, :value => digest} end end file = File.open(File.join(package_metadata_dir, "file_metadata.bin"), "w") Marshal.dump(file_metadata.to_hash, file) file.close else warn "Warning: package #{File.basename(package_file)} does not include file_metadata information." end end def requirements_for_currently_installed_package(pkgname=nil) requirements = [] metadata_for_installed_packages.each do |metadata| if !pkgname || pkgname == metadata[:name] req = { :name => metadata[:name], :minimum_version => metadata[:version], :type => :tpkg } if metadata[:package_version] req[:minimum_package_version] = metadata[:package_version] end requirements << req end end requirements end # Adds/modifies requirements and packages arguments to add requirements # and package entries for currently installed packages # Note: the requirements and packages arguments are modified by this method def requirements_for_currently_installed_packages(requirements, packages) metadata_for_installed_packages.each do |installed_xml| name = installed_xml[:name] version = installed_xml[:version] # For each currently installed package we insert a requirement for # at least that version of the package req = { :name => name, :minimum_version => version, :type => :tpkg } requirements << req # Initialize the list of possible packages for this req if !packages[name] packages[name] = available_packages_that_meet_requirement(req) end end end # Define requirements for requested packages # Takes an array of packages: files, URLs, or basic package specs ('foo' or # 'foo=1.0') # Adds/modifies requirements and packages arguments based on parsing those # requests # Input: # [ 'foo-1.0.tpkg', 'http://server/pkgs/bar-2.3.pkg', 'blat=0.5' ] # Result: # requirements << { :name => 'foo' }, packages['foo'] = { :source => 'foo-1.0.tpkg' } # requirements << { :name => 'bar' }, packages['bar'] = { :source => 'http://server/pkgs/bar-2.3.pkg' } # requirements << { :name => 'blat', :minimum_version => '0.5', :maximum_version => '0.5' }, packages['blat'] populated with available packages meeting that requirement # Note: the requirements and packages arguments are modified by this method def parse_requests(requests, requirements, packages) newreqs = [] requests.each do |request| puts "parse_requests processing #{request.inspect}" if @@debug # User specified a file or URI if request =~ /^http[s]?:\/\// or File.file?(request) req = {} metadata = nil source = nil localpath = nil if File.file?(request) raise "Invalid package filename #{request}" if !Tpkg::valid_pkg_filename?(request) puts "parse_requests treating request as a file" if @@debug if request !~ /\.tpkg$/ warn "Warning: Attempting to perform the request on #{File.expand_path(request)}. This might not be a valid package file." end localpath = request metadata = Tpkg::metadata_from_package(request) source = request else puts "parse_requests treating request as a URI" if @@debug uri = URI.parse(request) # This just serves as a sanity check # Using these File methods on a URI seems to work but is probably fragile source = File.dirname(request) + '/' # dirname chops off the / at the end, we need it in order to be compatible with URI.join pkgfile = File.basename(request) localpath = download(source, pkgfile, Tpkg::tempdir('download')) metadata = Tpkg::metadata_from_package(localpath) # Cleanup temp download dir FileUtils.rm_rf(localpath) end req[:name] = metadata[:name] req[:type] = :tpkg pkg = { :metadata => metadata, :source => source } newreqs << req # The user specified a particular package, so it is the only package # that can be used to meet the requirement packages[req[:name]] = [pkg] else # basic package specs ('foo' or 'foo=1.0') puts "parse_requests request looks like package spec" if @@debug # Tpkg::parse_request is a class method and doesn't know where packages are installed. # So we have to tell it ourselves. req = Tpkg::parse_request(request, @installed_directory) newreqs << req puts "Initializing the list of possible packages for this req" if @@debug if !packages[req[:name]] packages[req[:name]] = available_packages_that_meet_requirement(req) end end end requirements.concat(newreqs) newreqs end # After calling parse_request, we should call this method # to check whether or not we can meet the requirements/dependencies # of the result packages def check_requests(packages) all_requests_satisfied = true # whether or not all requests can be satisfied errors = [""] packages.each do |name, pkgs| if pkgs.empty? errors << ["Unable to find any packages which satisfy #{name}"] all_requests_satisfied = false next end request_satisfied = false # whether or not this request can be satisfied possible_errors = [] pkgs.each do |pkg| good_package = true metadata = pkg[:metadata] req = { :name => metadata[:name], :type => :tpkg } # Quick sanity check that the package can be installed on this machine. puts "check_requests checking that available package for request works on this machine: #{pkg.inspect}" if @@debug if !Tpkg::package_meets_requirement?(pkg, req) possible_errors << " Requested package #{metadata[:filename]} doesn't match this machine's OS or architecture" good_package = false next end # a sanity check that there is at least one package # available for each dependency of this package metadata[:dependencies].each do |depreq| puts "check_requests checking for available packages to satisfy dependency: #{depreq.inspect}" if @@debug if available_packages_that_meet_requirement(depreq).empty? && !Tpkg::packages_meet_requirement?(packages.values.flatten, depreq) possible_errors << " Requested package #{metadata[:filename]} depends on #{depreq.inspect}, no packages that satisfy that dependency are available" good_package = false end end if metadata[:dependencies] request_satisfied = true if good_package end if !request_satisfied errors << ["Unable to find any packages which satisfy #{name}. Possible error(s):"] errors << possible_errors all_requests_satisfied = false end end if !all_requests_satisfied puts errors.join("\n") raise "Unable to satisfy the request(s). Try running with --debug for more info" end end CHECK_INSTALL = 1 CHECK_UPGRADE = 2 CHECK_REMOVE = 3 def conflicting_files(package_file, mode=CHECK_INSTALL) metadata = Tpkg::metadata_from_package(package_file) pkgname = metadata[:name] conflicts = {} installed_files = files_for_installed_packages # Pull out the normalized paths, skipping appropriate packages based # on the requested mode installed_files_normalized = {} installed_files.each do |pkgfile, files| # Skip packages with the same name if the user is performing an upgrade if mode == CHECK_UPGRADE && files[:metadata][:name] == pkgname next end # Skip packages with the same filename if the user is removing if mode == CHECK_REMOVE && pkgfile == File.basename(package_file) next end installed_files_normalized[pkgfile] = files[:normalized] end fip = Tpkg::files_in_package(package_file) normalize_paths(fip) fip[:normalized].each do |file| installed_files_normalized.each do |instpkgfile, files| if files.include?(file) if !conflicts[instpkgfile] conflicts[instpkgfile] = [] end conflicts[instpkgfile] << file end end end # The remove method actually needs !conflicts, so invert in that case if mode == CHECK_REMOVE # Flatten conflicts to an array flatconflicts = [] conflicts.each_value { |files| flatconflicts.concat(files) } # And invert conflicts = fip[:normalized] - flatconflicts end conflicts end # This method is called by install and upgrade method to make sure there is # no conflicts between the existing pkgs and the pkgs we're about to install def handle_conflicting_pkgs(installed_pkgs, pkgs_to_install, options ={}) conflicting_pkgs = [] # check if existing pkgs have conflicts with pkgs we're about to install installed_pkgs.each do |pkg1| next if pkg1[:metadata][:conflicts].nil? pkg1[:metadata][:conflicts].each do | conflict | pkgs_to_install.each do |pkg2| if Tpkg::package_meets_requirement?(pkg2, conflict) conflicting_pkgs << pkg1 end end end end # check if pkgs we're about to install conflict with existing pkgs pkgs_to_install.each do |pkg1| next if pkg1[:metadata][:conflicts].nil? pkg1[:metadata][:conflicts].each do | conflict | conflicting_pkgs |= installed_packages_that_meet_requirement(conflict) end end # Check if there are conflicts among the pkgs we're about to install # For these type of conflicts, we can't proceed, so raise exception. pkgs_to_install.each do |pkg1| # native package might not have conflicts defined so skip next if pkg1[:metadata][:conflicts].nil? pkg1[:metadata][:conflicts].each do | conflict | pkgs_to_install.each do |pkg2| if Tpkg::package_meets_requirement?(pkg2, conflict) raise "Package conflicts between #{pkg2[:metadata][:filename]} and #{pkg1[:metadata][:filename]}" end end end end # Report to the users if there are conflicts unless conflicting_pkgs.empty? puts "The package(s) you're trying to install conflict with the following package(s):" conflicting_pkgs = conflicting_pkgs.collect{|pkg|pkg[:metadata][:filename]} puts conflicting_pkgs.join("\n") if options[:force_replace] puts "Attemping to replace the conflicting packages." success = remove(conflicting_pkgs) return success else puts "Try removing the conflicting package(s) first, or rerun tpkg with the --force-replace option." return false end end return true end def prompt_for_conflicting_files(package_file, mode=CHECK_INSTALL) if !@@prompt return true end result = true conflicts = conflicting_files(package_file, mode) # We don't want to prompt the user for directories, so strip those out conflicts.each do |pkgfile, files| files.reject! { |file| File.directory?(file) } end conflicts.reject! { |pkgfile, files| files.empty? } if !conflicts.empty? puts "File conflicts:" conflicts.each do |pkgfile, files| files.each do |file| puts "#{file} (#{pkgfile})" end end print "Proceed? [y/N] " response = $stdin.gets if response !~ /^y/i result = false end end result end def prompt_for_install(pkgs, promptstring) if @@prompt pkgs_to_report = pkgs.select do |pkg| pkg[:source] != :currently_installed && pkg[:source] != :native_installed end if !pkgs_to_report.empty? puts "The following packages will be #{promptstring}:" pkgs_to_report.sort(&SORT_PACKAGES).each do |pkg| if pkg[:source] == :native_available name = pkg[:metadata][:name] version = pkg[:metadata][:version] package_version = pkg[:metadata][:package_version] pkgname = "#{name}-#{version}" if package_version pkgname << "-#{package_version}" end puts "Native #{pkgname}" else puts pkg[:metadata][:filename] end end return Tpkg::confirm end end true end # See parse_requests for format of requests def install(requests, passphrase=nil, options={}) ret_val = 0 requirements = [] packages = {} lock parse_requests(requests, requirements, packages) check_requests(packages) core_packages = [] requirements.each do |req| core_packages << req[:name] if !core_packages.include?(req[:name]) end puts "install calling best_solution" if @@debug puts "install requirements: #{requirements.inspect}" if @@debug puts "install packages: #{packages.inspect}" if @@debug puts "install core_packages: #{core_packages.inspect}" if @@debug solution_packages = best_solution(requirements, packages, core_packages) if !solution_packages raise "Unable to resolve dependencies. Try running with --debug for more info" end success = handle_conflicting_pkgs(installed_packages, solution_packages, options) return false if !success if !prompt_for_install(solution_packages, 'installed') unlock return false end # Build an array of metadata of pkgs that are already installed # We will use this later on to figure out what new packages have been installed/removed # in order to report back to the server already_installed_pkgs = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} # Create array of packages (names) we have installed so far # We will use it later on to determine the order of how to install the packages installed_so_far = installed_packages.collect{|pkg| pkg[:metadata][:name]} while pkg = solution_packages.shift # get dependencies and make sure we install the packages in the correct order # based on the dependencies dependencies = nil if pkg[:metadata][:dependencies] dependencies = pkg[:metadata][:dependencies].collect { |dep| dep[:name] }.compact # don't install this pkg right now if its dependencies haven't been installed if !dependencies.empty? && !dependencies.to_set.subset?(installed_so_far.to_set) solution_packages.push(pkg) next end end if pkg[:source] == :currently_installed || pkg[:source] == :native_installed # Nothing to do for packages currently installed warn "Skipping #{pkg[:metadata][:name]}, already installed" elsif pkg[:source] == :native_available if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] package_version = pkg[:metadata][:package_version] # RPMs always have a release/package_version pkgname = "#{name}-#{version}-#{package_version}" puts "Running 'yum -y install #{pkgname}' to install native package" if @@debug system("yum -y install #{pkgname}") elsif Tpkg::get_os =~ /Debian|Ubuntu/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << "-#{pkg[:metadata][:package_version]}" end puts "Running 'apt-get -y install #{pkgname}' to install native package" if @@debug system("apt-get -y install #{pkgname}") elsif Tpkg::get_os =~ /Solaris/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << ",REV=#{pkg[:metadata][:package_version]}" end if File.exist?('/opt/csw/bin/pkg-get') puts "Running '/opt/csw/bin/pkg-get -i #{pkgname}' to install native package" if @@debug system("/opt/csw/bin/pkg-get -i #{pkgname}") else raise "No native package installation tool available" end elsif Tpkg::get_os =~ /FreeBSD/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << "_#{pkg[:metadata][:package_version]}" end puts "Running 'pkg_add -r #{pkgname}' to install native package" if @@debug system("pkg_add -r #{pkgname}") elsif Tpkg::get_os =~ /Darwin/ if File.exist?('/opt/local/bin/port') name = pkg[:metadata][:name] # MacPorts doesn't support installing a specific version (AFAIK) if pkg[:metadata][:version] warn "Ignoring version with MacPorts" end # Nor does it have a concept of a package version if pkg[:metadata][:package_version] warn "Ignoring package version with MacPorts" end # Just for consistency with the code for other platforms pkgname = name puts "Running '/opt/local/bin/port install #{pkgname}' to install native package" if @@debug system("/opt/local/bin/port install #{pkgname}") else # Fink support would be nice raise "No supported native package tool available on #{Tpkg::get_os}" end else raise "No native package installation support for #{Tpkg::get_os}" end else # regular tpkg that needs to be installed pkgfile = nil if File.file?(pkg[:source]) pkgfile = pkg[:source] elsif File.directory?(pkg[:source]) pkgfile = File.join(pkg[:source], pkg[:metadata][:filename]) else pkgfile = download(pkg[:source], pkg[:metadata][:filename]) end if File.exist?( File.join(@installed_directory, File.basename(pkgfile))) warn "Skipping #{File.basename(pkgfile)}, already installed" else if prompt_for_conflicting_files(pkgfile) ret_val |= unpack(pkgfile, :passphrase => passphrase) # create and install stubbed native package if needed stub_native_pkg(pkg) end end end # If we're down here, it means we have installed the package. So go ahead and # update the list of packages we installed so far installed_so_far << pkg[:metadata][:name] end # end while loop # log changes currently_installed = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} newly_installed = currently_installed - already_installed_pkgs log_changes({:newly_installed => newly_installed}) # send udpate back to reporting server unless @report_server.nil? options = {:newly_installed => newly_installed, :currently_installed => currently_installed} send_update_to_server(options) end unlock return ret_val end # This method can also be used for doing downgrade def upgrade(requests=nil, passphrase=nil, options={}) downgrade = options[:downgrade] || false ret_val = 0 requirements = [] packages = {} core_packages = [] lock has_updates = false # flags whether or not there was at least one actual package that # get updated # If the user specified some specific packages to upgrade in requests # then we look for upgrades for just those packages (and any necessary # dependency upgrades). If the user did not specify specific packages # then we look for upgrades for all currently installed packages. if requests puts "Upgrading requested packages only" if @@debug parse_requests(requests, requirements, packages) check_requests(packages) additional_requirements = [] requirements.each do |req| core_packages << req[:name] if !core_packages.include?(req[:name]) # When doing downgrade, we don't want to include the package being # downgrade as the requirements. Otherwise, we won't be able to downgrade it unless downgrade additional_requirements.concat( requirements_for_currently_installed_package(req[:name])) end # Initialize the list of possible packages for this req if !packages[req[:name]] packages[req[:name]] = available_packages_that_meet_requirement(req) end # Remove preference for currently installed package packages[req[:name]].each do |pkg| if pkg[:source] == :currently_installed pkg[:prefer] = false end end # Look for pkgs that might depend on the pkg we're upgrading, # and add them to our list of requirements. We need to make sure that we can still # satisfy the dependency requirements if we were to do the upgrade. metadata_for_installed_packages.each do | metadata | metadata[:dependencies].each do | dep | if dep[:name] == req[:name] # Package metadata is almost usable as-is as a req, just need to # set :type # and remove filename (since we're not explicitly requesting the exact file) addreq = metadata.to_hash.clone addreq[:type] = :tpkg addreq[:filename] = nil additional_requirements << addreq end end if metadata[:dependencies] end end requirements.concat(additional_requirements) requirements.uniq! else puts "Upgrading all packages" if @@debug requirements_for_currently_installed_packages(requirements, packages) # Remove preference for currently installed packages packages.each do |name, pkgs| core_packages << name if !core_packages.include?(name) pkgs.each do |pkg| if pkg[:source] == :currently_installed pkg[:prefer] = false end end end end puts "upgrade calling best_solution" if @@debug puts "upgrade requirements: #{requirements.inspect}" if @@debug puts "upgrade packages: #{packages.inspect}" if @@debug puts "upgrade core_packages: #{core_packages.inspect}" if @@debug solution_packages = best_solution(requirements, packages, core_packages) if solution_packages.nil? raise "Unable to find solution for upgrading. Please verify that you specified the correct package(s) for upgrade. Try running with --debug for more info" end success = handle_conflicting_pkgs(installed_packages, solution_packages, options) return false if !success if downgrade prompt_action = 'downgraded' else prompt_action = 'upgraded' end if !prompt_for_install(solution_packages, prompt_action) unlock return false end # Build an array of metadata of pkgs that are already installed # We will use this later on to figure out what new packages have been installed/removed # in order to report back to the server already_installed_pkgs = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} removed_pkgs = [] # keep track of what we removed so far while pkg = solution_packages.shift if pkg[:source] == :currently_installed || pkg[:source] == :native_installed # Nothing to do for packages currently installed elsif pkg[:source] == :native_available if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] package_version = pkg[:metadata][:package_version] # RPMs always have a release/package_version pkgname = "#{name}-#{version}-#{package_version}" puts "Running 'yum -y install #{pkgname}' to upgrade native package" if @@debug system("yum -y install #{pkgname}") has_updates = true elsif Tpkg::get_os =~ /Debian|Ubuntu/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << "-#{pkg[:metadata][:package_version]}" end puts "Running 'apt-get -y install #{pkgname}' to upgrade native package" if @@debug system("apt-get -y install #{pkgname}") has_updates = true elsif Tpkg::get_os =~ /Solaris/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << ",REV=#{pkg[:metadata][:package_version]}" end if File.exist?('/opt/csw/bin/pkg-get') puts "Running '/opt/csw/bin/pkg-get -i #{pkgname}' to upgrade native package" if @@debug system("/opt/csw/bin/pkg-get -i #{pkgname}") has_updates = true else raise "No native package upgrade tool available" end elsif Tpkg::get_os =~ /FreeBSD/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << "_#{pkg[:metadata][:package_version]}" end # This is not very ideal. It would be better to download the # new package, and if the download is successful remove the # old package and install the new one. The way we're doing it # here we risk leaving the system with neither version # installed if the download of the new package fails. # However, the FreeBSD package tools don't make it easy to # handle things properly. puts "Running 'pkg_delete #{name}' and 'pkg_add -r #{pkgname}' to upgrade native package" if @@debug system("pkg_delete #{name}") system("pkg_add -r #{pkgname}") has_updates = true elsif Tpkg::get_os =~ /Darwin/ if File.exist?('/opt/local/bin/port') name = pkg[:metadata][:name] # MacPorts doesn't support installing a specific version (AFAIK) if pkg[:metadata][:version] warn "Ignoring version with MacPorts" end # Nor does it have a concept of a package version if pkg[:metadata][:package_version] warn "Ignoring package version with MacPorts" end # Just for consistency with the code for other platforms pkgname = name puts "Running '/opt/local/bin/port upgrade #{pkgname}' to upgrade native package" if @@debug system("/opt/local/bin/port upgrade #{pkgname}") else # Fink support would be nice raise "No supported native package tool available on #{Tpkg::get_os}" end else raise "No native package upgrade support for #{Tpkg::get_os}" end else # tpkg pkgfile = nil if File.file?(pkg[:source]) pkgfile = pkg[:source] elsif File.directory?(pkg[:source]) pkgfile = File.join(pkg[:source], pkg[:metadata][:filename]) else pkgfile = download(pkg[:source], pkg[:metadata][:filename]) end if !Tpkg::valid_pkg_filename?(pkgfile) raise "Invalid package filename: #{pkgfile}" end if prompt_for_conflicting_files(pkgfile, CHECK_UPGRADE) # If the old and new packages have overlapping externals flag them # to be skipped so that the external isn't removed and then # immediately re-added oldpkgs = installed_packages_that_meet_requirement({:name => pkg[:metadata][:name], :type => :tpkg}) externals_to_skip = [] pkg[:metadata][:externals].each do |external| if oldpkgs.all? {|oldpkg| oldpkg[:metadata][:externals] && oldpkg[:metadata][:externals].include?(external)} externals_to_skip << external end end if pkg[:metadata][:externals] # Remove the old package if we haven't done so unless oldpkgs.nil? or oldpkgs.empty? or removed_pkgs.include?(pkg[:metadata][:name]) remove([pkg[:metadata][:name]], :upgrade => true, :externals_to_skip => externals_to_skip) removed_pkgs << pkg[:metadata][:name] end # determine if we can unpack the new version package now by # looking to see if all of its dependencies have been installed can_unpack = true pkg[:metadata][:dependencies].each do | dep | iptmr = installed_packages_that_meet_requirement(dep) if iptmr.nil? || iptmr.empty? can_unpack = false # Can't unpack yet. so push it back in the solution_packages queue solution_packages.push(pkg) break end end if pkg[:metadata][:dependencies] if can_unpack is_doing_upgrade = true if removed_pkgs.include?(pkg[:metadata][:name]) ret_val |= unpack(pkgfile, :passphrase => passphrase, :externals_to_skip => externals_to_skip, :is_doing_upgrade => is_doing_upgrade) # create and install stubbed native package if needed stub_native_pkg(pkg) end has_updates = true end end end # log changes currently_installed = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} newly_installed = currently_installed - already_installed_pkgs removed = already_installed_pkgs - currently_installed log_changes({:newly_installed => newly_installed, :removed => removed}) # send update back to reporting server if !has_updates puts "No updates available" elsif !@report_server.nil? options = {:newly_installed => newly_installed, :removed => removed, :currently_installed => currently_installed} send_update_to_server(options) end unlock return ret_val end def remove(requests=nil, options={}) ret_val = 0 lock packages_to_remove = nil if requests requests.uniq! if requests.is_a?(Array) packages_to_remove = [] requests.each do |request| req = Tpkg::parse_request(request, @installed_directory) packages_to_remove.concat(installed_packages_that_meet_requirement(req)) end else packages_to_remove = installed_packages_that_meet_requirement end if packages_to_remove.empty? puts "No matching packages" unlock return false end # Build an array of metadata of pkgs that are already installed # We will use this later on to figure out what new packages have been installed/removed # in order to report back to the server already_installed_pkgs = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} # If user want to remove all the dependent pkgs, then go ahead # and include them in our array of things to remove if options[:remove_all_dep] packages_to_remove |= get_dependents(packages_to_remove) elsif options[:remove_all_prereq] puts "Attempting to remove #{packages_to_remove.map do |pkg| pkg[:metadata][:filename] end} and all prerequisites." # Get list of dependency prerequisites ptr = packages_to_remove | get_prerequisites(packages_to_remove) pkg_files_to_remove = ptr.map { |pkg| pkg[:metadata][:filename] } # see if any other packages depends on the ones we're about to remove # If so, we can't remove that package + any of its prerequisites non_removable_pkg_files = [] metadata_for_installed_packages.each do |metadata| next if pkg_files_to_remove.include?(metadata[:filename]) next if metadata[:dependencies].nil? metadata[:dependencies].each do |req| # We ignore native dependencies because there is no way a removal # can break a native dependency, we don't support removing native # packages. if req[:type] != :native iptmr = installed_packages_that_meet_requirement(req) if iptmr.all? { |pkg| pkg_files_to_remove.include?(pkg[:metadata][:filename]) } non_removable_pkg_files |= iptmr.map{ |pkg| pkg[:metadata][:filename]} non_removable_pkg_files |= get_prerequisites(iptmr).map{ |pkg| pkg[:metadata][:filename]} end end end end # Generate final list of packages that we should remove. packages_to_remove = {} ptr.each do | pkg | next if pkg[:source] == :native or pkg[:source] == :native_installed next if non_removable_pkg_files.include?(pkg[:metadata][:filename]) packages_to_remove[pkg[:metadata][:filename]] = pkg end packages_to_remove = packages_to_remove.values if packages_to_remove.empty? raise "Can't remove request package because other packages depend on it." elsif !non_removable_pkg_files.empty? puts "Can't remove #{non_removable_pkg_files.inspect} because other packages depend on them." end # Check that this doesn't leave any dependencies unresolved elsif !options[:upgrade] pkg_files_to_remove = packages_to_remove.map { |pkg| pkg[:metadata][:filename] } metadata_for_installed_packages.each do |metadata| next if pkg_files_to_remove.include?(metadata[:filename]) next if metadata[:dependencies].nil? metadata[:dependencies].each do |req| # We ignore native dependencies because there is no way a removal # can break a native dependency, we don't support removing native # packages. # FIXME: Should we also consider :native_installed? if req[:type] != :native if installed_packages_that_meet_requirement(req).all? { |pkg| pkg_files_to_remove.include?(pkg[:metadata][:filename]) } raise "Package #{metadata[:filename]} depends on #{req[:name]}" end end end end end # Confirm with the user # upgrade does its own prompting if @@prompt && !options[:upgrade] puts "The following packages will be removed:" packages_to_remove.each do |pkg| puts pkg[:metadata][:filename] end unless Tpkg::confirm unlock return false end end # Stop the services if there's init script if !options[:upgrade] packages_to_remove.each do |pkg| init_scripts_metadata = init_scripts(pkg[:metadata]) if init_scripts_metadata && !init_scripts_metadata.empty? execute_init_for_package(pkg, 'stop') end end end # Remove the packages packages_to_remove.each do |pkg| pkgname = pkg[:metadata][:name] package_file = File.join(@installed_directory, pkg[:metadata][:filename]) topleveldir = Tpkg::package_toplevel_directory(package_file) workdir = Tpkg::tempdir(topleveldir, @tmp_directory) extract_tpkg_tar_command = Tpkg::cmd_to_extract_tpkg_tar(package_file, topleveldir) system("#{extract_tpkg_tar_command} | #{@tar} #{@@taroptions} -C #{workdir} -xpf -") # Run preremove script if File.exist?(File.join(workdir, 'tpkg', 'preremove')) pwd = Dir.pwd # chdir into the working directory so that the user can specify a # relative path to their file/script. Dir.chdir(File.join(workdir, 'tpkg')) # Warn the user about non-executable files, as system will just # silently fail and exit if that's the case. if !File.executable?(File.join(workdir, 'tpkg', 'preremove')) warn "Warning: preremove script for #{File.basename(package_file)} is not executable, execution will likely fail" end if @force system(File.join(workdir, 'tpkg', 'preremove')) || warn("Warning: preremove for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") else system(File.join(workdir, 'tpkg', 'preremove')) || raise("Error: preremove for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") end # Switch back to our previous directory Dir.chdir(pwd) end remove_init_scripts(pkg[:metadata]) remove_crontabs(pkg[:metadata]) # Run any externals pkg[:metadata][:externals].each do |external| if !options[:externals_to_skip] || !options[:externals_to_skip].include?(external) run_external(pkg[:metadata][:filename], :remove, external[:name], external[:data]) end end if pkg[:metadata][:externals] # determine which configuration files have been modified modified_conf_files = [] file_metadata = file_metadata_for_installed_packages([pkg[:metadata][:filename]]).values[0] file_metadata[:files].each do |file| if file[:config] # get expected checksum. For files that were encrypted, we're interested in the # checksum of the decrypted version chksum_expected = file[:checksum][:digests].first[:value] file[:checksum][:digests].each do | digest | if digest[:decrypted] == true chksum_expected = digest[:value].to_s end end fp = normalize_path(file[:path]) chksum_actual = Digest::SHA256.hexdigest(File.read(fp)) if chksum_actual != chksum_expected modified_conf_files << fp end end end if file_metadata # Remove files files_to_remove = conflicting_files(package_file, CHECK_REMOVE) # Reverse the order of the files, as directories will appear first # in the listing but we want to remove any files in them before # trying to remove the directory. files_to_remove.reverse.each do |file| # don't remove conf files that have been modified next if modified_conf_files.include?(file) begin if !File.directory?(file) File.delete(file) else begin Dir.delete(file) rescue SystemCallError => e # Directory isn't empty #puts e.message end end rescue Errno::ENOENT warn "File #{file} from package #{File.basename(package_file)} missing during remove" # I know it's bad to have a generic rescue for all exceptions, but in this case, there # can be many things that might go wrong when removing a file. We don't want tpkg # to crash and leave the packages in a bad state. It's better to catch # all exceptions and give the user some warnings. rescue warn "Failed to remove file #{file}." end end # Run postremove script if File.exist?(File.join(workdir, 'tpkg', 'postremove')) pwd = Dir.pwd # chdir into the working directory so that the user can specify a # relative path to their file/script. Dir.chdir(File.join(workdir, 'tpkg')) # Warn the user about non-executable files, as system will just # silently fail and exit if that's the case. if !File.executable?(File.join(workdir, 'tpkg', 'postremove')) warn "Warning: postremove script for #{File.basename(package_file)} is not executable, execution will likely fail" end # Note this only warns the user if the postremove fails, it does # not raise an exception like we do if preremove fails. Raising # an exception would leave the package's files removed but the # package still registered as installed, which does not seem # desirable. We could reinstall the package's files and raise an # exception, but this seems the best approach to me. system(File.join(workdir, 'tpkg', 'postremove')) || warn("Warning: postremove for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") ret_val = POSTREMOVE_ERR if $?.exitstatus > 0 # Switch back to our previous directory Dir.chdir(pwd) end File.delete(package_file) # delete metadata dir of this package package_metadata_dir = File.join(@metadata_directory, File.basename(package_file, File.extname(package_file))) FileUtils.rm_rf(package_metadata_dir) # remove native dependency stub packages if needed remove_native_stub_pkg(pkg) # Cleanup FileUtils.rm_rf(workdir) end # log changes currently_installed = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} removed = already_installed_pkgs - currently_installed log_changes({:removed => removed}) # send update back to reporting server unless @report_server.nil? || options[:upgrade] options = {:removed => removed, :currently_installed => currently_installed} send_update_to_server(options) end unlock return ret_val end def verify_file_metadata(requests) results = {} packages = [] # parse request to determine what packages the user wants to verify requests.each do |request| req = Tpkg::parse_request(request) packages.concat(installed_packages_that_meet_requirement(req).collect { |pkg| pkg[:metadata][:filename] }) end # loop through each package, and verify checksum, owner, group and perm of each file that was installed packages.each do | package_file | puts "Verifying #{package_file}" package_full_name = File.basename(package_file, File.extname(package_file)) # Extract checksum.xml from the package checksum_xml = nil # get file_metadata from the installed package file_metadata = FileMetadata::instantiate_from_dir(File.join(@metadata_directory, package_full_name)) if !file_metadata errors = [] errors << "Can't find file metadata. Most likely this is because the package was created before the verify feature was added" results[package_file] = errors return results end # verify installed files match their checksum file_metadata[:files].each do |file| errors = [] gid_expected, uid_expected, perms_expected, chksum_expected = nil fp = file[:path] # get expected checksum. For files that were encrypted, we're interested in the # checksum of the decrypted version if file[:checksum] chksum_expected = file[:checksum][:digests].first[:value] file[:checksum][:digests].each do | digest | if digest[:decrypted] == true chksum_expected = digest[:value].to_s end end end # get expected acl values if file[:uid] uid_expected = file[:uid].to_i end if file[:gid] gid_expected = file[:gid].to_i end if file[:perms] perms_expected = file[:perms].to_s end fp = normalize_path(fp) # can't handle symlink if File.symlink?(fp) next end # check if file exist if !File.exists?(fp) errors << "File is missing" else # get actual values chksum_actual = Digest::SHA256.hexdigest(File.read(fp)) if File.file?(fp) uid_actual = File.stat(fp).uid gid_actual = File.stat(fp).gid perms_actual = File.stat(fp).mode.to_s(8) end if !chksum_expected.nil? && !chksum_actual.nil? && chksum_expected != chksum_actual errors << "Checksum doesn't match (Expected: #{chksum_expected}, Actual: #{chksum_actual}" end if !uid_expected.nil? && !uid_actual.nil? && uid_expected != uid_actual errors << "uid doesn't match (Expected: #{uid_expected}, Actual: #{uid_actual}) " end if !gid_expected.nil? && !gid_actual.nil? && gid_expected != gid_actual errors << "gid doesn't match (Expected: #{gid_expected}, Actual: #{gid_actual})" end if !perms_expected.nil? && !perms_actual.nil? && perms_expected != perms_actual errors << "perms doesn't match (Expected: #{perms_expected}, Actual: #{perms_actual})" end results[fp] = errors end end return results end def execute_init(options, *moreoptions) ret_val = 0 packages_to_execute_on = [] if options.is_a?(Hash) action = options[:cmd] requested_packages = options[:packages] requested_init_scripts = options[:scripts] else # for backward compatibility action = moreoptions[0] requested_packages = options end # if user specified no packages, then assume all if requested_packages.nil? packages_to_execute_on = installed_packages_that_meet_requirement(nil) else requested_packages.uniq! requested_packages.each do |request| req = Tpkg::parse_request(request) packages_to_execute_on.concat(installed_packages_that_meet_requirement(req)) end end if packages_to_execute_on.empty? warn "Warning: Unable to find package(s) \"#{requested_packages.join(",")}\"." else packages_to_execute_on.each do |pkg| ret_val |= execute_init_for_package(pkg, action, requested_init_scripts) end end return ret_val end def execute_init_for_package(pkg, action, requested_init_scripts = nil) ret_val = 0 # Get init scripts metadata for the given package init_scripts_metadata = init_scripts(pkg[:metadata]) # warn if there's no init script and then return if init_scripts_metadata.nil? || init_scripts_metadata.empty? warn "Warning: There is no init script for #{pkg[:metadata][:name]}." return 1 end # convert the init scripts metadata to an array of { path => value, start => value} # so that we can order them based on their start value. This is necessary because # we need to execute the init scripts in correct order. init_scripts = [] init_scripts_metadata.each do | installed_path, init_info | init = {} init[:path] = installed_path init[:start] = init_info[:init][:start] || 0 # if user requests specific init scripts, then only include those if requested_init_scripts.nil? or requested_init_scripts && requested_init_scripts.include?(File.basename(installed_path)) init_scripts << init end end if requested_init_scripts && init_scripts.empty? warn "Warning: There are no init scripts that satisfy your request: #{requested_init_scripts.inspect} for package #{pkg[:metadata][:name]}." end # Reverse order if doing stop. if action == "stop" ordered_init_scripts = init_scripts.sort{ |a,b| b[:start] <=> a[:start] } else ordered_init_scripts = init_scripts.sort{ |a,b| a[:start] <=> b[:start] } end ordered_init_scripts.each do |init_script| installed_path = init_script[:path] system("#{installed_path} #{action}") ret_val = INITSCRIPT_ERR if $?.exitstatus > 0 end return ret_val end # We can't safely calculate a set of dependencies and install the # resulting set of packages if another user is manipulating the installed # packages at the same time. These methods lock and unlock the package # system so that only one user makes changes at a time. def lock if @locks > 0 @locks += 1 return end if File.directory?(@lock_directory) if @lockforce warn "Forcing lock removal" FileUtils.rm_rf(@lock_directory) else # Remove old lock files on the assumption that they were left behind # by a previous failed run if File.mtime(@lock_directory) < Time.at(Time.now - 60 * 60 * 2) warn "Lock is more than 2 hours old, removing" FileUtils.rm_rf(@lock_directory) end end end begin Dir.mkdir(@lock_directory) File.open(@lock_pid_file, 'w') { |file| file.puts($$) } @locks = 1 rescue Errno::EEXIST lockpid = '' begin File.open(@lock_pid_file) { |file| lockpid = file.gets.chomp } rescue Errno::ENOENT end # check that the process is actually running # if not, clean up old lock and attemp to obtain lock again if Tpkg::process_running?(lockpid) raise "tpkg repository locked by another process (with PID #{lockpid})" else FileUtils.rm_rf(@lock_directory) lock end end end def unlock if @locks == 0 warn "unlock called but not locked, that probably shouldn't happen" return end @locks -= 1 if @locks == 0 FileUtils.rm_rf(@lock_directory) end end # Build a dependency map of currently installed packages # For example, if we have pkgB and pkgC which depends on pkgA, then # the dependency map would look like this: # "pkgA.tpkg" => [{pkgB metadata}, {pkgC metadata}] def get_dependency_mapping dependency_mapping = {} installed_packages.each do | pkg | metadata = pkg[:metadata] # Get list of pkgs that this pkg depends on next if metadata[:dependencies].nil? depended_on = [] metadata[:dependencies].each do |req| next if req[:type] == :native depended_on |= installed_packages_that_meet_requirement(req) end # populate the depencency map depended_on.each do | req_pkg | dependency_mapping[req_pkg[:metadata][:filename]] ||= [] dependency_mapping[req_pkg[:metadata][:filename]] << pkg end end return dependency_mapping end # Given a list of packages, return a list of dependents packages def get_dependents(pkgs) dependents = [] to_check = pkgs.map { |pkg| pkg[:metadata][:filename] } dependency = get_dependency_mapping while pkgfile = to_check.pop pkgs = dependency[pkgfile.to_s] next if pkgs.nil? dependents |= pkgs to_check |= pkgs.map { |pkg| pkg[:metadata][:filename] } end return dependents end # Given a list of packages, return a list of all their prerequisite dependencies # Example: If pkgA depends on pkgB, and pkgB depends on pkgC, then calling this # method on pkgA will returns pkgB and pkgC # Assumption: There is no cyclic dependency def get_prerequisites(pkgs) pre_reqs = [] to_check = pkgs.clone while pkg = to_check.pop next if pkg[:metadata][:dependencies].nil? pkg[:metadata][:dependencies].each do | dep | pre_req = installed_packages_that_meet_requirement(dep) pre_reqs |= pre_req to_check |= pre_req end end return pre_reqs end # print out history packages installation/remove def installation_history if !File.exists?(File.join(@log_directory,'changes.log')) puts "Tpkg history log does not exist." return GENERIC_ERR end IO.foreach(File.join(@log_directory,'changes.log')) do |line| puts line end end # Download packages that meet the requests specified by the user. # Packages are downloaded into the current directory or into the directory # specified in options[:out] def download_pkgs(requests, options={}) if options[:out] if !File.exists?(options[:out]) FileUtils.mkdir_p(options[:out]) elsif !File.directory?(options[:out]) puts "#{options[:out]} is not a valid directory." return GENERIC_ERR end end output_dir = options[:out] || Dir.pwd requirements = [] packages = {} original_dir = Dir.pwd workdir = Tpkg::tempdir("tpkg_download") Dir.chdir(workdir) parse_requests(requests, requirements, packages) packages = packages.values.flatten if packages.size < 1 puts "Unable to find any packages that satisfy your request. Try running with --debug for more info" Dir.chdir(original_dir) return GENERIC_ERR end # Confirm with user what packages will be downloaded packages.delete_if{|pkg|pkg[:source] !~ /^http/} puts "The following packages will be downloaded:" packages.each do |pkg| puts "#{pkg[:metadata][:filename]} (source: #{pkg[:source]})" end if @@prompt && !Tpkg::confirm Dir.chdir(original_dir) return 0 end err_code = 0 puts "Downloading to #{output_dir}" packages.each do |pkg| puts "Downloading #{pkg[:metadata][:filename]}" begin downloaded_file = download(pkg[:source], pkg[:metadata][:filename], Dir.pwd, false) # copy downloaded files over to destination FileUtils.cp(downloaded_file, output_dir) rescue warn "Warning: unable to download #{pkg[:metadata][:filename]} to #{output_dir}" err_code = GENERIC_ERR end end # clean up working directory FileUtils.rm_rf(workdir) Dir.chdir(original_dir) return err_code end # TODO: figure out what other methods above can be turned into protected methods protected # log changes of pkgs that were installed/removed def log_changes(options={}) msg = "" user = Etc.getlogin || Etc.getpwuid(Process.uid).name newly_installed = removed = [] newly_installed = options[:newly_installed] if options[:newly_installed] removed = options[:removed] if options[:removed] removed.each do |pkg| msg = "#{msg}#{Time.new} #{pkg[:filename]} was removed by #{user}\n" end newly_installed.each do |pkg| msg = "#{msg}#{Time.new} #{pkg[:filename]} was installed by #{user}\n" end msg.lstrip! unless msg.empty? File.open(File.join(@log_directory,'changes.log'), 'a') {|f| f.write(msg) } end end def send_update_to_server(options={}) request = {"client"=>Facter['fqdn'].value} request[:user] = Etc.getlogin || Etc.getpwuid(Process.uid).name request[:tpkg_home] = ENV['TPKG_HOME'] if options[:currently_installed] currently_installed = options[:currently_installed] else currently_installed = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} end # Figure out list of packages that were already installed, newly installed and newly removed if options[:newly_installed] newly_installed = options[:newly_installed] request[:newly_installed] = URI.escape(YAML.dump(newly_installed)) already_installed = currently_installed - newly_installed else already_installed = currently_installed end request[:already_installed] = URI.escape(YAML.dump(already_installed)) if options[:removed] removed = options[:removed] request[:removed] = URI.escape(YAML.dump(removed)) end begin response = nil # Need to set timeout otherwise tpkg can hang for a long time when having # problem talking to the reporter server. # I can't seem get net-ssh timeout to work so we'll just handle the timeout ourselves timeout(CONNECTION_TIMEOUT) do update_uri = URI.parse("#{@report_server}") http = Tpkg::gethttp(update_uri) post = Net::HTTP::Post.new(update_uri.path) post.set_form_data(request) response = http.request(post) end case response when Net::HTTPSuccess puts "Successfully send update to reporter server" else $stderr.puts response.body #response.error! # just ignore error and give user warning puts "Failed to send update to reporter server" end rescue Timeout::Error puts "Timed out when trying to send update to reporter server" rescue puts "Failed to send update to reporter server" end end # create and install native stub package if needed # this stub package helps prevent user from removing native packages that # our tpkg packages depend on def stub_native_pkg(pkg) # gather all of the native dependencies native_deps = pkg[:metadata].get_native_deps return if native_deps.nil? or native_deps.empty? if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ rpm = create_rpm("stub_for_#{pkg[:metadata][:name]}", native_deps) return if rpm.nil? # install the rpm cmd = "rpm -i #{rpm}" puts cmd if @@debug system(cmd) if !$?.success? warn "Warning: Failed to install native stub package for #{pkg[:metadata][:name]}" end else # TODO: support other OSes end end # remove the native dependency stub packages if there's any def remove_native_stub_pkg(pkg) # Don't have to do anything if this package has no native dependencies native_deps = pkg[:metadata].get_native_deps return if native_deps.nil? or native_deps.empty? # the convention is that stub package is named as "stub_for_pkgname" stub_pkg_name = "stub_for_#{pkg[:metadata][:name]}" if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ cmd = "yum -y remove #{stub_pkg_name}" puts cmd if @@debug system(cmd) if !$?.success? warn "Warning: Failed to remove native stub package for #{pkg[:metadata][:name]}" end else # TODO: support other OSes end end def create_rpm(name, deps=[]) # setup directories for rpmbuild topdir = Tpkg::tempdir('rpmbuild') %w[BUILD RPMS SOURCES SPECS SRPMS].each do |dir| FileUtils.mkdir_p(File.join(topdir, dir)) end dep_list = deps.collect{|dep|dep[:name]}.join(",") # create rpm spec file spec = <<-EOS.gsub(/^\s+/, "") Name: #{name} Summary: stub pkg created by tpkg Version: 1 Release: 1 buildarch: noarch Requires: #{dep_list} Group: Applications/System License: MIT BuildRoot: %{_builddir}/%{name}-buildroot %description stub pkg created by tpkg for the following dependencies: #{dep_list} %files EOS spec_file = File.join(topdir, 'SPECS', 'pkg.spec') File.open(spec_file, 'w') do |file| file.puts(spec) end # run rpmbuild system("rpmbuild -bb --define '_topdir #{topdir}' #{spec_file}") if !$?.success? warn "Warning: Failed to create native stub package for #{name}" return nil end # copy result over to tmpfile result = File.join(topdir, 'RPMS', 'noarch', "#{name}-1-1.noarch.rpm") rpm = nil if File.exists?(result) tmpfile = Tempfile.new(File.basename(result)) FileUtils.cp(result, tmpfile.path) rpm = tmpfile.path end # cleanup FileUtils.rm_rf(topdir) return rpm end end Replace a couple of instances of "if $?.exitstatus > 0" with "if !$?.success?". The exitstatus check didn't account for negative exit values, or cases where the process didn't terminate normally. I ran into the second case with an buggy init script that was killing itself, leading to exitstatus returning nil. ############################################################################## # tpkg package management system library # Copyright 2009, 2010 AT&T Interactive # License: MIT (http://www.opensource.org/licenses/mit-license.php) ############################################################################## STDOUT.sync = STDERR.sync = true # All outputs/prompts to the kernel ASAP # When we build the tpkg packages we put this file in # /usr/lib/ruby/site_ruby/1.8/ or similar and then the rest of the ruby # files (versiontype.rb, deployer.rb, etc) into # /usr/lib/ruby/site_ruby/1.8/tpkg/ # We need to tell Ruby to search that tpkg subdirectory. # The alternative is to specify the subdirectory in the require # (require 'tpkg/versiontype' for example), but tpkg is also the name # of the executable script so we can't create a subdirectory here named # tpkg. If we put the subdir in the require lines then users couldn't # run tpkg directly from an svn working copy. tpkglibdir = File.join(File.dirname(__FILE__), 'tpkg') if File.directory?(tpkglibdir) $:.unshift(tpkglibdir) end # We store this gem in our thirdparty directory. So we need to add it # it to the search path # This one is for when everything is installed $:.unshift(File.join(File.dirname(__FILE__), 'thirdparty/kwalify-0.7.1/lib')) # And this one for when we're in the svn directory structure $:.unshift(File.join(File.dirname(File.dirname(__FILE__)), 'thirdparty/kwalify-0.7.1/lib')) begin # Try loading facter w/o gems first so that we don't introduce a # dependency on gems if it is not needed. require 'facter' # Facter rescue LoadError require 'rubygems' require 'facter' end require 'digest/sha2' # Digest::SHA256#hexdigest, etc. require 'uri' # URI require 'net/http' # Net::HTTP require 'net/https' # Net::HTTP#use_ssl, etc. require 'time' # Time#httpdate require 'rexml/document' # REXML::Document require 'fileutils' # FileUtils.cp, rm, etc. require 'tempfile' # Tempfile require 'find' # Find require 'etc' # Etc.getpwnam, getgrnam require 'openssl' # OpenSSL require 'open3' # Open3 require 'versiontype' # Version require 'deployer' require 'set' require 'metadata' require 'kwalify' # for validating yaml class Tpkg VERSION = 'trunk' CONFIGDIR = '/etc' GENERIC_ERR = 1 POSTINSTALL_ERR = 2 POSTREMOVE_ERR = 3 INITSCRIPT_ERR = 4 CONNECTION_TIMEOUT = 10 DEFAULT_OWNERSHIP_UID = 0 attr_reader :installed_directory # # Class methods # @@debug = false def self.set_debug(debug) @@debug = debug end @@prompt = true def self.set_prompt(prompt) @@prompt = prompt end # Find GNU tar or bsdtar in ENV['PATH'] # Raises an exception if a suitable tar cannot be found @@tar = nil @@taroptions = "" @@tarinfo = {:version => 'unknown'} TARNAMES = ['tar', 'gtar', 'gnutar', 'bsdtar'] def self.find_tar if !@@tar catch :tar_found do if !ENV['PATH'] raise "tpkg cannot run because the PATH env variable is not set." end ENV['PATH'].split(':').each do |path| TARNAMES.each do |tarname| if File.executable?(File.join(path, tarname)) IO.popen("#{File.join(path, tarname)} --version 2>/dev/null") do |pipe| pipe.each_line do |line| if line.include?('GNU tar') @@tarinfo[:type] = 'gnu' @@tar = File.join(path, tarname) elsif line.include?('bsdtar') @@tarinfo[:type] = 'bsd' @@tar = File.join(path, tarname) end if line =~ /(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)/ @@tarinfo[:version] = [$1, $2, $3].compact.join(".") end throw :tar_found if @@tar end end end end end # Raise an exception if we didn't find a suitable tar raise "Unable to find GNU tar or bsdtar in PATH" end end # bsdtar uses pax format by default. This format allows for vendor extensions, such # as the SCHILY.* extensions which were introduced by star). bsdtar actually uses # these extensions. These extension headers includde useful, but not vital information. # gnu tar should just ignore them and gives a warning. This is what the latest gnu tar # will do. However, on older gnu tar, it only threw an error at the end. The work # around is to explicitly tell gnu tar to ignore those extensions. if @@tarinfo[:type] == 'gnu' && @@tarinfo[:version] != 'unknown' && @@tarinfo[:version] >= '1.15.1' @@taroptions = "--pax-option='delete=SCHILY.*,delete=LIBARCHIVE.*'" end @@tar.dup end def self.clear_cached_tar @@tar = nil @@taroptions = "" @@tarinfo = {:version => 'unknown'} end # Encrypts the given file in-place (the plaintext file is replaced by the # encrypted file). The resulting file is compatible with openssl's 'enc' # utility. # Algorithm from http://www.ruby-forum.com/topic/101936#225585 MAGIC = 'Salted__' SALT_LEN = 8 @@passphrase = nil def self.encrypt(pkgname, filename, passphrase, cipher='aes-256-cbc') # passphrase can be a callback Proc, call it if that's the case pass = nil if @@passphrase pass = @@passphrase elsif passphrase.kind_of?(Proc) pass = passphrase.call(pkgname) @@passphrase = pass else pass = passphrase end # special handling for directory if File.directory?(filename) Find.find(filename) do |f| encrypt(pkgname, f, pass, cipher) if File.file?(f) end return end salt = OpenSSL::Random::random_bytes(SALT_LEN) c = OpenSSL::Cipher::Cipher.new(cipher) c.encrypt c.pkcs5_keyivgen(pass, salt, 1) tmpfile = Tempfile.new(File.basename(filename), File.dirname(filename)) # Match permissions and ownership of plaintext file st = File.stat(filename) File.chmod(st.mode & 07777, tmpfile.path) begin File.chown(st.uid, st.gid, tmpfile.path) rescue Errno::EPERM raise if Process.euid == 0 end tmpfile.write(MAGIC) tmpfile.write(salt) tmpfile.write(c.update(IO.read(filename)) + c.final) tmpfile.close File.rename(tmpfile.path, filename) end # Decrypt the given file in-place. def self.decrypt(pkgname, filename, passphrase, cipher='aes-256-cbc') # passphrase can be a callback Proc, call it if that's the case pass = nil if @@passphrase pass = @@passphrase elsif passphrase.kind_of?(Proc) pass = passphrase.call(pkgname) @@passphrase = pass else pass = passphrase end if File.directory?(filename) Find.find(filename) do |f| decrypt(pkgname, f, pass, cipher) if File.file?(f) end return end file = File.open(filename) if (buf = file.read(MAGIC.length)) != MAGIC raise "Unrecognized encrypted file #{filename}" end salt = file.read(SALT_LEN) c = OpenSSL::Cipher::Cipher.new(cipher) c.decrypt c.pkcs5_keyivgen(pass, salt, 1) tmpfile = Tempfile.new(File.basename(filename), File.dirname(filename)) # Match permissions and ownership of encrypted file st = File.stat(filename) File.chmod(st.mode & 07777, tmpfile.path) begin File.chown(st.uid, st.gid, tmpfile.path) rescue Errno::EPERM raise if Process.euid == 0 end tmpfile.write(c.update(file.read) + c.final) tmpfile.close File.rename(tmpfile.path, filename) end def self.verify_precrypt_file(filename) # This currently just verifies that the file seems to start with the # right bits. Any further verification would require the passphrase # and cipher so we could decrypt the file, but that would preclude # folks from including precrypt files for which they don't have the # passphrase in a package. In some environments it might be desirable # for folks to be able to build the package even if they couldn't # install it. file = File.open(filename) if (buf = file.read(MAGIC.length)) != MAGIC raise "Unrecognized encrypted file #{filename}" end true end # Makes a package from a directory containing the files to put into the package def self.make_package(pkgsrcdir, passphrase=nil, options = {}) pkgfile = nil # validate the output directory if the user has specified one outdir = options[:out] if outdir outdir = File.expand_path(outdir) if !File.directory?(outdir) raise "#{outdir} is not a valid directory" elsif !File.writable?(outdir) raise "#{outdir} is not writable" end end # Make a working directory workdir = nil # dirname('.') returns '.', which screws things up. So in cases # where the user passed us a directory that doesn't have enough # parts that we can get the parent directory we use a working # directory in the system's temp area. As an alternative we could # use Pathname.realpath to convert whatever the user passed us into # an absolute path. if File.dirname(pkgsrcdir) == pkgsrcdir workdir = tempdir('tpkg') else workdir = tempdir('tpkg', File.dirname(pkgsrcdir)) end begin # Make the 'tpkg' directory for storing the package contents tpkgdir = File.join(workdir, 'tpkg') Dir.mkdir(tpkgdir) # A package really shouldn't be partially relocatable, warn the user if # they're creating such a scourge. if (File.exist?(File.join(pkgsrcdir, 'root')) && File.exist?(File.join(pkgsrcdir, 'reloc'))) warn 'Warning: Your source directory should contain either a "root" or "reloc" directory, but not both.' end # Copy the package contents into that directory # I tried to use FileUtils.cp_r but it doesn't handle symlinks properly # And on further reflection it makes sense to only have one chunk of # code (tar) ever touch the user's files. system("#{find_tar} -C #{pkgsrcdir} -cf - . | #{find_tar} -C #{tpkgdir} -xpf -") || raise("Package content copy failed") # check metadata file errors = [] metadata = Metadata::instantiate_from_dir(tpkgdir) if !metadata raise 'Your source directory does not contain the metadata configuration file.' end # This is for when we're in developement mode or when installed as gem if File.exists?(File.join(File.dirname(File.dirname(__FILE__)), "schema")) schema_dir = File.join(File.dirname(File.dirname(__FILE__)), "schema") # This is the directory where we put our dtd/schema for validating # the metadata file elsif File.exist?(File.join(CONFIGDIR, 'tpkg', 'schema')) schema_dir = File.join(CONFIGDIR, 'tpkg', 'schema') else warn "Warning: unable to find schema for tpkg.yml" end errors = metadata.validate(schema_dir) if schema_dir if errors && !errors.empty? puts "Bad metadata file. Possible error(s):" errors.each {|e| puts e } raise "Failed to create package." unless options[:force] end # file_metadata hold information for files that are installed # by the package. For example, checksum, path, relocatable or not, etc. File.open(File.join(tpkgdir, "file_metadata.bin"), "w") do |file| filemetadata = get_filemetadata_from_directory(tpkgdir) filemetadata[:files].each do |file1| if metadata[:files] && metadata[:files][:files] && metadata[:files][:files].any?{|file2|file2[:path] == file1[:path] && file2[:config]} file1[:config] = true end end data = filemetadata.to_hash.recursively{|h| h.stringify_keys } Marshal::dump(data, file) end # Check all the files are there as specified in the metadata config file metadata[:files][:files].each do |tpkgfile| tpkg_path = tpkgfile[:path] working_path = nil if tpkg_path[0,1] == File::SEPARATOR working_path = File.join(tpkgdir, 'root', tpkg_path) else working_path = File.join(tpkgdir, 'reloc', tpkg_path) end # Raise an exception if any files listed in tpkg.yml can't be found if !File.exist?(working_path) && !File.symlink?(working_path) raise "File #{tpkg_path} referenced in tpkg.yml but not found" end # check permission/ownership of crontab files if tpkgfile[:crontab] data = {:actual_file => working_path, :metadata => metadata, :file_metadata => tpkgfile} perms, uid, gid = predict_file_perms_and_ownership(data) # crontab needs to be owned by root, and is not writable by group or others if uid != 0 warn "Warning: Your cron jobs in \"#{tpkgfile[:path]}\" might fail to run because the file is not owned by root." end if (perms & 0022) != 0 warn "Warning: Your cron jobs in \"#{tpkgfile[:path]}\" might fail to run because the file is writable by group and/or others." end end # Encrypt any files marked for encryption if tpkgfile[:encrypt] if tpkgfile[:encrypt][:precrypt] verify_precrypt_file(working_path) else if passphrase.nil? raise "Package requires encryption but supplied passphrase is nil" end encrypt(metadata[:name], working_path, passphrase, *([tpkgfile[:encrypt][:algorithm]].compact)) end end end unless metadata[:files].nil? or metadata[:files][:files].nil? package_filename = metadata.generate_package_filename package_directory = File.join(workdir, package_filename) Dir.mkdir(package_directory) if outdir pkgfile = File.join(outdir, package_filename + '.tpkg') else pkgfile = File.join(File.dirname(pkgsrcdir), package_filename + '.tpkg') end if File.exist?(pkgfile) || File.symlink?(pkgfile) if @@prompt print "Package file #{pkgfile} already exists, overwrite? [y/N]" response = $stdin.gets if response !~ /^y/i return end end File.delete(pkgfile) end # update metadata file with the tpkg version metadata.add_tpkg_version(VERSION) # Tar up the tpkg directory tpkgfile = File.join(package_directory, 'tpkg.tar') system("#{find_tar} -C #{workdir} -cf #{tpkgfile} tpkg") || raise("tpkg.tar creation failed") # Checksum the tarball # Older ruby version doesn't support this # digest = Digest::SHA256.file(tpkgfile).hexdigest digest = Digest::SHA256.hexdigest(File.read(tpkgfile)) # Create checksum.xml File.open(File.join(package_directory, 'checksum.xml'), 'w') do |csx| csx.puts('<tpkg_checksums>') csx.puts(' <checksum>') csx.puts(' <algorithm>SHA256</algorithm>') csx.puts(" <digest>#{digest}</digest>") csx.puts(' </checksum>') csx.puts('</tpkg_checksums>') end # compress if needed if options[:compress] tpkgfile = compress_file(tpkgfile, options[:compress]) end # Tar up checksum.xml and the main tarball system("#{find_tar} -C #{workdir} -cf #{pkgfile} #{package_filename}") || raise("Final package creation failed") ensure # Remove our working directory FileUtils.rm_rf(workdir) end # Return the filename of the package pkgfile end def self.package_toplevel_directory(package_file) # This assumes the first entry in the tarball is the top level directory. # I think that is a safe assumption. toplevel = nil # FIXME: This is so lame, to read the whole package to get the # first filename. Blech. IO.popen("#{find_tar} -tf #{package_file} #{@@taroptions}") do |pipe| toplevel = pipe.gets if toplevel.nil? raise "Package directory structure of #{package_file} unexpected. Unable to get top level." end toplevel.chomp! # Avoid SIGPIPE, if we don't sink the rest of the output from tar # then tar ends up getting SIGPIPE when it tries to write to the # closed pipe and exits with error, which causes us to throw an # exception down below here when we check the exit status. pipe.read end if !$?.success? raise "Error reading top level directory from #{package_file}" end # Strip off the trailing slash toplevel.sub!(Regexp.new("#{File::SEPARATOR}$"), '') if toplevel.include?(File::SEPARATOR) raise "Package directory structure of #{package_file} unexpected, top level is more than one directory deep" end toplevel end def self.get_filemetadata_from_directory(tpkgdir) filemetadata = {} root_dir = File.join(tpkgdir, "root") reloc_dir = File.join(tpkgdir, "reloc") files = [] Find.find(root_dir, reloc_dir) do |f| next if !File.exist?(f) relocatable = false # Append file separator at the end for directory if File.directory?(f) f += File::SEPARATOR end # check if it's from root dir or reloc dir if f =~ /^#{Regexp.escape(root_dir)}/ short_fn = f[root_dir.length ..-1] else short_fn = f[reloc_dir.length + 1..-1] relocatable = true end next if short_fn.nil? or short_fn.empty? file = {} file[:path] = short_fn file[:relocatable] = relocatable # only do checksum for file if File.file?(f) digest = Digest::SHA256.hexdigest(File.read(f)) file[:checksum] = {:algorithm => "SHA256", :digests => [{:value => digest}]} end files << file end filemetadata['files'] = files #return FileMetadata.new(YAML::dump(filemetadata),'yml') return FileMetadata.new(Marshal::dump(filemetadata),'bin') end def self.verify_package_checksum(package_file, options = {}) topleveldir = options[:topleveldir] || package_toplevel_directory(package_file) # Extract checksum.xml from the package checksum_xml = nil IO.popen("#{find_tar} #{@@taroptions} -xf #{package_file} -O #{File.join(topleveldir, 'checksum.xml')}") do |pipe| checksum_xml = REXML::Document.new(pipe.read) end if !$?.success? raise "Error extracting checksum.xml from #{package_file}" end # Verify checksum.xml checksum_xml.elements.each('/tpkg_checksums/checksum') do |checksum| digest = nil algorithm = checksum.elements['algorithm'].text digest_from_package = checksum.elements['digest'].text case algorithm when 'SHA224' digest = Digest::SHA224.new when 'SHA256' digest = Digest::SHA256.new when 'SHA384' digest = Digest::SHA384.new when 'SHA512' digest = Digest::SHA512.new else raise("Unrecognized checksum algorithm #{checksum.elements['algorithm']}") end # Extract tpkg.tar from the package and digest it extract_tpkg_tar_command = cmd_to_extract_tpkg_tar(package_file, topleveldir) IO.popen(extract_tpkg_tar_command) do |pipe| #IO.popen("#{find_tar} -xf #{package_file} -O #{File.join(topleveldir, 'tpkg.tar')} #{@@taroptions}") do |pipe| # Package files can be quite large, so we digest the package in # chunks. A survey of the Internet turns up someone who tested # various chunk sizes on various platforms and found 4k to be # consistently the best. I'm too lazy to do my own testing. # http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/721d304fc8a5cc71 while buf = pipe.read(4096) digest << buf end end if !$?.success? raise "Error extracting tpkg.tar from #{package_file}" end if digest != digest_from_package raise "Checksum mismatch for #{algorithm}, #{digest} != #{digest_from_package}" end end end # Extracts and returns the metadata from a package file def self.metadata_from_package(package_file, options = {}) topleveldir = options[:topleveldir] || package_toplevel_directory(package_file) # Verify checksum verify_package_checksum(package_file) # Extract and parse tpkg.xml metadata = nil ['yml','xml'].each do |format| file = File.join('tpkg', "tpkg.#{format}") # use popen3 instead of popen because popen display stderr when there's an error such as # tpkg.yml not being there, which is something we want to ignore since old tpkg doesn't # have tpkg.yml file extract_tpkg_tar_command = cmd_to_extract_tpkg_tar(package_file, topleveldir) stdin, stdout, stderr = Open3.popen3("#{extract_tpkg_tar_command} | #{find_tar} -xf - -O #{file}") filecontent = stdout.read if filecontent.nil? or filecontent.empty? next else metadata = Metadata.new(filecontent, format) break end end unless metadata raise "Failed to extract metadata from #{package_file}" end # Insert an attribute on the root element with the package filename metadata[:filename] = File.basename(package_file) return metadata end # Extracts and returns the metadata from a directory of package files def self.metadata_from_directory(directory) metadata = [] # if metadata.xml already exists, then go ahead and # parse it existing_metadata_file = File.join(directory, 'metadata.yml') existing_metadata = {} if File.exists?(existing_metadata_file) metadata_lists = File.read(File.join(directory, 'metadata.yml')).split("---") metadata_lists.each do | metadata_text | if metadata_text =~ /^:?filename:(.+)/ filename = $1.strip existing_metadata[filename] = Metadata.new(metadata_text,'yml') end end end # Populate the metadata array with metadata for all of the packages # in the given directory. Reuse existing metadata if possible. Dir.glob(File.join(directory, '*.tpkg')) do |pkg| if existing_metadata[File.basename(pkg)] metadata << existing_metadata[File.basename(pkg)] else metadata_yml = metadata_from_package(pkg) metadata << metadata_yml end end return metadata end # Extracts the metadata from a directory of package files and saves it # to metadata.xml in that directory def self.extract_metadata(directory, dest=nil) dest = directory if dest.nil? metadata = metadata_from_directory(directory) # And write that out to metadata.yml metadata_tmpfile = Tempfile.new('metadata.yml', dest) metadata.each do | metadata | YAML::dump(metadata.to_hash.recursively{|h| h.stringify_keys }, metadata_tmpfile) #YAML::dump(metadata.to_hash, metadata_tmpfile) end metadata_tmpfile.close File.chmod(0644, metadata_tmpfile.path) File.rename(metadata_tmpfile.path, File.join(dest, 'metadata.yml')) end # Haven't found a Ruby method for creating temporary directories, # so create a temporary file and replace it with a directory. def self.tempdir(basename, tmpdir=Dir::tmpdir) tmpfile = Tempfile.new(basename, tmpdir) tmpdir = tmpfile.path tmpfile.close! Dir.mkdir(tmpdir) tmpdir end @@arch = nil def self.get_arch if !@@arch Facter.loadfacts @@arch = Facter['hardwaremodel'].value end @@arch.dup end # Returns a string representing the OS of this box of the form: # "OSname-OSmajorversion". The OS name is currently whatever facter # returns for the 'operatingsystem' fact. The major version is a bit # messier, as we try on a per-OS basis to come up with something that # represents the major version number of the OS, where binaries are # expected to be compatible across all versions of the OS with that # same major version number. Examples include RedHat-5, CentOS-5, # FreeBSD-7, Darwin-10.5, and Solaris-5.10 @@os = nil def self.get_os if !@@os # Tell facter to load everything, otherwise it tries to dynamically # load the individual fact libraries using a very broken mechanism Facter.loadfacts operatingsystem = Facter['operatingsystem'].value osver = nil if Facter['lsbmajdistrelease'] && Facter['lsbmajdistrelease'].value && !Facter['lsbmajdistrelease'].value.empty? osver = Facter['lsbmajdistrelease'].value elsif operatingsystem == 'Ubuntu' # Work around lack of lsbmajdistrelease on older versions of Ubuntu # due to older version of facter. Support for lsbmajdistrelease on # Ubuntu was added in facter 1.5.3, but there's no good way to force # older Ubuntu systems to a newer version of facter. osver = Facter['lsbdistrelease'].value.split('.').first elsif Facter['kernel'] && Facter['kernel'].value == 'Darwin' && Facter['macosx_productversion'] && Facter['macosx_productversion'].value && !Facter['macosx_productversion'].value.empty? macver = Facter['macosx_productversion'].value # Extract 10.5 from 10.5.6, for example osver = macver.split('.')[0,2].join('.') elsif Facter['operatingsystem'] && Facter['operatingsystem'].value == 'FreeBSD' # Extract 7 from 7.1-RELEASE, for example fbver = Facter['operatingsystemrelease'].value osver = fbver.split('.').first elsif Facter['operatingsystemrelease'] && Facter['operatingsystemrelease'].value && !Facter['operatingsystemrelease'].value.empty? osver = Facter['operatingsystemrelease'].value else raise "Unable to determine proper OS value on this platform" end @@os = "#{operatingsystem}-#{osver}" end @@os.dup end # Given an array of pkgs. Determine if any of those package # satisfy the requirement specified by req def self.packages_meet_requirement?(pkgs, req) pkgs.each do | pkg | return true if Tpkg::package_meets_requirement?(pkg, req) end return false end # pkg is a standard Hash format used in the library to represent an # available package # req is a standard Hash format used in the library to represent package # requirements def self.package_meets_requirement?(pkg, req) result = true puts "pkg_meets_req checking #{pkg.inspect} against #{req.inspect}" if @@debug metadata = pkg[:metadata] if req[:type] == :native && pkg[:source] != :native_installed && pkg[:source] != :native_available # A req for a native package must be satisfied by a native package puts "Package fails native requirement" if @@debug result = false elsif req[:filename] result = false if req[:filename] != metadata[:filename] elsif req[:type] == :tpkg && (pkg[:source] == :native_installed || pkg[:source] == :native_available) # Likewise a req for a tpkg must be satisfied by a tpkg puts "Package fails non-native requirement" if @@debug result = false elsif metadata[:name] == req[:name] same_min_ver_req = false same_max_ver_req = false if req[:allowed_versions] version = metadata[:version] version = "#{version}-#{metadata[:package_version]}" if metadata[:package_version] if !File.fnmatch(req[:allowed_versions], version) puts "Package fails version requirement.)" if @@debug result = false end end if req[:minimum_version] pkgver = Version.new(metadata[:version]) reqver = Version.new(req[:minimum_version]) if pkgver < reqver puts "Package fails minimum_version (#{pkgver} < #{reqver})" if @@debug result = false elsif pkgver == reqver same_min_ver_req = true end end if req[:maximum_version] pkgver = Version.new(metadata[:version]) reqver = Version.new(req[:maximum_version]) if pkgver > reqver puts "Package fails maximum_version (#{pkgver} > #{reqver})" if @@debug result = false elsif pkgver == reqver same_max_ver_req = true end end if same_min_ver_req && req[:minimum_package_version] pkgver = Version.new(metadata[:package_version]) reqver = Version.new(req[:minimum_package_version]) if pkgver < reqver puts "Package fails minimum_package_version (#{pkgver} < #{reqver})" if @@debug result = false end end if same_max_ver_req && req[:maximum_package_version] pkgver = Version.new(metadata[:package_version]) reqver = Version.new(req[:maximum_package_version]) if pkgver > reqver puts "Package fails maximum_package_version (#{pkgver} > #{reqver})" if @@debug result = false end end # The empty? check ensures that a package with no operatingsystem # field matches all clients. if metadata[:operatingsystem] && !metadata[:operatingsystem].empty? && !metadata[:operatingsystem].include?(get_os) && !metadata[:operatingsystem].any?{|os| get_os =~ /#{os}/} puts "Package fails operatingsystem" if @@debug result = false end # Same deal with empty? here if metadata[:architecture] && !metadata[:architecture].empty? && !metadata[:architecture].include?(get_arch) && !metadata[:architecture].any?{|arch| get_arch =~ /#{arch}/} puts "Package fails architecture" if @@debug result = false end else puts "Package fails name" if @@debug result = false end if result puts "Package matches" if @@debug end result end # Define a block for sorting packages in order of desirability # Suitable for passing to Array#sort as array.sort(&SORT_PACKAGES) SORT_PACKAGES = lambda do |a,b| # # We first prepare all of the values we wish to compare # # Name aname = a[:metadata][:name] bname = b[:metadata][:name] # Currently installed # Conflicted about whether this belongs here or not, not sure if all # potential users of this sorting system would want to prefer currently # installed packages. acurrentinstall = 0 if (a[:source] == :currently_installed || a[:source] == :native_installed) && a[:prefer] == true acurrentinstall = 1 end bcurrentinstall = 0 if (b[:source] == :currently_installed || b[:source] == :native_installed) && b[:prefer] == true bcurrentinstall = 1 end # Version aversion = Version.new(a[:metadata][:version]) bversion = Version.new(b[:metadata][:version]) # Package version apkgver = Version.new(0) if a[:metadata][:package_version] apkgver = Version.new(a[:metadata][:package_version]) end bpkgver = Version.new(0) if b[:metadata][:package_version] bpkgver = Version.new(b[:metadata][:package_version]) end # OS # Fewer OSs is better, but zero is least desirable because zero means # the package works on all OSs (i.e. it is the most generic package). # We prefer packages tuned to a particular set of OSs over packages # that work everywhere on the assumption that the package that works # on only a few platforms was tuned more specifically for those # platforms. We remap 0 to a big number so that the sorting works # properly. aoslength = 0 aoslength = a[:metadata][:operatingsystem].length if a[:metadata][:operatingsystem] if aoslength == 0 # See comments above aoslength = 1000 end boslength = 0 boslength = b[:metadata][:operatingsystem].length if b[:metadata][:operatingsystem] if boslength == 0 boslength = 1000 end # Architecture # Same deal here, fewer architectures is better but zero is least desirable aarchlength = 0 aarchlength = a[:metadata][:architecture].length if a[:metadata][:architecture] if aarchlength == 0 aarchlength = 1000 end barchlength = 0 barchlength = b[:metadata][:architecture].length if b[:metadata][:architecture] if barchlength == 0 barchlength = 1000 end # Prefer a currently installed package over an otherwise identical # not installed package even if :prefer==false as a last deciding # factor. acurrentinstallnoprefer = 0 if a[:source] == :currently_installed || a[:source] == :native_installed acurrentinstallnoprefer = 1 end bcurrentinstallnoprefer = 0 if b[:source] == :currently_installed || b[:source] == :native_installed bcurrentinstallnoprefer = 1 end # # Then compare # # The mixture of a's and b's in these two arrays may seem odd at first, # but for some fields bigger is better (versions) but for other fields # smaller is better. [aname, bcurrentinstall, bversion, bpkgver, aoslength, aarchlength, bcurrentinstallnoprefer] <=> [bname, acurrentinstall, aversion, apkgver, boslength, barchlength, acurrentinstallnoprefer] end def self.files_in_package(package_file, options = {}) files = {:root => [], :reloc => []} # If the metadata_directory option is available, it means this package # has been installed and the file_metadata might be available in that directory. # If that's the case, then parse the file_metadata to get the file list. It's # much faster than extracting from the tar file if metadata_directory = options[:metadata_directory] package_name = File.basename(package_file, File.extname(package_file)) file_metadata = FileMetadata::instantiate_from_dir(File.join(metadata_directory, package_name)) end if file_metadata file_metadata[:files].each do |file| if file[:relocatable] files[:reloc] << file[:path] else files[:root] << file[:path] end end else file_lists = [] topleveldir = package_toplevel_directory(package_file) extract_tpkg_tar_cmd = cmd_to_extract_tpkg_tar(package_file, topleveldir) IO.popen("#{extract_tpkg_tar_cmd} | #{find_tar} #{@@taroptions} -tf -") do |pipe| pipe.each do |file| file_lists << file.chomp! end end if !$?.success? raise "Extracting file list from #{package_file} failed" end file_lists.each do |file| if file =~ Regexp.new(File.join('tpkg', 'root')) files[:root] << file.sub(Regexp.new(File.join('tpkg', 'root')), '') elsif file =~ Regexp.new(File.join('tpkg', 'reloc', '.')) files[:reloc] << file.sub(Regexp.new(File.join('tpkg', 'reloc', '')), '') end end end files end def self.lookup_uid(user) uid = nil if user =~ /^\d+$/ # If the user was specified as a numeric UID, use it directly. uid = user else # Otherwise attempt to look up the username to get a UID. # Default to UID 0 if the username can't be found. # TODO: Should we cache this info somewhere? begin pw = Etc.getpwnam(user) uid = pw.uid rescue ArgumentError puts "Package requests user #{user}, but that user can't be found. Using UID 0." uid = 0 end end uid.to_i end def self.lookup_gid(group) gid = nil if group =~ /^\d+$/ # If the group was specified as a numeric GID, use it directly. gid = group else # Otherwise attempt to look up the group to get a GID. Default # to GID 0 if the group can't be found. # TODO: Should we cache this info somewhere? begin gr = Etc.getgrnam(group) gid = gr.gid rescue ArgumentError puts "Package requests group #{group}, but that group can't be found. Using GID 0." gid = 0 end end gid.to_i end def self.gethttp(uri) if uri.scheme != 'http' && uri.scheme != 'https' # It would be possible to add support for FTP and possibly # other things if anyone cares raise "Only http/https URIs are supported, got: '#{uri}'" end http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == 'https' # Eliminate the OpenSSL "using default DH parameters" warning if File.exist?(File.join(CONFIGDIR, 'tpkg', 'dhparams')) dh = OpenSSL::PKey::DH.new(IO.read(File.join(CONFIGDIR, 'tpkg', 'dhparams'))) Net::HTTP.ssl_context_accessor(:tmp_dh_callback) http.tmp_dh_callback = proc { dh } end http.use_ssl = true if File.exist?(File.join(CONFIGDIR, 'tpkg', 'ca.pem')) http.ca_file = File.join(CONFIGDIR, 'tpkg', 'ca.pem') http.verify_mode = OpenSSL::SSL::VERIFY_PEER elsif File.directory?(File.join(CONFIGDIR, 'tpkg', 'ca')) http.ca_path = File.join(CONFIGDIR, 'tpkg', 'ca') http.verify_mode = OpenSSL::SSL::VERIFY_PEER end end http.start http end # foo # foo=1.0 # foo=1.0=1 # foo-1.0-1.tpkg def self.parse_request(request, installed_dir = nil) # FIXME: Add support for <, <=, >, >= req = {} parts = request.split('=') # upgrade/remove/query options could take package filenames # We're assuming that the filename ends in .tpkg and has a version number that starts # with a digit. For example: foo-1.0.tpkg, foo-bar-1.0-1.tpkg if request =~ /\.tpkg$/ req = {:filename => request, :name => request.split(/-\d/)[0]} elsif parts.length > 2 && parts[-2] =~ /^[\d\.]/ && parts[-1] =~ /^[\d\.]/ package_version = parts.pop version = parts.pop req[:name] = parts.join('-') req[:minimum_version] = version req[:maximum_version] = version req[:minimum_package_version] = package_version req[:maximum_package_version] = package_version elsif parts.length > 1 && parts[-1] =~ /^[\d\.]/ version = parts.pop req[:name] = parts.join('-') req[:minimum_version] = version req[:maximum_version] = version else req[:name] = parts.join('-') end req[:type] = :tpkg req end # deploy_options is used for configuration the deployer. It is a map of option_names => option_values. Possible # options are: use-ssh-key, deploy-as, worker-count, abort-on-fail # # deploy_params is an array that holds the list of paramters that is used when invoking tpkg on to the remote # servers where we want to deploy to. # # servers is an array, a filename or a callback that list the remote servers where we want to deploy to def self.deploy(deploy_params, deploy_options, servers) servers.uniq! deployer = Deployer.new(deploy_options) deployer.deploy(deploy_params, servers) end # Given a pid, check if it is running def self.process_running?(pid) return false if pid.nil? or pid == "" begin Process.kill(0, pid.to_i) rescue Errno::ESRCH return false rescue => e puts e return true end end # Prompt user to confirm yes or no. Default to yes if user just hit enter without any input. def self.confirm while true print "Confirm? [Y/n] " response = $stdin.gets if response =~ /^n/i return false elsif response =~ /^y|^\s$/i return true end end end def self.extract_tpkg_metadata_file(package_file) result = "" workdir = "" begin topleveldir = Tpkg::package_toplevel_directory(package_file) workdir = Tpkg::tempdir(topleveldir) extract_tpkg_tar_command = cmd_to_extract_tpkg_tar(package_file, topleveldir) system("#{extract_tpkg_tar_command} | #{find_tar} #{@@taroptions} -C #{workdir} -xpf -") if File.exist?(File.join(workdir,"tpkg", "tpkg.yml")) metadata_file = File.join(workdir,"tpkg", "tpkg.yml") elsif File.exist?(File.join(workdir,"tpkg", "tpkg.xml")) metadata_file = File.join(workdir,"tpkg", "tpkg.xml") else raise "#{package_file} does not contain metadata configuration file." end result = File.read(metadata_file) rescue puts "Failed to extract package." ensure FileUtils.rm_rf(workdir) if workdir end return result end # The only restriction right now is that the file doesn't begin with "." def self.valid_pkg_filename?(filename) return File.basename(filename) !~ /^\./ end # helper method for predicting the permissions and ownership of a file that # will be installed by tpkg. This is done by looking at: # 1) its current perms & ownership # 2) the file_defaults settings of the metadata file # 3) the explicitly defined settings in the corresponding file section of the metadata file def self.predict_file_perms_and_ownership(data) perms = uid = gid = nil # get current permission and ownership if data[:actual_file] stat = File.stat(data[:actual_file]) perms = stat.mode # This is what we set the ownership to by default uid = DEFAULT_OWNERSHIP_UID gid = DEFAULT_OWNERSHIP_UID end # get default permission and ownership metadata = data[:metadata] if (metadata && metadata[:files] && metadata[:files][:file_defaults] && metadata[:files][:file_defaults][:posix]) uid = Tpkg::lookup_uid(metadata[:files][:file_defaults][:posix][:owner]) if metadata[:files][:file_defaults][:posix][:owner] gid = Tpkg::lookup_gid(metadata[:files][:file_defaults][:posix][:group]) if metadata[:files][:file_defaults][:posix][:group] perms = metadata[:files][:file_defaults][:posix][:perms] if metadata[:files][:file_defaults][:posix][:perms] end # get explicitly defined permission and ownership file_metadata = data[:file_metadata] if file_metadata && file_metadata[:posix] uid = Tpkg::lookup_uid(file_metadata[:posix][:owner]) if file_metadata[:posix][:owner] gid = Tpkg::lookup_gid(file_metadata[:posix][:group]) if file_metadata[:posix][:group] perms = file_metadata[:posix][:perms] if file_metadata[:posix][:perms] end return perms, uid, gid end # Given a package file, figure out if tpkg.tar was compressed # Return what type of compression. If tpkg.tar wasn't compressed, then return nil. def self.get_compression(package_file) compression = nil IO.popen("#{find_tar} #{@@taroptions} -tf #{package_file}") do |pipe| pipe.each do |file| if file =~ /tpkg.tar.gz$/ compression = "gzip" elsif file =~ /tpkg.tar.bz2$/ compression = "bz2" end end end return compression end # Given a .tpkg file and the topleveldir, generate the command for # extracting tpkg.tar def self.cmd_to_extract_tpkg_tar(package_file, topleveldir) compression = get_compression(package_file) if compression == "gzip" cmd = "#{find_tar} #{@@taroptions} -xf #{package_file} -O #{File.join(topleveldir, 'tpkg.tar.gz')} | gunzip -c" elsif compression == "bz2" cmd = "#{find_tar} #{@@taroptions} -xf #{package_file} -O #{File.join(topleveldir, 'tpkg.tar.bz2')} | bunzip2 -c" else cmd = "#{find_tar} #{@@taroptions} -xf #{package_file} -O #{File.join(topleveldir, 'tpkg.tar')}" end end # Compresses the file using the compression type # specified by the compress flag # Returns the compressed file def self.compress_file(file, compress) if compress == true or compress == "gzip" result = "#{file}.gz" system("gzip #{file}") elsif compress == "bz2" result = "#{file}.bz2" system("bzip2 #{file}") else raise "Compression #{compress} is not supported" end if !$?.success? or !File.exists?(result) raise "Failed to compress the package" end return result end # Used where we wish to capture an exception and modify the message. This # method returns a new exception with desired message but with the backtrace # from the original exception so that the backtrace info is not lost. This # is necessary because Exception lacks a set_message method. def self.wrap_exception(e, message) eprime = e.exception(message) eprime.set_backtrace(e.backtrace) eprime end # # Instance methods # DEFAULT_BASE = '/opt/tpkg' def initialize(options) # Options @base = options[:base] # An array of filenames or URLs which point to individual package files # or directories containing packages and extracted metadata. @sources = [] if options[:sources] @sources = options[:sources] # Clean up any URI sources by ensuring they have a trailing slash # so that they are compatible with URI::join @sources.map! do |source| if !File.exist?(source) && source !~ %r{/$} source << '/' end source end end @report_server = nil if options[:report_server] @report_server = options[:report_server] end @lockforce = false if options.has_key?(:lockforce) @lockforce = options[:lockforce] end @force =false if options.has_key?(:force) @force = options[:force] end @sudo = true if options.has_key?(:sudo) @sudo = options[:sudo] end @file_system_root = '/' # Not sure if this needs to be more portable # This option is only intended for use by the test suite if options[:file_system_root] @file_system_root = options[:file_system_root] @base = File.join(@file_system_root, @base) end # Various external scripts that we run might need to adjust things for # relocatable packages based on the base directory. Set $TPKG_HOME so # those scripts know what base directory is being used. ENV['TPKG_HOME'] = @base # Other instance variables @metadata = {} @available_packages = {} @available_native_packages = {} @var_directory = File.join(@base, 'var', 'tpkg') if !File.exist?(@var_directory) begin FileUtils.mkdir_p(@var_directory) rescue Errno::EACCES raise if Process.euid == 0 rescue Errno::EIO => e if Tpkg::get_os =~ /Darwin/ # Try to help our Mac OS X users, otherwise this could be # rather confusing. warn "\nNote: /home is controlled by the automounter by default on Mac OS X.\n" + "You'll either need to disable that in /etc/auto_master or configure\n" + "tpkg to use a different base via tpkg.conf.\n" end raise e end end @installed_directory = File.join(@var_directory, 'installed') @metadata_directory = File.join(@installed_directory, 'metadata') @sources_directory = File.join(@var_directory, 'sources') @tmp_directory = File.join(@var_directory, 'tmp') @log_directory = File.join(@var_directory, 'logs') # It is important to create these dirs in correct order dirs_to_create = [@installed_directory, @metadata_directory, @sources_directory, @tmp_directory, @log_directory] dirs_to_create.each do |dir| if !File.exist?(dir) begin FileUtils.mkdir_p(dir) rescue Errno::EACCES raise if Process.euid == 0 end end end @tar = Tpkg::find_tar @external_directory = File.join(@file_system_root, 'usr', 'lib', 'tpkg', 'externals') @lock_directory = File.join(@var_directory, 'lock') @lock_pid_file = File.join(@lock_directory, 'pid') @locks = 0 @installed_metadata = {} @available_packages_cache = {} end attr_reader :base attr_reader :sources attr_reader :report_server attr_reader :lockforce attr_reader :force attr_reader :sudo attr_reader :file_system_root def source_to_local_directory(source) source_as_directory = source.gsub(/[^a-zA-Z0-9]/, '') File.join(@sources_directory, source_as_directory) end # One-time operations related to loading information about available # packages def prep_metadata if @metadata.empty? metadata = {} @sources.each do |source| if File.file?(source) metadata_yml = Tpkg::metadata_from_package(source) metadata_yml.source = source name = metadata_yml[:name] metadata[name] = [] if !metadata[name] metadata[name] << metadata_yml elsif File.directory?(source) if !File.exists?(File.join(source, 'metadata.yml')) warn "Warning: the source directory #{source} has no metadata.yml file. Try running tpkg -x #{source} first." next end metadata_contents = File.read(File.join(source, 'metadata.yml')) Metadata::get_pkgs_metadata_from_yml_doc(metadata_contents, metadata, source) else uri = http = localdate = remotedate = localdir = localpath = nil uri = URI.join(source, 'metadata.yml') http = Tpkg::gethttp(uri) # Calculate the path to the local copy of the metadata for this URI localdir = source_to_local_directory(source) localpath = File.join(localdir, 'metadata.yml') if File.exist?(localpath) localdate = File.mtime(localpath) end # get last modified time of the metadata file from the server response = http.head(uri.path) case response when Net::HTTPSuccess remotedate = Time.httpdate(response['Date']) else puts "Error fetching metadata from #{uri}: #{response.body}" response.error! # Throws an exception end # Fetch the metadata if necessary metadata_contents = nil if !localdate || remotedate != localdate response = http.get(uri.path) case response when Net::HTTPSuccess metadata_contents = response.body remotedate = Time.httpdate(response['Date']) # Attempt to save a local copy, might not work if we're not # running with sufficient privileges begin if !File.exist?(localdir) FileUtils.mkdir_p(localdir) end File.open(localpath, 'w') do |file| file.puts(response.body) end File.utime(remotedate, remotedate, localpath) rescue Errno::EACCES raise if Process.euid == 0 end else puts "Error fetching metadata from #{uri}: #{response.body}" response.error! # Throws an exception end else metadata_contents = IO.read(localpath) end # This method will parse the yml doc and populate the metadata variable # with list of pkgs' metadata Metadata::get_pkgs_metadata_from_yml_doc(metadata_contents, metadata, source) end end @metadata = metadata if @@debug @sources.each do |source| count = metadata.inject(0) do |memo,m| # metadata is a hash of pkgname => array of Metadata # objects. # Thus m is a 2 element array of [pkgname, array of # Metadata objects] And thus m[1] is the array of # Metadata objects. memo + m[1].select{|mo| mo.source == source}.length end puts "Found #{count} packages from #{source}" end end end end # Populate our list of available packages for a given package name def load_available_packages(name=nil) prep_metadata if name if !@available_packages[name] packages = [] if @metadata[name] @metadata[name].each do |metadata_obj| packages << { :metadata => metadata_obj, :source => metadata_obj.source } end end @available_packages[name] = packages if @@debug puts "Loaded #{@available_packages[name].size} available packages for #{name}" end end else # Load all packages @metadata.each do |pkgname, metadata_objs| if !@available_packages[pkgname] packages = [] metadata_objs.each do |metadata_obj| packages << { :metadata => metadata_obj, :source => metadata_obj.source } end @available_packages[pkgname] = packages end end end end # Used by load_available_native_packages to stuff all the info about a # native package into a hash to match the structure we pass around # internally for tpkgs def pkg_for_native_package(name, version, package_version, source) metadata = {} metadata[:name] = name metadata[:version] = version metadata[:package_version] = package_version if package_version pkg = { :metadata => metadata, :source => source } if source == :native_installed pkg[:prefer] = true end pkg end def load_available_native_packages(pkgname) if !@available_native_packages[pkgname] native_packages = [] if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ [ {:arg => 'installed', :header => 'Installed', :source => :native_installed}, {:arg => 'available', :header => 'Available', :source => :native_available} ].each do |yum| cmd = "yum info #{yum[:arg]} #{pkgname}" puts "available_native_packages running '#{cmd}'" if @@debug stderr_first_line = nil Open3.popen3(cmd) do |stdin, stdout, stderr| stdin.close read_packages = false name = version = package_version = nil stdout.each_line do |line| if line =~ /#{yum[:header]} Packages/ # Skip the header lines until we get to this line read_packages = true elsif read_packages if line =~ /^Name\s*:\s*(.+)/ name = $1.strip elsif line =~ /^Arch\s*:\s*(.+)/ arch = $1.strip elsif line =~ /^Version\s*:\s*(.+)/ version = $1.strip.to_s elsif line =~ /^Release\s*:\s*(.+)/ package_version = $1.strip.to_s elsif line =~ /^Repo\s*:\s*(.+)/ repo = $1.strip elsif line =~ /^\s*$/ pkg = pkg_for_native_package(name, version, package_version, yum[:source]) native_packages << pkg name = version = package_version = nil end # In the end we ignore the architecture. Anything that # shows up in yum should be installable on this box, and # the chance of a mismatch between facter's idea of the # architecture and RPM's idea is high. I.e. i386 vs i686 # or i32e vs x86_64 or whatever. end end stderr_first_line = stderr.gets end if !$?.success? # Ignore 'no matching packages', raise anything else if stderr_first_line != "Error: No matching Packages to list\n" raise "available_native_packages error running yum" end end end elsif Tpkg::get_os =~ /Debian|Ubuntu/ # The default 'dpkg -l' format has an optional third column for # errors, which makes it hard to parse reliably. puts "available_native_packages running dpkg-query -W -f='${Package} ${Version} ${Status}\n' #{pkgname}" if @@debug stderr_first_line = nil Open3.popen3("dpkg-query -W -f='${Package} ${Version} ${Status}\n' #{pkgname}") do |stdin, stdout, stderr| stdin.close stdout.each_line do |line| name, debversion, status = line.split(' ', 3) # Seems to be Debian convention that if the package has a # package version you seperate that from the upstream version # with a hyphen. version = nil package_version = nil if debversion =~ /-/ version, package_version = debversion.split('-', 2) else version = debversion end # We want packages with a state of "installed". However, # there's also a state of "not-installed", and the state # field contains several space-seperated values, so we have # to be somewhat careful to pick out "installed". if status.split(' ').include?('installed') pkg = pkg_for_native_package(name, version, package_version, :native_installed) native_packages << pkg end end stderr_first_line = stderr.gets end if !$?.success? # Ignore 'no matching packages', raise anything else if stderr_first_line !~ 'No packages found matching' raise "available_native_packages error running dpkg-query" end end puts "available_native_packages running 'apt-cache show #{pkgname}'" if @@debug IO.popen("apt-cache show #{pkgname}") do |pipe| name = nil version = nil package_version = nil pipe.each_line do |line| if line =~ /^Package: (.*)/ name = $1 version = nil package_version = nil elsif line =~ /^Version: (.*)/ debversion = $1 # Seems to be Debian convention that if the package has a # package version you seperate that from the upstream version # with a hyphen. if debversion =~ /-/ version, package_version = debversion.split('-', 2) else version = debversion end pkg = pkg_for_native_package(name, version, package_version, :native_available) native_packages << pkg end end end if !$?.success? raise "available_native_packages error running apt-cache" end elsif Tpkg::get_os =~ /Solaris/ # Example of pkginfo -x output: # SUNWzfsu ZFS (Usr) # (i386) 11.10.0,REV=2006.05.18.01.46 puts "available_native_packages running 'pkginfo -x #{pkgname}'" if @@debug IO.popen("pkginfo -x #{pkgname}") do |pipe| name = nil version = nil package_version = nil pipe.each_line do |line| if line =~ /^\w/ name = line.split(' ') version = nil package_version = nil else arch, solversion = line.split(' ') # Lots of Sun and some third party packages (including CSW) # seem to use this REV= convention in the version. I've # never seen it documented, but since it seems to be a # widely used convention we'll go with it. if solversion =~ /,REV=/ version, package_version = solversion.split(',REV=') else version = solversion end pkg = pkg_for_native_package(name, version, package_version, :native_installed) native_packages << pkg end end end if !$?.success? raise "available_native_packages error running pkginfo" end if File.exist?('/opt/csw/bin/pkg-get') puts "available_native_packages running '/opt/csw/bin/pkg-get -a'" if @@debug IO.popen('/opt/csw/bin/pkg-get -a') do |pipe| pipe.each_line do |line| next if line =~ /^#/ # Skip comments name, solversion = line.split # pkg-get doesn't have an option to only show available # packages matching a specific name, so we have to look over # all available packages and pick out the ones that match. next if name != pkgname # Lots of Sun and some third party packages (including CSW) # seem to use this REV= convention in the version. I've # never seen it documented, but since it seems to be a # widely used convention we'll go with it. version = nil package_version = nil if solversion =~ /,REV=/ version, package_version = solversion.split(',REV=') else version = solversion end pkg = pkg_for_native_package(name, version, package_version, :native_available) native_packages << pkg end end end elsif Tpkg::get_os =~ /FreeBSD/ puts "available_native_packages running 'pkg_info #{pkgname}'" if @@debug IO.popen("pkg_info #{pkgname}") do |pipe| pipe.each_line do |line| name_and_version = line.split(' ', 3) nameparts = name_and_version.split('-') fbversion = nameparts.pop name = nameparts.join('-') # Seems to be FreeBSD convention that if the package has a # package version you seperate that from the upstream version # with an underscore. version = nil package_version = nil if fbversion =~ /_/ version, package_version = fbversion.split('_', 2) else version = fbversion end pkg = pkg_for_native_package(name, version, package_version, :native_installed) package_version << pkg end end if !$?.success? raise "available_native_packages error running pkg_info" end # FIXME: FreeBSD available packages # We could either poke around in the ports tree (if installed), or # try to recreate the URL "pkg_add -r" would use and pull a # directory listing. elsif Tpkg::get_os =~ /Darwin/ if File.exist?('/opt/local/bin/port') puts "available_native_packages running '/opt/local/bin/port installed #{pkgname}'" if @@debug IO.popen("/opt/local/bin/port installed #{pkgname}") do |pipe| pipe.each_line do |line| next if line =~ /The following ports are currently installed/ next if line =~ /None of the specified ports are installed/ next if line !~ /\(active\)/ name, version = line.split(' ') version.sub!(/^@/, '') # Remove variant names version.sub!(/\+.*/, '') # Remove the _number that is always listed on installed ports, # presumably some sort of differentiator if multiple copies of # the same port version are installed. version.sub!(/_\d+$/, '') package_version = nil pkg = pkg_for_native_package(name, version, package_version, :native_installed) native_packages << pkg end end if !$?.success? raise "available_native_packages error running port" end puts "available_native_packages running '/opt/local/bin/port list #{pkgname}'" if @@debug IO.popen("/opt/local/bin/port list #{pkgname}") do |pipe| pipe.each_line do |line| name, version = line.split(' ') version.sub!(/^@/, '') package_version = nil pkg = pkg_for_native_package(name, version, package_version, :native_available) native_packages << pkg end end if !$?.success? raise "available_native_packages error running port" end else # Fink support would be nice raise "No supported native package tool available on #{Tpkg::get_os}" end else puts "Unknown value for OS: #{Tpkg::get_os}" end @available_native_packages[pkgname] = native_packages if @@debug nicount = native_packages.select{|pkg| pkg[:source] == :native_installed}.length nacount = native_packages.select{|pkg| pkg[:source] == :native_available}.length puts "Found #{nicount} installed native packages for #{pkgname}" puts "Found #{nacount} available native packages for #{pkgname}" end end end # Returns an array of metadata for installed packages def metadata_for_installed_packages metadata = {} if File.directory?(@installed_directory) Dir.foreach(@installed_directory) do |entry| next if entry == '.' || entry == '..' || entry == 'metadata' || !Tpkg::valid_pkg_filename?(entry) # Check the timestamp on the file to see if it is new or has # changed since we last loaded data timestamp = File.mtime(File.join(@installed_directory, entry)) if @installed_metadata[entry] && timestamp == @installed_metadata[entry][:timestamp] puts "Using cached installed metadata for #{entry}" if @@debug metadata[entry] = @installed_metadata[entry] else puts "Loading installed metadata from disk for #{entry}" if @@debug # Check to see if we already have a saved copy of the metadata # Originally tpkg just stored a copy of the package file in # @installed_directory and we had to extract the metadata # from the package file every time we needed it. That was # determined to be too slow, so we now cache a copy of the # metadata separately. However we may encounter installs by # old copies of tpkg and need to extract and cache the # metadata. package_metadata_dir = File.join(@metadata_directory, File.basename(entry, File.extname(entry))) metadata_file = File.join(package_metadata_dir, "tpkg.yml") m = Metadata::instantiate_from_dir(package_metadata_dir) # No cached metadata found, we have to extract it ourselves # and save it for next time if !m m = Tpkg::metadata_from_package( File.join(@installed_directory, entry)) begin FileUtils.mkdir_p(package_metadata_dir) File.open(metadata_file, "w") do |file| YAML::dump(m.to_hash, file) end rescue Errno::EACCES raise if Process.euid == 0 end end metadata[entry] = { :timestamp => timestamp, :metadata => m } unless m.nil? end end end @installed_metadata = metadata # FIXME: dup the array we return? @installed_metadata.collect { |im| im[1][:metadata] } end # Convert metadata_for_installed_packages into pkg hashes def installed_packages(pkgname=nil) instpkgs = [] metadata_for_installed_packages.each do |metadata| if !pkgname || metadata[:name] == pkgname instpkgs << { :metadata => metadata, :source => :currently_installed, # It seems reasonable for this to default to true :prefer => true } end end instpkgs end # Returns a hash of file_metadata for installed packages def file_metadata_for_installed_packages(package_files = nil) ret = {} if package_files package_files.collect!{|package_file| File.basename(package_file, File.extname(package_file))} end if File.directory?(@metadata_directory) Dir.foreach(@metadata_directory) do |entry| next if entry == '.' || entry == '..' next if package_files && !package_files.include?(entry) file_metadata = FileMetadata::instantiate_from_dir(File.join(@metadata_directory, entry)) ret[file_metadata[:package_file]] = file_metadata end end ret end # Returns an array of packages which meet the given requirement def available_packages_that_meet_requirement(req=nil) pkgs = nil puts "avail_pkgs_that_meet_req checking for #{req.inspect}" if @@debug if @available_packages_cache[req] puts "avail_pkgs_that_meet_req returning cached result" if @@debug pkgs = @available_packages_cache[req] else pkgs = [] if req req = req.clone # we're using req as the key for our cache, so it's important # that we clone it here. Otherwise, req can be changed later on from # the calling method and modify our cache inadvertently if req[:type] == :native load_available_native_packages(req[:name]) @available_native_packages[req[:name]].each do |pkg| if Tpkg::package_meets_requirement?(pkg, req) pkgs << pkg end end else load_available_packages(req[:name]) @available_packages[req[:name]].each do |pkg| if Tpkg::package_meets_requirement?(pkg, req) pkgs << pkg end end # There's a weird dicotomy here where @available_packages contains # available tpkg and native packages, and _installed_ native # packages, but not installed tpkgs. That's somewhat intentional, # as we don't want to cache the installed state since that might # change during a run. We probably should be consistent, and not # cache installed native packages either. However, we do have # some intelligent caching of the installed tpkg state which would # be hard to replicate for native packages, and this method gets # called a lot so re-running the native package query commands # frequently would not be acceptable. So maybe we have the right # design, and this just serves as a note that it is not obvious. pkgs.concat(installed_packages_that_meet_requirement(req)) end else # We return everything available if given a nil requirement # We do not include native packages load_available_packages # @available_packages is a hash of pkgname => array of pkgs # Thus m is a 2 element array of [pkgname, array of pkgs] # And thus m[1] is the array of packages pkgs = @available_packages.collect{|m| m[1]}.flatten end @available_packages_cache[req] = pkgs end pkgs end def installed_packages_that_meet_requirement(req=nil) pkgs = [] if req && req[:type] == :native load_available_native_packages(req[:name]) @available_native_packages[req[:name]].each do |pkg| if pkg[:source] == :native_installed && Tpkg::package_meets_requirement?(pkg, req) pkgs << pkg end end else pkgname = nil if req && req[:name] pkgname = req[:name] end # Passing a package name if we have one to installed_packages serves # primarily to make following the debugging output of dependency # resolution easier. The dependency resolution process makes frequent # calls to available_packages_that_meet_requirement, which in turn calls # this method. For available packages we're able to pre-filter based on # package name before calling package_meets_requirement? because we # store available packages hashed based on package name. # package_meets_requirement? is fairly verbose in its debugging output, # so the user sees each package it checks against a given requirement. # It is therefore a bit disconcerting when trying to follow the # debugging output to see the fairly clean process of checking available # packages which have already been filtered to match the desired name, # and then available_packages_that_meet_requirement calls this method, # and the user starts to see every installed package checked against the # same requirement. It is not obvious to the someone why all of a # sudden packages that aren't even remotely close to the requirement # start getting checked. Doing a pre-filter based on package name here # makes the process more consistent and easier to follow. installed_packages(pkgname).each do |pkg| if req if Tpkg::package_meets_requirement?(pkg, req) pkgs << pkg end else pkgs << pkg end end end pkgs end # Takes a files structure as returned by files_in_package. Inserts # a new entry in the structure with the combined relocatable and # non-relocatable file lists normalized to their full paths. def normalize_paths(files) files[:normalized] = [] files[:root].each do |rootfile| files[:normalized] << File.join(@file_system_root, rootfile) end files[:reloc].each do |relocfile| files[:normalized] << File.join(@base, relocfile) end end def normalize_path(path,root=nil,base=nil) root ||= @file_system_root base ||= @base if path[0,1] == File::SEPARATOR normalized_path = File.join(root, path) else normalized_path = File.join(base, path) end normalized_path end def files_for_installed_packages(package_files=nil) files = {} if !package_files package_files = [] metadata_for_installed_packages.each do |metadata| package_files << metadata[:filename] end end metadata_for_installed_packages.each do |metadata| package_file = metadata[:filename] if package_files.include?(package_file) fip = Tpkg::files_in_package(File.join(@installed_directory, package_file), {:metadata_directory => @metadata_directory}) normalize_paths(fip) fip[:metadata] = metadata files[package_file] = fip end end files end # Returns the best solution that meets the given requirements. Some or all # packages may be optionally pre-selected and specified via the packages # parameter, otherwise packages are picked from the set of available # packages. The requirements parameter is an array of package requirements. # The packages parameter is in the form of a hash with package names as keys # pointing to arrays of package specs (our standard hash of package metadata # and source). The core_packages parameter is an array of the names of # packages that should be considered core requirements, i.e. the user # specifically requested they be installed or upgraded. The return value # will be an array of package specs. MAX_POSSIBLE_SOLUTIONS_TO_CHECK = 10000 def best_solution(requirements, packages, core_packages) result = resolve_dependencies(requirements, {:tpkg => packages, :native => {}}, core_packages) if @@debug if result[:solution] puts "bestsol picks: #{result[:solution].inspect}" if @@debug else puts "bestsol checked #{result[:number_of_possible_solutions_checked]} possible solutions, none worked" end end result[:solution] end # Recursive method used by best_solution # Parameters mostly map from best_solution, but packages turns into a hash # with two possible keys, :tpkg and :native. The value for the :tpkg key # would be the packages parameter from best_solution. Native packages are # only installed due to dependencies, we don't let the user request them # directly, so callers of best_solution never need to pass in a package list # for native packages. Separating the two sets of packages allows us to # calculate a solution that contains both a tpkg and a native package with # the same name. This may be necessary if different dependencies of the # core packages end up needing both. def resolve_dependencies(requirements, packages, core_packages, number_of_possible_solutions_checked=0) # We're probably going to make changes to packages, dup it now so # that we don't mess up the caller's state. packages = {:tpkg => packages[:tpkg].dup, :native => packages[:native].dup} # Make sure we have populated package lists for all requirements. # Filter the package lists against the requirements and # ensure we can at least satisfy the initial requirements. requirements.each do |req| if !packages[req[:type]][req[:name]] puts "resolvedeps initializing packages for #{req.inspect}" if @@debug packages[req[:type]][req[:name]] = available_packages_that_meet_requirement(req) else # Loop over packages and eliminate ones that don't work for # this requirement puts "resolvedeps filtering packages for #{req.inspect}" if @@debug packages[req[:type]][req[:name]] = packages[req[:type]][req[:name]].select do |pkg| # When this method is called recursively there might be a # nil entry inserted into packages by the sorting code # below. We need to skip those. if pkg != nil Tpkg::package_meets_requirement?(pkg, req) end end end if packages[req[:type]][req[:name]].empty? if @@debug puts "No packages matching #{req.inspect}" end return {:number_of_possible_solutions_checked => number_of_possible_solutions_checked} end end # FIXME: Should we weed out any entries in packages that don't correspond # to something in requirements? We operate later on the assumption that # there are no such entries. Because we dup packages at the right points # I believe we'll never accidently end up with orphaned entries, but maybe # it would be worth the compute cycles to make sure? # Sort the packages [:tpkg, :native].each do |type| packages[type].each do |pkgname, pkgs| pkgs.sort!(&SORT_PACKAGES) # Only currently installed packages are allowed to score 0. # Anything else can score 1 at best. This ensures # that we prefer the solution which leaves the most # currently installed packages alone. if pkgs[0] && pkgs[0][:source] != :currently_installed && pkgs[0][:source] != :native_installed pkgs.unshift(nil) end end end if @@debug puts "Packages after initial population and filtering:" puts packages.inspect end # Here's an example of the possible solution sets we should come # up with and the proper ordering. Sets with identical averages # are equivalent, the order they appear in does not matter. # # packages: [a0, a1, a2], [b0, b1, b2], [c0, c1, c2] # core_packages: a, b # # [a0, b0, c0] (core avg 0) (avg 0) # [a0, b0, c1] (avg .33) # [a0, b0, c2] (avg .66) # [a0, b1, c0] (core avg .5) (avg .33) # [a1, b0, c0] # [a0, b1, c1] (avg .66) # [a1, b0, c1] # [a0, b1, c2] (avg 1) # [a1, b0, c2] # [a1, b1, c0] (core avg 1) (avg .66) # [a0, b2, c0] # [a2, b0, c0] # [a1, b1, c1] (avg 1) # [a0, b2, c1] # [a2, b0, c1] # [a1, b1, c2] (avg 1.33) # [a0, b2, c2] # [a2, b0, c2] # [a1, b2, c0] (core avg 1.5) (avg 1) # [a2, b1, c0] # [a1, b2, c1] (avg 1.33) # [a2, b1, c1] # [a1, b2, c2] (avg 1.67) # [a2, b1, c2] # [a2, b2, c0] (core avg 2) (avg 1.33) # [a2, b2, c1] (avg 1.67) # [a2, b2, c2] (avg 2) # Divide packages into core and non-core packages corepkgs = packages[:tpkg].reject{|pkgname, pkgs| !core_packages.include?(pkgname)} noncorepkgs = {} noncorepkgs[:tpkg] = packages[:tpkg].reject{|pkgname, pkgs| core_packages.include?(pkgname)} noncorepkgs[:native] = packages[:native] # Calculate total package depth, the sum of the lengths (or rather # the max array index) of each array of packages. coretotaldepth = corepkgs.inject(0) {|memo, pkgs| memo + pkgs[1].length - 1} noncoretotaldepth = noncorepkgs[:tpkg].inject(0) {|memo, pkgs| memo + pkgs[1].length - 1} + noncorepkgs[:native].inject(0) {|memo, pkgs| memo + pkgs[1].length - 1} if @@debug puts "resolvedeps coretotaldepth #{coretotaldepth}" puts "resolvedeps noncoretotaldepth #{noncoretotaldepth}" end # First pass, combinations of core packages (0..coretotaldepth).each do |coredepth| puts "resolvedeps checking coredepth: #{coredepth}" if @@debug core_solutions = [{:remaining_coredepth => coredepth, :pkgs => []}] corepkgs.each do |pkgname, pkgs| puts "resolvedeps corepkg #{pkgname}: #{pkgs.inspect}" if @@debug new_core_solutions = [] core_solutions.each do |core_solution| remaining_coredepth = core_solution[:remaining_coredepth] puts "resolvedeps :remaining_coredepth: #{remaining_coredepth}" if @@debug (0..[remaining_coredepth, pkgs.length-1].min).each do |corepkgdepth| puts "resolvedeps corepkgdepth: #{corepkgdepth}" if @@debug # We insert a nil entry in some situations (see the sort # step earlier), so skip nil entries in the pkgs array. if pkgs[corepkgdepth] != nil coresol = core_solution.dup # Hash#dup doesn't dup each key/value, so we need to # explicitly dup :pkgs so that each copy has an # independent array that we can modify. coresol[:pkgs] = core_solution[:pkgs].dup coresol[:remaining_coredepth] -= corepkgdepth coresol[:pkgs] << pkgs[corepkgdepth] new_core_solutions << coresol # If this is a complete combination of core packages then # proceed to the next step puts "resolvedeps coresol[:pkgs] #{coresol[:pkgs].inspect}" if @@debug if coresol[:pkgs].length == corepkgs.length puts "resolvedeps complete core pkg set: #{coresol.inspect}" if @@debug # Solutions with remaining depth are duplicates of # solutions we already checked at lower depth levels # I.e. at coredepth==0 we'd have: # {:pkgs=>{a0, b0}, :remaining_coredepth=0} # And at coredepth==1: # {:pkgs=>{a0,b0}, :remaining_coredepth=1} # Whereas at coredepth==1 this is new and needs to be checked: # {:pkgs=>{a1,b0}, :remaining_coredepth=0} if coresol[:remaining_coredepth] == 0 # Second pass, add combinations of non-core packages if noncorepkgs[:tpkg].empty? && noncorepkgs[:native].empty? puts "resolvedeps noncorepkgs empty, checking solution" if @@debug result = check_solution(coresol, requirements, packages, core_packages, number_of_possible_solutions_checked) if result[:solution] return result else number_of_possible_solutions_checked = result[:number_of_possible_solutions_checked] end else (0..noncoretotaldepth).each do |noncoredepth| puts "resolvedeps noncoredepth: #{noncoredepth}" if @@debug coresol[:remaining_noncoredepth] = noncoredepth solutions = [coresol] [:tpkg, :native].each do |nctype| noncorepkgs[nctype].each do |ncpkgname, ncpkgs| puts "resolvedeps noncorepkg #{nctype} #{ncpkgname}: #{ncpkgs.inspect}" if @@debug new_solutions = [] solutions.each do |solution| remaining_noncoredepth = solution[:remaining_noncoredepth] puts "resolvedeps :remaining_noncoredepth: #{remaining_noncoredepth}" if @@debug (0..[remaining_noncoredepth, ncpkgs.length-1].min).each do |ncpkgdepth| puts "resolvedeps ncpkgdepth: #{ncpkgdepth}" if @@debug # We insert a nil entry in some situations (see the sort # step earlier), so skip nil entries in the pkgs array. if ncpkgs[ncpkgdepth] != nil sol = solution.dup # Hash#dup doesn't dup each key/value, so we need to # explicitly dup :pkgs so that each copy has an # independent array that we can modify. sol[:pkgs] = solution[:pkgs].dup sol[:remaining_noncoredepth] -= ncpkgdepth sol[:pkgs] << ncpkgs[ncpkgdepth] new_solutions << sol # If this is a complete combination of packages then # proceed to the next step puts "resolvedeps sol[:pkgs] #{sol[:pkgs].inspect}" if @@debug if sol[:pkgs].length == packages[:tpkg].length + packages[:native].length puts "resolvedeps complete pkg set: #{sol.inspect}" if @@debug # Solutions with remaining depth are duplicates of # solutions we already checked at lower depth levels if sol[:remaining_noncoredepth] == 0 result = check_solution(sol, requirements, packages, core_packages, number_of_possible_solutions_checked) if result[:solution] puts "resolvdeps returning successful solution" if @@debug return result else number_of_possible_solutions_checked = result[:number_of_possible_solutions_checked] end end end end end end solutions = new_solutions end end end end end end end end end core_solutions = new_core_solutions end end # No solutions found puts "resolvedeps returning failure" if @@debug return {:number_of_possible_solutions_checked => number_of_possible_solutions_checked} end # Used by resolve_dependencies def check_solution(solution, requirements, packages, core_packages, number_of_possible_solutions_checked) number_of_possible_solutions_checked += 1 # Probably should give the user a way to override this if number_of_possible_solutions_checked > MAX_POSSIBLE_SOLUTIONS_TO_CHECK raise "Checked #{MAX_POSSIBLE_SOLUTIONS_TO_CHECK} possible solutions to requirements and dependencies, no solution found" end if @@debug puts "checksol checking sol #{solution.inspect}" end # Extract dependencies from each package in the solution newreqs = [] solution[:pkgs].each do |pkg| puts "checksol pkg #{pkg.inspect}" if @@debug if pkg[:metadata][:dependencies] pkg[:metadata][:dependencies].each do |depreq| if !requirements.include?(depreq) && !newreqs.include?(depreq) puts "checksol new depreq #{depreq.inspect}" if @@debug newreqs << depreq end end end end if newreqs.empty? # No additional requirements, this is a complete solution puts "checksol no newreqs, complete solution" if @@debug return {:solution => solution[:pkgs]} else newreqs_that_need_packages = [] newreqs.each do |newreq| puts "checksol checking newreq: #{newreq.inspect}" if @@debug if packages[newreq[:type]][newreq[:name]] pkg = solution[:pkgs].find{|solpkg| solpkg[:metadata][:name] == newreq[:name]} puts "checksol newreq pkg: #{pkg.inspect}" if @@debug if pkg && Tpkg::package_meets_requirement?(pkg, newreq) # No change to solution needed else # Solution no longer works puts "checksol solution no longer works" if @@debug return {:number_of_possible_solutions_checked => number_of_possible_solutions_checked} end else puts "checksol newreq needs packages" if @@debug newreqs_that_need_packages << newreq end end if newreqs_that_need_packages.empty? # None of the new requirements changed the solution, so the solution is complete puts "checksol no newreqs that need packages, complete solution" if @@debug return {:solution => solution[:pkgs]} else puts "checksol newreqs need packages, calling resolvedeps" if @@debug result = resolve_dependencies(requirements+newreqs_that_need_packages, packages, core_packages, number_of_possible_solutions_checked) if result[:solution] puts "checksol returning successful solution" if @@debug return result else number_of_possible_solutions_checked = result[:number_of_possible_solutions_checked] end end end puts "checksol returning failure" if @@debug return {:number_of_possible_solutions_checked => number_of_possible_solutions_checked} end def download(source, path, downloaddir = nil, use_cache = true) http = Tpkg::gethttp(URI.parse(source)) localdir = source_to_local_directory(source) localpath = File.join(localdir, File.basename(path)) # Don't download again if file is already there from previous installation # and still has valid checksum if File.file?(localpath) && use_cache begin Tpkg::verify_package_checksum(localpath) return localpath rescue RuntimeError, NoMethodError # Previous download is bad (which can happen for a variety of # reasons like an interrupted download or a bad package on the # server). Delete it and we'll try to grab it again. File.delete(localpath) end else # If downloaddir is specified, then download to that directory. Otherwise, # download to default source directory localdir = downloaddir || localdir if !File.exist?(localdir) FileUtils.mkdir_p(localdir) end localpath = File.join(localdir, File.basename(path)) end uri = URI.join(source, path) tmpfile = Tempfile.new(File.basename(localpath), File.dirname(localpath)) http.request_get(uri.path) do |response| # Package files can be quite large, so we transfer the package to a # local file in chunks response.read_body do |chunk| tmpfile.write(chunk) end remotedate = Time.httpdate(response['Date']) File.utime(remotedate, remotedate, tmpfile.path) end tmpfile.close begin Tpkg::verify_package_checksum(tmpfile.path) File.chmod(0644, tmpfile.path) File.rename(tmpfile.path, localpath) rescue raise "Unable to download and/or verify the package." end localpath end # Given a package's metadata return a hash of init scripts in the # package and the entry for that file from the metadata def init_scripts(metadata) init_scripts = {} # don't do anything unless we have to unless metadata[:files] && metadata[:files][:files] return init_scripts end metadata[:files][:files].each do |tpkgfile| if tpkgfile[:init] tpkg_path = tpkgfile[:path] installed_path = normalize_path(tpkg_path) init_scripts[installed_path] = tpkgfile end end init_scripts end # Given a package's metadata return a hash of init scripts in the # package and where they need to be linked to on the system def init_links(metadata) links = {} init_scripts(metadata).each do |installed_path, tpkgfile| # SysV-style init if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ || Tpkg::get_os =~ /Debian|Ubuntu/ || Tpkg::get_os =~ /Solaris/ start = '99' if tpkgfile[:init][:start] start = tpkgfile[:init][:start] end levels = nil if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ || Tpkg::get_os =~ /Debian|Ubuntu/ levels = ['2', '3', '4', '5'] elsif Tpkg::get_os =~ /Solaris/ levels = ['2', '3'] end if tpkgfile[:init][:levels] levels = tpkgfile[:init][:levels] end init_directory = nil if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ init_directory = File.join(@file_system_root, 'etc', 'rc.d') elsif Tpkg::get_os =~ /Debian|Ubuntu/ || Tpkg::get_os =~ /Solaris/ init_directory = File.join(@file_system_root, 'etc') end # in case user specify levels in yaml as string/integer instead of array if !levels.kind_of?(Array) levels = levels.to_s.split(//) end levels.each do |level| links[File.join(init_directory, "rc#{level}.d", 'S' + start.to_s + File.basename(installed_path))] = installed_path end elsif Tpkg::get_os =~ /FreeBSD/ init_directory = File.join(@file_system_root, 'usr', 'local', 'etc', 'rc.d') if tpkgfile[:init][:levels] && tpkgfile[:init][:levels].empty? # User doesn't want the init script linked in to auto-start else links[File.join(init_directory, File.basename(installed_path))] = installed_path end else warn "No init script support for #{Tpkg::get_os}" end end links end # Given a package's metadata return a hash of crontabs in the # package and where they need to be installed on the system def crontab_destinations(metadata) destinations = {} # Don't do anything unless we have to unless metadata[:files] && metadata[:files][:files] return destinations end metadata[:files][:files].each do |tpkgfile| if tpkgfile[:crontab] tpkg_path = tpkgfile[:path] installed_path = normalize_path(tpkg_path) destinations[installed_path] = {} # Decide whether we're going to add the file to a per-user # crontab or link it into a directory of misc. crontabs. If the # system only supports per-user crontabs we have to go the # per-user route. If the system supports both we decide based on # whether the package specifies a user for the crontab. # Systems that only support per-user style if Tpkg::get_os =~ /FreeBSD/ || Tpkg::get_os =~ /Solaris/ || Tpkg::get_os =~ /Darwin/ if tpkgfile[:crontab][:user] user = tpkgfile[:crontab][:user] if Tpkg::get_os =~ /FreeBSD/ destinations[installed_path][:file] = File.join(@file_system_root, 'var', 'cron', 'tabs', user) elsif Tpkg::get_os =~ /Solaris/ destinations[installed_path][:file] = File.join(@file_system_root, 'var', 'spool', 'cron', 'crontabs', user) elsif Tpkg::get_os =~ /Darwin/ destinations[installed_path][:file] = File.join(@file_system_root, 'usr', 'lib', 'cron', 'tabs', user) end else raise "No user specified for crontab in #{metadata[:filename]}" end # Systems that support cron.d style elsif Tpkg::get_os =~ /RedHat|CentOS|Fedora/ || Tpkg::get_os =~ /Debian|Ubuntu/ # If a user is specified go the per-user route if tpkgfile[:crontab][:user] user = tpkgfile[:crontab][:user] if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ destinations[installed_path][:file] = File.join(@file_system_root, 'var', 'spool', 'cron', user) elsif Tpkg::get_os =~ /Debian|Ubuntu/ destinations[installed_path][:file] = File.join(@file_system_root, 'var', 'spool', 'cron', 'crontabs', user) end # Otherwise go the cron.d route else destinations[installed_path][:link] = File.join(@file_system_root, 'etc', 'cron.d', File.basename(installed_path)) end else warn "No crontab support for #{Tpkg::get_os}" end end end destinations end def run_external(pkgfile, operation, name, data) externalpath = File.join(@external_directory, name) if !File.executable?(externalpath) raise "External #{externalpath} does not exist or is not executable" end case operation when :install begin IO.popen("#{externalpath} '#{pkgfile}' install", 'w') do |pipe| pipe.write(data) end if !$?.success? raise "Exit value #{$?.exitstatus}" end rescue => e # Tell the user which external and package were involved, otherwise # failures in externals are very hard to debug # FIXME: should we clean up the external request files? raise Tpkg.wrap_exception(e, "External #{name} #{operation} for #{File.basename(pkgfile)}: " + e.message) end when :remove begin IO.popen("#{externalpath} '#{pkgfile}' remove", 'w') do |pipe| pipe.write(data) end if !$?.success? raise "Exit value #{$?.exitstatus}" end rescue => e raise Tpkg.wrap_exception(e, "External #{name} #{operation} for #{File.basename(pkgfile)}: " + e.message) end else raise "Bug, unknown external operation #{operation}" end end # Unpack the files from a package into place, decrypt as necessary, set # permissions and ownership, etc. Does not check for conflicting # files or packages, etc. Those checks (if desired) must be done before # calling this method. def unpack(package_file, options={}) ret_val = 0 # set env variable to let pre/post install know whether this unpack # is part of an install or upgrade if options[:is_doing_upgrade] ENV['TPKG_ACTION'] = "upgrade" else ENV['TPKG_ACTION'] = "install" end # Unpack files in a temporary directory # I'd prefer to unpack on the fly so that the user doesn't need to # have disk space to hold three copies of the package (the package # file itself, this temporary unpack, and the final copy of the # files). However, I haven't figured out a way to get that to work, # since we need to strip several layers of directories out of the # directory structure in the package. topleveldir = Tpkg::package_toplevel_directory(package_file) workdir = Tpkg::tempdir(topleveldir, @tmp_directory) extract_tpkg_tar_cmd = Tpkg::cmd_to_extract_tpkg_tar(package_file, topleveldir) system("#{extract_tpkg_tar_cmd} | #{@tar} #{@@taroptions} -C #{workdir} -xpf -") files_info = {} # store perms, uid, gid, etc. for files checksums_of_decrypted_files = {} metadata = Tpkg::metadata_from_package(package_file, {:topleveldir => topleveldir}) # Get list of files/directories that already exist in the system. Store their perm/ownership. # That way, when we copy over the new files, we can set the new files to have the same perm/owernship. conflicting_files = {} fip = Tpkg::files_in_package(package_file) (fip[:root] | fip[:reloc]).each do |file| file_in_staging = normalize_path(file, File.join(workdir, 'tpkg', 'root'), File.join(workdir, 'tpkg', 'reloc')) file_in_system = normalize_path(file) if File.exists?(file_in_system) && !File.symlink?(file_in_system) conflicting_files[file] = {:normalized => file_in_staging, :stat => File.stat(file_in_system)} end end run_preinstall(package_file, workdir) run_externals_for_install(metadata, workdir, options[:externals_to_skip]) # Since we're stuck with unpacking to a temporary folder take # advantage of that to handle permissions, ownership and decryption # tasks before moving the files into their final location. # Handle any default permissions and ownership default_uid = DEFAULT_OWNERSHIP_UID default_gid = DEFAULT_OWNERSHIP_UID default_perms = nil if (metadata[:files][:file_defaults][:posix][:owner] rescue nil) default_uid = Tpkg::lookup_uid(metadata[:files][:file_defaults][:posix][:owner]) end if (metadata[:files][:file_defaults][:posix][:group] rescue nil) default_gid = Tpkg::lookup_gid(metadata[:files][:file_defaults][:posix][:group]) end if (metadata[:files][:file_defaults][:posix][:perms] rescue nil) default_perms = metadata[:files][:file_defaults][:posix][:perms] end # Set default dir uid/gid to be same as for file. default_dir_uid = default_uid default_dir_gid = default_gid default_dir_perms = 0755 if (metadata[:files][:dir_defaults][:posix][:owner] rescue nil) default_dir_uid = Tpkg::lookup_uid(metadata[:files][:dir_defaults][:posix][:owner]) end if (metadata[:files][:dir_defaults][:posix][:group] rescue nil) default_dir_gid = Tpkg::lookup_gid(metadata[:files][:dir_defaults][:posix][:group]) end if (metadata[:files][:dir_defaults][:posix][:perms] rescue nil) default_dir_perms = metadata[:files][:dir_defaults][:posix][:perms] end root_dir = File.join(workdir, 'tpkg', 'root') reloc_dir = File.join(workdir, 'tpkg', 'reloc') Find.find(root_dir, reloc_dir) do |f| # If the package doesn't contain either of the top level # directories we need to skip them, find will pass them to us # even if they don't exist. next if !File.exist?(f) begin if File.directory?(f) File.chown(default_dir_uid, default_dir_gid, f) else File.chown(default_uid, default_gid, f) end rescue Errno::EPERM raise if Process.euid == 0 end if File.file?(f) && !File.symlink?(f) if default_perms File.chmod(default_perms, f) end elsif File.directory?(f) && !File.symlink?(f) File.chmod(default_dir_perms, f) end end # Reset the permission/ownership of the conflicting files as how they were before. # This needs to be done after the default permission/ownership is applied, but before # the handling of ownership/permissions on specific files conflicting_files.each do | file, info | stat = info[:stat] file_path = info[:normalized] File.chmod(stat.mode, file_path) File.chown(stat.uid, stat.gid, file_path) end # Handle any decryption, ownership/permissions, and other issues for specific files metadata[:files][:files].each do |tpkgfile| tpkg_path = tpkgfile[:path] working_path = normalize_path(tpkg_path, File.join(workdir, 'tpkg', 'root'), File.join(workdir, 'tpkg', 'reloc')) if !File.exist?(working_path) && !File.symlink?(working_path) raise "tpkg.xml for #{File.basename(package_file)} references file #{tpkg_path} but that file is not in the package" end # Set permissions and ownership for specific files # We do this before the decryption stage so that permissions and # ownership designed to protect private file contents are in place # prior to decryption. The decrypt method preserves the permissions # and ownership of the encrypted file on the decrypted file. if tpkgfile[:posix] if tpkgfile[:posix][:owner] || tpkgfile[:posix][:group] uid = nil if tpkgfile[:posix][:owner] uid = Tpkg::lookup_uid(tpkgfile[:posix][:owner]) end gid = nil if tpkgfile[:posix][:group] gid = Tpkg::lookup_gid(tpkgfile[:posix][:group]) end begin File.chown(uid, gid, working_path) rescue Errno::EPERM raise if Process.euid == 0 end end if tpkgfile[:posix][:perms] perms = tpkgfile[:posix][:perms] File.chmod(perms, working_path) end end # Decrypt any files marked for decryption if tpkgfile[:encrypt] if !options[:passphrase] # If the user didn't supply a passphrase then just remove the # encrypted file. This allows users to install packages that # contain encrypted files for which they don't have the # passphrase. They end up with just the non-encrypted files, # potentially useful for development or QA environments. File.delete(working_path) else (1..3).each do | i | begin Tpkg::decrypt(metadata[:name], working_path, options[:passphrase], *([tpkgfile[:encrypt][:algorithm]].compact)) break rescue OpenSSL::CipherError @@passphrase = nil if i == 3 raise "Incorrect passphrase." else puts "Incorrect passphrase. Try again." end end end if File.file?(working_path) digest = Digest::SHA256.hexdigest(File.read(working_path)) # get checksum for the decrypted file. Will be used for creating file_metadata checksums_of_decrypted_files[File.expand_path(tpkg_path)] = digest end end end # If a conf file already exists on the file system, don't overwrite it. Rename # the new one with .tpkgnew file extension. if tpkgfile[:config] && conflicting_files[tpkgfile[:path]] FileUtils.mv(conflicting_files[tpkgfile[:path]][:normalized], "#{conflicting_files[tpkgfile[:path]][:normalized]}.tpkgnew") end end if metadata[:files] && metadata[:files][:files] # We should get the perms, gid, uid stuff here since all the files # have been set up correctly Find.find(root_dir, reloc_dir) do |f| # If the package doesn't contain either of the top level # directory we need to skip them, find will pass them to us # even if they don't exist. next if !File.exist?(f) next if File.symlink?(f) # check if it's from root dir or reloc dir if f =~ /^#{Regexp.escape(root_dir)}/ short_fn = f[root_dir.length ..-1] else short_fn = f[reloc_dir.length + 1..-1] relocatable = "true" end acl = {} acl["gid"] = File.stat(f).gid acl["uid"] = File.stat(f).uid acl["perms"] = File.stat(f).mode.to_s(8) files_info[short_fn] = acl end # Move files into place # If we implement any of the ACL permissions features we'll have to be # careful here that tar preserves those permissions. Otherwise we'll # need to apply them after moving the files into place. if File.directory?(File.join(workdir, 'tpkg', 'root')) system("#{@tar} -C #{File.join(workdir, 'tpkg', 'root')} -cf - . | #{@tar} -C #{@file_system_root} -xpf -") end if File.directory?(File.join(workdir, 'tpkg', 'reloc')) system("#{@tar} -C #{File.join(workdir, 'tpkg', 'reloc')} -cf - . | #{@tar} -C #{@base} -xpf -") end install_init_scripts(metadata) install_crontabs(metadata) ret_val = run_postinstall(package_file, workdir) save_package_metadata(package_file, workdir, metadata, files_info, checksums_of_decrypted_files) # Copy the package file to the directory for installed packages FileUtils.cp(package_file, @installed_directory) # Cleanup FileUtils.rm_rf(workdir) return ret_val end def install_init_scripts(metadata) init_links(metadata).each do |link, init_script| # We don't have to do anything if there's already symlink to our init # script. This can happen if the user removes a package manually without # removing the init symlink next if File.symlink?(link) && File.readlink(link) == init_script begin if !File.exist?(File.dirname(link)) FileUtils.mkdir_p(File.dirname(link)) end begin File.symlink(init_script, link) rescue Errno::EEXIST # The link name that init_links provides is not guaranteed to # be unique. It might collide with a base system init script # or an init script from another tpkg. If the link name # supplied by init_links results in EEXIST then try appending # a number to the end of the link name. catch :init_link_done do 1.upto(9) do |i| begin File.symlink(init_script, link + i.to_s) throw :init_link_done rescue Errno::EEXIST end end # If we get here (i.e. we never reached the throw) then we # failed to create any of the possible link names. raise "Failed to install init script #{init_script} -> #{link} for #{File.basename(metadata[:filename].to_s)}, too many overlapping filenames" end end # EACCES for file/directory permissions issues rescue Errno::EACCES => e # If creating the link fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to install init script for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end end end end def remove_init_scripts(metadata) init_links(metadata).each do |link, init_script| # The link we ended up making when we unpacked the package could be any # of a series (see the code in install_init_scripts for the reasoning), # we need to check them all. links = [link] links.concat((1..9).to_a.map { |i| link + i.to_s }) links.each do |l| if File.symlink?(l) && File.readlink(l) == init_script begin File.delete(l) # EACCES for file/directory permissions issues rescue Errno::EACCES => e # If removing the link fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to remove init script for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end end end end end end def install_crontabs(metadata) crontab_destinations(metadata).each do |crontab, destination| # FIXME: Besides the regex being ugly it is also only going to match on # Linux, need to figure out if there's a reason for that or if this can # be made more generic. if !@sudo && (destination[destination.keys.first] =~ /\/var\/spool\/cron/) install_crontab_bycmd(metadata, crontab, destination) next end begin if destination[:link] install_crontab_link(metadata, crontab, destination) elsif destination[:file] install_crontab_file(metadata, crontab, destination) end # EACCES for file/directory permissions issues rescue Errno::EACCES => e # If installing the crontab fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to install crontab for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end rescue RuntimeError => e if e.message.include?('cannot generate tempfile') && Process.euid != 0 warn "Failed to install crontab for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end end end end def install_crontab_link(metadata, crontab, destination) return if File.symlink?(destination[:link]) && File.readlink(destination[:link]) == crontab if !File.exist?(File.dirname(destination[:link])) FileUtils.mkdir_p(File.dirname(destination[:link])) end begin File.symlink(crontab, destination[:link]) rescue Errno::EEXIST # The link name that crontab_destinations provides is not # guaranteed to be unique. It might collide with a base # system crontab or a crontab from another tpkg. If the # link name supplied by crontab_destinations results in # EEXIST then try appending a number to the end of the link # name. catch :crontab_link_done do 1.upto(9) do |i| begin File.symlink(crontab, destination[:link] + i.to_s) throw :crontab_link_done rescue Errno::EEXIST end end # If we get here (i.e. we never reached the throw) then we # failed to create any of the possible link names. raise "Failed to install crontab #{crontab} -> #{destination[:link]} for #{File.basename(metadata[:filename].to_s)}, too many overlapping filenames" end end end # FIXME: Can this be replaced by install_crontab_bycmd? def install_crontab_file(metadata, crontab, destination) if !File.exist?(File.dirname(destination[:file])) FileUtils.mkdir_p(File.dirname(destination[:file])) end tmpfile = Tempfile.new(File.basename(destination[:file]), File.dirname(destination[:file])) if File.exist?(destination[:file]) # Match permissions and ownership of current crontab st = File.stat(destination[:file]) begin File.chmod(st.mode & 07777, tmpfile.path) File.chown(st.uid, st.gid, tmpfile.path) # EPERM for attempts to chown/chmod as non-root user rescue Errno::EPERM => e # If installing the crontab fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to install crontab for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end end # Insert the contents of the current crontab file File.open(destination[:file]) { |file| tmpfile.write(file.read) } end # Insert a header line so we can find this section to remove later tmpfile.puts "### TPKG START - #{@base} - #{File.basename(metadata[:filename].to_s)}" # Insert the package crontab contents crontab_contents = IO.read(crontab) tmpfile.write(crontab_contents) # Insert a newline if the crontab doesn't end with one if crontab_contents.chomp == crontab_contents tmpfile.puts end # Insert a footer line tmpfile.puts "### TPKG END - #{@base} - #{File.basename(metadata[:filename].to_s)}" tmpfile.close File.rename(tmpfile.path, destination[:file]) # FIXME: On Solaris we should bounce cron or use the crontab # command, otherwise cron won't pick up the changes end def install_crontab_bycmd(metadata, crontab, destination) oldcron = `crontab -l` tmpf = '/tmp/tpkg_cron.' + rand.to_s tmpfh = File.open(tmpf,'w') tmpfh.write(oldcron) unless oldcron.empty? tmpfh.puts "### TPKG START - #{@base} - #{File.basename(metadata[:filename].to_s)}" tmpfh.write File.readlines(crontab) tmpfh.puts "### TPKG END - #{@base} - #{File.basename(metadata[:filename].to_s)}" tmpfh.close `crontab #{tmpf}` FileUtils.rm(tmpf) end def remove_crontabs(metadata) crontab_destinations(metadata).each do |crontab, destination| # FIXME: Besides the regex being ugly it is also only going to match on # Linux, need to figure out if there's a reason for that or if this can # be made more generic. if !@sudo && (destination[destination.keys.first] =~ /\/var\/spool\/cron/) remove_crontab_bycmd(metadata, crontab, destination) next end begin if destination[:link] remove_crontab_link(metadata, crontab, destination) elsif destination[:file] remove_crontab_file(metadata, crontab, destination) end # EACCES for file/directory permissions issues rescue Errno::EACCES => e # If removing the crontab fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to remove crontab for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise e end end end end def remove_crontab_link(metadata, crontab, destination) # The link we ended up making when we unpacked the package could # be any of a series (see the code in unpack for the reasoning), # we need to check them all. links = [destination[:link]] links.concat((1..9).to_a.map { |i| destination[:link] + i.to_s }) links.each do |l| if File.symlink?(l) && File.readlink(l) == crontab File.delete(l) end end end # FIXME: Can this be replaced by remove_crontab_bycmd? def remove_crontab_file(metadata, crontab, destination) if File.exist?(destination[:file]) tmpfile = Tempfile.new(File.basename(destination[:file]), File.dirname(destination[:file])) # Match permissions and ownership of current crontab st = File.stat(destination[:file]) begin File.chmod(st.mode & 07777, tmpfile.path) File.chown(st.uid, st.gid, tmpfile.path) # EPERM for attempts to chown/chmod as non-root user rescue Errno::EPERM => e # If installing the crontab fails due to permission problems and # we're not running as root just warn the user, allowing folks # to run tpkg as a non-root user with reduced functionality. if Process.euid != 0 warn "Failed to install crontab for #{File.basename(metadata[:filename].to_s)}, probably due to lack of root privileges: #{e.message}" else raise end end # Remove section associated with this package skip = false IO.foreach(destination[:file]) do |line| if line == "### TPKG START - #{@base} - #{File.basename(metadata[:filename].to_s)}\n" skip = true elsif line == "### TPKG END - #{@base} - #{File.basename(metadata[:filename].to_s)}\n" skip = false elsif !skip tmpfile.write(line) end end tmpfile.close File.rename(tmpfile.path, destination[:file]) # FIXME: On Solaris we should bounce cron or use the crontab # command, otherwise cron won't pick up the changes end end def remove_crontab_bycmd(metadata, crontab, destination) oldcron = `crontab -l` tmpf = '/tmp/tpkg_cron.' + rand.to_s tmpfh = File.open(tmpf,'w') skip = false oldcron.each do |line| if line == "### TPKG START - #{@base} - #{File.basename(metadata[:filename].to_s)}\n" skip = true elsif line == "### TPKG END - #{@base} - #{File.basename(metadata[:filename].to_s)}\n" skip = false elsif !skip tmpfh.write(line) end end tmpfh.close `crontab #{tmpf}` FileUtils.rm(tmpf) end def run_preinstall(package_file, workdir) if File.exist?(File.join(workdir, 'tpkg', 'preinstall')) pwd = Dir.pwd # chdir into the working directory so that the user can specify # relative paths to other files in the package. Dir.chdir(File.join(workdir, 'tpkg')) begin # Warn the user about non-executable files, as system will just # silently fail and exit if that's the case. if !File.executable?(File.join(workdir, 'tpkg', 'preinstall')) warn "Warning: preinstall script for #{File.basename(package_file)} is not executable, execution will likely fail" end if @force system(File.join(workdir, 'tpkg', 'preinstall')) || warn("Warning: preinstall for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") else system(File.join(workdir, 'tpkg', 'preinstall')) || raise("Error: preinstall for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") end ensure # Switch back to our previous directory Dir.chdir(pwd) end end end def run_postinstall(package_file, workdir) r = 0 if File.exist?(File.join(workdir, 'tpkg', 'postinstall')) pwd = Dir.pwd # chdir into the working directory so that the user can specify # relative paths to other files in the package. Dir.chdir(File.join(workdir, 'tpkg')) begin # Warn the user about non-executable files, as system will just # silently fail and exit if that's the case. if !File.executable?(File.join(workdir, 'tpkg', 'postinstall')) warn "Warning: postinstall script for #{File.basename(package_file)} is not executable, execution will likely fail" end # Note this only warns the user if the postinstall fails, it does # not raise an exception like we do if preinstall fails. Raising # an exception would leave the package's files installed but the # package not registered as installed, which does not seem # desirable. We could remove the package's files and raise an # exception, but this seems the best approach to me. system(File.join(workdir, 'tpkg', 'postinstall')) if !$?.success? warn("Warning: postinstall for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") r = POSTINSTALL_ERR end ensure # Switch back to our previous directory Dir.chdir(pwd) end end r end def run_externals_for_install(metadata, workdir, externals_to_skip=[]) metadata[:externals].each do |external| if !externals_to_skip || !externals_to_skip.include?(external) # If the external references a datafile or datascript then read/run it # now that we've unpacked the package contents and have the file/script # available. This will get us the data for the external. if external[:datafile] || external[:datascript] pwd = Dir.pwd # chdir into the working directory so that the user can specify a # relative path to their file/script. Dir.chdir(File.join(workdir, 'tpkg')) begin if external[:datafile] # Read the file external[:data] = IO.read(external[:datafile]) # Drop the datafile key so that we don't waste time re-reading the # datafile again in the future. external.delete(:datafile) elsif external[:datascript] # Run the script IO.popen(external[:datascript]) do |pipe| external[:data] = pipe.read end if !$?.success? raise "Datascript #{external[:datascript]} for package #{File.basename(metadata[:filename])} had exit value #{$?.exitstatus}" end # Drop the datascript key so that we don't waste time re-running the # datascript again in the future. external.delete(:datascript) end ensure # Switch back to our previous directory Dir.chdir(pwd) end end run_external(metadata[:filename], :install, external[:name], external[:data]) end end if metadata[:externals] end def save_package_metadata(package_file, workdir, metadata, files_info, checksums_of_decrypted_files) # Save metadata for this pkg package_name = File.basename(package_file, File.extname(package_file)) package_metadata_dir = File.join(@metadata_directory, package_name) FileUtils.mkdir_p(package_metadata_dir) metadata.write(package_metadata_dir) # Save file_metadata for this pkg file_metadata = FileMetadata::instantiate_from_dir(File.join(workdir, 'tpkg')) if file_metadata file_metadata[:package_file] = File.basename(package_file) file_metadata[:files].each do |file| # update file_metadata with user/group ownership and permission acl = files_info[file[:path]] file.merge!(acl) unless acl.nil? # update file_metadata with the checksums of decrypted files digest = checksums_of_decrypted_files[File.expand_path(file[:path])] if digest digests = file[:checksum][:digests] digests[0][:encrypted] = true digests[1] = {:decrypted => true, :value => digest} end end file = File.open(File.join(package_metadata_dir, "file_metadata.bin"), "w") Marshal.dump(file_metadata.to_hash, file) file.close else warn "Warning: package #{File.basename(package_file)} does not include file_metadata information." end end def requirements_for_currently_installed_package(pkgname=nil) requirements = [] metadata_for_installed_packages.each do |metadata| if !pkgname || pkgname == metadata[:name] req = { :name => metadata[:name], :minimum_version => metadata[:version], :type => :tpkg } if metadata[:package_version] req[:minimum_package_version] = metadata[:package_version] end requirements << req end end requirements end # Adds/modifies requirements and packages arguments to add requirements # and package entries for currently installed packages # Note: the requirements and packages arguments are modified by this method def requirements_for_currently_installed_packages(requirements, packages) metadata_for_installed_packages.each do |installed_xml| name = installed_xml[:name] version = installed_xml[:version] # For each currently installed package we insert a requirement for # at least that version of the package req = { :name => name, :minimum_version => version, :type => :tpkg } requirements << req # Initialize the list of possible packages for this req if !packages[name] packages[name] = available_packages_that_meet_requirement(req) end end end # Define requirements for requested packages # Takes an array of packages: files, URLs, or basic package specs ('foo' or # 'foo=1.0') # Adds/modifies requirements and packages arguments based on parsing those # requests # Input: # [ 'foo-1.0.tpkg', 'http://server/pkgs/bar-2.3.pkg', 'blat=0.5' ] # Result: # requirements << { :name => 'foo' }, packages['foo'] = { :source => 'foo-1.0.tpkg' } # requirements << { :name => 'bar' }, packages['bar'] = { :source => 'http://server/pkgs/bar-2.3.pkg' } # requirements << { :name => 'blat', :minimum_version => '0.5', :maximum_version => '0.5' }, packages['blat'] populated with available packages meeting that requirement # Note: the requirements and packages arguments are modified by this method def parse_requests(requests, requirements, packages) newreqs = [] requests.each do |request| puts "parse_requests processing #{request.inspect}" if @@debug # User specified a file or URI if request =~ /^http[s]?:\/\// or File.file?(request) req = {} metadata = nil source = nil localpath = nil if File.file?(request) raise "Invalid package filename #{request}" if !Tpkg::valid_pkg_filename?(request) puts "parse_requests treating request as a file" if @@debug if request !~ /\.tpkg$/ warn "Warning: Attempting to perform the request on #{File.expand_path(request)}. This might not be a valid package file." end localpath = request metadata = Tpkg::metadata_from_package(request) source = request else puts "parse_requests treating request as a URI" if @@debug uri = URI.parse(request) # This just serves as a sanity check # Using these File methods on a URI seems to work but is probably fragile source = File.dirname(request) + '/' # dirname chops off the / at the end, we need it in order to be compatible with URI.join pkgfile = File.basename(request) localpath = download(source, pkgfile, Tpkg::tempdir('download')) metadata = Tpkg::metadata_from_package(localpath) # Cleanup temp download dir FileUtils.rm_rf(localpath) end req[:name] = metadata[:name] req[:type] = :tpkg pkg = { :metadata => metadata, :source => source } newreqs << req # The user specified a particular package, so it is the only package # that can be used to meet the requirement packages[req[:name]] = [pkg] else # basic package specs ('foo' or 'foo=1.0') puts "parse_requests request looks like package spec" if @@debug # Tpkg::parse_request is a class method and doesn't know where packages are installed. # So we have to tell it ourselves. req = Tpkg::parse_request(request, @installed_directory) newreqs << req puts "Initializing the list of possible packages for this req" if @@debug if !packages[req[:name]] packages[req[:name]] = available_packages_that_meet_requirement(req) end end end requirements.concat(newreqs) newreqs end # After calling parse_request, we should call this method # to check whether or not we can meet the requirements/dependencies # of the result packages def check_requests(packages) all_requests_satisfied = true # whether or not all requests can be satisfied errors = [""] packages.each do |name, pkgs| if pkgs.empty? errors << ["Unable to find any packages which satisfy #{name}"] all_requests_satisfied = false next end request_satisfied = false # whether or not this request can be satisfied possible_errors = [] pkgs.each do |pkg| good_package = true metadata = pkg[:metadata] req = { :name => metadata[:name], :type => :tpkg } # Quick sanity check that the package can be installed on this machine. puts "check_requests checking that available package for request works on this machine: #{pkg.inspect}" if @@debug if !Tpkg::package_meets_requirement?(pkg, req) possible_errors << " Requested package #{metadata[:filename]} doesn't match this machine's OS or architecture" good_package = false next end # a sanity check that there is at least one package # available for each dependency of this package metadata[:dependencies].each do |depreq| puts "check_requests checking for available packages to satisfy dependency: #{depreq.inspect}" if @@debug if available_packages_that_meet_requirement(depreq).empty? && !Tpkg::packages_meet_requirement?(packages.values.flatten, depreq) possible_errors << " Requested package #{metadata[:filename]} depends on #{depreq.inspect}, no packages that satisfy that dependency are available" good_package = false end end if metadata[:dependencies] request_satisfied = true if good_package end if !request_satisfied errors << ["Unable to find any packages which satisfy #{name}. Possible error(s):"] errors << possible_errors all_requests_satisfied = false end end if !all_requests_satisfied puts errors.join("\n") raise "Unable to satisfy the request(s). Try running with --debug for more info" end end CHECK_INSTALL = 1 CHECK_UPGRADE = 2 CHECK_REMOVE = 3 def conflicting_files(package_file, mode=CHECK_INSTALL) metadata = Tpkg::metadata_from_package(package_file) pkgname = metadata[:name] conflicts = {} installed_files = files_for_installed_packages # Pull out the normalized paths, skipping appropriate packages based # on the requested mode installed_files_normalized = {} installed_files.each do |pkgfile, files| # Skip packages with the same name if the user is performing an upgrade if mode == CHECK_UPGRADE && files[:metadata][:name] == pkgname next end # Skip packages with the same filename if the user is removing if mode == CHECK_REMOVE && pkgfile == File.basename(package_file) next end installed_files_normalized[pkgfile] = files[:normalized] end fip = Tpkg::files_in_package(package_file) normalize_paths(fip) fip[:normalized].each do |file| installed_files_normalized.each do |instpkgfile, files| if files.include?(file) if !conflicts[instpkgfile] conflicts[instpkgfile] = [] end conflicts[instpkgfile] << file end end end # The remove method actually needs !conflicts, so invert in that case if mode == CHECK_REMOVE # Flatten conflicts to an array flatconflicts = [] conflicts.each_value { |files| flatconflicts.concat(files) } # And invert conflicts = fip[:normalized] - flatconflicts end conflicts end # This method is called by install and upgrade method to make sure there is # no conflicts between the existing pkgs and the pkgs we're about to install def handle_conflicting_pkgs(installed_pkgs, pkgs_to_install, options ={}) conflicting_pkgs = [] # check if existing pkgs have conflicts with pkgs we're about to install installed_pkgs.each do |pkg1| next if pkg1[:metadata][:conflicts].nil? pkg1[:metadata][:conflicts].each do | conflict | pkgs_to_install.each do |pkg2| if Tpkg::package_meets_requirement?(pkg2, conflict) conflicting_pkgs << pkg1 end end end end # check if pkgs we're about to install conflict with existing pkgs pkgs_to_install.each do |pkg1| next if pkg1[:metadata][:conflicts].nil? pkg1[:metadata][:conflicts].each do | conflict | conflicting_pkgs |= installed_packages_that_meet_requirement(conflict) end end # Check if there are conflicts among the pkgs we're about to install # For these type of conflicts, we can't proceed, so raise exception. pkgs_to_install.each do |pkg1| # native package might not have conflicts defined so skip next if pkg1[:metadata][:conflicts].nil? pkg1[:metadata][:conflicts].each do | conflict | pkgs_to_install.each do |pkg2| if Tpkg::package_meets_requirement?(pkg2, conflict) raise "Package conflicts between #{pkg2[:metadata][:filename]} and #{pkg1[:metadata][:filename]}" end end end end # Report to the users if there are conflicts unless conflicting_pkgs.empty? puts "The package(s) you're trying to install conflict with the following package(s):" conflicting_pkgs = conflicting_pkgs.collect{|pkg|pkg[:metadata][:filename]} puts conflicting_pkgs.join("\n") if options[:force_replace] puts "Attemping to replace the conflicting packages." success = remove(conflicting_pkgs) return success else puts "Try removing the conflicting package(s) first, or rerun tpkg with the --force-replace option." return false end end return true end def prompt_for_conflicting_files(package_file, mode=CHECK_INSTALL) if !@@prompt return true end result = true conflicts = conflicting_files(package_file, mode) # We don't want to prompt the user for directories, so strip those out conflicts.each do |pkgfile, files| files.reject! { |file| File.directory?(file) } end conflicts.reject! { |pkgfile, files| files.empty? } if !conflicts.empty? puts "File conflicts:" conflicts.each do |pkgfile, files| files.each do |file| puts "#{file} (#{pkgfile})" end end print "Proceed? [y/N] " response = $stdin.gets if response !~ /^y/i result = false end end result end def prompt_for_install(pkgs, promptstring) if @@prompt pkgs_to_report = pkgs.select do |pkg| pkg[:source] != :currently_installed && pkg[:source] != :native_installed end if !pkgs_to_report.empty? puts "The following packages will be #{promptstring}:" pkgs_to_report.sort(&SORT_PACKAGES).each do |pkg| if pkg[:source] == :native_available name = pkg[:metadata][:name] version = pkg[:metadata][:version] package_version = pkg[:metadata][:package_version] pkgname = "#{name}-#{version}" if package_version pkgname << "-#{package_version}" end puts "Native #{pkgname}" else puts pkg[:metadata][:filename] end end return Tpkg::confirm end end true end # See parse_requests for format of requests def install(requests, passphrase=nil, options={}) ret_val = 0 requirements = [] packages = {} lock parse_requests(requests, requirements, packages) check_requests(packages) core_packages = [] requirements.each do |req| core_packages << req[:name] if !core_packages.include?(req[:name]) end puts "install calling best_solution" if @@debug puts "install requirements: #{requirements.inspect}" if @@debug puts "install packages: #{packages.inspect}" if @@debug puts "install core_packages: #{core_packages.inspect}" if @@debug solution_packages = best_solution(requirements, packages, core_packages) if !solution_packages raise "Unable to resolve dependencies. Try running with --debug for more info" end success = handle_conflicting_pkgs(installed_packages, solution_packages, options) return false if !success if !prompt_for_install(solution_packages, 'installed') unlock return false end # Build an array of metadata of pkgs that are already installed # We will use this later on to figure out what new packages have been installed/removed # in order to report back to the server already_installed_pkgs = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} # Create array of packages (names) we have installed so far # We will use it later on to determine the order of how to install the packages installed_so_far = installed_packages.collect{|pkg| pkg[:metadata][:name]} while pkg = solution_packages.shift # get dependencies and make sure we install the packages in the correct order # based on the dependencies dependencies = nil if pkg[:metadata][:dependencies] dependencies = pkg[:metadata][:dependencies].collect { |dep| dep[:name] }.compact # don't install this pkg right now if its dependencies haven't been installed if !dependencies.empty? && !dependencies.to_set.subset?(installed_so_far.to_set) solution_packages.push(pkg) next end end if pkg[:source] == :currently_installed || pkg[:source] == :native_installed # Nothing to do for packages currently installed warn "Skipping #{pkg[:metadata][:name]}, already installed" elsif pkg[:source] == :native_available if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] package_version = pkg[:metadata][:package_version] # RPMs always have a release/package_version pkgname = "#{name}-#{version}-#{package_version}" puts "Running 'yum -y install #{pkgname}' to install native package" if @@debug system("yum -y install #{pkgname}") elsif Tpkg::get_os =~ /Debian|Ubuntu/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << "-#{pkg[:metadata][:package_version]}" end puts "Running 'apt-get -y install #{pkgname}' to install native package" if @@debug system("apt-get -y install #{pkgname}") elsif Tpkg::get_os =~ /Solaris/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << ",REV=#{pkg[:metadata][:package_version]}" end if File.exist?('/opt/csw/bin/pkg-get') puts "Running '/opt/csw/bin/pkg-get -i #{pkgname}' to install native package" if @@debug system("/opt/csw/bin/pkg-get -i #{pkgname}") else raise "No native package installation tool available" end elsif Tpkg::get_os =~ /FreeBSD/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << "_#{pkg[:metadata][:package_version]}" end puts "Running 'pkg_add -r #{pkgname}' to install native package" if @@debug system("pkg_add -r #{pkgname}") elsif Tpkg::get_os =~ /Darwin/ if File.exist?('/opt/local/bin/port') name = pkg[:metadata][:name] # MacPorts doesn't support installing a specific version (AFAIK) if pkg[:metadata][:version] warn "Ignoring version with MacPorts" end # Nor does it have a concept of a package version if pkg[:metadata][:package_version] warn "Ignoring package version with MacPorts" end # Just for consistency with the code for other platforms pkgname = name puts "Running '/opt/local/bin/port install #{pkgname}' to install native package" if @@debug system("/opt/local/bin/port install #{pkgname}") else # Fink support would be nice raise "No supported native package tool available on #{Tpkg::get_os}" end else raise "No native package installation support for #{Tpkg::get_os}" end else # regular tpkg that needs to be installed pkgfile = nil if File.file?(pkg[:source]) pkgfile = pkg[:source] elsif File.directory?(pkg[:source]) pkgfile = File.join(pkg[:source], pkg[:metadata][:filename]) else pkgfile = download(pkg[:source], pkg[:metadata][:filename]) end if File.exist?( File.join(@installed_directory, File.basename(pkgfile))) warn "Skipping #{File.basename(pkgfile)}, already installed" else if prompt_for_conflicting_files(pkgfile) ret_val |= unpack(pkgfile, :passphrase => passphrase) # create and install stubbed native package if needed stub_native_pkg(pkg) end end end # If we're down here, it means we have installed the package. So go ahead and # update the list of packages we installed so far installed_so_far << pkg[:metadata][:name] end # end while loop # log changes currently_installed = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} newly_installed = currently_installed - already_installed_pkgs log_changes({:newly_installed => newly_installed}) # send udpate back to reporting server unless @report_server.nil? options = {:newly_installed => newly_installed, :currently_installed => currently_installed} send_update_to_server(options) end unlock return ret_val end # This method can also be used for doing downgrade def upgrade(requests=nil, passphrase=nil, options={}) downgrade = options[:downgrade] || false ret_val = 0 requirements = [] packages = {} core_packages = [] lock has_updates = false # flags whether or not there was at least one actual package that # get updated # If the user specified some specific packages to upgrade in requests # then we look for upgrades for just those packages (and any necessary # dependency upgrades). If the user did not specify specific packages # then we look for upgrades for all currently installed packages. if requests puts "Upgrading requested packages only" if @@debug parse_requests(requests, requirements, packages) check_requests(packages) additional_requirements = [] requirements.each do |req| core_packages << req[:name] if !core_packages.include?(req[:name]) # When doing downgrade, we don't want to include the package being # downgrade as the requirements. Otherwise, we won't be able to downgrade it unless downgrade additional_requirements.concat( requirements_for_currently_installed_package(req[:name])) end # Initialize the list of possible packages for this req if !packages[req[:name]] packages[req[:name]] = available_packages_that_meet_requirement(req) end # Remove preference for currently installed package packages[req[:name]].each do |pkg| if pkg[:source] == :currently_installed pkg[:prefer] = false end end # Look for pkgs that might depend on the pkg we're upgrading, # and add them to our list of requirements. We need to make sure that we can still # satisfy the dependency requirements if we were to do the upgrade. metadata_for_installed_packages.each do | metadata | metadata[:dependencies].each do | dep | if dep[:name] == req[:name] # Package metadata is almost usable as-is as a req, just need to # set :type # and remove filename (since we're not explicitly requesting the exact file) addreq = metadata.to_hash.clone addreq[:type] = :tpkg addreq[:filename] = nil additional_requirements << addreq end end if metadata[:dependencies] end end requirements.concat(additional_requirements) requirements.uniq! else puts "Upgrading all packages" if @@debug requirements_for_currently_installed_packages(requirements, packages) # Remove preference for currently installed packages packages.each do |name, pkgs| core_packages << name if !core_packages.include?(name) pkgs.each do |pkg| if pkg[:source] == :currently_installed pkg[:prefer] = false end end end end puts "upgrade calling best_solution" if @@debug puts "upgrade requirements: #{requirements.inspect}" if @@debug puts "upgrade packages: #{packages.inspect}" if @@debug puts "upgrade core_packages: #{core_packages.inspect}" if @@debug solution_packages = best_solution(requirements, packages, core_packages) if solution_packages.nil? raise "Unable to find solution for upgrading. Please verify that you specified the correct package(s) for upgrade. Try running with --debug for more info" end success = handle_conflicting_pkgs(installed_packages, solution_packages, options) return false if !success if downgrade prompt_action = 'downgraded' else prompt_action = 'upgraded' end if !prompt_for_install(solution_packages, prompt_action) unlock return false end # Build an array of metadata of pkgs that are already installed # We will use this later on to figure out what new packages have been installed/removed # in order to report back to the server already_installed_pkgs = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} removed_pkgs = [] # keep track of what we removed so far while pkg = solution_packages.shift if pkg[:source] == :currently_installed || pkg[:source] == :native_installed # Nothing to do for packages currently installed elsif pkg[:source] == :native_available if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] package_version = pkg[:metadata][:package_version] # RPMs always have a release/package_version pkgname = "#{name}-#{version}-#{package_version}" puts "Running 'yum -y install #{pkgname}' to upgrade native package" if @@debug system("yum -y install #{pkgname}") has_updates = true elsif Tpkg::get_os =~ /Debian|Ubuntu/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << "-#{pkg[:metadata][:package_version]}" end puts "Running 'apt-get -y install #{pkgname}' to upgrade native package" if @@debug system("apt-get -y install #{pkgname}") has_updates = true elsif Tpkg::get_os =~ /Solaris/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << ",REV=#{pkg[:metadata][:package_version]}" end if File.exist?('/opt/csw/bin/pkg-get') puts "Running '/opt/csw/bin/pkg-get -i #{pkgname}' to upgrade native package" if @@debug system("/opt/csw/bin/pkg-get -i #{pkgname}") has_updates = true else raise "No native package upgrade tool available" end elsif Tpkg::get_os =~ /FreeBSD/ name = pkg[:metadata][:name] version = pkg[:metadata][:version] pkgname = "#{name}-#{version}" if pkg[:metadata][:package_version] pkgname << "_#{pkg[:metadata][:package_version]}" end # This is not very ideal. It would be better to download the # new package, and if the download is successful remove the # old package and install the new one. The way we're doing it # here we risk leaving the system with neither version # installed if the download of the new package fails. # However, the FreeBSD package tools don't make it easy to # handle things properly. puts "Running 'pkg_delete #{name}' and 'pkg_add -r #{pkgname}' to upgrade native package" if @@debug system("pkg_delete #{name}") system("pkg_add -r #{pkgname}") has_updates = true elsif Tpkg::get_os =~ /Darwin/ if File.exist?('/opt/local/bin/port') name = pkg[:metadata][:name] # MacPorts doesn't support installing a specific version (AFAIK) if pkg[:metadata][:version] warn "Ignoring version with MacPorts" end # Nor does it have a concept of a package version if pkg[:metadata][:package_version] warn "Ignoring package version with MacPorts" end # Just for consistency with the code for other platforms pkgname = name puts "Running '/opt/local/bin/port upgrade #{pkgname}' to upgrade native package" if @@debug system("/opt/local/bin/port upgrade #{pkgname}") else # Fink support would be nice raise "No supported native package tool available on #{Tpkg::get_os}" end else raise "No native package upgrade support for #{Tpkg::get_os}" end else # tpkg pkgfile = nil if File.file?(pkg[:source]) pkgfile = pkg[:source] elsif File.directory?(pkg[:source]) pkgfile = File.join(pkg[:source], pkg[:metadata][:filename]) else pkgfile = download(pkg[:source], pkg[:metadata][:filename]) end if !Tpkg::valid_pkg_filename?(pkgfile) raise "Invalid package filename: #{pkgfile}" end if prompt_for_conflicting_files(pkgfile, CHECK_UPGRADE) # If the old and new packages have overlapping externals flag them # to be skipped so that the external isn't removed and then # immediately re-added oldpkgs = installed_packages_that_meet_requirement({:name => pkg[:metadata][:name], :type => :tpkg}) externals_to_skip = [] pkg[:metadata][:externals].each do |external| if oldpkgs.all? {|oldpkg| oldpkg[:metadata][:externals] && oldpkg[:metadata][:externals].include?(external)} externals_to_skip << external end end if pkg[:metadata][:externals] # Remove the old package if we haven't done so unless oldpkgs.nil? or oldpkgs.empty? or removed_pkgs.include?(pkg[:metadata][:name]) remove([pkg[:metadata][:name]], :upgrade => true, :externals_to_skip => externals_to_skip) removed_pkgs << pkg[:metadata][:name] end # determine if we can unpack the new version package now by # looking to see if all of its dependencies have been installed can_unpack = true pkg[:metadata][:dependencies].each do | dep | iptmr = installed_packages_that_meet_requirement(dep) if iptmr.nil? || iptmr.empty? can_unpack = false # Can't unpack yet. so push it back in the solution_packages queue solution_packages.push(pkg) break end end if pkg[:metadata][:dependencies] if can_unpack is_doing_upgrade = true if removed_pkgs.include?(pkg[:metadata][:name]) ret_val |= unpack(pkgfile, :passphrase => passphrase, :externals_to_skip => externals_to_skip, :is_doing_upgrade => is_doing_upgrade) # create and install stubbed native package if needed stub_native_pkg(pkg) end has_updates = true end end end # log changes currently_installed = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} newly_installed = currently_installed - already_installed_pkgs removed = already_installed_pkgs - currently_installed log_changes({:newly_installed => newly_installed, :removed => removed}) # send update back to reporting server if !has_updates puts "No updates available" elsif !@report_server.nil? options = {:newly_installed => newly_installed, :removed => removed, :currently_installed => currently_installed} send_update_to_server(options) end unlock return ret_val end def remove(requests=nil, options={}) ret_val = 0 lock packages_to_remove = nil if requests requests.uniq! if requests.is_a?(Array) packages_to_remove = [] requests.each do |request| req = Tpkg::parse_request(request, @installed_directory) packages_to_remove.concat(installed_packages_that_meet_requirement(req)) end else packages_to_remove = installed_packages_that_meet_requirement end if packages_to_remove.empty? puts "No matching packages" unlock return false end # Build an array of metadata of pkgs that are already installed # We will use this later on to figure out what new packages have been installed/removed # in order to report back to the server already_installed_pkgs = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} # If user want to remove all the dependent pkgs, then go ahead # and include them in our array of things to remove if options[:remove_all_dep] packages_to_remove |= get_dependents(packages_to_remove) elsif options[:remove_all_prereq] puts "Attempting to remove #{packages_to_remove.map do |pkg| pkg[:metadata][:filename] end} and all prerequisites." # Get list of dependency prerequisites ptr = packages_to_remove | get_prerequisites(packages_to_remove) pkg_files_to_remove = ptr.map { |pkg| pkg[:metadata][:filename] } # see if any other packages depends on the ones we're about to remove # If so, we can't remove that package + any of its prerequisites non_removable_pkg_files = [] metadata_for_installed_packages.each do |metadata| next if pkg_files_to_remove.include?(metadata[:filename]) next if metadata[:dependencies].nil? metadata[:dependencies].each do |req| # We ignore native dependencies because there is no way a removal # can break a native dependency, we don't support removing native # packages. if req[:type] != :native iptmr = installed_packages_that_meet_requirement(req) if iptmr.all? { |pkg| pkg_files_to_remove.include?(pkg[:metadata][:filename]) } non_removable_pkg_files |= iptmr.map{ |pkg| pkg[:metadata][:filename]} non_removable_pkg_files |= get_prerequisites(iptmr).map{ |pkg| pkg[:metadata][:filename]} end end end end # Generate final list of packages that we should remove. packages_to_remove = {} ptr.each do | pkg | next if pkg[:source] == :native or pkg[:source] == :native_installed next if non_removable_pkg_files.include?(pkg[:metadata][:filename]) packages_to_remove[pkg[:metadata][:filename]] = pkg end packages_to_remove = packages_to_remove.values if packages_to_remove.empty? raise "Can't remove request package because other packages depend on it." elsif !non_removable_pkg_files.empty? puts "Can't remove #{non_removable_pkg_files.inspect} because other packages depend on them." end # Check that this doesn't leave any dependencies unresolved elsif !options[:upgrade] pkg_files_to_remove = packages_to_remove.map { |pkg| pkg[:metadata][:filename] } metadata_for_installed_packages.each do |metadata| next if pkg_files_to_remove.include?(metadata[:filename]) next if metadata[:dependencies].nil? metadata[:dependencies].each do |req| # We ignore native dependencies because there is no way a removal # can break a native dependency, we don't support removing native # packages. # FIXME: Should we also consider :native_installed? if req[:type] != :native if installed_packages_that_meet_requirement(req).all? { |pkg| pkg_files_to_remove.include?(pkg[:metadata][:filename]) } raise "Package #{metadata[:filename]} depends on #{req[:name]}" end end end end end # Confirm with the user # upgrade does its own prompting if @@prompt && !options[:upgrade] puts "The following packages will be removed:" packages_to_remove.each do |pkg| puts pkg[:metadata][:filename] end unless Tpkg::confirm unlock return false end end # Stop the services if there's init script if !options[:upgrade] packages_to_remove.each do |pkg| init_scripts_metadata = init_scripts(pkg[:metadata]) if init_scripts_metadata && !init_scripts_metadata.empty? execute_init_for_package(pkg, 'stop') end end end # Remove the packages packages_to_remove.each do |pkg| pkgname = pkg[:metadata][:name] package_file = File.join(@installed_directory, pkg[:metadata][:filename]) topleveldir = Tpkg::package_toplevel_directory(package_file) workdir = Tpkg::tempdir(topleveldir, @tmp_directory) extract_tpkg_tar_command = Tpkg::cmd_to_extract_tpkg_tar(package_file, topleveldir) system("#{extract_tpkg_tar_command} | #{@tar} #{@@taroptions} -C #{workdir} -xpf -") # Run preremove script if File.exist?(File.join(workdir, 'tpkg', 'preremove')) pwd = Dir.pwd # chdir into the working directory so that the user can specify a # relative path to their file/script. Dir.chdir(File.join(workdir, 'tpkg')) # Warn the user about non-executable files, as system will just # silently fail and exit if that's the case. if !File.executable?(File.join(workdir, 'tpkg', 'preremove')) warn "Warning: preremove script for #{File.basename(package_file)} is not executable, execution will likely fail" end if @force system(File.join(workdir, 'tpkg', 'preremove')) || warn("Warning: preremove for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") else system(File.join(workdir, 'tpkg', 'preremove')) || raise("Error: preremove for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") end # Switch back to our previous directory Dir.chdir(pwd) end remove_init_scripts(pkg[:metadata]) remove_crontabs(pkg[:metadata]) # Run any externals pkg[:metadata][:externals].each do |external| if !options[:externals_to_skip] || !options[:externals_to_skip].include?(external) run_external(pkg[:metadata][:filename], :remove, external[:name], external[:data]) end end if pkg[:metadata][:externals] # determine which configuration files have been modified modified_conf_files = [] file_metadata = file_metadata_for_installed_packages([pkg[:metadata][:filename]]).values[0] file_metadata[:files].each do |file| if file[:config] # get expected checksum. For files that were encrypted, we're interested in the # checksum of the decrypted version chksum_expected = file[:checksum][:digests].first[:value] file[:checksum][:digests].each do | digest | if digest[:decrypted] == true chksum_expected = digest[:value].to_s end end fp = normalize_path(file[:path]) chksum_actual = Digest::SHA256.hexdigest(File.read(fp)) if chksum_actual != chksum_expected modified_conf_files << fp end end end if file_metadata # Remove files files_to_remove = conflicting_files(package_file, CHECK_REMOVE) # Reverse the order of the files, as directories will appear first # in the listing but we want to remove any files in them before # trying to remove the directory. files_to_remove.reverse.each do |file| # don't remove conf files that have been modified next if modified_conf_files.include?(file) begin if !File.directory?(file) File.delete(file) else begin Dir.delete(file) rescue SystemCallError => e # Directory isn't empty #puts e.message end end rescue Errno::ENOENT warn "File #{file} from package #{File.basename(package_file)} missing during remove" # I know it's bad to have a generic rescue for all exceptions, but in this case, there # can be many things that might go wrong when removing a file. We don't want tpkg # to crash and leave the packages in a bad state. It's better to catch # all exceptions and give the user some warnings. rescue warn "Failed to remove file #{file}." end end # Run postremove script if File.exist?(File.join(workdir, 'tpkg', 'postremove')) pwd = Dir.pwd # chdir into the working directory so that the user can specify a # relative path to their file/script. Dir.chdir(File.join(workdir, 'tpkg')) # Warn the user about non-executable files, as system will just # silently fail and exit if that's the case. if !File.executable?(File.join(workdir, 'tpkg', 'postremove')) warn "Warning: postremove script for #{File.basename(package_file)} is not executable, execution will likely fail" end # Note this only warns the user if the postremove fails, it does # not raise an exception like we do if preremove fails. Raising # an exception would leave the package's files removed but the # package still registered as installed, which does not seem # desirable. We could reinstall the package's files and raise an # exception, but this seems the best approach to me. system(File.join(workdir, 'tpkg', 'postremove')) || warn("Warning: postremove for #{File.basename(package_file)} failed with exit value #{$?.exitstatus}") ret_val = POSTREMOVE_ERR if !$?.success? # Switch back to our previous directory Dir.chdir(pwd) end File.delete(package_file) # delete metadata dir of this package package_metadata_dir = File.join(@metadata_directory, File.basename(package_file, File.extname(package_file))) FileUtils.rm_rf(package_metadata_dir) # remove native dependency stub packages if needed remove_native_stub_pkg(pkg) # Cleanup FileUtils.rm_rf(workdir) end # log changes currently_installed = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} removed = already_installed_pkgs - currently_installed log_changes({:removed => removed}) # send update back to reporting server unless @report_server.nil? || options[:upgrade] options = {:removed => removed, :currently_installed => currently_installed} send_update_to_server(options) end unlock return ret_val end def verify_file_metadata(requests) results = {} packages = [] # parse request to determine what packages the user wants to verify requests.each do |request| req = Tpkg::parse_request(request) packages.concat(installed_packages_that_meet_requirement(req).collect { |pkg| pkg[:metadata][:filename] }) end # loop through each package, and verify checksum, owner, group and perm of each file that was installed packages.each do | package_file | puts "Verifying #{package_file}" package_full_name = File.basename(package_file, File.extname(package_file)) # Extract checksum.xml from the package checksum_xml = nil # get file_metadata from the installed package file_metadata = FileMetadata::instantiate_from_dir(File.join(@metadata_directory, package_full_name)) if !file_metadata errors = [] errors << "Can't find file metadata. Most likely this is because the package was created before the verify feature was added" results[package_file] = errors return results end # verify installed files match their checksum file_metadata[:files].each do |file| errors = [] gid_expected, uid_expected, perms_expected, chksum_expected = nil fp = file[:path] # get expected checksum. For files that were encrypted, we're interested in the # checksum of the decrypted version if file[:checksum] chksum_expected = file[:checksum][:digests].first[:value] file[:checksum][:digests].each do | digest | if digest[:decrypted] == true chksum_expected = digest[:value].to_s end end end # get expected acl values if file[:uid] uid_expected = file[:uid].to_i end if file[:gid] gid_expected = file[:gid].to_i end if file[:perms] perms_expected = file[:perms].to_s end fp = normalize_path(fp) # can't handle symlink if File.symlink?(fp) next end # check if file exist if !File.exists?(fp) errors << "File is missing" else # get actual values chksum_actual = Digest::SHA256.hexdigest(File.read(fp)) if File.file?(fp) uid_actual = File.stat(fp).uid gid_actual = File.stat(fp).gid perms_actual = File.stat(fp).mode.to_s(8) end if !chksum_expected.nil? && !chksum_actual.nil? && chksum_expected != chksum_actual errors << "Checksum doesn't match (Expected: #{chksum_expected}, Actual: #{chksum_actual}" end if !uid_expected.nil? && !uid_actual.nil? && uid_expected != uid_actual errors << "uid doesn't match (Expected: #{uid_expected}, Actual: #{uid_actual}) " end if !gid_expected.nil? && !gid_actual.nil? && gid_expected != gid_actual errors << "gid doesn't match (Expected: #{gid_expected}, Actual: #{gid_actual})" end if !perms_expected.nil? && !perms_actual.nil? && perms_expected != perms_actual errors << "perms doesn't match (Expected: #{perms_expected}, Actual: #{perms_actual})" end results[fp] = errors end end return results end def execute_init(options, *moreoptions) ret_val = 0 packages_to_execute_on = [] if options.is_a?(Hash) action = options[:cmd] requested_packages = options[:packages] requested_init_scripts = options[:scripts] else # for backward compatibility action = moreoptions[0] requested_packages = options end # if user specified no packages, then assume all if requested_packages.nil? packages_to_execute_on = installed_packages_that_meet_requirement(nil) else requested_packages.uniq! requested_packages.each do |request| req = Tpkg::parse_request(request) packages_to_execute_on.concat(installed_packages_that_meet_requirement(req)) end end if packages_to_execute_on.empty? warn "Warning: Unable to find package(s) \"#{requested_packages.join(",")}\"." else packages_to_execute_on.each do |pkg| ret_val |= execute_init_for_package(pkg, action, requested_init_scripts) end end return ret_val end def execute_init_for_package(pkg, action, requested_init_scripts = nil) ret_val = 0 # Get init scripts metadata for the given package init_scripts_metadata = init_scripts(pkg[:metadata]) # warn if there's no init script and then return if init_scripts_metadata.nil? || init_scripts_metadata.empty? warn "Warning: There is no init script for #{pkg[:metadata][:name]}." return 1 end # convert the init scripts metadata to an array of { path => value, start => value} # so that we can order them based on their start value. This is necessary because # we need to execute the init scripts in correct order. init_scripts = [] init_scripts_metadata.each do | installed_path, init_info | init = {} init[:path] = installed_path init[:start] = init_info[:init][:start] || 0 # if user requests specific init scripts, then only include those if requested_init_scripts.nil? or requested_init_scripts && requested_init_scripts.include?(File.basename(installed_path)) init_scripts << init end end if requested_init_scripts && init_scripts.empty? warn "Warning: There are no init scripts that satisfy your request: #{requested_init_scripts.inspect} for package #{pkg[:metadata][:name]}." end # Reverse order if doing stop. if action == "stop" ordered_init_scripts = init_scripts.sort{ |a,b| b[:start] <=> a[:start] } else ordered_init_scripts = init_scripts.sort{ |a,b| a[:start] <=> b[:start] } end ordered_init_scripts.each do |init_script| installed_path = init_script[:path] system("#{installed_path} #{action}") ret_val = INITSCRIPT_ERR if !$?.success? end return ret_val end # We can't safely calculate a set of dependencies and install the # resulting set of packages if another user is manipulating the installed # packages at the same time. These methods lock and unlock the package # system so that only one user makes changes at a time. def lock if @locks > 0 @locks += 1 return end if File.directory?(@lock_directory) if @lockforce warn "Forcing lock removal" FileUtils.rm_rf(@lock_directory) else # Remove old lock files on the assumption that they were left behind # by a previous failed run if File.mtime(@lock_directory) < Time.at(Time.now - 60 * 60 * 2) warn "Lock is more than 2 hours old, removing" FileUtils.rm_rf(@lock_directory) end end end begin Dir.mkdir(@lock_directory) File.open(@lock_pid_file, 'w') { |file| file.puts($$) } @locks = 1 rescue Errno::EEXIST lockpid = '' begin File.open(@lock_pid_file) { |file| lockpid = file.gets.chomp } rescue Errno::ENOENT end # check that the process is actually running # if not, clean up old lock and attemp to obtain lock again if Tpkg::process_running?(lockpid) raise "tpkg repository locked by another process (with PID #{lockpid})" else FileUtils.rm_rf(@lock_directory) lock end end end def unlock if @locks == 0 warn "unlock called but not locked, that probably shouldn't happen" return end @locks -= 1 if @locks == 0 FileUtils.rm_rf(@lock_directory) end end # Build a dependency map of currently installed packages # For example, if we have pkgB and pkgC which depends on pkgA, then # the dependency map would look like this: # "pkgA.tpkg" => [{pkgB metadata}, {pkgC metadata}] def get_dependency_mapping dependency_mapping = {} installed_packages.each do | pkg | metadata = pkg[:metadata] # Get list of pkgs that this pkg depends on next if metadata[:dependencies].nil? depended_on = [] metadata[:dependencies].each do |req| next if req[:type] == :native depended_on |= installed_packages_that_meet_requirement(req) end # populate the depencency map depended_on.each do | req_pkg | dependency_mapping[req_pkg[:metadata][:filename]] ||= [] dependency_mapping[req_pkg[:metadata][:filename]] << pkg end end return dependency_mapping end # Given a list of packages, return a list of dependents packages def get_dependents(pkgs) dependents = [] to_check = pkgs.map { |pkg| pkg[:metadata][:filename] } dependency = get_dependency_mapping while pkgfile = to_check.pop pkgs = dependency[pkgfile.to_s] next if pkgs.nil? dependents |= pkgs to_check |= pkgs.map { |pkg| pkg[:metadata][:filename] } end return dependents end # Given a list of packages, return a list of all their prerequisite dependencies # Example: If pkgA depends on pkgB, and pkgB depends on pkgC, then calling this # method on pkgA will returns pkgB and pkgC # Assumption: There is no cyclic dependency def get_prerequisites(pkgs) pre_reqs = [] to_check = pkgs.clone while pkg = to_check.pop next if pkg[:metadata][:dependencies].nil? pkg[:metadata][:dependencies].each do | dep | pre_req = installed_packages_that_meet_requirement(dep) pre_reqs |= pre_req to_check |= pre_req end end return pre_reqs end # print out history packages installation/remove def installation_history if !File.exists?(File.join(@log_directory,'changes.log')) puts "Tpkg history log does not exist." return GENERIC_ERR end IO.foreach(File.join(@log_directory,'changes.log')) do |line| puts line end end # Download packages that meet the requests specified by the user. # Packages are downloaded into the current directory or into the directory # specified in options[:out] def download_pkgs(requests, options={}) if options[:out] if !File.exists?(options[:out]) FileUtils.mkdir_p(options[:out]) elsif !File.directory?(options[:out]) puts "#{options[:out]} is not a valid directory." return GENERIC_ERR end end output_dir = options[:out] || Dir.pwd requirements = [] packages = {} original_dir = Dir.pwd workdir = Tpkg::tempdir("tpkg_download") Dir.chdir(workdir) parse_requests(requests, requirements, packages) packages = packages.values.flatten if packages.size < 1 puts "Unable to find any packages that satisfy your request. Try running with --debug for more info" Dir.chdir(original_dir) return GENERIC_ERR end # Confirm with user what packages will be downloaded packages.delete_if{|pkg|pkg[:source] !~ /^http/} puts "The following packages will be downloaded:" packages.each do |pkg| puts "#{pkg[:metadata][:filename]} (source: #{pkg[:source]})" end if @@prompt && !Tpkg::confirm Dir.chdir(original_dir) return 0 end err_code = 0 puts "Downloading to #{output_dir}" packages.each do |pkg| puts "Downloading #{pkg[:metadata][:filename]}" begin downloaded_file = download(pkg[:source], pkg[:metadata][:filename], Dir.pwd, false) # copy downloaded files over to destination FileUtils.cp(downloaded_file, output_dir) rescue warn "Warning: unable to download #{pkg[:metadata][:filename]} to #{output_dir}" err_code = GENERIC_ERR end end # clean up working directory FileUtils.rm_rf(workdir) Dir.chdir(original_dir) return err_code end # TODO: figure out what other methods above can be turned into protected methods protected # log changes of pkgs that were installed/removed def log_changes(options={}) msg = "" user = Etc.getlogin || Etc.getpwuid(Process.uid).name newly_installed = removed = [] newly_installed = options[:newly_installed] if options[:newly_installed] removed = options[:removed] if options[:removed] removed.each do |pkg| msg = "#{msg}#{Time.new} #{pkg[:filename]} was removed by #{user}\n" end newly_installed.each do |pkg| msg = "#{msg}#{Time.new} #{pkg[:filename]} was installed by #{user}\n" end msg.lstrip! unless msg.empty? File.open(File.join(@log_directory,'changes.log'), 'a') {|f| f.write(msg) } end end def send_update_to_server(options={}) request = {"client"=>Facter['fqdn'].value} request[:user] = Etc.getlogin || Etc.getpwuid(Process.uid).name request[:tpkg_home] = ENV['TPKG_HOME'] if options[:currently_installed] currently_installed = options[:currently_installed] else currently_installed = metadata_for_installed_packages.collect{|metadata| metadata.to_hash} end # Figure out list of packages that were already installed, newly installed and newly removed if options[:newly_installed] newly_installed = options[:newly_installed] request[:newly_installed] = URI.escape(YAML.dump(newly_installed)) already_installed = currently_installed - newly_installed else already_installed = currently_installed end request[:already_installed] = URI.escape(YAML.dump(already_installed)) if options[:removed] removed = options[:removed] request[:removed] = URI.escape(YAML.dump(removed)) end begin response = nil # Need to set timeout otherwise tpkg can hang for a long time when having # problem talking to the reporter server. # I can't seem get net-ssh timeout to work so we'll just handle the timeout ourselves timeout(CONNECTION_TIMEOUT) do update_uri = URI.parse("#{@report_server}") http = Tpkg::gethttp(update_uri) post = Net::HTTP::Post.new(update_uri.path) post.set_form_data(request) response = http.request(post) end case response when Net::HTTPSuccess puts "Successfully send update to reporter server" else $stderr.puts response.body #response.error! # just ignore error and give user warning puts "Failed to send update to reporter server" end rescue Timeout::Error puts "Timed out when trying to send update to reporter server" rescue puts "Failed to send update to reporter server" end end # create and install native stub package if needed # this stub package helps prevent user from removing native packages that # our tpkg packages depend on def stub_native_pkg(pkg) # gather all of the native dependencies native_deps = pkg[:metadata].get_native_deps return if native_deps.nil? or native_deps.empty? if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ rpm = create_rpm("stub_for_#{pkg[:metadata][:name]}", native_deps) return if rpm.nil? # install the rpm cmd = "rpm -i #{rpm}" puts cmd if @@debug system(cmd) if !$?.success? warn "Warning: Failed to install native stub package for #{pkg[:metadata][:name]}" end else # TODO: support other OSes end end # remove the native dependency stub packages if there's any def remove_native_stub_pkg(pkg) # Don't have to do anything if this package has no native dependencies native_deps = pkg[:metadata].get_native_deps return if native_deps.nil? or native_deps.empty? # the convention is that stub package is named as "stub_for_pkgname" stub_pkg_name = "stub_for_#{pkg[:metadata][:name]}" if Tpkg::get_os =~ /RedHat|CentOS|Fedora/ cmd = "yum -y remove #{stub_pkg_name}" puts cmd if @@debug system(cmd) if !$?.success? warn "Warning: Failed to remove native stub package for #{pkg[:metadata][:name]}" end else # TODO: support other OSes end end def create_rpm(name, deps=[]) # setup directories for rpmbuild topdir = Tpkg::tempdir('rpmbuild') %w[BUILD RPMS SOURCES SPECS SRPMS].each do |dir| FileUtils.mkdir_p(File.join(topdir, dir)) end dep_list = deps.collect{|dep|dep[:name]}.join(",") # create rpm spec file spec = <<-EOS.gsub(/^\s+/, "") Name: #{name} Summary: stub pkg created by tpkg Version: 1 Release: 1 buildarch: noarch Requires: #{dep_list} Group: Applications/System License: MIT BuildRoot: %{_builddir}/%{name}-buildroot %description stub pkg created by tpkg for the following dependencies: #{dep_list} %files EOS spec_file = File.join(topdir, 'SPECS', 'pkg.spec') File.open(spec_file, 'w') do |file| file.puts(spec) end # run rpmbuild system("rpmbuild -bb --define '_topdir #{topdir}' #{spec_file}") if !$?.success? warn "Warning: Failed to create native stub package for #{name}" return nil end # copy result over to tmpfile result = File.join(topdir, 'RPMS', 'noarch', "#{name}-1-1.noarch.rpm") rpm = nil if File.exists?(result) tmpfile = Tempfile.new(File.basename(result)) FileUtils.cp(result, tmpfile.path) rpm = tmpfile.path end # cleanup FileUtils.rm_rf(topdir) return rpm end end
module Chore module Version MAJOR = 1 MINOR = 1 PATCH = 1 STRING = [ MAJOR, MINOR, PATCH ].join('.') end end Tag v1.1.2 release module Chore module Version MAJOR = 1 MINOR = 1 PATCH = 2 STRING = [ MAJOR, MINOR, PATCH ].join('.') end end
$LOAD_PATH.push File.expand_path('../lib', __FILE__) require 'link_preview/version' Gem::Specification.new do |s| s.name = 'link_preview' s.version = LinkPreview::VERSION s.authors = ['Michael Andrews'] s.email = ['michael@socialcast.com'] s.homepage = 'https://github.com/socialcast/link_preview' s.summary = 'Generate a link_preview for any URL' s.description = 'Generate a link_preview for any URL' s.files = Dir['{lib,spec/support/link_preview}/**/*'] + ['LICENSE.txt', 'Rakefile', 'README.md'] s.test_files = Dir['spec/**/*'] s.add_dependency('ruby-oembed', '~> 0.9.0') s.add_dependency('addressable') s.add_dependency('faraday', '~> 0.9.0') s.add_dependency('nokogiri') s.add_dependency('multi_json') s.add_dependency('activesupport') # Development s.add_development_dependency('rake') s.add_development_dependency('rubocop') # Testing s.add_development_dependency('rspec', '>= 2.9') s.add_development_dependency('vcr') s.add_development_dependency('webmock') s.add_development_dependency('debugger') if RUBY_VERSION.start_with?('1') s.add_development_dependency('byebug') if RUBY_VERSION.start_with?('2') end Remove ruby 1.9.x check $LOAD_PATH.push File.expand_path('../lib', __FILE__) require 'link_preview/version' Gem::Specification.new do |s| s.name = 'link_preview' s.version = LinkPreview::VERSION s.authors = ['Michael Andrews'] s.email = ['michael@socialcast.com'] s.homepage = 'https://github.com/socialcast/link_preview' s.summary = 'Generate a link_preview for any URL' s.description = 'Generate a link_preview for any URL' s.files = Dir['{lib,spec/support/link_preview}/**/*'] + ['LICENSE.txt', 'Rakefile', 'README.md'] s.test_files = Dir['spec/**/*'] s.add_dependency('ruby-oembed', '~> 0.9.0') s.add_dependency('addressable') s.add_dependency('faraday', '~> 0.9.0') s.add_dependency('nokogiri') s.add_dependency('multi_json') s.add_dependency('activesupport') # Development s.add_development_dependency('rake') s.add_development_dependency('rubocop') # Testing s.add_development_dependency('rspec', '>= 2.9') s.add_development_dependency('vcr') s.add_development_dependency('webmock') s.add_development_dependency('byebug') end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "lederhosen" s.version = "0.5.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Austin G. Davis-Richardson"] s.date = "2012-08-27" s.description = "Various tools for OTU clustering" s.email = "harekrishna@gmail.com" s.executables = ["lederhosen"] s.extra_rdoc_files = [ "LICENSE.txt" ] s.files = [ ".rspec", ".rvmrc", "Gemfile", "LICENSE.txt", "Rakefile", "bin/lederhosen", "examples/hierarchical_clustering.sh", "examples/pipeline.sh", "lederhosen.gemspec", "lib/lederhosen.rb", "lib/lederhosen/buffer.rb", "lib/lederhosen/cli.rb", "lib/lederhosen/helpers.rb", "lib/lederhosen/tasks/add_names.rb", "lib/lederhosen/tasks/cluster.rb", "lib/lederhosen/tasks/join.rb", "lib/lederhosen/tasks/k_filter.rb", "lib/lederhosen/tasks/name.rb", "lib/lederhosen/tasks/otu_filter.rb", "lib/lederhosen/tasks/otu_table.rb", "lib/lederhosen/tasks/rep_reads.rb", "lib/lederhosen/tasks/sort.rb", "lib/lederhosen/tasks/split.rb", "lib/lederhosen/tasks/split_fasta.rb", "lib/lederhosen/tasks/squish.rb", "lib/lederhosen/tasks/trim.rb", "lib/lederhosen/tasks/uc_filter.rb", "lib/lederhosen/tasks/uc_stats.rb", "lib/lederhosen/tasks/version.rb", "lib/lederhosen/version.rb", "readme.md", "spec/cli_spec.rb", "spec/data/ILT_L_9_B_001_1.txt.gz", "spec/data/ILT_L_9_B_001_3.txt.gz", "spec/data/ILT_L_9_B_002_1.txt.gz", "spec/data/ILT_L_9_B_002_3.txt.gz", "spec/data/blat.txt", "spec/data/otus.csv", "spec/helpers_spec.rb", "spec/misc_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://audy.github.com/lederhosen" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.24" s.summary = "OTU Clustering" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<dna>, ["= 0.0.12"]) s.add_runtime_dependency(%q<progressbar>, [">= 0"]) s.add_runtime_dependency(%q<thor>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, [">= 0"]) s.add_development_dependency(%q<jeweler>, [">= 0"]) else s.add_dependency(%q<dna>, ["= 0.0.12"]) s.add_dependency(%q<progressbar>, [">= 0"]) s.add_dependency(%q<thor>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) end else s.add_dependency(%q<dna>, ["= 0.0.12"]) s.add_dependency(%q<progressbar>, [">= 0"]) s.add_dependency(%q<thor>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) end end Regenerate gemspec for version 0.5.2 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "lederhosen" s.version = "0.5.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Austin G. Davis-Richardson"] s.date = "2012-08-27" s.description = "Various tools for OTU clustering" s.email = "harekrishna@gmail.com" s.executables = ["lederhosen"] s.extra_rdoc_files = [ "LICENSE.txt" ] s.files = [ ".rspec", ".rvmrc", "Gemfile", "LICENSE.txt", "Rakefile", "bin/lederhosen", "examples/hierarchical_clustering.sh", "examples/pipeline.sh", "lederhosen.gemspec", "lib/lederhosen.rb", "lib/lederhosen/buffer.rb", "lib/lederhosen/cli.rb", "lib/lederhosen/helpers.rb", "lib/lederhosen/tasks/add_names.rb", "lib/lederhosen/tasks/cluster.rb", "lib/lederhosen/tasks/join.rb", "lib/lederhosen/tasks/k_filter.rb", "lib/lederhosen/tasks/name.rb", "lib/lederhosen/tasks/otu_filter.rb", "lib/lederhosen/tasks/otu_table.rb", "lib/lederhosen/tasks/rep_reads.rb", "lib/lederhosen/tasks/sort.rb", "lib/lederhosen/tasks/split.rb", "lib/lederhosen/tasks/split_fasta.rb", "lib/lederhosen/tasks/squish.rb", "lib/lederhosen/tasks/trim.rb", "lib/lederhosen/tasks/uc_filter.rb", "lib/lederhosen/tasks/uc_stats.rb", "lib/lederhosen/tasks/version.rb", "lib/lederhosen/version.rb", "readme.md", "spec/cli_spec.rb", "spec/data/ILT_L_9_B_001_1.txt.gz", "spec/data/ILT_L_9_B_001_3.txt.gz", "spec/data/ILT_L_9_B_002_1.txt.gz", "spec/data/ILT_L_9_B_002_3.txt.gz", "spec/data/blat.txt", "spec/data/otus.csv", "spec/helpers_spec.rb", "spec/misc_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://audy.github.com/lederhosen" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.24" s.summary = "OTU Clustering" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<dna>, ["= 0.0.12"]) s.add_runtime_dependency(%q<progressbar>, [">= 0"]) s.add_runtime_dependency(%q<thor>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, [">= 0"]) s.add_development_dependency(%q<jeweler>, [">= 0"]) else s.add_dependency(%q<dna>, ["= 0.0.12"]) s.add_dependency(%q<progressbar>, [">= 0"]) s.add_dependency(%q<thor>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) end else s.add_dependency(%q<dna>, ["= 0.0.12"]) s.add_dependency(%q<progressbar>, [">= 0"]) s.add_dependency(%q<thor>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) end end
module Click class Clicker def click! observers.each { |o| o.before_click(self) } ObjectSpace.garbage_collect @state = Hash.new(0) ObjectSpace.each_object do |object| @state[object.class] += 1 end @state[Symbol] = Symbol.all_symbols.count observers.each { |o| o.after_click(self) } end def object_counts @state.dup end def instance_count(klass) @state.fetch(klass, 0) end def add_observer(observer) observers << observer end private def observers @observers ||= [] end end end Make click! more resilient against unclassy things module Click class Clicker def click! observers.each { |o| o.before_click(self) } ObjectSpace.garbage_collect @state = Hash.new(0) ObjectSpace.each_object do |object| begin klass = object.class next unless klass.is_a?(Class) rescue NoMethodError next end @state[klass] += 1 end @state[Symbol] = Symbol.all_symbols.count observers.each { |o| o.after_click(self) } end def object_counts @state.dup end def instance_count(klass) @state.fetch(klass, 0) end def add_observer(observer) observers << observer end private def observers @observers ||= [] end end end
module Click VERSION = "0.0.1" end Bump to 0.0.2 module Click VERSION = "0.0.2" end
require 'test_helper' # For tooling related to using the clinicfinder gem class ClinicfindersControllerTest < ActionDispatch::IntegrationTest describe 'search' do before do # Mock service @clinic_finder_mock = Minitest::Mock.new @clinic_finder_mock.expect(:locate_nearest_clinics, [create(:clinic)], ['12345']) sign_in create(:user) end it 'should respond successfully' do ClinicFinder::Locator.stub(:new, @clinic_finder_mock) do post clinicfinder_search_path, params: { zip: '12345' }, xhr: true end assert_response :success end it 'should choke if there is not a zip code' do ClinicFinder::Locator.stub(:new, @clinic_finder_mock) do post clinicfinder_search_path, xhr: true end assert_response :bad_request end end end oh right, integration test require 'test_helper' # For tooling related to using the clinicfinder gem class ClinicfindersControllerTest < ActionDispatch::IntegrationTest describe 'search' do before do # Mock service @clinic_struct = OpenStruct.new create(:clinic).attributes @clinic_struct.distance = 300.30 @clinic_finder_mock = Minitest::Mock.new @clinic_finder_mock.expect(:locate_nearest_clinics, [@clinic_struct], ['12345']) sign_in create(:user) end it 'should respond successfully' do ClinicFinder::Locator.stub(:new, @clinic_finder_mock) do post clinicfinder_search_path, params: { zip: '12345' }, xhr: true end assert_response :success end it 'should choke if there is not a zip code' do ClinicFinder::Locator.stub(:new, @clinic_finder_mock) do post clinicfinder_search_path, xhr: true end assert_response :bad_request end end end
module VmCommon extend ActiveSupport::Concern # handle buttons pressed on the button bar def button @edit = session[:edit] # Restore @edit for adv search box params[:page] = @current_page if @current_page != nil # Save current page for list refresh @refresh_div = "main_div" # Default div for button.rjs to refresh custom_buttons if params[:pressed] == "custom_button" perf_chart_chooser if params[:pressed] == "perf_reload" perf_refresh_data if params[:pressed] == "perf_refresh" remove_service if params[:pressed] == "remove_service" return if ["custom_button"].include?(params[:pressed]) # custom button screen, so return, let custom_buttons method handle everything # VM sub-screen is showing, so return return if ["perf_reload"].include?(params[:pressed]) && @flash_array == nil if @flash_array == nil # if no button handler ran, show not implemented msg add_flash(_("Button not yet implemented"), :error) @refresh_partial = "layouts/flash_msg" @refresh_div = "flash_msg_div" else # Figure out what was showing to refresh it if @lastaction == "show" && ["vmtree"].include?(@showtype) @refresh_partial = @showtype elsif @lastaction == "show" && ["config"].include?(@showtype) @refresh_partial = @showtype elsif @lastaction == "show_list" # default to the gtl_type already set else @refresh_partial = "layouts/flash_msg" @refresh_div = "flash_msg_div" end end @vm = @record = identify_record(params[:id], VmOrTemplate) unless @lastaction == "show_list" if !@flash_array.nil? && @single_delete render :update do |page| page.redirect_to :action => 'show_list', :flash_msg=>@flash_array[0][:message] # redirect to build the retire screen end elsif params[:pressed].ends_with?("_edit") if @redirect_controller render :update do |page| page.redirect_to :controller=>@redirect_controller, :action=>@refresh_partial, :id=>@redirect_id, :org_controller=>@org_controller end else render :update do |page| page.redirect_to :action=>@refresh_partial, :id=>@redirect_id end end else if @refresh_div == "main_div" && @lastaction == "show_list" replace_gtl_main_div else if @refresh_div == "flash_msg_div" render :partial => "shared/ajax/flash_msg_replace" else options partial_replace(@refresh_div, "vm_common/#{@refresh_partial}") end end end end def show_timeline db = get_rec_cls @display = "timeline" session[:tl_record_id] = params[:id] if params[:id] @record = find_by_id_filtered(db, from_cid(session[:tl_record_id])) @timeline = @timeline_filter = true @lastaction = "show_timeline" tl_build_timeline # Create the timeline report drop_breadcrumb( {:name=>"Timelines", :url=>"/#{db}/show_timeline/#{@record.id}?refresh=n"} ) if @explorer @refresh_partial = "layouts/tl_show" if params[:refresh] @sb[:action] = "timeline" replace_right_cell end end end alias image_timeline show_timeline alias instance_timeline show_timeline alias vm_timeline show_timeline alias miq_template_timeline show_timeline # Launch a VM console def console console_type = get_vmdb_config.fetch_path(:server, :remote_console_type).downcase unless params[:task_id] console_before_task(console_type) else console_after_task(console_type) end end alias vmrc_console console # VMRC needs its own URL for RBAC checking alias vnc_console console # VNC needs its own URL for RBAC checking def launch_vmware_console console_type = get_vmdb_config.fetch_path(:server, :remote_console_type).downcase @vm = @record = identify_record(params[:id], VmOrTemplate) case console_type when "mks" @mks_version = get_vmdb_config[:server][:mks_version] @mks = @sb[:mks] when "vmrc" @vmrc = Hash.new @vmrc[:host] = @record.ext_management_system.ipaddress || @record.ext_management_system.hostname @vmrc[:vmid] = @record.ems_ref @vmrc[:ticket] = @sb[:vmrc_ticket] @vmrc[:api_version] = @record.ext_management_system.api_version.to_s @vmrc[:os] = browser_info(:os).downcase end render :action=>"console" end # VM clicked on in the explorer right cell def x_show @explorer = true @vm = @record = identify_record(params[:id], VmOrTemplate) respond_to do |format| format.js do # AJAX, select the node unless @record redirect_to :action => "explorer" return end params[:id] = x_build_node_id(@record) # Get the tree node id tree_select end format.html do # HTML, redirect to explorer tree_node_id = TreeBuilder.build_node_id(@record) session[:exp_parms] = {:id => tree_node_id} redirect_to :action => "explorer" end format.any {render :nothing=>true, :status=>404} # Anything else, just send 404 end end def show(id = nil) @flash_array = [] if params[:display] @sb[:action] = params[:display] return if perfmenu_click? @display = params[:display] || "main" unless control_selected? @display = params[:vm_tree] if params[:vm_tree] @lastaction = "show" @showtype = "config" @record = identify_record(id || params[:id], VmOrTemplate) return if record_no_longer_exists?(@record) @explorer = true if request.xml_http_request? # Ajax request means in explorer if !@explorer && @display != "download_pdf" tree_node_id = TreeBuilder.build_node_id(@record) session[:exp_parms] = {:display => @display, :refresh => params[:refresh], :id => tree_node_id} redirect_to :controller => controller_for_vm(model_for_vm(@record)), :action => "explorer" return end if @record.class.base_model.to_s == "MiqTemplate" rec_cls = @record.class.base_model.to_s.underscore else rec_cls = "vm" end @gtl_url = "/#{rec_cls}/show/" << @record.id.to_s << "?" if ["download_pdf","main","summary_only"].include?(@display) get_tagdata(@record) drop_breadcrumb({:name=>"Virtual Machines", :url=>"/#{rec_cls}/show_list?page=#{@current_page}&refresh=y"}, true) drop_breadcrumb( {:name=>@record.name + " (Summary)", :url=>"/#{rec_cls}/show/#{@record.id}"} ) @showtype = "main" @button_group = "#{rec_cls}" set_summary_pdf_data if ["download_pdf","summary_only"].include?(@display) elsif @display == "networks" drop_breadcrumb( {:name=>@record.name+" (Networks)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) elsif @display == "os_info" drop_breadcrumb( {:name=>@record.name+" (OS Information)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) elsif @display == "hv_info" drop_breadcrumb( {:name=>@record.name+" (Container)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) elsif @display == "resources_info" drop_breadcrumb( {:name=>@record.name+" (Resources)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) elsif @display == "snapshot_info" drop_breadcrumb( {:name=>@record.name+" (Snapshots)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) build_snapshot_tree @button_group = "snapshot" elsif @display == "miq_proxies" drop_breadcrumb({:name=>"Virtual Machines", :url=>"/#{rec_cls}/show_list?page=#{@current_page}&refresh=y"}, true) drop_breadcrumb( {:name=>@record.name+" (Managing SmartProxies)", :url=>"/#{rec_cls}/show/#{@record.id}?display=miq_proxies"} ) @view, @pages = get_view(MiqProxy, :parent=>@record) # Get the records (into a view) and the paginator @showtype = "miq_proxies" @gtl_url = "/#{rec_cls}/show/" << @record.id.to_s << "?" elsif @display == "vmtree_info" @tree_vms = Array.new # Capture all VM ids in the tree drop_breadcrumb( {:name=>@record.name, :url=>"/#{rec_cls}/show/#{@record.id}"}, true ) drop_breadcrumb( {:name=>@record.name+" (Genealogy)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) #session[:base_id] = @record.id vmtree_nodes = vmtree(@record) @temp[:vm_tree] = vmtree_nodes.to_json @temp[:tree_name] = "genealogy_tree" @button_group = "vmtree" elsif @display == "compliance_history" count = params[:count] ? params[:count].to_i : 10 session[:ch_tree] = compliance_history_tree(@record, count).to_json session[:tree_name] = "ch_tree" session[:squash_open] = (count == 1) drop_breadcrumb( {:name=>@record.name, :url=>"/#{rec_cls}/show/#{@record.id}"}, true ) if count == 1 drop_breadcrumb( {:name=>@record.name+" (Latest Compliance Check)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) else drop_breadcrumb( {:name=>@record.name+" (Compliance History - Last #{count} Checks)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) end @showtype = @display elsif @display == "performance" @showtype = "performance" drop_breadcrumb( {:name=>"#{@record.name} Capacity & Utilization", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}&refresh=n"} ) perf_gen_init_options # Initialize perf chart options, charts will be generated async elsif @display == "disks" @showtype = "disks" disks drop_breadcrumb( {:name=>"#{@record.name} (Disks)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) elsif @display == "ontap_logical_disks" drop_breadcrumb( {:name=>@record.name+" (All #{ui_lookup(:tables=>"ontap_logical_disk")})", :url=>"/#{rec_cls}/show/#{@record.id}?display=ontap_logical_disks"} ) @view, @pages = get_view(OntapLogicalDisk, :parent=>@record, :parent_method => :logical_disks) # Get the records (into a view) and the paginator @showtype = "ontap_logical_disks" elsif @display == "ontap_storage_systems" drop_breadcrumb( {:name=>@record.name+" (All #{ui_lookup(:tables=>"ontap_storage_system")})", :url=>"/#{rec_cls}/show/#{@record.id}?display=ontap_storage_systems"} ) @view, @pages = get_view(OntapStorageSystem, :parent=>@record, :parent_method => :storage_systems) # Get the records (into a view) and the paginator @showtype = "ontap_storage_systems" elsif @display == "ontap_storage_volumes" drop_breadcrumb( {:name=>@record.name+" (All #{ui_lookup(:tables=>"ontap_storage_volume")})", :url=>"/#{rec_cls}/show/#{@record.id}?display=ontap_storage_volumes"} ) @view, @pages = get_view(OntapStorageVolume, :parent=>@record, :parent_method => :storage_volumes) # Get the records (into a view) and the paginator @showtype = "ontap_storage_volumes" elsif @display == "ontap_file_shares" drop_breadcrumb( {:name=>@record.name+" (All #{ui_lookup(:tables=>"ontap_file_share")})", :url=>"/#{rec_cls}/show/#{@record.id}?display=ontap_file_shares"} ) @view, @pages = get_view(OntapFileShare, :parent=>@record, :parent_method => :file_shares) # Get the records (into a view) and the paginator @showtype = "ontap_file_shares" end unless @record.hardware.nil? @record_notes = @record.hardware.annotation.nil? ? "<No notes have been entered for this VM>" : @record.hardware.annotation end set_config(@record) get_host_for_vm(@record) session[:tl_record_id] = @record.id # Came in from outside show_list partial if params[:ppsetting] || params[:searchtag] || params[:entry] || params[:sort_choice] replace_gtl_main_div end if @explorer # @in_a_form = true @refresh_partial = "layouts/performance" replace_right_cell if !["download_pdf","performance"].include?(params[:display]) end end def summary_pdf return if perfmenu_click? @display = params[:display] || "main" unless control_selected? @display = params[:vm_tree] if params[:vm_tree] @lastaction = "show" @showtype = "config" @vm = @record = identify_record(params[:id], VmOrTemplate) return if record_no_longer_exists?(@vm) rec_cls = "vm" @gtl_url = "/#{rec_cls}/show/" << @record.id.to_s << "?" get_tagdata(@record) drop_breadcrumb({:name=>"Virtual Machines", :url=>"/#{rec_cls}/show_list?page=#{@current_page}&refresh=y"}, true) drop_breadcrumb( {:name=>@record.name + " (Summary)", :url=>"/#{rec_cls}/show/#{@record.id}"} ) @showtype = "main" @button_group = "#{rec_cls}" @report_only = true @showtype = "summary_only" @title = @record.name + " (Summary)" unless @record.hardware.nil? @record_notes = @record.hardware.annotation.nil? ? "<No notes have been entered for this VM>" : @record.hardware.annotation end set_config(@record) get_host_for_vm(@record) session[:tl_record_id] = @record.id html_string = render_to_string(:template => '/layouts/show_pdf', :layout => false) pdf_data = PdfGenerator.pdf_from_string(html_string, 'pdf_summary') disable_client_cache fname = "#{@record.name}_summary_#{format_timezone(Time.now, Time.zone, "fname")}" send_data(pdf_data, :filename => "#{fname}.pdf", :type => "application/pdf" ) end def vmtree(vm) session[:base_vm] = "_h-" + vm.id.to_s + "|" if vm.parents.length > 0 vm_parent = vm.parents @tree_vms.push(vm_parent[0]) unless @tree_vms.include?(vm_parent[0]) parent_node = Hash.new session[:parent_vm] = "_v-" + vm_parent[0].id.to_s + "|" # setting base node id to be passed for check/uncheck all button image = "" if vm_parent[0].retired == true image = "retired.png" else if vm_parent[0].template? if vm_parent[0].host image = "template.png" else image = "template-no-host.png" end else image = "#{vm_parent[0].current_state.downcase}.png" end end parent_node = TreeNodeBuilder.generic_tree_node( "_v-#{vm_parent[0].id}|", "#{vm_parent[0].name} (Parent)", image, "VM: #{vm_parent[0].name} (Click to view)", ) else session[:parent_vm] = nil end session[:parent_vm] = session[:base_vm] if session[:parent_vm].nil? # setting base node id to be passed for check/uncheck all button if vm has no parent base = Array.new base_node = vm_kidstree(vm) base.push(base_node) if !parent_node.nil? parent_node[:children] = base parent_node[:expand] = true return parent_node else base_node[:expand] = true return base_node end end # Recursive method to build a snapshot tree node def vm_kidstree(vm) branch = Hash.new key = "_v-#{vm.id}|" title = vm.name style = "" tooltip = "VM: #{vm.name} (Click to view)" if session[:base_vm] == "_h-#{vm.id}|" title << " (Selected)" key = session[:base_vm] style = "dynatree-cfme-active cfme-no-cursor-node" tooltip = "" end image = "" if vm.template? if vm.host image = "template.png" else image = "template-no-host.png" end else image = "#{vm.current_state.downcase}.png" end branch = TreeNodeBuilder.generic_tree_node( key, title, image, tooltip, :style_class => style ) @tree_vms.push(vm) unless @tree_vms.include?(vm) if vm.children.length > 0 kids = Array.new vm.children.each do |kid| kids.push(vm_kidstree(kid)) unless @tree_vms.include?(kid) end branch[:children] = kids.sort_by { |a| a[:title].downcase } end return branch end def build_snapshot_tree vms = @record.snapshots.all parent = TreeNodeBuilder.generic_tree_node( "snaproot", @record.name, "vm.png", nil, :cfme_no_click => true, :expand => true, :style_class => "cfme-no-cursor-node" ) @record.snapshots.each do | s | if s.current.to_i == 1 @root = s.id @active = true end end @root = @record.snapshots.first.id if @root.nil? && @record.snapshots.size > 0 session[:snap_selected] = @root if params[:display] == "snapshot_info" @temp[:snap_selected] = Snapshot.find(session[:snap_selected]) unless session[:snap_selected].nil? snapshots = Array.new vms.each do |snap| if snap.parent_id.nil? snapshots.push(snaptree(snap)) end end parent[:children] = snapshots top = @record.snapshots.find_by_parent_id(nil) @snaps = [parent].to_json unless top.nil? && parent.blank? end # Recursive method to build a snapshot nodes def snaptree(node) branch = TreeNodeBuilder.generic_tree_node( node.id, node.name, "snapshot.png", "Click to select", :expand => true ) branch[:title] << " (Active)" if node.current? branch[:addClass] = "dynatree-cfme-active" if session[:snap_selected].to_s == branch[:key].to_s if node.children.count > 0 kids = Array.new node.children.each do |kid| kids.push(snaptree(kid)) end branch[:children] = kids end return branch end def vmtree_selected base = params[:id].split('-') base = base[1].slice(0,base[1].length-1) session[:base_vm] = "_h-" + base.to_s @display = "vmtree_info" render :update do |page| # Use RJS to update the display page.redirect_to :action=>"show", :id=>base,:vm_tree=>"vmtree_info" end end def snap_pressed session[:snap_selected] = params[:id] @temp[:snap_selected] = Snapshot.find_by_id(session[:snap_selected]) @vm = @record = identify_record(x_node.split('-').last, VmOrTemplate) if @temp[:snap_selected].nil? @display = "snapshot_info" add_flash(_("Last selected %s no longer exists") % "Snapshot", :error) end build_snapshot_tree @active = @temp[:snap_selected].current.to_i == 1 if @temp[:snap_selected] @button_group = "snapshot" @explorer = true c_buttons, c_xml = build_toolbar_buttons_and_xml("x_vm_center_tb") render :update do |page| # Use RJS to update the display if c_buttons && c_xml page << "dhxLayoutB.cells('a').expand();" page << javascript_for_toolbar_reload('center_tb', c_buttons, c_xml) page << javascript_show_if_exists("center_buttons_div") else page << javascript_hide_if_exists("center_buttons_div") end page.replace("flash_msg_div", :partial => "layouts/flash_msg") page.replace("desc_content", :partial => "/vm_common/snapshots_desc", :locals => {:selected => params[:id]}) page.replace("snapshots_tree_div", :partial => "/vm_common/snapshots_tree") end end def disks #flag to show cursor as default in grid so rows don't look clickable @temp[:ro_grid] = true @grid_xml = build_disks_tree(@record) end def build_disks_tree(view) xml = REXML::Document.load("") xml << REXML::XMLDecl.new(1.0, "UTF-8") # Create root element root = xml.add_element("rows") # Build the header row hrow = root.add_element("head") grid_add_header(@record, hrow) # Sort disks by disk_name within device_type view.hardware.disks.sort{|x,y| cmp = x.device_type.to_s.downcase <=> y.device_type.to_s.downcase; cmp == 0 ? calculate_disk_name(x).downcase <=> calculate_disk_name(y).downcase : cmp }.each_with_index do |disk,idx| srow = root.add_element("row", {"id" => "Disk_#{idx}"}) srow.add_element("cell", {"image" => "blank.gif", "title" => "Disk #{idx}"}).text = calculate_disk_name(disk) srow.add_element("cell", {"image" => "blank.gif", "title" => "#{disk.disk_type}"}).text = disk.disk_type srow.add_element("cell", {"image" => "blank.gif", "title" => "#{disk.mode}"}).text = disk.mode srow.add_element("cell", {"image" => "blank.gif", "title" => "#{disk.partitions_aligned}",}).text = disk.partitions_aligned srow.add_element("cell", {"image" => "blank.gif", "title" => "#{calculate_size(disk.size)}"}).text = calculate_size(disk.size) srow.add_element("cell", {"image" => "blank.gif", "title" => "#{calculate_size(disk.size_on_disk)}"}).text = calculate_size(disk.size_on_disk) srow.add_element("cell", {"image" => "blank.gif", "title" => "#{disk.used_percent_of_provisioned}"}).text = disk.used_percent_of_provisioned end return xml.to_s end def calculate_volume_name(vname) vname.blank? ? "Volume N/A" : "Volume #{vname}" end def calculate_size(size) size.blank? ? nil : number_to_human_size(size,:precision=>2) end def calculate_disk_name(disk) loc = disk.location.nil? ? "" : disk.location dev = "#{disk.controller_type} #{loc}" # default device is controller_type # Customize disk entries by type if disk.device_type == "cdrom-raw" dev = "CD-ROM (IDE " << loc << ")" elsif disk.device_type == "atapi-cdrom" dev = "ATAPI CD-ROM (IDE " << loc << ")" elsif disk.device_type == "cdrom-image" dev = "CD-ROM Image (IDE " << loc << ")" elsif disk.device_type == "disk" if disk.controller_type == "ide" dev = "Hard Disk (IDE " << loc << ")" elsif disk.controller_type == "scsi" dev = "Hard Disk (SCSI " << loc << ")" end elsif disk.device_type == "ide" dev = "Hard Disk (IDE " << loc << ")" elsif ["scsi", "scsi-hardDisk"].include?(disk.device_type) dev = "Hard Disk (SCSI " << loc << ")" elsif disk.device_type == "scsi-passthru" dev = "Generic SCSI (" << loc << ")" elsif disk.device_type == "floppy" dev = dev end return dev end def grid_add_header(view, head) col_width = 100 #disk new_column = head.add_element("column", {"width"=>"120","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Device Type" #device_type new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Type" #mode new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Mode" # alignment new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Partitions Aligned" # commented for FB6679 # #filesystem # new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) # new_column.add_attribute("type", 'ro') # new_column.text = "Filesystem" #size new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Provisioned Size" #size_on_disk new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Used Size" #used_percent_of_provisioned new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Percent Used of Provisioned Size" end def show_association(action, display_name, listicon, method, klass, association = nil) @explorer = true if request.xml_http_request? # Ajax request means in explorer if @explorer # Save vars for tree history array @action = action @x_show = params[:x_show] end @vm = @record = identify_record(params[:id], VmOrTemplate) return if record_no_longer_exists?(@vm) rec_cls = "vm" @sb[:action] = @lastaction = action if params[:show] != nil || params[:x_show] != nil id = params[:show] ? params[:show] : params[:x_show] if method.kind_of?(Array) obj = @record while meth = method.shift do obj = obj.send(meth) end @item = obj.find(from_cid(id)) else @item = @record.send(method).find(from_cid(id)) end drop_breadcrumb( { :name => "#{@record.name} (#{display_name})", :url=>"/#{rec_cls}/#{action}/#{@record.id}?page=#{@current_page}"} ) drop_breadcrumb( { :name => @item.name, :url=>"/#{rec_cls}/#{action}/#{@record.id}?show=#{@item.id}"} ) @view = get_db_view(klass, :association=>association) show_item else drop_breadcrumb( { :name => @record.name, :url=>"/#{rec_cls}/show/#{@record.id}"}, true ) drop_breadcrumb( { :name => "#{@record.name} (#{display_name})", :url=>"/#{rec_cls}/#{action}/#{@record.id}"} ) @listicon = listicon if association.nil? show_details(klass) else show_details(klass, :association => association ) end end end def processes show_association('processes', 'Running Processes', 'processes', [:operating_system, :processes], OsProcess, 'processes') end def registry_items show_association('registry_items', 'Registry Entries', 'registry_items', :registry_items, RegistryItem) end def advanced_settings show_association('advanced_settings', 'Advanced Settings', 'advancedsetting', :advanced_settings, AdvancedSetting) end def linux_initprocesses show_association('linux_initprocesses', 'Init Processes', 'linuxinitprocesses', :linux_initprocesses, SystemService, 'linux_initprocesses') end def win32_services show_association('win32_services', 'Win32 Services', 'win32service', :win32_services, SystemService, 'win32_services') end def kernel_drivers show_association('kernel_drivers', 'Kernel Drivers', 'kerneldriver', :kernel_drivers, SystemService, 'kernel_drivers') end def filesystem_drivers show_association('filesystem_drivers', 'File System Drivers', 'filesystemdriver', :filesystem_drivers, SystemService, 'filesystem_drivers') end def filesystems show_association('filesystems', 'Files', 'filesystems', :filesystems, Filesystem) end def security_groups show_association('security_groups', 'Security Groups', 'security_group', :security_groups, SecurityGroup) end def snap assert_privileges(params[:pressed]) @vm = @record = identify_record(params[:id], VmOrTemplate) @name = @description = "" @in_a_form = true @button_group = "snap" drop_breadcrumb( {:name=>"Snapshot VM '" + @record.name + "'", :url=>"/vm_common/snap", :display=>"snapshot_info"} ) if @explorer @edit ||= Hash.new @edit[:explorer] = true session[:changed] = true @refresh_partial = "vm_common/snap" end end alias vm_snapshot_add snap def snap_vm @vm = @record = identify_record(params[:id], VmOrTemplate) if params["cancel"] || params[:button] == "cancel" flash = _("%s was cancelled by the user") % "Snapshot of VM #{@record.name}" if session[:edit] && session[:edit][:explorer] add_flash(flash) @_params[:display] = "snapshot_info" show else redirect_to :action=>@lastaction, :id=>@record.id, :flash_msg=>flash end elsif params["create.x"] || params[:button] == "create" @name = params[:name] @description = params[:description] if params[:name].blank? add_flash(_("%s is required") % "Name", :error) @in_a_form = true drop_breadcrumb( {:name=>"Snapshot VM '" + @record.name + "'", :url=>"/vm_common/snap"} ) if session[:edit] && session[:edit][:explorer] @edit = session[:edit] #saving it to use in next transaction render :partial => "shared/ajax/flash_msg_replace" else render :action=>"snap" end else flash_error = false # audit = {:event=>"vm_genealogy_change", :target_id=>@record.id, :target_class=>@record.class.base_class.name, :userid => session[:userid]} begin # @record.create_snapshot(params[:name], params[:description], params[:snap_memory]) Vm.process_tasks( :ids => [@record.id], :task => "create_snapshot", :userid => session[:userid], :name => params[:name], :description => params[:description], :memory => params[:snap_memory] == "1") rescue StandardError => bang puts bang.backtrace.join("\n") flash = _("Error during '%s': ") % "Create Snapshot" << bang.message; flash_error = true # AuditEvent.failure(audit.merge(:message=>"[#{@record.name} -- #{@record.location}] Update returned: #{bang}")) else flash = _("Create Snapshot for %{model} \"%{name}\" was started") % {:model=>ui_lookup(:model=>"Vm"), :name=>@record.name} # AuditEvent.success(build_saved_vm_audit(@record)) end params[:id] = @record.id.to_s # reset id in params for show #params[:display] = "snapshot_info" if session[:edit] && session[:edit][:explorer] add_flash(flash, flash_error ? :error : :info) @_params[:display] = "snapshot_info" show else redirect_to :action=>@lastaction, :id=>@record.id, :flash_msg=>flash, :flash_error=>flash_error, :display=>"snapshot_info" end end end end def policies @vm = @record = identify_record(params[:id], VmOrTemplate) @lastaction = "rsop" @showtype = "policies" drop_breadcrumb( {:name=>"Policy Simulation Details for " + @record.name, :url=>"/vm/policies/#{@record.id}"} ) @polArr = Array.new @record.resolve_profiles(session[:policies].keys).sort{|a,b| a["description"] <=> b["description"]}.each do | a | @polArr.push(a) end @policy_options = Hash.new @policy_options[:out_of_scope] = true @policy_options[:passed] = true @policy_options[:failed] = true build_policy_tree(@polArr) @edit = session[:edit] if session[:edit] if @edit && @edit[:explorer] @in_a_form = true replace_right_cell else render :template => 'vm/show' end end # policy simulation tree def build_policy_tree(profiles) session[:squash_open] = false vm_node = TreeNodeBuilder.generic_tree_node( "h_#{@record.name}", @record.name, "vm.png", @record.name, {:style_class => "cfme-no-cursor-node", :expand => true } ) vm_node[:title] = "<b>#{vm_node[:title]}</b>" vm_node[:children] = build_profile_nodes(profiles) if profiles.length > 0 session[:policy_tree] = [vm_node].to_json session[:tree_name] = "rsop_tree" end def build_profile_nodes(profiles) profile_nodes = [] profiles.each do |profile| if profile["result"] == "allow" icon = "checkmark.png" elsif profile["result"] == "N/A" icon = "na.png" else icon = "x.png" end profile_node = TreeNodeBuilder.generic_tree_node( "policy_profile_#{profile['id']}", profile['description'], icon, nil, {:style_class => "cfme-no-cursor-node"} ) profile_node[:title] = "<b>Policy Profile:</b> #{profile_node[:title]}" profile_node[:children] = build_policy_node(profile["policies"]) if profile["policies"].length > 0 if @policy_options[:out_of_scope] == false profile_nodes.push(profile_node) if profile["result"] != "N/A" else profile_nodes.push(profile_node) end end profile_nodes.push(build_empty_node) if profile_nodes.blank? profile_nodes end def build_empty_node TreeNodeBuilder.generic_tree_node( nil, "Items out of scope", "blank.gif", nil, {:style_class => "cfme-no-cursor-node"} ) end def build_policy_node(policies) policy_nodes = [] policies.sort_by{ |a| a["description"] }.each do |policy| active_caption = policy["active"] ? "" : " (Inactive)" if policy["result"] == "allow" icon = "checkmark.png" elsif policy["result"] == "N/A" icon = "na.png" else icon = "x.png" end policy_node = TreeNodeBuilder.generic_tree_node( "policy_#{policy["id"]}", policy['description'], icon, nil, {:style_class => "cfme-no-cursor-node"} ) policy_node[:title] = "<b>Policy#{active_caption}:</b> #{policy_node[:title]}" policy_children = [] policy_children.push(build_scope_or_expression_node(policy["scope"], "scope_#{policy["id"]}_#{policy["name"]}", "Scope")) if policy["scope"] policy_children.concat(build_condition_nodes(policy)) if policy["conditions"].length > 0 policy_node[:children] = policy_children unless policy_children.empty? if @policy_options[:out_of_scope] == false && @policy_options[:passed] == true && @policy_options[:failed] == true policy_nodes.push(policy_node) if policy["result"] != "N/A" elsif @policy_options[:passed] == true && @policy_options[:failed] == false && @policy_options[:out_of_scope] == false policy_nodes.push(policy_node) if policy["result"] == "allow" elsif @policy_options[:passed] == true && @policy_options[:failed] == false && @policy_options[:out_of_scope] == true policy_nodes.push(policy_node) if policy["result"] == "N/A" || policy["result"] == "allow" elsif @policy_options[:failed] == true && @policy_options[:passed] == false policy_nodes.push(policy_node) if policy["result"] == "deny" elsif @policy_options[:out_of_scope] == true && @policy_options[:passed] == true && policy["result"] == "N/A" policy_nodes.push(policy_node) else policy_nodes.push(policy_node) end end policy_nodes end def build_condition_nodes(policy) condition_nodes = [] policy["conditions"].sort_by{ |a| a["description"] }.each do |condition| if condition["result"] == "allow" icon = "checkmark.png" elsif condition["result"] == "N/A" || !condition["expression"] icon = "na.png" else icon = "x.png" end condition_node = TreeNodeBuilder.generic_tree_node( "condition_#{condition["id"]}_#{condition["name"]}_#{policy["name"]}", condition["description"], icon, nil, {:style_class => "cfme-no-cursor-node"} ) condition_node[:title] = "<b>Condition:</b> #{condition_node[:title]}" condition_children = [] condition_children.push(build_scope_or_expression_node(condition["scope"], "scope_#{condition["id"]}_#{condition["name"]}", "Scope")) if condition["scope"] condition_children.push(build_scope_or_expression_node(condition["expression"], "expression_#{condition["id"]}_#{condition["name"]}", "Expression")) if condition["expression"] condition_node[:children] = condition_children if !condition_children.blank? if @policy_options[:out_of_scope] == false condition_nodes.push(condition_node) if condition["result"] != "N/A" else condition_nodes.push(condition_node) end end condition_nodes end def build_scope_or_expression_node(scope_or_expression, node_key, title_prefix) exp_string,exp_tooltip = exp_build_string(scope_or_expression) if scope_or_expression["result"] == true icon = "checkmark.png" else icon = "na.png" end node = TreeNodeBuilder.generic_tree_node( node_key, exp_string.html_safe, icon, exp_tooltip.html_safe, {:style_class => "cfme-no-cursor-node"} ) node[:title] = "<b>#{title_prefix}:</b> #{node[:title]}" if @policy_options[:out_of_scope] == false node if scope_or_expression["result"] != "N/A" else node end end def policy_show_options if params[:passed] == "null" || params[:passed] == "" @policy_options[:passed] = false @policy_options[:failed] = true elsif params[:failed] == "null" || params[:failed] == "" @policy_options[:passed] = true @policy_options[:failed] = false elsif params[:failed] == "1" @policy_options[:failed] = true elsif params[:passed] == "1" @policy_options[:passed] = true end @vm = @record = identify_record(params[:id], VmOrTemplate) build_policy_tree(@polArr) render :update do |page| page.replace_html("flash_msg_div", :partial => "layouts/flash_msg") page.replace_html("main_div", :partial => "vm_common/policies") end end # Show/Unshow out of scope items def policy_options @vm = @record = identify_record(params[:id], VmOrTemplate) @policy_options ||= Hash.new @policy_options[:out_of_scope] = (params[:out_of_scope] == "1") build_policy_tree(@polArr) render :update do |page| page.replace("flash_msg_div", :partial => "layouts/flash_msg") page << "#{session[:tree_name]}.saveOpenStates('#{session[:tree_name]}','path=/');" page << "#{session[:tree_name]}.loadOpenStates('#{session[:tree_name]}');" #page.replace("policy_options_div", :partial=>"vm/policy_options") page.replace("main_div", :partial=>"vm_common/policies") end end def toggle_policy_profile session[:policy_profile_compressed] = ! session[:policy_profile_compressed] @compressed = session[:policy_profile_compressed] render :update do |page| # Use RJS to update the display page.replace_html("view_buttons_div", :partial=>"layouts/view_buttons") # Replace the view buttons page.replace_html("main_div", :partial=>"policies") # Replace the main div area contents end end # Set right_size selected db records def right_size @record = Vm.find_by_id(params[:id]) @lastaction = "right_size" @rightsize = true @in_a_form = true if params[:button] == "back" render :update do |page| page.redirect_to(previous_breadcrumb_url) end end if !@explorer && params[:button] != "back" drop_breadcrumb(:name => "Right Size VM '" + @record.name + "'", :url => "/vm/right_size") render :action=>"show" end end def evm_relationship @record = find_by_id_filtered(VmOrTemplate, params[:id]) # Set the VM object @edit = Hash.new @edit[:vm_id] = @record.id @edit[:key] = "evm_relationship_edit__new" @edit[:current] = Hash.new @edit[:new] = Hash.new evm_relationship_build_screen @edit[:current] = copy_hash(@edit[:new]) session[:changed] = false @tabs = [ ["evm_relationship", @record.id.to_s], ["evm_relationship", "Edit Management Engine Relationship"] ] @in_a_form = true if @explorer @refresh_partial = "vm_common/evm_relationship" @edit[:explorer] = true end end alias image_evm_relationship evm_relationship alias instance_evm_relationship evm_relationship alias vm_evm_relationship evm_relationship alias miq_template_evm_relationship evm_relationship # Build the evm_relationship assignment screen def evm_relationship_build_screen @servers = Hash.new # Users array for first chooser MiqServer.all.each{|s| @servers["#{s.name} (#{s.id})"] = s.id.to_s} @edit[:new][:server] = @record.miq_server ? @record.miq_server.id.to_s : nil # Set to first category, if not already set end def evm_relationship_field_changed return unless load_edit("evm_relationship_edit__new") evm_relationship_get_form_vars changed = (@edit[:new] != @edit[:current]) render :update do |page| # Use JS to update the display page << javascript_for_miq_button_visibility(changed) end end def evm_relationship_get_form_vars @record = VmOrTemplate.find_by_id(@edit[:vm_id]) @edit[:new][:server] = params[:server_id] if params[:server_id] end def evm_relationship_update return unless load_edit("evm_relationship_edit__new") evm_relationship_get_form_vars case params[:button] when "cancel" msg = _("%s was cancelled by the user") % "Edit Management Engine Relationship" if @edit[:explorer] add_flash(msg) @sb[:action] = nil replace_right_cell else render :update do |page| page.redirect_to :action=>'show', :id=>@record.id, :flash_msg=>msg end end when "save" svr = @edit[:new][:server] && @edit[:new][:server] != "" ? MiqServer.find(@edit[:new][:server]) : nil @record.miq_server = svr @record.save msg = _("%s saved") % "Management Engine Relationship" if @edit[:explorer] add_flash(msg) @sb[:action] = nil replace_right_cell else render :update do |page| page.redirect_to :action=>'show', :id=>@record.id,:flash_msg=>msg end end when "reset" @in_a_form = true if @edit[:explorer] @explorer = true evm_relationship add_flash(_("All changes have been reset"), :warning) replace_right_cell else render :update do |page| page.redirect_to :action=>'evm_relationship', :id=>@record.id, :flash_msg=>_("All changes have been reset"), :flash_warning=>true, :escape=>true end end end end def delete @lastaction = "delete" redirect_to :action => 'show_list', :layout=>false end def destroy find_by_id_filtered(VmOrTemplate, params[:id]).destroy redirect_to :action => 'list' end def profile_build session[:vm].resolve_profiles(session[:policies].keys).sort{|a,b| a["description"] <=> b["description"]}.each do | policy | @catinfo ||= Hash.new # Hash to hold category squashed states policy.each do | key, cat| if key == "description" if @catinfo[cat] == nil @catinfo[cat] = true # Set compressed if no entry present yet end end end end end def profile_toggle if params[:pressed] == "tag_cat_toggle" profile_build policy_escaped = j(params[:policy]) cat = params[:cat] render :update do |page| if @catinfo[cat] @catinfo[cat] = false page << javascript_show("cat_#{policy_escaped}_div") page << "$('#cat_#{policy_escaped}_icon').prop('src', '/images/tree/compress.png');" else @catinfo[cat] = true # Set squashed = true page << javascript_hide("cat_#{policy_escaped}_div") page << "$('#cat_#{policy_escaped}_icon').prop('src', '/images/tree/expand.png');" end end else add_flash(_("Button not yet implemented"), :error) render :partial => "shared/ajax/flash_msg_replace" end end def add_to_service @record = find_by_id_filtered(Vm, params[:id]) @svcs = Hash.new Service.all.each {|s| @svcs[s.name] = s.id } drop_breadcrumb( {:name=>"Add VM to a Service", :url=>"/vm/add_to_service"} ) @in_a_form = true end def add_vm_to_service @record = find_by_id_filtered(Vm, params[:id]) if params["cancel.x"] flash = _("Add VM \"%s\" to a Service was cancelled by the user") % @record.name redirect_to :action=>@lastaction, :id=>@record.id, :flash_msg=>flash else chosen = params[:chosen_service].to_i flash = _("%{model} \"%{name}\" successfully added to Service \"%{to_name}\"") % {:model=>ui_lookup(:model=>"Vm"), :name=>@record.name, :to_name=>Service.find(chosen).name} begin @record.add_to_vsc(Service.find(chosen).name) rescue StandardError => bang flash = _("Error during '%s': ") % "Add VM to service" << bang end redirect_to :action => @lastaction, :id=>@record.id, :flash_msg=>flash end end def remove_service assert_privileges(params[:pressed]) @record = find_by_id_filtered(Vm, params[:id]) begin @vervice_name = Service.find_by_name(@record.location).name @record.remove_from_vsc(@vervice_name) rescue StandardError => bang add_flash(_("Error during '%s': ") % "Remove VM from service" + bang.message, :error) else add_flash(_("VM successfully removed from service \"%s\"") % @vervice_name) end end def edit @record = find_by_id_filtered(VmOrTemplate, params[:id]) # Set the VM object set_form_vars build_edit_screen session[:changed] = false @tabs = [ ["edit", @record.id.to_s], ["edit", "Information"] ] @refresh_partial = "vm_common/form" end alias image_edit edit alias instance_edit edit alias vm_edit edit alias miq_template_edit edit def build_edit_screen drop_breadcrumb(:name => "Edit VM '" + @record.name + "'", :url => "/vm/edit") unless @explorer session[:edit] = @edit @in_a_form = true @tabs = [ ["edit", @record.id.to_s], ["edit", "Information"] ] end # AJAX driven routine to check for changes in ANY field on the form def form_field_changed return unless load_edit("vm_edit__#{params[:id]}") get_form_vars changed = (@edit[:new] != @edit[:current]) render :update do |page| # Use JS to update the display page.replace_html("main_div", :partial => "vm_common/form") if %w(allright left right).include?(params[:button]) page << javascript_for_miq_button_visibility(changed) if changed page << "miqSparkle(false);" end end def edit_vm return unless load_edit("vm_edit__#{params[:id]}") #reset @explorer if coming from explorer views @explorer = true if @edit[:explorer] get_form_vars case params[:button] when "cancel" if @edit[:explorer] add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model=>ui_lookup(:model=>@record.class.base_model.name), :name=>@record.name}) @record = @sb[:action] = nil replace_right_cell else add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "Vm"), :name => @record.name}) session[:flash_msgs] = @flash_array.dup render :update do |page| page.redirect_to(previous_breadcrumb_url) end end when "save" if @edit[:new][:parent] != -1 && @edit[:new][:kids].invert.include?(@edit[:new][:parent]) # Check if parent is a kid, if selected add_flash(_("Parent VM can not be one of the child VMs"), :error) @changed = session[:changed] = (@edit[:new] != @edit[:current]) build_edit_screen if @edit[:explorer] replace_right_cell else render :action=>"edit" end else current = @record.parents.length == 0 ? -1 : @record.parents.first.id # get current parent id chosen = @edit[:new][:parent].to_i # get the chosen parent id @record.custom_1 = @edit[:new][:custom_1] @record.description = @edit[:new][:description] # add vm description if current != chosen @record.remove_parent(@record.parents.first) unless current == -1 # Remove existing parent, if there is one @record.set_parent(VmOrTemplate.find(chosen)) unless chosen == -1 # Set new parent, if one was chosen end vms = @record.children # Get the VM's child VMs kids = @edit[:new][:kids].invert # Get the VM ids from the kids list box audit = {:event=>"vm_genealogy_change", :target_id=>@record.id, :target_class=>@record.class.base_class.name, :userid => session[:userid]} begin @record.save! vms.each { |v| @record.remove_child(v) if !kids.include?(v.id) } # Remove any VMs no longer in the kids list box kids.each_key { |k| @record.set_child(VmOrTemplate.find(k)) } # Add all VMs in kids hash, dups will not be re-added rescue StandardError => bang add_flash(_("Error during '%s': ") % "#{@record.class.base_model.name} update" << bang.message, :error) AuditEvent.failure(audit.merge(:message=>"[#{@record.name} -- #{@record.location}] Update returned: #{bang}")) else flash = _("%{model} \"%{name}\" was saved") % {:model=>ui_lookup(:model=>@record.class.base_model.name), :name=>@record.name} AuditEvent.success(build_saved_vm_audit(@record)) end params[:id] = @record.id.to_s # reset id in params for show @record = nil add_flash(flash) if @edit[:explorer] @sb[:action] = nil replace_right_cell else session[:flash_msgs] = @flash_array.dup render :update do |page| page.redirect_to(previous_breadcrumb_url) end end end when "reset" edit add_flash(_("All changes have been reset"), :warning) session[:flash_msgs] = @flash_array.dup get_vm_child_selection if params["right.x"] || params["left.x"] || params["allright.x"] @changed = session[:changed] = false build_edit_screen if @edit[:explorer] replace_right_cell else render :update do |page| page.redirect_to(:action => "edit", :controller => "vm", :id => params[:id]) end end else @changed = session[:changed] = (@edit[:new] != @edit[:current]) build_edit_screen if @edit[:explorer] replace_right_cell else render :action=>"edit" end end end def set_checked_items session[:checked_items] = Array.new if params[:all_checked] ids = params[:all_checked].split(',') ids.each do |id| id = id.split('-') id = id[1].slice(0,id[1].length-1) session[:checked_items].push(id) unless session[:checked_items].include?(id) end end @lastaction = "set_checked_items" render :nothing => true end def scan_history @vm = @record = identify_record(params[:id], VmOrTemplate) @scan_history = ScanHistory.find_by_vm_or_template_id(@record.id) @listicon = "scan_history" @showtype = "scan_history" @lastaction = "scan_history" @gtl_url = "/vm/scan_history/?" @no_checkboxes = true @showlinks = true @view, @pages = get_view(ScanHistory, :parent=>@record) # Get the records (into a view) and the paginator @current_page = @pages[:current] if @pages != nil # save the current page number if @scan_history.nil? drop_breadcrumb( {:name=>@record.name + " (Analysis History)", :url=>"/vm/#{@record.id}"} ) else drop_breadcrumb( {:name=>@record.name + " (Analysis History)", :url=>"/vm/scan_history/#{@scan_history.vm_or_template_id}"} ) end # Came in from outside show_list partial if params[:ppsetting] || params[:searchtag] || params[:entry] || params[:sort_choice] render :update do |page| page.replace_html("gtl_div", :partial=>"layouts/gtl") page << "miqSparkle(false);" # Need to turn off sparkle in case original ajax element gets replaced end else if @explorer || request.xml_http_request? # Is this an Ajax request? @sb[:action] = params[:action] @refresh_partial = "layouts/#{@showtype}" replace_right_cell else render :action => 'show' end end end def scan_histories @vm = @record = identify_record(params[:id], VmOrTemplate) @explorer = true if request.xml_http_request? # Ajax request means in explorer @scan_history = ScanHistory.find_by_vm_or_template_id(@record.id) if @scan_history == nil redirect_to :action=>"scan_history", :flash_msg=>_("Error: Record no longer exists in the database"), :flash_error=>true return end @lastaction = "scan_histories" @sb[:action] = params[:action] if params[:show] != nil || params[:x_show] != nil id = params[:show] ? params[:show] : params[:x_show] @item = ScanHistory.find(from_cid(id)) drop_breadcrumb( {:name=>time_ago_in_words(@item.started_on.in_time_zone(Time.zone)).titleize, :url=>"/vm/scan_history/#{@scan_history.vm_or_template_id}?show=#{@item.id}"} ) @view = get_db_view(ScanHistory) # Instantiate the MIQ Report view object show_item else drop_breadcrumb( {:name=>time_ago_in_words(@scan_history.started_on.in_time_zone(Time.zone)).titleize, :url=>"/vm/show/#{@scan_history.vm_or_template_id}"}, true ) @listicon = "scan_history" show_details(ScanHistory) end end # Tree node selected in explorer def tree_select @explorer = true @lastaction = "explorer" @sb[:action] = nil # Need to see if record is unauthorized if it's a VM node @nodetype, id = params[:id].split("_").last.split("-") @vm = @record = identify_record(id, VmOrTemplate) if ["Vm", "MiqTemplate"].include?(TreeBuilder.get_model_for_prefix(@nodetype)) && !@record # Handle filtered tree nodes if x_tree[:type] == :filter && !["Vm", "MiqTemplate"].include?(TreeBuilder.get_model_for_prefix(@nodetype)) search_id = @nodetype == "root" ? 0 : from_cid(id) adv_search_build(vm_model_from_active_tree(x_active_tree)) session[:edit] = @edit # Set because next method will restore @edit from session listnav_search_selected(search_id) unless params.has_key?(:search_text) # Clear or set the adv search filter if @edit[:adv_search_applied] && MiqExpression.quick_search?(@edit[:adv_search_applied][:exp]) && %w(reload tree_select).include?(params[:action]) self.x_node = params[:id] quick_search_show return end end unless @unauthorized self.x_node = params[:id] replace_right_cell else add_flash("User is not authorized to view #{ui_lookup(:model=>@record.class.base_model.to_s)} \"#{@record.name}\"", :error) render :partial => "shared/tree_select_error", :locals => {:options => {:select_node => x_node}} end end # Accordion selected in explorer def accordion_select @lastaction = "explorer" self.x_active_accord = params[:id] self.x_active_tree = "#{params[:id]}_tree" @sb[:action] = nil replace_right_cell end private ############################ # First time thru, kick off the acquire ticket task def console_before_task(console_type) @vm = @record = identify_record(params[:id], VmOrTemplate) api_version = @record.ext_management_system.api_version.to_s if !api_version.starts_with?("5") add_flash(_("Console access failed: %s") % "Unsupported Provider API version #{api_version}", :error) else task_id = @record.remote_console_acquire_ticket_queue(console_type.to_sym, session[:userid], MiqServer.my_server.id) unless task_id.is_a?(Fixnum) add_flash(_("Console access failed: %s") % "Task start failed: ID [#{task_id.inspect}]", :error) end end if @flash_array render :partial => "shared/ajax/flash_msg_replace" else initiate_wait_for_task(:task_id => task_id) # Spin the Q until the task is done end end # Task complete, show error or launch console using VNC/MKS/VMRC task info def console_after_task(console_type) miq_task = MiqTask.find(params[:task_id]) if miq_task.status == "Error" || miq_task.task_results.blank? add_flash(_("Console access failed: %s") % miq_task.message, :error) else @vm = @record = identify_record(params[:id], VmOrTemplate) case console_type when "mks" @sb[:mks] = miq_task.task_results when "vmrc" @sb[:vmrc_ticket] = miq_task.task_results end end render :update do |page| if @flash_array page.replace(:flash_msg_div, :partial=>"layouts/flash_msg") page << "miqSparkle(false);" elsif console_type == "vnc" # VNC - send down the miqvncplugin and launch it page << "if (typeof miqvncplugin == 'undefined')" page.insert_html(:after, "page_footer_div", :partial=>"layouts/miq_vnc_plugin") pwd, host, port, proxy, proxy_port = miq_task.task_results # Split array into parms if proxy.blank? || proxy_port.blank? page << "miqLaunchMiqVncConsole('#{pwd}', '#{host}', #{port});" else page << "miqLaunchMiqVncConsole('#{pwd}', '#{host}', #{port}, '#{proxy}', #{proxy_port});" end page << "miqSparkle(false);" else # MKS or VMRC - open a new web page page << "miqSparkle(false);" page << "window.open('#{url_for :controller => controller_name, :action => 'launch_vmware_console', :id => @record.id}');" end end end # Check for parent nodes missing from vandt tree and return them if any def open_parent_nodes(record) add_nodes = nil existing_node = nil # Init var if record.orphaned? || record.archived? parents = [{:type=>"x", :id=>"#{record.orphaned ? "orph" : "arch"}"}] else if x_active_tree == :instances_tree parents = record.kind_of?(VmCloud) && record.availability_zone ? [record.availability_zone] : [record.ext_management_system] else parents = record.parent_blue_folders({:exclude_non_display_folders=>true}) end end # Go up thru the parents and find the highest level unopened, mark all as opened along the way unless parents.empty? || # Skip if no parents or parent already open x_tree[:open_nodes].include?(x_build_node_id(parents.last)) parents.reverse.each do |p| p_node = x_build_node_id(p) unless x_tree[:open_nodes].include?(p_node) x_tree[:open_nodes].push(p_node) existing_node = p_node end end end # Start at the EMS if record has an EMS and it's not opened yet if record.ext_management_system ems_node = x_build_node_id(record.ext_management_system) unless x_tree[:open_nodes].include?(ems_node) x_tree[:open_nodes].push(ems_node) existing_node = ems_node end end add_nodes = {:key => existing_node, :children => tree_add_child_nodes(existing_node)} if existing_node return add_nodes end # Get all info for the node about to be displayed def get_node_info(treenodeid) #resetting action that was stored during edit to determine what is being edited @sb[:action] = nil @nodetype, id = valid_active_node(treenodeid).split("_").last.split("-") model, title = case x_active_tree.to_s when "images_filter_tree" ["TemplateCloud", "Images"] when "images_tree" ["TemplateCloud", "Images by Provider"] when "instances_filter_tree" ["VmCloud", "Instances"] when "instances_tree" ["VmCloud", "Instances by Provider"] when "vandt_tree" ["VmOrTemplate", "VMs & Templates"] when "vms_instances_filter_tree" ["Vm", "VMs & Instances"] when "templates_images_filter_tree" ["MiqTemplate", "Templates & Images"] when "templates_filter_tree" ["TemplateInfra", "Templates"] when "vms_filter_tree" ["VmInfra", "VMs"] else [nil, nil] end case TreeBuilder.get_model_for_prefix(@nodetype) when "Vm", "MiqTemplate" # VM or Template record, show the record show_record(from_cid(id)) if @record.nil? self.x_node = "root" get_node_info("root") return else @right_cell_text = _("%{model} \"%{name}\"") % {:name=>@record.name, :model=>"#{ui_lookup(:model => model && model != "VmOrTemplate" ? model : TreeBuilder.get_model_for_prefix(@nodetype))}"} end else # Get list of child VMs of this node options = {:model=>model} if x_node == "root" # TODO: potential to move this into a model with a scope built into it options[:where_clause] = ["vms.type IN (?)", VmInfra::SUBCLASSES + TemplateInfra::SUBCLASSES] if x_active_tree == :vandt_tree process_show_list(options) # Get all VMs & Templates # :model=>ui_lookup(:models=>"VmOrTemplate")) # TODO: Change ui_lookup/dictionary to handle VmOrTemplate, returning VMs And Templates @right_cell_text = _("All %s") % title ? "#{title}" : "VMs & Templates" else if TreeBuilder.get_model_for_prefix(@nodetype) == "Hash" options[:where_clause] = ["vms.type IN (?)", VmInfra::SUBCLASSES + TemplateInfra::SUBCLASSES] if x_active_tree == :vandt_tree if id == "orph" options[:where_clause] = MiqExpression.merge_where_clauses(options[:where_clause], VmOrTemplate::ORPHANED_CONDITIONS) process_show_list(options) @right_cell_text = "Orphaned #{model ? ui_lookup(:models => model) : "VMs & Templates"}" elsif id == "arch" options[:where_clause] = MiqExpression.merge_where_clauses(options[:where_clause], VmOrTemplate::ARCHIVED_CONDITIONS) process_show_list(options) @right_cell_text = "Archived #{model ? ui_lookup(:models => model) : "VMs & Templates"}" end elsif TreeBuilder.get_model_for_prefix(@nodetype) == "MiqSearch" process_show_list(options) # Get all VMs & Templates @right_cell_text = _("All %s") % model ? "#{ui_lookup(:models=>model)}" : "VMs & Templates" else rec = TreeBuilder.get_model_for_prefix(@nodetype).constantize.find(from_cid(id)) options.merge!({:association=>"#{@nodetype == "az" ? "vms" : "all_vms_and_templates"}", :parent=>rec}) process_show_list(options) model_name = @nodetype == "d" ? "Datacenter" : ui_lookup(:model=>rec.class.base_class.to_s) @is_redhat = case model_name when 'Datacenter' then EmsInfra.find(rec.ems_id).type == 'EmsRedhat' when 'Provider' then rec.type == 'EmsRedhat' else false end # @right_cell_text = "#{ui_lookup(:models=>"VmOrTemplate")} under #{model_name} \"#{rec.name}\"" # TODO: Change ui_lookup/dictionary to handle VmOrTemplate, returning VMs And Templates @right_cell_text = "#{model ? ui_lookup(:models => model) : "VMs & Templates"} under #{model_name} \"#{rec.name}\"" end end # Add adv search filter to header @right_cell_text += @edit[:adv_search_applied][:text] if @edit && @edit[:adv_search_applied] end if @edit && @edit.fetch_path(:adv_search_applied, :qs_exp) # If qs is active, save it in history x_history_add_item(:id=>x_node, :qs_exp=>@edit[:adv_search_applied][:qs_exp], :text=>@right_cell_text) else x_history_add_item(:id=>treenodeid, :text=>@right_cell_text) # Add to history pulldown array end # After adding to history, add name filter suffix if showing a list unless ["Vm", "MiqTemplate"].include?(TreeBuilder.get_model_for_prefix(@nodetype)) unless @search_text.blank? @right_cell_text += _(" (Names with \"%s\")") % @search_text end end end # Replace the right cell of the explorer def replace_right_cell(action=nil) @explorer = true @sb[:action] = action if !action.nil? if @sb[:action] || params[:display] partial, action, @right_cell_text = set_right_cell_vars # Set partial name, action and cell header end if !@in_a_form && !@sb[:action] get_node_info(x_node) #set @delete_node since we don't rebuild vm tree @delete_node = params[:id] if @replace_trees #get_node_info might set this type, id = x_node.split("_").last.split("-") record_showing = type && ["Vm", "MiqTemplate"].include?(TreeBuilder.get_model_for_prefix(type)) c_buttons, c_xml = build_toolbar_buttons_and_xml(center_toolbar_filename) # Use vm or template tb if record_showing cb_buttons, cb_xml = build_toolbar_buttons_and_xml("custom_buttons_tb") v_buttons, v_xml = build_toolbar_buttons_and_xml("x_summary_view_tb") else v_buttons, v_xml = build_toolbar_buttons_and_xml("x_gtl_view_tb") end elsif ["compare","drift"].include?(@sb[:action]) @in_a_form = true # Turn on Cancel button c_buttons, c_xml = build_toolbar_buttons_and_xml("#{@sb[:action]}_center_tb") v_buttons, v_xml = build_toolbar_buttons_and_xml("#{@sb[:action]}_view_tb") elsif @sb[:action] == "performance" c_buttons, c_xml = build_toolbar_buttons_and_xml("x_vm_performance_tb") elsif @sb[:action] == "drift_history" c_buttons, c_xml = build_toolbar_buttons_and_xml("drifts_center_tb") # Use vm or template tb elsif ["snapshot_info","vmtree_info"].include?(@sb[:action]) c_buttons, c_xml = build_toolbar_buttons_and_xml("x_vm_center_tb") # Use vm or template tb end h_buttons, h_xml = build_toolbar_buttons_and_xml("x_history_tb") unless @in_a_form unless x_active_tree == :vandt_tree # Clicked on right cell record, open the tree enough to show the node, if not already showing if params[:action] == "x_show" && @record && # Showing a record !@in_a_form && # Not in a form x_tree[:type] != :filter # Not in a filter tree add_nodes = open_parent_nodes(@record) # Open the parent nodes of selected record, if not open end end # Build presenter to render the JS command for the tree update presenter = ExplorerPresenter.new( :active_tree => x_active_tree, :temp => @temp, :add_nodes => add_nodes, # Update the tree with any new nodes :delete_node => @delete_node, # Remove a new node from the tree ) r = proc { |opts| render_to_string(opts) } add_ajax = false if record_showing presenter[:set_visible_elements][:form_buttons_div] = false path_dir = @record.kind_of?(VmCloud) || @record.kind_of?(TemplateCloud) ? "vm_cloud" : "vm_common" presenter[:update_partials][:main_div] = r[:partial=>"#{path_dir}/main", :locals=>{:controller=>'vm'}] elsif @in_a_form partial_locals = {:controller=>'vm'} partial_locals[:action_url] = @lastaction if partial == 'layouts/x_gtl' presenter[:update_partials][:main_div] = r[:partial=>partial, :locals=>partial_locals] locals = {:action_url => action, :record_id => @record ? @record.id : nil} if ['clone', 'migrate', 'miq_request_new', 'pre_prov', 'publish', 'reconfigure', 'retire'].include?(@sb[:action]) locals[:no_reset] = true # don't need reset button on the screen locals[:submit_button] = ['clone', 'migrate', 'publish', 'reconfigure', 'pre_prov'].include?(@sb[:action]) # need submit button on the screen locals[:continue_button] = ['miq_request_new'].include?(@sb[:action]) # need continue button on the screen update_buttons(locals) if @edit && @edit[:buttons].present? presenter[:clear_tree_cookies] = "prov_trees" end if ['snapshot_add'].include?(@sb[:action]) locals[:no_reset] = true locals[:create_button] = true end if @record.kind_of?(Dialog) @record.dialog_fields.each do |field| if %w(DialogFieldDateControl DialogFieldDateTimeControl).include?(field.type) presenter[:build_calendar] = { :date_from => field.show_past_dates ? nil : Time.now.in_time_zone(session[:user_tz]).to_i * 1000 } end end end if %w(ownership protect reconfigure retire tag).include?(@sb[:action]) locals[:multi_record] = true # need save/cancel buttons on edit screen even tho @record.id is not there locals[:record_id] = @sb[:rec_id] || @edit[:object_ids][0] if @sb[:action] == "tag" unless @sb[:action] == 'ownership' presenter[:build_calendar] = { :date_from => Time.now.in_time_zone(@tz).to_i * 1000, :date_to => nil, } end end add_ajax = true if ['compare', 'drift'].include?(@sb[:action]) presenter[:update_partials][:custom_left_cell_div] = r[ :partial => 'layouts/listnav/x_compare_sections', :locals => {:truncate_length => 23}] presenter[:cell_a_view] = 'custom' end elsif @sb[:action] || params[:display] partial_locals = { :controller => ['ontap_storage_volumes', 'ontap_file_shares', 'ontap_logical_disks', 'ontap_storage_systems'].include?(@showtype) ? @showtype.singularize : 'vm' } if partial == 'layouts/x_gtl' partial_locals[:action_url] = @lastaction presenter[:miq_parent_id] = @record.id # Set parent rec id for JS function miqGridSort to build URL presenter[:miq_parent_class] = request[:controller] # Set parent class for URL also end presenter[:update_partials][:main_div] = r[:partial=>partial, :locals=>partial_locals] add_ajax = true presenter[:build_calendar] = true else presenter[:update_partials][:main_div] = r[:partial=>'layouts/x_gtl'] end presenter[:ajax_action] = { :controller => request.parameters["controller"], :action => @ajax_action, :record_id => @record.id } if add_ajax && ['performance','timeline'].include?(@sb[:action]) # Replace the searchbox presenter[:replace_partials][:adv_searchbox_div] = r[ :partial => 'layouts/x_adv_searchbox', :locals => {:nameonly => ([:images_tree, :instances_tree, :vandt_tree].include?(x_active_tree))} ] # Clear the JS gtl_list_grid var if changing to a type other than list presenter[:clear_gtl_list_grid] = @gtl_type && @gtl_type != 'list' presenter[:clear_tree_cookies] = "edit_treeOpenStatex" if @sb[:action] == "policy_sim" # Handle bottom cell if @pages || @in_a_form if @pages && !@in_a_form @ajax_paging_buttons = true # FIXME: this should not be done this way if @sb[:action] && @record # Came in from an action link presenter[:update_partials][:paging_div] = r[ :partial => 'layouts/x_pagingcontrols', :locals => { :action_url => @sb[:action], :action_method => @sb[:action], # FIXME: action method and url the same?! :action_id => @record.id } ] else presenter[:update_partials][:paging_div] = r[:partial => 'layouts/x_pagingcontrols'] end presenter[:set_visible_elements][:form_buttons_div] = false presenter[:set_visible_elements][:pc_div_1] = true elsif @in_a_form if @sb[:action] == 'dialog_provision' presenter[:update_partials][:form_buttons_div] = r[ :partial => 'layouts/x_dialog_buttons', :locals => { :action_url => action, :record_id => @edit[:rec_id], } ] else presenter[:update_partials][:form_buttons_div] = r[:partial => 'layouts/x_edit_buttons', :locals => locals] end presenter[:set_visible_elements][:pc_div_1] = false presenter[:set_visible_elements][:form_buttons_div] = true end presenter[:expand_collapse_cells][:c] = 'expand' else presenter[:expand_collapse_cells][:c] = 'collapse' end presenter[:right_cell_text] = @right_cell_text # Rebuild the toolbars presenter[:set_visible_elements][:history_buttons_div] = h_buttons && h_xml presenter[:set_visible_elements][:center_buttons_div] = c_buttons && c_xml presenter[:set_visible_elements][:view_buttons_div] = v_buttons && v_xml presenter[:set_visible_elements][:custom_buttons_div] = cb_buttons && cb_xml presenter[:reload_toolbars][:history] = {:buttons => h_buttons, :xml => h_xml} if h_buttons && h_xml presenter[:reload_toolbars][:center] = {:buttons => c_buttons, :xml => c_xml} if c_buttons && c_xml presenter[:reload_toolbars][:view] = {:buttons => v_buttons, :xml => v_xml} if v_buttons && v_xml presenter[:reload_toolbars][:custom] = {:buttons => cb_buttons, :xml => cb_xml} if cb_buttons && cb_xml presenter[:expand_collapse_cells][:a] = h_buttons || c_buttons || v_buttons ? 'expand' : 'collapse' presenter[:miq_record_id] = @record ? @record.id : nil # Hide/show searchbox depending on if a list is showing presenter[:set_visible_elements][:adv_searchbox_div] = !(@record || @in_a_form) presenter[:osf_node] = x_node # Open, select, and focus on this node # Save open nodes, if any were added presenter[:save_open_states_trees] = [x_active_tree.to_s] if add_nodes presenter[:set_visible_elements][:blocker_div] = false unless @edit && @edit[:adv_search_open] presenter[:set_visible_elements][:quicksearchbox] = false presenter[:lock_unlock_trees][x_active_tree] = @in_a_form && @edit # Render the JS responses to update the explorer screen render :js => presenter.to_html end # get the host that this vm belongs to def get_host_for_vm(vm) if vm.host @hosts = Array.new @hosts.push vm.host end end # Set form variables for edit def set_form_vars @edit = Hash.new @edit[:vm_id] = @record.id @edit[:new] = Hash.new @edit[:current] = Hash.new @edit[:key] = "vm_edit__#{@record.id || "new"}" @edit[:explorer] = true if params[:action] == "x_button" || session.fetch_path(:edit, :explorer) @edit[:current][:custom_1] = @edit[:new][:custom_1] = @record.custom_1.to_s @edit[:current][:description] = @edit[:new][:description] = @record.description.to_s @edit[:pchoices] = Hash.new # Build a hash for the parent choices box VmOrTemplate.all.each { |vm| @edit[:pchoices][vm.name + " -- #{vm.location}"] = vm.id unless vm.id == @record.id } # Build a hash for the parents to choose from, not matching current VM @edit[:pchoices]['"no parent"'] = -1 # Add "no parent" entry if @record.parents.length == 0 # Set the currently selected parent @edit[:new][:parent] = -1 else @edit[:new][:parent] = @record.parents.first.id end vms = @record.children # Get the child VMs @edit[:new][:kids] = Hash.new vms.each { |vm| @edit[:new][:kids][vm.name + " -- #{vm.location}"] = vm.id } # Build a hash for the kids list box @edit[:choices] = Hash.new VmOrTemplate.all.each { |vm| @edit[:choices][vm.name + " -- #{vm.location}"] = vm.id if vm.parents.length == 0 } # Build a hash for the VMs to choose from, only if they have no parent @edit[:new][:kids].each_key { |key| @edit[:choices].delete(key) } # Remove any VMs that are in the kids list box from the choices @edit[:choices].delete(@record.name + " -- #{@record.location}") # Remove the current VM from the choices list @edit[:current][:parent] = @edit[:new][:parent] @edit[:current][:kids] = @edit[:new][:kids].dup session[:edit] = @edit end #set partial name and cell header for edit screens def set_right_cell_vars name = @record ? @record.name.to_s.gsub(/'/,"\\\\'") : "" # If record, get escaped name table = request.parameters["controller"] case @sb[:action] when "compare","drift" partial = "layouts/#{@sb[:action]}" if @sb[:action] == "compare" header = _("Compare %s") % ui_lookup(:model => @sb[:compare_db]) else header = _("Drift for %{model} \"%{name}\"") % {:name => name, :model => ui_lookup(:model => @sb[:compare_db])} end action = nil when "clone","migrate","publish" partial = "miq_request/prov_edit" header = _("%{task} %{model}") % {:task=>@sb[:action].capitalize, :model=>ui_lookup(:table => table)} action = "prov_edit" when "dialog_provision" partial = "shared/dialogs/dialog_provision" header = @right_cell_text action = "dialog_form_button_pressed" when "edit" partial = "vm_common/form" header = _("Editing %{model} \"%{name}\"") % {:name=>name, :model=>ui_lookup(:table => table)} action = "edit_vm" when "evm_relationship" partial = "vm_common/evm_relationship" header = _("Edit CFME Server Relationship for %{model} \"%{name}\"") % {:model=>ui_lookup(:table => table), :name => name} action = "evm_relationship_update" #when "miq_request_new" # partial = "miq_request/prov_edit" # header = _("Provision %s") % ui_lookup(:models=>"Vm") # action = "prov_edit" when "miq_request_new" partial = "miq_request/pre_prov" typ = request.parameters[:controller] == "vm_cloud" ? "an #{ui_lookup(:table => "template_cloud")}" : "a #{ui_lookup(:table => "template_infra")}" header = _("Provision %{model} - Select %{typ}") % {:model=>ui_lookup(:tables => table), :typ => typ} action = "pre_prov" when "pre_prov" partial = "miq_request/prov_edit" header = _("Provision %s") % ui_lookup(:tables => table) action = "pre_prov_continue" when "pre_prov_continue" partial = "miq_request/prov_edit" header = _("Provision %s") % ui_lookup(:tables => table) action = "prov_edit" when "ownership" partial = "shared/views/ownership" header = _("Set Ownership for %s") % ui_lookup(:table => table) action = "ownership_update" when "performance" partial = "layouts/performance" header = _("Capacity & Utilization data for %{model} \"%{name}\"") % {:model=>ui_lookup(:table => table), :name => name} x_history_add_item(:id=>x_node, :text=>header, :button=>params[:pressed], :display=>params[:display]) action = nil when "policy_sim" if params[:action] == "policies" partial = "vm_common/policies" header = _("%s Policy Simulation") % ui_lookup(:table => table) action = nil else partial = "layouts/policy_sim" header = _("%s Policy Simulation") % ui_lookup(:table => table) action = nil end when "protect" partial = "layouts/protect" header = _("%s Policy Assignment") % ui_lookup(:table => table) action = "protect" when "reconfigure" partial = "vm_common/reconfigure" header = _("Reconfigure %s") % ui_lookup(:table => table) action = "reconfigure_update" when "retire" partial = "shared/views/retire" header = _("Set/Remove retirement date for %s") % ui_lookup(:table => table) action = "retire" when "right_size" partial = "vm_common/right_size" header = _("Right Size Recommendation for %{model} \"%{name}\"") % {:name=>name, :model=>ui_lookup(:table => table)} action = nil when "tag" partial = "layouts/tagging" header = _("Edit Tags for %s") % ui_lookup(:table => table) action = "tagging_edit" when "snapshot_add" partial = "vm_common/snap" header = _("Adding a new %s") % ui_lookup(:model => "Snapshot") action = "snap_vm" when "timeline" partial = "layouts/tl_show" header = _("Timelines for %{model} \"%{name}\"") % {:model=>ui_lookup(:table => table), :name=>name} x_history_add_item(:id=>x_node, :text=>header, :button=>params[:pressed]) action = nil else # now take care of links on summary screen if ["details","ontap_storage_volumes","ontap_file_shares","ontap_logical_disks","ontap_storage_systems"].include?(@showtype) partial = "layouts/x_gtl" elsif @showtype == "item" partial = "layouts/item" elsif @showtype == "drift_history" partial = "layouts/#{@showtype}" else partial = "#{@showtype == "compliance_history" ? "shared/views" : "vm_common"}/#{@showtype}" end if @showtype == "item" header = _("%{action} \"%{item_name}\" for %{model} \"%{name}\"") % {:model=>ui_lookup(:table => table), :name=>name, :item_name=>@item.kind_of?(ScanHistory) ? @item.started_on.to_s : @item.name, :action=>Dictionary::gettext(@sb[:action], :type=>:ui_action, :notfound=>:titleize).singularize} x_history_add_item(:id=>x_node, :text=>header, :action=>@sb[:action], :item=>@item.id) else header = _("\"%{action}\" for %{model} \"%{name}\"") % {:model=>ui_lookup(:table => table), :name=>name, :action=>Dictionary::gettext(@sb[:action], :type=>:ui_action, :notfound=>:titleize)} if @display && @display != "main" x_history_add_item(:id=>x_node, :text=>header, :display=>@display) else x_history_add_item(:id=>x_node, :text=>header, :action=>@sb[:action]) if @sb[:action] != "drift_history" end end action = nil end return partial,action,header end def get_vm_child_selection if params["right.x"] || params[:button] == "right" if params[:kids_chosen] == nil add_flash(_("No %s were selected to move right") % "VMs", :error) else kids = @edit[:new][:kids].invert params[:kids_chosen].each do |kc| if @edit[:new][:kids].has_value?(kc.to_i) @edit[:choices][kids[kc.to_i]] = kc.to_i @edit[:new][:kids].delete(kids[kc.to_i]) end end end elsif params["left.x"] || params[:button] == "left" if params[:choices_chosen] == nil add_flash(_("No %s were selected to move left") % "VMs", :error) else kids = @edit[:choices].invert params[:choices_chosen].each do |cc| if @edit[:choices].has_value?(cc.to_i) @edit[:new][:kids][kids[cc.to_i]] = cc.to_i @edit[:choices].delete(kids[cc.to_i]) end end end elsif params["allright.x"] || params[:button] == "allright" if @edit[:new][:kids].length == 0 add_flash(_("No child VMs to move right, no action taken"), :error) else @edit[:new][:kids].each do |key, value| @edit[:choices][key] = value end @edit[:new][:kids].clear end end end # Get variables from edit form def get_form_vars @record = VmOrTemplate.find_by_id(@edit[:vm_id]) @edit[:new][:custom_1] = params[:custom_1] if params[:custom_1] @edit[:new][:description] = params[:description] if params[:description] @edit[:new][:parent] = params[:chosen_parent].to_i if params[:chosen_parent] #if coming from explorer get_vm_child_selection if ["allright","left","right"].include?(params[:button]) end # Build the audit object when a record is saved, including all of the changed fields def build_saved_vm_audit(vm) msg = "[#{vm.name} -- #{vm.location}] Record saved (" event = "vm_genealogy_change" i = 0 @edit[:new].each_key do |k| if @edit[:new][k] != @edit[:current][k] msg = msg + ", " if i > 0 i += 1 if k == :kids #if @edit[:new][k].is_a?(Hash) msg = msg + k.to_s + ":[" + @edit[:current][k].keys.join(",") + "] to [" + @edit[:new][k].keys.join(",") + "]" elsif k == :parent msg = msg + k.to_s + ":[" + @edit[:pchoices].invert[@edit[:current][k]] + "] to [" + @edit[:pchoices].invert[@edit[:new][k]] + "]" else msg = msg + k.to_s + ":[" + @edit[:current][k].to_s + "] to [" + @edit[:new][k].to_s + "]" end end end msg = msg + ")" audit = {:event=>event, :target_id=>vm.id, :target_class=>vm.class.base_class.name, :userid => session[:userid], :message=>msg} end # get the sort column for the detail lists that was clicked on, else use the current one def get_detail_sort_col if params[:page]==nil && params[:type] == nil && params[:searchtag] == nil # paging, gtltype change, or search tag did not come in if params[:sortby] == nil # no column clicked, reset to first column, ascending @detail_sortcol = 0 @detail_sortdir = "ASC" else if @detail_sortcol == params[:sortby].to_i # if same column was selected @detail_sortdir = @detail_sortdir == "ASC" ? "DESC" : "ASC" # switch around ascending/descending else @detail_sortdir = "ASC" end @detail_sortcol = params[:sortby].to_i end end # in case sort column is not set, set the defaults if @detail_sortcol == nil @detail_sortcol = 0 @detail_sortdir = "ASC" end return @detail_sortcol end # Gather up the vm records from the DB def get_vms(selected=nil) page = params[:page] == nil ? 1 : params[:page].to_i @current_page = page @items_per_page = @settings[:perpage][@gtl_type.to_sym] # Get the per page setting for this gtl type if selected # came in with a list of selected ids (i.e. checked vms) @record_pages, @records = paginate(:vms, :per_page => @items_per_page, :order => @col_names[get_sort_col] + " " + @sortdir, :conditions=>["id IN (?)", selected]) else # getting ALL vms @record_pages, @records = paginate(:vms, :per_page => @items_per_page, :order => @col_names[get_sort_col] + " " + @sortdir) end end def identify_record(id, klass = self.class.model) record = super # Need to find the unauthorized record if in explorer if record.nil? && @explorer record = klass.find_by_id(from_cid(id)) @unauthorized = true unless record.nil? end record end def update_buttons(locals) locals[:continue_button] = locals[:submit_button] = false locals[:continue_button] = true if @edit[:buttons].include?(:continue) locals[:submit_button] = true if @edit[:buttons].include?(:submit) end end Console: initial implementation steps. (transferred from ManageIQ/manageiq@bd791e517d3abb1df7a809b89be20d4cf932799b) module VmCommon extend ActiveSupport::Concern # handle buttons pressed on the button bar def button @edit = session[:edit] # Restore @edit for adv search box params[:page] = @current_page if @current_page != nil # Save current page for list refresh @refresh_div = "main_div" # Default div for button.rjs to refresh custom_buttons if params[:pressed] == "custom_button" perf_chart_chooser if params[:pressed] == "perf_reload" perf_refresh_data if params[:pressed] == "perf_refresh" remove_service if params[:pressed] == "remove_service" return if ["custom_button"].include?(params[:pressed]) # custom button screen, so return, let custom_buttons method handle everything # VM sub-screen is showing, so return return if ["perf_reload"].include?(params[:pressed]) && @flash_array == nil if @flash_array == nil # if no button handler ran, show not implemented msg add_flash(_("Button not yet implemented"), :error) @refresh_partial = "layouts/flash_msg" @refresh_div = "flash_msg_div" else # Figure out what was showing to refresh it if @lastaction == "show" && ["vmtree"].include?(@showtype) @refresh_partial = @showtype elsif @lastaction == "show" && ["config"].include?(@showtype) @refresh_partial = @showtype elsif @lastaction == "show_list" # default to the gtl_type already set else @refresh_partial = "layouts/flash_msg" @refresh_div = "flash_msg_div" end end @vm = @record = identify_record(params[:id], VmOrTemplate) unless @lastaction == "show_list" if !@flash_array.nil? && @single_delete render :update do |page| page.redirect_to :action => 'show_list', :flash_msg=>@flash_array[0][:message] # redirect to build the retire screen end elsif params[:pressed].ends_with?("_edit") if @redirect_controller render :update do |page| page.redirect_to :controller=>@redirect_controller, :action=>@refresh_partial, :id=>@redirect_id, :org_controller=>@org_controller end else render :update do |page| page.redirect_to :action=>@refresh_partial, :id=>@redirect_id end end else if @refresh_div == "main_div" && @lastaction == "show_list" replace_gtl_main_div else if @refresh_div == "flash_msg_div" render :partial => "shared/ajax/flash_msg_replace" else options partial_replace(@refresh_div, "vm_common/#{@refresh_partial}") end end end end def show_timeline db = get_rec_cls @display = "timeline" session[:tl_record_id] = params[:id] if params[:id] @record = find_by_id_filtered(db, from_cid(session[:tl_record_id])) @timeline = @timeline_filter = true @lastaction = "show_timeline" tl_build_timeline # Create the timeline report drop_breadcrumb( {:name=>"Timelines", :url=>"/#{db}/show_timeline/#{@record.id}?refresh=n"} ) if @explorer @refresh_partial = "layouts/tl_show" if params[:refresh] @sb[:action] = "timeline" replace_right_cell end end end alias image_timeline show_timeline alias instance_timeline show_timeline alias vm_timeline show_timeline alias miq_template_timeline show_timeline # Launch a VM console def console console_type = get_vmdb_config.fetch_path(:server, :remote_console_type).downcase unless params[:task_id] console_before_task(console_type) else console_after_task(console_type) end end alias vmrc_console console # VMRC needs its own URL for RBAC checking alias vnc_console console # VNC needs its own URL for RBAC checking def launch_vmware_console console_type = get_vmdb_config.fetch_path(:server, :remote_console_type).downcase @vm = @record = identify_record(params[:id], VmOrTemplate) case console_type when "mks" @mks_version = get_vmdb_config[:server][:mks_version] @mks = @sb[:mks] when "vmrc" @vmrc = Hash.new @vmrc[:host] = @record.ext_management_system.ipaddress || @record.ext_management_system.hostname @vmrc[:vmid] = @record.ems_ref @vmrc[:ticket] = @sb[:vmrc_ticket] @vmrc[:api_version] = @record.ext_management_system.api_version.to_s @vmrc[:os] = browser_info(:os).downcase end render :action=>"console" end def launch_novnc_console @vnc = {} @vnc[:password], @vnc[:host], @vnc[:host_port] = @sb[:vnc] @vnc[:encrypt] = get_vmdb_config.fetch_path(:server, :websocket_encrypt) WsProxy.start( :host => @vnc[:host], :host_port => @vnc[:host_port], :password => @vnc[:password] ).merge(:type => 'vnc') render :action => 'console' end # VM clicked on in the explorer right cell def x_show @explorer = true @vm = @record = identify_record(params[:id], VmOrTemplate) respond_to do |format| format.js do # AJAX, select the node unless @record redirect_to :action => "explorer" return end params[:id] = x_build_node_id(@record) # Get the tree node id tree_select end format.html do # HTML, redirect to explorer tree_node_id = TreeBuilder.build_node_id(@record) session[:exp_parms] = {:id => tree_node_id} redirect_to :action => "explorer" end format.any {render :nothing=>true, :status=>404} # Anything else, just send 404 end end def show(id = nil) @flash_array = [] if params[:display] @sb[:action] = params[:display] return if perfmenu_click? @display = params[:display] || "main" unless control_selected? @display = params[:vm_tree] if params[:vm_tree] @lastaction = "show" @showtype = "config" @record = identify_record(id || params[:id], VmOrTemplate) return if record_no_longer_exists?(@record) @explorer = true if request.xml_http_request? # Ajax request means in explorer if !@explorer && @display != "download_pdf" tree_node_id = TreeBuilder.build_node_id(@record) session[:exp_parms] = {:display => @display, :refresh => params[:refresh], :id => tree_node_id} redirect_to :controller => controller_for_vm(model_for_vm(@record)), :action => "explorer" return end if @record.class.base_model.to_s == "MiqTemplate" rec_cls = @record.class.base_model.to_s.underscore else rec_cls = "vm" end @gtl_url = "/#{rec_cls}/show/" << @record.id.to_s << "?" if ["download_pdf","main","summary_only"].include?(@display) get_tagdata(@record) drop_breadcrumb({:name=>"Virtual Machines", :url=>"/#{rec_cls}/show_list?page=#{@current_page}&refresh=y"}, true) drop_breadcrumb( {:name=>@record.name + " (Summary)", :url=>"/#{rec_cls}/show/#{@record.id}"} ) @showtype = "main" @button_group = "#{rec_cls}" set_summary_pdf_data if ["download_pdf","summary_only"].include?(@display) elsif @display == "networks" drop_breadcrumb( {:name=>@record.name+" (Networks)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) elsif @display == "os_info" drop_breadcrumb( {:name=>@record.name+" (OS Information)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) elsif @display == "hv_info" drop_breadcrumb( {:name=>@record.name+" (Container)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) elsif @display == "resources_info" drop_breadcrumb( {:name=>@record.name+" (Resources)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) elsif @display == "snapshot_info" drop_breadcrumb( {:name=>@record.name+" (Snapshots)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) build_snapshot_tree @button_group = "snapshot" elsif @display == "miq_proxies" drop_breadcrumb({:name=>"Virtual Machines", :url=>"/#{rec_cls}/show_list?page=#{@current_page}&refresh=y"}, true) drop_breadcrumb( {:name=>@record.name+" (Managing SmartProxies)", :url=>"/#{rec_cls}/show/#{@record.id}?display=miq_proxies"} ) @view, @pages = get_view(MiqProxy, :parent=>@record) # Get the records (into a view) and the paginator @showtype = "miq_proxies" @gtl_url = "/#{rec_cls}/show/" << @record.id.to_s << "?" elsif @display == "vmtree_info" @tree_vms = Array.new # Capture all VM ids in the tree drop_breadcrumb( {:name=>@record.name, :url=>"/#{rec_cls}/show/#{@record.id}"}, true ) drop_breadcrumb( {:name=>@record.name+" (Genealogy)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) #session[:base_id] = @record.id vmtree_nodes = vmtree(@record) @temp[:vm_tree] = vmtree_nodes.to_json @temp[:tree_name] = "genealogy_tree" @button_group = "vmtree" elsif @display == "compliance_history" count = params[:count] ? params[:count].to_i : 10 session[:ch_tree] = compliance_history_tree(@record, count).to_json session[:tree_name] = "ch_tree" session[:squash_open] = (count == 1) drop_breadcrumb( {:name=>@record.name, :url=>"/#{rec_cls}/show/#{@record.id}"}, true ) if count == 1 drop_breadcrumb( {:name=>@record.name+" (Latest Compliance Check)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) else drop_breadcrumb( {:name=>@record.name+" (Compliance History - Last #{count} Checks)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) end @showtype = @display elsif @display == "performance" @showtype = "performance" drop_breadcrumb( {:name=>"#{@record.name} Capacity & Utilization", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}&refresh=n"} ) perf_gen_init_options # Initialize perf chart options, charts will be generated async elsif @display == "disks" @showtype = "disks" disks drop_breadcrumb( {:name=>"#{@record.name} (Disks)", :url=>"/#{rec_cls}/show/#{@record.id}?display=#{@display}"} ) elsif @display == "ontap_logical_disks" drop_breadcrumb( {:name=>@record.name+" (All #{ui_lookup(:tables=>"ontap_logical_disk")})", :url=>"/#{rec_cls}/show/#{@record.id}?display=ontap_logical_disks"} ) @view, @pages = get_view(OntapLogicalDisk, :parent=>@record, :parent_method => :logical_disks) # Get the records (into a view) and the paginator @showtype = "ontap_logical_disks" elsif @display == "ontap_storage_systems" drop_breadcrumb( {:name=>@record.name+" (All #{ui_lookup(:tables=>"ontap_storage_system")})", :url=>"/#{rec_cls}/show/#{@record.id}?display=ontap_storage_systems"} ) @view, @pages = get_view(OntapStorageSystem, :parent=>@record, :parent_method => :storage_systems) # Get the records (into a view) and the paginator @showtype = "ontap_storage_systems" elsif @display == "ontap_storage_volumes" drop_breadcrumb( {:name=>@record.name+" (All #{ui_lookup(:tables=>"ontap_storage_volume")})", :url=>"/#{rec_cls}/show/#{@record.id}?display=ontap_storage_volumes"} ) @view, @pages = get_view(OntapStorageVolume, :parent=>@record, :parent_method => :storage_volumes) # Get the records (into a view) and the paginator @showtype = "ontap_storage_volumes" elsif @display == "ontap_file_shares" drop_breadcrumb( {:name=>@record.name+" (All #{ui_lookup(:tables=>"ontap_file_share")})", :url=>"/#{rec_cls}/show/#{@record.id}?display=ontap_file_shares"} ) @view, @pages = get_view(OntapFileShare, :parent=>@record, :parent_method => :file_shares) # Get the records (into a view) and the paginator @showtype = "ontap_file_shares" end unless @record.hardware.nil? @record_notes = @record.hardware.annotation.nil? ? "<No notes have been entered for this VM>" : @record.hardware.annotation end set_config(@record) get_host_for_vm(@record) session[:tl_record_id] = @record.id # Came in from outside show_list partial if params[:ppsetting] || params[:searchtag] || params[:entry] || params[:sort_choice] replace_gtl_main_div end if @explorer # @in_a_form = true @refresh_partial = "layouts/performance" replace_right_cell if !["download_pdf","performance"].include?(params[:display]) end end def summary_pdf return if perfmenu_click? @display = params[:display] || "main" unless control_selected? @display = params[:vm_tree] if params[:vm_tree] @lastaction = "show" @showtype = "config" @vm = @record = identify_record(params[:id], VmOrTemplate) return if record_no_longer_exists?(@vm) rec_cls = "vm" @gtl_url = "/#{rec_cls}/show/" << @record.id.to_s << "?" get_tagdata(@record) drop_breadcrumb({:name=>"Virtual Machines", :url=>"/#{rec_cls}/show_list?page=#{@current_page}&refresh=y"}, true) drop_breadcrumb( {:name=>@record.name + " (Summary)", :url=>"/#{rec_cls}/show/#{@record.id}"} ) @showtype = "main" @button_group = "#{rec_cls}" @report_only = true @showtype = "summary_only" @title = @record.name + " (Summary)" unless @record.hardware.nil? @record_notes = @record.hardware.annotation.nil? ? "<No notes have been entered for this VM>" : @record.hardware.annotation end set_config(@record) get_host_for_vm(@record) session[:tl_record_id] = @record.id html_string = render_to_string(:template => '/layouts/show_pdf', :layout => false) pdf_data = PdfGenerator.pdf_from_string(html_string, 'pdf_summary') disable_client_cache fname = "#{@record.name}_summary_#{format_timezone(Time.now, Time.zone, "fname")}" send_data(pdf_data, :filename => "#{fname}.pdf", :type => "application/pdf" ) end def vmtree(vm) session[:base_vm] = "_h-" + vm.id.to_s + "|" if vm.parents.length > 0 vm_parent = vm.parents @tree_vms.push(vm_parent[0]) unless @tree_vms.include?(vm_parent[0]) parent_node = Hash.new session[:parent_vm] = "_v-" + vm_parent[0].id.to_s + "|" # setting base node id to be passed for check/uncheck all button image = "" if vm_parent[0].retired == true image = "retired.png" else if vm_parent[0].template? if vm_parent[0].host image = "template.png" else image = "template-no-host.png" end else image = "#{vm_parent[0].current_state.downcase}.png" end end parent_node = TreeNodeBuilder.generic_tree_node( "_v-#{vm_parent[0].id}|", "#{vm_parent[0].name} (Parent)", image, "VM: #{vm_parent[0].name} (Click to view)", ) else session[:parent_vm] = nil end session[:parent_vm] = session[:base_vm] if session[:parent_vm].nil? # setting base node id to be passed for check/uncheck all button if vm has no parent base = Array.new base_node = vm_kidstree(vm) base.push(base_node) if !parent_node.nil? parent_node[:children] = base parent_node[:expand] = true return parent_node else base_node[:expand] = true return base_node end end # Recursive method to build a snapshot tree node def vm_kidstree(vm) branch = Hash.new key = "_v-#{vm.id}|" title = vm.name style = "" tooltip = "VM: #{vm.name} (Click to view)" if session[:base_vm] == "_h-#{vm.id}|" title << " (Selected)" key = session[:base_vm] style = "dynatree-cfme-active cfme-no-cursor-node" tooltip = "" end image = "" if vm.template? if vm.host image = "template.png" else image = "template-no-host.png" end else image = "#{vm.current_state.downcase}.png" end branch = TreeNodeBuilder.generic_tree_node( key, title, image, tooltip, :style_class => style ) @tree_vms.push(vm) unless @tree_vms.include?(vm) if vm.children.length > 0 kids = Array.new vm.children.each do |kid| kids.push(vm_kidstree(kid)) unless @tree_vms.include?(kid) end branch[:children] = kids.sort_by { |a| a[:title].downcase } end return branch end def build_snapshot_tree vms = @record.snapshots.all parent = TreeNodeBuilder.generic_tree_node( "snaproot", @record.name, "vm.png", nil, :cfme_no_click => true, :expand => true, :style_class => "cfme-no-cursor-node" ) @record.snapshots.each do | s | if s.current.to_i == 1 @root = s.id @active = true end end @root = @record.snapshots.first.id if @root.nil? && @record.snapshots.size > 0 session[:snap_selected] = @root if params[:display] == "snapshot_info" @temp[:snap_selected] = Snapshot.find(session[:snap_selected]) unless session[:snap_selected].nil? snapshots = Array.new vms.each do |snap| if snap.parent_id.nil? snapshots.push(snaptree(snap)) end end parent[:children] = snapshots top = @record.snapshots.find_by_parent_id(nil) @snaps = [parent].to_json unless top.nil? && parent.blank? end # Recursive method to build a snapshot nodes def snaptree(node) branch = TreeNodeBuilder.generic_tree_node( node.id, node.name, "snapshot.png", "Click to select", :expand => true ) branch[:title] << " (Active)" if node.current? branch[:addClass] = "dynatree-cfme-active" if session[:snap_selected].to_s == branch[:key].to_s if node.children.count > 0 kids = Array.new node.children.each do |kid| kids.push(snaptree(kid)) end branch[:children] = kids end return branch end def vmtree_selected base = params[:id].split('-') base = base[1].slice(0,base[1].length-1) session[:base_vm] = "_h-" + base.to_s @display = "vmtree_info" render :update do |page| # Use RJS to update the display page.redirect_to :action=>"show", :id=>base,:vm_tree=>"vmtree_info" end end def snap_pressed session[:snap_selected] = params[:id] @temp[:snap_selected] = Snapshot.find_by_id(session[:snap_selected]) @vm = @record = identify_record(x_node.split('-').last, VmOrTemplate) if @temp[:snap_selected].nil? @display = "snapshot_info" add_flash(_("Last selected %s no longer exists") % "Snapshot", :error) end build_snapshot_tree @active = @temp[:snap_selected].current.to_i == 1 if @temp[:snap_selected] @button_group = "snapshot" @explorer = true c_buttons, c_xml = build_toolbar_buttons_and_xml("x_vm_center_tb") render :update do |page| # Use RJS to update the display if c_buttons && c_xml page << "dhxLayoutB.cells('a').expand();" page << javascript_for_toolbar_reload('center_tb', c_buttons, c_xml) page << javascript_show_if_exists("center_buttons_div") else page << javascript_hide_if_exists("center_buttons_div") end page.replace("flash_msg_div", :partial => "layouts/flash_msg") page.replace("desc_content", :partial => "/vm_common/snapshots_desc", :locals => {:selected => params[:id]}) page.replace("snapshots_tree_div", :partial => "/vm_common/snapshots_tree") end end def disks #flag to show cursor as default in grid so rows don't look clickable @temp[:ro_grid] = true @grid_xml = build_disks_tree(@record) end def build_disks_tree(view) xml = REXML::Document.load("") xml << REXML::XMLDecl.new(1.0, "UTF-8") # Create root element root = xml.add_element("rows") # Build the header row hrow = root.add_element("head") grid_add_header(@record, hrow) # Sort disks by disk_name within device_type view.hardware.disks.sort{|x,y| cmp = x.device_type.to_s.downcase <=> y.device_type.to_s.downcase; cmp == 0 ? calculate_disk_name(x).downcase <=> calculate_disk_name(y).downcase : cmp }.each_with_index do |disk,idx| srow = root.add_element("row", {"id" => "Disk_#{idx}"}) srow.add_element("cell", {"image" => "blank.gif", "title" => "Disk #{idx}"}).text = calculate_disk_name(disk) srow.add_element("cell", {"image" => "blank.gif", "title" => "#{disk.disk_type}"}).text = disk.disk_type srow.add_element("cell", {"image" => "blank.gif", "title" => "#{disk.mode}"}).text = disk.mode srow.add_element("cell", {"image" => "blank.gif", "title" => "#{disk.partitions_aligned}",}).text = disk.partitions_aligned srow.add_element("cell", {"image" => "blank.gif", "title" => "#{calculate_size(disk.size)}"}).text = calculate_size(disk.size) srow.add_element("cell", {"image" => "blank.gif", "title" => "#{calculate_size(disk.size_on_disk)}"}).text = calculate_size(disk.size_on_disk) srow.add_element("cell", {"image" => "blank.gif", "title" => "#{disk.used_percent_of_provisioned}"}).text = disk.used_percent_of_provisioned end return xml.to_s end def calculate_volume_name(vname) vname.blank? ? "Volume N/A" : "Volume #{vname}" end def calculate_size(size) size.blank? ? nil : number_to_human_size(size,:precision=>2) end def calculate_disk_name(disk) loc = disk.location.nil? ? "" : disk.location dev = "#{disk.controller_type} #{loc}" # default device is controller_type # Customize disk entries by type if disk.device_type == "cdrom-raw" dev = "CD-ROM (IDE " << loc << ")" elsif disk.device_type == "atapi-cdrom" dev = "ATAPI CD-ROM (IDE " << loc << ")" elsif disk.device_type == "cdrom-image" dev = "CD-ROM Image (IDE " << loc << ")" elsif disk.device_type == "disk" if disk.controller_type == "ide" dev = "Hard Disk (IDE " << loc << ")" elsif disk.controller_type == "scsi" dev = "Hard Disk (SCSI " << loc << ")" end elsif disk.device_type == "ide" dev = "Hard Disk (IDE " << loc << ")" elsif ["scsi", "scsi-hardDisk"].include?(disk.device_type) dev = "Hard Disk (SCSI " << loc << ")" elsif disk.device_type == "scsi-passthru" dev = "Generic SCSI (" << loc << ")" elsif disk.device_type == "floppy" dev = dev end return dev end def grid_add_header(view, head) col_width = 100 #disk new_column = head.add_element("column", {"width"=>"120","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Device Type" #device_type new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Type" #mode new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Mode" # alignment new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Partitions Aligned" # commented for FB6679 # #filesystem # new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) # new_column.add_attribute("type", 'ro') # new_column.text = "Filesystem" #size new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Provisioned Size" #size_on_disk new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Used Size" #used_percent_of_provisioned new_column = head.add_element("column", {"width"=>"#{col_width}","sort"=>"na"}) new_column.add_attribute("type", 'ro') new_column.text = "Percent Used of Provisioned Size" end def show_association(action, display_name, listicon, method, klass, association = nil) @explorer = true if request.xml_http_request? # Ajax request means in explorer if @explorer # Save vars for tree history array @action = action @x_show = params[:x_show] end @vm = @record = identify_record(params[:id], VmOrTemplate) return if record_no_longer_exists?(@vm) rec_cls = "vm" @sb[:action] = @lastaction = action if params[:show] != nil || params[:x_show] != nil id = params[:show] ? params[:show] : params[:x_show] if method.kind_of?(Array) obj = @record while meth = method.shift do obj = obj.send(meth) end @item = obj.find(from_cid(id)) else @item = @record.send(method).find(from_cid(id)) end drop_breadcrumb( { :name => "#{@record.name} (#{display_name})", :url=>"/#{rec_cls}/#{action}/#{@record.id}?page=#{@current_page}"} ) drop_breadcrumb( { :name => @item.name, :url=>"/#{rec_cls}/#{action}/#{@record.id}?show=#{@item.id}"} ) @view = get_db_view(klass, :association=>association) show_item else drop_breadcrumb( { :name => @record.name, :url=>"/#{rec_cls}/show/#{@record.id}"}, true ) drop_breadcrumb( { :name => "#{@record.name} (#{display_name})", :url=>"/#{rec_cls}/#{action}/#{@record.id}"} ) @listicon = listicon if association.nil? show_details(klass) else show_details(klass, :association => association ) end end end def processes show_association('processes', 'Running Processes', 'processes', [:operating_system, :processes], OsProcess, 'processes') end def registry_items show_association('registry_items', 'Registry Entries', 'registry_items', :registry_items, RegistryItem) end def advanced_settings show_association('advanced_settings', 'Advanced Settings', 'advancedsetting', :advanced_settings, AdvancedSetting) end def linux_initprocesses show_association('linux_initprocesses', 'Init Processes', 'linuxinitprocesses', :linux_initprocesses, SystemService, 'linux_initprocesses') end def win32_services show_association('win32_services', 'Win32 Services', 'win32service', :win32_services, SystemService, 'win32_services') end def kernel_drivers show_association('kernel_drivers', 'Kernel Drivers', 'kerneldriver', :kernel_drivers, SystemService, 'kernel_drivers') end def filesystem_drivers show_association('filesystem_drivers', 'File System Drivers', 'filesystemdriver', :filesystem_drivers, SystemService, 'filesystem_drivers') end def filesystems show_association('filesystems', 'Files', 'filesystems', :filesystems, Filesystem) end def security_groups show_association('security_groups', 'Security Groups', 'security_group', :security_groups, SecurityGroup) end def snap assert_privileges(params[:pressed]) @vm = @record = identify_record(params[:id], VmOrTemplate) @name = @description = "" @in_a_form = true @button_group = "snap" drop_breadcrumb( {:name=>"Snapshot VM '" + @record.name + "'", :url=>"/vm_common/snap", :display=>"snapshot_info"} ) if @explorer @edit ||= Hash.new @edit[:explorer] = true session[:changed] = true @refresh_partial = "vm_common/snap" end end alias vm_snapshot_add snap def snap_vm @vm = @record = identify_record(params[:id], VmOrTemplate) if params["cancel"] || params[:button] == "cancel" flash = _("%s was cancelled by the user") % "Snapshot of VM #{@record.name}" if session[:edit] && session[:edit][:explorer] add_flash(flash) @_params[:display] = "snapshot_info" show else redirect_to :action=>@lastaction, :id=>@record.id, :flash_msg=>flash end elsif params["create.x"] || params[:button] == "create" @name = params[:name] @description = params[:description] if params[:name].blank? add_flash(_("%s is required") % "Name", :error) @in_a_form = true drop_breadcrumb( {:name=>"Snapshot VM '" + @record.name + "'", :url=>"/vm_common/snap"} ) if session[:edit] && session[:edit][:explorer] @edit = session[:edit] #saving it to use in next transaction render :partial => "shared/ajax/flash_msg_replace" else render :action=>"snap" end else flash_error = false # audit = {:event=>"vm_genealogy_change", :target_id=>@record.id, :target_class=>@record.class.base_class.name, :userid => session[:userid]} begin # @record.create_snapshot(params[:name], params[:description], params[:snap_memory]) Vm.process_tasks( :ids => [@record.id], :task => "create_snapshot", :userid => session[:userid], :name => params[:name], :description => params[:description], :memory => params[:snap_memory] == "1") rescue StandardError => bang puts bang.backtrace.join("\n") flash = _("Error during '%s': ") % "Create Snapshot" << bang.message; flash_error = true # AuditEvent.failure(audit.merge(:message=>"[#{@record.name} -- #{@record.location}] Update returned: #{bang}")) else flash = _("Create Snapshot for %{model} \"%{name}\" was started") % {:model=>ui_lookup(:model=>"Vm"), :name=>@record.name} # AuditEvent.success(build_saved_vm_audit(@record)) end params[:id] = @record.id.to_s # reset id in params for show #params[:display] = "snapshot_info" if session[:edit] && session[:edit][:explorer] add_flash(flash, flash_error ? :error : :info) @_params[:display] = "snapshot_info" show else redirect_to :action=>@lastaction, :id=>@record.id, :flash_msg=>flash, :flash_error=>flash_error, :display=>"snapshot_info" end end end end def policies @vm = @record = identify_record(params[:id], VmOrTemplate) @lastaction = "rsop" @showtype = "policies" drop_breadcrumb( {:name=>"Policy Simulation Details for " + @record.name, :url=>"/vm/policies/#{@record.id}"} ) @polArr = Array.new @record.resolve_profiles(session[:policies].keys).sort{|a,b| a["description"] <=> b["description"]}.each do | a | @polArr.push(a) end @policy_options = Hash.new @policy_options[:out_of_scope] = true @policy_options[:passed] = true @policy_options[:failed] = true build_policy_tree(@polArr) @edit = session[:edit] if session[:edit] if @edit && @edit[:explorer] @in_a_form = true replace_right_cell else render :template => 'vm/show' end end # policy simulation tree def build_policy_tree(profiles) session[:squash_open] = false vm_node = TreeNodeBuilder.generic_tree_node( "h_#{@record.name}", @record.name, "vm.png", @record.name, {:style_class => "cfme-no-cursor-node", :expand => true } ) vm_node[:title] = "<b>#{vm_node[:title]}</b>" vm_node[:children] = build_profile_nodes(profiles) if profiles.length > 0 session[:policy_tree] = [vm_node].to_json session[:tree_name] = "rsop_tree" end def build_profile_nodes(profiles) profile_nodes = [] profiles.each do |profile| if profile["result"] == "allow" icon = "checkmark.png" elsif profile["result"] == "N/A" icon = "na.png" else icon = "x.png" end profile_node = TreeNodeBuilder.generic_tree_node( "policy_profile_#{profile['id']}", profile['description'], icon, nil, {:style_class => "cfme-no-cursor-node"} ) profile_node[:title] = "<b>Policy Profile:</b> #{profile_node[:title]}" profile_node[:children] = build_policy_node(profile["policies"]) if profile["policies"].length > 0 if @policy_options[:out_of_scope] == false profile_nodes.push(profile_node) if profile["result"] != "N/A" else profile_nodes.push(profile_node) end end profile_nodes.push(build_empty_node) if profile_nodes.blank? profile_nodes end def build_empty_node TreeNodeBuilder.generic_tree_node( nil, "Items out of scope", "blank.gif", nil, {:style_class => "cfme-no-cursor-node"} ) end def build_policy_node(policies) policy_nodes = [] policies.sort_by{ |a| a["description"] }.each do |policy| active_caption = policy["active"] ? "" : " (Inactive)" if policy["result"] == "allow" icon = "checkmark.png" elsif policy["result"] == "N/A" icon = "na.png" else icon = "x.png" end policy_node = TreeNodeBuilder.generic_tree_node( "policy_#{policy["id"]}", policy['description'], icon, nil, {:style_class => "cfme-no-cursor-node"} ) policy_node[:title] = "<b>Policy#{active_caption}:</b> #{policy_node[:title]}" policy_children = [] policy_children.push(build_scope_or_expression_node(policy["scope"], "scope_#{policy["id"]}_#{policy["name"]}", "Scope")) if policy["scope"] policy_children.concat(build_condition_nodes(policy)) if policy["conditions"].length > 0 policy_node[:children] = policy_children unless policy_children.empty? if @policy_options[:out_of_scope] == false && @policy_options[:passed] == true && @policy_options[:failed] == true policy_nodes.push(policy_node) if policy["result"] != "N/A" elsif @policy_options[:passed] == true && @policy_options[:failed] == false && @policy_options[:out_of_scope] == false policy_nodes.push(policy_node) if policy["result"] == "allow" elsif @policy_options[:passed] == true && @policy_options[:failed] == false && @policy_options[:out_of_scope] == true policy_nodes.push(policy_node) if policy["result"] == "N/A" || policy["result"] == "allow" elsif @policy_options[:failed] == true && @policy_options[:passed] == false policy_nodes.push(policy_node) if policy["result"] == "deny" elsif @policy_options[:out_of_scope] == true && @policy_options[:passed] == true && policy["result"] == "N/A" policy_nodes.push(policy_node) else policy_nodes.push(policy_node) end end policy_nodes end def build_condition_nodes(policy) condition_nodes = [] policy["conditions"].sort_by{ |a| a["description"] }.each do |condition| if condition["result"] == "allow" icon = "checkmark.png" elsif condition["result"] == "N/A" || !condition["expression"] icon = "na.png" else icon = "x.png" end condition_node = TreeNodeBuilder.generic_tree_node( "condition_#{condition["id"]}_#{condition["name"]}_#{policy["name"]}", condition["description"], icon, nil, {:style_class => "cfme-no-cursor-node"} ) condition_node[:title] = "<b>Condition:</b> #{condition_node[:title]}" condition_children = [] condition_children.push(build_scope_or_expression_node(condition["scope"], "scope_#{condition["id"]}_#{condition["name"]}", "Scope")) if condition["scope"] condition_children.push(build_scope_or_expression_node(condition["expression"], "expression_#{condition["id"]}_#{condition["name"]}", "Expression")) if condition["expression"] condition_node[:children] = condition_children if !condition_children.blank? if @policy_options[:out_of_scope] == false condition_nodes.push(condition_node) if condition["result"] != "N/A" else condition_nodes.push(condition_node) end end condition_nodes end def build_scope_or_expression_node(scope_or_expression, node_key, title_prefix) exp_string,exp_tooltip = exp_build_string(scope_or_expression) if scope_or_expression["result"] == true icon = "checkmark.png" else icon = "na.png" end node = TreeNodeBuilder.generic_tree_node( node_key, exp_string.html_safe, icon, exp_tooltip.html_safe, {:style_class => "cfme-no-cursor-node"} ) node[:title] = "<b>#{title_prefix}:</b> #{node[:title]}" if @policy_options[:out_of_scope] == false node if scope_or_expression["result"] != "N/A" else node end end def policy_show_options if params[:passed] == "null" || params[:passed] == "" @policy_options[:passed] = false @policy_options[:failed] = true elsif params[:failed] == "null" || params[:failed] == "" @policy_options[:passed] = true @policy_options[:failed] = false elsif params[:failed] == "1" @policy_options[:failed] = true elsif params[:passed] == "1" @policy_options[:passed] = true end @vm = @record = identify_record(params[:id], VmOrTemplate) build_policy_tree(@polArr) render :update do |page| page.replace_html("flash_msg_div", :partial => "layouts/flash_msg") page.replace_html("main_div", :partial => "vm_common/policies") end end # Show/Unshow out of scope items def policy_options @vm = @record = identify_record(params[:id], VmOrTemplate) @policy_options ||= Hash.new @policy_options[:out_of_scope] = (params[:out_of_scope] == "1") build_policy_tree(@polArr) render :update do |page| page.replace("flash_msg_div", :partial => "layouts/flash_msg") page << "#{session[:tree_name]}.saveOpenStates('#{session[:tree_name]}','path=/');" page << "#{session[:tree_name]}.loadOpenStates('#{session[:tree_name]}');" #page.replace("policy_options_div", :partial=>"vm/policy_options") page.replace("main_div", :partial=>"vm_common/policies") end end def toggle_policy_profile session[:policy_profile_compressed] = ! session[:policy_profile_compressed] @compressed = session[:policy_profile_compressed] render :update do |page| # Use RJS to update the display page.replace_html("view_buttons_div", :partial=>"layouts/view_buttons") # Replace the view buttons page.replace_html("main_div", :partial=>"policies") # Replace the main div area contents end end # Set right_size selected db records def right_size @record = Vm.find_by_id(params[:id]) @lastaction = "right_size" @rightsize = true @in_a_form = true if params[:button] == "back" render :update do |page| page.redirect_to(previous_breadcrumb_url) end end if !@explorer && params[:button] != "back" drop_breadcrumb(:name => "Right Size VM '" + @record.name + "'", :url => "/vm/right_size") render :action=>"show" end end def evm_relationship @record = find_by_id_filtered(VmOrTemplate, params[:id]) # Set the VM object @edit = Hash.new @edit[:vm_id] = @record.id @edit[:key] = "evm_relationship_edit__new" @edit[:current] = Hash.new @edit[:new] = Hash.new evm_relationship_build_screen @edit[:current] = copy_hash(@edit[:new]) session[:changed] = false @tabs = [ ["evm_relationship", @record.id.to_s], ["evm_relationship", "Edit Management Engine Relationship"] ] @in_a_form = true if @explorer @refresh_partial = "vm_common/evm_relationship" @edit[:explorer] = true end end alias image_evm_relationship evm_relationship alias instance_evm_relationship evm_relationship alias vm_evm_relationship evm_relationship alias miq_template_evm_relationship evm_relationship # Build the evm_relationship assignment screen def evm_relationship_build_screen @servers = Hash.new # Users array for first chooser MiqServer.all.each{|s| @servers["#{s.name} (#{s.id})"] = s.id.to_s} @edit[:new][:server] = @record.miq_server ? @record.miq_server.id.to_s : nil # Set to first category, if not already set end def evm_relationship_field_changed return unless load_edit("evm_relationship_edit__new") evm_relationship_get_form_vars changed = (@edit[:new] != @edit[:current]) render :update do |page| # Use JS to update the display page << javascript_for_miq_button_visibility(changed) end end def evm_relationship_get_form_vars @record = VmOrTemplate.find_by_id(@edit[:vm_id]) @edit[:new][:server] = params[:server_id] if params[:server_id] end def evm_relationship_update return unless load_edit("evm_relationship_edit__new") evm_relationship_get_form_vars case params[:button] when "cancel" msg = _("%s was cancelled by the user") % "Edit Management Engine Relationship" if @edit[:explorer] add_flash(msg) @sb[:action] = nil replace_right_cell else render :update do |page| page.redirect_to :action=>'show', :id=>@record.id, :flash_msg=>msg end end when "save" svr = @edit[:new][:server] && @edit[:new][:server] != "" ? MiqServer.find(@edit[:new][:server]) : nil @record.miq_server = svr @record.save msg = _("%s saved") % "Management Engine Relationship" if @edit[:explorer] add_flash(msg) @sb[:action] = nil replace_right_cell else render :update do |page| page.redirect_to :action=>'show', :id=>@record.id,:flash_msg=>msg end end when "reset" @in_a_form = true if @edit[:explorer] @explorer = true evm_relationship add_flash(_("All changes have been reset"), :warning) replace_right_cell else render :update do |page| page.redirect_to :action=>'evm_relationship', :id=>@record.id, :flash_msg=>_("All changes have been reset"), :flash_warning=>true, :escape=>true end end end end def delete @lastaction = "delete" redirect_to :action => 'show_list', :layout=>false end def destroy find_by_id_filtered(VmOrTemplate, params[:id]).destroy redirect_to :action => 'list' end def profile_build session[:vm].resolve_profiles(session[:policies].keys).sort{|a,b| a["description"] <=> b["description"]}.each do | policy | @catinfo ||= Hash.new # Hash to hold category squashed states policy.each do | key, cat| if key == "description" if @catinfo[cat] == nil @catinfo[cat] = true # Set compressed if no entry present yet end end end end end def profile_toggle if params[:pressed] == "tag_cat_toggle" profile_build policy_escaped = j(params[:policy]) cat = params[:cat] render :update do |page| if @catinfo[cat] @catinfo[cat] = false page << javascript_show("cat_#{policy_escaped}_div") page << "$('#cat_#{policy_escaped}_icon').prop('src', '/images/tree/compress.png');" else @catinfo[cat] = true # Set squashed = true page << javascript_hide("cat_#{policy_escaped}_div") page << "$('#cat_#{policy_escaped}_icon').prop('src', '/images/tree/expand.png');" end end else add_flash(_("Button not yet implemented"), :error) render :partial => "shared/ajax/flash_msg_replace" end end def add_to_service @record = find_by_id_filtered(Vm, params[:id]) @svcs = Hash.new Service.all.each {|s| @svcs[s.name] = s.id } drop_breadcrumb( {:name=>"Add VM to a Service", :url=>"/vm/add_to_service"} ) @in_a_form = true end def add_vm_to_service @record = find_by_id_filtered(Vm, params[:id]) if params["cancel.x"] flash = _("Add VM \"%s\" to a Service was cancelled by the user") % @record.name redirect_to :action=>@lastaction, :id=>@record.id, :flash_msg=>flash else chosen = params[:chosen_service].to_i flash = _("%{model} \"%{name}\" successfully added to Service \"%{to_name}\"") % {:model=>ui_lookup(:model=>"Vm"), :name=>@record.name, :to_name=>Service.find(chosen).name} begin @record.add_to_vsc(Service.find(chosen).name) rescue StandardError => bang flash = _("Error during '%s': ") % "Add VM to service" << bang end redirect_to :action => @lastaction, :id=>@record.id, :flash_msg=>flash end end def remove_service assert_privileges(params[:pressed]) @record = find_by_id_filtered(Vm, params[:id]) begin @vervice_name = Service.find_by_name(@record.location).name @record.remove_from_vsc(@vervice_name) rescue StandardError => bang add_flash(_("Error during '%s': ") % "Remove VM from service" + bang.message, :error) else add_flash(_("VM successfully removed from service \"%s\"") % @vervice_name) end end def edit @record = find_by_id_filtered(VmOrTemplate, params[:id]) # Set the VM object set_form_vars build_edit_screen session[:changed] = false @tabs = [ ["edit", @record.id.to_s], ["edit", "Information"] ] @refresh_partial = "vm_common/form" end alias image_edit edit alias instance_edit edit alias vm_edit edit alias miq_template_edit edit def build_edit_screen drop_breadcrumb(:name => "Edit VM '" + @record.name + "'", :url => "/vm/edit") unless @explorer session[:edit] = @edit @in_a_form = true @tabs = [ ["edit", @record.id.to_s], ["edit", "Information"] ] end # AJAX driven routine to check for changes in ANY field on the form def form_field_changed return unless load_edit("vm_edit__#{params[:id]}") get_form_vars changed = (@edit[:new] != @edit[:current]) render :update do |page| # Use JS to update the display page.replace_html("main_div", :partial => "vm_common/form") if %w(allright left right).include?(params[:button]) page << javascript_for_miq_button_visibility(changed) if changed page << "miqSparkle(false);" end end def edit_vm return unless load_edit("vm_edit__#{params[:id]}") #reset @explorer if coming from explorer views @explorer = true if @edit[:explorer] get_form_vars case params[:button] when "cancel" if @edit[:explorer] add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model=>ui_lookup(:model=>@record.class.base_model.name), :name=>@record.name}) @record = @sb[:action] = nil replace_right_cell else add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "Vm"), :name => @record.name}) session[:flash_msgs] = @flash_array.dup render :update do |page| page.redirect_to(previous_breadcrumb_url) end end when "save" if @edit[:new][:parent] != -1 && @edit[:new][:kids].invert.include?(@edit[:new][:parent]) # Check if parent is a kid, if selected add_flash(_("Parent VM can not be one of the child VMs"), :error) @changed = session[:changed] = (@edit[:new] != @edit[:current]) build_edit_screen if @edit[:explorer] replace_right_cell else render :action=>"edit" end else current = @record.parents.length == 0 ? -1 : @record.parents.first.id # get current parent id chosen = @edit[:new][:parent].to_i # get the chosen parent id @record.custom_1 = @edit[:new][:custom_1] @record.description = @edit[:new][:description] # add vm description if current != chosen @record.remove_parent(@record.parents.first) unless current == -1 # Remove existing parent, if there is one @record.set_parent(VmOrTemplate.find(chosen)) unless chosen == -1 # Set new parent, if one was chosen end vms = @record.children # Get the VM's child VMs kids = @edit[:new][:kids].invert # Get the VM ids from the kids list box audit = {:event=>"vm_genealogy_change", :target_id=>@record.id, :target_class=>@record.class.base_class.name, :userid => session[:userid]} begin @record.save! vms.each { |v| @record.remove_child(v) if !kids.include?(v.id) } # Remove any VMs no longer in the kids list box kids.each_key { |k| @record.set_child(VmOrTemplate.find(k)) } # Add all VMs in kids hash, dups will not be re-added rescue StandardError => bang add_flash(_("Error during '%s': ") % "#{@record.class.base_model.name} update" << bang.message, :error) AuditEvent.failure(audit.merge(:message=>"[#{@record.name} -- #{@record.location}] Update returned: #{bang}")) else flash = _("%{model} \"%{name}\" was saved") % {:model=>ui_lookup(:model=>@record.class.base_model.name), :name=>@record.name} AuditEvent.success(build_saved_vm_audit(@record)) end params[:id] = @record.id.to_s # reset id in params for show @record = nil add_flash(flash) if @edit[:explorer] @sb[:action] = nil replace_right_cell else session[:flash_msgs] = @flash_array.dup render :update do |page| page.redirect_to(previous_breadcrumb_url) end end end when "reset" edit add_flash(_("All changes have been reset"), :warning) session[:flash_msgs] = @flash_array.dup get_vm_child_selection if params["right.x"] || params["left.x"] || params["allright.x"] @changed = session[:changed] = false build_edit_screen if @edit[:explorer] replace_right_cell else render :update do |page| page.redirect_to(:action => "edit", :controller => "vm", :id => params[:id]) end end else @changed = session[:changed] = (@edit[:new] != @edit[:current]) build_edit_screen if @edit[:explorer] replace_right_cell else render :action=>"edit" end end end def set_checked_items session[:checked_items] = Array.new if params[:all_checked] ids = params[:all_checked].split(',') ids.each do |id| id = id.split('-') id = id[1].slice(0,id[1].length-1) session[:checked_items].push(id) unless session[:checked_items].include?(id) end end @lastaction = "set_checked_items" render :nothing => true end def scan_history @vm = @record = identify_record(params[:id], VmOrTemplate) @scan_history = ScanHistory.find_by_vm_or_template_id(@record.id) @listicon = "scan_history" @showtype = "scan_history" @lastaction = "scan_history" @gtl_url = "/vm/scan_history/?" @no_checkboxes = true @showlinks = true @view, @pages = get_view(ScanHistory, :parent=>@record) # Get the records (into a view) and the paginator @current_page = @pages[:current] if @pages != nil # save the current page number if @scan_history.nil? drop_breadcrumb( {:name=>@record.name + " (Analysis History)", :url=>"/vm/#{@record.id}"} ) else drop_breadcrumb( {:name=>@record.name + " (Analysis History)", :url=>"/vm/scan_history/#{@scan_history.vm_or_template_id}"} ) end # Came in from outside show_list partial if params[:ppsetting] || params[:searchtag] || params[:entry] || params[:sort_choice] render :update do |page| page.replace_html("gtl_div", :partial=>"layouts/gtl") page << "miqSparkle(false);" # Need to turn off sparkle in case original ajax element gets replaced end else if @explorer || request.xml_http_request? # Is this an Ajax request? @sb[:action] = params[:action] @refresh_partial = "layouts/#{@showtype}" replace_right_cell else render :action => 'show' end end end def scan_histories @vm = @record = identify_record(params[:id], VmOrTemplate) @explorer = true if request.xml_http_request? # Ajax request means in explorer @scan_history = ScanHistory.find_by_vm_or_template_id(@record.id) if @scan_history == nil redirect_to :action=>"scan_history", :flash_msg=>_("Error: Record no longer exists in the database"), :flash_error=>true return end @lastaction = "scan_histories" @sb[:action] = params[:action] if params[:show] != nil || params[:x_show] != nil id = params[:show] ? params[:show] : params[:x_show] @item = ScanHistory.find(from_cid(id)) drop_breadcrumb( {:name=>time_ago_in_words(@item.started_on.in_time_zone(Time.zone)).titleize, :url=>"/vm/scan_history/#{@scan_history.vm_or_template_id}?show=#{@item.id}"} ) @view = get_db_view(ScanHistory) # Instantiate the MIQ Report view object show_item else drop_breadcrumb( {:name=>time_ago_in_words(@scan_history.started_on.in_time_zone(Time.zone)).titleize, :url=>"/vm/show/#{@scan_history.vm_or_template_id}"}, true ) @listicon = "scan_history" show_details(ScanHistory) end end # Tree node selected in explorer def tree_select @explorer = true @lastaction = "explorer" @sb[:action] = nil # Need to see if record is unauthorized if it's a VM node @nodetype, id = params[:id].split("_").last.split("-") @vm = @record = identify_record(id, VmOrTemplate) if ["Vm", "MiqTemplate"].include?(TreeBuilder.get_model_for_prefix(@nodetype)) && !@record # Handle filtered tree nodes if x_tree[:type] == :filter && !["Vm", "MiqTemplate"].include?(TreeBuilder.get_model_for_prefix(@nodetype)) search_id = @nodetype == "root" ? 0 : from_cid(id) adv_search_build(vm_model_from_active_tree(x_active_tree)) session[:edit] = @edit # Set because next method will restore @edit from session listnav_search_selected(search_id) unless params.has_key?(:search_text) # Clear or set the adv search filter if @edit[:adv_search_applied] && MiqExpression.quick_search?(@edit[:adv_search_applied][:exp]) && %w(reload tree_select).include?(params[:action]) self.x_node = params[:id] quick_search_show return end end unless @unauthorized self.x_node = params[:id] replace_right_cell else add_flash("User is not authorized to view #{ui_lookup(:model=>@record.class.base_model.to_s)} \"#{@record.name}\"", :error) render :partial => "shared/tree_select_error", :locals => {:options => {:select_node => x_node}} end end # Accordion selected in explorer def accordion_select @lastaction = "explorer" self.x_active_accord = params[:id] self.x_active_tree = "#{params[:id]}_tree" @sb[:action] = nil replace_right_cell end private ############################ # First time thru, kick off the acquire ticket task def console_before_task(console_type) @vm = @record = identify_record(params[:id], VmOrTemplate) api_version = @record.ext_management_system.api_version.to_s if !api_version.starts_with?("5") add_flash(_("Console access failed: %s") % "Unsupported Provider API version #{api_version}", :error) else task_id = @record.remote_console_acquire_ticket_queue(console_type.to_sym, session[:userid], MiqServer.my_server.id) unless task_id.is_a?(Fixnum) add_flash(_("Console access failed: %s") % "Task start failed: ID [#{task_id.inspect}]", :error) end end if @flash_array render :partial => "shared/ajax/flash_msg_replace" else initiate_wait_for_task(:task_id => task_id) # Spin the Q until the task is done end end # Task complete, show error or launch console using VNC/MKS/VMRC task info def console_after_task(console_type) miq_task = MiqTask.find(params[:task_id]) if miq_task.status == "Error" || miq_task.task_results.blank? add_flash(_("Console access failed: %s") % miq_task.message, :error) else @vm = @record = identify_record(params[:id], VmOrTemplate) @sb[console_type.to_sym] = miq_task.task_results # VNC, MKS or VMRC end render :update do |page| if @flash_array page.replace(:flash_msg_div, :partial=>"layouts/flash_msg") page << "miqSparkle(false);" else # open a window to show a VNC or VMWare console console_action = console_type == 'vnc' ? 'launch_novnc_console' : 'launch_vmware_console' page << "miqSparkle(false);" page << "window.open('#{url_for :controller => controller_name, :action => console_action, :id => @record.id}');" end end end # Check for parent nodes missing from vandt tree and return them if any def open_parent_nodes(record) add_nodes = nil existing_node = nil # Init var if record.orphaned? || record.archived? parents = [{:type=>"x", :id=>"#{record.orphaned ? "orph" : "arch"}"}] else if x_active_tree == :instances_tree parents = record.kind_of?(VmCloud) && record.availability_zone ? [record.availability_zone] : [record.ext_management_system] else parents = record.parent_blue_folders({:exclude_non_display_folders=>true}) end end # Go up thru the parents and find the highest level unopened, mark all as opened along the way unless parents.empty? || # Skip if no parents or parent already open x_tree[:open_nodes].include?(x_build_node_id(parents.last)) parents.reverse.each do |p| p_node = x_build_node_id(p) unless x_tree[:open_nodes].include?(p_node) x_tree[:open_nodes].push(p_node) existing_node = p_node end end end # Start at the EMS if record has an EMS and it's not opened yet if record.ext_management_system ems_node = x_build_node_id(record.ext_management_system) unless x_tree[:open_nodes].include?(ems_node) x_tree[:open_nodes].push(ems_node) existing_node = ems_node end end add_nodes = {:key => existing_node, :children => tree_add_child_nodes(existing_node)} if existing_node return add_nodes end # Get all info for the node about to be displayed def get_node_info(treenodeid) #resetting action that was stored during edit to determine what is being edited @sb[:action] = nil @nodetype, id = valid_active_node(treenodeid).split("_").last.split("-") model, title = case x_active_tree.to_s when "images_filter_tree" ["TemplateCloud", "Images"] when "images_tree" ["TemplateCloud", "Images by Provider"] when "instances_filter_tree" ["VmCloud", "Instances"] when "instances_tree" ["VmCloud", "Instances by Provider"] when "vandt_tree" ["VmOrTemplate", "VMs & Templates"] when "vms_instances_filter_tree" ["Vm", "VMs & Instances"] when "templates_images_filter_tree" ["MiqTemplate", "Templates & Images"] when "templates_filter_tree" ["TemplateInfra", "Templates"] when "vms_filter_tree" ["VmInfra", "VMs"] else [nil, nil] end case TreeBuilder.get_model_for_prefix(@nodetype) when "Vm", "MiqTemplate" # VM or Template record, show the record show_record(from_cid(id)) if @record.nil? self.x_node = "root" get_node_info("root") return else @right_cell_text = _("%{model} \"%{name}\"") % {:name=>@record.name, :model=>"#{ui_lookup(:model => model && model != "VmOrTemplate" ? model : TreeBuilder.get_model_for_prefix(@nodetype))}"} end else # Get list of child VMs of this node options = {:model=>model} if x_node == "root" # TODO: potential to move this into a model with a scope built into it options[:where_clause] = ["vms.type IN (?)", VmInfra::SUBCLASSES + TemplateInfra::SUBCLASSES] if x_active_tree == :vandt_tree process_show_list(options) # Get all VMs & Templates # :model=>ui_lookup(:models=>"VmOrTemplate")) # TODO: Change ui_lookup/dictionary to handle VmOrTemplate, returning VMs And Templates @right_cell_text = _("All %s") % title ? "#{title}" : "VMs & Templates" else if TreeBuilder.get_model_for_prefix(@nodetype) == "Hash" options[:where_clause] = ["vms.type IN (?)", VmInfra::SUBCLASSES + TemplateInfra::SUBCLASSES] if x_active_tree == :vandt_tree if id == "orph" options[:where_clause] = MiqExpression.merge_where_clauses(options[:where_clause], VmOrTemplate::ORPHANED_CONDITIONS) process_show_list(options) @right_cell_text = "Orphaned #{model ? ui_lookup(:models => model) : "VMs & Templates"}" elsif id == "arch" options[:where_clause] = MiqExpression.merge_where_clauses(options[:where_clause], VmOrTemplate::ARCHIVED_CONDITIONS) process_show_list(options) @right_cell_text = "Archived #{model ? ui_lookup(:models => model) : "VMs & Templates"}" end elsif TreeBuilder.get_model_for_prefix(@nodetype) == "MiqSearch" process_show_list(options) # Get all VMs & Templates @right_cell_text = _("All %s") % model ? "#{ui_lookup(:models=>model)}" : "VMs & Templates" else rec = TreeBuilder.get_model_for_prefix(@nodetype).constantize.find(from_cid(id)) options.merge!({:association=>"#{@nodetype == "az" ? "vms" : "all_vms_and_templates"}", :parent=>rec}) process_show_list(options) model_name = @nodetype == "d" ? "Datacenter" : ui_lookup(:model=>rec.class.base_class.to_s) @is_redhat = case model_name when 'Datacenter' then EmsInfra.find(rec.ems_id).type == 'EmsRedhat' when 'Provider' then rec.type == 'EmsRedhat' else false end # @right_cell_text = "#{ui_lookup(:models=>"VmOrTemplate")} under #{model_name} \"#{rec.name}\"" # TODO: Change ui_lookup/dictionary to handle VmOrTemplate, returning VMs And Templates @right_cell_text = "#{model ? ui_lookup(:models => model) : "VMs & Templates"} under #{model_name} \"#{rec.name}\"" end end # Add adv search filter to header @right_cell_text += @edit[:adv_search_applied][:text] if @edit && @edit[:adv_search_applied] end if @edit && @edit.fetch_path(:adv_search_applied, :qs_exp) # If qs is active, save it in history x_history_add_item(:id=>x_node, :qs_exp=>@edit[:adv_search_applied][:qs_exp], :text=>@right_cell_text) else x_history_add_item(:id=>treenodeid, :text=>@right_cell_text) # Add to history pulldown array end # After adding to history, add name filter suffix if showing a list unless ["Vm", "MiqTemplate"].include?(TreeBuilder.get_model_for_prefix(@nodetype)) unless @search_text.blank? @right_cell_text += _(" (Names with \"%s\")") % @search_text end end end # Replace the right cell of the explorer def replace_right_cell(action=nil) @explorer = true @sb[:action] = action if !action.nil? if @sb[:action] || params[:display] partial, action, @right_cell_text = set_right_cell_vars # Set partial name, action and cell header end if !@in_a_form && !@sb[:action] get_node_info(x_node) #set @delete_node since we don't rebuild vm tree @delete_node = params[:id] if @replace_trees #get_node_info might set this type, id = x_node.split("_").last.split("-") record_showing = type && ["Vm", "MiqTemplate"].include?(TreeBuilder.get_model_for_prefix(type)) c_buttons, c_xml = build_toolbar_buttons_and_xml(center_toolbar_filename) # Use vm or template tb if record_showing cb_buttons, cb_xml = build_toolbar_buttons_and_xml("custom_buttons_tb") v_buttons, v_xml = build_toolbar_buttons_and_xml("x_summary_view_tb") else v_buttons, v_xml = build_toolbar_buttons_and_xml("x_gtl_view_tb") end elsif ["compare","drift"].include?(@sb[:action]) @in_a_form = true # Turn on Cancel button c_buttons, c_xml = build_toolbar_buttons_and_xml("#{@sb[:action]}_center_tb") v_buttons, v_xml = build_toolbar_buttons_and_xml("#{@sb[:action]}_view_tb") elsif @sb[:action] == "performance" c_buttons, c_xml = build_toolbar_buttons_and_xml("x_vm_performance_tb") elsif @sb[:action] == "drift_history" c_buttons, c_xml = build_toolbar_buttons_and_xml("drifts_center_tb") # Use vm or template tb elsif ["snapshot_info","vmtree_info"].include?(@sb[:action]) c_buttons, c_xml = build_toolbar_buttons_and_xml("x_vm_center_tb") # Use vm or template tb end h_buttons, h_xml = build_toolbar_buttons_and_xml("x_history_tb") unless @in_a_form unless x_active_tree == :vandt_tree # Clicked on right cell record, open the tree enough to show the node, if not already showing if params[:action] == "x_show" && @record && # Showing a record !@in_a_form && # Not in a form x_tree[:type] != :filter # Not in a filter tree add_nodes = open_parent_nodes(@record) # Open the parent nodes of selected record, if not open end end # Build presenter to render the JS command for the tree update presenter = ExplorerPresenter.new( :active_tree => x_active_tree, :temp => @temp, :add_nodes => add_nodes, # Update the tree with any new nodes :delete_node => @delete_node, # Remove a new node from the tree ) r = proc { |opts| render_to_string(opts) } add_ajax = false if record_showing presenter[:set_visible_elements][:form_buttons_div] = false path_dir = @record.kind_of?(VmCloud) || @record.kind_of?(TemplateCloud) ? "vm_cloud" : "vm_common" presenter[:update_partials][:main_div] = r[:partial=>"#{path_dir}/main", :locals=>{:controller=>'vm'}] elsif @in_a_form partial_locals = {:controller=>'vm'} partial_locals[:action_url] = @lastaction if partial == 'layouts/x_gtl' presenter[:update_partials][:main_div] = r[:partial=>partial, :locals=>partial_locals] locals = {:action_url => action, :record_id => @record ? @record.id : nil} if ['clone', 'migrate', 'miq_request_new', 'pre_prov', 'publish', 'reconfigure', 'retire'].include?(@sb[:action]) locals[:no_reset] = true # don't need reset button on the screen locals[:submit_button] = ['clone', 'migrate', 'publish', 'reconfigure', 'pre_prov'].include?(@sb[:action]) # need submit button on the screen locals[:continue_button] = ['miq_request_new'].include?(@sb[:action]) # need continue button on the screen update_buttons(locals) if @edit && @edit[:buttons].present? presenter[:clear_tree_cookies] = "prov_trees" end if ['snapshot_add'].include?(@sb[:action]) locals[:no_reset] = true locals[:create_button] = true end if @record.kind_of?(Dialog) @record.dialog_fields.each do |field| if %w(DialogFieldDateControl DialogFieldDateTimeControl).include?(field.type) presenter[:build_calendar] = { :date_from => field.show_past_dates ? nil : Time.now.in_time_zone(session[:user_tz]).to_i * 1000 } end end end if %w(ownership protect reconfigure retire tag).include?(@sb[:action]) locals[:multi_record] = true # need save/cancel buttons on edit screen even tho @record.id is not there locals[:record_id] = @sb[:rec_id] || @edit[:object_ids][0] if @sb[:action] == "tag" unless @sb[:action] == 'ownership' presenter[:build_calendar] = { :date_from => Time.now.in_time_zone(@tz).to_i * 1000, :date_to => nil, } end end add_ajax = true if ['compare', 'drift'].include?(@sb[:action]) presenter[:update_partials][:custom_left_cell_div] = r[ :partial => 'layouts/listnav/x_compare_sections', :locals => {:truncate_length => 23}] presenter[:cell_a_view] = 'custom' end elsif @sb[:action] || params[:display] partial_locals = { :controller => ['ontap_storage_volumes', 'ontap_file_shares', 'ontap_logical_disks', 'ontap_storage_systems'].include?(@showtype) ? @showtype.singularize : 'vm' } if partial == 'layouts/x_gtl' partial_locals[:action_url] = @lastaction presenter[:miq_parent_id] = @record.id # Set parent rec id for JS function miqGridSort to build URL presenter[:miq_parent_class] = request[:controller] # Set parent class for URL also end presenter[:update_partials][:main_div] = r[:partial=>partial, :locals=>partial_locals] add_ajax = true presenter[:build_calendar] = true else presenter[:update_partials][:main_div] = r[:partial=>'layouts/x_gtl'] end presenter[:ajax_action] = { :controller => request.parameters["controller"], :action => @ajax_action, :record_id => @record.id } if add_ajax && ['performance','timeline'].include?(@sb[:action]) # Replace the searchbox presenter[:replace_partials][:adv_searchbox_div] = r[ :partial => 'layouts/x_adv_searchbox', :locals => {:nameonly => ([:images_tree, :instances_tree, :vandt_tree].include?(x_active_tree))} ] # Clear the JS gtl_list_grid var if changing to a type other than list presenter[:clear_gtl_list_grid] = @gtl_type && @gtl_type != 'list' presenter[:clear_tree_cookies] = "edit_treeOpenStatex" if @sb[:action] == "policy_sim" # Handle bottom cell if @pages || @in_a_form if @pages && !@in_a_form @ajax_paging_buttons = true # FIXME: this should not be done this way if @sb[:action] && @record # Came in from an action link presenter[:update_partials][:paging_div] = r[ :partial => 'layouts/x_pagingcontrols', :locals => { :action_url => @sb[:action], :action_method => @sb[:action], # FIXME: action method and url the same?! :action_id => @record.id } ] else presenter[:update_partials][:paging_div] = r[:partial => 'layouts/x_pagingcontrols'] end presenter[:set_visible_elements][:form_buttons_div] = false presenter[:set_visible_elements][:pc_div_1] = true elsif @in_a_form if @sb[:action] == 'dialog_provision' presenter[:update_partials][:form_buttons_div] = r[ :partial => 'layouts/x_dialog_buttons', :locals => { :action_url => action, :record_id => @edit[:rec_id], } ] else presenter[:update_partials][:form_buttons_div] = r[:partial => 'layouts/x_edit_buttons', :locals => locals] end presenter[:set_visible_elements][:pc_div_1] = false presenter[:set_visible_elements][:form_buttons_div] = true end presenter[:expand_collapse_cells][:c] = 'expand' else presenter[:expand_collapse_cells][:c] = 'collapse' end presenter[:right_cell_text] = @right_cell_text # Rebuild the toolbars presenter[:set_visible_elements][:history_buttons_div] = h_buttons && h_xml presenter[:set_visible_elements][:center_buttons_div] = c_buttons && c_xml presenter[:set_visible_elements][:view_buttons_div] = v_buttons && v_xml presenter[:set_visible_elements][:custom_buttons_div] = cb_buttons && cb_xml presenter[:reload_toolbars][:history] = {:buttons => h_buttons, :xml => h_xml} if h_buttons && h_xml presenter[:reload_toolbars][:center] = {:buttons => c_buttons, :xml => c_xml} if c_buttons && c_xml presenter[:reload_toolbars][:view] = {:buttons => v_buttons, :xml => v_xml} if v_buttons && v_xml presenter[:reload_toolbars][:custom] = {:buttons => cb_buttons, :xml => cb_xml} if cb_buttons && cb_xml presenter[:expand_collapse_cells][:a] = h_buttons || c_buttons || v_buttons ? 'expand' : 'collapse' presenter[:miq_record_id] = @record ? @record.id : nil # Hide/show searchbox depending on if a list is showing presenter[:set_visible_elements][:adv_searchbox_div] = !(@record || @in_a_form) presenter[:osf_node] = x_node # Open, select, and focus on this node # Save open nodes, if any were added presenter[:save_open_states_trees] = [x_active_tree.to_s] if add_nodes presenter[:set_visible_elements][:blocker_div] = false unless @edit && @edit[:adv_search_open] presenter[:set_visible_elements][:quicksearchbox] = false presenter[:lock_unlock_trees][x_active_tree] = @in_a_form && @edit # Render the JS responses to update the explorer screen render :js => presenter.to_html end # get the host that this vm belongs to def get_host_for_vm(vm) if vm.host @hosts = Array.new @hosts.push vm.host end end # Set form variables for edit def set_form_vars @edit = Hash.new @edit[:vm_id] = @record.id @edit[:new] = Hash.new @edit[:current] = Hash.new @edit[:key] = "vm_edit__#{@record.id || "new"}" @edit[:explorer] = true if params[:action] == "x_button" || session.fetch_path(:edit, :explorer) @edit[:current][:custom_1] = @edit[:new][:custom_1] = @record.custom_1.to_s @edit[:current][:description] = @edit[:new][:description] = @record.description.to_s @edit[:pchoices] = Hash.new # Build a hash for the parent choices box VmOrTemplate.all.each { |vm| @edit[:pchoices][vm.name + " -- #{vm.location}"] = vm.id unless vm.id == @record.id } # Build a hash for the parents to choose from, not matching current VM @edit[:pchoices]['"no parent"'] = -1 # Add "no parent" entry if @record.parents.length == 0 # Set the currently selected parent @edit[:new][:parent] = -1 else @edit[:new][:parent] = @record.parents.first.id end vms = @record.children # Get the child VMs @edit[:new][:kids] = Hash.new vms.each { |vm| @edit[:new][:kids][vm.name + " -- #{vm.location}"] = vm.id } # Build a hash for the kids list box @edit[:choices] = Hash.new VmOrTemplate.all.each { |vm| @edit[:choices][vm.name + " -- #{vm.location}"] = vm.id if vm.parents.length == 0 } # Build a hash for the VMs to choose from, only if they have no parent @edit[:new][:kids].each_key { |key| @edit[:choices].delete(key) } # Remove any VMs that are in the kids list box from the choices @edit[:choices].delete(@record.name + " -- #{@record.location}") # Remove the current VM from the choices list @edit[:current][:parent] = @edit[:new][:parent] @edit[:current][:kids] = @edit[:new][:kids].dup session[:edit] = @edit end #set partial name and cell header for edit screens def set_right_cell_vars name = @record ? @record.name.to_s.gsub(/'/,"\\\\'") : "" # If record, get escaped name table = request.parameters["controller"] case @sb[:action] when "compare","drift" partial = "layouts/#{@sb[:action]}" if @sb[:action] == "compare" header = _("Compare %s") % ui_lookup(:model => @sb[:compare_db]) else header = _("Drift for %{model} \"%{name}\"") % {:name => name, :model => ui_lookup(:model => @sb[:compare_db])} end action = nil when "clone","migrate","publish" partial = "miq_request/prov_edit" header = _("%{task} %{model}") % {:task=>@sb[:action].capitalize, :model=>ui_lookup(:table => table)} action = "prov_edit" when "dialog_provision" partial = "shared/dialogs/dialog_provision" header = @right_cell_text action = "dialog_form_button_pressed" when "edit" partial = "vm_common/form" header = _("Editing %{model} \"%{name}\"") % {:name=>name, :model=>ui_lookup(:table => table)} action = "edit_vm" when "evm_relationship" partial = "vm_common/evm_relationship" header = _("Edit CFME Server Relationship for %{model} \"%{name}\"") % {:model=>ui_lookup(:table => table), :name => name} action = "evm_relationship_update" #when "miq_request_new" # partial = "miq_request/prov_edit" # header = _("Provision %s") % ui_lookup(:models=>"Vm") # action = "prov_edit" when "miq_request_new" partial = "miq_request/pre_prov" typ = request.parameters[:controller] == "vm_cloud" ? "an #{ui_lookup(:table => "template_cloud")}" : "a #{ui_lookup(:table => "template_infra")}" header = _("Provision %{model} - Select %{typ}") % {:model=>ui_lookup(:tables => table), :typ => typ} action = "pre_prov" when "pre_prov" partial = "miq_request/prov_edit" header = _("Provision %s") % ui_lookup(:tables => table) action = "pre_prov_continue" when "pre_prov_continue" partial = "miq_request/prov_edit" header = _("Provision %s") % ui_lookup(:tables => table) action = "prov_edit" when "ownership" partial = "shared/views/ownership" header = _("Set Ownership for %s") % ui_lookup(:table => table) action = "ownership_update" when "performance" partial = "layouts/performance" header = _("Capacity & Utilization data for %{model} \"%{name}\"") % {:model=>ui_lookup(:table => table), :name => name} x_history_add_item(:id=>x_node, :text=>header, :button=>params[:pressed], :display=>params[:display]) action = nil when "policy_sim" if params[:action] == "policies" partial = "vm_common/policies" header = _("%s Policy Simulation") % ui_lookup(:table => table) action = nil else partial = "layouts/policy_sim" header = _("%s Policy Simulation") % ui_lookup(:table => table) action = nil end when "protect" partial = "layouts/protect" header = _("%s Policy Assignment") % ui_lookup(:table => table) action = "protect" when "reconfigure" partial = "vm_common/reconfigure" header = _("Reconfigure %s") % ui_lookup(:table => table) action = "reconfigure_update" when "retire" partial = "shared/views/retire" header = _("Set/Remove retirement date for %s") % ui_lookup(:table => table) action = "retire" when "right_size" partial = "vm_common/right_size" header = _("Right Size Recommendation for %{model} \"%{name}\"") % {:name=>name, :model=>ui_lookup(:table => table)} action = nil when "tag" partial = "layouts/tagging" header = _("Edit Tags for %s") % ui_lookup(:table => table) action = "tagging_edit" when "snapshot_add" partial = "vm_common/snap" header = _("Adding a new %s") % ui_lookup(:model => "Snapshot") action = "snap_vm" when "timeline" partial = "layouts/tl_show" header = _("Timelines for %{model} \"%{name}\"") % {:model=>ui_lookup(:table => table), :name=>name} x_history_add_item(:id=>x_node, :text=>header, :button=>params[:pressed]) action = nil else # now take care of links on summary screen if ["details","ontap_storage_volumes","ontap_file_shares","ontap_logical_disks","ontap_storage_systems"].include?(@showtype) partial = "layouts/x_gtl" elsif @showtype == "item" partial = "layouts/item" elsif @showtype == "drift_history" partial = "layouts/#{@showtype}" else partial = "#{@showtype == "compliance_history" ? "shared/views" : "vm_common"}/#{@showtype}" end if @showtype == "item" header = _("%{action} \"%{item_name}\" for %{model} \"%{name}\"") % {:model=>ui_lookup(:table => table), :name=>name, :item_name=>@item.kind_of?(ScanHistory) ? @item.started_on.to_s : @item.name, :action=>Dictionary::gettext(@sb[:action], :type=>:ui_action, :notfound=>:titleize).singularize} x_history_add_item(:id=>x_node, :text=>header, :action=>@sb[:action], :item=>@item.id) else header = _("\"%{action}\" for %{model} \"%{name}\"") % {:model=>ui_lookup(:table => table), :name=>name, :action=>Dictionary::gettext(@sb[:action], :type=>:ui_action, :notfound=>:titleize)} if @display && @display != "main" x_history_add_item(:id=>x_node, :text=>header, :display=>@display) else x_history_add_item(:id=>x_node, :text=>header, :action=>@sb[:action]) if @sb[:action] != "drift_history" end end action = nil end return partial,action,header end def get_vm_child_selection if params["right.x"] || params[:button] == "right" if params[:kids_chosen] == nil add_flash(_("No %s were selected to move right") % "VMs", :error) else kids = @edit[:new][:kids].invert params[:kids_chosen].each do |kc| if @edit[:new][:kids].has_value?(kc.to_i) @edit[:choices][kids[kc.to_i]] = kc.to_i @edit[:new][:kids].delete(kids[kc.to_i]) end end end elsif params["left.x"] || params[:button] == "left" if params[:choices_chosen] == nil add_flash(_("No %s were selected to move left") % "VMs", :error) else kids = @edit[:choices].invert params[:choices_chosen].each do |cc| if @edit[:choices].has_value?(cc.to_i) @edit[:new][:kids][kids[cc.to_i]] = cc.to_i @edit[:choices].delete(kids[cc.to_i]) end end end elsif params["allright.x"] || params[:button] == "allright" if @edit[:new][:kids].length == 0 add_flash(_("No child VMs to move right, no action taken"), :error) else @edit[:new][:kids].each do |key, value| @edit[:choices][key] = value end @edit[:new][:kids].clear end end end # Get variables from edit form def get_form_vars @record = VmOrTemplate.find_by_id(@edit[:vm_id]) @edit[:new][:custom_1] = params[:custom_1] if params[:custom_1] @edit[:new][:description] = params[:description] if params[:description] @edit[:new][:parent] = params[:chosen_parent].to_i if params[:chosen_parent] #if coming from explorer get_vm_child_selection if ["allright","left","right"].include?(params[:button]) end # Build the audit object when a record is saved, including all of the changed fields def build_saved_vm_audit(vm) msg = "[#{vm.name} -- #{vm.location}] Record saved (" event = "vm_genealogy_change" i = 0 @edit[:new].each_key do |k| if @edit[:new][k] != @edit[:current][k] msg = msg + ", " if i > 0 i += 1 if k == :kids #if @edit[:new][k].is_a?(Hash) msg = msg + k.to_s + ":[" + @edit[:current][k].keys.join(",") + "] to [" + @edit[:new][k].keys.join(",") + "]" elsif k == :parent msg = msg + k.to_s + ":[" + @edit[:pchoices].invert[@edit[:current][k]] + "] to [" + @edit[:pchoices].invert[@edit[:new][k]] + "]" else msg = msg + k.to_s + ":[" + @edit[:current][k].to_s + "] to [" + @edit[:new][k].to_s + "]" end end end msg = msg + ")" audit = {:event=>event, :target_id=>vm.id, :target_class=>vm.class.base_class.name, :userid => session[:userid], :message=>msg} end # get the sort column for the detail lists that was clicked on, else use the current one def get_detail_sort_col if params[:page]==nil && params[:type] == nil && params[:searchtag] == nil # paging, gtltype change, or search tag did not come in if params[:sortby] == nil # no column clicked, reset to first column, ascending @detail_sortcol = 0 @detail_sortdir = "ASC" else if @detail_sortcol == params[:sortby].to_i # if same column was selected @detail_sortdir = @detail_sortdir == "ASC" ? "DESC" : "ASC" # switch around ascending/descending else @detail_sortdir = "ASC" end @detail_sortcol = params[:sortby].to_i end end # in case sort column is not set, set the defaults if @detail_sortcol == nil @detail_sortcol = 0 @detail_sortdir = "ASC" end return @detail_sortcol end # Gather up the vm records from the DB def get_vms(selected=nil) page = params[:page] == nil ? 1 : params[:page].to_i @current_page = page @items_per_page = @settings[:perpage][@gtl_type.to_sym] # Get the per page setting for this gtl type if selected # came in with a list of selected ids (i.e. checked vms) @record_pages, @records = paginate(:vms, :per_page => @items_per_page, :order => @col_names[get_sort_col] + " " + @sortdir, :conditions=>["id IN (?)", selected]) else # getting ALL vms @record_pages, @records = paginate(:vms, :per_page => @items_per_page, :order => @col_names[get_sort_col] + " " + @sortdir) end end def identify_record(id, klass = self.class.model) record = super # Need to find the unauthorized record if in explorer if record.nil? && @explorer record = klass.find_by_id(from_cid(id)) @unauthorized = true unless record.nil? end record end def update_buttons(locals) locals[:continue_button] = locals[:submit_button] = false locals[:continue_button] = true if @edit[:buttons].include?(:continue) locals[:submit_button] = true if @edit[:buttons].include?(:submit) end end
class Square attr_reader :x, :y def initialize(x, y) @x = x @y = y end def ==(other) x == other.x and y == other.y end def out_of_the_board [x, y].any? { |coordinate| coordinate < 0 or coordinate > 7 } end def to_a [x, y] end end class Piece WHITE = "white".freeze BLACK = "black".freeze attr_reader :color def initialize(color, board) @color = color @board = board end def obstructions?(dx, dy, steps, position) (1...steps).each do |step| x = position.x + step * dx y = position.y + step * dy return true unless @board.empty(Square.new(x, y)) end false end def move(from, to) @board.move(from, to) if valid_move?(from, to) end def any_moves?(from, in_directions, max_steps=8) directions.each do |dx, dy| to, steps = Square.new(from.x, from.y), 0 while true to, steps = Square.new(to.x + dx, to.y + dy), steps.succ break if to.out_of_the_board if @board.empty(to) and @board.king_remains_safe_after_move?(from, to) return true if @board.color_of_piece_on(to) != color return true if @board.king_remains_safe_after_move?(from, to) else break end break if steps == max_steps end end false end end class Queen < Piece def valid_move?(from, to) Rook.new(@color, @board).valid_move?(from, to) or Bishop.new(@color, @board).valid_move?(from, to) end def any_moves?(from) in_directions = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]] super(from, in_directions) end end class Bishop < Piece def valid_move?(from, to) return false if (from.x - to.x).abs != (from.y - to.y) dx = from.x <=> to.x dy = from.y <=> to.y steps = (from.x - to.x).abs return false if obstructions?(dx, dy, steps, from) @board.king_remains_safe_after_move?(from, to) end def any_moves?(from) in_directions = [[1, 1], [-1, 1], [1, -1], [-1, -1]] super(from, in_directions) end end class Knight < Piece def valid_move?(from, to) horizontal = (from.x - to.x).abs == 2 and (from.y - to.y).abs == 1 vertical =(from.x - to.x).abs == 1 and (from.y - to.y).abs == 2 return false unless vertical or horizontal @board.king_remains_safe_after_move?(from, to) end def any_moves?(from) positions = [[from.x + 1, from.y + 2], [from.x + 2, from.y + 1], [from.x + 2, from.y - 1], [from.x + 1, from.y - 2], [from.x - 1, from.y + 2], [from.x - 2, from.y + 1], [from.x - 1, from.y - 2], [from.x - 2, from.y - 1]] positions.each do |position| next unless position.all? { |coordinate| coordinate.between?(0, 7) } return true if valid_move?(from, position) end end end class Pawn < Piece attr_reader :moved def initialize(color, board) super @moved = false end def valid_move?(from, to) return false unless valid_direction?(from, to) if (to.y - from.y).abs == 1 return false if from.x == to.x and not @board.empty?(to) return false if (from.x - to.x).abs == 1 and @board.empty?(to) elsif (to.y - from.y).abs == 2 return false if moved or from.x != to.x or obstructions?(0, to.x <=> from.x, 3, from) else return false end @board.king_remains_safe_after_move?(from, to) end def valid_direction?(from, to) @board.color_of_piece_on(from) == WHITE ? to.y < from.y : to.y > from.y end def any_moves?(from) positions = [[from.x + 1, from.y - 1], [from.x, from.y - 1], [from.x - 1, from.y - 1], [from.x, from.y + 1], [from.x + 1, from.y + 1], [from.x - 1, from.y + 1]] positions.each do |position| next unless position.all? { |coordinate| coordinate.between?(0, 7) } return true if valid_move?(from, position) end end def move(from, to) if super @moved = true @board.pawn_promotion_position = to if to.y == 0 or to.y == 7 end end end class King < Piece attr_reader :moved def initialize(color, board) super @moved = false end def castle?(king_position, rook_position) return false if moved or not piece_on(rook_position).is_a? Rook return false if piece_on(rook_position).moved square_between_king_and_rook = Square.new(king_position.x, king_position.y) dx, dy, steps = rook_position.x > king_position.x ? [1, 0, 3] : [-1, 0, 4] return false if obstructions?(dx, dy, steps, king_position) 3.times do return false unless king_safe?(square_between_king_and_rook) square_between_king_and_rook.x += dx end true end def valid_move?(from, to) return false if (from.y - to.y).abs > 1 if (from.x - to.x).abs > 1 if to.x == from.x + 2 and from.y == to.y rook_position = Square.new(7, from.y) return false unless castle?(from, rook_position) elsif to.x == from.x - 2 and from.y == to.y rook_position = Square.new(0, from.y) return false unless castle?(from, rook_position) else return false end end @board.king_remains_safe_after_move?(from, to) end def safe_from?(position) not (attacked_by_a_pawn?(position) or attacked_by_a_knight?(position) or attacked_by_other?(position)) end def attacked_by_a_pawn?(from) if color == WHITE positions = [[from.x + 1, from.y - 1], [from.x - 1, from.y - 1]] else positions = [[from.x + 1, from.y + 1], [from.x + 1, from.y + 1]] end positions.any? do |position| @board.piece_on(position).is_a? Pawn and @board.piece_on(position).color != color end end def attacked_by_a_knight?(from) positions = [[from.x + 2, from.y + 1], [from.x + 2, from.y - 1], [from.x - 2, from.y + 1], [from.x - 2, from.y - 1], [from.x + 1, from.y + 2], [from.x + 1, from.y - 2], [from.x - 1, from.y + 2], [from.x - 1, from.y - 2]] positions.any? do |position| @board.piece_on(position).is_a? Knight and @board.piece_on(position).color != color end end def attacked_by_other?(position) directions = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]] directions.each do |dx, dy| to, steps = Square.new(position.x, position.y), 0 while true to, steps = Square.new(to.x + dx, to.y + dy), steps.succ break if to.out_of_the_board next if @board.empty(to) break if @board.color_of_piece_on(to) == color case @board.piece_on(to) when King then return true if steps == 1 when Queen then return true when Rook then return true if dx.abs != dy.abs when Bishop then return true if dx.abs == dy.abs end break end end false end def any_moves?(from) in_directions = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]] return true if super(from, in_directions) right_rook_position = Square.new(from.x + 3, from.y) left_rook_position = Square.new(from.x - 4, from.y) castle?(from, right_rook_position) or castle?(from, left_rook_position) end def move(from, to) if valid_move?(from, to) if to.x == from.x + 2 @board.move(Square.new(7, to.y), Square.new(5, to.y)) elsif to.x == from.x - 2 @board.move(Square.new(0, to.y), Square.new(3, to.y)) end @board.move(from, to) @moved = true end end end class Rook < Piece attr_reader :moved def initialize(color, board) super @moved = false end def valid_move?(from, to) return false if from.x != to.x and from.y != to.y dx = to.x <=> from.x dy = to.y <=> from.y steps = [(from.x - to.x).abs, (from.y - to.y).abs].max return false if obstructions?(dx, dy, steps, from) @board.king_remains_safe_after_move?(from, to) end def any_moves?(from) in_directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] super(from, in_directions) end def move(from, to) @moved = true if super end end class ChessBoard attr_reader :game_status, :turn attr_writer :pawn_promotion_position WHITE = "white".freeze BLACK = "black".freeze GAME_IN_PROGRESS = "Game in progress.".freeze BLACK_WIN = "Black win!".freeze WHITE_WIN = "White win!".freeze STALEMATE = "Stalemate!".freeze def initialize @board = { [0, 0] => Rook.new(BLACK, self), [1, 0] => Knight.new(BLACK, self), [2, 0] => Bishop.new(BLACK, self), [3, 0] => Queen.new(BLACK, self), [4, 0] => King.new(BLACK, self), [5, 0] => Bishop.new(BLACK, self), [6, 0] => Knight.new(BLACK, self), [7, 0] => Rook.new(BLACK, self), [0, 7] => Rook.new(WHITE, self), [1, 7] => Knight.new(WHITE, self), [2, 7] => Bishop.new(WHITE, self), [3, 7] => Queen.new(WHITE, self), [4, 7] => King.new(WHITE, self), [5, 7] => Bishop.new(WHITE, self), [6, 7] => Knight.new(WHITE, self), [7, 7] => Rook.new(WHITE, self), } 0.upto(7).each do |column| @board[column, 1] = Pawn.new(BLACK, self) @board[column, 6] = Pawn.new(WHITE, self) end @turn = WHITE @game_status = GAME_IN_PROGRESS @pawn_promotion_position = nil end def move(from, to) @board[to.to_a] = @board[from.to_a] @board.delete from end def king_remains_safe_after_move?(from, to) from_before_move = piece_on(from) to_before_move = piece_on(to) move(from, to) king_position, king = king_of(turn).to_a.flatten(1) result = king.safe_from?(king_position) @board[from.to_a] = from_before_move @board[to.to_a] = to_before_move result end def out_of_the_board?(from, to) from.out_of_the_board or to.out_of_the_board end def color_of_piece_on(position) @board[position.to_a].color end def king_of(color) @board.select { |_, piece| piece.is_a? King and piece.color == color } end def empty?(position) @board[position.to_a].nil? end def piece_on(position) @board[position.to_a] end def pieces_of_the_same_color?(from, to) not empty?(to) and color_of_piece_on(from) == color_of_piece_on(to) end def any_valid_moves_for_player_on_turn? @board.each do |from, piece| return true if piece.color == turn and piece.any_moves?(Square.new(*from)) end false end def king_of_current_player_is_in_check? king_position, king = king_of(turn).to_a.flatten(1) true unless king.safe_from?(Square.new(*king_position)) end def switch_players turn == WHITE ? BLACK : WHITE end def player_owns_piece_on?(position) turn == color_of_piece_on(position) end def allowed_to_move_piece_on?(from, to) piece_on(from).move(from, to) end def game_over? unless any_valid_moves_for_player_on_turn? if king_of_current_player_is_in_check? @game_status = turn == WHITE ? BLACK_WIN : WHITE_WIN else @game_status = STALEMATE end end end def make_a_move(from, to) return if empty?(from) return if out_of_the_board?(from, to) return if pieces_of_the_same_color?(from, to) return if from == to return unless player_owns_piece_on?(from) return unless allowed_to_move_piece_on?(from, to) switch_players game_over? end def white_win? @game_status == WHITE_WIN end def black_win? @game_status == BLACK_WIN end def stalemate? @game_status == STALEMATE end def promote_pawn_to(piece) @board[pawn_promotion_position.to_a] = piece @pawn_promotion_position = nil game_over? end def promotion? @pawn_promotion_position end end Modify Piece#any_moves? class Square attr_reader :x, :y def initialize(x, y) @x = x @y = y end def ==(other) x == other.x and y == other.y end def out_of_the_board [x, y].any? { |coordinate| coordinate < 0 or coordinate > 7 } end def to_a [x, y] end end class Piece WHITE = "white".freeze BLACK = "black".freeze attr_reader :color def initialize(color, board) @color = color @board = board end def obstructions?(dx, dy, steps, position) (1...steps).each do |step| x = position.x + step * dx y = position.y + step * dy return true unless @board.empty(Square.new(x, y)) end false end def move(from, to) @board.move(from, to) if valid_move?(from, to) end def any_moves?(from, in_directions, max_steps=8) directions.each do |dx, dy| to, steps = Square.new(from.x, from.y), 0 while true to, steps = Square.new(to.x + dx, to.y + dy), steps.succ break if to.out_of_the_board if @board.empty(to) or @board.color_of_piece_on(to) != color return true if @board.king_remains_safe_after_move?(from, to) end break if @board.color_of_piece_on(to) == color or steps == max_steps end end false end end class Queen < Piece def valid_move?(from, to) Rook.new(@color, @board).valid_move?(from, to) or Bishop.new(@color, @board).valid_move?(from, to) end def any_moves?(from) in_directions = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]] super(from, in_directions) end end class Bishop < Piece def valid_move?(from, to) return false if (from.x - to.x).abs != (from.y - to.y) dx = from.x <=> to.x dy = from.y <=> to.y steps = (from.x - to.x).abs return false if obstructions?(dx, dy, steps, from) @board.king_remains_safe_after_move?(from, to) end def any_moves?(from) in_directions = [[1, 1], [-1, 1], [1, -1], [-1, -1]] super(from, in_directions) end end class Knight < Piece def valid_move?(from, to) horizontal = (from.x - to.x).abs == 2 and (from.y - to.y).abs == 1 vertical =(from.x - to.x).abs == 1 and (from.y - to.y).abs == 2 return false unless vertical or horizontal @board.king_remains_safe_after_move?(from, to) end def any_moves?(from) positions = [[from.x + 1, from.y + 2], [from.x + 2, from.y + 1], [from.x + 2, from.y - 1], [from.x + 1, from.y - 2], [from.x - 1, from.y + 2], [from.x - 2, from.y + 1], [from.x - 1, from.y - 2], [from.x - 2, from.y - 1]] positions.each do |position| next unless position.all? { |coordinate| coordinate.between?(0, 7) } return true if valid_move?(from, position) end end end class Pawn < Piece attr_reader :moved def initialize(color, board) super @moved = false end def valid_move?(from, to) return false unless valid_direction?(from, to) if (to.y - from.y).abs == 1 return false if from.x == to.x and not @board.empty?(to) return false if (from.x - to.x).abs == 1 and @board.empty?(to) elsif (to.y - from.y).abs == 2 return false if moved or from.x != to.x or obstructions?(0, to.x <=> from.x, 3, from) else return false end @board.king_remains_safe_after_move?(from, to) end def valid_direction?(from, to) @board.color_of_piece_on(from) == WHITE ? to.y < from.y : to.y > from.y end def any_moves?(from) positions = [[from.x + 1, from.y - 1], [from.x, from.y - 1], [from.x - 1, from.y - 1], [from.x, from.y + 1], [from.x + 1, from.y + 1], [from.x - 1, from.y + 1]] positions.each do |position| next unless position.all? { |coordinate| coordinate.between?(0, 7) } return true if valid_move?(from, position) end end def move(from, to) if super @moved = true @board.pawn_promotion_position = to if to.y == 0 or to.y == 7 end end end class King < Piece attr_reader :moved def initialize(color, board) super @moved = false end def castle?(king_position, rook_position) return false if moved or not piece_on(rook_position).is_a? Rook return false if piece_on(rook_position).moved square_between_king_and_rook = Square.new(king_position.x, king_position.y) dx, dy, steps = rook_position.x > king_position.x ? [1, 0, 3] : [-1, 0, 4] return false if obstructions?(dx, dy, steps, king_position) 3.times do return false unless king_safe?(square_between_king_and_rook) square_between_king_and_rook.x += dx end true end def valid_move?(from, to) return false if (from.y - to.y).abs > 1 if (from.x - to.x).abs > 1 if to.x == from.x + 2 and from.y == to.y rook_position = Square.new(7, from.y) return false unless castle?(from, rook_position) elsif to.x == from.x - 2 and from.y == to.y rook_position = Square.new(0, from.y) return false unless castle?(from, rook_position) else return false end end @board.king_remains_safe_after_move?(from, to) end def safe_from?(position) not (attacked_by_a_pawn?(position) or attacked_by_a_knight?(position) or attacked_by_other?(position)) end def attacked_by_a_pawn?(from) if color == WHITE positions = [[from.x + 1, from.y - 1], [from.x - 1, from.y - 1]] else positions = [[from.x + 1, from.y + 1], [from.x + 1, from.y + 1]] end positions.any? do |position| @board.piece_on(position).is_a? Pawn and @board.piece_on(position).color != color end end def attacked_by_a_knight?(from) positions = [[from.x + 2, from.y + 1], [from.x + 2, from.y - 1], [from.x - 2, from.y + 1], [from.x - 2, from.y - 1], [from.x + 1, from.y + 2], [from.x + 1, from.y - 2], [from.x - 1, from.y + 2], [from.x - 1, from.y - 2]] positions.any? do |position| @board.piece_on(position).is_a? Knight and @board.piece_on(position).color != color end end def attacked_by_other?(position) directions = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]] directions.each do |dx, dy| to, steps = Square.new(position.x, position.y), 0 while true to, steps = Square.new(to.x + dx, to.y + dy), steps.succ break if to.out_of_the_board next if @board.empty(to) break if @board.color_of_piece_on(to) == color case @board.piece_on(to) when King then return true if steps == 1 when Queen then return true when Rook then return true if dx.abs != dy.abs when Bishop then return true if dx.abs == dy.abs end break end end false end def any_moves?(from) in_directions = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]] return true if super(from, in_directions) right_rook_position = Square.new(from.x + 3, from.y) left_rook_position = Square.new(from.x - 4, from.y) castle?(from, right_rook_position) or castle?(from, left_rook_position) end def move(from, to) if valid_move?(from, to) if to.x == from.x + 2 @board.move(Square.new(7, to.y), Square.new(5, to.y)) elsif to.x == from.x - 2 @board.move(Square.new(0, to.y), Square.new(3, to.y)) end @board.move(from, to) @moved = true end end end class Rook < Piece attr_reader :moved def initialize(color, board) super @moved = false end def valid_move?(from, to) return false if from.x != to.x and from.y != to.y dx = to.x <=> from.x dy = to.y <=> from.y steps = [(from.x - to.x).abs, (from.y - to.y).abs].max return false if obstructions?(dx, dy, steps, from) @board.king_remains_safe_after_move?(from, to) end def any_moves?(from) in_directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] super(from, in_directions) end def move(from, to) @moved = true if super end end class ChessBoard attr_reader :game_status, :turn attr_writer :pawn_promotion_position WHITE = "white".freeze BLACK = "black".freeze GAME_IN_PROGRESS = "Game in progress.".freeze BLACK_WIN = "Black win!".freeze WHITE_WIN = "White win!".freeze STALEMATE = "Stalemate!".freeze def initialize @board = { [0, 0] => Rook.new(BLACK, self), [1, 0] => Knight.new(BLACK, self), [2, 0] => Bishop.new(BLACK, self), [3, 0] => Queen.new(BLACK, self), [4, 0] => King.new(BLACK, self), [5, 0] => Bishop.new(BLACK, self), [6, 0] => Knight.new(BLACK, self), [7, 0] => Rook.new(BLACK, self), [0, 7] => Rook.new(WHITE, self), [1, 7] => Knight.new(WHITE, self), [2, 7] => Bishop.new(WHITE, self), [3, 7] => Queen.new(WHITE, self), [4, 7] => King.new(WHITE, self), [5, 7] => Bishop.new(WHITE, self), [6, 7] => Knight.new(WHITE, self), [7, 7] => Rook.new(WHITE, self), } 0.upto(7).each do |column| @board[column, 1] = Pawn.new(BLACK, self) @board[column, 6] = Pawn.new(WHITE, self) end @turn = WHITE @game_status = GAME_IN_PROGRESS @pawn_promotion_position = nil end def move(from, to) @board[to.to_a] = @board[from.to_a] @board.delete from end def king_remains_safe_after_move?(from, to) from_before_move = piece_on(from) to_before_move = piece_on(to) move(from, to) king_position, king = king_of(turn).to_a.flatten(1) result = king.safe_from?(king_position) @board[from.to_a] = from_before_move @board[to.to_a] = to_before_move result end def out_of_the_board?(from, to) from.out_of_the_board or to.out_of_the_board end def color_of_piece_on(position) @board[position.to_a].color end def king_of(color) @board.select { |_, piece| piece.is_a? King and piece.color == color } end def empty?(position) @board[position.to_a].nil? end def piece_on(position) @board[position.to_a] end def pieces_of_the_same_color?(from, to) not empty?(to) and color_of_piece_on(from) == color_of_piece_on(to) end def any_valid_moves_for_player_on_turn? @board.each do |from, piece| return true if piece.color == turn and piece.any_moves?(Square.new(*from)) end false end def king_of_current_player_is_in_check? king_position, king = king_of(turn).to_a.flatten(1) true unless king.safe_from?(Square.new(*king_position)) end def switch_players turn == WHITE ? BLACK : WHITE end def player_owns_piece_on?(position) turn == color_of_piece_on(position) end def allowed_to_move_piece_on?(from, to) piece_on(from).move(from, to) end def game_over? unless any_valid_moves_for_player_on_turn? if king_of_current_player_is_in_check? @game_status = turn == WHITE ? BLACK_WIN : WHITE_WIN else @game_status = STALEMATE end end end def make_a_move(from, to) return if empty?(from) return if out_of_the_board?(from, to) return if pieces_of_the_same_color?(from, to) return if from == to return unless player_owns_piece_on?(from) return unless allowed_to_move_piece_on?(from, to) switch_players game_over? end def white_win? @game_status == WHITE_WIN end def black_win? @game_status == BLACK_WIN end def stalemate? @game_status == STALEMATE end def promote_pawn_to(piece) @board[pawn_promotion_position.to_a] = piece @pawn_promotion_position = nil game_over? end def promotion? @pawn_promotion_position end end
class Ability include CanCan::Ability def initialize(user) # Define abilities for the passed in user here. For example: # # user ||= User.new # guest user (not logged in) # if user.admin? # can :manage, :all # else # can :read, :all # end # # The first argument to `can` is the action you are giving the user # permission to do. # If you pass :manage it will apply to every action. Other common actions # here are :read, :create, :update and :destroy. # # The second argument is the resource the user can perform the action on. # If you pass :all it will apply to every resource. Otherwise pass a Ruby # class of the resource. # # The third argument is an optional hash of conditions to further filter the # objects. # For example, here the user can only update published articles. # # can :update, Article, :published => true # # See the wiki for details: # https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities user ||= User.new # Everyone can see the cities and the squats can :read, Squat can :read, City if user.role == "admin" can :manage, :all # logged in admin user can :update_location, City elsif user.role == "user" can :manage, Squat # logged in regular user can :update, City # logged in regular user else end end end allow regular users to manage pictures class Ability include CanCan::Ability def initialize(user) # Define abilities for the passed in user here. For example: # # user ||= User.new # guest user (not logged in) # if user.admin? # can :manage, :all # else # can :read, :all # end # # The first argument to `can` is the action you are giving the user # permission to do. # If you pass :manage it will apply to every action. Other common actions # here are :read, :create, :update and :destroy. # # The second argument is the resource the user can perform the action on. # If you pass :all it will apply to every resource. Otherwise pass a Ruby # class of the resource. # # The third argument is an optional hash of conditions to further filter the # objects. # For example, here the user can only update published articles. # # can :update, Article, :published => true # # See the wiki for details: # https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities user ||= User.new # Everyone can see the cities and the squats can :read, Squat can :read, City if user.role == "admin" # logged in admin user can :manage, :all can :update_location, City elsif user.role == "user" # logged in regular user can :manage, Squat can :update, City can :manage, Picture else end end end
class Ability include Hydra::Ability # include GeoConcerns::Ability # def can_create_any_work? Hyrax.config.curation_concerns.any? do |curation_concern_type| can?(:create, curation_concern_type) end end # Define any customized permissions here. def custom_permissions alias_action :show, :manifest, to: :read alias_action :color_pdf, :pdf, :edit, to: :modify roles.each do |role| send "#{role}_permissions" if current_user.send "#{role}?" end end # Abilities that should only be granted to admin users def admin_permissions can [:manage], :all end # Abilities that should be granted to technicians def image_editor_permissions can [:read, :create, :modify, :update, :publish], curation_concerns can [:file_manager, :save_structure], ScannedResource can [:file_manager, :save_structure], MultiVolumeWork can [:create, :read, :edit, :update, :publish, :download], FileSet can [:create, :read, :edit, :update, :publish], Collection # do not allow completing resources cannot [:complete], curation_concerns # only allow deleting for own objects, without ARKs can [:destroy], FileSet, depositor: current_user.uid can [:destroy], curation_concerns, depositor: current_user.uid cannot [:destroy], curation_concerns do |obj| !obj.identifier.nil? end end def editor_permissions can [:read, :modify, :update], curation_concerns can [:file_manager, :save_structure], ScannedResource can [:file_manager, :save_structure], MultiVolumeWork can [:read, :edit, :update], FileSet can [:read, :edit, :update], Collection # do not allow completing resources cannot [:complete], curation_concerns curation_concern_read_permissions end def fulfiller_permissions can [:read], curation_concerns can [:read, :download], FileSet can [:read], Collection curation_concern_read_permissions end def curator_permissions can [:read], curation_concerns can [:read], FileSet can [:read], Collection # do not allow viewing pending resources curation_concern_read_permissions end # Abilities that should be granted to patron def campus_patron_permissions anonymous_permissions end def anonymous_permissions # do not allow viewing incomplete resources curation_concern_read_permissions end def curation_concern_read_permissions cannot [:read], curation_concerns do |curation_concern| !readable_concern?(curation_concern) end can :pdf, (curation_concerns + [ScannedResourceShowPresenter]) do |curation_concern| ["color", "gray"].include?(Array(curation_concern.pdf_type).first) end can :color_pdf, (curation_concerns + [ScannedResourceShowPresenter]) do |curation_concern| curation_concern.pdf_type == ["color"] end end def readable_concern?(curation_concern) !unreadable_states.include?(curation_concern.workflow_state) end def unreadable_states if current_user.curator? %w(pending) elsif universal_reader? [] else %w(pending metadata_review final_review takedown) end end delegate :admin?, to: :current_user private def universal_reader? current_user.curator? || current_user.image_editor? || current_user.fulfiller? || current_user.editor? || current_user.admin? end def curation_concerns Hyrax.config.curation_concerns end def roles ['anonymous', 'campus_patron', 'curator', 'fulfiller', 'editor', 'image_editor', 'admin'] end end Fix identifier check class Ability include Hydra::Ability # include GeoConcerns::Ability # def can_create_any_work? Hyrax.config.curation_concerns.any? do |curation_concern_type| can?(:create, curation_concern_type) end end # Define any customized permissions here. def custom_permissions alias_action :show, :manifest, to: :read alias_action :color_pdf, :pdf, :edit, to: :modify roles.each do |role| send "#{role}_permissions" if current_user.send "#{role}?" end end # Abilities that should only be granted to admin users def admin_permissions can [:manage], :all end # Abilities that should be granted to technicians def image_editor_permissions can [:read, :create, :modify, :update, :publish], curation_concerns can [:file_manager, :save_structure], ScannedResource can [:file_manager, :save_structure], MultiVolumeWork can [:create, :read, :edit, :update, :publish, :download], FileSet can [:create, :read, :edit, :update, :publish], Collection # do not allow completing resources cannot [:complete], curation_concerns # only allow deleting for own objects, without ARKs can [:destroy], FileSet, depositor: current_user.uid can [:destroy], curation_concerns, depositor: current_user.uid cannot [:destroy], curation_concerns do |obj| !obj.identifier.blank? end end def editor_permissions can [:read, :modify, :update], curation_concerns can [:file_manager, :save_structure], ScannedResource can [:file_manager, :save_structure], MultiVolumeWork can [:read, :edit, :update], FileSet can [:read, :edit, :update], Collection # do not allow completing resources cannot [:complete], curation_concerns curation_concern_read_permissions end def fulfiller_permissions can [:read], curation_concerns can [:read, :download], FileSet can [:read], Collection curation_concern_read_permissions end def curator_permissions can [:read], curation_concerns can [:read], FileSet can [:read], Collection # do not allow viewing pending resources curation_concern_read_permissions end # Abilities that should be granted to patron def campus_patron_permissions anonymous_permissions end def anonymous_permissions # do not allow viewing incomplete resources curation_concern_read_permissions end def curation_concern_read_permissions cannot [:read], curation_concerns do |curation_concern| !readable_concern?(curation_concern) end can :pdf, (curation_concerns + [ScannedResourceShowPresenter]) do |curation_concern| ["color", "gray"].include?(Array(curation_concern.pdf_type).first) end can :color_pdf, (curation_concerns + [ScannedResourceShowPresenter]) do |curation_concern| curation_concern.pdf_type == ["color"] end end def readable_concern?(curation_concern) !unreadable_states.include?(curation_concern.workflow_state) end def unreadable_states if current_user.curator? %w(pending) elsif universal_reader? [] else %w(pending metadata_review final_review takedown) end end delegate :admin?, to: :current_user private def universal_reader? current_user.curator? || current_user.image_editor? || current_user.fulfiller? || current_user.editor? || current_user.admin? end def curation_concerns Hyrax.config.curation_concerns end def roles ['anonymous', 'campus_patron', 'curator', 'fulfiller', 'editor', 'image_editor', 'admin'] end end
class Ability include CanCan::Ability def initialize(user, options = {}) controller_namespace = options[:controller_namespace] || "" project = options[:project] || nil alias_action :index, :show, :autocomplete, :parents, :childs, :tree, to: :read alias_action :edit, :update, :destroy, to: :restful_actions alias_action [], to: :admin_actions alias_action [], to: :moderation_actions alias_action :assign, :reject, :hold_on, to: :supervisor_actions alias_action :restful_actions, :admin_actions, to: :administrate alias_action :restful_actions, :moderation_actions, to: :moderate alias_action :read, :assign_actions, to: :supervisor can :read, [ Area, Profession, Product, Project, Vacancy, Candidature, Story, Task, Result, Comment ] can [:read, :check_name, :check_url, :check_email, :check_email_unblocked], User if user.present? can :destroy, User, id: user.id can [:new, :create], [Area, Profession, Project, Vacancy, Candidature, Comment] { user_id: [Product, Project, Candidature, Comment, ProjectUser, Result], offeror_id: [Vacancy, Story, Task] }.each do |attribute, classes| can :restful_actions, classes, attribute => user.id end can Candidature::EVENTS, Candidature, offeror_id: user.id can Vacancy::EVENTS, Vacancy, offeror_id: user.id if user.name == 'Master' can [:manage, :moderate, :administrate, :supervisor], :all end end end end restful_actions now include new and create action. class Ability include CanCan::Ability def initialize(user, options = {}) controller_namespace = options[:controller_namespace] || "" project = options[:project] || nil alias_action :index, :show, :autocomplete, :parents, :childs, :tree, to: :read alias_action :new, :create, :edit, :update, :destroy, to: :restful_actions alias_action [], to: :admin_actions alias_action [], to: :moderation_actions alias_action :assign, :reject, :hold_on, to: :supervisor_actions alias_action :restful_actions, :admin_actions, to: :administrate alias_action :restful_actions, :moderation_actions, to: :moderate alias_action :read, :assign_actions, to: :supervisor can :read, [ Area, Profession, Product, Project, Vacancy, Candidature, Story, Task, Result, Comment ] can [:read, :check_name, :check_url, :check_email, :check_email_unblocked], User if user.present? can :destroy, User, id: user.id can [:new, :create], [Area, Profession, Project, Vacancy, Candidature, Comment] { user_id: [Product, Project, Candidature, Comment, ProjectUser, Result], offeror_id: [Vacancy, Story, Task] }.each do |attribute, classes| can :restful_actions, classes, attribute => user.id end can Candidature::EVENTS, Candidature, offeror_id: user.id can Vacancy::EVENTS, Vacancy, offeror_id: user.id if user.name == 'Master' can [:manage, :moderate, :administrate, :supervisor], :all end end end end
class Ability include CanCan::Ability def initialize(user) user ||= User.new alias_action :update, :destroy, :to => :modify if user.role == "admin" can :manage, :all elsif user.role == "edi_ops" can :manage, :all cannot :modify, User elsif user.role == "user" can :read, :all elsif user.role == "service" can :read, Person end end end Tighten access. class Ability include CanCan::Ability def initialize(user) user ||= User.new alias_action :update, :destroy, :to => :modify if user.role == "admin" can :manage, :all elsif user.role == "edi_ops" can :manage, :all cannot :modify, User cannot :edit, User cannot :show, User cannot :update, User cannot :delete, User cannot :index, User elsif user.role == "user" can :read, :all elsif user.role == "service" can :read, Person end end end
class Ability include CanCan::Ability def initialize(user) user ||= User.new #guest user. if user.role? :admin can :manage, :all else can :create, User do user.id.nil? end if user.role?(:respondent_admin) can [:respondents, :submit, :submission, :download_user_pdf, :to_pdf], Questionnaire can [:save_answers, :submission, :load_lazy, :questions, :loop_item_names], Section can [:update, :add_document, :add_link], Answer can [:show, :update], User, id: user.id end if user.role?(:respondent) || user.is_delegate? can :submission, Questionnaire do |questionnaire| user.authorized_to_answer? questionnaire end can [:save_answers, :submission, :load_lazy], Section do |section| user.authorized_to_answer? section.questionnaire end can :change_language, AuthorizedSubmitter can [:update, :add_document, :add_link], Answer if user.role?(:delegate) can [:show, :update], User, id: user.id end if user.role?(:respondent) can [:create], User can [:show, :update, :update_submission_page, :upload_list_of, :group, :remove_group, :delegate_section], User, id: user.id can [:submit, :download_user_pdf, :to_pdf], Questionnaire do |questionnaire| user.authorized_to_answer? questionnaire end can [:questions, :loop_item_names ], Section do |section| user.authorized_to_answer? section.questionnaire end can :manage, DelegationSection do |delegation_section| delegation_section.delegation.user == user end can :manage, Delegation do |delegation| delegation.user == user end end end end end end Respondent admin should be able to revert submission of questionnaires class Ability include CanCan::Ability def initialize(user) user ||= User.new #guest user. if user.role? :admin can :manage, :all else can :create, User do user.id.nil? end if user.role?(:respondent_admin) can [:respondents, :submit, :submission, :unsubmit, :download_user_pdf, :to_pdf], Questionnaire can [:save_answers, :submission, :load_lazy, :questions, :loop_item_names], Section can [:update, :add_document, :add_link], Answer can [:show, :update], User, id: user.id end if user.role?(:respondent) || user.is_delegate? can :submission, Questionnaire do |questionnaire| user.authorized_to_answer? questionnaire end can [:save_answers, :submission, :load_lazy], Section do |section| user.authorized_to_answer? section.questionnaire end can :change_language, AuthorizedSubmitter can [:update, :add_document, :add_link], Answer if user.role?(:delegate) can [:show, :update], User, id: user.id end if user.role?(:respondent) can [:create], User can [:show, :update, :update_submission_page, :upload_list_of, :group, :remove_group, :delegate_section], User, id: user.id can [:submit, :download_user_pdf, :to_pdf], Questionnaire do |questionnaire| user.authorized_to_answer? questionnaire end can [:questions, :loop_item_names ], Section do |section| user.authorized_to_answer? section.questionnaire end can :manage, DelegationSection do |delegation_section| delegation_section.delegation.user == user end can :manage, Delegation do |delegation| delegation.user == user end end end end end end
# Reference: https://github.com/ryanb/cancan/wiki/Defining-Abilities class Ability include CanCan::Ability def initialize(user) user ||= User.new alias_action :create, :read, :update, :destroy, :to => :crud if user.admin? can :manage, :all end # Collection can :read, Collection, public: true # Comment can :read, Comment # Favourite can :read, Favourite, wallpaper: { processing: false, purity: 'sfw' } # User can :read, User # Group can :read, Group, access: ['public', 'private'] # Forum can :read, Forum, can_read: true # Topic can :read, Topic, forum: { can_read: true }, hidden: false # Tag can :read, Tag if user.persisted? # Wallpaper can :read, Wallpaper, processing: false cannot :read, Wallpaper, approved_at: nil unless user.moderator? can :create, Wallpaper, user_id: user.id # can :crud, Wallpaper, user_id: user.id # cannot :update_purity, Wallpaper, purity_locked: true unless user.moderator? # Favourite can :crud, Favourite, user_id: user.id # Collection can :crud, Collection, user_id: user.id # Comment can :crud, Comment, user_id: user.id cannot [:update, :destroy], Comment do |comment| # 15 minutes to destroy a comment Time.now - comment.created_at > 15.minutes end unless user.moderator? can :update, Comment, commentable_type: 'Topic', user_id: user.id # User can :crud, User, id: user.id # Group can :crud, Group, owner_id: user.id can :join, Group, access: 'public' cannot :join, Group, users_groups: { user_id: user.id } can :leave, Group, users_groups: { user_id: user.id } cannot :leave, Group, owner_id: user.id # Forum can :post, Forum, can_post: true # Report can :create, Report # Topic can :create, Topic, forum: { can_post: true } can :comment, Topic, forum: { can_comment: true }, locked: false can :update, Topic, user_id: user.id # Tag can :create, Tag, coined_by_id: user.id # Subscription can :crud, Subscription, user_id: user.id can :subscribe, :all cannot :subscribe, Collection, user_id: user.id cannot :subscribe, User, id: user.id # Moderators if user.moderator? can :manage, Category can :manage, Comment can :manage, Report can :manage, Tag can :manage, Wallpaper can :manage, ActiveAdmin::Comment end else # Wallpaper can :read, Wallpaper, processing: false, purity: 'sfw' end end end Fix admin permission on dashboard page # Reference: https://github.com/ryanb/cancan/wiki/Defining-Abilities class Ability include CanCan::Ability def initialize(user) user ||= User.new alias_action :create, :read, :update, :destroy, :to => :crud if user.admin? can :manage, :all end # Collection can :read, Collection, public: true # Comment can :read, Comment # Favourite can :read, Favourite, wallpaper: { processing: false, purity: 'sfw' } # User can :read, User # Group can :read, Group, access: ['public', 'private'] # Forum can :read, Forum, can_read: true # Topic can :read, Topic, forum: { can_read: true }, hidden: false # Tag can :read, Tag if user.persisted? # Wallpaper can :read, Wallpaper, processing: false cannot :read, Wallpaper, approved_at: nil unless user.moderator? can :create, Wallpaper, user_id: user.id # can :crud, Wallpaper, user_id: user.id # cannot :update_purity, Wallpaper, purity_locked: true unless user.moderator? # Favourite can :crud, Favourite, user_id: user.id # Collection can :crud, Collection, user_id: user.id # Comment can :crud, Comment, user_id: user.id cannot [:update, :destroy], Comment do |comment| # 15 minutes to destroy a comment Time.now - comment.created_at > 15.minutes end unless user.moderator? can :update, Comment, commentable_type: 'Topic', user_id: user.id # User can :crud, User, id: user.id # Group can :crud, Group, owner_id: user.id can :join, Group, access: 'public' cannot :join, Group, users_groups: { user_id: user.id } can :leave, Group, users_groups: { user_id: user.id } cannot :leave, Group, owner_id: user.id # Forum can :post, Forum, can_post: true # Report can :create, Report # Topic can :create, Topic, forum: { can_post: true } can :comment, Topic, forum: { can_comment: true }, locked: false can :update, Topic, user_id: user.id # Tag can :create, Tag, coined_by_id: user.id # Subscription can :crud, Subscription, user_id: user.id can :subscribe, :all cannot :subscribe, Collection, user_id: user.id cannot :subscribe, User, id: user.id # Moderators if user.moderator? can :manage, Category can :manage, Comment can :manage, Report can :manage, Tag can :manage, Wallpaper can :manage, ActiveAdmin::Comment can :read, ActiveAdmin::Page, name: 'Dashboard' end else # Wallpaper can :read, Wallpaper, processing: false, purity: 'sfw' end end end
# # Copyright (C) 2011 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # require 'atom' class Account < ActiveRecord::Base include Context include OutcomeImportContext include Pronouns INSTANCE_GUID_SUFFIX = 'canvas-lms' include Workflow include BrandConfigHelpers belongs_to :root_account, :class_name => 'Account' belongs_to :parent_account, :class_name => 'Account' has_many :courses has_many :favorites, inverse_of: :root_account has_many :all_courses, :class_name => 'Course', :foreign_key => 'root_account_id' has_one :terms_of_service, :dependent => :destroy has_one :terms_of_service_content, :dependent => :destroy has_many :group_categories, -> { where(deleted_at: nil) }, as: :context, inverse_of: :context has_many :all_group_categories, :class_name => 'GroupCategory', foreign_key: 'root_account_id', inverse_of: :root_account has_many :groups, :as => :context, :inverse_of => :context has_many :all_groups, class_name: 'Group', foreign_key: 'root_account_id', inverse_of: :root_account has_many :all_group_memberships, source: 'group_memberships', through: :all_groups has_many :enrollment_terms, :foreign_key => 'root_account_id' has_many :active_enrollment_terms, -> { where("enrollment_terms.workflow_state<>'deleted'") }, class_name: 'EnrollmentTerm', foreign_key: 'root_account_id' has_many :grading_period_groups, inverse_of: :root_account, dependent: :destroy has_many :grading_periods, through: :grading_period_groups has_many :enrollments, -> { where("enrollments.type<>'StudentViewEnrollment'") }, foreign_key: 'root_account_id' has_many :all_enrollments, :class_name => 'Enrollment', :foreign_key => 'root_account_id' has_many :sub_accounts, -> { where("workflow_state<>'deleted'") }, class_name: 'Account', foreign_key: 'parent_account_id' has_many :all_accounts, -> { order(:name) }, class_name: 'Account', foreign_key: 'root_account_id' has_many :account_users, :dependent => :destroy has_many :active_account_users, -> { active }, class_name: 'AccountUser' has_many :course_sections, :foreign_key => 'root_account_id' has_many :sis_batches has_many :abstract_courses, :class_name => 'AbstractCourse', :foreign_key => 'account_id' has_many :root_abstract_courses, :class_name => 'AbstractCourse', :foreign_key => 'root_account_id' has_many :users, :through => :active_account_users has_many :pseudonyms, -> { preload(:user) }, inverse_of: :account has_many :role_overrides, :as => :context, :inverse_of => :context has_many :course_account_associations has_many :child_courses, -> { where(course_account_associations: { depth: 0 }) }, through: :course_account_associations, source: :course has_many :attachments, :as => :context, :inverse_of => :context, :dependent => :destroy has_many :active_assignments, -> { where("assignments.workflow_state<>'deleted'") }, as: :context, inverse_of: :context, class_name: 'Assignment' has_many :folders, -> { order('folders.name') }, as: :context, inverse_of: :context, dependent: :destroy has_many :active_folders, -> { where("folder.workflow_state<>'deleted'").order('folders.name') }, class_name: 'Folder', as: :context, inverse_of: :context has_many :developer_keys has_many :developer_key_account_bindings, inverse_of: :account, dependent: :destroy has_many :authentication_providers, -> { order(:position) }, inverse_of: :account, extend: AuthenticationProvider::FindWithType has_many :account_reports, inverse_of: :account has_many :grading_standards, -> { where("workflow_state<>'deleted'") }, as: :context, inverse_of: :context has_many :assessment_question_banks, -> { preload(:assessment_questions, :assessment_question_bank_users) }, as: :context, inverse_of: :context has_many :assessment_questions, :through => :assessment_question_banks has_many :roles has_many :all_roles, :class_name => 'Role', :foreign_key => 'root_account_id' has_many :progresses, :as => :context, :inverse_of => :context has_many :content_migrations, :as => :context, :inverse_of => :context has_many :sis_batch_errors, foreign_key: :root_account_id, inverse_of: :root_account has_one :outcome_proficiency, as: :context, inverse_of: :context, dependent: :destroy has_one :outcome_calculation_method, as: :context, inverse_of: :context, dependent: :destroy has_many :auditor_authentication_records, class_name: "Auditors::ActiveRecord::AuthenticationRecord", dependent: :destroy, inverse_of: :account has_many :auditor_course_records, class_name: "Auditors::ActiveRecord::CourseRecord", dependent: :destroy, inverse_of: :account has_many :auditor_grade_change_records, class_name: "Auditors::ActiveRecord::GradeChangeRecord", dependent: :destroy, inverse_of: :account has_many :auditor_root_grade_change_records, foreign_key: 'root_account_id', class_name: "Auditors::ActiveRecord::GradeChangeRecord", dependent: :destroy, inverse_of: :root_account def inherited_assessment_question_banks(include_self = false, *additional_contexts) sql, conds = [], [] contexts = additional_contexts + account_chain contexts.delete(self) unless include_self contexts.each { |c| sql << "context_type = ? AND context_id = ?" conds += [c.class.to_s, c.id] } conds.unshift(sql.join(" OR ")) AssessmentQuestionBank.where(conds) end include LearningOutcomeContext include RubricContext has_many :context_external_tools, -> { order(:name) }, as: :context, inverse_of: :context, dependent: :destroy has_many :error_reports has_many :announcements, :class_name => 'AccountNotification' has_many :alerts, -> { preload(:criteria) }, as: :context, inverse_of: :context has_many :user_account_associations has_many :report_snapshots has_many :external_integration_keys, :as => :context, :inverse_of => :context, :dependent => :destroy has_many :shared_brand_configs belongs_to :brand_config, foreign_key: "brand_config_md5" before_validation :verify_unique_sis_source_id before_save :ensure_defaults before_create :enable_sis_imports, if: :root_account? after_save :update_account_associations_if_changed after_save :check_downstream_caches before_save :setup_cache_invalidation after_save :invalidate_caches_if_changed after_update :clear_special_account_cache_if_special after_update :clear_cached_short_name, :if => :saved_change_to_name? after_create :create_default_objects serialize :settings, Hash include TimeZoneHelper time_zone_attribute :default_time_zone, default: "America/Denver" def default_time_zone if read_attribute(:default_time_zone) || root_account? super else root_account.default_time_zone end end alias_method :time_zone, :default_time_zone validates_locale :default_locale, :allow_nil => true validates_length_of :name, :maximum => maximum_string_length, :allow_blank => true validate :account_chain_loop, :if => :parent_account_id_changed? validate :validate_auth_discovery_url validates :workflow_state, presence: true validate :no_active_courses, if: lambda { |a| a.workflow_state_changed? && !a.active? } validate :no_active_sub_accounts, if: lambda { |a| a.workflow_state_changed? && !a.active? } validate :validate_help_links, if: lambda { |a| a.settings_changed? } include StickySisFields are_sis_sticky :name, :parent_account_id include FeatureFlags def feature_flag_cache MultiCache.cache end def redis_for_root_account_cache_register return unless MultiCache.cache.respond_to?(:redis) redis = MultiCache.cache.redis return if redis.respond_to?(:node_for) redis end def root_account_cache_key base_key = self.class.base_cache_register_key_for(self) "#{base_key}/feature_flags" end def cache_key(key_type = nil) return super if new_record? return super unless root_account? && key_type == :feature_flags return super unless (redis = redis_for_root_account_cache_register) # partially taken from CacheRegister.cache_key_for_id, but modified to # target HACache full_key = root_account_cache_key RequestCache.cache(full_key) do now = Time.now.utc.to_s(self.cache_timestamp_format) # try to get the timestamp for the type, set it to now if it doesn't exist ts = Canvas::CacheRegister.lua.run(:get_key, [full_key], [now], redis) "#{self.model_name.cache_key}/#{global_id}-#{ts}" end end def clear_cache_key(*key_types) return super unless root_account? && key_types == [:feature_flags] return super unless redis_for_root_account_cache_register MultiCache.delete(root_account_cache_key) end def self.recursive_default_locale_for_id(account_id) local_id, shard = Shard.local_id_for(account_id) (shard || Shard.current).activate do obj = Account.new(id: local_id) # someday i should figure out a better way to avoid instantiating an object instead of tricking cache register Rails.cache.fetch_with_batched_keys('default_locale_for_id', batch_object: obj, batched_keys: [:account_chain, :default_locale]) do # couldn't find the cache so now we actually need to find the account acc = Account.find(local_id) acc.default_locale || (acc.parent_account_id && recursive_default_locale_for_id(acc.parent_account_id)) end end end def default_locale result = read_attribute(:default_locale) result = nil unless I18n.locale_available?(result) result end def resolved_outcome_proficiency if outcome_proficiency&.active? outcome_proficiency elsif parent_account parent_account.resolved_outcome_proficiency elsif self.feature_enabled?(:account_level_mastery_scales) OutcomeProficiency.find_or_create_default!(self) end end def resolved_outcome_calculation_method if outcome_calculation_method&.active? outcome_calculation_method elsif parent_account parent_account.resolved_outcome_calculation_method elsif self.feature_enabled?(:account_level_mastery_scales) OutcomeCalculationMethod.find_or_create_default!(self) end end include ::Account::Settings include ::Csp::AccountHelper # these settings either are or could be easily added to # the account settings page add_setting :sis_app_token, :root_only => true add_setting :sis_app_url, :root_only => true add_setting :sis_name, :root_only => true add_setting :sis_syncing, :boolean => true, :default => false, :inheritable => true add_setting :sis_default_grade_export, :boolean => true, :default => false, :inheritable => true add_setting :include_integration_ids_in_gradebook_exports, :boolean => true, :default => false, :root_only => true add_setting :sis_require_assignment_due_date, :boolean => true, :default => false, :inheritable => true add_setting :sis_assignment_name_length, :boolean => true, :default => false, :inheritable => true add_setting :sis_assignment_name_length_input, :inheritable => true add_setting :global_includes, :root_only => true, :boolean => true, :default => false add_setting :sub_account_includes, :boolean => true, :default => false # Help link settings add_setting :custom_help_links, :root_only => true add_setting :help_link_icon, :root_only => true add_setting :help_link_name, :root_only => true add_setting :support_url, :root_only => true add_setting :prevent_course_renaming_by_teachers, :boolean => true, :root_only => true add_setting :login_handle_name, root_only: true add_setting :change_password_url, root_only: true add_setting :unknown_user_url, root_only: true add_setting :fft_registration_url, root_only: true add_setting :restrict_student_future_view, :boolean => true, :default => false, :inheritable => true add_setting :restrict_student_future_listing, :boolean => true, :default => false, :inheritable => true add_setting :restrict_student_past_view, :boolean => true, :default => false, :inheritable => true add_setting :teachers_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :students_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :restrict_quiz_questions, :boolean => true, :root_only => true, :default => false add_setting :no_enrollments_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :allow_sending_scores_in_emails, :boolean => true, :root_only => true add_setting :can_add_pronouns, :boolean => true, :root_only => true, :default => false add_setting :self_enrollment add_setting :equella_endpoint add_setting :equella_teaser add_setting :enable_alerts, :boolean => true, :root_only => true add_setting :enable_eportfolios, :boolean => true, :root_only => true add_setting :users_can_edit_name, :boolean => true, :root_only => true add_setting :open_registration, :boolean => true, :root_only => true add_setting :show_scheduler, :boolean => true, :root_only => true, :default => false add_setting :enable_profiles, :boolean => true, :root_only => true, :default => false add_setting :enable_turnitin, :boolean => true, :default => false add_setting :mfa_settings, :root_only => true add_setting :mobile_qr_login_is_enabled, :boolean => true, :root_only => true, :default => true add_setting :admins_can_change_passwords, :boolean => true, :root_only => true, :default => false add_setting :admins_can_view_notifications, :boolean => true, :root_only => true, :default => false add_setting :canvadocs_prefer_office_online, :boolean => true, :root_only => true, :default => false add_setting :outgoing_email_default_name add_setting :external_notification_warning, :boolean => true, :default => false # Terms of Use and Privacy Policy settings for the root account add_setting :terms_changed_at, :root_only => true add_setting :account_terms_required, :root_only => true, :boolean => true, :default => true # When a user is invited to a course, do we let them see a preview of the # course even without registering? This is part of the free-for-teacher # account perks, since anyone can invite anyone to join any course, and it'd # be nice to be able to see the course first if you weren't expecting the # invitation. add_setting :allow_invitation_previews, :boolean => true, :root_only => true, :default => false add_setting :large_course_rosters, :boolean => true, :root_only => true, :default => false add_setting :edit_institution_email, :boolean => true, :root_only => true, :default => true add_setting :js_kaltura_uploader, :boolean => true, :root_only => true, :default => false add_setting :google_docs_domain, root_only: true add_setting :dashboard_url, root_only: true add_setting :product_name, root_only: true add_setting :author_email_in_notifications, boolean: true, root_only: true, default: false add_setting :include_students_in_global_survey, boolean: true, root_only: true, default: false add_setting :trusted_referers, root_only: true add_setting :app_center_access_token add_setting :enable_offline_web_export, boolean: true, default: false, inheritable: true add_setting :disable_rce_media_uploads, boolean: true, default: false, inheritable: true add_setting :strict_sis_check, :boolean => true, :root_only => true, :default => false add_setting :lock_all_announcements, default: false, boolean: true, inheritable: true add_setting :enable_gravatar, :boolean => true, :root_only => true, :default => true # For setting the default dashboard (e.g. Student Planner/List View, Activity Stream, Dashboard Cards) add_setting :default_dashboard_view, :inheritable => true add_setting :require_confirmed_email, :boolean => true, :root_only => true, :default => false add_setting :enable_course_catalog, :boolean => true, :root_only => true, :default => false add_setting :usage_rights_required, :boolean => true, :default => false, :inheritable => true add_setting :limit_parent_app_web_access, boolean: true, default: false, root_only: true add_setting :kill_joy, boolean: true, default: false, root_only: true add_setting :smart_alerts_threshold, default: 36, root_only: true add_setting :disable_post_to_sis_when_grading_period_closed, boolean: true, root_only: true, default: false # privacy settings for root accounts add_setting :enable_fullstory, boolean: true, root_only: true, default: true add_setting :enable_google_analytics, boolean: true, root_only: true, default: true add_setting :rce_favorite_tool_ids, :inheritable => true def settings=(hash) if hash.is_a?(Hash) || hash.is_a?(ActionController::Parameters) hash.each do |key, val| key = key.to_sym if account_settings_options && (opts = account_settings_options[key]) if (opts[:root_only] && !self.root_account?) || (opts[:condition] && !self.send("#{opts[:condition]}?".to_sym)) settings.delete key elsif opts[:hash] new_hash = {} if val.is_a?(Hash) || val.is_a?(ActionController::Parameters) val.each do |inner_key, inner_val| inner_key = inner_key.to_sym if opts[:values].include?(inner_key) if opts[:inheritable] && (inner_key == :locked || (inner_key == :value && opts[:boolean])) new_hash[inner_key] = Canvas::Plugin.value_to_boolean(inner_val) else new_hash[inner_key] = inner_val.to_s end end end end settings[key] = new_hash.empty? ? nil : new_hash elsif opts[:boolean] settings[key] = Canvas::Plugin.value_to_boolean(val) else settings[key] = val.to_s end end end end # prune nil or "" hash values to save space in the DB. settings.reject! { |_, value| value.nil? || value == "" } settings end def product_name settings[:product_name] || t("#product_name", "Canvas") end def usage_rights_required? usage_rights_required[:value] end def allow_global_includes? if root_account? global_includes? else root_account.try(:sub_account_includes?) && root_account.try(:allow_global_includes?) end end def pronouns return [] unless settings[:can_add_pronouns] settings[:pronouns]&.map{|p| translate_pronouns(p)} || Pronouns.default_pronouns end def pronouns=(pronouns) settings[:pronouns] = pronouns&.map{|p| untranslate_pronouns(p)}&.reject(&:blank?) end def mfa_settings settings[:mfa_settings].try(:to_sym) || :disabled end def non_canvas_auth_configured? authentication_providers.active.where("auth_type<>'canvas'").exists? end def canvas_authentication_provider @canvas_ap ||= authentication_providers.active.where(auth_type: 'canvas').first end def canvas_authentication? !!canvas_authentication_provider end def enable_canvas_authentication return unless root_account? # for migrations creating a new db return unless Account.connection.data_source_exists?("authentication_providers") return if authentication_providers.active.where(auth_type: 'canvas').exists? authentication_providers.create!(auth_type: 'canvas') end def enable_offline_web_export? enable_offline_web_export[:value] end def disable_rce_media_uploads? disable_rce_media_uploads[:value] end def open_registration? !!settings[:open_registration] && canvas_authentication? end def self_registration? canvas_authentication_provider.try(:jit_provisioning?) end def self_registration_type canvas_authentication_provider.try(:self_registration) end def self_registration_captcha? canvas_authentication_provider.try(:enable_captcha) end def self_registration_allowed_for?(type) return false unless self_registration? return false if self_registration_type != 'all' && type != self_registration_type true end def enable_self_registration canvas_authentication_provider.update_attribute(:self_registration, true) end def terms_required? terms = TermsOfService.ensure_terms_for_account(root_account) !(terms.terms_type == 'no_terms' || terms.passive) end def require_acceptance_of_terms?(user) return false if !terms_required? return true if (user.nil? || user.new_record?) soc2_start_date = Setting.get('SOC2_start_date', Time.new(2015, 5, 16, 0, 0, 0).utc).to_datetime return false if user.created_at < soc2_start_date terms_changed_at = root_account.terms_of_service.terms_of_service_content&.terms_updated_at || settings[:terms_changed_at] last_accepted = user.preferences[:accepted_terms] return false if last_accepted && (terms_changed_at.nil? || last_accepted > terms_changed_at) true end def ip_filters=(params) filters = {} require 'ipaddr' params.each do |key, str| ips = [] vals = str.split(/,/) vals.each do |val| ip = IPAddr.new(val) rescue nil # right now the ip_filter column on quizzes is just a string, # so it has a max length. I figure whatever we set it to this # setter should at the very least limit stored values to that # length. ips << val if ip && val.length <= 255 end filters[key] = ips.join(',') unless ips.empty? end settings[:ip_filters] = filters end def enable_sis_imports self.allow_sis_import = true end def ensure_defaults self.name&.delete!("\r") self.uuid ||= CanvasSlug.generate_securish_uuid self.lti_guid ||= "#{self.uuid}:#{INSTANCE_GUID_SUFFIX}" if self.respond_to?(:lti_guid) self.root_account_id ||= self.parent_account.root_account_id if self.parent_account self.root_account_id ||= self.parent_account_id self.parent_account_id ||= self.root_account_id true end def verify_unique_sis_source_id return true unless self.sis_source_id return true if !root_account_id_changed? && !sis_source_id_changed? if self.root_account? self.errors.add(:sis_source_id, t('#account.root_account_cant_have_sis_id', "SIS IDs cannot be set on root accounts")) throw :abort end scope = root_account.all_accounts.where(sis_source_id: self.sis_source_id) scope = scope.where("id<>?", self) unless self.new_record? return true unless scope.exists? self.errors.add(:sis_source_id, t('#account.sis_id_in_use', "SIS ID \"%{sis_id}\" is already in use", :sis_id => self.sis_source_id)) throw :abort end def update_account_associations_if_changed if self.saved_change_to_parent_account_id? || self.saved_change_to_root_account_id? self.shard.activate do send_later_if_production(:update_account_associations) end end end def check_downstream_caches keys_to_clear = [] keys_to_clear << :account_chain if self.saved_change_to_parent_account_id? || self.saved_change_to_root_account_id? if self.saved_change_to_brand_config_md5? || (@old_settings && @old_settings[:sub_account_includes] != settings[:sub_account_includes]) keys_to_clear << :brand_config end keys_to_clear << :default_locale if self.saved_change_to_default_locale? if keys_to_clear.any? self.shard.activate do send_later_if_production(:clear_downstream_caches, *keys_to_clear) end end end def clear_downstream_caches(*key_types) self.shard.activate do Account.clear_cache_keys([self.id] + Account.sub_account_ids_recursive(self.id), *key_types) end end def equella_settings endpoint = self.settings[:equella_endpoint] || self.equella_endpoint if !endpoint.blank? OpenObject.new({ :endpoint => endpoint, :default_action => self.settings[:equella_action] || 'selectOrAdd', :teaser => self.settings[:equella_teaser] }) else nil end end def settings result = self.read_attribute(:settings) if result @old_settings ||= result.dup return result end return write_attribute(:settings, {}) unless frozen? {}.freeze end def domain(current_host = nil) HostUrl.context_host(self, current_host) end def self.find_by_domain(domain) self.default if HostUrl.default_host == domain end def root_account? !self.root_account_id end def root_account return self if root_account? super end def resolved_root_account_id root_account_id || id end def sub_accounts_as_options(indent = 0, preloaded_accounts = nil) unless preloaded_accounts preloaded_accounts = {} self.root_account.all_accounts.active.each do |account| (preloaded_accounts[account.parent_account_id] ||= []) << account end end res = [[("&nbsp;&nbsp;" * indent).html_safe + self.name, self.id]] if preloaded_accounts[self.id] preloaded_accounts[self.id].each do |account| res += account.sub_accounts_as_options(indent + 1, preloaded_accounts) end end res end def users_visible_to(user) self.grants_right?(user, :read) ? self.all_users : self.all_users.none end def users_name_like(query="") @cached_users_name_like ||= {} @cached_users_name_like[query] ||= self.fast_all_users.name_like(query) end def associated_courses(opts = {}) if root_account? all_courses else shard.activate do if opts[:include_crosslisted_courses] Course.where("EXISTS (?)", CourseAccountAssociation.where(account_id: self). where("course_id=courses.id")) else Course.where("EXISTS (?)", CourseAccountAssociation.where(account_id: self, course_section_id: nil). where("course_id=courses.id")) end end end end def associated_user?(user) user_account_associations.where(user_id: user).exists? end def fast_course_base(opts = {}) opts[:order] ||= Course.best_unicode_collation_key("courses.name").asc columns = "courses.id, courses.name, courses.workflow_state, courses.course_code, courses.sis_source_id, courses.enrollment_term_id" associated_courses = self.associated_courses( :include_crosslisted_courses => opts[:include_crosslisted_courses] ) associated_courses = associated_courses.active.order(opts[:order]) associated_courses = associated_courses.with_enrollments if opts[:hide_enrollmentless_courses] associated_courses = associated_courses.master_courses if opts[:only_master_courses] associated_courses = associated_courses.for_term(opts[:term]) if opts[:term].present? associated_courses = yield associated_courses if block_given? associated_courses.limit(opts[:limit]).active_first.select(columns).to_a end def fast_all_courses(opts={}) @cached_fast_all_courses ||= {} @cached_fast_all_courses[opts] ||= self.fast_course_base(opts) end def all_users(limit=250) @cached_all_users ||= {} @cached_all_users[limit] ||= User.of_account(self).limit(limit) end def fast_all_users(limit=nil) @cached_fast_all_users ||= {} @cached_fast_all_users[limit] ||= self.all_users(limit).active.select("users.id, users.updated_at, users.name, users.sortable_name").order_by_sortable_name end def users_not_in_groups(groups, opts={}) scope = User.active.joins(:user_account_associations). where(user_account_associations: {account_id: self}). where(Group.not_in_group_sql_fragment(groups.map(&:id))). select("users.id, users.name") scope = scope.select(opts[:order]).order(opts[:order]) if opts[:order] scope end def courses_name_like(query="", opts={}) opts[:limit] ||= 200 @cached_courses_name_like ||= {} @cached_courses_name_like[[query, opts]] ||= self.fast_course_base(opts) {|q| q.name_like(query)} end def self_enrollment_course_for(code) all_courses. where(:self_enrollment_code => code). first end def file_namespace if Shard.current == Shard.birth "account_#{root_account.local_id}" else root_account.global_asset_string end end def self.account_lookup_cache_key(id) ['_account_lookup5', id].cache_key end def self.invalidate_cache(id) return unless id default_id = Shard.relative_id_for(id, Shard.current, Shard.default) Shard.default.activate do MultiCache.delete(account_lookup_cache_key(default_id)) if default_id end rescue nil end def setup_cache_invalidation @invalidations = [] unless self.new_record? invalidate_all = self.parent_account_id_changed? # apparently, the try_rescues are because these columns don't exist on old migrations @invalidations += ['default_storage_quota', 'current_quota'] if invalidate_all || self.try_rescue(:default_storage_quota_changed?) @invalidations << 'default_group_storage_quota' if invalidate_all || self.try_rescue(:default_group_storage_quota_changed?) end end def invalidate_caches_if_changed if changed? connection.after_transaction_commit do if root_account? Account.invalidate_cache(id) else shard.activate do Rails.cache.delete(["account"/ id].cache_key) end end end end @invalidations ||= [] if self.saved_change_to_parent_account_id? @invalidations += Account.inheritable_settings # invalidate all of them elsif @old_settings Account.inheritable_settings.each do |key| @invalidations << key if @old_settings[key] != settings[key] # only invalidate if needed end @old_settings = nil end if @invalidations.present? shard.activate do @invalidations.each do |key| Rails.cache.delete([key, self.global_id].cache_key) end Account.send_later_if_production(:invalidate_inherited_caches, self, @invalidations) end end end def self.invalidate_inherited_caches(parent_account, keys) parent_account.shard.activate do account_ids = Account.sub_account_ids_recursive(parent_account.id) account_ids.each do |id| global_id = Shard.global_id_for(id) keys.each do |key| Rails.cache.delete([key, global_id].cache_key) end end access_keys = keys & [:restrict_student_future_view, :restrict_student_past_view] if access_keys.any? EnrollmentState.invalidate_access_for_accounts([parent_account.id] + account_ids, access_keys) end end end def self.default_storage_quota Setting.get('account_default_quota', 500.megabytes.to_s).to_i end def quota return storage_quota if read_attribute(:storage_quote) return self.class.default_storage_quota if root_account? shard.activate do Rails.cache.fetch(['current_quota', self.global_id].cache_key) do self.parent_account.default_storage_quota end end end def default_storage_quota return super if read_attribute(:default_storage_quota) return self.class.default_storage_quota if root_account? shard.activate do @default_storage_quota ||= Rails.cache.fetch(['default_storage_quota', self.global_id].cache_key) do parent_account.default_storage_quota end end end def default_storage_quota_mb default_storage_quota / 1.megabyte end def default_storage_quota_mb=(val) self.default_storage_quota = val.try(:to_i).try(:megabytes) end def default_storage_quota=(val) val = val.to_f val = nil if val <= 0 # If the value is the same as the inherited value, then go # ahead and blank it so it keeps using the inherited value if parent_account && parent_account.default_storage_quota == val val = nil end write_attribute(:default_storage_quota, val) end def default_user_storage_quota read_attribute(:default_user_storage_quota) || User.default_storage_quota end def default_user_storage_quota=(val) val = val.to_i val = nil if val == User.default_storage_quota || val <= 0 write_attribute(:default_user_storage_quota, val) end def default_user_storage_quota_mb default_user_storage_quota / 1.megabyte end def default_user_storage_quota_mb=(val) self.default_user_storage_quota = val.try(:to_i).try(:megabytes) end def default_group_storage_quota return super if read_attribute(:default_group_storage_quota) return Group.default_storage_quota if root_account? shard.activate do Rails.cache.fetch(['default_group_storage_quota', self.global_id].cache_key) do self.parent_account.default_group_storage_quota end end end def default_group_storage_quota=(val) val = val.to_i if (val == Group.default_storage_quota) || (val <= 0) || (self.parent_account && self.parent_account.default_group_storage_quota == val) val = nil end write_attribute(:default_group_storage_quota, val) end def default_group_storage_quota_mb default_group_storage_quota / 1.megabyte end def default_group_storage_quota_mb=(val) self.default_group_storage_quota = val.try(:to_i).try(:megabytes) end def turnitin_shared_secret=(secret) return if secret.blank? self.turnitin_crypted_secret, self.turnitin_salt = Canvas::Security.encrypt_password(secret, 'instructure_turnitin_secret_shared') end def turnitin_shared_secret return nil unless self.turnitin_salt && self.turnitin_crypted_secret Canvas::Security.decrypt_password(self.turnitin_crypted_secret, self.turnitin_salt, 'instructure_turnitin_secret_shared') end def self.account_chain(starting_account_id) chain = [] if (starting_account_id.is_a?(Account)) chain << starting_account_id starting_account_id = starting_account_id.parent_account_id end if starting_account_id guard_rail_env = Account.connection.open_transactions == 0 ? :secondary : GuardRail.environment GuardRail.activate(guard_rail_env) do chain.concat(Shard.shard_for(starting_account_id).activate do Account.find_by_sql(<<~SQL) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE id=#{Shard.local_id_for(starting_account_id).first} UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT * FROM t SQL end) end end chain end def self.account_chain_ids(starting_account_id) block = lambda do |_name| Shard.shard_for(starting_account_id).activate do id_chain = [] if (starting_account_id.is_a?(Account)) id_chain << starting_account_id.id starting_account_id = starting_account_id.parent_account_id end if starting_account_id GuardRail.activate(:secondary) do ids = Account.connection.select_values(<<~SQL) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE id=#{Shard.local_id_for(starting_account_id).first} UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t SQL id_chain.concat(ids.map(&:to_i)) end end id_chain end end key = Account.cache_key_for_id(starting_account_id, :account_chain) key ? Rails.cache.fetch(['account_chain_ids', key], &block) : block.call(nil) end def self.multi_account_chain_ids(starting_account_ids) if connection.adapter_name == 'PostgreSQL' original_shard = Shard.current Shard.partition_by_shard(starting_account_ids) do |sliced_acc_ids| ids = Account.connection.select_values(<<~SQL) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE id IN (#{sliced_acc_ids.join(", ")}) UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t SQL ids.map{|id| Shard.relative_id_for(id, Shard.current, original_shard)} end else account_chain(starting_account_id).map(&:id) end end def self.add_site_admin_to_chain!(chain) chain << Account.site_admin unless chain.last.site_admin? chain end def account_chain(include_site_admin: false) @account_chain ||= Account.account_chain(self) result = @account_chain.dup Account.add_site_admin_to_chain!(result) if include_site_admin result end def account_chain_ids @cached_account_chain_ids ||= Account.account_chain_ids(self) end def account_chain_loop # this record hasn't been saved to the db yet, so if the the chain includes # this account, it won't point to the new parent yet, and should still be # valid if self.parent_account.account_chain.include?(self) errors.add(:parent_account_id, "Setting account #{self.sis_source_id || self.id}'s parent to #{self.parent_account.sis_source_id || self.parent_account_id} would create a loop") end end # returns all sub_accounts recursively as far down as they go, in id order # because this uses a custom sql query for postgresql, we can't use a normal # named scope, so we pass the limit and offset into the method instead and # build our own query string def sub_accounts_recursive(limit, offset) if ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'postgresql' Account.find_by_sql([<<~SQL, self.id, limit.to_i, offset.to_i]) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE parent_account_id = ? AND workflow_state <>'deleted' UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.parent_account_id = t.id WHERE accounts.workflow_state <>'deleted' ) SELECT * FROM t ORDER BY parent_account_id, id LIMIT ? OFFSET ? SQL else account_descendents = lambda do |id| as = Account.where(:parent_account_id => id).active.order(:id) as.empty? ? [] : as << as.map { |a| account_descendents.call(a.id) } end account_descendents.call(id).flatten[offset, limit] end end def self.sub_account_ids_recursive(parent_account_id) if connection.adapter_name == 'PostgreSQL' guard_rail_env = Account.connection.open_transactions == 0 ? :secondary : GuardRail.environment GuardRail.activate(guard_rail_env) do sql = Account.sub_account_ids_recursive_sql(parent_account_id) Account.find_by_sql(sql).map(&:id) end else account_descendants = lambda do |ids| as = Account.where(:parent_account_id => ids).active.pluck(:id) as + account_descendants.call(as) end account_descendants.call([parent_account_id]) end end def self.sub_account_ids_recursive_sql(parent_account_id) "WITH RECURSIVE t AS ( SELECT id, parent_account_id FROM #{Account.quoted_table_name} WHERE parent_account_id = #{parent_account_id} AND workflow_state <> 'deleted' UNION SELECT accounts.id, accounts.parent_account_id FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.parent_account_id = t.id WHERE accounts.workflow_state <> 'deleted' ) SELECT id FROM t" end def associated_accounts self.account_chain end def membership_for_user(user) self.account_users.active.where(user_id: user).first if user end def available_custom_account_roles(include_inactive=false) available_custom_roles(include_inactive).for_accounts.to_a end def available_account_roles(include_inactive=false, user = nil) account_roles = available_custom_account_roles(include_inactive) account_roles << Role.get_built_in_role('AccountAdmin', root_account_id: resolved_root_account_id) if user account_roles.select! { |role| au = account_users.new; au.role_id = role.id; au.grants_right?(user, :create) } end account_roles end def available_custom_course_roles(include_inactive=false) available_custom_roles(include_inactive).for_courses.to_a end def available_course_roles(include_inactive=false) course_roles = available_custom_course_roles(include_inactive) course_roles += Role.built_in_course_roles(root_account_id: resolved_root_account_id) course_roles end def available_custom_roles(include_inactive=false) scope = Role.where(:account_id => account_chain_ids) scope = include_inactive ? scope.not_deleted : scope.active scope end def available_roles(include_inactive=false) available_account_roles(include_inactive) + available_course_roles(include_inactive) end def get_account_role_by_name(role_name) role = get_role_by_name(role_name) return role if role && role.account_role? end def get_course_role_by_name(role_name) role = get_role_by_name(role_name) return role if role && role.course_role? end def get_role_by_name(role_name) if (role = Role.get_built_in_role(role_name, root_account_id: self.resolved_root_account_id)) return role end self.shard.activate do role_scope = Role.not_deleted.where(:name => role_name) if self.class.connection.adapter_name == 'PostgreSQL' role_scope = role_scope.where("account_id = ? OR account_id IN ( WITH RECURSIVE t AS ( SELECT id, parent_account_id FROM #{Account.quoted_table_name} WHERE id = ? UNION SELECT accounts.id, accounts.parent_account_id FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t )", self.id, self.id) else role_scope = role_scope.where(:account_id => self.account_chain.map(&:id)) end role_scope.first end end def get_role_by_id(role_id) role = Role.get_role_by_id(role_id) return role if valid_role?(role) end def valid_role?(role) role && (role.built_in? || (self.id == role.account_id) || self.account_chain_ids.include?(role.account_id)) end def login_handle_name_is_customized? self.login_handle_name.present? end def customized_login_handle_name if login_handle_name_is_customized? self.login_handle_name elsif self.delegated_authentication? AuthenticationProvider.default_delegated_login_handle_name end end def login_handle_name_with_inference customized_login_handle_name || AuthenticationProvider.default_login_handle_name end def self_and_all_sub_accounts @self_and_all_sub_accounts ||= Account.where("root_account_id=? OR parent_account_id=?", self, self).pluck(:id).uniq + [self.id] end workflow do state :active state :deleted end def account_users_for(user) if self == Account.site_admin shard.activate do all_site_admin_account_users_hash = MultiCache.fetch("all_site_admin_account_users3") do # this is a plain ruby hash to keep the cached portion as small as possible self.account_users.active.inject({}) { |result, au| result[au.user_id] ||= []; result[au.user_id] << [au.id, au.role_id]; result } end (all_site_admin_account_users_hash[user.id] || []).map do |(id, role_id)| au = AccountUser.new au.id = id au.account = Account.site_admin au.user = user au.role_id = role_id au.readonly! au end end else @account_chain_ids ||= self.account_chain(:include_site_admin => true).map { |a| a.active? ? a.id : nil }.compact Shard.partition_by_shard(@account_chain_ids) do |account_chain_ids| if account_chain_ids == [Account.site_admin.id] Account.site_admin.account_users_for(user) else AccountUser.where(:account_id => account_chain_ids, :user_id => user).active.to_a end end end end def cached_account_users_for(user) return [] unless user @account_users_cache ||= {} @account_users_cache[user.global_id] ||= begin if self.site_admin? account_users_for(user) # has own cache else Rails.cache.fetch_with_batched_keys(['account_users_for_user', user.cache_key(:account_users)].cache_key, batch_object: self, batched_keys: :account_chain, skip_cache_if_disabled: true) do aus = account_users_for(user) aus.each{|au| au.instance_variable_set(:@association_cache, {})} aus end end end end # returns all active account users for this entire account tree def all_account_users_for(user) raise "must be a root account" unless self.root_account? Shard.partition_by_shard(account_chain(include_site_admin: true).uniq) do |accounts| next unless user.associated_shards.include?(Shard.current) AccountUser.active.eager_load(:account).where("user_id=? AND (accounts.root_account_id IN (?) OR account_id IN (?))", user, accounts, accounts) end end def cached_all_account_users_for(user) return [] unless user Rails.cache.fetch_with_batched_keys(['all_account_users_for_user', user.cache_key(:account_users)].cache_key, batch_object: self, batched_keys: :account_chain, skip_cache_if_disabled: true) do all_account_users_for(user) end end set_policy do RoleOverride.permissions.each do |permission, _details| given { |user| self.cached_account_users_for(user).any? { |au| au.has_permission_to?(self, permission) } } can permission can :create_courses if permission == :manage_courses end given { |user| !self.cached_account_users_for(user).empty? } can :read and can :read_as_admin and can :manage and can :update and can :delete and can :read_outcomes and can :read_terms given { |user| self.root_account? && self.cached_all_account_users_for(user).any? } can :read_terms given { |user| result = false if !root_account.site_admin? && user scope = root_account.enrollments.active.where(user_id: user) result = root_account.teachers_can_create_courses? && scope.where(:type => ['TeacherEnrollment', 'DesignerEnrollment']).exists? result ||= root_account.students_can_create_courses? && scope.where(:type => ['StudentEnrollment', 'ObserverEnrollment']).exists? result ||= root_account.no_enrollments_can_create_courses? && !scope.exists? end result } can :create_courses # allow teachers to view term dates given { |user| self.root_account? && !self.site_admin? && self.enrollments.active.of_instructor_type.where(:user_id => user).exists? } can :read_terms # any logged in user can read global outcomes, but must be checked against the site admin given{ |user| self.site_admin? && user } can :read_global_outcomes # any user with an association to this account can read the outcomes in the account given{ |user| user && self.user_account_associations.where(user_id: user).exists? } can :read_outcomes # any user with an admin enrollment in one of the courses can read given { |user| user && self.courses.where(:id => user.enrollments.active.admin.pluck(:course_id)).exists? } can :read given { |user| self.grants_right?(user, :lti_add_edit)} can :create_tool_manually given { |user| !self.site_admin? && self.root_account? && self.grants_right?(user, :manage_site_settings) } can :manage_privacy_settings end alias_method :destroy_permanently!, :destroy def destroy self.transaction do self.account_users.update_all(workflow_state: 'deleted') self.workflow_state = 'deleted' self.deleted_at = Time.now.utc save! end end def to_atom Atom::Entry.new do |entry| entry.title = self.name entry.updated = self.updated_at entry.published = self.created_at entry.links << Atom::Link.new(:rel => 'alternate', :href => "/accounts/#{self.id}") end end def default_enrollment_term return @default_enrollment_term if @default_enrollment_term if self.root_account? @default_enrollment_term = GuardRail.activate(:primary) { self.enrollment_terms.active.where(name: EnrollmentTerm::DEFAULT_TERM_NAME).first_or_create } end end def context_code raise "DONT USE THIS, use .short_name instead" unless Rails.env.production? end def short_name name end # can be set/overridden by plugin to enforce email pseudonyms attr_accessor :email_pseudonyms def password_policy Canvas::PasswordPolicy.default_policy.merge(settings[:password_policy] || {}) end def delegated_authentication? authentication_providers.active.first.is_a?(AuthenticationProvider::Delegated) end def forgot_password_external_url self.change_password_url end def auth_discovery_url=(url) self.settings[:auth_discovery_url] = url end def auth_discovery_url self.settings[:auth_discovery_url] end def login_handle_name=(handle_name) self.settings[:login_handle_name] = handle_name end def login_handle_name self.settings[:login_handle_name] end def change_password_url=(change_password_url) self.settings[:change_password_url] = change_password_url end def change_password_url self.settings[:change_password_url] end def unknown_user_url=(unknown_user_url) self.settings[:unknown_user_url] = unknown_user_url end def unknown_user_url self.settings[:unknown_user_url] end def validate_auth_discovery_url return if self.settings[:auth_discovery_url].blank? begin value, _uri = CanvasHttp.validate_url(self.settings[:auth_discovery_url]) self.auth_discovery_url = value rescue URI::Error, ArgumentError errors.add(:discovery_url, t('errors.invalid_discovery_url', "The discovery URL is not valid" )) end end def validate_help_links links = self.settings[:custom_help_links] return if links.blank? link_errors = HelpLinks.validate_links(links) link_errors.each do |link_error| errors.add(:custom_help_links, link_error) end end def no_active_courses return true if root_account? if associated_courses.not_deleted.exists? errors.add(:workflow_state, "Can't delete an account with active courses.") end end def no_active_sub_accounts return true if root_account? if sub_accounts.exists? errors.add(:workflow_state, "Can't delete an account with active sub_accounts.") end end def find_courses(string) self.all_courses.select{|c| c.name.match(string) } end def find_users(string) self.pseudonyms.map{|p| p.user }.select{|u| u.name.match(string) } end class << self def special_accounts @special_accounts ||= {} end def special_account_ids @special_account_ids ||= {} end def special_account_timed_cache @special_account_timed_cache ||= TimedCache.new(-> { Setting.get('account_special_account_cache_time', 60).to_i.seconds.ago }) do special_accounts.clear end end def special_account_list @special_account_list ||= [] end def clear_special_account_cache!(force = false) special_account_timed_cache.clear(force) end def define_special_account(key, name = nil) name ||= key.to_s.titleize self.special_account_list << key instance_eval <<-RUBY, __FILE__, __LINE__ + 1 def self.#{key}(force_create = false) get_special_account(:#{key}, #{name.inspect}, force_create) end RUBY end def all_special_accounts special_account_list.map { |key| send(key) } end end define_special_account(:default, 'Default Account') # Account.default define_special_account(:site_admin) # Account.site_admin def clear_special_account_cache_if_special if self.shard == Shard.birth && Account.special_account_ids.values.map(&:to_i).include?(self.id) Account.clear_special_account_cache!(true) end end # an opportunity for plugins to load some other stuff up before caching the account def precache end class ::Canvas::AccountCacheError < StandardError; end def self.find_cached(id) default_id = Shard.relative_id_for(id, Shard.current, Shard.default) Shard.default.activate do MultiCache.fetch(account_lookup_cache_key(default_id)) do begin account = Account.find(default_id) rescue ActiveRecord::RecordNotFound => e raise ::Canvas::AccountCacheError, e.message end raise "Account.find_cached should only be used with root accounts" if !account.root_account? && !Rails.env.production? account.precache account end end end def self.get_special_account(special_account_type, default_account_name, force_create = false) Shard.birth.activate do account = special_accounts[special_account_type] unless account special_account_id = special_account_ids[special_account_type] ||= Setting.get("#{special_account_type}_account_id", nil) begin account = special_accounts[special_account_type] = Account.find_cached(special_account_id) if special_account_id rescue ::Canvas::AccountCacheError raise unless Rails.env.test? end end # another process (i.e. selenium spec) may have changed the setting unless account special_account_id = Setting.get("#{special_account_type}_account_id", nil) if special_account_id && special_account_id != special_account_ids[special_account_type] special_account_ids[special_account_type] = special_account_id account = special_accounts[special_account_type] = Account.where(id: special_account_id).first end end if !account && default_account_name && ((!special_account_id && !Rails.env.production?) || force_create) t '#account.default_site_administrator_account_name', 'Site Admin' t '#account.default_account_name', 'Default Account' account = special_accounts[special_account_type] = Account.new(:name => default_account_name) account.save! Setting.set("#{special_account_type}_account_id", account.id) special_account_ids[special_account_type] = account.id end account end end def site_admin? self == Account.site_admin end def display_name self.name end # Updates account associations for all the courses and users associated with this account def update_account_associations self.shard.activate do account_chain_cache = {} all_user_ids = Set.new # make sure to use the non-associated_courses associations # to catch courses that didn't ever have an association created scopes = if root_account? [all_courses, associated_courses. where("root_account_id<>?", self)] else [courses, associated_courses. where("courses.account_id<>?", self)] end # match the "batch" size in Course.update_account_associations scopes.each do |scope| scope.select([:id, :account_id]).find_in_batches(:batch_size => 500) do |courses| all_user_ids.merge Course.update_account_associations(courses, :skip_user_account_associations => true, :account_chain_cache => account_chain_cache) end end # Make sure we have all users with existing account associations. all_user_ids.merge self.user_account_associations.pluck(:user_id) if root_account? all_user_ids.merge self.pseudonyms.active.pluck(:user_id) end # Update the users' associations as well User.update_account_associations(all_user_ids.to_a, :account_chain_cache => account_chain_cache) end end def self.update_all_update_account_associations Account.root_accounts.active.non_shadow.find_in_batches(strategy: :pluck_ids) do |account_batch| account_batch.each(&:update_account_associations) end end def course_count self.courses.active.count end def sub_account_count self.sub_accounts.active.count end def user_count self.user_account_associations.count end def current_sis_batch if (current_sis_batch_id = self.read_attribute(:current_sis_batch_id)) && current_sis_batch_id.present? self.sis_batches.where(id: current_sis_batch_id).first end end def turnitin_settings return @turnitin_settings if defined?(@turnitin_settings) if self.turnitin_account_id.present? && self.turnitin_shared_secret.present? if settings[:enable_turnitin] @turnitin_settings = [self.turnitin_account_id, self.turnitin_shared_secret, self.turnitin_host] end else @turnitin_settings = self.parent_account.try(:turnitin_settings) end end def closest_turnitin_pledge closest_account_value(:turnitin_pledge, t('This assignment submission is my own, original work')) end def closest_turnitin_comments closest_account_value(:turnitin_comments) end def closest_turnitin_originality closest_account_value(:turnitin_originality, 'immediate') end def closest_account_value(value, default = '') account_with_value = account_chain.find { |a| a.send(value.to_sym).present? } account_with_value&.send(value.to_sym) || default end def self_enrollment_allowed?(course) if !settings[:self_enrollment].blank? !!(settings[:self_enrollment] == 'any' || (!course.sis_source_id && settings[:self_enrollment] == 'manually_created')) else !!(parent_account && parent_account.self_enrollment_allowed?(course)) end end def allow_self_enrollment!(setting='any') settings[:self_enrollment] = setting self.save! end TAB_COURSES = 0 TAB_STATISTICS = 1 TAB_PERMISSIONS = 2 TAB_SUB_ACCOUNTS = 3 TAB_TERMS = 4 TAB_AUTHENTICATION = 5 TAB_USERS = 6 TAB_OUTCOMES = 7 TAB_RUBRICS = 8 TAB_SETTINGS = 9 TAB_FACULTY_JOURNAL = 10 TAB_SIS_IMPORT = 11 TAB_GRADING_STANDARDS = 12 TAB_QUESTION_BANKS = 13 TAB_ADMIN_TOOLS = 17 TAB_SEARCH = 18 TAB_BRAND_CONFIGS = 19 TAB_EPORTFOLIO_MODERATION = 20 # site admin tabs TAB_PLUGINS = 14 TAB_JOBS = 15 TAB_DEVELOPER_KEYS = 16 def external_tool_tabs(opts, user) tools = ContextExternalTool.active.find_all_for(self, :account_navigation) .select { |t| t.permission_given?(:account_navigation, user, self) } Lti::ExternalToolTab.new(self, :account_navigation, tools, opts[:language]).tabs end def tabs_available(user=nil, opts={}) manage_settings = user && self.grants_right?(user, :manage_account_settings) if root_account.site_admin? tabs = [] tabs << { :id => TAB_USERS, :label => t("People"), :css_class => 'users', :href => :account_users_path } if user && self.grants_right?(user, :read_roster) tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && self.grants_right?(user, :manage_role_overrides) tabs << { :id => TAB_SUB_ACCOUNTS, :label => t('#account.tab_sub_accounts', "Sub-Accounts"), :css_class => 'sub_accounts', :href => :account_sub_accounts_path } if manage_settings tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if root_account? && manage_settings tabs << { :id => TAB_PLUGINS, :label => t("#account.tab_plugins", "Plugins"), :css_class => "plugins", :href => :plugins_path, :no_args => true } if root_account? && self.grants_right?(user, :manage_site_settings) tabs << { :id => TAB_JOBS, :label => t("#account.tab_jobs", "Jobs"), :css_class => "jobs", :href => :jobs_path, :no_args => true } if root_account? && self.grants_right?(user, :view_jobs) else tabs = [] tabs << { :id => TAB_COURSES, :label => t('#account.tab_courses', "Courses"), :css_class => 'courses', :href => :account_path } if user && self.grants_right?(user, :read_course_list) tabs << { :id => TAB_USERS, :label => t("People"), :css_class => 'users', :href => :account_users_path } if user && self.grants_right?(user, :read_roster) tabs << { :id => TAB_STATISTICS, :label => t('#account.tab_statistics', "Statistics"), :css_class => 'statistics', :href => :statistics_account_path } if user && self.grants_right?(user, :view_statistics) tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && self.grants_right?(user, :manage_role_overrides) if user && self.grants_right?(user, :manage_outcomes) tabs << { :id => TAB_OUTCOMES, :label => t('#account.tab_outcomes', "Outcomes"), :css_class => 'outcomes', :href => :account_outcomes_path } end if self.can_see_rubrics_tab?(user) tabs << { :id => TAB_RUBRICS, :label => t('#account.tab_rubrics', "Rubrics"), :css_class => 'rubrics', :href => :account_rubrics_path } end tabs << { :id => TAB_GRADING_STANDARDS, :label => t('#account.tab_grading_standards', "Grading"), :css_class => 'grading_standards', :href => :account_grading_standards_path } if user && self.grants_right?(user, :manage_grades) tabs << { :id => TAB_QUESTION_BANKS, :label => t('#account.tab_question_banks', "Question Banks"), :css_class => 'question_banks', :href => :account_question_banks_path } if user && self.grants_right?(user, :manage_assignments) tabs << { :id => TAB_SUB_ACCOUNTS, :label => t('#account.tab_sub_accounts', "Sub-Accounts"), :css_class => 'sub_accounts', :href => :account_sub_accounts_path } if manage_settings tabs << { :id => TAB_FACULTY_JOURNAL, :label => t('#account.tab_faculty_journal', "Faculty Journal"), :css_class => 'faculty_journal', :href => :account_user_notes_path} if self.enable_user_notes && user && self.grants_right?(user, :manage_user_notes) tabs << { :id => TAB_TERMS, :label => t('#account.tab_terms', "Terms"), :css_class => 'terms', :href => :account_terms_path } if self.root_account? && manage_settings tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if self.root_account? && manage_settings if self.root_account? && self.allow_sis_import && user && self.grants_any_right?(user, :manage_sis, :import_sis) tabs << { id: TAB_SIS_IMPORT, label: t('#account.tab_sis_import', "SIS Import"), css_class: 'sis_import', href: :account_sis_import_path } end end tabs << { :id => TAB_BRAND_CONFIGS, :label => t('#account.tab_brand_configs', "Themes"), :css_class => 'brand_configs', :href => :account_brand_configs_path } if manage_settings && branding_allowed? if root_account? && self.grants_right?(user, :manage_developer_keys) tabs << { :id => TAB_DEVELOPER_KEYS, :label => t("#account.tab_developer_keys", "Developer Keys"), :css_class => "developer_keys", :href => :account_developer_keys_path, account_id: root_account.id } end tabs += external_tool_tabs(opts, user) tabs += Lti::MessageHandler.lti_apps_tabs(self, [Lti::ResourcePlacement::ACCOUNT_NAVIGATION], opts) tabs << { :id => TAB_ADMIN_TOOLS, :label => t('#account.tab_admin_tools', "Admin Tools"), :css_class => 'admin_tools', :href => :account_admin_tools_path } if can_see_admin_tools_tab?(user) if user && grants_right?(user, :moderate_user_content) tabs << { id: TAB_EPORTFOLIO_MODERATION, label: t("ePortfolio Moderation"), css_class: "eportfolio_moderation", href: :account_eportfolio_moderation_path } end tabs << { :id => TAB_SETTINGS, :label => t('#account.tab_settings', "Settings"), :css_class => 'settings', :href => :account_settings_path } tabs.delete_if{ |t| t[:visibility] == 'admins' } unless self.grants_right?(user, :manage) tabs end def can_see_rubrics_tab?(user) user && self.grants_right?(user, :manage_rubrics) end def can_see_admin_tools_tab?(user) return false if !user || root_account.site_admin? admin_tool_permissions = RoleOverride.manageable_permissions(self).find_all{|p| p[1][:admin_tool]} admin_tool_permissions.any? do |p| self.grants_right?(user, p.first) end end def is_a_context? true end def help_links links = settings[:custom_help_links] # set the type to custom for any existing custom links that don't have a type set # the new ui will set the type ('custom' or 'default') for any new custom links # since we now allow reordering the links, the default links get stored in the settings as well if !links.blank? links.each do |link| if link[:type].blank? link[:type] = 'custom' end end links = help_links_builder.map_default_links(links) end result = if settings[:new_custom_help_links] links || help_links_builder.default_links else help_links_builder.default_links + (links || []) end filtered_result = help_links_builder.filtered_links(result) help_links_builder.instantiate_links(filtered_result) end def help_links_builder @help_links_builder ||= HelpLinks.new(self) end def set_service_availability(service, enable) service = service.to_sym raise "Invalid Service" unless AccountServices.allowable_services[service] allowed_service_names = (self.allowed_services || "").split(",").compact if allowed_service_names.count > 0 && ![ '+', '-' ].include?(allowed_service_names[0][0,1]) # This account has a hard-coded list of services, so handle accordingly allowed_service_names.reject! { |flag| flag.match("^[+-]?#{service}$") } allowed_service_names << service if enable else allowed_service_names.reject! { |flag| flag.match("^[+-]?#{service}$") } if enable # only enable if it is not enabled by default allowed_service_names << "+#{service}" unless AccountServices.default_allowable_services[service] else # only disable if it is not enabled by default allowed_service_names << "-#{service}" if AccountServices.default_allowable_services[service] end end @allowed_services_hash = nil self.allowed_services = allowed_service_names.empty? ? nil : allowed_service_names.join(",") end def enable_service(service) set_service_availability(service, true) end def disable_service(service) set_service_availability(service, false) end def allowed_services_hash return @allowed_services_hash if @allowed_services_hash account_allowed_services = AccountServices.default_allowable_services if self.allowed_services allowed_service_names = self.allowed_services.split(",").compact if allowed_service_names.count > 0 unless [ '+', '-' ].member?(allowed_service_names[0][0,1]) # This account has a hard-coded list of services, so we clear out the defaults account_allowed_services = AccountServices::AllowedServicesHash.new end allowed_service_names.each do |service_switch| if service_switch =~ /\A([+-]?)(.*)\z/ flag = $1 service_name = $2.to_sym if flag == '-' account_allowed_services.delete(service_name) else account_allowed_services[service_name] = AccountServices.allowable_services[service_name] end end end end end @allowed_services_hash = account_allowed_services end # if expose_as is nil, all services exposed in the ui are returned # if it's :service or :setting, then only services set to be exposed as that type are returned def self.services_exposed_to_ui_hash(expose_as = nil, current_user = nil, account = nil) if expose_as AccountServices.allowable_services.reject { |_, setting| setting[:expose_to_ui] != expose_as } else AccountServices.allowable_services.reject { |_, setting| !setting[:expose_to_ui] } end.reject { |_, setting| setting[:expose_to_ui_proc] && !setting[:expose_to_ui_proc].call(current_user, account) } end def service_enabled?(service) service = service.to_sym case service when :none self.allowed_services_hash.empty? else self.allowed_services_hash.has_key?(service) end end def self.all_accounts_for(context) if context.respond_to?(:account) context.account.account_chain elsif context.respond_to?(:parent_account) context.account_chain else [] end end def find_child(child_id) return all_accounts.find(child_id) if root_account? child = Account.find(child_id) raise ActiveRecord::RecordNotFound unless child.account_chain.include?(self) child end def manually_created_courses_account return self.root_account.manually_created_courses_account unless self.root_account? display_name = t('#account.manually_created_courses', "Manually-Created Courses") acct = manually_created_courses_account_from_settings if acct.blank? transaction do lock! acct = manually_created_courses_account_from_settings acct ||= self.sub_accounts.where(name: display_name).first_or_create! # for backwards compatibility if acct.id != self.settings[:manually_created_courses_account_id] self.settings[:manually_created_courses_account_id] = acct.id self.save! end end end acct end def manually_created_courses_account_from_settings acct_id = self.settings[:manually_created_courses_account_id] acct = self.sub_accounts.where(id: acct_id).first if acct_id.present? acct = nil if acct.present? && acct.root_account_id != self.id acct end private :manually_created_courses_account_from_settings def trusted_account_ids return [] if !root_account? || self == Account.site_admin [ Account.site_admin.id ] end def trust_exists? false end def user_list_search_mode_for(user) return :preferred if self.root_account.open_registration? return :preferred if self.root_account.grants_right?(user, :manage_user_logins) :closed end scope :root_accounts, -> { where(:root_account_id => nil).where.not(id: 0) } scope :processing_sis_batch, -> { where("accounts.current_sis_batch_id IS NOT NULL").order(:updated_at) } scope :name_like, lambda { |name| where(wildcard('accounts.name', name)) } scope :active, -> { where("accounts.workflow_state<>'deleted'") } def change_root_account_setting!(setting_name, new_value) root_account.settings[setting_name] = new_value root_account.save! end Bookmarker = BookmarkedCollection::SimpleBookmarker.new(Account, :name, :id) def format_referer(referer_url) begin referer = URI(referer_url || '') rescue URI::Error return end return unless referer.host referer_with_port = "#{referer.scheme}://#{referer.host}" referer_with_port += ":#{referer.port}" unless referer.port == (referer.scheme == 'https' ? 443 : 80) referer_with_port end def trusted_referers=(value) self.settings[:trusted_referers] = unless value.blank? value.split(',').map { |referer_url| format_referer(referer_url) }.compact.join(',') end end def trusted_referer?(referer_url) return if !self.settings.has_key?(:trusted_referers) || self.settings[:trusted_referers].blank? if (referer_with_port = format_referer(referer_url)) self.settings[:trusted_referers].split(',').include?(referer_with_port) end end def parent_registration? authentication_providers.where(parent_registration: true).exists? end def parent_auth_type return nil unless parent_registration? parent_registration_aac.auth_type end def parent_registration_aac authentication_providers.where(parent_registration: true).first end def require_email_for_registration? Canvas::Plugin.value_to_boolean(settings[:require_email_for_registration]) || false end def to_param return 'site_admin' if site_admin? super end def create_default_objects work = -> do default_enrollment_term enable_canvas_authentication TermsOfService.ensure_terms_for_account(self, true) if self.root_account? && !TermsOfService.skip_automatic_terms_creation create_built_in_roles if self.root_account? end return work.call if Rails.env.test? self.class.connection.after_transaction_commit(&work) end def create_built_in_roles self.shard.activate do Role::BASE_TYPES.each do |base_type| role = Role.new role.name = base_type role.base_role_type = base_type role.workflow_state = :built_in role.root_account_id = self.id role.save! end end end def migrate_to_canvadocs? Canvadocs.hijack_crocodoc_sessions? end def update_terms_of_service(terms_params) terms = TermsOfService.ensure_terms_for_account(self) terms.terms_type = terms_params[:terms_type] if terms_params[:terms_type] terms.passive = Canvas::Plugin.value_to_boolean(terms_params[:passive]) if terms_params.has_key?(:passive) if terms.custom? TermsOfServiceContent.ensure_content_for_account(self) self.terms_of_service_content.update_attribute(:content, terms_params[:content]) if terms_params[:content] end if terms.changed? unless terms.save self.errors.add(:terms_of_service, t("Terms of Service attributes not valid")) end end end # Different views are available depending on feature flags def dashboard_views ['activity', 'cards', 'planner'] end # Getter/Setter for default_dashboard_view account setting def default_dashboard_view=(view) return unless dashboard_views.include?(view) self.settings[:default_dashboard_view] = view end def default_dashboard_view @default_dashboard_view ||= self.settings[:default_dashboard_view] end # Forces the default setting to overwrite each user's preference def update_user_dashboards User.where(id: self.user_account_associations.select(:user_id)) .where("#{User.table_name}.preferences LIKE ?", "%:dashboard_view:%") .find_in_batches do |batch| users = batch.reject { |user| user.preferences[:dashboard_view].nil? || user.dashboard_view(self) == default_dashboard_view } users.each do |user| user.preferences.delete(:dashboard_view) user.save! end end end handle_asynchronously :update_user_dashboards, :priority => Delayed::LOW_PRIORITY, :max_attempts => 1 def process_external_integration_keys(params_keys, current_user, keys = ExternalIntegrationKey.indexed_keys_for(self)) return unless params_keys keys.each do |key_type, key| next unless params_keys.key?(key_type) next unless key.grants_right?(current_user, :write) unless params_keys[key_type].blank? key.key_value = params_keys[key_type] key.save! else key.delete end end end def available_course_visibility_override_options(_options=nil) _options || {} end def user_needs_verification?(user) self.require_confirmed_email? && (user.nil? || !user.cached_active_emails.any?) end def allow_disable_post_to_sis_when_grading_period_closed? return false unless root_account? return false unless feature_enabled?(:disable_post_to_sis_when_grading_period_closed) Account.site_admin.feature_enabled?(:new_sis_integrations) end class << self attr_accessor :current_domain_root_account end module DomainRootAccountCache def find_one(id) return Account.current_domain_root_account if Account.current_domain_root_account && Account.current_domain_root_account.shard == shard_value && Account.current_domain_root_account.local_id == id super end def find_take return super unless where_clause.send(:predicates).length == 1 predicates = where_clause.to_h return super unless predicates.length == 1 return super unless predicates.keys.first == "id" return Account.current_domain_root_account if Account.current_domain_root_account && Account.current_domain_root_account.shard == shard_value && Account.current_domain_root_account.local_id == predicates.values.first super end end relation_delegate_class(ActiveRecord::Relation).prepend(DomainRootAccountCache) relation_delegate_class(ActiveRecord::AssociationRelation).prepend(DomainRootAccountCache) def self.ensure_dummy_root_account Account.find_or_create_by!(id: 0) if Rails.env.test? end def roles_with_enabled_permission(permission) roles = available_roles roles.select do |role| RoleOverride.permission_for(self, permission, role, self, true)[:enabled] end end def get_rce_favorite_tool_ids rce_favorite_tool_ids[:value] || ContextExternalTool.all_tools_for(self, placements: [:editor_button]). # TODO remove after datafixup and the is_rce_favorite column is removed where(:is_rce_favorite => true).pluck(:id).map{|id| Shard.global_id_for(id)} end end ensure only one invalidate_inherited_caches is run at a time Change-Id: Ie3bd093b2dba8446e6e4bed6a266af21d90fada2 Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/249655 Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com> Reviewed-by: Simon Williams <088e16a1019277b15d58faf0541e11910eb756f6@instructure.com> QA-Review: Cody Cutrer <c4fe2b1d90ef8f2548c8aeabfa633434316f0305@instructure.com> Product-Review: Cody Cutrer <c4fe2b1d90ef8f2548c8aeabfa633434316f0305@instructure.com> # # Copyright (C) 2011 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # require 'atom' class Account < ActiveRecord::Base include Context include OutcomeImportContext include Pronouns INSTANCE_GUID_SUFFIX = 'canvas-lms' include Workflow include BrandConfigHelpers belongs_to :root_account, :class_name => 'Account' belongs_to :parent_account, :class_name => 'Account' has_many :courses has_many :favorites, inverse_of: :root_account has_many :all_courses, :class_name => 'Course', :foreign_key => 'root_account_id' has_one :terms_of_service, :dependent => :destroy has_one :terms_of_service_content, :dependent => :destroy has_many :group_categories, -> { where(deleted_at: nil) }, as: :context, inverse_of: :context has_many :all_group_categories, :class_name => 'GroupCategory', foreign_key: 'root_account_id', inverse_of: :root_account has_many :groups, :as => :context, :inverse_of => :context has_many :all_groups, class_name: 'Group', foreign_key: 'root_account_id', inverse_of: :root_account has_many :all_group_memberships, source: 'group_memberships', through: :all_groups has_many :enrollment_terms, :foreign_key => 'root_account_id' has_many :active_enrollment_terms, -> { where("enrollment_terms.workflow_state<>'deleted'") }, class_name: 'EnrollmentTerm', foreign_key: 'root_account_id' has_many :grading_period_groups, inverse_of: :root_account, dependent: :destroy has_many :grading_periods, through: :grading_period_groups has_many :enrollments, -> { where("enrollments.type<>'StudentViewEnrollment'") }, foreign_key: 'root_account_id' has_many :all_enrollments, :class_name => 'Enrollment', :foreign_key => 'root_account_id' has_many :sub_accounts, -> { where("workflow_state<>'deleted'") }, class_name: 'Account', foreign_key: 'parent_account_id' has_many :all_accounts, -> { order(:name) }, class_name: 'Account', foreign_key: 'root_account_id' has_many :account_users, :dependent => :destroy has_many :active_account_users, -> { active }, class_name: 'AccountUser' has_many :course_sections, :foreign_key => 'root_account_id' has_many :sis_batches has_many :abstract_courses, :class_name => 'AbstractCourse', :foreign_key => 'account_id' has_many :root_abstract_courses, :class_name => 'AbstractCourse', :foreign_key => 'root_account_id' has_many :users, :through => :active_account_users has_many :pseudonyms, -> { preload(:user) }, inverse_of: :account has_many :role_overrides, :as => :context, :inverse_of => :context has_many :course_account_associations has_many :child_courses, -> { where(course_account_associations: { depth: 0 }) }, through: :course_account_associations, source: :course has_many :attachments, :as => :context, :inverse_of => :context, :dependent => :destroy has_many :active_assignments, -> { where("assignments.workflow_state<>'deleted'") }, as: :context, inverse_of: :context, class_name: 'Assignment' has_many :folders, -> { order('folders.name') }, as: :context, inverse_of: :context, dependent: :destroy has_many :active_folders, -> { where("folder.workflow_state<>'deleted'").order('folders.name') }, class_name: 'Folder', as: :context, inverse_of: :context has_many :developer_keys has_many :developer_key_account_bindings, inverse_of: :account, dependent: :destroy has_many :authentication_providers, -> { order(:position) }, inverse_of: :account, extend: AuthenticationProvider::FindWithType has_many :account_reports, inverse_of: :account has_many :grading_standards, -> { where("workflow_state<>'deleted'") }, as: :context, inverse_of: :context has_many :assessment_question_banks, -> { preload(:assessment_questions, :assessment_question_bank_users) }, as: :context, inverse_of: :context has_many :assessment_questions, :through => :assessment_question_banks has_many :roles has_many :all_roles, :class_name => 'Role', :foreign_key => 'root_account_id' has_many :progresses, :as => :context, :inverse_of => :context has_many :content_migrations, :as => :context, :inverse_of => :context has_many :sis_batch_errors, foreign_key: :root_account_id, inverse_of: :root_account has_one :outcome_proficiency, as: :context, inverse_of: :context, dependent: :destroy has_one :outcome_calculation_method, as: :context, inverse_of: :context, dependent: :destroy has_many :auditor_authentication_records, class_name: "Auditors::ActiveRecord::AuthenticationRecord", dependent: :destroy, inverse_of: :account has_many :auditor_course_records, class_name: "Auditors::ActiveRecord::CourseRecord", dependent: :destroy, inverse_of: :account has_many :auditor_grade_change_records, class_name: "Auditors::ActiveRecord::GradeChangeRecord", dependent: :destroy, inverse_of: :account has_many :auditor_root_grade_change_records, foreign_key: 'root_account_id', class_name: "Auditors::ActiveRecord::GradeChangeRecord", dependent: :destroy, inverse_of: :root_account def inherited_assessment_question_banks(include_self = false, *additional_contexts) sql, conds = [], [] contexts = additional_contexts + account_chain contexts.delete(self) unless include_self contexts.each { |c| sql << "context_type = ? AND context_id = ?" conds += [c.class.to_s, c.id] } conds.unshift(sql.join(" OR ")) AssessmentQuestionBank.where(conds) end include LearningOutcomeContext include RubricContext has_many :context_external_tools, -> { order(:name) }, as: :context, inverse_of: :context, dependent: :destroy has_many :error_reports has_many :announcements, :class_name => 'AccountNotification' has_many :alerts, -> { preload(:criteria) }, as: :context, inverse_of: :context has_many :user_account_associations has_many :report_snapshots has_many :external_integration_keys, :as => :context, :inverse_of => :context, :dependent => :destroy has_many :shared_brand_configs belongs_to :brand_config, foreign_key: "brand_config_md5" before_validation :verify_unique_sis_source_id before_save :ensure_defaults before_create :enable_sis_imports, if: :root_account? after_save :update_account_associations_if_changed after_save :check_downstream_caches before_save :setup_cache_invalidation after_save :invalidate_caches_if_changed after_update :clear_special_account_cache_if_special after_update :clear_cached_short_name, :if => :saved_change_to_name? after_create :create_default_objects serialize :settings, Hash include TimeZoneHelper time_zone_attribute :default_time_zone, default: "America/Denver" def default_time_zone if read_attribute(:default_time_zone) || root_account? super else root_account.default_time_zone end end alias_method :time_zone, :default_time_zone validates_locale :default_locale, :allow_nil => true validates_length_of :name, :maximum => maximum_string_length, :allow_blank => true validate :account_chain_loop, :if => :parent_account_id_changed? validate :validate_auth_discovery_url validates :workflow_state, presence: true validate :no_active_courses, if: lambda { |a| a.workflow_state_changed? && !a.active? } validate :no_active_sub_accounts, if: lambda { |a| a.workflow_state_changed? && !a.active? } validate :validate_help_links, if: lambda { |a| a.settings_changed? } include StickySisFields are_sis_sticky :name, :parent_account_id include FeatureFlags def feature_flag_cache MultiCache.cache end def redis_for_root_account_cache_register return unless MultiCache.cache.respond_to?(:redis) redis = MultiCache.cache.redis return if redis.respond_to?(:node_for) redis end def root_account_cache_key base_key = self.class.base_cache_register_key_for(self) "#{base_key}/feature_flags" end def cache_key(key_type = nil) return super if new_record? return super unless root_account? && key_type == :feature_flags return super unless (redis = redis_for_root_account_cache_register) # partially taken from CacheRegister.cache_key_for_id, but modified to # target HACache full_key = root_account_cache_key RequestCache.cache(full_key) do now = Time.now.utc.to_s(self.cache_timestamp_format) # try to get the timestamp for the type, set it to now if it doesn't exist ts = Canvas::CacheRegister.lua.run(:get_key, [full_key], [now], redis) "#{self.model_name.cache_key}/#{global_id}-#{ts}" end end def clear_cache_key(*key_types) return super unless root_account? && key_types == [:feature_flags] return super unless redis_for_root_account_cache_register MultiCache.delete(root_account_cache_key) end def self.recursive_default_locale_for_id(account_id) local_id, shard = Shard.local_id_for(account_id) (shard || Shard.current).activate do obj = Account.new(id: local_id) # someday i should figure out a better way to avoid instantiating an object instead of tricking cache register Rails.cache.fetch_with_batched_keys('default_locale_for_id', batch_object: obj, batched_keys: [:account_chain, :default_locale]) do # couldn't find the cache so now we actually need to find the account acc = Account.find(local_id) acc.default_locale || (acc.parent_account_id && recursive_default_locale_for_id(acc.parent_account_id)) end end end def default_locale result = read_attribute(:default_locale) result = nil unless I18n.locale_available?(result) result end def resolved_outcome_proficiency if outcome_proficiency&.active? outcome_proficiency elsif parent_account parent_account.resolved_outcome_proficiency elsif self.feature_enabled?(:account_level_mastery_scales) OutcomeProficiency.find_or_create_default!(self) end end def resolved_outcome_calculation_method if outcome_calculation_method&.active? outcome_calculation_method elsif parent_account parent_account.resolved_outcome_calculation_method elsif self.feature_enabled?(:account_level_mastery_scales) OutcomeCalculationMethod.find_or_create_default!(self) end end include ::Account::Settings include ::Csp::AccountHelper # these settings either are or could be easily added to # the account settings page add_setting :sis_app_token, :root_only => true add_setting :sis_app_url, :root_only => true add_setting :sis_name, :root_only => true add_setting :sis_syncing, :boolean => true, :default => false, :inheritable => true add_setting :sis_default_grade_export, :boolean => true, :default => false, :inheritable => true add_setting :include_integration_ids_in_gradebook_exports, :boolean => true, :default => false, :root_only => true add_setting :sis_require_assignment_due_date, :boolean => true, :default => false, :inheritable => true add_setting :sis_assignment_name_length, :boolean => true, :default => false, :inheritable => true add_setting :sis_assignment_name_length_input, :inheritable => true add_setting :global_includes, :root_only => true, :boolean => true, :default => false add_setting :sub_account_includes, :boolean => true, :default => false # Help link settings add_setting :custom_help_links, :root_only => true add_setting :help_link_icon, :root_only => true add_setting :help_link_name, :root_only => true add_setting :support_url, :root_only => true add_setting :prevent_course_renaming_by_teachers, :boolean => true, :root_only => true add_setting :login_handle_name, root_only: true add_setting :change_password_url, root_only: true add_setting :unknown_user_url, root_only: true add_setting :fft_registration_url, root_only: true add_setting :restrict_student_future_view, :boolean => true, :default => false, :inheritable => true add_setting :restrict_student_future_listing, :boolean => true, :default => false, :inheritable => true add_setting :restrict_student_past_view, :boolean => true, :default => false, :inheritable => true add_setting :teachers_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :students_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :restrict_quiz_questions, :boolean => true, :root_only => true, :default => false add_setting :no_enrollments_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :allow_sending_scores_in_emails, :boolean => true, :root_only => true add_setting :can_add_pronouns, :boolean => true, :root_only => true, :default => false add_setting :self_enrollment add_setting :equella_endpoint add_setting :equella_teaser add_setting :enable_alerts, :boolean => true, :root_only => true add_setting :enable_eportfolios, :boolean => true, :root_only => true add_setting :users_can_edit_name, :boolean => true, :root_only => true add_setting :open_registration, :boolean => true, :root_only => true add_setting :show_scheduler, :boolean => true, :root_only => true, :default => false add_setting :enable_profiles, :boolean => true, :root_only => true, :default => false add_setting :enable_turnitin, :boolean => true, :default => false add_setting :mfa_settings, :root_only => true add_setting :mobile_qr_login_is_enabled, :boolean => true, :root_only => true, :default => true add_setting :admins_can_change_passwords, :boolean => true, :root_only => true, :default => false add_setting :admins_can_view_notifications, :boolean => true, :root_only => true, :default => false add_setting :canvadocs_prefer_office_online, :boolean => true, :root_only => true, :default => false add_setting :outgoing_email_default_name add_setting :external_notification_warning, :boolean => true, :default => false # Terms of Use and Privacy Policy settings for the root account add_setting :terms_changed_at, :root_only => true add_setting :account_terms_required, :root_only => true, :boolean => true, :default => true # When a user is invited to a course, do we let them see a preview of the # course even without registering? This is part of the free-for-teacher # account perks, since anyone can invite anyone to join any course, and it'd # be nice to be able to see the course first if you weren't expecting the # invitation. add_setting :allow_invitation_previews, :boolean => true, :root_only => true, :default => false add_setting :large_course_rosters, :boolean => true, :root_only => true, :default => false add_setting :edit_institution_email, :boolean => true, :root_only => true, :default => true add_setting :js_kaltura_uploader, :boolean => true, :root_only => true, :default => false add_setting :google_docs_domain, root_only: true add_setting :dashboard_url, root_only: true add_setting :product_name, root_only: true add_setting :author_email_in_notifications, boolean: true, root_only: true, default: false add_setting :include_students_in_global_survey, boolean: true, root_only: true, default: false add_setting :trusted_referers, root_only: true add_setting :app_center_access_token add_setting :enable_offline_web_export, boolean: true, default: false, inheritable: true add_setting :disable_rce_media_uploads, boolean: true, default: false, inheritable: true add_setting :strict_sis_check, :boolean => true, :root_only => true, :default => false add_setting :lock_all_announcements, default: false, boolean: true, inheritable: true add_setting :enable_gravatar, :boolean => true, :root_only => true, :default => true # For setting the default dashboard (e.g. Student Planner/List View, Activity Stream, Dashboard Cards) add_setting :default_dashboard_view, :inheritable => true add_setting :require_confirmed_email, :boolean => true, :root_only => true, :default => false add_setting :enable_course_catalog, :boolean => true, :root_only => true, :default => false add_setting :usage_rights_required, :boolean => true, :default => false, :inheritable => true add_setting :limit_parent_app_web_access, boolean: true, default: false, root_only: true add_setting :kill_joy, boolean: true, default: false, root_only: true add_setting :smart_alerts_threshold, default: 36, root_only: true add_setting :disable_post_to_sis_when_grading_period_closed, boolean: true, root_only: true, default: false # privacy settings for root accounts add_setting :enable_fullstory, boolean: true, root_only: true, default: true add_setting :enable_google_analytics, boolean: true, root_only: true, default: true add_setting :rce_favorite_tool_ids, :inheritable => true def settings=(hash) if hash.is_a?(Hash) || hash.is_a?(ActionController::Parameters) hash.each do |key, val| key = key.to_sym if account_settings_options && (opts = account_settings_options[key]) if (opts[:root_only] && !self.root_account?) || (opts[:condition] && !self.send("#{opts[:condition]}?".to_sym)) settings.delete key elsif opts[:hash] new_hash = {} if val.is_a?(Hash) || val.is_a?(ActionController::Parameters) val.each do |inner_key, inner_val| inner_key = inner_key.to_sym if opts[:values].include?(inner_key) if opts[:inheritable] && (inner_key == :locked || (inner_key == :value && opts[:boolean])) new_hash[inner_key] = Canvas::Plugin.value_to_boolean(inner_val) else new_hash[inner_key] = inner_val.to_s end end end end settings[key] = new_hash.empty? ? nil : new_hash elsif opts[:boolean] settings[key] = Canvas::Plugin.value_to_boolean(val) else settings[key] = val.to_s end end end end # prune nil or "" hash values to save space in the DB. settings.reject! { |_, value| value.nil? || value == "" } settings end def product_name settings[:product_name] || t("#product_name", "Canvas") end def usage_rights_required? usage_rights_required[:value] end def allow_global_includes? if root_account? global_includes? else root_account.try(:sub_account_includes?) && root_account.try(:allow_global_includes?) end end def pronouns return [] unless settings[:can_add_pronouns] settings[:pronouns]&.map{|p| translate_pronouns(p)} || Pronouns.default_pronouns end def pronouns=(pronouns) settings[:pronouns] = pronouns&.map{|p| untranslate_pronouns(p)}&.reject(&:blank?) end def mfa_settings settings[:mfa_settings].try(:to_sym) || :disabled end def non_canvas_auth_configured? authentication_providers.active.where("auth_type<>'canvas'").exists? end def canvas_authentication_provider @canvas_ap ||= authentication_providers.active.where(auth_type: 'canvas').first end def canvas_authentication? !!canvas_authentication_provider end def enable_canvas_authentication return unless root_account? # for migrations creating a new db return unless Account.connection.data_source_exists?("authentication_providers") return if authentication_providers.active.where(auth_type: 'canvas').exists? authentication_providers.create!(auth_type: 'canvas') end def enable_offline_web_export? enable_offline_web_export[:value] end def disable_rce_media_uploads? disable_rce_media_uploads[:value] end def open_registration? !!settings[:open_registration] && canvas_authentication? end def self_registration? canvas_authentication_provider.try(:jit_provisioning?) end def self_registration_type canvas_authentication_provider.try(:self_registration) end def self_registration_captcha? canvas_authentication_provider.try(:enable_captcha) end def self_registration_allowed_for?(type) return false unless self_registration? return false if self_registration_type != 'all' && type != self_registration_type true end def enable_self_registration canvas_authentication_provider.update_attribute(:self_registration, true) end def terms_required? terms = TermsOfService.ensure_terms_for_account(root_account) !(terms.terms_type == 'no_terms' || terms.passive) end def require_acceptance_of_terms?(user) return false if !terms_required? return true if (user.nil? || user.new_record?) soc2_start_date = Setting.get('SOC2_start_date', Time.new(2015, 5, 16, 0, 0, 0).utc).to_datetime return false if user.created_at < soc2_start_date terms_changed_at = root_account.terms_of_service.terms_of_service_content&.terms_updated_at || settings[:terms_changed_at] last_accepted = user.preferences[:accepted_terms] return false if last_accepted && (terms_changed_at.nil? || last_accepted > terms_changed_at) true end def ip_filters=(params) filters = {} require 'ipaddr' params.each do |key, str| ips = [] vals = str.split(/,/) vals.each do |val| ip = IPAddr.new(val) rescue nil # right now the ip_filter column on quizzes is just a string, # so it has a max length. I figure whatever we set it to this # setter should at the very least limit stored values to that # length. ips << val if ip && val.length <= 255 end filters[key] = ips.join(',') unless ips.empty? end settings[:ip_filters] = filters end def enable_sis_imports self.allow_sis_import = true end def ensure_defaults self.name&.delete!("\r") self.uuid ||= CanvasSlug.generate_securish_uuid self.lti_guid ||= "#{self.uuid}:#{INSTANCE_GUID_SUFFIX}" if self.respond_to?(:lti_guid) self.root_account_id ||= self.parent_account.root_account_id if self.parent_account self.root_account_id ||= self.parent_account_id self.parent_account_id ||= self.root_account_id true end def verify_unique_sis_source_id return true unless self.sis_source_id return true if !root_account_id_changed? && !sis_source_id_changed? if self.root_account? self.errors.add(:sis_source_id, t('#account.root_account_cant_have_sis_id', "SIS IDs cannot be set on root accounts")) throw :abort end scope = root_account.all_accounts.where(sis_source_id: self.sis_source_id) scope = scope.where("id<>?", self) unless self.new_record? return true unless scope.exists? self.errors.add(:sis_source_id, t('#account.sis_id_in_use', "SIS ID \"%{sis_id}\" is already in use", :sis_id => self.sis_source_id)) throw :abort end def update_account_associations_if_changed if self.saved_change_to_parent_account_id? || self.saved_change_to_root_account_id? self.shard.activate do send_later_if_production(:update_account_associations) end end end def check_downstream_caches keys_to_clear = [] keys_to_clear << :account_chain if self.saved_change_to_parent_account_id? || self.saved_change_to_root_account_id? if self.saved_change_to_brand_config_md5? || (@old_settings && @old_settings[:sub_account_includes] != settings[:sub_account_includes]) keys_to_clear << :brand_config end keys_to_clear << :default_locale if self.saved_change_to_default_locale? if keys_to_clear.any? self.shard.activate do send_later_if_production(:clear_downstream_caches, *keys_to_clear) end end end def clear_downstream_caches(*key_types) self.shard.activate do Account.clear_cache_keys([self.id] + Account.sub_account_ids_recursive(self.id), *key_types) end end def equella_settings endpoint = self.settings[:equella_endpoint] || self.equella_endpoint if !endpoint.blank? OpenObject.new({ :endpoint => endpoint, :default_action => self.settings[:equella_action] || 'selectOrAdd', :teaser => self.settings[:equella_teaser] }) else nil end end def settings result = self.read_attribute(:settings) if result @old_settings ||= result.dup return result end return write_attribute(:settings, {}) unless frozen? {}.freeze end def domain(current_host = nil) HostUrl.context_host(self, current_host) end def self.find_by_domain(domain) self.default if HostUrl.default_host == domain end def root_account? !self.root_account_id end def root_account return self if root_account? super end def resolved_root_account_id root_account_id || id end def sub_accounts_as_options(indent = 0, preloaded_accounts = nil) unless preloaded_accounts preloaded_accounts = {} self.root_account.all_accounts.active.each do |account| (preloaded_accounts[account.parent_account_id] ||= []) << account end end res = [[("&nbsp;&nbsp;" * indent).html_safe + self.name, self.id]] if preloaded_accounts[self.id] preloaded_accounts[self.id].each do |account| res += account.sub_accounts_as_options(indent + 1, preloaded_accounts) end end res end def users_visible_to(user) self.grants_right?(user, :read) ? self.all_users : self.all_users.none end def users_name_like(query="") @cached_users_name_like ||= {} @cached_users_name_like[query] ||= self.fast_all_users.name_like(query) end def associated_courses(opts = {}) if root_account? all_courses else shard.activate do if opts[:include_crosslisted_courses] Course.where("EXISTS (?)", CourseAccountAssociation.where(account_id: self). where("course_id=courses.id")) else Course.where("EXISTS (?)", CourseAccountAssociation.where(account_id: self, course_section_id: nil). where("course_id=courses.id")) end end end end def associated_user?(user) user_account_associations.where(user_id: user).exists? end def fast_course_base(opts = {}) opts[:order] ||= Course.best_unicode_collation_key("courses.name").asc columns = "courses.id, courses.name, courses.workflow_state, courses.course_code, courses.sis_source_id, courses.enrollment_term_id" associated_courses = self.associated_courses( :include_crosslisted_courses => opts[:include_crosslisted_courses] ) associated_courses = associated_courses.active.order(opts[:order]) associated_courses = associated_courses.with_enrollments if opts[:hide_enrollmentless_courses] associated_courses = associated_courses.master_courses if opts[:only_master_courses] associated_courses = associated_courses.for_term(opts[:term]) if opts[:term].present? associated_courses = yield associated_courses if block_given? associated_courses.limit(opts[:limit]).active_first.select(columns).to_a end def fast_all_courses(opts={}) @cached_fast_all_courses ||= {} @cached_fast_all_courses[opts] ||= self.fast_course_base(opts) end def all_users(limit=250) @cached_all_users ||= {} @cached_all_users[limit] ||= User.of_account(self).limit(limit) end def fast_all_users(limit=nil) @cached_fast_all_users ||= {} @cached_fast_all_users[limit] ||= self.all_users(limit).active.select("users.id, users.updated_at, users.name, users.sortable_name").order_by_sortable_name end def users_not_in_groups(groups, opts={}) scope = User.active.joins(:user_account_associations). where(user_account_associations: {account_id: self}). where(Group.not_in_group_sql_fragment(groups.map(&:id))). select("users.id, users.name") scope = scope.select(opts[:order]).order(opts[:order]) if opts[:order] scope end def courses_name_like(query="", opts={}) opts[:limit] ||= 200 @cached_courses_name_like ||= {} @cached_courses_name_like[[query, opts]] ||= self.fast_course_base(opts) {|q| q.name_like(query)} end def self_enrollment_course_for(code) all_courses. where(:self_enrollment_code => code). first end def file_namespace if Shard.current == Shard.birth "account_#{root_account.local_id}" else root_account.global_asset_string end end def self.account_lookup_cache_key(id) ['_account_lookup5', id].cache_key end def self.invalidate_cache(id) return unless id default_id = Shard.relative_id_for(id, Shard.current, Shard.default) Shard.default.activate do MultiCache.delete(account_lookup_cache_key(default_id)) if default_id end rescue nil end def setup_cache_invalidation @invalidations = [] unless self.new_record? invalidate_all = self.parent_account_id_changed? # apparently, the try_rescues are because these columns don't exist on old migrations @invalidations += ['default_storage_quota', 'current_quota'] if invalidate_all || self.try_rescue(:default_storage_quota_changed?) @invalidations << 'default_group_storage_quota' if invalidate_all || self.try_rescue(:default_group_storage_quota_changed?) end end def invalidate_caches_if_changed if changed? connection.after_transaction_commit do if root_account? Account.invalidate_cache(id) else shard.activate do Rails.cache.delete(["account"/ id].cache_key) end end end end @invalidations ||= [] if self.saved_change_to_parent_account_id? @invalidations += Account.inheritable_settings # invalidate all of them elsif @old_settings Account.inheritable_settings.each do |key| @invalidations << key if @old_settings[key] != settings[key] # only invalidate if needed end @old_settings = nil end if @invalidations.present? shard.activate do @invalidations.each do |key| Rails.cache.delete([key, self.global_id].cache_key) end Account.send_later_if_production_enqueue_args(:invalidate_inherited_caches, { singleton: "Account.invalidate_inherited_caches_#{global_id}" }, self, @invalidations) end end end def self.invalidate_inherited_caches(parent_account, keys) parent_account.shard.activate do account_ids = Account.sub_account_ids_recursive(parent_account.id) account_ids.each do |id| global_id = Shard.global_id_for(id) keys.each do |key| Rails.cache.delete([key, global_id].cache_key) end end access_keys = keys & [:restrict_student_future_view, :restrict_student_past_view] if access_keys.any? EnrollmentState.invalidate_access_for_accounts([parent_account.id] + account_ids, access_keys) end end end def self.default_storage_quota Setting.get('account_default_quota', 500.megabytes.to_s).to_i end def quota return storage_quota if read_attribute(:storage_quote) return self.class.default_storage_quota if root_account? shard.activate do Rails.cache.fetch(['current_quota', self.global_id].cache_key) do self.parent_account.default_storage_quota end end end def default_storage_quota return super if read_attribute(:default_storage_quota) return self.class.default_storage_quota if root_account? shard.activate do @default_storage_quota ||= Rails.cache.fetch(['default_storage_quota', self.global_id].cache_key) do parent_account.default_storage_quota end end end def default_storage_quota_mb default_storage_quota / 1.megabyte end def default_storage_quota_mb=(val) self.default_storage_quota = val.try(:to_i).try(:megabytes) end def default_storage_quota=(val) val = val.to_f val = nil if val <= 0 # If the value is the same as the inherited value, then go # ahead and blank it so it keeps using the inherited value if parent_account && parent_account.default_storage_quota == val val = nil end write_attribute(:default_storage_quota, val) end def default_user_storage_quota read_attribute(:default_user_storage_quota) || User.default_storage_quota end def default_user_storage_quota=(val) val = val.to_i val = nil if val == User.default_storage_quota || val <= 0 write_attribute(:default_user_storage_quota, val) end def default_user_storage_quota_mb default_user_storage_quota / 1.megabyte end def default_user_storage_quota_mb=(val) self.default_user_storage_quota = val.try(:to_i).try(:megabytes) end def default_group_storage_quota return super if read_attribute(:default_group_storage_quota) return Group.default_storage_quota if root_account? shard.activate do Rails.cache.fetch(['default_group_storage_quota', self.global_id].cache_key) do self.parent_account.default_group_storage_quota end end end def default_group_storage_quota=(val) val = val.to_i if (val == Group.default_storage_quota) || (val <= 0) || (self.parent_account && self.parent_account.default_group_storage_quota == val) val = nil end write_attribute(:default_group_storage_quota, val) end def default_group_storage_quota_mb default_group_storage_quota / 1.megabyte end def default_group_storage_quota_mb=(val) self.default_group_storage_quota = val.try(:to_i).try(:megabytes) end def turnitin_shared_secret=(secret) return if secret.blank? self.turnitin_crypted_secret, self.turnitin_salt = Canvas::Security.encrypt_password(secret, 'instructure_turnitin_secret_shared') end def turnitin_shared_secret return nil unless self.turnitin_salt && self.turnitin_crypted_secret Canvas::Security.decrypt_password(self.turnitin_crypted_secret, self.turnitin_salt, 'instructure_turnitin_secret_shared') end def self.account_chain(starting_account_id) chain = [] if (starting_account_id.is_a?(Account)) chain << starting_account_id starting_account_id = starting_account_id.parent_account_id end if starting_account_id guard_rail_env = Account.connection.open_transactions == 0 ? :secondary : GuardRail.environment GuardRail.activate(guard_rail_env) do chain.concat(Shard.shard_for(starting_account_id).activate do Account.find_by_sql(<<~SQL) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE id=#{Shard.local_id_for(starting_account_id).first} UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT * FROM t SQL end) end end chain end def self.account_chain_ids(starting_account_id) block = lambda do |_name| Shard.shard_for(starting_account_id).activate do id_chain = [] if (starting_account_id.is_a?(Account)) id_chain << starting_account_id.id starting_account_id = starting_account_id.parent_account_id end if starting_account_id GuardRail.activate(:secondary) do ids = Account.connection.select_values(<<~SQL) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE id=#{Shard.local_id_for(starting_account_id).first} UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t SQL id_chain.concat(ids.map(&:to_i)) end end id_chain end end key = Account.cache_key_for_id(starting_account_id, :account_chain) key ? Rails.cache.fetch(['account_chain_ids', key], &block) : block.call(nil) end def self.multi_account_chain_ids(starting_account_ids) if connection.adapter_name == 'PostgreSQL' original_shard = Shard.current Shard.partition_by_shard(starting_account_ids) do |sliced_acc_ids| ids = Account.connection.select_values(<<~SQL) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE id IN (#{sliced_acc_ids.join(", ")}) UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t SQL ids.map{|id| Shard.relative_id_for(id, Shard.current, original_shard)} end else account_chain(starting_account_id).map(&:id) end end def self.add_site_admin_to_chain!(chain) chain << Account.site_admin unless chain.last.site_admin? chain end def account_chain(include_site_admin: false) @account_chain ||= Account.account_chain(self) result = @account_chain.dup Account.add_site_admin_to_chain!(result) if include_site_admin result end def account_chain_ids @cached_account_chain_ids ||= Account.account_chain_ids(self) end def account_chain_loop # this record hasn't been saved to the db yet, so if the the chain includes # this account, it won't point to the new parent yet, and should still be # valid if self.parent_account.account_chain.include?(self) errors.add(:parent_account_id, "Setting account #{self.sis_source_id || self.id}'s parent to #{self.parent_account.sis_source_id || self.parent_account_id} would create a loop") end end # returns all sub_accounts recursively as far down as they go, in id order # because this uses a custom sql query for postgresql, we can't use a normal # named scope, so we pass the limit and offset into the method instead and # build our own query string def sub_accounts_recursive(limit, offset) if ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'postgresql' Account.find_by_sql([<<~SQL, self.id, limit.to_i, offset.to_i]) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE parent_account_id = ? AND workflow_state <>'deleted' UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.parent_account_id = t.id WHERE accounts.workflow_state <>'deleted' ) SELECT * FROM t ORDER BY parent_account_id, id LIMIT ? OFFSET ? SQL else account_descendents = lambda do |id| as = Account.where(:parent_account_id => id).active.order(:id) as.empty? ? [] : as << as.map { |a| account_descendents.call(a.id) } end account_descendents.call(id).flatten[offset, limit] end end def self.sub_account_ids_recursive(parent_account_id) if connection.adapter_name == 'PostgreSQL' guard_rail_env = Account.connection.open_transactions == 0 ? :secondary : GuardRail.environment GuardRail.activate(guard_rail_env) do sql = Account.sub_account_ids_recursive_sql(parent_account_id) Account.find_by_sql(sql).map(&:id) end else account_descendants = lambda do |ids| as = Account.where(:parent_account_id => ids).active.pluck(:id) as + account_descendants.call(as) end account_descendants.call([parent_account_id]) end end def self.sub_account_ids_recursive_sql(parent_account_id) "WITH RECURSIVE t AS ( SELECT id, parent_account_id FROM #{Account.quoted_table_name} WHERE parent_account_id = #{parent_account_id} AND workflow_state <> 'deleted' UNION SELECT accounts.id, accounts.parent_account_id FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.parent_account_id = t.id WHERE accounts.workflow_state <> 'deleted' ) SELECT id FROM t" end def associated_accounts self.account_chain end def membership_for_user(user) self.account_users.active.where(user_id: user).first if user end def available_custom_account_roles(include_inactive=false) available_custom_roles(include_inactive).for_accounts.to_a end def available_account_roles(include_inactive=false, user = nil) account_roles = available_custom_account_roles(include_inactive) account_roles << Role.get_built_in_role('AccountAdmin', root_account_id: resolved_root_account_id) if user account_roles.select! { |role| au = account_users.new; au.role_id = role.id; au.grants_right?(user, :create) } end account_roles end def available_custom_course_roles(include_inactive=false) available_custom_roles(include_inactive).for_courses.to_a end def available_course_roles(include_inactive=false) course_roles = available_custom_course_roles(include_inactive) course_roles += Role.built_in_course_roles(root_account_id: resolved_root_account_id) course_roles end def available_custom_roles(include_inactive=false) scope = Role.where(:account_id => account_chain_ids) scope = include_inactive ? scope.not_deleted : scope.active scope end def available_roles(include_inactive=false) available_account_roles(include_inactive) + available_course_roles(include_inactive) end def get_account_role_by_name(role_name) role = get_role_by_name(role_name) return role if role && role.account_role? end def get_course_role_by_name(role_name) role = get_role_by_name(role_name) return role if role && role.course_role? end def get_role_by_name(role_name) if (role = Role.get_built_in_role(role_name, root_account_id: self.resolved_root_account_id)) return role end self.shard.activate do role_scope = Role.not_deleted.where(:name => role_name) if self.class.connection.adapter_name == 'PostgreSQL' role_scope = role_scope.where("account_id = ? OR account_id IN ( WITH RECURSIVE t AS ( SELECT id, parent_account_id FROM #{Account.quoted_table_name} WHERE id = ? UNION SELECT accounts.id, accounts.parent_account_id FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t )", self.id, self.id) else role_scope = role_scope.where(:account_id => self.account_chain.map(&:id)) end role_scope.first end end def get_role_by_id(role_id) role = Role.get_role_by_id(role_id) return role if valid_role?(role) end def valid_role?(role) role && (role.built_in? || (self.id == role.account_id) || self.account_chain_ids.include?(role.account_id)) end def login_handle_name_is_customized? self.login_handle_name.present? end def customized_login_handle_name if login_handle_name_is_customized? self.login_handle_name elsif self.delegated_authentication? AuthenticationProvider.default_delegated_login_handle_name end end def login_handle_name_with_inference customized_login_handle_name || AuthenticationProvider.default_login_handle_name end def self_and_all_sub_accounts @self_and_all_sub_accounts ||= Account.where("root_account_id=? OR parent_account_id=?", self, self).pluck(:id).uniq + [self.id] end workflow do state :active state :deleted end def account_users_for(user) if self == Account.site_admin shard.activate do all_site_admin_account_users_hash = MultiCache.fetch("all_site_admin_account_users3") do # this is a plain ruby hash to keep the cached portion as small as possible self.account_users.active.inject({}) { |result, au| result[au.user_id] ||= []; result[au.user_id] << [au.id, au.role_id]; result } end (all_site_admin_account_users_hash[user.id] || []).map do |(id, role_id)| au = AccountUser.new au.id = id au.account = Account.site_admin au.user = user au.role_id = role_id au.readonly! au end end else @account_chain_ids ||= self.account_chain(:include_site_admin => true).map { |a| a.active? ? a.id : nil }.compact Shard.partition_by_shard(@account_chain_ids) do |account_chain_ids| if account_chain_ids == [Account.site_admin.id] Account.site_admin.account_users_for(user) else AccountUser.where(:account_id => account_chain_ids, :user_id => user).active.to_a end end end end def cached_account_users_for(user) return [] unless user @account_users_cache ||= {} @account_users_cache[user.global_id] ||= begin if self.site_admin? account_users_for(user) # has own cache else Rails.cache.fetch_with_batched_keys(['account_users_for_user', user.cache_key(:account_users)].cache_key, batch_object: self, batched_keys: :account_chain, skip_cache_if_disabled: true) do aus = account_users_for(user) aus.each{|au| au.instance_variable_set(:@association_cache, {})} aus end end end end # returns all active account users for this entire account tree def all_account_users_for(user) raise "must be a root account" unless self.root_account? Shard.partition_by_shard(account_chain(include_site_admin: true).uniq) do |accounts| next unless user.associated_shards.include?(Shard.current) AccountUser.active.eager_load(:account).where("user_id=? AND (accounts.root_account_id IN (?) OR account_id IN (?))", user, accounts, accounts) end end def cached_all_account_users_for(user) return [] unless user Rails.cache.fetch_with_batched_keys(['all_account_users_for_user', user.cache_key(:account_users)].cache_key, batch_object: self, batched_keys: :account_chain, skip_cache_if_disabled: true) do all_account_users_for(user) end end set_policy do RoleOverride.permissions.each do |permission, _details| given { |user| self.cached_account_users_for(user).any? { |au| au.has_permission_to?(self, permission) } } can permission can :create_courses if permission == :manage_courses end given { |user| !self.cached_account_users_for(user).empty? } can :read and can :read_as_admin and can :manage and can :update and can :delete and can :read_outcomes and can :read_terms given { |user| self.root_account? && self.cached_all_account_users_for(user).any? } can :read_terms given { |user| result = false if !root_account.site_admin? && user scope = root_account.enrollments.active.where(user_id: user) result = root_account.teachers_can_create_courses? && scope.where(:type => ['TeacherEnrollment', 'DesignerEnrollment']).exists? result ||= root_account.students_can_create_courses? && scope.where(:type => ['StudentEnrollment', 'ObserverEnrollment']).exists? result ||= root_account.no_enrollments_can_create_courses? && !scope.exists? end result } can :create_courses # allow teachers to view term dates given { |user| self.root_account? && !self.site_admin? && self.enrollments.active.of_instructor_type.where(:user_id => user).exists? } can :read_terms # any logged in user can read global outcomes, but must be checked against the site admin given{ |user| self.site_admin? && user } can :read_global_outcomes # any user with an association to this account can read the outcomes in the account given{ |user| user && self.user_account_associations.where(user_id: user).exists? } can :read_outcomes # any user with an admin enrollment in one of the courses can read given { |user| user && self.courses.where(:id => user.enrollments.active.admin.pluck(:course_id)).exists? } can :read given { |user| self.grants_right?(user, :lti_add_edit)} can :create_tool_manually given { |user| !self.site_admin? && self.root_account? && self.grants_right?(user, :manage_site_settings) } can :manage_privacy_settings end alias_method :destroy_permanently!, :destroy def destroy self.transaction do self.account_users.update_all(workflow_state: 'deleted') self.workflow_state = 'deleted' self.deleted_at = Time.now.utc save! end end def to_atom Atom::Entry.new do |entry| entry.title = self.name entry.updated = self.updated_at entry.published = self.created_at entry.links << Atom::Link.new(:rel => 'alternate', :href => "/accounts/#{self.id}") end end def default_enrollment_term return @default_enrollment_term if @default_enrollment_term if self.root_account? @default_enrollment_term = GuardRail.activate(:primary) { self.enrollment_terms.active.where(name: EnrollmentTerm::DEFAULT_TERM_NAME).first_or_create } end end def context_code raise "DONT USE THIS, use .short_name instead" unless Rails.env.production? end def short_name name end # can be set/overridden by plugin to enforce email pseudonyms attr_accessor :email_pseudonyms def password_policy Canvas::PasswordPolicy.default_policy.merge(settings[:password_policy] || {}) end def delegated_authentication? authentication_providers.active.first.is_a?(AuthenticationProvider::Delegated) end def forgot_password_external_url self.change_password_url end def auth_discovery_url=(url) self.settings[:auth_discovery_url] = url end def auth_discovery_url self.settings[:auth_discovery_url] end def login_handle_name=(handle_name) self.settings[:login_handle_name] = handle_name end def login_handle_name self.settings[:login_handle_name] end def change_password_url=(change_password_url) self.settings[:change_password_url] = change_password_url end def change_password_url self.settings[:change_password_url] end def unknown_user_url=(unknown_user_url) self.settings[:unknown_user_url] = unknown_user_url end def unknown_user_url self.settings[:unknown_user_url] end def validate_auth_discovery_url return if self.settings[:auth_discovery_url].blank? begin value, _uri = CanvasHttp.validate_url(self.settings[:auth_discovery_url]) self.auth_discovery_url = value rescue URI::Error, ArgumentError errors.add(:discovery_url, t('errors.invalid_discovery_url', "The discovery URL is not valid" )) end end def validate_help_links links = self.settings[:custom_help_links] return if links.blank? link_errors = HelpLinks.validate_links(links) link_errors.each do |link_error| errors.add(:custom_help_links, link_error) end end def no_active_courses return true if root_account? if associated_courses.not_deleted.exists? errors.add(:workflow_state, "Can't delete an account with active courses.") end end def no_active_sub_accounts return true if root_account? if sub_accounts.exists? errors.add(:workflow_state, "Can't delete an account with active sub_accounts.") end end def find_courses(string) self.all_courses.select{|c| c.name.match(string) } end def find_users(string) self.pseudonyms.map{|p| p.user }.select{|u| u.name.match(string) } end class << self def special_accounts @special_accounts ||= {} end def special_account_ids @special_account_ids ||= {} end def special_account_timed_cache @special_account_timed_cache ||= TimedCache.new(-> { Setting.get('account_special_account_cache_time', 60).to_i.seconds.ago }) do special_accounts.clear end end def special_account_list @special_account_list ||= [] end def clear_special_account_cache!(force = false) special_account_timed_cache.clear(force) end def define_special_account(key, name = nil) name ||= key.to_s.titleize self.special_account_list << key instance_eval <<-RUBY, __FILE__, __LINE__ + 1 def self.#{key}(force_create = false) get_special_account(:#{key}, #{name.inspect}, force_create) end RUBY end def all_special_accounts special_account_list.map { |key| send(key) } end end define_special_account(:default, 'Default Account') # Account.default define_special_account(:site_admin) # Account.site_admin def clear_special_account_cache_if_special if self.shard == Shard.birth && Account.special_account_ids.values.map(&:to_i).include?(self.id) Account.clear_special_account_cache!(true) end end # an opportunity for plugins to load some other stuff up before caching the account def precache end class ::Canvas::AccountCacheError < StandardError; end def self.find_cached(id) default_id = Shard.relative_id_for(id, Shard.current, Shard.default) Shard.default.activate do MultiCache.fetch(account_lookup_cache_key(default_id)) do begin account = Account.find(default_id) rescue ActiveRecord::RecordNotFound => e raise ::Canvas::AccountCacheError, e.message end raise "Account.find_cached should only be used with root accounts" if !account.root_account? && !Rails.env.production? account.precache account end end end def self.get_special_account(special_account_type, default_account_name, force_create = false) Shard.birth.activate do account = special_accounts[special_account_type] unless account special_account_id = special_account_ids[special_account_type] ||= Setting.get("#{special_account_type}_account_id", nil) begin account = special_accounts[special_account_type] = Account.find_cached(special_account_id) if special_account_id rescue ::Canvas::AccountCacheError raise unless Rails.env.test? end end # another process (i.e. selenium spec) may have changed the setting unless account special_account_id = Setting.get("#{special_account_type}_account_id", nil) if special_account_id && special_account_id != special_account_ids[special_account_type] special_account_ids[special_account_type] = special_account_id account = special_accounts[special_account_type] = Account.where(id: special_account_id).first end end if !account && default_account_name && ((!special_account_id && !Rails.env.production?) || force_create) t '#account.default_site_administrator_account_name', 'Site Admin' t '#account.default_account_name', 'Default Account' account = special_accounts[special_account_type] = Account.new(:name => default_account_name) account.save! Setting.set("#{special_account_type}_account_id", account.id) special_account_ids[special_account_type] = account.id end account end end def site_admin? self == Account.site_admin end def display_name self.name end # Updates account associations for all the courses and users associated with this account def update_account_associations self.shard.activate do account_chain_cache = {} all_user_ids = Set.new # make sure to use the non-associated_courses associations # to catch courses that didn't ever have an association created scopes = if root_account? [all_courses, associated_courses. where("root_account_id<>?", self)] else [courses, associated_courses. where("courses.account_id<>?", self)] end # match the "batch" size in Course.update_account_associations scopes.each do |scope| scope.select([:id, :account_id]).find_in_batches(:batch_size => 500) do |courses| all_user_ids.merge Course.update_account_associations(courses, :skip_user_account_associations => true, :account_chain_cache => account_chain_cache) end end # Make sure we have all users with existing account associations. all_user_ids.merge self.user_account_associations.pluck(:user_id) if root_account? all_user_ids.merge self.pseudonyms.active.pluck(:user_id) end # Update the users' associations as well User.update_account_associations(all_user_ids.to_a, :account_chain_cache => account_chain_cache) end end def self.update_all_update_account_associations Account.root_accounts.active.non_shadow.find_in_batches(strategy: :pluck_ids) do |account_batch| account_batch.each(&:update_account_associations) end end def course_count self.courses.active.count end def sub_account_count self.sub_accounts.active.count end def user_count self.user_account_associations.count end def current_sis_batch if (current_sis_batch_id = self.read_attribute(:current_sis_batch_id)) && current_sis_batch_id.present? self.sis_batches.where(id: current_sis_batch_id).first end end def turnitin_settings return @turnitin_settings if defined?(@turnitin_settings) if self.turnitin_account_id.present? && self.turnitin_shared_secret.present? if settings[:enable_turnitin] @turnitin_settings = [self.turnitin_account_id, self.turnitin_shared_secret, self.turnitin_host] end else @turnitin_settings = self.parent_account.try(:turnitin_settings) end end def closest_turnitin_pledge closest_account_value(:turnitin_pledge, t('This assignment submission is my own, original work')) end def closest_turnitin_comments closest_account_value(:turnitin_comments) end def closest_turnitin_originality closest_account_value(:turnitin_originality, 'immediate') end def closest_account_value(value, default = '') account_with_value = account_chain.find { |a| a.send(value.to_sym).present? } account_with_value&.send(value.to_sym) || default end def self_enrollment_allowed?(course) if !settings[:self_enrollment].blank? !!(settings[:self_enrollment] == 'any' || (!course.sis_source_id && settings[:self_enrollment] == 'manually_created')) else !!(parent_account && parent_account.self_enrollment_allowed?(course)) end end def allow_self_enrollment!(setting='any') settings[:self_enrollment] = setting self.save! end TAB_COURSES = 0 TAB_STATISTICS = 1 TAB_PERMISSIONS = 2 TAB_SUB_ACCOUNTS = 3 TAB_TERMS = 4 TAB_AUTHENTICATION = 5 TAB_USERS = 6 TAB_OUTCOMES = 7 TAB_RUBRICS = 8 TAB_SETTINGS = 9 TAB_FACULTY_JOURNAL = 10 TAB_SIS_IMPORT = 11 TAB_GRADING_STANDARDS = 12 TAB_QUESTION_BANKS = 13 TAB_ADMIN_TOOLS = 17 TAB_SEARCH = 18 TAB_BRAND_CONFIGS = 19 TAB_EPORTFOLIO_MODERATION = 20 # site admin tabs TAB_PLUGINS = 14 TAB_JOBS = 15 TAB_DEVELOPER_KEYS = 16 def external_tool_tabs(opts, user) tools = ContextExternalTool.active.find_all_for(self, :account_navigation) .select { |t| t.permission_given?(:account_navigation, user, self) } Lti::ExternalToolTab.new(self, :account_navigation, tools, opts[:language]).tabs end def tabs_available(user=nil, opts={}) manage_settings = user && self.grants_right?(user, :manage_account_settings) if root_account.site_admin? tabs = [] tabs << { :id => TAB_USERS, :label => t("People"), :css_class => 'users', :href => :account_users_path } if user && self.grants_right?(user, :read_roster) tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && self.grants_right?(user, :manage_role_overrides) tabs << { :id => TAB_SUB_ACCOUNTS, :label => t('#account.tab_sub_accounts', "Sub-Accounts"), :css_class => 'sub_accounts', :href => :account_sub_accounts_path } if manage_settings tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if root_account? && manage_settings tabs << { :id => TAB_PLUGINS, :label => t("#account.tab_plugins", "Plugins"), :css_class => "plugins", :href => :plugins_path, :no_args => true } if root_account? && self.grants_right?(user, :manage_site_settings) tabs << { :id => TAB_JOBS, :label => t("#account.tab_jobs", "Jobs"), :css_class => "jobs", :href => :jobs_path, :no_args => true } if root_account? && self.grants_right?(user, :view_jobs) else tabs = [] tabs << { :id => TAB_COURSES, :label => t('#account.tab_courses', "Courses"), :css_class => 'courses', :href => :account_path } if user && self.grants_right?(user, :read_course_list) tabs << { :id => TAB_USERS, :label => t("People"), :css_class => 'users', :href => :account_users_path } if user && self.grants_right?(user, :read_roster) tabs << { :id => TAB_STATISTICS, :label => t('#account.tab_statistics', "Statistics"), :css_class => 'statistics', :href => :statistics_account_path } if user && self.grants_right?(user, :view_statistics) tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && self.grants_right?(user, :manage_role_overrides) if user && self.grants_right?(user, :manage_outcomes) tabs << { :id => TAB_OUTCOMES, :label => t('#account.tab_outcomes', "Outcomes"), :css_class => 'outcomes', :href => :account_outcomes_path } end if self.can_see_rubrics_tab?(user) tabs << { :id => TAB_RUBRICS, :label => t('#account.tab_rubrics', "Rubrics"), :css_class => 'rubrics', :href => :account_rubrics_path } end tabs << { :id => TAB_GRADING_STANDARDS, :label => t('#account.tab_grading_standards', "Grading"), :css_class => 'grading_standards', :href => :account_grading_standards_path } if user && self.grants_right?(user, :manage_grades) tabs << { :id => TAB_QUESTION_BANKS, :label => t('#account.tab_question_banks', "Question Banks"), :css_class => 'question_banks', :href => :account_question_banks_path } if user && self.grants_right?(user, :manage_assignments) tabs << { :id => TAB_SUB_ACCOUNTS, :label => t('#account.tab_sub_accounts', "Sub-Accounts"), :css_class => 'sub_accounts', :href => :account_sub_accounts_path } if manage_settings tabs << { :id => TAB_FACULTY_JOURNAL, :label => t('#account.tab_faculty_journal', "Faculty Journal"), :css_class => 'faculty_journal', :href => :account_user_notes_path} if self.enable_user_notes && user && self.grants_right?(user, :manage_user_notes) tabs << { :id => TAB_TERMS, :label => t('#account.tab_terms', "Terms"), :css_class => 'terms', :href => :account_terms_path } if self.root_account? && manage_settings tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if self.root_account? && manage_settings if self.root_account? && self.allow_sis_import && user && self.grants_any_right?(user, :manage_sis, :import_sis) tabs << { id: TAB_SIS_IMPORT, label: t('#account.tab_sis_import', "SIS Import"), css_class: 'sis_import', href: :account_sis_import_path } end end tabs << { :id => TAB_BRAND_CONFIGS, :label => t('#account.tab_brand_configs', "Themes"), :css_class => 'brand_configs', :href => :account_brand_configs_path } if manage_settings && branding_allowed? if root_account? && self.grants_right?(user, :manage_developer_keys) tabs << { :id => TAB_DEVELOPER_KEYS, :label => t("#account.tab_developer_keys", "Developer Keys"), :css_class => "developer_keys", :href => :account_developer_keys_path, account_id: root_account.id } end tabs += external_tool_tabs(opts, user) tabs += Lti::MessageHandler.lti_apps_tabs(self, [Lti::ResourcePlacement::ACCOUNT_NAVIGATION], opts) tabs << { :id => TAB_ADMIN_TOOLS, :label => t('#account.tab_admin_tools', "Admin Tools"), :css_class => 'admin_tools', :href => :account_admin_tools_path } if can_see_admin_tools_tab?(user) if user && grants_right?(user, :moderate_user_content) tabs << { id: TAB_EPORTFOLIO_MODERATION, label: t("ePortfolio Moderation"), css_class: "eportfolio_moderation", href: :account_eportfolio_moderation_path } end tabs << { :id => TAB_SETTINGS, :label => t('#account.tab_settings', "Settings"), :css_class => 'settings', :href => :account_settings_path } tabs.delete_if{ |t| t[:visibility] == 'admins' } unless self.grants_right?(user, :manage) tabs end def can_see_rubrics_tab?(user) user && self.grants_right?(user, :manage_rubrics) end def can_see_admin_tools_tab?(user) return false if !user || root_account.site_admin? admin_tool_permissions = RoleOverride.manageable_permissions(self).find_all{|p| p[1][:admin_tool]} admin_tool_permissions.any? do |p| self.grants_right?(user, p.first) end end def is_a_context? true end def help_links links = settings[:custom_help_links] # set the type to custom for any existing custom links that don't have a type set # the new ui will set the type ('custom' or 'default') for any new custom links # since we now allow reordering the links, the default links get stored in the settings as well if !links.blank? links.each do |link| if link[:type].blank? link[:type] = 'custom' end end links = help_links_builder.map_default_links(links) end result = if settings[:new_custom_help_links] links || help_links_builder.default_links else help_links_builder.default_links + (links || []) end filtered_result = help_links_builder.filtered_links(result) help_links_builder.instantiate_links(filtered_result) end def help_links_builder @help_links_builder ||= HelpLinks.new(self) end def set_service_availability(service, enable) service = service.to_sym raise "Invalid Service" unless AccountServices.allowable_services[service] allowed_service_names = (self.allowed_services || "").split(",").compact if allowed_service_names.count > 0 && ![ '+', '-' ].include?(allowed_service_names[0][0,1]) # This account has a hard-coded list of services, so handle accordingly allowed_service_names.reject! { |flag| flag.match("^[+-]?#{service}$") } allowed_service_names << service if enable else allowed_service_names.reject! { |flag| flag.match("^[+-]?#{service}$") } if enable # only enable if it is not enabled by default allowed_service_names << "+#{service}" unless AccountServices.default_allowable_services[service] else # only disable if it is not enabled by default allowed_service_names << "-#{service}" if AccountServices.default_allowable_services[service] end end @allowed_services_hash = nil self.allowed_services = allowed_service_names.empty? ? nil : allowed_service_names.join(",") end def enable_service(service) set_service_availability(service, true) end def disable_service(service) set_service_availability(service, false) end def allowed_services_hash return @allowed_services_hash if @allowed_services_hash account_allowed_services = AccountServices.default_allowable_services if self.allowed_services allowed_service_names = self.allowed_services.split(",").compact if allowed_service_names.count > 0 unless [ '+', '-' ].member?(allowed_service_names[0][0,1]) # This account has a hard-coded list of services, so we clear out the defaults account_allowed_services = AccountServices::AllowedServicesHash.new end allowed_service_names.each do |service_switch| if service_switch =~ /\A([+-]?)(.*)\z/ flag = $1 service_name = $2.to_sym if flag == '-' account_allowed_services.delete(service_name) else account_allowed_services[service_name] = AccountServices.allowable_services[service_name] end end end end end @allowed_services_hash = account_allowed_services end # if expose_as is nil, all services exposed in the ui are returned # if it's :service or :setting, then only services set to be exposed as that type are returned def self.services_exposed_to_ui_hash(expose_as = nil, current_user = nil, account = nil) if expose_as AccountServices.allowable_services.reject { |_, setting| setting[:expose_to_ui] != expose_as } else AccountServices.allowable_services.reject { |_, setting| !setting[:expose_to_ui] } end.reject { |_, setting| setting[:expose_to_ui_proc] && !setting[:expose_to_ui_proc].call(current_user, account) } end def service_enabled?(service) service = service.to_sym case service when :none self.allowed_services_hash.empty? else self.allowed_services_hash.has_key?(service) end end def self.all_accounts_for(context) if context.respond_to?(:account) context.account.account_chain elsif context.respond_to?(:parent_account) context.account_chain else [] end end def find_child(child_id) return all_accounts.find(child_id) if root_account? child = Account.find(child_id) raise ActiveRecord::RecordNotFound unless child.account_chain.include?(self) child end def manually_created_courses_account return self.root_account.manually_created_courses_account unless self.root_account? display_name = t('#account.manually_created_courses', "Manually-Created Courses") acct = manually_created_courses_account_from_settings if acct.blank? transaction do lock! acct = manually_created_courses_account_from_settings acct ||= self.sub_accounts.where(name: display_name).first_or_create! # for backwards compatibility if acct.id != self.settings[:manually_created_courses_account_id] self.settings[:manually_created_courses_account_id] = acct.id self.save! end end end acct end def manually_created_courses_account_from_settings acct_id = self.settings[:manually_created_courses_account_id] acct = self.sub_accounts.where(id: acct_id).first if acct_id.present? acct = nil if acct.present? && acct.root_account_id != self.id acct end private :manually_created_courses_account_from_settings def trusted_account_ids return [] if !root_account? || self == Account.site_admin [ Account.site_admin.id ] end def trust_exists? false end def user_list_search_mode_for(user) return :preferred if self.root_account.open_registration? return :preferred if self.root_account.grants_right?(user, :manage_user_logins) :closed end scope :root_accounts, -> { where(:root_account_id => nil).where.not(id: 0) } scope :processing_sis_batch, -> { where("accounts.current_sis_batch_id IS NOT NULL").order(:updated_at) } scope :name_like, lambda { |name| where(wildcard('accounts.name', name)) } scope :active, -> { where("accounts.workflow_state<>'deleted'") } def change_root_account_setting!(setting_name, new_value) root_account.settings[setting_name] = new_value root_account.save! end Bookmarker = BookmarkedCollection::SimpleBookmarker.new(Account, :name, :id) def format_referer(referer_url) begin referer = URI(referer_url || '') rescue URI::Error return end return unless referer.host referer_with_port = "#{referer.scheme}://#{referer.host}" referer_with_port += ":#{referer.port}" unless referer.port == (referer.scheme == 'https' ? 443 : 80) referer_with_port end def trusted_referers=(value) self.settings[:trusted_referers] = unless value.blank? value.split(',').map { |referer_url| format_referer(referer_url) }.compact.join(',') end end def trusted_referer?(referer_url) return if !self.settings.has_key?(:trusted_referers) || self.settings[:trusted_referers].blank? if (referer_with_port = format_referer(referer_url)) self.settings[:trusted_referers].split(',').include?(referer_with_port) end end def parent_registration? authentication_providers.where(parent_registration: true).exists? end def parent_auth_type return nil unless parent_registration? parent_registration_aac.auth_type end def parent_registration_aac authentication_providers.where(parent_registration: true).first end def require_email_for_registration? Canvas::Plugin.value_to_boolean(settings[:require_email_for_registration]) || false end def to_param return 'site_admin' if site_admin? super end def create_default_objects work = -> do default_enrollment_term enable_canvas_authentication TermsOfService.ensure_terms_for_account(self, true) if self.root_account? && !TermsOfService.skip_automatic_terms_creation create_built_in_roles if self.root_account? end return work.call if Rails.env.test? self.class.connection.after_transaction_commit(&work) end def create_built_in_roles self.shard.activate do Role::BASE_TYPES.each do |base_type| role = Role.new role.name = base_type role.base_role_type = base_type role.workflow_state = :built_in role.root_account_id = self.id role.save! end end end def migrate_to_canvadocs? Canvadocs.hijack_crocodoc_sessions? end def update_terms_of_service(terms_params) terms = TermsOfService.ensure_terms_for_account(self) terms.terms_type = terms_params[:terms_type] if terms_params[:terms_type] terms.passive = Canvas::Plugin.value_to_boolean(terms_params[:passive]) if terms_params.has_key?(:passive) if terms.custom? TermsOfServiceContent.ensure_content_for_account(self) self.terms_of_service_content.update_attribute(:content, terms_params[:content]) if terms_params[:content] end if terms.changed? unless terms.save self.errors.add(:terms_of_service, t("Terms of Service attributes not valid")) end end end # Different views are available depending on feature flags def dashboard_views ['activity', 'cards', 'planner'] end # Getter/Setter for default_dashboard_view account setting def default_dashboard_view=(view) return unless dashboard_views.include?(view) self.settings[:default_dashboard_view] = view end def default_dashboard_view @default_dashboard_view ||= self.settings[:default_dashboard_view] end # Forces the default setting to overwrite each user's preference def update_user_dashboards User.where(id: self.user_account_associations.select(:user_id)) .where("#{User.table_name}.preferences LIKE ?", "%:dashboard_view:%") .find_in_batches do |batch| users = batch.reject { |user| user.preferences[:dashboard_view].nil? || user.dashboard_view(self) == default_dashboard_view } users.each do |user| user.preferences.delete(:dashboard_view) user.save! end end end handle_asynchronously :update_user_dashboards, :priority => Delayed::LOW_PRIORITY, :max_attempts => 1 def process_external_integration_keys(params_keys, current_user, keys = ExternalIntegrationKey.indexed_keys_for(self)) return unless params_keys keys.each do |key_type, key| next unless params_keys.key?(key_type) next unless key.grants_right?(current_user, :write) unless params_keys[key_type].blank? key.key_value = params_keys[key_type] key.save! else key.delete end end end def available_course_visibility_override_options(_options=nil) _options || {} end def user_needs_verification?(user) self.require_confirmed_email? && (user.nil? || !user.cached_active_emails.any?) end def allow_disable_post_to_sis_when_grading_period_closed? return false unless root_account? return false unless feature_enabled?(:disable_post_to_sis_when_grading_period_closed) Account.site_admin.feature_enabled?(:new_sis_integrations) end class << self attr_accessor :current_domain_root_account end module DomainRootAccountCache def find_one(id) return Account.current_domain_root_account if Account.current_domain_root_account && Account.current_domain_root_account.shard == shard_value && Account.current_domain_root_account.local_id == id super end def find_take return super unless where_clause.send(:predicates).length == 1 predicates = where_clause.to_h return super unless predicates.length == 1 return super unless predicates.keys.first == "id" return Account.current_domain_root_account if Account.current_domain_root_account && Account.current_domain_root_account.shard == shard_value && Account.current_domain_root_account.local_id == predicates.values.first super end end relation_delegate_class(ActiveRecord::Relation).prepend(DomainRootAccountCache) relation_delegate_class(ActiveRecord::AssociationRelation).prepend(DomainRootAccountCache) def self.ensure_dummy_root_account Account.find_or_create_by!(id: 0) if Rails.env.test? end def roles_with_enabled_permission(permission) roles = available_roles roles.select do |role| RoleOverride.permission_for(self, permission, role, self, true)[:enabled] end end def get_rce_favorite_tool_ids rce_favorite_tool_ids[:value] || ContextExternalTool.all_tools_for(self, placements: [:editor_button]). # TODO remove after datafixup and the is_rce_favorite column is removed where(:is_rce_favorite => true).pluck(:id).map{|id| Shard.global_id_for(id)} end end
class Account include DataMapper::Resource property :id, Serial property :name, String property :opening_balance, Integer, :default => 0 property :gl_code, String property :parent_id, String belongs_to :account, :model => 'Account', :child_key => [:parent_id] belongs_to :account_type has n, :postings is :tree, :order => :name validates_present :name validates_present :gl_code validates_length :name, :minimum => 3 validates_length :gl_code, :minimum => 3 validates_is_unique :gl_code validates_is_number :opening_balance end Added date for opening balance to account class Account include DataMapper::Resource property :id, Serial property :name, String property :opening_balance, Integer, :default => 0 property :opening_balance_on_date, Date, :nullable => false property :gl_code, String property :parent_id, String belongs_to :account, :model => 'Account', :child_key => [:parent_id] belongs_to :account_type has n, :postings is :tree, :order => :name validates_present :name validates_present :gl_code validates_length :name, :minimum => 3 validates_length :gl_code, :minimum => 3 validates_is_unique :gl_code validates_is_number :opening_balance end
# # Copyright (C) 2011 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # require 'atom' class Account < ActiveRecord::Base include Context INSTANCE_GUID_SUFFIX = 'canvas-lms' include Workflow include BrandConfigHelpers belongs_to :parent_account, :class_name => 'Account' belongs_to :root_account, :class_name => 'Account' authenticates_many :pseudonym_sessions has_many :courses has_many :all_courses, :class_name => 'Course', :foreign_key => 'root_account_id' has_many :group_categories, -> { where(deleted_at: nil) }, as: :context, inverse_of: :context has_many :all_group_categories, :class_name => 'GroupCategory', :as => :context, :inverse_of => :context has_many :groups, :as => :context, :inverse_of => :context has_many :all_groups, :class_name => 'Group', :foreign_key => 'root_account_id' has_many :all_group_memberships, source: 'group_memberships', through: :all_groups has_many :enrollment_terms, :foreign_key => 'root_account_id' has_many :active_enrollment_terms, -> { where("enrollment_terms.workflow_state<>'deleted'") }, class_name: 'EnrollmentTerm', foreign_key: 'root_account_id' has_many :grading_period_groups, inverse_of: :root_account, dependent: :destroy has_many :grading_periods, through: :grading_period_groups has_many :enrollments, -> { where("enrollments.type<>'StudentViewEnrollment'") }, foreign_key: 'root_account_id' has_many :all_enrollments, :class_name => 'Enrollment', :foreign_key => 'root_account_id' has_many :sub_accounts, -> { where("workflow_state<>'deleted'") }, class_name: 'Account', foreign_key: 'parent_account_id' has_many :all_accounts, -> { order(:name) }, class_name: 'Account', foreign_key: 'root_account_id' has_many :account_users, :dependent => :destroy has_many :course_sections, :foreign_key => 'root_account_id' has_many :sis_batches has_many :abstract_courses, :class_name => 'AbstractCourse', :foreign_key => 'account_id' has_many :root_abstract_courses, :class_name => 'AbstractCourse', :foreign_key => 'root_account_id' has_many :users, :through => :account_users has_many :pseudonyms, -> { preload(:user) }, inverse_of: :account has_many :role_overrides, :as => :context, :inverse_of => :context has_many :course_account_associations has_many :child_courses, -> { where(course_account_associations: { depth: 0 }) }, through: :course_account_associations, source: :course has_many :attachments, :as => :context, :inverse_of => :context, :dependent => :destroy has_many :active_assignments, -> { where("assignments.workflow_state<>'deleted'") }, as: :context, inverse_of: :context, class_name: 'Assignment' has_many :folders, -> { order('folders.name') }, as: :context, inverse_of: :context, dependent: :destroy has_many :active_folders, -> { where("folder.workflow_state<>'deleted'").order('folders.name') }, class_name: 'Folder', as: :context, inverse_of: :context has_many :developer_keys has_many :authentication_providers, -> { order(:position) }, extend: AccountAuthorizationConfig::FindWithType, class_name: "AccountAuthorizationConfig" has_many :account_reports has_many :grading_standards, -> { where("workflow_state<>'deleted'") }, as: :context, inverse_of: :context has_many :assessment_questions, :through => :assessment_question_banks has_many :assessment_question_banks, -> { preload(:assessment_questions, :assessment_question_bank_users) }, as: :context, inverse_of: :context has_many :roles has_many :all_roles, :class_name => 'Role', :foreign_key => 'root_account_id' has_many :progresses, :as => :context, :inverse_of => :context has_many :content_migrations, :as => :context, :inverse_of => :context def inherited_assessment_question_banks(include_self = false, *additional_contexts) sql = [] conds = [] contexts = additional_contexts + account_chain contexts.delete(self) unless include_self contexts.each { |c| sql << "context_type = ? AND context_id = ?" conds += [c.class.to_s, c.id] } conds.unshift(sql.join(" OR ")) AssessmentQuestionBank.where(conds) end include LearningOutcomeContext include RubricContext has_many :context_external_tools, -> { order(:name) }, as: :context, inverse_of: :context, dependent: :destroy has_many :error_reports has_many :announcements, :class_name => 'AccountNotification' has_many :alerts, -> { preload(:criteria) }, as: :context, inverse_of: :context has_many :user_account_associations has_many :report_snapshots has_many :external_integration_keys, :as => :context, :inverse_of => :context, :dependent => :destroy has_many :shared_brand_configs belongs_to :brand_config, foreign_key: "brand_config_md5" before_validation :verify_unique_sis_source_id before_save :ensure_defaults after_save :update_account_associations_if_changed before_save :setup_cache_invalidation after_save :invalidate_caches_if_changed after_update :clear_special_account_cache_if_special after_create :create_default_objects serialize :settings, Hash include TimeZoneHelper time_zone_attribute :default_time_zone, default: "America/Denver" def default_time_zone if read_attribute(:default_time_zone) || root_account? super else root_account.default_time_zone end end alias_method :time_zone, :default_time_zone validates_locale :default_locale, :allow_nil => true validates_length_of :name, :maximum => maximum_string_length, :allow_blank => true validate :account_chain_loop, :if => :parent_account_id_changed? validate :validate_auth_discovery_url validates_presence_of :workflow_state include StickySisFields are_sis_sticky :name include FeatureFlags def default_locale(recurse = false) result = read_attribute(:default_locale) if recurse result ||= Rails.cache.fetch(['default_locale', self.global_id].cache_key) do parent_account.default_locale(true) if parent_account end end result = nil unless I18n.locale_available?(result) result end include ::Account::Settings # these settings either are or could be easily added to # the account settings page add_setting :sis_app_token, :root_only => true add_setting :sis_app_url, :root_only => true add_setting :sis_name, :root_only => true add_setting :sis_syncing, :boolean => true, :default => false, :inheritable => true add_setting :sis_default_grade_export, :boolean => true, :default => false, :inheritable => true add_setting :sis_require_assignment_due_date, :boolean => true, :default => false, :inheritable => true add_setting :sis_assignment_name_length, :boolean => true, :default => false, :inheritable => true add_setting :sis_assignment_name_length_input, :inheritable => true add_setting :global_includes, :root_only => true, :boolean => true, :default => false add_setting :sub_account_includes, :boolean => true, :default => false # Help link settings add_setting :custom_help_links, :root_only => true add_setting :help_link_icon, :root_only => true add_setting :help_link_name, :root_only => true add_setting :support_url, :root_only => true add_setting :prevent_course_renaming_by_teachers, :boolean => true, :root_only => true add_setting :login_handle_name, root_only: true add_setting :change_password_url, root_only: true add_setting :unknown_user_url, root_only: true add_setting :fft_registration_url, root_only: true add_setting :restrict_student_future_view, :boolean => true, :default => false, :inheritable => true add_setting :restrict_student_future_listing, :boolean => true, :default => false, :inheritable => true add_setting :restrict_student_past_view, :boolean => true, :default => false, :inheritable => true add_setting :teachers_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :students_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :restrict_quiz_questions, :boolean => true, :root_only => true, :default => false add_setting :no_enrollments_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :allow_sending_scores_in_emails, :boolean => true, :root_only => true add_setting :self_enrollment add_setting :equella_endpoint add_setting :equella_teaser add_setting :enable_alerts, :boolean => true, :root_only => true add_setting :enable_eportfolios, :boolean => true, :root_only => true add_setting :users_can_edit_name, :boolean => true, :root_only => true add_setting :open_registration, :boolean => true, :root_only => true add_setting :show_scheduler, :boolean => true, :root_only => true, :default => false add_setting :enable_profiles, :boolean => true, :root_only => true, :default => false add_setting :enable_turnitin, :boolean => true, :default => false add_setting :mfa_settings, :root_only => true add_setting :admins_can_change_passwords, :boolean => true, :root_only => true, :default => false add_setting :admins_can_view_notifications, :boolean => true, :root_only => true, :default => false add_setting :canvadocs_prefer_office_online, :boolean => true, :root_only => true, :default => false add_setting :outgoing_email_default_name add_setting :external_notification_warning, :boolean => true, :default => false # Terms of Use and Privacy Policy settings for the root account add_setting :terms_changed_at, :root_only => true add_setting :account_terms_required, :root_only => true, :boolean => true, :default => true # When a user is invited to a course, do we let them see a preview of the # course even without registering? This is part of the free-for-teacher # account perks, since anyone can invite anyone to join any course, and it'd # be nice to be able to see the course first if you weren't expecting the # invitation. add_setting :allow_invitation_previews, :boolean => true, :root_only => true, :default => false add_setting :large_course_rosters, :boolean => true, :root_only => true, :default => false add_setting :edit_institution_email, :boolean => true, :root_only => true, :default => true add_setting :js_kaltura_uploader, :boolean => true, :root_only => true, :default => false add_setting :google_docs_domain, root_only: true add_setting :dashboard_url, root_only: true add_setting :product_name, root_only: true add_setting :author_email_in_notifications, boolean: true, root_only: true, default: false add_setting :include_students_in_global_survey, boolean: true, root_only: true, default: false add_setting :trusted_referers, root_only: true add_setting :app_center_access_token add_setting :enable_offline_web_export, boolean: true, default: false, inheritable: true add_setting :strict_sis_check, :boolean => true, :root_only => true, :default => false add_setting :lock_all_announcements, default: false, boolean: true, inheritable: true def settings=(hash) if hash.is_a?(Hash) || hash.is_a?(ActionController::Parameters) hash.each do |key, val| if account_settings_options && account_settings_options[key.to_sym] opts = account_settings_options[key.to_sym] if (opts[:root_only] && !self.root_account?) || (opts[:condition] && !self.send("#{opts[:condition]}?".to_sym)) settings.delete key.to_sym elsif opts[:hash] new_hash = {} if val.is_a?(Hash) || val.is_a?(ActionController::Parameters) val.each do |inner_key, inner_val| inner_key = inner_key.to_sym if opts[:values].include?(inner_key) if opts[:inheritable] && (inner_key == :locked || (inner_key == :value && opts[:boolean])) new_hash[inner_key] = Canvas::Plugin.value_to_boolean(inner_val) else new_hash[inner_key] = inner_val.to_s end end end end settings[key.to_sym] = new_hash.empty? ? nil : new_hash elsif opts[:boolean] settings[key.to_sym] = Canvas::Plugin.value_to_boolean(val) else settings[key.to_sym] = val.to_s end end end end # prune nil or "" hash values to save space in the DB. settings.reject! { |_, value| value.nil? || value == "" } settings end def product_name settings[:product_name] || t("#product_name", "Canvas") end def allow_global_includes? if root_account? global_includes? else root_account.try(:sub_account_includes?) && root_account.try(:allow_global_includes?) end end def mfa_settings settings[:mfa_settings].try(:to_sym) || :disabled end def non_canvas_auth_configured? authentication_providers.active.where("auth_type<>'canvas'").exists? end def canvas_authentication_provider @canvas_ap ||= authentication_providers.active.where(auth_type: 'canvas').first end def canvas_authentication? !!canvas_authentication_provider end def enable_canvas_authentication return unless root_account? # for migrations creating a new db return unless AccountAuthorizationConfig::Canvas.columns_hash.key?('workflow_state') return if authentication_providers.active.where(auth_type: 'canvas').exists? authentication_providers.create!(auth_type: 'canvas') end def enable_offline_web_export? enable_offline_web_export[:value] end def open_registration? !!settings[:open_registration] && canvas_authentication? end def self_registration? canvas_authentication_provider.try(:jit_provisioning?) end def self_registration_type canvas_authentication_provider.try(:self_registration) end def self_registration_allowed_for?(type) return false unless self_registration? return false if self_registration_type != 'all' && type != self_registration_type true end def enable_self_registration canvas_authentication_provider.update_attribute(:self_registration, true) end def terms_required? Setting.get('terms_required', 'true') == 'true' && root_account.account_terms_required? end def require_acceptance_of_terms?(user) soc2_start_date = Setting.get('SOC2_start_date', Time.new(2015, 5, 16, 0, 0, 0).utc).to_datetime return false if !terms_required? return true if user.nil? || user.new_record? terms_changed_at = settings[:terms_changed_at] last_accepted = user.preferences[:accepted_terms] # make sure existing users are grandfathered in return false if terms_changed_at.nil? && user.registered? && user.created_at < soc2_start_date return false if last_accepted && (terms_changed_at.nil? || last_accepted > terms_changed_at) true end def ip_filters=(params) filters = {} require 'ipaddr' params.each do |key, str| ips = [] vals = str.split(/,/) vals.each do |val| ip = IPAddr.new(val) rescue nil # right now the ip_filter column on quizzes is just a string, # so it has a max length. I figure whatever we set it to this # setter should at the very least limit stored values to that # length. ips << val if ip && val.length <= 255 end filters[key] = ips.join(',') unless ips.empty? end settings[:ip_filters] = filters end def ensure_defaults self.uuid ||= CanvasSlug.generate_securish_uuid self.lti_guid ||= "#{self.uuid}:#{INSTANCE_GUID_SUFFIX}" if self.respond_to?(:lti_guid) self.root_account_id ||= self.parent_account.root_account_id if self.parent_account self.root_account_id ||= self.parent_account_id self.parent_account_id ||= self.root_account_id Account.invalidate_cache(self.id) if self.id true end def verify_unique_sis_source_id return true unless self.sis_source_id return true if !root_account_id_changed? && !sis_source_id_changed? if self.root_account? self.errors.add(:sis_source_id, t('#account.root_account_cant_have_sis_id', "SIS IDs cannot be set on root accounts")) throw :abort unless CANVAS_RAILS4_2 return false end scope = root_account.all_accounts.where(sis_source_id: self.sis_source_id) scope = scope.where("id<>?", self) unless self.new_record? return true unless scope.exists? self.errors.add(:sis_source_id, t('#account.sis_id_in_use', "SIS ID \"%{sis_id}\" is already in use", :sis_id => self.sis_source_id)) throw :abort unless CANVAS_RAILS4_2 false end def update_account_associations_if_changed send_later_if_production(:update_account_associations) if self.parent_account_id_changed? || self.root_account_id_changed? end def equella_settings endpoint = self.settings[:equella_endpoint] || self.equella_endpoint if !endpoint.blank? OpenObject.new({ :endpoint => endpoint, :default_action => self.settings[:equella_action] || 'selectOrAdd', :teaser => self.settings[:equella_teaser] }) else nil end end def settings result = self.read_attribute(:settings) if result @old_settings ||= result.dup return result end return write_attribute(:settings, {}) unless frozen? {}.freeze end def domain HostUrl.context_host(self) end def self.find_by_domain(domain) self.default if HostUrl.default_host == domain end def root_account? !self.root_account_id end def root_account return self if root_account? super end def sub_accounts_as_options(indent = 0, preloaded_accounts = nil) unless preloaded_accounts preloaded_accounts = {} self.root_account.all_accounts.active.each do |account| (preloaded_accounts[account.parent_account_id] ||= []) << account end end res = [[("&nbsp;&nbsp;" * indent).html_safe + self.name, self.id]] if preloaded_accounts[self.id] preloaded_accounts[self.id].each do |account| res += account.sub_accounts_as_options(indent + 1, preloaded_accounts) end end res end def users_visible_to(user) self.grants_right?(user, :read) ? self.all_users : self.all_users.none end def users_name_like(query="") @cached_users_name_like ||= {} @cached_users_name_like[query] ||= self.fast_all_users.name_like(query) end def associated_courses if root_account? all_courses else shard.activate do Course.where("EXISTS (?)", CourseAccountAssociation.where(account_id: self).where("course_id=courses.id")) end end end def associated_user?(user) user_account_associations.where(user_id: user).exists? end def fast_course_base(opts = {}) opts[:order] ||= "#{Course.best_unicode_collation_key("courses.name")} ASC" columns = "courses.id, courses.name, courses.workflow_state, courses.course_code, courses.sis_source_id, courses.enrollment_term_id" associated_courses = self.associated_courses.active.order(opts[:order]) associated_courses = associated_courses.with_enrollments if opts[:hide_enrollmentless_courses] associated_courses = associated_courses.master_courses if opts[:only_master_courses] associated_courses = associated_courses.for_term(opts[:term]) if opts[:term].present? associated_courses = yield associated_courses if block_given? associated_courses.limit(opts[:limit]).active_first.select(columns).to_a end def fast_all_courses(opts={}) @cached_fast_all_courses ||= {} @cached_fast_all_courses[opts] ||= self.fast_course_base(opts) end def all_users(limit=250) @cached_all_users ||= {} @cached_all_users[limit] ||= User.of_account(self).limit(limit) end def fast_all_users(limit=nil) @cached_fast_all_users ||= {} @cached_fast_all_users[limit] ||= self.all_users(limit).active.select("users.id, users.updated_at, users.name, users.sortable_name").order_by_sortable_name end def users_not_in_groups(groups, opts={}) scope = User.active.joins(:user_account_associations). where(user_account_associations: {account_id: self}). where(Group.not_in_group_sql_fragment(groups.map(&:id))). select("users.id, users.name") scope = scope.select(opts[:order]).order(opts[:order]) if opts[:order] scope end def courses_name_like(query="", opts={}) opts[:limit] ||= 200 @cached_courses_name_like ||= {} @cached_courses_name_like[[query, opts]] ||= self.fast_course_base(opts) {|q| q.name_like(query)} end def self_enrollment_course_for(code) all_courses. where(:self_enrollment_code => code). first end def file_namespace Shard.birth.activate { "account_#{self.root_account.id}" } end def self.account_lookup_cache_key(id) ['_account_lookup4', id].cache_key end def self.invalidate_cache(id) return unless id birth_id = Shard.relative_id_for(id, Shard.current, Shard.birth) Shard.birth.activate do Rails.cache.delete(account_lookup_cache_key(birth_id)) if birth_id end rescue nil end def setup_cache_invalidation @invalidations = [] unless self.new_record? invalidate_all = self.parent_account_id_changed? # apparently, the try_rescues are because these columns don't exist on old migrations @invalidations += ['default_storage_quota', 'current_quota'] if invalidate_all || self.try_rescue(:default_storage_quota_changed?) @invalidations << 'default_group_storage_quota' if invalidate_all || self.try_rescue(:default_group_storage_quota_changed?) @invalidations << 'default_locale' if invalidate_all || self.try_rescue(:default_locale_changed?) end end def invalidate_caches_if_changed @invalidations ||= [] if self.parent_account_id_changed? @invalidations += Account.inheritable_settings # invalidate all of them elsif @old_settings Account.inheritable_settings.each do |key| @invalidations << key if @old_settings[key] != settings[key] # only invalidate if needed end @old_settings = nil end if @invalidations.present? shard.activate do @invalidations.each do |key| Rails.cache.delete([key, self.global_id].cache_key) end Account.send_later_if_production(:invalidate_inherited_caches, self, @invalidations) end end end def self.invalidate_inherited_caches(parent_account, keys) parent_account.shard.activate do account_ids = Account.sub_account_ids_recursive(parent_account.id) account_ids.each do |id| global_id = Shard.global_id_for(id) keys.each do |key| Rails.cache.delete([key, global_id].cache_key) end end access_keys = keys & [:restrict_student_future_view, :restrict_student_past_view] if access_keys.any? EnrollmentState.invalidate_access_for_accounts([parent_account.id] + account_ids, access_keys) end end end def self.default_storage_quota Setting.get('account_default_quota', 500.megabytes.to_s).to_i end def quota return storage_quota if read_attribute(:storage_quote) return self.class.default_storage_quota if root_account? shard.activate do Rails.cache.fetch(['current_quota', self.global_id].cache_key) do self.parent_account.default_storage_quota end end end def default_storage_quota return super if read_attribute(:default_storage_quota) return self.class.default_storage_quota if root_account? shard.activate do @default_storage_quota ||= Rails.cache.fetch(['default_storage_quota', self.global_id].cache_key) do parent_account.default_storage_quota end end end def default_storage_quota_mb default_storage_quota / 1.megabyte end def default_storage_quota_mb=(val) self.default_storage_quota = val.try(:to_i).try(:megabytes) end def default_storage_quota=(val) val = val.to_f val = nil if val <= 0 # If the value is the same as the inherited value, then go # ahead and blank it so it keeps using the inherited value if parent_account && parent_account.default_storage_quota == val val = nil end write_attribute(:default_storage_quota, val) end def default_user_storage_quota read_attribute(:default_user_storage_quota) || User.default_storage_quota end def default_user_storage_quota=(val) val = val.to_i val = nil if val == User.default_storage_quota || val <= 0 write_attribute(:default_user_storage_quota, val) end def default_user_storage_quota_mb default_user_storage_quota / 1.megabyte end def default_user_storage_quota_mb=(val) self.default_user_storage_quota = val.try(:to_i).try(:megabytes) end def default_group_storage_quota return super if read_attribute(:default_group_storage_quota) return Group.default_storage_quota if root_account? shard.activate do Rails.cache.fetch(['default_group_storage_quota', self.global_id].cache_key) do self.parent_account.default_group_storage_quota end end end def default_group_storage_quota=(val) val = val.to_i if (val == Group.default_storage_quota) || (val <= 0) || (self.parent_account && self.parent_account.default_group_storage_quota == val) val = nil end write_attribute(:default_group_storage_quota, val) end def default_group_storage_quota_mb default_group_storage_quota / 1.megabyte end def default_group_storage_quota_mb=(val) self.default_group_storage_quota = val.try(:to_i).try(:megabytes) end def turnitin_shared_secret=(secret) return if secret.blank? self.turnitin_crypted_secret, self.turnitin_salt = Canvas::Security.encrypt_password(secret, 'instructure_turnitin_secret_shared') end def turnitin_shared_secret return nil unless self.turnitin_salt && self.turnitin_crypted_secret Canvas::Security.decrypt_password(self.turnitin_crypted_secret, self.turnitin_salt, 'instructure_turnitin_secret_shared') end def self.account_chain(starting_account_id) chain = [] if (starting_account_id.is_a?(Account)) chain << starting_account_id starting_account_id = starting_account_id.parent_account_id end if starting_account_id if ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'postgresql' chain.concat(Shard.shard_for(starting_account_id).activate do Account.find_by_sql(<<-SQL) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE id=#{Shard.local_id_for(starting_account_id).first} UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT * FROM t SQL end) else account = Account.find(starting_account_id) chain << account while account.parent_account account = account.parent_account chain << account end end end chain end def self.account_chain_ids(starting_account_id) if connection.adapter_name == 'PostgreSQL' Shard.shard_for(starting_account_id).activate do id_chain = [] if (starting_account_id.is_a?(Account)) id_chain << starting_account_id.id starting_account_id = starting_account_id.parent_account_id end if starting_account_id ids = Account.connection.select_values(<<-SQL) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE id=#{Shard.local_id_for(starting_account_id).first} UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t SQL id_chain.concat(ids.map(&:to_i)) end id_chain end else account_chain(starting_account_id).map(&:id) end end def self.add_site_admin_to_chain!(chain) chain << Account.site_admin unless chain.last.site_admin? chain end def account_chain(include_site_admin: false) @account_chain ||= Account.account_chain(self) result = @account_chain.dup Account.add_site_admin_to_chain!(result) if include_site_admin result end def account_chain_ids @cached_account_chain_ids ||= Account.account_chain_ids(self) end def account_chain_loop # this record hasn't been saved to the db yet, so if the the chain includes # this account, it won't point to the new parent yet, and should still be # valid if self.parent_account.account_chain.include?(self) errors.add(:parent_account_id, "Setting account #{self.sis_source_id || self.id}'s parent to #{self.parent_account.sis_source_id || self.parent_account_id} would create a loop") end end # returns all sub_accounts recursively as far down as they go, in id order # because this uses a custom sql query for postgresql, we can't use a normal # named scope, so we pass the limit and offset into the method instead and # build our own query string def sub_accounts_recursive(limit, offset) if ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'postgresql' Account.find_by_sql([<<-SQL, self.id, limit.to_i, offset.to_i]) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE parent_account_id = ? AND workflow_state <>'deleted' UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.parent_account_id = t.id WHERE accounts.workflow_state <>'deleted' ) SELECT * FROM t ORDER BY parent_account_id, id LIMIT ? OFFSET ? SQL else account_descendents = lambda do |id| as = Account.where(:parent_account_id => id).active.order(:id) as.empty? ? [] : as << as.map { |a| account_descendents.call(a.id) } end account_descendents.call(id).flatten[offset, limit] end end def self.sub_account_ids_recursive(parent_account_id) if connection.adapter_name == 'PostgreSQL' sql = Account.sub_account_ids_recursive_sql(parent_account_id) Account.find_by_sql(sql).map(&:id) else account_descendants = lambda do |ids| as = Account.where(:parent_account_id => ids).active.pluck(:id) as + account_descendants.call(as) end account_descendants.call([parent_account_id]) end end def self.sub_account_ids_recursive_sql(parent_account_id) "WITH RECURSIVE t AS ( SELECT id, parent_account_id FROM #{Account.quoted_table_name} WHERE parent_account_id = #{parent_account_id} AND workflow_state <> 'deleted' UNION SELECT accounts.id, accounts.parent_account_id FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.parent_account_id = t.id WHERE accounts.workflow_state <> 'deleted' ) SELECT id FROM t" end def associated_accounts self.account_chain end def membership_for_user(user) self.account_users.where(user_id: user).first if user end def available_custom_account_roles(include_inactive=false) available_custom_roles(include_inactive).for_accounts.to_a end def available_account_roles(include_inactive=false, user = nil) account_roles = available_custom_account_roles(include_inactive) account_roles << Role.get_built_in_role('AccountAdmin') if user account_roles.select! { |role| au = account_users.new; au.role_id = role.id; au.grants_right?(user, :create) } end account_roles end def available_custom_course_roles(include_inactive=false) available_custom_roles(include_inactive).for_courses.to_a end def available_course_roles(include_inactive=false) course_roles = available_custom_course_roles(include_inactive) course_roles += Role.built_in_course_roles course_roles end def available_custom_roles(include_inactive=false) scope = Role.where(:account_id => account_chain_ids) scope = include_inactive ? scope.not_deleted : scope.active scope end def available_roles(include_inactive=false) available_account_roles(include_inactive) + available_course_roles(include_inactive) end def get_account_role_by_name(role_name) role = get_role_by_name(role_name) return role if role && role.account_role? end def get_course_role_by_name(role_name) role = get_role_by_name(role_name) return role if role && role.course_role? end def get_role_by_name(role_name) if role = Role.get_built_in_role(role_name) return role end self.shard.activate do role_scope = Role.not_deleted.where(:name => role_name) if self.class.connection.adapter_name == 'PostgreSQL' role_scope = role_scope.where("account_id = ? OR account_id IN ( WITH RECURSIVE t AS ( SELECT id, parent_account_id FROM #{Account.quoted_table_name} WHERE id = ? UNION SELECT accounts.id, accounts.parent_account_id FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t )", self.id, self.id) else role_scope = role_scope.where(:account_id => self.account_chain.map(&:id)) end role_scope.first end end def get_role_by_id(role_id) role = Role.get_role_by_id(role_id) return role if valid_role?(role) end def valid_role?(role) role && (role.built_in? || (self.id == role.account_id) || self.account_chain_ids.include?(role.account_id)) end def login_handle_name_is_customized? self.login_handle_name.present? end def login_handle_name_with_inference if login_handle_name_is_customized? self.login_handle_name elsif self.delegated_authentication? AccountAuthorizationConfig.default_delegated_login_handle_name else AccountAuthorizationConfig.default_login_handle_name end end def self_and_all_sub_accounts @self_and_all_sub_accounts ||= Account.where("root_account_id=? OR parent_account_id=?", self, self).pluck(:id).uniq + [self.id] end workflow do state :active state :deleted end def account_users_for(user) return [] unless user @account_users_cache ||= {} if self == Account.site_admin shard.activate do @account_users_cache[user.global_id] ||= begin all_site_admin_account_users_hash = MultiCache.fetch("all_site_admin_account_users3") do # this is a plain ruby hash to keep the cached portion as small as possible self.account_users.inject({}) { |result, au| result[au.user_id] ||= []; result[au.user_id] << [au.id, au.role_id]; result } end (all_site_admin_account_users_hash[user.id] || []).map do |(id, role_id)| au = AccountUser.new au.id = id au.account = Account.site_admin au.user = user au.role_id = role_id au.readonly! au end end end else @account_chain_ids ||= self.account_chain(:include_site_admin => true).map { |a| a.active? ? a.id : nil }.compact @account_users_cache[user.global_id] ||= Shard.partition_by_shard(@account_chain_ids) do |account_chain_ids| if account_chain_ids == [Account.site_admin.id] Account.site_admin.account_users_for(user) else AccountUser.where(:account_id => account_chain_ids, :user_id => user).to_a end end end @account_users_cache[user.global_id] ||= [] @account_users_cache[user.global_id] end # returns all account users for this entire account tree def all_account_users_for(user) raise "must be a root account" unless self.root_account? Shard.partition_by_shard(account_chain(include_site_admin: true).uniq) do |accounts| next unless user.associated_shards.include?(Shard.current) AccountUser.eager_load(:account).where("user_id=? AND (root_account_id IN (?) OR account_id IN (?))", user, accounts, accounts) end end set_policy do enrollment_types = RoleOverride.enrollment_type_labels.map { |role| role[:name] } RoleOverride.permissions.each do |permission, details| given { |user| self.account_users_for(user).any? { |au| au.has_permission_to?(self, permission) } } can permission can :create_courses if permission == :manage_courses end given { |user| !self.account_users_for(user).empty? } can :read and can :read_as_admin and can :manage and can :update and can :delete and can :read_outcomes given { |user| result = false if !root_account.site_admin? && user scope = root_account.enrollments.active.where(user_id: user) result = root_account.teachers_can_create_courses? && scope.where(:type => ['TeacherEnrollment', 'DesignerEnrollment']).exists? result ||= root_account.students_can_create_courses? && scope.where(:type => ['StudentEnrollment', 'ObserverEnrollment']).exists? result ||= root_account.no_enrollments_can_create_courses? && !scope.exists? end result } can :create_courses # any logged in user can read global outcomes, but must be checked against the site admin given{ |user| self.site_admin? && user } can :read_global_outcomes # any user with an association to this account can read the outcomes in the account given{ |user| user && self.user_account_associations.where(user_id: user).exists? } can :read_outcomes # any user with an admin enrollment in one of the courses can read given { |user| user && self.courses.where(:id => user.enrollments.admin.pluck(:course_id)).exists? } can :read given { |user| self.grants_right?(user, :lti_add_edit)} can :create_tool_manually end alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' self.deleted_at = Time.now.utc save! end def to_atom Atom::Entry.new do |entry| entry.title = self.name entry.updated = self.updated_at entry.published = self.created_at entry.links << Atom::Link.new(:rel => 'alternate', :href => "/accounts/#{self.id}") end end def default_enrollment_term return @default_enrollment_term if @default_enrollment_term if self.root_account? @default_enrollment_term = Shackles.activate(:master) { self.enrollment_terms.active.where(name: EnrollmentTerm::DEFAULT_TERM_NAME).first_or_create } end end def context_code raise "DONT USE THIS, use .short_name instead" unless Rails.env.production? end def short_name name end # can be set/overridden by plugin to enforce email pseudonyms attr_accessor :email_pseudonyms def password_policy Canvas::PasswordPolicy.default_policy.merge(settings[:password_policy] || {}) end def delegated_authentication? authentication_providers.active.first.is_a?(AccountAuthorizationConfig::Delegated) end def forgot_password_external_url self.change_password_url end def auth_discovery_url=(url) self.settings[:auth_discovery_url] = url end def auth_discovery_url self.settings[:auth_discovery_url] end def login_handle_name=(handle_name) self.settings[:login_handle_name] = handle_name end def login_handle_name self.settings[:login_handle_name] end def change_password_url=(change_password_url) self.settings[:change_password_url] = change_password_url end def change_password_url self.settings[:change_password_url] end def unknown_user_url=(unknown_user_url) self.settings[:unknown_user_url] = unknown_user_url end def unknown_user_url self.settings[:unknown_user_url] end def validate_auth_discovery_url return if self.settings[:auth_discovery_url].blank? begin value, uri = CanvasHttp.validate_url(self.settings[:auth_discovery_url]) self.auth_discovery_url = value rescue URI::Error, ArgumentError errors.add(:discovery_url, t('errors.invalid_discovery_url', "The discovery URL is not valid" )) end end def find_courses(string) self.all_courses.select{|c| c.name.match(string) } end def find_users(string) self.pseudonyms.map{|p| p.user }.select{|u| u.name.match(string) } end class << self def special_accounts @special_accounts ||= {} end def special_account_ids @special_account_ids ||= {} end def special_account_timed_cache @special_account_timed_cache ||= TimedCache.new(-> { Setting.get('account_special_account_cache_time', 60).to_i.seconds.ago }) do special_accounts.clear end end def special_account_list @special_account_list ||= [] end def clear_special_account_cache!(force = false) special_account_timed_cache.clear(force) end def define_special_account(key, name = nil) name ||= key.to_s.titleize self.special_account_list << key instance_eval <<-RUBY, __FILE__, __LINE__ + 1 def self.#{key}(force_create = false) get_special_account(:#{key}, #{name.inspect}, force_create) end RUBY end def all_special_accounts special_account_list.map { |key| send(key) } end end define_special_account(:default, 'Default Account') # Account.default define_special_account(:site_admin) # Account.site_admin def clear_special_account_cache_if_special if self.shard == Shard.birth && Account.special_account_ids.values.map(&:to_i).include?(self.id) Account.clear_special_account_cache!(true) end end # an opportunity for plugins to load some other stuff up before caching the account def precache end class ::Canvas::AccountCacheError < StandardError; end def self.find_cached(id) birth_id = Shard.relative_id_for(id, Shard.current, Shard.birth) Shard.birth.activate do Rails.cache.fetch(account_lookup_cache_key(birth_id)) do begin account = Account.find(birth_id) rescue ActiveRecord::RecordNotFound => e raise ::Canvas::AccountCacheError, e.message end account.precache account end end end def self.get_special_account(special_account_type, default_account_name, force_create = false) Shard.birth.activate do account = special_accounts[special_account_type] unless account special_account_id = special_account_ids[special_account_type] ||= Setting.get("#{special_account_type}_account_id", nil) begin account = special_accounts[special_account_type] = Account.find_cached(special_account_id) if special_account_id rescue ::Canvas::AccountCacheError raise unless Rails.env.test? end end # another process (i.e. selenium spec) may have changed the setting unless account special_account_id = Setting.get("#{special_account_type}_account_id", nil) if special_account_id && special_account_id != special_account_ids[special_account_type] special_account_ids[special_account_type] = special_account_id account = special_accounts[special_account_type] = Account.where(id: special_account_id).first end end if !account && default_account_name && ((!special_account_id && !Rails.env.production?) || force_create) t '#account.default_site_administrator_account_name', 'Site Admin' t '#account.default_account_name', 'Default Account' account = special_accounts[special_account_type] = Account.new(:name => default_account_name) account.save! Setting.set("#{special_account_type}_account_id", account.id) special_account_ids[special_account_type] = account.id end account end end def site_admin? self == Account.site_admin end def display_name self.name end # Updates account associations for all the courses and users associated with this account def update_account_associations self.shard.activate do account_chain_cache = {} all_user_ids = Set.new # make sure to use the non-associated_courses associations # to catch courses that didn't ever have an association created scopes = if root_account? [all_courses, associated_courses. where("root_account_id<>?", self)] else [courses, associated_courses. where("courses.account_id<>?", self)] end # match the "batch" size in Course.update_account_associations scopes.each do |scope| scope.select([:id, :account_id]).find_in_batches(:batch_size => 500) do |courses| all_user_ids.merge Course.update_account_associations(courses, :skip_user_account_associations => true, :account_chain_cache => account_chain_cache) end end # Make sure we have all users with existing account associations. all_user_ids.merge self.user_account_associations.pluck(:user_id) if root_account? all_user_ids.merge self.pseudonyms.active.pluck(:user_id) end # Update the users' associations as well User.update_account_associations(all_user_ids.to_a, :account_chain_cache => account_chain_cache) end end def self.update_all_update_account_associations Account.root_accounts.active.find_each(&:update_account_associations) end def course_count self.courses.active.count end def sub_account_count self.sub_accounts.active.count end def user_count self.user_account_associations.count end def current_sis_batch if (current_sis_batch_id = self.read_attribute(:current_sis_batch_id)) && current_sis_batch_id.present? self.sis_batches.where(id: current_sis_batch_id).first end end def turnitin_settings return @turnitin_settings if defined?(@turnitin_settings) if self.turnitin_account_id.present? && self.turnitin_shared_secret.present? if settings[:enable_turnitin] @turnitin_settings = [self.turnitin_account_id, self.turnitin_shared_secret, self.turnitin_host] end else @turnitin_settings = self.parent_account.try(:turnitin_settings) end end def closest_turnitin_pledge if self.turnitin_pledge && !self.turnitin_pledge.empty? self.turnitin_pledge else res = self.parent_account.try(:closest_turnitin_pledge) res ||= t('#account.turnitin_pledge', "This assignment submission is my own, original work") end end def closest_turnitin_comments if self.turnitin_comments && !self.turnitin_comments.empty? self.turnitin_comments else self.parent_account.try(:closest_turnitin_comments) end end def closest_turnitin_originality if self.turnitin_originality && !self.turnitin_originality.empty? self.turnitin_originality else self.parent_account.try(:turnitin_originality) end end def self_enrollment_allowed?(course) if !settings[:self_enrollment].blank? !!(settings[:self_enrollment] == 'any' || (!course.sis_source_id && settings[:self_enrollment] == 'manually_created')) else !!(parent_account && parent_account.self_enrollment_allowed?(course)) end end def allow_self_enrollment!(setting='any') settings[:self_enrollment] = setting self.save! end TAB_COURSES = 0 TAB_STATISTICS = 1 TAB_PERMISSIONS = 2 TAB_SUB_ACCOUNTS = 3 TAB_TERMS = 4 TAB_AUTHENTICATION = 5 TAB_USERS = 6 TAB_OUTCOMES = 7 TAB_RUBRICS = 8 TAB_SETTINGS = 9 TAB_FACULTY_JOURNAL = 10 TAB_SIS_IMPORT = 11 TAB_GRADING_STANDARDS = 12 TAB_QUESTION_BANKS = 13 TAB_ADMIN_TOOLS = 17 TAB_SEARCH = 18 TAB_BRAND_CONFIGS = 19 # site admin tabs TAB_PLUGINS = 14 TAB_JOBS = 15 TAB_DEVELOPER_KEYS = 16 def external_tool_tabs(opts) tools = ContextExternalTool.active.find_all_for(self, :account_navigation) Lti::ExternalToolTab.new(self, :account_navigation, tools, opts[:language]).tabs end def tabs_available(user=nil, opts={}) manage_settings = user && self.grants_right?(user, :manage_account_settings) if root_account.site_admin? tabs = [] if user && self.grants_right?(user, :read_roster) if feature_enabled?(:course_user_search) tabs << { :id => TAB_SEARCH, :label => t("Search"), :css_class => 'search', :href => :account_course_user_search_path } else tabs << { :id => TAB_USERS, :label => t('#account.tab_users', "Users"), :css_class => 'users', :href => :account_users_path } end end tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && self.grants_right?(user, :manage_role_overrides) tabs << { :id => TAB_SUB_ACCOUNTS, :label => t('#account.tab_sub_accounts', "Sub-Accounts"), :css_class => 'sub_accounts', :href => :account_sub_accounts_path } if manage_settings tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if root_account? && manage_settings tabs << { :id => TAB_PLUGINS, :label => t("#account.tab_plugins", "Plugins"), :css_class => "plugins", :href => :plugins_path, :no_args => true } if root_account? && self.grants_right?(user, :manage_site_settings) tabs << { :id => TAB_JOBS, :label => t("#account.tab_jobs", "Jobs"), :css_class => "jobs", :href => :jobs_path, :no_args => true } if root_account? && self.grants_right?(user, :view_jobs) else tabs = [] if feature_enabled?(:course_user_search) tabs << { :id => TAB_SEARCH, :label => t("Search"), :css_class => 'search', :href => :account_path } if user && (grants_right?(user, :read_course_list) || grants_right?(user, :read_roster)) else tabs << { :id => TAB_COURSES, :label => t('#account.tab_courses', "Courses"), :css_class => 'courses', :href => :account_path } if user && self.grants_right?(user, :read_course_list) tabs << { :id => TAB_USERS, :label => t('#account.tab_users', "Users"), :css_class => 'users', :href => :account_users_path } if user && self.grants_right?(user, :read_roster) end tabs << { :id => TAB_STATISTICS, :label => t('#account.tab_statistics', "Statistics"), :css_class => 'statistics', :href => :statistics_account_path } if user && self.grants_right?(user, :view_statistics) tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && self.grants_right?(user, :manage_role_overrides) if user && self.grants_right?(user, :manage_outcomes) tabs << { :id => TAB_OUTCOMES, :label => t('#account.tab_outcomes', "Outcomes"), :css_class => 'outcomes', :href => :account_outcomes_path } tabs << { :id => TAB_RUBRICS, :label => t('#account.tab_rubrics', "Rubrics"), :css_class => 'rubrics', :href => :account_rubrics_path } end tabs << { :id => TAB_GRADING_STANDARDS, :label => t('#account.tab_grading_standards', "Grading"), :css_class => 'grading_standards', :href => :account_grading_standards_path } if user && self.grants_right?(user, :manage_grades) tabs << { :id => TAB_QUESTION_BANKS, :label => t('#account.tab_question_banks', "Question Banks"), :css_class => 'question_banks', :href => :account_question_banks_path } if user && self.grants_right?(user, :manage_assignments) tabs << { :id => TAB_SUB_ACCOUNTS, :label => t('#account.tab_sub_accounts', "Sub-Accounts"), :css_class => 'sub_accounts', :href => :account_sub_accounts_path } if manage_settings tabs << { :id => TAB_FACULTY_JOURNAL, :label => t('#account.tab_faculty_journal', "Faculty Journal"), :css_class => 'faculty_journal', :href => :account_user_notes_path} if self.enable_user_notes && user && self.grants_right?(user, :manage_user_notes) tabs << { :id => TAB_TERMS, :label => t('#account.tab_terms', "Terms"), :css_class => 'terms', :href => :account_terms_path } if self.root_account? && manage_settings tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if self.root_account? && manage_settings if self.root_account? && self.allow_sis_import && user && self.grants_any_right?(user, :manage_sis, :import_sis) tabs << { id: TAB_SIS_IMPORT, label: t('#account.tab_sis_import', "SIS Import"), css_class: 'sis_import', href: :account_sis_import_path } end end tabs << { :id => TAB_BRAND_CONFIGS, :label => t('#account.tab_brand_configs', "Themes"), :css_class => 'brand_configs', :href => :account_brand_configs_path } if manage_settings && branding_allowed? tabs << { :id => TAB_DEVELOPER_KEYS, :label => t("#account.tab_developer_keys", "Developer Keys"), :css_class => "developer_keys", :href => :account_developer_keys_path, account_id: root_account.id } if root_account? && self.grants_right?(user, :manage_developer_keys) tabs += external_tool_tabs(opts) tabs += Lti::MessageHandler.lti_apps_tabs(self, [Lti::ResourcePlacement::ACCOUNT_NAVIGATION], opts) tabs << { :id => TAB_ADMIN_TOOLS, :label => t('#account.tab_admin_tools', "Admin Tools"), :css_class => 'admin_tools', :href => :account_admin_tools_path } if can_see_admin_tools_tab?(user) tabs << { :id => TAB_SETTINGS, :label => t('#account.tab_settings', "Settings"), :css_class => 'settings', :href => :account_settings_path } tabs.delete_if{ |t| t[:visibility] == 'admins' } unless self.grants_right?(user, :manage) tabs end def can_see_admin_tools_tab?(user) return false if !user || root_account.site_admin? admin_tool_permissions = RoleOverride.manageable_permissions(self).find_all{|p| p[1][:admin_tool]} admin_tool_permissions.any? do |p| self.grants_right?(user, p.first) end end def is_a_context? true end def help_links links = settings[:custom_help_links] # set the type to custom for any existing custom links that don't have a type set # the new ui will set the type ('custom' or 'default') for any new custom links # since we now allow reordering the links, the default links get stored in the settings as well if !links.blank? links.each do |link| if link[:type].blank? link[:type] = 'custom' end end end if settings[:new_custom_help_links] links || Account::HelpLinks.default_links else Account::HelpLinks.default_links + (links || []) end end def set_service_availability(service, enable) service = service.to_sym raise "Invalid Service" unless AccountServices.allowable_services[service] allowed_service_names = (self.allowed_services || "").split(",").compact if allowed_service_names.count > 0 && ![ '+', '-' ].include?(allowed_service_names[0][0,1]) # This account has a hard-coded list of services, so handle accordingly allowed_service_names.reject! { |flag| flag.match("^[+-]?#{service}$") } allowed_service_names << service if enable else allowed_service_names.reject! { |flag| flag.match("^[+-]?#{service}$") } if enable # only enable if it is not enabled by default allowed_service_names << "+#{service}" unless AccountServices.default_allowable_services[service] else # only disable if it is not enabled by default allowed_service_names << "-#{service}" if AccountServices.default_allowable_services[service] end end @allowed_services_hash = nil self.allowed_services = allowed_service_names.empty? ? nil : allowed_service_names.join(",") end def enable_service(service) set_service_availability(service, true) end def disable_service(service) set_service_availability(service, false) end def allowed_services_hash return @allowed_services_hash if @allowed_services_hash account_allowed_services = AccountServices.default_allowable_services if self.allowed_services allowed_service_names = self.allowed_services.split(",").compact if allowed_service_names.count > 0 unless [ '+', '-' ].member?(allowed_service_names[0][0,1]) # This account has a hard-coded list of services, so we clear out the defaults account_allowed_services = { } end allowed_service_names.each do |service_switch| if service_switch =~ /\A([+-]?)(.*)\z/ flag = $1 service_name = $2.to_sym if flag == '-' account_allowed_services.delete(service_name) else account_allowed_services[service_name] = AccountServices.allowable_services[service_name] end end end end end @allowed_services_hash = account_allowed_services end # if expose_as is nil, all services exposed in the ui are returned # if it's :service or :setting, then only services set to be exposed as that type are returned def self.services_exposed_to_ui_hash(expose_as = nil, current_user = nil, account = nil) if expose_as AccountServices.allowable_services.reject { |_, setting| setting[:expose_to_ui] != expose_as } else AccountServices.allowable_services.reject { |_, setting| !setting[:expose_to_ui] } end.reject { |_, setting| setting[:expose_to_ui_proc] && !setting[:expose_to_ui_proc].call(current_user, account) } end def service_enabled?(service) service = service.to_sym case service when :none self.allowed_services_hash.empty? else self.allowed_services_hash.has_key?(service) end end def self.all_accounts_for(context) if context.respond_to?(:account) context.account.account_chain elsif context.respond_to?(:parent_account) context.account_chain else [] end end def find_child(child_id) return all_accounts.find(child_id) if root_account? child = Account.find(child_id) raise ActiveRecord::RecordNotFound unless child.account_chain.include?(self) child end def manually_created_courses_account return self.root_account.manually_created_courses_account unless self.root_account? display_name = t('#account.manually_created_courses', "Manually-Created Courses") acct = manually_created_courses_account_from_settings if acct.blank? transaction do lock! acct = manually_created_courses_account_from_settings acct ||= self.sub_accounts.where(name: display_name).first_or_create! # for backwards compatibility if acct.id != self.settings[:manually_created_courses_account_id] self.settings[:manually_created_courses_account_id] = acct.id self.save! end end end acct end def manually_created_courses_account_from_settings acct_id = self.settings[:manually_created_courses_account_id] acct = self.sub_accounts.where(id: acct_id).first if acct_id.present? acct = nil if acct.present? && acct.root_account_id != self.id acct end private :manually_created_courses_account_from_settings def trusted_account_ids return [] if !root_account? || self == Account.site_admin [ Account.site_admin.id ] end def trust_exists? false end def user_list_search_mode_for(user) return :preferred if self.root_account.open_registration? return :preferred if self.root_account.grants_right?(user, :manage_user_logins) :closed end scope :root_accounts, -> { where(:root_account_id => nil) } scope :processing_sis_batch, -> { where("accounts.current_sis_batch_id IS NOT NULL").order(:updated_at) } scope :name_like, lambda { |name| where(wildcard('accounts.name', name)) } scope :active, -> { where("accounts.workflow_state<>'deleted'") } def change_root_account_setting!(setting_name, new_value) root_account.settings[setting_name] = new_value root_account.save! end Bookmarker = BookmarkedCollection::SimpleBookmarker.new(Account, :name, :id) def format_referer(referer_url) begin referer = URI(referer_url || '') rescue URI::Error return end return unless referer.host referer_with_port = "#{referer.scheme}://#{referer.host}" referer_with_port += ":#{referer.port}" unless referer.port == (referer.scheme == 'https' ? 443 : 80) referer_with_port end def trusted_referers=(value) self.settings[:trusted_referers] = unless value.blank? value.split(',').map { |referer_url| format_referer(referer_url) }.compact.join(',') end end def trusted_referer?(referer_url) return if !self.settings.has_key?(:trusted_referers) || self.settings[:trusted_referers].blank? if referer_with_port = format_referer(referer_url) self.settings[:trusted_referers].split(',').include?(referer_with_port) end end def parent_registration? authentication_providers.where(parent_registration: true).exists? end def parent_auth_type return nil unless parent_registration? parent_registration_aac.auth_type end def parent_registration_aac authentication_providers.where(parent_registration: true).first end def to_param return 'site_admin' if site_admin? super end def create_default_objects work = -> do default_enrollment_term enable_canvas_authentication end return work.call if Rails.env.test? self.class.connection.after_transaction_commit(&work) end end make the root account cache relative to the default shard, not the birth refs CNVS-36971 this means if the account is already cached, and Rails hasn't loaded column info yet, the metadata query will happen against the default shard, not the birth shard Change-Id: Icfd98fb685a890b35446ebc841ee1a315b49ae9b Reviewed-on: https://gerrit.instructure.com/113083 Tested-by: Jenkins Reviewed-by: Rob Orton <7e09c9d3e96378bf549fc283fd6e1e5b7014cc33@instructure.com> Product-Review: Cody Cutrer <c4fe2b1d90ef8f2548c8aeabfa633434316f0305@instructure.com> QA-Review: Cody Cutrer <c4fe2b1d90ef8f2548c8aeabfa633434316f0305@instructure.com> # # Copyright (C) 2011 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # require 'atom' class Account < ActiveRecord::Base include Context INSTANCE_GUID_SUFFIX = 'canvas-lms' include Workflow include BrandConfigHelpers belongs_to :parent_account, :class_name => 'Account' belongs_to :root_account, :class_name => 'Account' authenticates_many :pseudonym_sessions has_many :courses has_many :all_courses, :class_name => 'Course', :foreign_key => 'root_account_id' has_many :group_categories, -> { where(deleted_at: nil) }, as: :context, inverse_of: :context has_many :all_group_categories, :class_name => 'GroupCategory', :as => :context, :inverse_of => :context has_many :groups, :as => :context, :inverse_of => :context has_many :all_groups, :class_name => 'Group', :foreign_key => 'root_account_id' has_many :all_group_memberships, source: 'group_memberships', through: :all_groups has_many :enrollment_terms, :foreign_key => 'root_account_id' has_many :active_enrollment_terms, -> { where("enrollment_terms.workflow_state<>'deleted'") }, class_name: 'EnrollmentTerm', foreign_key: 'root_account_id' has_many :grading_period_groups, inverse_of: :root_account, dependent: :destroy has_many :grading_periods, through: :grading_period_groups has_many :enrollments, -> { where("enrollments.type<>'StudentViewEnrollment'") }, foreign_key: 'root_account_id' has_many :all_enrollments, :class_name => 'Enrollment', :foreign_key => 'root_account_id' has_many :sub_accounts, -> { where("workflow_state<>'deleted'") }, class_name: 'Account', foreign_key: 'parent_account_id' has_many :all_accounts, -> { order(:name) }, class_name: 'Account', foreign_key: 'root_account_id' has_many :account_users, :dependent => :destroy has_many :course_sections, :foreign_key => 'root_account_id' has_many :sis_batches has_many :abstract_courses, :class_name => 'AbstractCourse', :foreign_key => 'account_id' has_many :root_abstract_courses, :class_name => 'AbstractCourse', :foreign_key => 'root_account_id' has_many :users, :through => :account_users has_many :pseudonyms, -> { preload(:user) }, inverse_of: :account has_many :role_overrides, :as => :context, :inverse_of => :context has_many :course_account_associations has_many :child_courses, -> { where(course_account_associations: { depth: 0 }) }, through: :course_account_associations, source: :course has_many :attachments, :as => :context, :inverse_of => :context, :dependent => :destroy has_many :active_assignments, -> { where("assignments.workflow_state<>'deleted'") }, as: :context, inverse_of: :context, class_name: 'Assignment' has_many :folders, -> { order('folders.name') }, as: :context, inverse_of: :context, dependent: :destroy has_many :active_folders, -> { where("folder.workflow_state<>'deleted'").order('folders.name') }, class_name: 'Folder', as: :context, inverse_of: :context has_many :developer_keys has_many :authentication_providers, -> { order(:position) }, extend: AccountAuthorizationConfig::FindWithType, class_name: "AccountAuthorizationConfig" has_many :account_reports has_many :grading_standards, -> { where("workflow_state<>'deleted'") }, as: :context, inverse_of: :context has_many :assessment_questions, :through => :assessment_question_banks has_many :assessment_question_banks, -> { preload(:assessment_questions, :assessment_question_bank_users) }, as: :context, inverse_of: :context has_many :roles has_many :all_roles, :class_name => 'Role', :foreign_key => 'root_account_id' has_many :progresses, :as => :context, :inverse_of => :context has_many :content_migrations, :as => :context, :inverse_of => :context def inherited_assessment_question_banks(include_self = false, *additional_contexts) sql = [] conds = [] contexts = additional_contexts + account_chain contexts.delete(self) unless include_self contexts.each { |c| sql << "context_type = ? AND context_id = ?" conds += [c.class.to_s, c.id] } conds.unshift(sql.join(" OR ")) AssessmentQuestionBank.where(conds) end include LearningOutcomeContext include RubricContext has_many :context_external_tools, -> { order(:name) }, as: :context, inverse_of: :context, dependent: :destroy has_many :error_reports has_many :announcements, :class_name => 'AccountNotification' has_many :alerts, -> { preload(:criteria) }, as: :context, inverse_of: :context has_many :user_account_associations has_many :report_snapshots has_many :external_integration_keys, :as => :context, :inverse_of => :context, :dependent => :destroy has_many :shared_brand_configs belongs_to :brand_config, foreign_key: "brand_config_md5" before_validation :verify_unique_sis_source_id before_save :ensure_defaults after_save :update_account_associations_if_changed before_save :setup_cache_invalidation after_save :invalidate_caches_if_changed after_update :clear_special_account_cache_if_special after_create :create_default_objects serialize :settings, Hash include TimeZoneHelper time_zone_attribute :default_time_zone, default: "America/Denver" def default_time_zone if read_attribute(:default_time_zone) || root_account? super else root_account.default_time_zone end end alias_method :time_zone, :default_time_zone validates_locale :default_locale, :allow_nil => true validates_length_of :name, :maximum => maximum_string_length, :allow_blank => true validate :account_chain_loop, :if => :parent_account_id_changed? validate :validate_auth_discovery_url validates_presence_of :workflow_state include StickySisFields are_sis_sticky :name include FeatureFlags def default_locale(recurse = false) result = read_attribute(:default_locale) if recurse result ||= Rails.cache.fetch(['default_locale', self.global_id].cache_key) do parent_account.default_locale(true) if parent_account end end result = nil unless I18n.locale_available?(result) result end include ::Account::Settings # these settings either are or could be easily added to # the account settings page add_setting :sis_app_token, :root_only => true add_setting :sis_app_url, :root_only => true add_setting :sis_name, :root_only => true add_setting :sis_syncing, :boolean => true, :default => false, :inheritable => true add_setting :sis_default_grade_export, :boolean => true, :default => false, :inheritable => true add_setting :sis_require_assignment_due_date, :boolean => true, :default => false, :inheritable => true add_setting :sis_assignment_name_length, :boolean => true, :default => false, :inheritable => true add_setting :sis_assignment_name_length_input, :inheritable => true add_setting :global_includes, :root_only => true, :boolean => true, :default => false add_setting :sub_account_includes, :boolean => true, :default => false # Help link settings add_setting :custom_help_links, :root_only => true add_setting :help_link_icon, :root_only => true add_setting :help_link_name, :root_only => true add_setting :support_url, :root_only => true add_setting :prevent_course_renaming_by_teachers, :boolean => true, :root_only => true add_setting :login_handle_name, root_only: true add_setting :change_password_url, root_only: true add_setting :unknown_user_url, root_only: true add_setting :fft_registration_url, root_only: true add_setting :restrict_student_future_view, :boolean => true, :default => false, :inheritable => true add_setting :restrict_student_future_listing, :boolean => true, :default => false, :inheritable => true add_setting :restrict_student_past_view, :boolean => true, :default => false, :inheritable => true add_setting :teachers_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :students_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :restrict_quiz_questions, :boolean => true, :root_only => true, :default => false add_setting :no_enrollments_can_create_courses, :boolean => true, :root_only => true, :default => false add_setting :allow_sending_scores_in_emails, :boolean => true, :root_only => true add_setting :self_enrollment add_setting :equella_endpoint add_setting :equella_teaser add_setting :enable_alerts, :boolean => true, :root_only => true add_setting :enable_eportfolios, :boolean => true, :root_only => true add_setting :users_can_edit_name, :boolean => true, :root_only => true add_setting :open_registration, :boolean => true, :root_only => true add_setting :show_scheduler, :boolean => true, :root_only => true, :default => false add_setting :enable_profiles, :boolean => true, :root_only => true, :default => false add_setting :enable_turnitin, :boolean => true, :default => false add_setting :mfa_settings, :root_only => true add_setting :admins_can_change_passwords, :boolean => true, :root_only => true, :default => false add_setting :admins_can_view_notifications, :boolean => true, :root_only => true, :default => false add_setting :canvadocs_prefer_office_online, :boolean => true, :root_only => true, :default => false add_setting :outgoing_email_default_name add_setting :external_notification_warning, :boolean => true, :default => false # Terms of Use and Privacy Policy settings for the root account add_setting :terms_changed_at, :root_only => true add_setting :account_terms_required, :root_only => true, :boolean => true, :default => true # When a user is invited to a course, do we let them see a preview of the # course even without registering? This is part of the free-for-teacher # account perks, since anyone can invite anyone to join any course, and it'd # be nice to be able to see the course first if you weren't expecting the # invitation. add_setting :allow_invitation_previews, :boolean => true, :root_only => true, :default => false add_setting :large_course_rosters, :boolean => true, :root_only => true, :default => false add_setting :edit_institution_email, :boolean => true, :root_only => true, :default => true add_setting :js_kaltura_uploader, :boolean => true, :root_only => true, :default => false add_setting :google_docs_domain, root_only: true add_setting :dashboard_url, root_only: true add_setting :product_name, root_only: true add_setting :author_email_in_notifications, boolean: true, root_only: true, default: false add_setting :include_students_in_global_survey, boolean: true, root_only: true, default: false add_setting :trusted_referers, root_only: true add_setting :app_center_access_token add_setting :enable_offline_web_export, boolean: true, default: false, inheritable: true add_setting :strict_sis_check, :boolean => true, :root_only => true, :default => false add_setting :lock_all_announcements, default: false, boolean: true, inheritable: true def settings=(hash) if hash.is_a?(Hash) || hash.is_a?(ActionController::Parameters) hash.each do |key, val| if account_settings_options && account_settings_options[key.to_sym] opts = account_settings_options[key.to_sym] if (opts[:root_only] && !self.root_account?) || (opts[:condition] && !self.send("#{opts[:condition]}?".to_sym)) settings.delete key.to_sym elsif opts[:hash] new_hash = {} if val.is_a?(Hash) || val.is_a?(ActionController::Parameters) val.each do |inner_key, inner_val| inner_key = inner_key.to_sym if opts[:values].include?(inner_key) if opts[:inheritable] && (inner_key == :locked || (inner_key == :value && opts[:boolean])) new_hash[inner_key] = Canvas::Plugin.value_to_boolean(inner_val) else new_hash[inner_key] = inner_val.to_s end end end end settings[key.to_sym] = new_hash.empty? ? nil : new_hash elsif opts[:boolean] settings[key.to_sym] = Canvas::Plugin.value_to_boolean(val) else settings[key.to_sym] = val.to_s end end end end # prune nil or "" hash values to save space in the DB. settings.reject! { |_, value| value.nil? || value == "" } settings end def product_name settings[:product_name] || t("#product_name", "Canvas") end def allow_global_includes? if root_account? global_includes? else root_account.try(:sub_account_includes?) && root_account.try(:allow_global_includes?) end end def mfa_settings settings[:mfa_settings].try(:to_sym) || :disabled end def non_canvas_auth_configured? authentication_providers.active.where("auth_type<>'canvas'").exists? end def canvas_authentication_provider @canvas_ap ||= authentication_providers.active.where(auth_type: 'canvas').first end def canvas_authentication? !!canvas_authentication_provider end def enable_canvas_authentication return unless root_account? # for migrations creating a new db return unless AccountAuthorizationConfig::Canvas.columns_hash.key?('workflow_state') return if authentication_providers.active.where(auth_type: 'canvas').exists? authentication_providers.create!(auth_type: 'canvas') end def enable_offline_web_export? enable_offline_web_export[:value] end def open_registration? !!settings[:open_registration] && canvas_authentication? end def self_registration? canvas_authentication_provider.try(:jit_provisioning?) end def self_registration_type canvas_authentication_provider.try(:self_registration) end def self_registration_allowed_for?(type) return false unless self_registration? return false if self_registration_type != 'all' && type != self_registration_type true end def enable_self_registration canvas_authentication_provider.update_attribute(:self_registration, true) end def terms_required? Setting.get('terms_required', 'true') == 'true' && root_account.account_terms_required? end def require_acceptance_of_terms?(user) soc2_start_date = Setting.get('SOC2_start_date', Time.new(2015, 5, 16, 0, 0, 0).utc).to_datetime return false if !terms_required? return true if user.nil? || user.new_record? terms_changed_at = settings[:terms_changed_at] last_accepted = user.preferences[:accepted_terms] # make sure existing users are grandfathered in return false if terms_changed_at.nil? && user.registered? && user.created_at < soc2_start_date return false if last_accepted && (terms_changed_at.nil? || last_accepted > terms_changed_at) true end def ip_filters=(params) filters = {} require 'ipaddr' params.each do |key, str| ips = [] vals = str.split(/,/) vals.each do |val| ip = IPAddr.new(val) rescue nil # right now the ip_filter column on quizzes is just a string, # so it has a max length. I figure whatever we set it to this # setter should at the very least limit stored values to that # length. ips << val if ip && val.length <= 255 end filters[key] = ips.join(',') unless ips.empty? end settings[:ip_filters] = filters end def ensure_defaults self.uuid ||= CanvasSlug.generate_securish_uuid self.lti_guid ||= "#{self.uuid}:#{INSTANCE_GUID_SUFFIX}" if self.respond_to?(:lti_guid) self.root_account_id ||= self.parent_account.root_account_id if self.parent_account self.root_account_id ||= self.parent_account_id self.parent_account_id ||= self.root_account_id Account.invalidate_cache(self.id) if self.id true end def verify_unique_sis_source_id return true unless self.sis_source_id return true if !root_account_id_changed? && !sis_source_id_changed? if self.root_account? self.errors.add(:sis_source_id, t('#account.root_account_cant_have_sis_id', "SIS IDs cannot be set on root accounts")) throw :abort unless CANVAS_RAILS4_2 return false end scope = root_account.all_accounts.where(sis_source_id: self.sis_source_id) scope = scope.where("id<>?", self) unless self.new_record? return true unless scope.exists? self.errors.add(:sis_source_id, t('#account.sis_id_in_use', "SIS ID \"%{sis_id}\" is already in use", :sis_id => self.sis_source_id)) throw :abort unless CANVAS_RAILS4_2 false end def update_account_associations_if_changed send_later_if_production(:update_account_associations) if self.parent_account_id_changed? || self.root_account_id_changed? end def equella_settings endpoint = self.settings[:equella_endpoint] || self.equella_endpoint if !endpoint.blank? OpenObject.new({ :endpoint => endpoint, :default_action => self.settings[:equella_action] || 'selectOrAdd', :teaser => self.settings[:equella_teaser] }) else nil end end def settings result = self.read_attribute(:settings) if result @old_settings ||= result.dup return result end return write_attribute(:settings, {}) unless frozen? {}.freeze end def domain HostUrl.context_host(self) end def self.find_by_domain(domain) self.default if HostUrl.default_host == domain end def root_account? !self.root_account_id end def root_account return self if root_account? super end def sub_accounts_as_options(indent = 0, preloaded_accounts = nil) unless preloaded_accounts preloaded_accounts = {} self.root_account.all_accounts.active.each do |account| (preloaded_accounts[account.parent_account_id] ||= []) << account end end res = [[("&nbsp;&nbsp;" * indent).html_safe + self.name, self.id]] if preloaded_accounts[self.id] preloaded_accounts[self.id].each do |account| res += account.sub_accounts_as_options(indent + 1, preloaded_accounts) end end res end def users_visible_to(user) self.grants_right?(user, :read) ? self.all_users : self.all_users.none end def users_name_like(query="") @cached_users_name_like ||= {} @cached_users_name_like[query] ||= self.fast_all_users.name_like(query) end def associated_courses if root_account? all_courses else shard.activate do Course.where("EXISTS (?)", CourseAccountAssociation.where(account_id: self).where("course_id=courses.id")) end end end def associated_user?(user) user_account_associations.where(user_id: user).exists? end def fast_course_base(opts = {}) opts[:order] ||= "#{Course.best_unicode_collation_key("courses.name")} ASC" columns = "courses.id, courses.name, courses.workflow_state, courses.course_code, courses.sis_source_id, courses.enrollment_term_id" associated_courses = self.associated_courses.active.order(opts[:order]) associated_courses = associated_courses.with_enrollments if opts[:hide_enrollmentless_courses] associated_courses = associated_courses.master_courses if opts[:only_master_courses] associated_courses = associated_courses.for_term(opts[:term]) if opts[:term].present? associated_courses = yield associated_courses if block_given? associated_courses.limit(opts[:limit]).active_first.select(columns).to_a end def fast_all_courses(opts={}) @cached_fast_all_courses ||= {} @cached_fast_all_courses[opts] ||= self.fast_course_base(opts) end def all_users(limit=250) @cached_all_users ||= {} @cached_all_users[limit] ||= User.of_account(self).limit(limit) end def fast_all_users(limit=nil) @cached_fast_all_users ||= {} @cached_fast_all_users[limit] ||= self.all_users(limit).active.select("users.id, users.updated_at, users.name, users.sortable_name").order_by_sortable_name end def users_not_in_groups(groups, opts={}) scope = User.active.joins(:user_account_associations). where(user_account_associations: {account_id: self}). where(Group.not_in_group_sql_fragment(groups.map(&:id))). select("users.id, users.name") scope = scope.select(opts[:order]).order(opts[:order]) if opts[:order] scope end def courses_name_like(query="", opts={}) opts[:limit] ||= 200 @cached_courses_name_like ||= {} @cached_courses_name_like[[query, opts]] ||= self.fast_course_base(opts) {|q| q.name_like(query)} end def self_enrollment_course_for(code) all_courses. where(:self_enrollment_code => code). first end def file_namespace Shard.birth.activate { "account_#{self.root_account.id}" } end def self.account_lookup_cache_key(id) ['_account_lookup5', id].cache_key end def self.invalidate_cache(id) return unless id default_id = Shard.relative_id_for(id, Shard.current, Shard.default) Shard.default.activate do Rails.cache.delete(account_lookup_cache_key(default_id)) if default_id end rescue nil end def setup_cache_invalidation @invalidations = [] unless self.new_record? invalidate_all = self.parent_account_id_changed? # apparently, the try_rescues are because these columns don't exist on old migrations @invalidations += ['default_storage_quota', 'current_quota'] if invalidate_all || self.try_rescue(:default_storage_quota_changed?) @invalidations << 'default_group_storage_quota' if invalidate_all || self.try_rescue(:default_group_storage_quota_changed?) @invalidations << 'default_locale' if invalidate_all || self.try_rescue(:default_locale_changed?) end end def invalidate_caches_if_changed @invalidations ||= [] if self.parent_account_id_changed? @invalidations += Account.inheritable_settings # invalidate all of them elsif @old_settings Account.inheritable_settings.each do |key| @invalidations << key if @old_settings[key] != settings[key] # only invalidate if needed end @old_settings = nil end if @invalidations.present? shard.activate do @invalidations.each do |key| Rails.cache.delete([key, self.global_id].cache_key) end Account.send_later_if_production(:invalidate_inherited_caches, self, @invalidations) end end end def self.invalidate_inherited_caches(parent_account, keys) parent_account.shard.activate do account_ids = Account.sub_account_ids_recursive(parent_account.id) account_ids.each do |id| global_id = Shard.global_id_for(id) keys.each do |key| Rails.cache.delete([key, global_id].cache_key) end end access_keys = keys & [:restrict_student_future_view, :restrict_student_past_view] if access_keys.any? EnrollmentState.invalidate_access_for_accounts([parent_account.id] + account_ids, access_keys) end end end def self.default_storage_quota Setting.get('account_default_quota', 500.megabytes.to_s).to_i end def quota return storage_quota if read_attribute(:storage_quote) return self.class.default_storage_quota if root_account? shard.activate do Rails.cache.fetch(['current_quota', self.global_id].cache_key) do self.parent_account.default_storage_quota end end end def default_storage_quota return super if read_attribute(:default_storage_quota) return self.class.default_storage_quota if root_account? shard.activate do @default_storage_quota ||= Rails.cache.fetch(['default_storage_quota', self.global_id].cache_key) do parent_account.default_storage_quota end end end def default_storage_quota_mb default_storage_quota / 1.megabyte end def default_storage_quota_mb=(val) self.default_storage_quota = val.try(:to_i).try(:megabytes) end def default_storage_quota=(val) val = val.to_f val = nil if val <= 0 # If the value is the same as the inherited value, then go # ahead and blank it so it keeps using the inherited value if parent_account && parent_account.default_storage_quota == val val = nil end write_attribute(:default_storage_quota, val) end def default_user_storage_quota read_attribute(:default_user_storage_quota) || User.default_storage_quota end def default_user_storage_quota=(val) val = val.to_i val = nil if val == User.default_storage_quota || val <= 0 write_attribute(:default_user_storage_quota, val) end def default_user_storage_quota_mb default_user_storage_quota / 1.megabyte end def default_user_storage_quota_mb=(val) self.default_user_storage_quota = val.try(:to_i).try(:megabytes) end def default_group_storage_quota return super if read_attribute(:default_group_storage_quota) return Group.default_storage_quota if root_account? shard.activate do Rails.cache.fetch(['default_group_storage_quota', self.global_id].cache_key) do self.parent_account.default_group_storage_quota end end end def default_group_storage_quota=(val) val = val.to_i if (val == Group.default_storage_quota) || (val <= 0) || (self.parent_account && self.parent_account.default_group_storage_quota == val) val = nil end write_attribute(:default_group_storage_quota, val) end def default_group_storage_quota_mb default_group_storage_quota / 1.megabyte end def default_group_storage_quota_mb=(val) self.default_group_storage_quota = val.try(:to_i).try(:megabytes) end def turnitin_shared_secret=(secret) return if secret.blank? self.turnitin_crypted_secret, self.turnitin_salt = Canvas::Security.encrypt_password(secret, 'instructure_turnitin_secret_shared') end def turnitin_shared_secret return nil unless self.turnitin_salt && self.turnitin_crypted_secret Canvas::Security.decrypt_password(self.turnitin_crypted_secret, self.turnitin_salt, 'instructure_turnitin_secret_shared') end def self.account_chain(starting_account_id) chain = [] if (starting_account_id.is_a?(Account)) chain << starting_account_id starting_account_id = starting_account_id.parent_account_id end if starting_account_id if ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'postgresql' chain.concat(Shard.shard_for(starting_account_id).activate do Account.find_by_sql(<<-SQL) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE id=#{Shard.local_id_for(starting_account_id).first} UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT * FROM t SQL end) else account = Account.find(starting_account_id) chain << account while account.parent_account account = account.parent_account chain << account end end end chain end def self.account_chain_ids(starting_account_id) if connection.adapter_name == 'PostgreSQL' Shard.shard_for(starting_account_id).activate do id_chain = [] if (starting_account_id.is_a?(Account)) id_chain << starting_account_id.id starting_account_id = starting_account_id.parent_account_id end if starting_account_id ids = Account.connection.select_values(<<-SQL) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE id=#{Shard.local_id_for(starting_account_id).first} UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t SQL id_chain.concat(ids.map(&:to_i)) end id_chain end else account_chain(starting_account_id).map(&:id) end end def self.add_site_admin_to_chain!(chain) chain << Account.site_admin unless chain.last.site_admin? chain end def account_chain(include_site_admin: false) @account_chain ||= Account.account_chain(self) result = @account_chain.dup Account.add_site_admin_to_chain!(result) if include_site_admin result end def account_chain_ids @cached_account_chain_ids ||= Account.account_chain_ids(self) end def account_chain_loop # this record hasn't been saved to the db yet, so if the the chain includes # this account, it won't point to the new parent yet, and should still be # valid if self.parent_account.account_chain.include?(self) errors.add(:parent_account_id, "Setting account #{self.sis_source_id || self.id}'s parent to #{self.parent_account.sis_source_id || self.parent_account_id} would create a loop") end end # returns all sub_accounts recursively as far down as they go, in id order # because this uses a custom sql query for postgresql, we can't use a normal # named scope, so we pass the limit and offset into the method instead and # build our own query string def sub_accounts_recursive(limit, offset) if ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'postgresql' Account.find_by_sql([<<-SQL, self.id, limit.to_i, offset.to_i]) WITH RECURSIVE t AS ( SELECT * FROM #{Account.quoted_table_name} WHERE parent_account_id = ? AND workflow_state <>'deleted' UNION SELECT accounts.* FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.parent_account_id = t.id WHERE accounts.workflow_state <>'deleted' ) SELECT * FROM t ORDER BY parent_account_id, id LIMIT ? OFFSET ? SQL else account_descendents = lambda do |id| as = Account.where(:parent_account_id => id).active.order(:id) as.empty? ? [] : as << as.map { |a| account_descendents.call(a.id) } end account_descendents.call(id).flatten[offset, limit] end end def self.sub_account_ids_recursive(parent_account_id) if connection.adapter_name == 'PostgreSQL' sql = Account.sub_account_ids_recursive_sql(parent_account_id) Account.find_by_sql(sql).map(&:id) else account_descendants = lambda do |ids| as = Account.where(:parent_account_id => ids).active.pluck(:id) as + account_descendants.call(as) end account_descendants.call([parent_account_id]) end end def self.sub_account_ids_recursive_sql(parent_account_id) "WITH RECURSIVE t AS ( SELECT id, parent_account_id FROM #{Account.quoted_table_name} WHERE parent_account_id = #{parent_account_id} AND workflow_state <> 'deleted' UNION SELECT accounts.id, accounts.parent_account_id FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.parent_account_id = t.id WHERE accounts.workflow_state <> 'deleted' ) SELECT id FROM t" end def associated_accounts self.account_chain end def membership_for_user(user) self.account_users.where(user_id: user).first if user end def available_custom_account_roles(include_inactive=false) available_custom_roles(include_inactive).for_accounts.to_a end def available_account_roles(include_inactive=false, user = nil) account_roles = available_custom_account_roles(include_inactive) account_roles << Role.get_built_in_role('AccountAdmin') if user account_roles.select! { |role| au = account_users.new; au.role_id = role.id; au.grants_right?(user, :create) } end account_roles end def available_custom_course_roles(include_inactive=false) available_custom_roles(include_inactive).for_courses.to_a end def available_course_roles(include_inactive=false) course_roles = available_custom_course_roles(include_inactive) course_roles += Role.built_in_course_roles course_roles end def available_custom_roles(include_inactive=false) scope = Role.where(:account_id => account_chain_ids) scope = include_inactive ? scope.not_deleted : scope.active scope end def available_roles(include_inactive=false) available_account_roles(include_inactive) + available_course_roles(include_inactive) end def get_account_role_by_name(role_name) role = get_role_by_name(role_name) return role if role && role.account_role? end def get_course_role_by_name(role_name) role = get_role_by_name(role_name) return role if role && role.course_role? end def get_role_by_name(role_name) if role = Role.get_built_in_role(role_name) return role end self.shard.activate do role_scope = Role.not_deleted.where(:name => role_name) if self.class.connection.adapter_name == 'PostgreSQL' role_scope = role_scope.where("account_id = ? OR account_id IN ( WITH RECURSIVE t AS ( SELECT id, parent_account_id FROM #{Account.quoted_table_name} WHERE id = ? UNION SELECT accounts.id, accounts.parent_account_id FROM #{Account.quoted_table_name} INNER JOIN t ON accounts.id=t.parent_account_id ) SELECT id FROM t )", self.id, self.id) else role_scope = role_scope.where(:account_id => self.account_chain.map(&:id)) end role_scope.first end end def get_role_by_id(role_id) role = Role.get_role_by_id(role_id) return role if valid_role?(role) end def valid_role?(role) role && (role.built_in? || (self.id == role.account_id) || self.account_chain_ids.include?(role.account_id)) end def login_handle_name_is_customized? self.login_handle_name.present? end def login_handle_name_with_inference if login_handle_name_is_customized? self.login_handle_name elsif self.delegated_authentication? AccountAuthorizationConfig.default_delegated_login_handle_name else AccountAuthorizationConfig.default_login_handle_name end end def self_and_all_sub_accounts @self_and_all_sub_accounts ||= Account.where("root_account_id=? OR parent_account_id=?", self, self).pluck(:id).uniq + [self.id] end workflow do state :active state :deleted end def account_users_for(user) return [] unless user @account_users_cache ||= {} if self == Account.site_admin shard.activate do @account_users_cache[user.global_id] ||= begin all_site_admin_account_users_hash = MultiCache.fetch("all_site_admin_account_users3") do # this is a plain ruby hash to keep the cached portion as small as possible self.account_users.inject({}) { |result, au| result[au.user_id] ||= []; result[au.user_id] << [au.id, au.role_id]; result } end (all_site_admin_account_users_hash[user.id] || []).map do |(id, role_id)| au = AccountUser.new au.id = id au.account = Account.site_admin au.user = user au.role_id = role_id au.readonly! au end end end else @account_chain_ids ||= self.account_chain(:include_site_admin => true).map { |a| a.active? ? a.id : nil }.compact @account_users_cache[user.global_id] ||= Shard.partition_by_shard(@account_chain_ids) do |account_chain_ids| if account_chain_ids == [Account.site_admin.id] Account.site_admin.account_users_for(user) else AccountUser.where(:account_id => account_chain_ids, :user_id => user).to_a end end end @account_users_cache[user.global_id] ||= [] @account_users_cache[user.global_id] end # returns all account users for this entire account tree def all_account_users_for(user) raise "must be a root account" unless self.root_account? Shard.partition_by_shard(account_chain(include_site_admin: true).uniq) do |accounts| next unless user.associated_shards.include?(Shard.current) AccountUser.eager_load(:account).where("user_id=? AND (root_account_id IN (?) OR account_id IN (?))", user, accounts, accounts) end end set_policy do enrollment_types = RoleOverride.enrollment_type_labels.map { |role| role[:name] } RoleOverride.permissions.each do |permission, details| given { |user| self.account_users_for(user).any? { |au| au.has_permission_to?(self, permission) } } can permission can :create_courses if permission == :manage_courses end given { |user| !self.account_users_for(user).empty? } can :read and can :read_as_admin and can :manage and can :update and can :delete and can :read_outcomes given { |user| result = false if !root_account.site_admin? && user scope = root_account.enrollments.active.where(user_id: user) result = root_account.teachers_can_create_courses? && scope.where(:type => ['TeacherEnrollment', 'DesignerEnrollment']).exists? result ||= root_account.students_can_create_courses? && scope.where(:type => ['StudentEnrollment', 'ObserverEnrollment']).exists? result ||= root_account.no_enrollments_can_create_courses? && !scope.exists? end result } can :create_courses # any logged in user can read global outcomes, but must be checked against the site admin given{ |user| self.site_admin? && user } can :read_global_outcomes # any user with an association to this account can read the outcomes in the account given{ |user| user && self.user_account_associations.where(user_id: user).exists? } can :read_outcomes # any user with an admin enrollment in one of the courses can read given { |user| user && self.courses.where(:id => user.enrollments.admin.pluck(:course_id)).exists? } can :read given { |user| self.grants_right?(user, :lti_add_edit)} can :create_tool_manually end alias_method :destroy_permanently!, :destroy def destroy self.workflow_state = 'deleted' self.deleted_at = Time.now.utc save! end def to_atom Atom::Entry.new do |entry| entry.title = self.name entry.updated = self.updated_at entry.published = self.created_at entry.links << Atom::Link.new(:rel => 'alternate', :href => "/accounts/#{self.id}") end end def default_enrollment_term return @default_enrollment_term if @default_enrollment_term if self.root_account? @default_enrollment_term = Shackles.activate(:master) { self.enrollment_terms.active.where(name: EnrollmentTerm::DEFAULT_TERM_NAME).first_or_create } end end def context_code raise "DONT USE THIS, use .short_name instead" unless Rails.env.production? end def short_name name end # can be set/overridden by plugin to enforce email pseudonyms attr_accessor :email_pseudonyms def password_policy Canvas::PasswordPolicy.default_policy.merge(settings[:password_policy] || {}) end def delegated_authentication? authentication_providers.active.first.is_a?(AccountAuthorizationConfig::Delegated) end def forgot_password_external_url self.change_password_url end def auth_discovery_url=(url) self.settings[:auth_discovery_url] = url end def auth_discovery_url self.settings[:auth_discovery_url] end def login_handle_name=(handle_name) self.settings[:login_handle_name] = handle_name end def login_handle_name self.settings[:login_handle_name] end def change_password_url=(change_password_url) self.settings[:change_password_url] = change_password_url end def change_password_url self.settings[:change_password_url] end def unknown_user_url=(unknown_user_url) self.settings[:unknown_user_url] = unknown_user_url end def unknown_user_url self.settings[:unknown_user_url] end def validate_auth_discovery_url return if self.settings[:auth_discovery_url].blank? begin value, uri = CanvasHttp.validate_url(self.settings[:auth_discovery_url]) self.auth_discovery_url = value rescue URI::Error, ArgumentError errors.add(:discovery_url, t('errors.invalid_discovery_url', "The discovery URL is not valid" )) end end def find_courses(string) self.all_courses.select{|c| c.name.match(string) } end def find_users(string) self.pseudonyms.map{|p| p.user }.select{|u| u.name.match(string) } end class << self def special_accounts @special_accounts ||= {} end def special_account_ids @special_account_ids ||= {} end def special_account_timed_cache @special_account_timed_cache ||= TimedCache.new(-> { Setting.get('account_special_account_cache_time', 60).to_i.seconds.ago }) do special_accounts.clear end end def special_account_list @special_account_list ||= [] end def clear_special_account_cache!(force = false) special_account_timed_cache.clear(force) end def define_special_account(key, name = nil) name ||= key.to_s.titleize self.special_account_list << key instance_eval <<-RUBY, __FILE__, __LINE__ + 1 def self.#{key}(force_create = false) get_special_account(:#{key}, #{name.inspect}, force_create) end RUBY end def all_special_accounts special_account_list.map { |key| send(key) } end end define_special_account(:default, 'Default Account') # Account.default define_special_account(:site_admin) # Account.site_admin def clear_special_account_cache_if_special if self.shard == Shard.birth && Account.special_account_ids.values.map(&:to_i).include?(self.id) Account.clear_special_account_cache!(true) end end # an opportunity for plugins to load some other stuff up before caching the account def precache end class ::Canvas::AccountCacheError < StandardError; end def self.find_cached(id) default_id = Shard.relative_id_for(id, Shard.current, Shard.default) Shard.default.activate do Rails.cache.fetch(account_lookup_cache_key(default_id)) do begin account = Account.find(default_id) rescue ActiveRecord::RecordNotFound => e raise ::Canvas::AccountCacheError, e.message end account.precache account end end end def self.get_special_account(special_account_type, default_account_name, force_create = false) Shard.birth.activate do account = special_accounts[special_account_type] unless account special_account_id = special_account_ids[special_account_type] ||= Setting.get("#{special_account_type}_account_id", nil) begin account = special_accounts[special_account_type] = Account.find_cached(special_account_id) if special_account_id rescue ::Canvas::AccountCacheError raise unless Rails.env.test? end end # another process (i.e. selenium spec) may have changed the setting unless account special_account_id = Setting.get("#{special_account_type}_account_id", nil) if special_account_id && special_account_id != special_account_ids[special_account_type] special_account_ids[special_account_type] = special_account_id account = special_accounts[special_account_type] = Account.where(id: special_account_id).first end end if !account && default_account_name && ((!special_account_id && !Rails.env.production?) || force_create) t '#account.default_site_administrator_account_name', 'Site Admin' t '#account.default_account_name', 'Default Account' account = special_accounts[special_account_type] = Account.new(:name => default_account_name) account.save! Setting.set("#{special_account_type}_account_id", account.id) special_account_ids[special_account_type] = account.id end account end end def site_admin? self == Account.site_admin end def display_name self.name end # Updates account associations for all the courses and users associated with this account def update_account_associations self.shard.activate do account_chain_cache = {} all_user_ids = Set.new # make sure to use the non-associated_courses associations # to catch courses that didn't ever have an association created scopes = if root_account? [all_courses, associated_courses. where("root_account_id<>?", self)] else [courses, associated_courses. where("courses.account_id<>?", self)] end # match the "batch" size in Course.update_account_associations scopes.each do |scope| scope.select([:id, :account_id]).find_in_batches(:batch_size => 500) do |courses| all_user_ids.merge Course.update_account_associations(courses, :skip_user_account_associations => true, :account_chain_cache => account_chain_cache) end end # Make sure we have all users with existing account associations. all_user_ids.merge self.user_account_associations.pluck(:user_id) if root_account? all_user_ids.merge self.pseudonyms.active.pluck(:user_id) end # Update the users' associations as well User.update_account_associations(all_user_ids.to_a, :account_chain_cache => account_chain_cache) end end def self.update_all_update_account_associations Account.root_accounts.active.find_each(&:update_account_associations) end def course_count self.courses.active.count end def sub_account_count self.sub_accounts.active.count end def user_count self.user_account_associations.count end def current_sis_batch if (current_sis_batch_id = self.read_attribute(:current_sis_batch_id)) && current_sis_batch_id.present? self.sis_batches.where(id: current_sis_batch_id).first end end def turnitin_settings return @turnitin_settings if defined?(@turnitin_settings) if self.turnitin_account_id.present? && self.turnitin_shared_secret.present? if settings[:enable_turnitin] @turnitin_settings = [self.turnitin_account_id, self.turnitin_shared_secret, self.turnitin_host] end else @turnitin_settings = self.parent_account.try(:turnitin_settings) end end def closest_turnitin_pledge if self.turnitin_pledge && !self.turnitin_pledge.empty? self.turnitin_pledge else res = self.parent_account.try(:closest_turnitin_pledge) res ||= t('#account.turnitin_pledge', "This assignment submission is my own, original work") end end def closest_turnitin_comments if self.turnitin_comments && !self.turnitin_comments.empty? self.turnitin_comments else self.parent_account.try(:closest_turnitin_comments) end end def closest_turnitin_originality if self.turnitin_originality && !self.turnitin_originality.empty? self.turnitin_originality else self.parent_account.try(:turnitin_originality) end end def self_enrollment_allowed?(course) if !settings[:self_enrollment].blank? !!(settings[:self_enrollment] == 'any' || (!course.sis_source_id && settings[:self_enrollment] == 'manually_created')) else !!(parent_account && parent_account.self_enrollment_allowed?(course)) end end def allow_self_enrollment!(setting='any') settings[:self_enrollment] = setting self.save! end TAB_COURSES = 0 TAB_STATISTICS = 1 TAB_PERMISSIONS = 2 TAB_SUB_ACCOUNTS = 3 TAB_TERMS = 4 TAB_AUTHENTICATION = 5 TAB_USERS = 6 TAB_OUTCOMES = 7 TAB_RUBRICS = 8 TAB_SETTINGS = 9 TAB_FACULTY_JOURNAL = 10 TAB_SIS_IMPORT = 11 TAB_GRADING_STANDARDS = 12 TAB_QUESTION_BANKS = 13 TAB_ADMIN_TOOLS = 17 TAB_SEARCH = 18 TAB_BRAND_CONFIGS = 19 # site admin tabs TAB_PLUGINS = 14 TAB_JOBS = 15 TAB_DEVELOPER_KEYS = 16 def external_tool_tabs(opts) tools = ContextExternalTool.active.find_all_for(self, :account_navigation) Lti::ExternalToolTab.new(self, :account_navigation, tools, opts[:language]).tabs end def tabs_available(user=nil, opts={}) manage_settings = user && self.grants_right?(user, :manage_account_settings) if root_account.site_admin? tabs = [] if user && self.grants_right?(user, :read_roster) if feature_enabled?(:course_user_search) tabs << { :id => TAB_SEARCH, :label => t("Search"), :css_class => 'search', :href => :account_course_user_search_path } else tabs << { :id => TAB_USERS, :label => t('#account.tab_users', "Users"), :css_class => 'users', :href => :account_users_path } end end tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && self.grants_right?(user, :manage_role_overrides) tabs << { :id => TAB_SUB_ACCOUNTS, :label => t('#account.tab_sub_accounts', "Sub-Accounts"), :css_class => 'sub_accounts', :href => :account_sub_accounts_path } if manage_settings tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if root_account? && manage_settings tabs << { :id => TAB_PLUGINS, :label => t("#account.tab_plugins", "Plugins"), :css_class => "plugins", :href => :plugins_path, :no_args => true } if root_account? && self.grants_right?(user, :manage_site_settings) tabs << { :id => TAB_JOBS, :label => t("#account.tab_jobs", "Jobs"), :css_class => "jobs", :href => :jobs_path, :no_args => true } if root_account? && self.grants_right?(user, :view_jobs) else tabs = [] if feature_enabled?(:course_user_search) tabs << { :id => TAB_SEARCH, :label => t("Search"), :css_class => 'search', :href => :account_path } if user && (grants_right?(user, :read_course_list) || grants_right?(user, :read_roster)) else tabs << { :id => TAB_COURSES, :label => t('#account.tab_courses', "Courses"), :css_class => 'courses', :href => :account_path } if user && self.grants_right?(user, :read_course_list) tabs << { :id => TAB_USERS, :label => t('#account.tab_users', "Users"), :css_class => 'users', :href => :account_users_path } if user && self.grants_right?(user, :read_roster) end tabs << { :id => TAB_STATISTICS, :label => t('#account.tab_statistics', "Statistics"), :css_class => 'statistics', :href => :statistics_account_path } if user && self.grants_right?(user, :view_statistics) tabs << { :id => TAB_PERMISSIONS, :label => t('#account.tab_permissions', "Permissions"), :css_class => 'permissions', :href => :account_permissions_path } if user && self.grants_right?(user, :manage_role_overrides) if user && self.grants_right?(user, :manage_outcomes) tabs << { :id => TAB_OUTCOMES, :label => t('#account.tab_outcomes', "Outcomes"), :css_class => 'outcomes', :href => :account_outcomes_path } tabs << { :id => TAB_RUBRICS, :label => t('#account.tab_rubrics', "Rubrics"), :css_class => 'rubrics', :href => :account_rubrics_path } end tabs << { :id => TAB_GRADING_STANDARDS, :label => t('#account.tab_grading_standards', "Grading"), :css_class => 'grading_standards', :href => :account_grading_standards_path } if user && self.grants_right?(user, :manage_grades) tabs << { :id => TAB_QUESTION_BANKS, :label => t('#account.tab_question_banks', "Question Banks"), :css_class => 'question_banks', :href => :account_question_banks_path } if user && self.grants_right?(user, :manage_assignments) tabs << { :id => TAB_SUB_ACCOUNTS, :label => t('#account.tab_sub_accounts', "Sub-Accounts"), :css_class => 'sub_accounts', :href => :account_sub_accounts_path } if manage_settings tabs << { :id => TAB_FACULTY_JOURNAL, :label => t('#account.tab_faculty_journal', "Faculty Journal"), :css_class => 'faculty_journal', :href => :account_user_notes_path} if self.enable_user_notes && user && self.grants_right?(user, :manage_user_notes) tabs << { :id => TAB_TERMS, :label => t('#account.tab_terms', "Terms"), :css_class => 'terms', :href => :account_terms_path } if self.root_account? && manage_settings tabs << { :id => TAB_AUTHENTICATION, :label => t('#account.tab_authentication', "Authentication"), :css_class => 'authentication', :href => :account_authentication_providers_path } if self.root_account? && manage_settings if self.root_account? && self.allow_sis_import && user && self.grants_any_right?(user, :manage_sis, :import_sis) tabs << { id: TAB_SIS_IMPORT, label: t('#account.tab_sis_import', "SIS Import"), css_class: 'sis_import', href: :account_sis_import_path } end end tabs << { :id => TAB_BRAND_CONFIGS, :label => t('#account.tab_brand_configs', "Themes"), :css_class => 'brand_configs', :href => :account_brand_configs_path } if manage_settings && branding_allowed? tabs << { :id => TAB_DEVELOPER_KEYS, :label => t("#account.tab_developer_keys", "Developer Keys"), :css_class => "developer_keys", :href => :account_developer_keys_path, account_id: root_account.id } if root_account? && self.grants_right?(user, :manage_developer_keys) tabs += external_tool_tabs(opts) tabs += Lti::MessageHandler.lti_apps_tabs(self, [Lti::ResourcePlacement::ACCOUNT_NAVIGATION], opts) tabs << { :id => TAB_ADMIN_TOOLS, :label => t('#account.tab_admin_tools', "Admin Tools"), :css_class => 'admin_tools', :href => :account_admin_tools_path } if can_see_admin_tools_tab?(user) tabs << { :id => TAB_SETTINGS, :label => t('#account.tab_settings', "Settings"), :css_class => 'settings', :href => :account_settings_path } tabs.delete_if{ |t| t[:visibility] == 'admins' } unless self.grants_right?(user, :manage) tabs end def can_see_admin_tools_tab?(user) return false if !user || root_account.site_admin? admin_tool_permissions = RoleOverride.manageable_permissions(self).find_all{|p| p[1][:admin_tool]} admin_tool_permissions.any? do |p| self.grants_right?(user, p.first) end end def is_a_context? true end def help_links links = settings[:custom_help_links] # set the type to custom for any existing custom links that don't have a type set # the new ui will set the type ('custom' or 'default') for any new custom links # since we now allow reordering the links, the default links get stored in the settings as well if !links.blank? links.each do |link| if link[:type].blank? link[:type] = 'custom' end end end if settings[:new_custom_help_links] links || Account::HelpLinks.default_links else Account::HelpLinks.default_links + (links || []) end end def set_service_availability(service, enable) service = service.to_sym raise "Invalid Service" unless AccountServices.allowable_services[service] allowed_service_names = (self.allowed_services || "").split(",").compact if allowed_service_names.count > 0 && ![ '+', '-' ].include?(allowed_service_names[0][0,1]) # This account has a hard-coded list of services, so handle accordingly allowed_service_names.reject! { |flag| flag.match("^[+-]?#{service}$") } allowed_service_names << service if enable else allowed_service_names.reject! { |flag| flag.match("^[+-]?#{service}$") } if enable # only enable if it is not enabled by default allowed_service_names << "+#{service}" unless AccountServices.default_allowable_services[service] else # only disable if it is not enabled by default allowed_service_names << "-#{service}" if AccountServices.default_allowable_services[service] end end @allowed_services_hash = nil self.allowed_services = allowed_service_names.empty? ? nil : allowed_service_names.join(",") end def enable_service(service) set_service_availability(service, true) end def disable_service(service) set_service_availability(service, false) end def allowed_services_hash return @allowed_services_hash if @allowed_services_hash account_allowed_services = AccountServices.default_allowable_services if self.allowed_services allowed_service_names = self.allowed_services.split(",").compact if allowed_service_names.count > 0 unless [ '+', '-' ].member?(allowed_service_names[0][0,1]) # This account has a hard-coded list of services, so we clear out the defaults account_allowed_services = { } end allowed_service_names.each do |service_switch| if service_switch =~ /\A([+-]?)(.*)\z/ flag = $1 service_name = $2.to_sym if flag == '-' account_allowed_services.delete(service_name) else account_allowed_services[service_name] = AccountServices.allowable_services[service_name] end end end end end @allowed_services_hash = account_allowed_services end # if expose_as is nil, all services exposed in the ui are returned # if it's :service or :setting, then only services set to be exposed as that type are returned def self.services_exposed_to_ui_hash(expose_as = nil, current_user = nil, account = nil) if expose_as AccountServices.allowable_services.reject { |_, setting| setting[:expose_to_ui] != expose_as } else AccountServices.allowable_services.reject { |_, setting| !setting[:expose_to_ui] } end.reject { |_, setting| setting[:expose_to_ui_proc] && !setting[:expose_to_ui_proc].call(current_user, account) } end def service_enabled?(service) service = service.to_sym case service when :none self.allowed_services_hash.empty? else self.allowed_services_hash.has_key?(service) end end def self.all_accounts_for(context) if context.respond_to?(:account) context.account.account_chain elsif context.respond_to?(:parent_account) context.account_chain else [] end end def find_child(child_id) return all_accounts.find(child_id) if root_account? child = Account.find(child_id) raise ActiveRecord::RecordNotFound unless child.account_chain.include?(self) child end def manually_created_courses_account return self.root_account.manually_created_courses_account unless self.root_account? display_name = t('#account.manually_created_courses', "Manually-Created Courses") acct = manually_created_courses_account_from_settings if acct.blank? transaction do lock! acct = manually_created_courses_account_from_settings acct ||= self.sub_accounts.where(name: display_name).first_or_create! # for backwards compatibility if acct.id != self.settings[:manually_created_courses_account_id] self.settings[:manually_created_courses_account_id] = acct.id self.save! end end end acct end def manually_created_courses_account_from_settings acct_id = self.settings[:manually_created_courses_account_id] acct = self.sub_accounts.where(id: acct_id).first if acct_id.present? acct = nil if acct.present? && acct.root_account_id != self.id acct end private :manually_created_courses_account_from_settings def trusted_account_ids return [] if !root_account? || self == Account.site_admin [ Account.site_admin.id ] end def trust_exists? false end def user_list_search_mode_for(user) return :preferred if self.root_account.open_registration? return :preferred if self.root_account.grants_right?(user, :manage_user_logins) :closed end scope :root_accounts, -> { where(:root_account_id => nil) } scope :processing_sis_batch, -> { where("accounts.current_sis_batch_id IS NOT NULL").order(:updated_at) } scope :name_like, lambda { |name| where(wildcard('accounts.name', name)) } scope :active, -> { where("accounts.workflow_state<>'deleted'") } def change_root_account_setting!(setting_name, new_value) root_account.settings[setting_name] = new_value root_account.save! end Bookmarker = BookmarkedCollection::SimpleBookmarker.new(Account, :name, :id) def format_referer(referer_url) begin referer = URI(referer_url || '') rescue URI::Error return end return unless referer.host referer_with_port = "#{referer.scheme}://#{referer.host}" referer_with_port += ":#{referer.port}" unless referer.port == (referer.scheme == 'https' ? 443 : 80) referer_with_port end def trusted_referers=(value) self.settings[:trusted_referers] = unless value.blank? value.split(',').map { |referer_url| format_referer(referer_url) }.compact.join(',') end end def trusted_referer?(referer_url) return if !self.settings.has_key?(:trusted_referers) || self.settings[:trusted_referers].blank? if referer_with_port = format_referer(referer_url) self.settings[:trusted_referers].split(',').include?(referer_with_port) end end def parent_registration? authentication_providers.where(parent_registration: true).exists? end def parent_auth_type return nil unless parent_registration? parent_registration_aac.auth_type end def parent_registration_aac authentication_providers.where(parent_registration: true).first end def to_param return 'site_admin' if site_admin? super end def create_default_objects work = -> do default_enrollment_term enable_canvas_authentication end return work.call if Rails.env.test? self.class.connection.after_transaction_commit(&work) end end
class Account < ActiveRecord::Base belongs_to :family validates_presence_of :name, :purpose, :family_id validates_uniqueness_of :name, :scope => :family_id Asset = "asset" Liability = "liability" Equity = "equity" Income = "income" Expense = "expense" ValidPurposes = [Asset, Liability, Equity, Income, Expense] before_validation {|a| a.purpose = a.purpose.downcase unless a.purpose.blank?} validates_inclusion_of :purpose, :in => ValidPurposes has_many :budgets, :order => "starting_on" named_scope :assets, :conditions => {:purpose => Asset} named_scope :liabilities, :conditions => {:purpose => Liability} named_scope :equities, :conditions => {:purpose => Equity} named_scope :incomes, :conditions => {:purpose => Income} named_scope :expenses, :conditions => {:purpose => Expense} named_scope :by_type_and_name, :order => "purpose, name" named_scope :purposes, lambda {|*purposes| {:conditions => {:purpose => purposes.flatten.compact}}} named_scope :by_most_debited, :select => "#{table_name}.*, SUM(#{Transfer.table_name}.amount) AS amount", :joins => "INNER JOIN #{Transfer.table_name} ON #{Transfer.table_name}.debit_account_id = #{table_name}.id", :order => "amount DESC", :group => "#{table_name}.family_id, #{table_name}.name, #{table_name}.purpose, #{table_name}.updated_at, #{table_name}.created_at, #{table_name}.id" named_scope :by_most_credited, :select => "#{table_name}.*, SUM(#{Transfer.table_name}.amount) AS amount", :joins => "INNER JOIN #{Transfer.table_name} ON #{Transfer.table_name}.credit_account_id = #{table_name}.id", :order => "amount DESC", :group => "#{table_name}.family_id, #{table_name}.name, #{table_name}.purpose, #{table_name}.updated_at, #{table_name}.created_at, #{table_name}.id" named_scope :in_period, lambda {|period| case period when /^(\d{4})-?(\d{2})/ year, month = $1.to_i, $2.to_i start = Date.new(year, month, 1) {:conditions => ["#{Transfer.table_name}.posted_on BETWEEN ? AND ?", start, (start >> 1) - 1]} when /^(\d{4})/ year = $1.to_i {:conditions => ["#{Transfer.table_name}.posted_on BETWEEN ? AND ?", Date.new(year, 1, 1), Date.new(year, 12, 31)]} when Date, Time, DateTime start = period.at_beginning_of_month.to_date {:conditions => ["#{Transfer.table_name}.posted_on BETWEEN ? AND ?", start, (start >> 1) - 1]} else {} end } attr_accessible :name, :purpose, :family def real_amount_in_period(year, month) debits = self.family.transfers.in_debit_accounts(self).in_year_month(year, month) credits = self.family.transfers.in_credit_accounts(self).in_year_month(year, month) debit_amount = debits.map(&:amount).compact.sum credit_amount = credits.map(&:amount).compact.sum normalize_amount(debit_amount, credit_amount) end def normalize_amount(debit_amount, credit_amount) case purpose when Asset, Expense debit_amount - credit_amount when Liability, Income, Equity credit_amount - debit_amount end end def budget_amount_in_period(year, month) self.budgets.for_account_year_month(self, year, month).map(&:amount).sum end def to_s name end ValidPurposes.each do |purpose| class_eval <<-EOF def #{purpose}? purpose == #{purpose.titleize} end EOF end class << self def most_active_income_in_period(period, options={}) in_period(period).purposes(Account::Income).by_most_credited.all end def most_active_expense_in_period(period, options={}) in_period(period).purposes(Account::Expense).by_most_debited.all end end end The default ordering of Family => Account was picked up, instead of amount class Account < ActiveRecord::Base belongs_to :family validates_presence_of :name, :purpose, :family_id validates_uniqueness_of :name, :scope => :family_id Asset = "asset" Liability = "liability" Equity = "equity" Income = "income" Expense = "expense" ValidPurposes = [Asset, Liability, Equity, Income, Expense] before_validation {|a| a.purpose = a.purpose.downcase unless a.purpose.blank?} validates_inclusion_of :purpose, :in => ValidPurposes has_many :budgets, :order => "starting_on" named_scope :assets, :conditions => {:purpose => Asset} named_scope :liabilities, :conditions => {:purpose => Liability} named_scope :equities, :conditions => {:purpose => Equity} named_scope :incomes, :conditions => {:purpose => Income} named_scope :expenses, :conditions => {:purpose => Expense} named_scope :by_type_and_name, :order => "purpose, name" named_scope :purposes, lambda {|*purposes| {:conditions => {:purpose => purposes.flatten.compact}}} named_scope :by_most_debited, :select => "#{table_name}.*, SUM(#{Transfer.table_name}.amount) AS amount", :joins => "INNER JOIN #{Transfer.table_name} ON #{Transfer.table_name}.debit_account_id = #{table_name}.id", :order => "amount DESC", :group => "#{table_name}.family_id, #{table_name}.name, #{table_name}.purpose, #{table_name}.updated_at, #{table_name}.created_at, #{table_name}.id" named_scope :by_most_credited, :select => "#{table_name}.*, SUM(#{Transfer.table_name}.amount) AS amount", :joins => "INNER JOIN #{Transfer.table_name} ON #{Transfer.table_name}.credit_account_id = #{table_name}.id", :order => "amount DESC", :group => "#{table_name}.family_id, #{table_name}.name, #{table_name}.purpose, #{table_name}.updated_at, #{table_name}.created_at, #{table_name}.id" named_scope :in_period, lambda {|period| case period when /^(\d{4})-?(\d{2})/ year, month = $1.to_i, $2.to_i start = Date.new(year, month, 1) {:conditions => ["#{Transfer.table_name}.posted_on BETWEEN ? AND ?", start, (start >> 1) - 1]} when /^(\d{4})/ year = $1.to_i {:conditions => ["#{Transfer.table_name}.posted_on BETWEEN ? AND ?", Date.new(year, 1, 1), Date.new(year, 12, 31)]} when Date, Time, DateTime start = period.at_beginning_of_month.to_date {:conditions => ["#{Transfer.table_name}.posted_on BETWEEN ? AND ?", start, (start >> 1) - 1]} else {} end } attr_accessible :name, :purpose, :family def real_amount_in_period(year, month) debits = self.family.transfers.in_debit_accounts(self).in_year_month(year, month) credits = self.family.transfers.in_credit_accounts(self).in_year_month(year, month) debit_amount = debits.map(&:amount).compact.sum credit_amount = credits.map(&:amount).compact.sum normalize_amount(debit_amount, credit_amount) end def normalize_amount(debit_amount, credit_amount) case purpose when Asset, Expense debit_amount - credit_amount when Liability, Income, Equity credit_amount - debit_amount end end def budget_amount_in_period(year, month) self.budgets.for_account_year_month(self, year, month).map(&:amount).sum end def to_s name end ValidPurposes.each do |purpose| class_eval <<-EOF def #{purpose}? purpose == #{purpose.titleize} end EOF end class << self def most_active_income_in_period(period, options={}) in_period(period).purposes(Account::Income).by_most_credited.all(:order => "amount DESC") end def most_active_expense_in_period(period, options={}) in_period(period).purposes(Account::Expense).by_most_debite.all(:order => "amount DESC") end end end
class Article < ActiveRecord::Base belongs_to :user has_many :taggings has_many :tags, :through => :taggings has_many :comments, :order => 'created_at' validates_presence_of :title, :user_id after_validation_on_create :create_permalink before_save :cache_redcloth after_save :save_taggings class << self def find_by_permalink(year, month, day, permalink) from, to = Time.delta(year, month, day) find :first, :conditions => ["published_at <= ? AND type IS NULL AND permalink = ? AND published_at BETWEEN ? AND ?", Time.now.utc, permalink, from, to] end def find_all_by_published_date(year, month, day = nil, options = {}) from, to = Time.delta(year, month, day) find(:all, options.merge(:order => 'published_at DESC', :conditions => ["published_at <= ? AND type IS NULL AND published_at BETWEEN ? AND ?", Time.now.utc, from, to])) end def count_by_published_date(year, month, day = nil) from, to = Time.delta(year, month, day) count ["published_at <= ? AND type IS NULL AND published_at BETWEEN ? AND ?", Time.now.utc, from, to] end end # Follow Mark Pilgrim's rules on creating a good ID # http://diveintomark.org/archives/2004/05/28/howto-atom-id def guid "/#{self.class.to_s.underscore}/#{published_at.year}/#{published_at.month}/#{published_at.day}/#{permalink}" end def published? not published_at.nil? end def pending? published? and Time.now.utc < published_at end def status return :unpublished unless published? return :pending if pending? :published end def tag_ids=(new_tags) taggings.each do |tagging| new_tags.include?(tagging.tag_id.to_s) ? new_tags.delete(new_tags.index(tagging.tag_id.to_s)) : tagging.destroy end @tags_to_save = Tag.find(:all, :conditions => ['id in (?)', new_tags]) end def to_liquid(mode = :list) { 'id' => id, 'title' => title, 'permalink' => permalink, 'url' => full_permalink, 'body' => body_for_mode(mode), 'published_at' => published_at, 'comments_count' => comments_count } end def hash_for_permalink(options = {}) { :year => published_at.year, :month => published_at.month, :day => published_at.day, :permalink => permalink }.merge(options) end def full_permalink ['', published_at.year, published_at.month, published_at.day, permalink].join('/') end protected def create_permalink self.permalink = title.to_permalink end def cache_redcloth self.summary_html = RedCloth.new(summary).to_html unless summary.blank? self.description_html = RedCloth.new(description).to_html unless description.blank? end def save_taggings @tags_to_save.each { |tag| taggings.create :tag => tag } if @tags_to_save end def body_for_mode(mode = :list) (mode == :single ? summary_html.to_s + "\n\n" + description_html.to_s : (summary_html || description_html)).strip end end Remove possible error from Article#create_permalink [court3nay] git-svn-id: 4158f9403e16ea83fe8a6e07a45f1f3b56a747ab@700 567b1171-46fb-0310-a4c9-b4bef9110e78 class Article < ActiveRecord::Base belongs_to :user has_many :taggings has_many :tags, :through => :taggings has_many :comments, :order => 'created_at' validates_presence_of :title, :user_id after_validation_on_create :create_permalink before_save :cache_redcloth after_save :save_taggings class << self def find_by_permalink(year, month, day, permalink) from, to = Time.delta(year, month, day) find :first, :conditions => ["published_at <= ? AND type IS NULL AND permalink = ? AND published_at BETWEEN ? AND ?", Time.now.utc, permalink, from, to] end def find_all_by_published_date(year, month, day = nil, options = {}) from, to = Time.delta(year, month, day) find(:all, options.merge(:order => 'published_at DESC', :conditions => ["published_at <= ? AND type IS NULL AND published_at BETWEEN ? AND ?", Time.now.utc, from, to])) end def count_by_published_date(year, month, day = nil) from, to = Time.delta(year, month, day) count ["published_at <= ? AND type IS NULL AND published_at BETWEEN ? AND ?", Time.now.utc, from, to] end end # Follow Mark Pilgrim's rules on creating a good ID # http://diveintomark.org/archives/2004/05/28/howto-atom-id def guid "/#{self.class.to_s.underscore}/#{published_at.year}/#{published_at.month}/#{published_at.day}/#{permalink}" end def published? not published_at.nil? end def pending? published? and Time.now.utc < published_at end def status return :unpublished unless published? return :pending if pending? :published end def tag_ids=(new_tags) taggings.each do |tagging| new_tags.include?(tagging.tag_id.to_s) ? new_tags.delete(new_tags.index(tagging.tag_id.to_s)) : tagging.destroy end @tags_to_save = Tag.find(:all, :conditions => ['id in (?)', new_tags]) end def to_liquid(mode = :list) { 'id' => id, 'title' => title, 'permalink' => permalink, 'url' => full_permalink, 'body' => body_for_mode(mode), 'published_at' => published_at, 'comments_count' => comments_count } end def hash_for_permalink(options = {}) { :year => published_at.year, :month => published_at.month, :day => published_at.day, :permalink => permalink }.merge(options) end def full_permalink ['', published_at.year, published_at.month, published_at.day, permalink].join('/') end protected def create_permalink self.permalink = title.to_permalink unless title.nil? end def cache_redcloth self.summary_html = RedCloth.new(summary).to_html unless summary.blank? self.description_html = RedCloth.new(description).to_html unless description.blank? end def save_taggings @tags_to_save.each { |tag| taggings.create :tag => tag } if @tags_to_save end def body_for_mode(mode = :list) (mode == :single ? summary_html.to_s + "\n\n" + description_html.to_s : (summary_html || description_html)).strip end end
class Channel < ApplicationRecord has_paper_trail belongs_to :publisher belongs_to :details, polymorphic: true, validate: true, autosave: true, optional: false, dependent: :delete belongs_to :site_channel_details, -> { where( channels: { details_type: 'SiteChannelDetails' } ) .includes( :channels ) }, foreign_key: 'details_id' belongs_to :youtube_channel_details, -> { where( channels: { details_type: 'YoutubeChannelDetails' } ) .includes( :channels ) }, foreign_key: 'details_id' belongs_to :twitch_channel_details, -> { where( channels: { details_type: 'TwitchChannelDetails' } ) .includes( :channels ) }, foreign_key: 'details_id' has_one :promo_registration, dependent: :destroy accepts_nested_attributes_for :details validate :details_not_changed? validates :verification_status, inclusion: { in: %w(started failed) }, allow_nil: true after_save :register_channel_for_promo, if: :should_register_channel_for_promo scope :site_channels, -> { joins(:site_channel_details) } scope :youtube_channels, -> { joins(:youtube_channel_details) } scope :twitch_channels, -> { joins(:twitch_channel_details) } # Once the verification_method has been set it shows we have presented the publisher with the token. We need to # ensure this site_channel will be preserved so the publisher cna come back to it. scope :visible_site_channels, -> { site_channels.where('channels.verified = true or NOT site_channel_details.verification_method IS NULL') } scope :visible_youtube_channels, -> { youtube_channels.where.not('youtube_channel_details.youtube_channel_id': nil) } scope :visible_twitch_channels, -> { twitch_channels.where.not('twitch_channel_details.twitch_channel_id': nil) } scope :visible, -> { left_outer_joins(:site_channel_details). where('channels.verified = true or NOT site_channel_details.verification_method IS NULL') } scope :verified, -> { where(verified: true) } scope :by_channel_identifier, -> (identifier) { case identifier.split("#")[0] when "twitch" visible_twitch_channels.where('twitch_channel_details.twitch_channel_id': identifier.split(":").last) when "youtube" visible_youtube_channels.where('youtube_channel_details.youtube_channel_id': identifier.split(":").last) else visible_site_channels.where('site_channel_details.brave_publisher_id': identifier) end } def publication_title details.publication_title end def details_not_changed? unless details_id_was.nil? || (details_id == details_id_was && details_type == details_type_was) errors.add(:details, "can't be changed") end end def channel_id channel_type = self.details_type case channel_type when "YoutubeChannelDetails" return self.details.youtube_channel_id when "SiteChannelDetails" return self.details.brave_publisher_id when "TwitchChannelDetails" return self.details.name else nil end end def promo_enabled? if self.promo_registration.present? if self.promo_registration.referral_code.present? return true end end false end def verification_started! update!(verified: false, verification_status: 'started', verification_details: nil) end def verification_failed!(details = nil) update!(verified: false, verification_status: 'failed', verification_details: details) end def verification_succeeded! update!(verified: true, verification_status: nil, verification_details: nil) end def verification_started? self.verification_status == 'started' end def verification_failed? self.verification_status == 'failed' end private def should_register_channel_for_promo promo_running = Rails.application.secrets[:active_promo_id].present? # Could use PromosHelper#active_promo_id publisher_enabled_promo = self.publisher.promo_enabled_2018q1? promo_running && publisher_enabled_promo && verified_changed? && verified end def register_channel_for_promo RegisterChannelForPromoJob.new.perform(channel: self) end end Add comment explaining Channel#channel_id class Channel < ApplicationRecord has_paper_trail belongs_to :publisher belongs_to :details, polymorphic: true, validate: true, autosave: true, optional: false, dependent: :delete belongs_to :site_channel_details, -> { where( channels: { details_type: 'SiteChannelDetails' } ) .includes( :channels ) }, foreign_key: 'details_id' belongs_to :youtube_channel_details, -> { where( channels: { details_type: 'YoutubeChannelDetails' } ) .includes( :channels ) }, foreign_key: 'details_id' belongs_to :twitch_channel_details, -> { where( channels: { details_type: 'TwitchChannelDetails' } ) .includes( :channels ) }, foreign_key: 'details_id' has_one :promo_registration, dependent: :destroy accepts_nested_attributes_for :details validate :details_not_changed? validates :verification_status, inclusion: { in: %w(started failed) }, allow_nil: true after_save :register_channel_for_promo, if: :should_register_channel_for_promo scope :site_channels, -> { joins(:site_channel_details) } scope :youtube_channels, -> { joins(:youtube_channel_details) } scope :twitch_channels, -> { joins(:twitch_channel_details) } # Once the verification_method has been set it shows we have presented the publisher with the token. We need to # ensure this site_channel will be preserved so the publisher cna come back to it. scope :visible_site_channels, -> { site_channels.where('channels.verified = true or NOT site_channel_details.verification_method IS NULL') } scope :visible_youtube_channels, -> { youtube_channels.where.not('youtube_channel_details.youtube_channel_id': nil) } scope :visible_twitch_channels, -> { twitch_channels.where.not('twitch_channel_details.twitch_channel_id': nil) } scope :visible, -> { left_outer_joins(:site_channel_details). where('channels.verified = true or NOT site_channel_details.verification_method IS NULL') } scope :verified, -> { where(verified: true) } scope :by_channel_identifier, -> (identifier) { case identifier.split("#")[0] when "twitch" visible_twitch_channels.where('twitch_channel_details.twitch_channel_id': identifier.split(":").last) when "youtube" visible_youtube_channels.where('youtube_channel_details.youtube_channel_id': identifier.split(":").last) else visible_site_channels.where('site_channel_details.brave_publisher_id': identifier) end } def publication_title details.publication_title end def details_not_changed? unless details_id_was.nil? || (details_id == details_id_was && details_type == details_type_was) errors.add(:details, "can't be changed") end end # NOTE This method is should only be used in referral promo logic. Use {channel}.details.channel_identifer for everything else. # This will return the channel_identifier without the youtube#channel: or twitch#channel: prefix def channel_id channel_type = self.details_type case channel_type when "YoutubeChannelDetails" return self.details.youtube_channel_id when "SiteChannelDetails" return self.details.brave_publisher_id when "TwitchChannelDetails" return self.details.name else nil end end def promo_enabled? if self.promo_registration.present? if self.promo_registration.referral_code.present? return true end end false end def verification_started! update!(verified: false, verification_status: 'started', verification_details: nil) end def verification_failed!(details = nil) update!(verified: false, verification_status: 'failed', verification_details: details) end def verification_succeeded! update!(verified: true, verification_status: nil, verification_details: nil) end def verification_started? self.verification_status == 'started' end def verification_failed? self.verification_status == 'failed' end private def should_register_channel_for_promo promo_running = Rails.application.secrets[:active_promo_id].present? # Could use PromosHelper#active_promo_id publisher_enabled_promo = self.publisher.promo_enabled_2018q1? promo_running && publisher_enabled_promo && verified_changed? && verified end def register_channel_for_promo RegisterChannelForPromoJob.new.perform(channel: self) end end
class Checkin < ActiveRecord::Base attr_accessible :item_identifier, :librarian_id, :auto_checkin default_scope :order => 'id DESC' scope :on, lambda {|date| {:conditions => ['created_at >= ? AND created_at < ?', date.beginning_of_day, date.tomorrow.beginning_of_day]}} has_one :checkout belongs_to :item belongs_to :librarian, :class_name => 'User' belongs_to :basket validates_presence_of :item, :basket, :on => :update validates_associated :item, :librarian, :basket, :on => :update validates_presence_of :item_identifier, :on => :create attr_accessor :item_identifier attr_accessible :item_id after_create :store_history def item_checkin(current_user, escape_flag = false) message = [] Checkin.transaction do checkouts = Checkout.not_returned.where(:item_id => self.item_id).select([:id, :item_id, :lock_version]) self.item.checkin! rescue nil # unless escape_flag #message << I18n.t('item.this_item_include_supplement') + '<br />' if self.item.include_supplements? message << 'item.this_item_include_supplement' if self.item.include_supplements? # for item on closing shelf message << 'item.close_shelf' unless self.item.shelf.open? checkouts.each do |checkout| # TODO: ILL時の処理 checkout.checkin = self logger.error "**** before checkout save: #{checkout.attributes}" checkout.save(:validate => false) logger.error "*** checkout saved" #message << I18n.t('checkin.other_library_item') + '<br />' unless checkout.item.shelf.library == current_user.library unless escape_flag unless checkout.item.shelf.library == current_user.library message << 'checkin.other_library_item' InterLibraryLoan.new.request_for_checkin(self.item, current_user.library) return end end end # checkout.user = nil unless checkout.user.save_checkout_history unless escape_flag if self.item.manifestation.next_reservation # TODO: もっと目立たせるために別画面を表示するべき? #message << I18n.t('item.this_item_is_reserved') + '<br />' message << 'item.this_item_is_reserved' self.item.retain(current_user) end end # メールとメッセージの送信 #ReservationNotifier.deliver_reserved(self.item.manifestation.reserves.first.user, self.item.manifestation) #Message.create(:sender => current_user, :receiver => self.item.manifestation.next_reservation.user, :subject => message_template.title, :body => message_template.body, :recipient => self.item.manifestation.next_reservation.user) end if message.present? message else nil end end def store_history CheckoutHistory.store_history("checkin", self) unless self.auto_checkin end end # == Schema Information # # Table name: checkins # # id :integer not null, primary key # item_id :integer not null # librarian_id :integer # basket_id :integer # created_at :datetime # updated_at :datetime # refs 4083 delete from reminder list when after checkin class Checkin < ActiveRecord::Base attr_accessible :item_identifier, :librarian_id, :auto_checkin default_scope :order => 'id DESC' scope :on, lambda {|date| {:conditions => ['created_at >= ? AND created_at < ?', date.beginning_of_day, date.tomorrow.beginning_of_day]}} has_one :checkout belongs_to :item belongs_to :librarian, :class_name => 'User' belongs_to :basket validates_presence_of :item, :basket, :on => :update validates_associated :item, :librarian, :basket, :on => :update validates_presence_of :item_identifier, :on => :create attr_accessor :item_identifier attr_accessible :item_id after_create :store_history def item_checkin(current_user, escape_flag = false) message = [] Checkin.transaction do checkouts = Checkout.not_returned.where(:item_id => self.item_id).select([:id, :item_id, :lock_version]) self.item.checkin! rescue nil # unless escape_flag #message << I18n.t('item.this_item_include_supplement') + '<br />' if self.item.include_supplements? message << 'item.this_item_include_supplement' if self.item.include_supplements? # for item on closing shelf message << 'item.close_shelf' unless self.item.shelf.open? checkouts.each do |checkout| # TODO: ILL時の処理 checkout.checkin = self checkout.save(:validate => false) # delete from reminder list ReminderList.delete_all(:checkout_id => checkout.id) #message << I18n.t('checkin.other_library_item') + '<br />' unless checkout.item.shelf.library == current_user.library unless escape_flag unless checkout.item.shelf.library == current_user.library message << 'checkin.other_library_item' InterLibraryLoan.new.request_for_checkin(self.item, current_user.library) return end end end # checkout.user = nil unless checkout.user.save_checkout_history unless escape_flag if self.item.manifestation.next_reservation # TODO: もっと目立たせるために別画面を表示するべき? #message << I18n.t('item.this_item_is_reserved') + '<br />' message << 'item.this_item_is_reserved' self.item.retain(current_user) end end # メールとメッセージの送信 #ReservationNotifier.deliver_reserved(self.item.manifestation.reserves.first.user, self.item.manifestation) #Message.create(:sender => current_user, :receiver => self.item.manifestation.next_reservation.user, :subject => message_template.title, :body => message_template.body, :recipient => self.item.manifestation.next_reservation.user) end if message.present? message else nil end end def store_history CheckoutHistory.store_history("checkin", self) unless self.auto_checkin end end # == Schema Information # # Table name: checkins # # id :integer not null, primary key # item_id :integer not null # librarian_id :integer # basket_id :integer # created_at :datetime # updated_at :datetime #
class Citizen < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :profile, :profile_attributes has_one :authentication, dependent: :destroy has_one :profile, dependent: :destroy has_many :ideas, foreign_key: "author_id" has_many :comments, foreign_key: "author_id" has_many :idea_comments, through: :ideas accepts_nested_attributes_for :profile [ :first_name, :last_name, :name ].each { |attribute| delegate attribute, to: :profile } def self.find_for_facebook_auth(auth_hash) auth = Authentication.where(provider: auth_hash[:provider], uid: auth_hash[:uid]).first auth && auth.citizen || nil end def self.build_from_auth_hash(auth_hash) info = auth_hash[:extra][:raw_info] c = Citizen.where(email: info[:email]).first c ||= Citizen.new email: info[:email], password: Devise.friendly_token[0,20], profile: Profile.new(first_name: info[:first_name], last_name: info[:last_name]) c.authentication = Authentication.new provider: auth_hash[:provider], uid: auth_hash[:uid], citizen: c c.save! c end private after_initialize do |citizen| citizen.build_profile unless citizen.profile end end Store all auth data available to the db. class Citizen < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :profile, :profile_attributes has_one :authentication, dependent: :destroy has_one :profile, dependent: :destroy has_many :ideas, foreign_key: "author_id" has_many :comments, foreign_key: "author_id" has_many :idea_comments, through: :ideas accepts_nested_attributes_for :profile [ :first_name, :last_name, :name ].each { |attribute| delegate attribute, to: :profile } def self.find_for_facebook_auth(auth_hash) auth = Authentication.where(provider: auth_hash[:provider], uid: auth_hash[:uid]).first auth && auth.citizen || nil end def self.build_from_auth_hash(auth_hash) info = auth_hash[:extra][:raw_info] c = Citizen.where(email: info[:email]).first c ||= Citizen.new email: info[:email], password: Devise.friendly_token[0,20], profile: Profile.new(first_name: info[:first_name], last_name: info[:last_name]) c.authentication = Authentication.new provider: auth_hash[:provider], uid: auth_hash[:uid], citizen: c, info: auth_hash[:info], credentials: auth_hash[:credentials], extra: auth_hash[:extra] c.save! c end private after_initialize do |citizen| citizen.build_profile unless citizen.profile end end
# == Schema Information # # Table name: clientes # # id :integer not null, primary key # nombre :string(255) # direccion :string(255) # numero_de_identificacion :string(255) # telefono :string(255) # email :string(255) # created_at :datetime # updated_at :datetime # class Cliente < ActiveRecord::Base #validations # relationships has_one :user has_many :proformas has_many :facturas #method end agregado validacion de la cedula # == Schema Information # # Table name: clientes # # id :integer not null, primary key # nombre :string(255) # direccion :string(255) # numero_de_identificacion :string(255) # telefono :string(255) # email :string(255) # created_at :datetime # updated_at :datetime # class Cliente < ActiveRecord::Base #validations validates :nombre, :numero_de_identificacion, :presence =>true validates_id :numero_de_identificacion # relationships has_one :user has_many :proformas has_many :facturas #method end
class Comment < ActiveRecord::Base include ActsAsCommentable::Comment belongs_to :commentable, :polymorphic => true default_scope :order => 'created_at DESC' # NOTE: install the acts_as_votable plugin if you # want user to vote on the quality of comments. #acts_as_voteable # NOTE: Comments belong to a user belongs_to :user def date "#{self.created_at.time.month}-#{self.created_at.time.day}-#{self.created_at.time.year}" end def time_formatted if self.created_at.time.hour > 12 @hour = self.created_at.time.hour - 12 @ampm = 'pm' else @hour = self.created_at.time.hour @ampm = 'am' end if self.created_at.time.min < 10 @min = '0' + self.created_at.time.min.to_s else @min = self.created_at.time.min end "#{@hour}:#{@min} #{@ampm}" end end [MODEL] removed unnecessary methods class Comment < ActiveRecord::Base include ActsAsCommentable::Comment belongs_to :commentable, :polymorphic => true default_scope :order => 'created_at DESC' # NOTE: install the acts_as_votable plugin if you # want user to vote on the quality of comments. #acts_as_voteable # NOTE: Comments belong to a user belongs_to :user end
require 'digest/md5' class Comment < ActiveRecord::Base include ActionView::Helpers::SanitizeHelper extend ActionView::Helpers::SanitizeHelper::ClassMethods belongs_to :page, :counter_cache => true validate :validate_spam_answer validates_presence_of :author, :author_email, :content before_save :auto_approve before_save :apply_filter after_save :save_mollom_servers attr_accessor :valid_spam_answer, :spam_answer attr_accessible :author, :author_email, :author_url, :filter_id, :content, :valid_spam_answer, :spam_answer def self.per_page count = Radiant::Config['comments.per_page'].to_i.abs count > 0 ? count : 50 end def request=(request) self.author_ip = request.remote_ip self.user_agent = request.env['HTTP_USER_AGENT'] self.referrer = request.env['HTTP_REFERER'] end def akismet @akismet ||= Akismet.new(Radiant::Config['comments.akismet_key'], Radiant::Config['comments.akismet_url']) end def save_mollom_servers Rails.cache.write('MOLLOM_SERVER_CACHE', mollom.server_list.to_yaml) if mollom.key_ok? rescue Mollom::Error #TODO: something with this error... end def mollom return @mollom if @mollom @mollom ||= Mollom.new(:private_key => Radiant::Config['comments.mollom_privatekey'], :public_key => Radiant::Config['comments.mollom_publickey']) unless Rails.cache.read('MOLLOM_SERVER_CACHE').blank? @mollom.server_list = YAML::load(Rails.cache.read('MOLLOM_SERVER_CACHE')) end @mollom end # If the Akismet details are valid, and Akismet thinks this is a non-spam # comment, this method will return true def auto_approve? if using_logic_spam_filter? passes_logic_spam_filter? elsif akismet.valid? # We do the negation because true means spam, false means ham !akismet.commentCheck( self.author_ip, # remote IP self.user_agent, # user agent self.referrer, # http referer self.page.url, # permalink 'comment', # comment type self.author, # author name self.author_email, # author email self.author_url, # author url self.content, # comment text {} # other ) elsif mollom.key_ok? response = mollom.check_content( :author_name => self.author, # author name :author_mail => self.author_email, # author email :author_url => self.author_url, # author url :post_body => self.content # comment text ) ham = response.ham? self.mollom_id = response.session_id response.ham? else false end rescue Mollom::Error return false end def unapproved? !approved? end def approved? !approved_at.nil? end def ap_status if approved? "approved" else "unapproved" end end def approve! self.update_attribute(:approved_at, Time.now) end def unapprove! self.update_attribute(:approved_at, nil) # if we have to unapprove, and use mollom, it means # the initial check was false. Submit this to mollom as Spam. # Ideally, we'd need a different feedback for # - spam # - profanity # - unwanted # - low-quality begin if mollom.key_ok? and !self.mollom_id.empty? mollom.send_feedback :session_id => self.mollom_id, :feedback => 'spam' end rescue Mollom::Error => e raise Comment::AntispamWarning.new(e.to_s) end end private def validate_spam_answer if using_logic_spam_filter? && !passes_logic_spam_filter? self.errors.add :spam_answer, "is not correct." end end def passes_logic_spam_filter? if valid_spam_answer == hashed_spam_answer true else false end end def using_logic_spam_filter? !valid_spam_answer.blank? end def hashed_spam_answer Digest::MD5.hexdigest(spam_answer.to_s.to_slug) end def auto_approve self.approved_at = Time.now if auto_approve? end def apply_filter self.content_html = sanitize(filter.filter(content)) end def filter if filtering_enabled? && filter_from_form filter_from_form else SimpleFilter.new end end def filter_from_form TextFilter.descendants.find { |f| f.filter_name == filter_id } end def filtering_enabled? Radiant::Config['comments.filters_enabled'] == "true" end class SimpleFilter include ERB::Util include ActionView::Helpers::TextHelper include ActionView::Helpers::TagHelper def filter(content) simple_format(h(content)) end end class AntispamWarning < StandardError; end end Comment#auto_approve? should return false if comments.auto_approve isn't set tu true. Signed-off-by: Jim Gay <1cd02e31b43620d7c664e038ca42a060d61727b9@saturnflyer.com> require 'digest/md5' class Comment < ActiveRecord::Base include ActionView::Helpers::SanitizeHelper extend ActionView::Helpers::SanitizeHelper::ClassMethods belongs_to :page, :counter_cache => true validate :validate_spam_answer validates_presence_of :author, :author_email, :content before_save :auto_approve before_save :apply_filter after_save :save_mollom_servers attr_accessor :valid_spam_answer, :spam_answer attr_accessible :author, :author_email, :author_url, :filter_id, :content, :valid_spam_answer, :spam_answer def self.per_page count = Radiant::Config['comments.per_page'].to_i.abs count > 0 ? count : 50 end def request=(request) self.author_ip = request.remote_ip self.user_agent = request.env['HTTP_USER_AGENT'] self.referrer = request.env['HTTP_REFERER'] end def akismet @akismet ||= Akismet.new(Radiant::Config['comments.akismet_key'], Radiant::Config['comments.akismet_url']) end def save_mollom_servers Rails.cache.write('MOLLOM_SERVER_CACHE', mollom.server_list.to_yaml) if mollom.key_ok? rescue Mollom::Error #TODO: something with this error... end def mollom return @mollom if @mollom @mollom ||= Mollom.new(:private_key => Radiant::Config['comments.mollom_privatekey'], :public_key => Radiant::Config['comments.mollom_publickey']) unless Rails.cache.read('MOLLOM_SERVER_CACHE').blank? @mollom.server_list = YAML::load(Rails.cache.read('MOLLOM_SERVER_CACHE')) end @mollom end # If the Akismet details are valid, and Akismet thinks this is a non-spam # comment, this method will return true def auto_approve? return false if Radiant::Config['comments.auto_approve'] != "true" if using_logic_spam_filter? passes_logic_spam_filter? elsif akismet.valid? # We do the negation because true means spam, false means ham !akismet.commentCheck( self.author_ip, # remote IP self.user_agent, # user agent self.referrer, # http referer self.page.url, # permalink 'comment', # comment type self.author, # author name self.author_email, # author email self.author_url, # author url self.content, # comment text {} # other ) elsif mollom.key_ok? response = mollom.check_content( :author_name => self.author, # author name :author_mail => self.author_email, # author email :author_url => self.author_url, # author url :post_body => self.content # comment text ) ham = response.ham? self.mollom_id = response.session_id response.ham? else false end rescue Mollom::Error return false end def unapproved? !approved? end def approved? !approved_at.nil? end def ap_status if approved? "approved" else "unapproved" end end def approve! self.update_attribute(:approved_at, Time.now) end def unapprove! self.update_attribute(:approved_at, nil) # if we have to unapprove, and use mollom, it means # the initial check was false. Submit this to mollom as Spam. # Ideally, we'd need a different feedback for # - spam # - profanity # - unwanted # - low-quality begin if mollom.key_ok? and !self.mollom_id.empty? mollom.send_feedback :session_id => self.mollom_id, :feedback => 'spam' end rescue Mollom::Error => e raise Comment::AntispamWarning.new(e.to_s) end end private def validate_spam_answer if using_logic_spam_filter? && !passes_logic_spam_filter? self.errors.add :spam_answer, "is not correct." end end def passes_logic_spam_filter? if valid_spam_answer == hashed_spam_answer true else false end end def using_logic_spam_filter? !valid_spam_answer.blank? end def hashed_spam_answer Digest::MD5.hexdigest(spam_answer.to_s.to_slug) end def auto_approve self.approved_at = Time.now if auto_approve? end def apply_filter self.content_html = sanitize(filter.filter(content)) end def filter if filtering_enabled? && filter_from_form filter_from_form else SimpleFilter.new end end def filter_from_form TextFilter.descendants.find { |f| f.filter_name == filter_id } end def filtering_enabled? Radiant::Config['comments.filters_enabled'] == "true" end class SimpleFilter include ERB::Util include ActionView::Helpers::TextHelper include ActionView::Helpers::TagHelper def filter(content) simple_format(h(content)) end end class AntispamWarning < StandardError; end end
# == Schema Information # Schema version: 20080819191919 # # Table name: companies # # id :integer not null, primary key # name :string(255) not null # code :string(8) not null # siren :string(9) # born_on :date # locked :boolean not null # deleted :boolean not null # created_at :datetime not null # updated_at :datetime not null # created_by :integer # updated_by :integer # lock_version :integer default(0), not null # class Company < ActiveRecord::Base has_many :users def before_validation self.code = name.to_s[0..7].simpleize if code.blank? self.code = rand.to_s[2..100].to_i.to_s(36)[0..7] if code.blank? self.code.upper! while Company.count(:conditions=>["code=? AND id!=?",self.code, self.id])>0 do self.code.succ! end self.siren = '123456789' if self.siren.blank? end def after_create role = Role.create!(:name=>lc(:administrator), :company_id=>self.id) role.can_do :all role = Role.create!(:name=>lc(:public), :company_id=>self.id) self.parameter('general.language').value=Language.find_by_iso2('fr') self.load_template("#{RAILS_ROOT}/lib/template.xml") self.departments.create(:name=>lc(:default_department_name)) self.establishments.create(:name=>lc(:default_establishment_name), :nic=>"00000") self.journal_natures.create(:name=>lc(:default_sales_journal_nature_name)) self.journal_natures.create(:name=>lc(:default_purchases_journal_nature_name)) self.journal_natures.create(:name=>lc(:default_bank_journal_nature_name)) self.journal_natures.create(:name=>lc(:default_operations_journal_nature_name)) self.load_accounting_system end def parameter(name) parameter = Parameter.find_by_name_and_company_id(name,self.id) parameter = Parameter.new(:name=>name, :nature=>:u, :company_id=>self.id) parameter end def load_accounting_system for a in 1..8 self.accounts.create!(:number=>a.to_s, :name=>l(:accounting_system, a.to_sym)) end end def load_template(filename) f = File.open(filename,'rb') Template.create!(:name=>filename.simpleize,:company_id=>self.id, :content=>f.read) f.close end def admin_role self.roles.find(:first, :conditions=>"actions=' all '") end end git-svn-id: https://www.ekylibre.org/svn/trunk/ekylibre@128 67a09383-3dfa-4221-8551-890bac9c277c # == Schema Information # Schema version: 20080819191919 # # Table name: companies # # id :integer not null, primary key # name :string(255) not null # code :string(8) not null # siren :string(9) # born_on :date # locked :boolean not null # deleted :boolean not null # created_at :datetime not null # updated_at :datetime not null # created_by :integer # updated_by :integer # lock_version :integer default(0), not null # class Company < ActiveRecord::Base has_many :users def before_validation self.code = name.to_s[0..7].simpleize if code.blank? self.code = rand.to_s[2..100].to_i.to_s(36)[0..7] if code.blank? self.code.upper! while Company.count(:conditions=>["code=? AND id!=?",self.code, self.id])>0 do self.code.succ! end self.siren = '123456789' if self.siren.blank? end def after_create role = Role.create!(:name=>lc(:administrator), :company_id=>self.id) role.can_do :all role = Role.create!(:name=>lc(:public), :company_id=>self.id) self.parameter('general.language').value=Language.find_by_iso2('fr') self.load_template("#{RAILS_ROOT}/lib/template.xml") self.departments.create(:name=>lc(:default_department_name)) self.establishments.create(:name=>lc(:default_establishment_name), :nic=>"00000") self.journal_natures.create(:name=>lc(:default_sales_journal_nature_name)) self.journal_natures.create(:name=>lc(:default_purchases_journal_nature_name)) self.journal_natures.create(:name=>lc(:default_bank_journal_nature_name)) self.journal_natures.create(:name=>lc(:default_operations_journal_nature_name)) # self.load_accounting_system end def parameter(name) parameter = Parameter.find_by_name_and_company_id(name,self.id) parameter = Parameter.new(:name=>name, :nature=>:u, :company_id=>self.id) parameter end def load_accounting_system for a in 1..8 self.accounts.create!(:number=>a.to_s, :name=>l(:accounting_system, a.to_sym)) end end def load_template(filename) f = File.open(filename,'rb') Template.create!(:name=>filename.simpleize,:company_id=>self.id, :content=>f.read) f.close end def admin_role self.roles.find(:first, :conditions=>"actions=' all '") end end
class Compare def initialize(fest1, fest2) @fest1 = fest1 @fest2 = fest2 end def artists_in_common @fest1.artists.select do |a| @fest2.artists.include?(a) end end def unique_artists(fest) fest.artists.select {|artist| !artists_in_common.include?(artist)} end end change unique artists method to make more efficient fingers crossed class Compare def initialize(fest1, fest2) @fest1 = fest1 @fest2 = fest2 end def artists_in_common @fest1.artists.select do |a| @fest2.artists.include?(a) end end def unique_artists(fest) a = artists_in_common fest.artists.select {|artist| !a.include?(artist)} end end
class Contest < ApplicationRecord has_many :problems has_many :data_sets, through: :problems has_many :submissions, through: :problems has_many :contest_registrations has_many :users, through: :contest_registrations def preparing? start_at > Time.now end def started? start_at < Time.now end def ended? end_at < Time.now end def during? started? && !ended? end def name_and_description(lang) { id: id, name: lang == :ja ? name_ja : name_en, description: lang == :ja ? description_ja : description_en, start_at: start_at, end_at: end_at } end def problems_to_show(user_id, lang) { problems: problems.map do |problem| { id: problem.id, name: lang == :ja ? problem.name_ja : problem.name_en, description: lang == :ja ? problem.description_ja : problem.description_en }.merge(problem.label_and_score(user_id)) end } end def problems_for_ranking(user_id) { problems: problems.map do |problem| { id: problem.id }.merge(problem.label_score_solved_at(user_id)) end } end def registered_by?(user) ContestRegistration.find_by(user_id: user.id, contest_id: id).present? end def register(user) ContestRegistration.create(user_id: user.id, contest_id: id) end def users_sorted_by_rank users.sort { |a, b| b.score_for_contest(self) <=> a.score_for_contest(self) } end end Fix problems order #133 class Contest < ApplicationRecord has_many :problems has_many :data_sets, through: :problems has_many :submissions, through: :problems has_many :contest_registrations has_many :users, through: :contest_registrations def preparing? start_at > Time.now end def started? start_at < Time.now end def ended? end_at < Time.now end def during? started? && !ended? end def name_and_description(lang) { id: id, name: lang == :ja ? name_ja : name_en, description: lang == :ja ? description_ja : description_en, start_at: start_at, end_at: end_at } end def problems_to_show(user_id, lang) { problems: problems.order(order: :asc).map do |problem| { id: problem.id, name: lang == :ja ? problem.name_ja : problem.name_en, description: lang == :ja ? problem.description_ja : problem.description_en }.merge(problem.label_and_score(user_id)) end } end def problems_for_ranking(user_id) { problems: problems.order(order: :asc).map do |problem| { id: problem.id }.merge(problem.label_score_solved_at(user_id)) end } end def registered_by?(user) ContestRegistration.find_by(user_id: user.id, contest_id: id).present? end def register(user) ContestRegistration.create(user_id: user.id, contest_id: id) end def users_sorted_by_rank users.sort { |a, b| b.score_for_contest(self) <=> a.score_for_contest(self) } end end
class Dataset < ApplicationRecord belongs_to :user has_many :commits has_many :edits, through: :commits, source: :dataset_edits validates :geo_id, presence: true validates :name, presence: true def self.clones(dataset, user) where(geo_id: dataset.geo_id) .order("FIELD(`id`, #{dataset.id}) DESC, `created_at` DESC") end def group if geo_id =~ /^GM/ or geo_id =~ /^BEGM/ 'municipality' elsif geo_id =~ /^WK/ 'district' elsif geo_id =~ /^BU/ 'neighbourhood' elsif geo_id =~ /^RG/ 'region' else 'province' end end def as_json(*) super .except('created_at', 'updated_at') .merge(group: I18n.t("datasets.area_groups.#{group}")) end # Public: country # # All the regions of ETLocal currently lie within the borders of Holland. def country 'nl'.freeze end def atlas_dataset Etsource.datasets[geo_id] end def chart_id if is_province? geo_id.titleize.sub(/\s/, '-') else geo_id end end def editable_attributes @editable_attributes ||= EditableAttributesCollection.new(self) end # Public: A version of the dataset name with normalize unicode characters, and # any non-alphanumeric characters removed. # # Returns a string. def normalized_name name.strip.mb_chars.normalize(:kd).to_s .downcase.gsub(/[^0-9a-z_\s\-]/, '').gsub(/[\s_-]+/, '_') end def temp_name @temp_name ||= "#{SecureRandom.hex(10)}-#{normalized_name}" end def creator @creator ||= begin if user.group user.group.key.humanize else user.name end end end private def is_province? !(geo_id =~ /^(BU|GM|WK)/) end end assign RES datasets to region group, Belgian BU datasets to neighbourhoods class Dataset < ApplicationRecord belongs_to :user has_many :commits has_many :edits, through: :commits, source: :dataset_edits validates :geo_id, presence: true validates :name, presence: true def self.clones(dataset, user) where(geo_id: dataset.geo_id) .order("FIELD(`id`, #{dataset.id}) DESC, `created_at` DESC") end def group if geo_id =~ /^GM/ or geo_id =~ /^BEGM/ 'municipality' elsif geo_id =~ /^WK/ 'district' elsif geo_id =~ /^BU/ or geo_id =~ /^BEBU/ 'neighbourhood' elsif geo_id =~ /^RG/ or geo_id =~ /^RES/ 'region' else 'province' end end def as_json(*) super .except('created_at', 'updated_at') .merge(group: I18n.t("datasets.area_groups.#{group}")) end # Public: country # # All the regions of ETLocal currently lie within the borders of Holland. def country 'nl'.freeze end def atlas_dataset Etsource.datasets[geo_id] end def chart_id if is_province? geo_id.titleize.sub(/\s/, '-') else geo_id end end def editable_attributes @editable_attributes ||= EditableAttributesCollection.new(self) end # Public: A version of the dataset name with normalize unicode characters, and # any non-alphanumeric characters removed. # # Returns a string. def normalized_name name.strip.mb_chars.normalize(:kd).to_s .downcase.gsub(/[^0-9a-z_\s\-]/, '').gsub(/[\s_-]+/, '_') end def temp_name @temp_name ||= "#{SecureRandom.hex(10)}-#{normalized_name}" end def creator @creator ||= begin if user.group user.group.key.humanize else user.name end end end private def is_province? !(geo_id =~ /^(BU|GM|WK)/) end end
# The base class for all editoral content. It configures the searchable options and callbacks. # @abstract Using STI should not create editions directly. class Edition < ActiveRecord::Base include Edition::Traits include Edition::NullImages include Edition::NullWorldLocations include Edition::Identifiable include Edition::LimitedAccess include Edition::Workflow include Edition::Publishing include Edition::AuditTrail include Edition::ActiveEditors include Edition::Translatable include Edition::SpecialistSectors serialize :need_ids, Array # This mixin should go away when we switch to a search backend for admin documents extend Edition::FindableByOrganisation include Searchable has_many :editorial_remarks, dependent: :destroy has_many :edition_authors, dependent: :destroy has_many :authors, through: :edition_authors, source: :user has_many :classification_featurings, inverse_of: :edition has_many :links_reports, as: :link_reportable validates_with SafeHtmlValidator validates_with NoFootnotesInGovspeakValidator, attribute: :body validates :creator, presence: true validates :title, presence: true, if: :title_required? validates :body, presence: true, if: :body_required? validates :summary, presence: true, if: :summary_required? validates :first_published_at, recent_date: true, allow_blank: true validate :need_ids_are_six_digit_integers? UNMODIFIABLE_STATES = %w(scheduled published superseded deleted).freeze FROZEN_STATES = %w(superseded deleted).freeze PRE_PUBLICATION_STATES = %w(imported draft submitted rejected scheduled).freeze POST_PUBLICATION_STATES = %w(published superseded archived).freeze PUBLICLY_VISIBLE_STATES = %w(published archived).freeze scope :with_title_or_summary_containing, -> *keywords { pattern = "(#{keywords.map { |k| Regexp.escape(k) }.join('|')})" in_default_locale.where("edition_translations.title REGEXP :pattern OR edition_translations.summary REGEXP :pattern", pattern: pattern) } scope :with_title_containing, -> *keywords { bind_parameters = {} where_clause_parts = [] keywords.map.with_index do |keyword, i| parameter_name = :"pattern#{i}" escaped_like_expression = keyword.gsub(/([%_])/, '%' => '\\%', '_' => '\\_') bind_parameters[parameter_name] = "%#{escaped_like_expression}%" where_clause_parts << "edition_translations.title LIKE :#{parameter_name}" end where_clause_parts << "documents.slug = :slug" bind_parameters[:slug] = keywords in_default_locale .includes(:document) .where(where_clause_parts.join(" OR "), bind_parameters) } scope :force_published, -> { where(state: "published", force_published: true) } scope :not_published, -> { where(state: %w(draft submitted rejected)) } scope :announcements, -> { where(type: Announcement.concrete_descendants.collect(&:name)) } scope :consultations, -> { where(type: "Consultation") } scope :detailed_guides, -> { where(type: "DetailedGuide") } scope :policies, -> { where(type: "Policy") } scope :statistical_publications, -> { where("publication_type_id IN (?)", PublicationType.statistical.map(&:id)) } scope :non_statistical_publications, -> { where("publication_type_id NOT IN (?)", PublicationType.statistical.map(&:id)) } scope :corporate_publications, -> { where(publication_type_id: PublicationType::CorporateReport.id) } scope :worldwide_priorities, -> { where(type: "WorldwidePriority") } scope :corporate_information_pages, -> { where(type: "CorporateInformationPage") } scope :publicly_visible, -> { where(state: PUBLICLY_VISIBLE_STATES) } # @!group Callbacks before_save :set_public_timestamp # @!endgroup class UnmodifiableValidator < ActiveModel::Validator def validate(record) significant_changed_attributes(record).each do |attribute| record.errors.add(attribute, "cannot be modified when edition is in the #{record.state} state") end end def significant_changed_attributes(record) record.changed - modifiable_attributes(record.state_was, record.state) end def modifiable_attributes(previous_state, current_state) modifiable = %w{state updated_at force_published} if previous_state == 'scheduled' modifiable += %w{major_change_published_at first_published_at access_limited} end if PRE_PUBLICATION_STATES.include?(previous_state) || being_unpublished?(previous_state, current_state) modifiable += %w{published_major_version published_minor_version} end modifiable end def being_unpublished?(previous_state, current_state) previous_state == 'published' && %w(draft archived).include?(current_state) end end validates_with UnmodifiableValidator, if: :unmodifiable? def self.alphabetical(locale = I18n.locale) with_translations(locale).order("edition_translations.title ASC") end def self.published_before(date) where(arel_table[:public_timestamp].lteq(date)) end def self.published_after(date) where(arel_table[:public_timestamp].gteq(date)) end def self.in_chronological_order order(arel_table[:public_timestamp].asc, arel_table[:document_id].asc) end def self.in_reverse_chronological_order order(arel_table[:public_timestamp].desc, arel_table[:document_id].desc, arel_table[:id].desc) end def self.without_editions_of_type(*edition_classes) where(arel_table[:type].not_in(edition_classes.map(&:name))) end def self.not_relevant_to_local_government relevant_to_local_government(false) end def self.relevant_to_local_government(include_relevant = true) types_that_get_relevance_from_related_policies = Edition::CanApplyToLocalGovernmentThroughRelatedPolicies.edition_types.map(&:name) where(%{ ( type IN (:types) AND EXISTS ( SELECT 1 FROM editions related_editions INNER JOIN edition_relations ON related_editions.document_id = edition_relations.document_id WHERE edition_relations.edition_id = editions.id AND related_editions.type = 'Policy' AND related_editions.relevant_to_local_government = :relevant AND related_editions.state = 'published' ) ) OR ( type NOT IN (:types) AND editions.relevant_to_local_government = :relevant ) }, types: types_that_get_relevance_from_related_policies, relevant: include_relevant) end def self.published_and_available_in_english with_translations(:en).published end def self.format_name @format_name ||= model_name.human.downcase end def self.authored_by(user) if user && user.id where("EXISTS ( SELECT * FROM edition_authors ea_authorship_check WHERE ea_authorship_check.edition_id=editions.id AND ea_authorship_check.user_id=? )", user.id) end end # used by Admin::EditionFilter def self.by_type(type) where(type: type) end # used by Admin::EditionFilter def self.by_subtype(type, subtype) type.by_subtype(subtype) end # used by Admin::EditionFilter def self.by_subtypes(type, subtype_ids) type.by_subtypes(subtype_ids) end # used by Admin::EditionFilter def self.in_world_location(world_location) joins(:world_locations).where('world_locations.id' => world_location) end def self.from_date(date) where("editions.updated_at >= ?", date) end def self.to_date(date) where("editions.updated_at <= ?", date) end def self.related_to(edition) related = if edition.is_a?(Policy) edition.related_editions else edition.related_policies end # This works around a wierd bug in ActiveRecord where an outer scope applied # to Edition would be applied to this association. See EditionActiveRecordBugWorkaroundTest. all_after_forcing_query_execution = related.all where(id: all_after_forcing_query_execution.map(&:id)) end def self.latest_edition where("NOT EXISTS ( SELECT 1 FROM editions e2 WHERE e2.document_id = editions.document_id AND e2.id > editions.id AND e2.state <> 'deleted')") end def self.latest_published_edition published.where("NOT EXISTS ( SELECT 1 FROM editions e2 WHERE e2.document_id = editions.document_id AND e2.id > editions.id AND e2.state = 'published')") end def self.search_format_type self.name.underscore.gsub('_', '-') end def self.concrete_descendants descendants.reject { |model| model.descendants.any? }.sort_by { |model| model.name } end def self.concrete_descendant_search_format_types concrete_descendants.map { |model| model.search_format_type } end # NOTE: this scope becomes redundant once Admin::EditionFilterer is backed by an admin-only rummager index def self.with_classification(classification) joins('INNER JOIN classification_memberships ON classification_memberships.edition_id = editions.id'). where("classification_memberships.classification_id" => classification.id) end def self.due_for_publication(within_time = 0) cutoff = Time.zone.now + within_time scheduled.where(arel_table[:scheduled_publication].lteq(cutoff)) end def self.scheduled_for_publication_as(slug) document = Document.at_slug(document_type, slug) document && document.scheduled_edition end def skip_main_validation? FROZEN_STATES.include?(state) end def unmodifiable? persisted? && UNMODIFIABLE_STATES.include?(state_was) end def clear_slug document.update_slug_if_possible("deleted-#{title(I18n.default_locale)}") end searchable( id: :id, title: :search_title, link: :search_link, format: -> d { d.format_name.gsub(" ", "_") }, content: :indexable_content, description: :summary, section: :section, subsection: :subsection, subsubsection: :subsubsection, organisations: nil, people: nil, display_type: :display_type, public_timestamp: :public_timestamp, relevant_to_local_government: :relevant_to_local_government?, world_locations: nil, topics: nil, only: :search_only, index_after: [], unindex_after: [], search_format_types: :search_format_types, attachments: nil, operational_field: nil, specialist_sectors: :live_specialist_sector_tags, latest_change_note: :most_recent_change_note, ) def search_title title end def search_link Whitehall.url_maker.public_document_path(self) end def search_format_types [Edition.search_format_type] end def self.search_only published_and_available_in_english end def refresh_index_if_required if document.editions.published.any? document.editions.published.last.update_in_search_index else remove_from_search_index end end def creator edition_authors.first && edition_authors.first.user end def creator=(user) if new_record? edition_author = edition_authors.first || edition_authors.build edition_author.user = user else raise "author can only be set on new records" end end def publicly_visible? PUBLICLY_VISIBLE_STATES.include?(state) end # @group Overwritable permission methods def can_be_associated_with_topics? false end def can_be_associated_with_topical_events? false end def can_be_associated_with_ministers? false end def can_be_associated_with_role_appointments? false end def can_be_associated_with_worldwide_priorities? false end def can_be_associated_with_statistical_data_sets? false end def can_be_associated_with_worldwide_organisations? false end def can_be_fact_checked? false end def can_be_related_to_policies? false end def can_be_related_to_mainstream_content? false end def can_be_related_to_organisations? false end def can_be_associated_with_mainstream_categories? false end def can_apply_to_subset_of_nations? false end def allows_attachments? false end def allows_attachment_references? false end def allows_inline_attachments? false end def allows_supporting_pages? false end def can_be_grouped_in_collections? false end def has_operational_field? false end def image_disallowed_in_body_text?(i) false end def can_apply_to_local_government? false end def national_statistic? false end def has_consultation_participation? false end # @!endgroup def create_draft(user) unless published? raise "Cannot create new edition based on edition in the #{state} state" end draft_attributes = attributes.except(*%w{id type state created_at updated_at change_note minor_change force_published scheduled_publication}) self.class.new(draft_attributes.merge('state' => 'draft', 'creator' => user)).tap do |draft| traits.each { |t| t.process_associations_before_save(draft) } if draft.valid? || !draft.errors.keys.include?(:base) if draft.save(validate: false) traits.each { |t| t.process_associations_after_save(draft) } end end end end def author_names edition_authors.map(&:user).map(&:name).uniq end def rejected_by rejected_event = latest_version_audit_entry_for('rejected') rejected_event && rejected_event.actor end def published_by published_event = latest_version_audit_entry_for('published') published_event && published_event.actor end def scheduled_by scheduled_event = latest_version_audit_entry_for('scheduled') scheduled_event && scheduled_event.actor end def submitted_by most_recent_submission_audit_entry.try(:actor) end def title_with_state "#{title} (#{state})" end def indexable_content body_without_markup end def body_without_markup Govspeak::Document.new(body).to_text end def section nil end def subsection nil end def subsubsection nil end def other_editions if self.persisted? document.editions.where(self.class.arel_table[:id].not_eq(self.id)) else document.editions end end def other_draft_editions other_editions.draft end def latest_edition document.editions.latest_edition.first end def latest_published_edition document.editions.latest_published_edition.first end def previous_edition if pre_publication? latest_published_edition else document.ever_published_editions.reverse.second end end def is_latest_edition? latest_edition == self end def most_recent_change_note if minor_change? previous_major_version = Edition.unscoped.where('document_id=? and published_major_version=? and published_minor_version=0', document_id, published_major_version) previous_major_version.first.change_note if previous_major_version.any? else change_note unless first_published_version? end end def format_name self.class.format_name end def display_type format_name.capitalize end def display_type_key format_name.tr(' ', '_') end def first_public_at first_published_at end def make_public_at(date) self.first_published_at ||= date end def alternative_format_contact_email nil end def valid_as_draft? errors_as_draft.empty? end def editable? imported? || draft? || submitted? || rejected? end def can_have_some_invalid_data? imported? || deleted? || superseded? end attr_accessor :trying_to_convert_to_draft def errors_as_draft if imported? original_errors = self.errors.dup begin self.trying_to_convert_to_draft = true self.try_draft return valid? ? [] : errors.dup ensure self.back_to_imported self.trying_to_convert_to_draft = false self.errors.initialize_dup(original_errors) end else valid? ? [] : errors end end def set_public_timestamp if first_published_version? self.public_timestamp = first_public_at else self.public_timestamp = major_change_published_at end end def title_required? true end def body_required? true end def has_associated_needs? associated_needs.any? end def associated_needs return [] if need_ids.empty? Whitehall.need_api.needs_by_id(*need_ids).with_subsequent_pages.to_a end def need_ids_are_six_digit_integers? invalid_need_ids = need_ids.reject { |need_id| need_id =~ /\A\d{6}\z/ } unless invalid_need_ids.empty? errors.add(:need_ids, "are invalid: #{invalid_need_ids.join(", ")}") end end attr_accessor :has_first_published_error attr_writer :previously_published def previously_published if @previously_published.present? @previously_published elsif imported? true elsif !new_record? first_published_at.present? end end def trigger_previously_published_validations @validate_previously_published = true end validate :previously_published_documents_have_date def previously_published_documents_have_date return unless @validate_previously_published if @previously_published.nil? errors[:base] << 'You must specify whether the document has been published before' @has_first_published_error = true elsif previously_published == 'true' # not a real field, so isn't converted to bool errors.add(:first_published_at, "can't be blank") if first_published_at.blank? @has_first_published_error = true end end private def enforcer(user) Whitehall::Authority::Enforcer.new(user, self) end def summary_required? true end end Simplify the `#with_title_containing` scope This is never called with a list of keywords, only ever called with a single keyword. This allows us to simplify the code significantly. # The base class for all editoral content. It configures the searchable options and callbacks. # @abstract Using STI should not create editions directly. class Edition < ActiveRecord::Base include Edition::Traits include Edition::NullImages include Edition::NullWorldLocations include Edition::Identifiable include Edition::LimitedAccess include Edition::Workflow include Edition::Publishing include Edition::AuditTrail include Edition::ActiveEditors include Edition::Translatable include Edition::SpecialistSectors serialize :need_ids, Array # This mixin should go away when we switch to a search backend for admin documents extend Edition::FindableByOrganisation include Searchable has_many :editorial_remarks, dependent: :destroy has_many :edition_authors, dependent: :destroy has_many :authors, through: :edition_authors, source: :user has_many :classification_featurings, inverse_of: :edition has_many :links_reports, as: :link_reportable validates_with SafeHtmlValidator validates_with NoFootnotesInGovspeakValidator, attribute: :body validates :creator, presence: true validates :title, presence: true, if: :title_required? validates :body, presence: true, if: :body_required? validates :summary, presence: true, if: :summary_required? validates :first_published_at, recent_date: true, allow_blank: true validate :need_ids_are_six_digit_integers? UNMODIFIABLE_STATES = %w(scheduled published superseded deleted).freeze FROZEN_STATES = %w(superseded deleted).freeze PRE_PUBLICATION_STATES = %w(imported draft submitted rejected scheduled).freeze POST_PUBLICATION_STATES = %w(published superseded archived).freeze PUBLICLY_VISIBLE_STATES = %w(published archived).freeze scope :with_title_or_summary_containing, -> *keywords { pattern = "(#{keywords.map { |k| Regexp.escape(k) }.join('|')})" in_default_locale.where("edition_translations.title REGEXP :pattern OR edition_translations.summary REGEXP :pattern", pattern: pattern) } scope :with_title_containing, ->(keywords) { escaped_like_expression = keywords.gsub(/([%_])/, '%' => '\\%', '_' => '\\_') like_clause = "%#{escaped_like_expression}%" in_default_locale .includes(:document) .where("edition_translations.title LIKE :like_clause OR documents.slug = :slug", like_clause: like_clause, slug: keywords) } scope :force_published, -> { where(state: "published", force_published: true) } scope :not_published, -> { where(state: %w(draft submitted rejected)) } scope :announcements, -> { where(type: Announcement.concrete_descendants.collect(&:name)) } scope :consultations, -> { where(type: "Consultation") } scope :detailed_guides, -> { where(type: "DetailedGuide") } scope :policies, -> { where(type: "Policy") } scope :statistical_publications, -> { where("publication_type_id IN (?)", PublicationType.statistical.map(&:id)) } scope :non_statistical_publications, -> { where("publication_type_id NOT IN (?)", PublicationType.statistical.map(&:id)) } scope :corporate_publications, -> { where(publication_type_id: PublicationType::CorporateReport.id) } scope :worldwide_priorities, -> { where(type: "WorldwidePriority") } scope :corporate_information_pages, -> { where(type: "CorporateInformationPage") } scope :publicly_visible, -> { where(state: PUBLICLY_VISIBLE_STATES) } # @!group Callbacks before_save :set_public_timestamp # @!endgroup class UnmodifiableValidator < ActiveModel::Validator def validate(record) significant_changed_attributes(record).each do |attribute| record.errors.add(attribute, "cannot be modified when edition is in the #{record.state} state") end end def significant_changed_attributes(record) record.changed - modifiable_attributes(record.state_was, record.state) end def modifiable_attributes(previous_state, current_state) modifiable = %w{state updated_at force_published} if previous_state == 'scheduled' modifiable += %w{major_change_published_at first_published_at access_limited} end if PRE_PUBLICATION_STATES.include?(previous_state) || being_unpublished?(previous_state, current_state) modifiable += %w{published_major_version published_minor_version} end modifiable end def being_unpublished?(previous_state, current_state) previous_state == 'published' && %w(draft archived).include?(current_state) end end validates_with UnmodifiableValidator, if: :unmodifiable? def self.alphabetical(locale = I18n.locale) with_translations(locale).order("edition_translations.title ASC") end def self.published_before(date) where(arel_table[:public_timestamp].lteq(date)) end def self.published_after(date) where(arel_table[:public_timestamp].gteq(date)) end def self.in_chronological_order order(arel_table[:public_timestamp].asc, arel_table[:document_id].asc) end def self.in_reverse_chronological_order order(arel_table[:public_timestamp].desc, arel_table[:document_id].desc, arel_table[:id].desc) end def self.without_editions_of_type(*edition_classes) where(arel_table[:type].not_in(edition_classes.map(&:name))) end def self.not_relevant_to_local_government relevant_to_local_government(false) end def self.relevant_to_local_government(include_relevant = true) types_that_get_relevance_from_related_policies = Edition::CanApplyToLocalGovernmentThroughRelatedPolicies.edition_types.map(&:name) where(%{ ( type IN (:types) AND EXISTS ( SELECT 1 FROM editions related_editions INNER JOIN edition_relations ON related_editions.document_id = edition_relations.document_id WHERE edition_relations.edition_id = editions.id AND related_editions.type = 'Policy' AND related_editions.relevant_to_local_government = :relevant AND related_editions.state = 'published' ) ) OR ( type NOT IN (:types) AND editions.relevant_to_local_government = :relevant ) }, types: types_that_get_relevance_from_related_policies, relevant: include_relevant) end def self.published_and_available_in_english with_translations(:en).published end def self.format_name @format_name ||= model_name.human.downcase end def self.authored_by(user) if user && user.id where("EXISTS ( SELECT * FROM edition_authors ea_authorship_check WHERE ea_authorship_check.edition_id=editions.id AND ea_authorship_check.user_id=? )", user.id) end end # used by Admin::EditionFilter def self.by_type(type) where(type: type) end # used by Admin::EditionFilter def self.by_subtype(type, subtype) type.by_subtype(subtype) end # used by Admin::EditionFilter def self.by_subtypes(type, subtype_ids) type.by_subtypes(subtype_ids) end # used by Admin::EditionFilter def self.in_world_location(world_location) joins(:world_locations).where('world_locations.id' => world_location) end def self.from_date(date) where("editions.updated_at >= ?", date) end def self.to_date(date) where("editions.updated_at <= ?", date) end def self.related_to(edition) related = if edition.is_a?(Policy) edition.related_editions else edition.related_policies end # This works around a wierd bug in ActiveRecord where an outer scope applied # to Edition would be applied to this association. See EditionActiveRecordBugWorkaroundTest. all_after_forcing_query_execution = related.all where(id: all_after_forcing_query_execution.map(&:id)) end def self.latest_edition where("NOT EXISTS ( SELECT 1 FROM editions e2 WHERE e2.document_id = editions.document_id AND e2.id > editions.id AND e2.state <> 'deleted')") end def self.latest_published_edition published.where("NOT EXISTS ( SELECT 1 FROM editions e2 WHERE e2.document_id = editions.document_id AND e2.id > editions.id AND e2.state = 'published')") end def self.search_format_type self.name.underscore.gsub('_', '-') end def self.concrete_descendants descendants.reject { |model| model.descendants.any? }.sort_by { |model| model.name } end def self.concrete_descendant_search_format_types concrete_descendants.map { |model| model.search_format_type } end # NOTE: this scope becomes redundant once Admin::EditionFilterer is backed by an admin-only rummager index def self.with_classification(classification) joins('INNER JOIN classification_memberships ON classification_memberships.edition_id = editions.id'). where("classification_memberships.classification_id" => classification.id) end def self.due_for_publication(within_time = 0) cutoff = Time.zone.now + within_time scheduled.where(arel_table[:scheduled_publication].lteq(cutoff)) end def self.scheduled_for_publication_as(slug) document = Document.at_slug(document_type, slug) document && document.scheduled_edition end def skip_main_validation? FROZEN_STATES.include?(state) end def unmodifiable? persisted? && UNMODIFIABLE_STATES.include?(state_was) end def clear_slug document.update_slug_if_possible("deleted-#{title(I18n.default_locale)}") end searchable( id: :id, title: :search_title, link: :search_link, format: -> d { d.format_name.gsub(" ", "_") }, content: :indexable_content, description: :summary, section: :section, subsection: :subsection, subsubsection: :subsubsection, organisations: nil, people: nil, display_type: :display_type, public_timestamp: :public_timestamp, relevant_to_local_government: :relevant_to_local_government?, world_locations: nil, topics: nil, only: :search_only, index_after: [], unindex_after: [], search_format_types: :search_format_types, attachments: nil, operational_field: nil, specialist_sectors: :live_specialist_sector_tags, latest_change_note: :most_recent_change_note, ) def search_title title end def search_link Whitehall.url_maker.public_document_path(self) end def search_format_types [Edition.search_format_type] end def self.search_only published_and_available_in_english end def refresh_index_if_required if document.editions.published.any? document.editions.published.last.update_in_search_index else remove_from_search_index end end def creator edition_authors.first && edition_authors.first.user end def creator=(user) if new_record? edition_author = edition_authors.first || edition_authors.build edition_author.user = user else raise "author can only be set on new records" end end def publicly_visible? PUBLICLY_VISIBLE_STATES.include?(state) end # @group Overwritable permission methods def can_be_associated_with_topics? false end def can_be_associated_with_topical_events? false end def can_be_associated_with_ministers? false end def can_be_associated_with_role_appointments? false end def can_be_associated_with_worldwide_priorities? false end def can_be_associated_with_statistical_data_sets? false end def can_be_associated_with_worldwide_organisations? false end def can_be_fact_checked? false end def can_be_related_to_policies? false end def can_be_related_to_mainstream_content? false end def can_be_related_to_organisations? false end def can_be_associated_with_mainstream_categories? false end def can_apply_to_subset_of_nations? false end def allows_attachments? false end def allows_attachment_references? false end def allows_inline_attachments? false end def allows_supporting_pages? false end def can_be_grouped_in_collections? false end def has_operational_field? false end def image_disallowed_in_body_text?(i) false end def can_apply_to_local_government? false end def national_statistic? false end def has_consultation_participation? false end # @!endgroup def create_draft(user) unless published? raise "Cannot create new edition based on edition in the #{state} state" end draft_attributes = attributes.except(*%w{id type state created_at updated_at change_note minor_change force_published scheduled_publication}) self.class.new(draft_attributes.merge('state' => 'draft', 'creator' => user)).tap do |draft| traits.each { |t| t.process_associations_before_save(draft) } if draft.valid? || !draft.errors.keys.include?(:base) if draft.save(validate: false) traits.each { |t| t.process_associations_after_save(draft) } end end end end def author_names edition_authors.map(&:user).map(&:name).uniq end def rejected_by rejected_event = latest_version_audit_entry_for('rejected') rejected_event && rejected_event.actor end def published_by published_event = latest_version_audit_entry_for('published') published_event && published_event.actor end def scheduled_by scheduled_event = latest_version_audit_entry_for('scheduled') scheduled_event && scheduled_event.actor end def submitted_by most_recent_submission_audit_entry.try(:actor) end def title_with_state "#{title} (#{state})" end def indexable_content body_without_markup end def body_without_markup Govspeak::Document.new(body).to_text end def section nil end def subsection nil end def subsubsection nil end def other_editions if self.persisted? document.editions.where(self.class.arel_table[:id].not_eq(self.id)) else document.editions end end def other_draft_editions other_editions.draft end def latest_edition document.editions.latest_edition.first end def latest_published_edition document.editions.latest_published_edition.first end def previous_edition if pre_publication? latest_published_edition else document.ever_published_editions.reverse.second end end def is_latest_edition? latest_edition == self end def most_recent_change_note if minor_change? previous_major_version = Edition.unscoped.where('document_id=? and published_major_version=? and published_minor_version=0', document_id, published_major_version) previous_major_version.first.change_note if previous_major_version.any? else change_note unless first_published_version? end end def format_name self.class.format_name end def display_type format_name.capitalize end def display_type_key format_name.tr(' ', '_') end def first_public_at first_published_at end def make_public_at(date) self.first_published_at ||= date end def alternative_format_contact_email nil end def valid_as_draft? errors_as_draft.empty? end def editable? imported? || draft? || submitted? || rejected? end def can_have_some_invalid_data? imported? || deleted? || superseded? end attr_accessor :trying_to_convert_to_draft def errors_as_draft if imported? original_errors = self.errors.dup begin self.trying_to_convert_to_draft = true self.try_draft return valid? ? [] : errors.dup ensure self.back_to_imported self.trying_to_convert_to_draft = false self.errors.initialize_dup(original_errors) end else valid? ? [] : errors end end def set_public_timestamp if first_published_version? self.public_timestamp = first_public_at else self.public_timestamp = major_change_published_at end end def title_required? true end def body_required? true end def has_associated_needs? associated_needs.any? end def associated_needs return [] if need_ids.empty? Whitehall.need_api.needs_by_id(*need_ids).with_subsequent_pages.to_a end def need_ids_are_six_digit_integers? invalid_need_ids = need_ids.reject { |need_id| need_id =~ /\A\d{6}\z/ } unless invalid_need_ids.empty? errors.add(:need_ids, "are invalid: #{invalid_need_ids.join(", ")}") end end attr_accessor :has_first_published_error attr_writer :previously_published def previously_published if @previously_published.present? @previously_published elsif imported? true elsif !new_record? first_published_at.present? end end def trigger_previously_published_validations @validate_previously_published = true end validate :previously_published_documents_have_date def previously_published_documents_have_date return unless @validate_previously_published if @previously_published.nil? errors[:base] << 'You must specify whether the document has been published before' @has_first_published_error = true elsif previously_published == 'true' # not a real field, so isn't converted to bool errors.add(:first_published_at, "can't be blank") if first_published_at.blank? @has_first_published_error = true end end private def enforcer(user) Whitehall::Authority::Enforcer.new(user, self) end def summary_required? true end end
class Edition < ActiveRecord::Base acts_as_commentable belongs_to :guide, touch: true belongs_to :user has_one :approval belongs_to :content_owner scope :draft, -> { where(state: 'draft') } scope :published, -> { where(state: 'published') } scope :review_requested, -> { where(state: 'review_requested') } validates_presence_of [:state, :phase, :description, :title, :update_type, :body, :content_owner, :user] validates_inclusion_of :state, in: %w(draft published review_requested approved) validates :change_note, presence: true, if: :major? validate :published_cant_change %w{minor major}.each do |s| define_method "#{s}?" do update_type == s end end def draft? state == 'draft' end def published? state == 'published' end def review_requested? state == 'review_requested' end def approved? state == 'approved' end def can_request_review? return false if !persisted? return false if review_requested? return false if published? return false if approved? true end def can_be_approved? persisted? && review_requested? end def can_be_published? return false if published? return false if !latest_edition? approved? end def latest_edition? self == guide.latest_edition end def content_owner_title content_owner.try(:title) end def previously_published_edition guide.editions.published.where("id < ?", id).order(id: :desc).first end def change_note_html Redcarpet::Markdown.new( Redcarpet::Render::HTML, extensions = { autolink: true, }, ).render(change_note) end def draft_copy dup.tap do |e| e.change_note = nil e.update_type = "minor" e.state = "draft" end end private def published_cant_change if state_was == 'published' && changes.except('updated_at').present? errors.add(:base, "can not be changed after it's been published. Perhaps someone has published it whilst you were editing it.") end end def assign_publisher_href self.publisher_href = PUBLISHERS[publisher_title] if publisher_title.present? end end Memoize previously_published_edition It's called multiple times per request and it's not expected to change. class Edition < ActiveRecord::Base acts_as_commentable belongs_to :guide, touch: true belongs_to :user has_one :approval belongs_to :content_owner scope :draft, -> { where(state: 'draft') } scope :published, -> { where(state: 'published') } scope :review_requested, -> { where(state: 'review_requested') } validates_presence_of [:state, :phase, :description, :title, :update_type, :body, :content_owner, :user] validates_inclusion_of :state, in: %w(draft published review_requested approved) validates :change_note, presence: true, if: :major? validate :published_cant_change %w{minor major}.each do |s| define_method "#{s}?" do update_type == s end end def draft? state == 'draft' end def published? state == 'published' end def review_requested? state == 'review_requested' end def approved? state == 'approved' end def can_request_review? return false if !persisted? return false if review_requested? return false if published? return false if approved? true end def can_be_approved? persisted? && review_requested? end def can_be_published? return false if published? return false if !latest_edition? approved? end def latest_edition? self == guide.latest_edition end def content_owner_title content_owner.try(:title) end def previously_published_edition @previously_published_edition ||= guide.editions.published.where("id < ?", id).order(id: :desc).first end def change_note_html Redcarpet::Markdown.new( Redcarpet::Render::HTML, extensions = { autolink: true, }, ).render(change_note) end def draft_copy dup.tap do |e| e.change_note = nil e.update_type = "minor" e.state = "draft" end end private def published_cant_change if state_was == 'published' && changes.except('updated_at').present? errors.add(:base, "can not be changed after it's been published. Perhaps someone has published it whilst you were editing it.") end end def assign_publisher_href self.publisher_href = PUBLISHERS[publisher_title] if publisher_title.present? end end
class Emailer < ActionMailer::Base include ActionView::Helpers::TextHelper include Emailer::Incoming helper :application ANSWER_LINE = '-----------------------------==-----------------------------' class << self def emailer_defaults { :content_type => 'text/html', # :sent_on => Time.now, :from => from_address } end def send_email(template, *args) send_with_language(template, :en, *args) end def send_with_language(template, language, *args) old_locale = I18n.locale I18n.locale = language begin send(template, *args).deliver ensure I18n.locale = old_locale end end # can't use regular `receive` class method since it deals with Mail objects def receive_params(params) new.receive(params) end def from_user(reply_identifier, user) unless Teambox.config.allow_incoming_email and reply_identifier reply_identifier = "no-reply" end from_address(reply_identifier, user.try(:name)) end def from_address(recipient = "no-reply", name = "Teambox") domain = Teambox.config.smtp_settings[:domain] address = "#{recipient}@#{domain}" if name.blank? or Teambox.config.smtp_settings[:safe_from] address else %("#{name}" <#{address}>) end end end default emailer_defaults def confirm_email(user_id) @user = User.find(user_id) @login_link = confirm_email_user_url(@user, :token => @user.login_token) mail( :to => @user.email, :subject => I18n.t("emailer.confirm.subject") ) end def reset_password(user_id) @user = User.find(user_id) mail( :to => @user.email, :subject => I18n.t("emailer.reset_password.subject") ) end def forgot_password(reset_password_id) reset_password = ResetPassword.find(reset_password_id) @user = reset_password.user @url = reset_password_url(reset_password.reset_code) mail( :to => reset_password.user.email, :subject => I18n.t("emailer.forgot_password.subject") ) end def project_invitation(invitation_id) @invitation = Invitation.find(invitation_id) @referral = @invitation.user @project = @invitation.project mail( :to => @invitation.email, :from => self.class.from_user(nil, @invitation.user), :subject => I18n.t("emailer.invitation.subject", :user => @invitation.user.name, :project => @invitation.project.name) ) end def signup_invitation(invitation_id) @invitation = Invitation.find(invitation_id) @referral = @invitation.user @project = @invitation.project mail( :to => @invitation.email, :subject => I18n.t("emailer.invitation.subject", :user => @invitation.user.name, :project => @invitation.project.name) ) end def notify_export(data_id) @data = TeamboxData.find(data_id) @user = @data.user @error = !@data.exported? mail( :to => @data.user.email, :subject => @error ? I18n.t('emailer.teamboxdata.export_failed') : I18n.t('emailer.teamboxdata.exported') ) end def notify_import(data_id) @data = TeamboxData.find(data_id) @user = @data.user @error = !@data.imported? mail( :to => @data.user.email, :subject => @error ? I18n.t('emailer.teamboxdata.import_failed') : I18n.t('emailer.teamboxdata.imported') ) end def notify_conversation(user_id, project_id, conversation_id) @project = Project.find(project_id) @conversation = Conversation.find(conversation_id) @recipient = User.find(user_id) @organization = @project.organization title = @conversation.name.blank? ? truncate(@conversation.comments.first(:order => 'id ASC').body.strip) : @conversation.name mail({ :to => @recipient.email, :subject => "[#{@project.permalink}] #{title}" }.merge( from_reply_to "#{@project.permalink}+conversation+#{@conversation.id}", @conversation.comments.first.user )) end def notify_task(user_id, project_id, task_id) @project = Project.find(project_id) @task = Task.find(task_id) @task_list = @task.task_list @recipient = User.find(user_id) @organization = @task.project.organization mail({ :to => @recipient.email, :subject => "[#{@project.permalink}] #{@task.name}#{task_description(@task)}" }.merge( from_reply_to "#{@project.permalink}+task+#{@task.id}", @task.comments.first.user )) end def project_membership_notification(invitation_id) @invitation = Invitation.find_with_deleted(invitation_id) @project = @invitation.project @recipient = @invitation.invited_user mail({ :to => @invitation.invited_user.email, :subject => I18n.t("emailer.project_membership_notification.subject", :user => @invitation.user.name, :project => @invitation.project.name) }.merge( from_reply_to "#{@invitation.project.permalink}", @invitation.user )) end def daily_task_reminder(user_id) @user = User.find(user_id) @tasks = @user.tasks_for_daily_reminder_email mail( :to => @user.email, :subject => I18n.t("users.daily_task_reminder_email.daily_task_reminder") ) end def bounce_message(exception_mail, pretty_exception) info_url = 'http://help.teambox.com/faqs/advanced-features/email' mail( :to => exception_mail, :subject => I18n.t("emailer.bounce.subject"), :body => I18n.t("emailer.bounce.#{pretty_exception}") + "\n\n---\n" + I18n.t("emailer.bounce.not_delivered", :link => info_url) ) end # requires data from rake db:seed class Preview < MailView def notify_task task = Task.find_by_name "Contact area businesses for banner exchange" ::Emailer.notify_task(task.user.id, task.project.id, task.id) end def notify_conversation conversation = Conversation.find_by_name "Seth Godin's 'What matters now'" ::Emailer.notify_conversation(conversation.user.id, conversation.project.id, conversation.id) end def daily_task_reminder user = User.first ::Emailer.daily_task_reminder(user.id) end def signup_invitation invitation = Invitation.new do |i| i.email = 'test@teambox.com' i.token = ActiveSupport::SecureRandom.hex(20) i.user = User.first i.project = Project.first end invitation.save!(false) ::Emailer.signup_invitation(invitation.id) end def reset_password user = User.first ::Emailer.reset_password(user.id) end def forgot_password password_reset = ResetPassword.create! do |passwd| passwd.email = "reset#{ActiveSupport::SecureRandom.hex(20)}@example.com" passwd.user = User.first passwd.reset_code = ActiveSupport::SecureRandom.hex(20) end ::Emailer.forgot_password(password_reset.id) end def project_membership_notification invitation = Invitation.new do |i| i.user = User.first i.invited_user = User.last i.project = Project.first end invitation.save!(false) ::Emailer.project_membership_notification(invitation.id) end def project_invitation invitation = Invitation.new do |i| i.token = ActiveSupport::SecureRandom.hex(20) i.user = User.first i.invited_user = User.last i.project = Project.first end invitation.is_silent = true invitation.save!(false) ::Emailer.project_invitation(invitation.id) end def confirm_email user = User.first ::Emailer.confirm_email(user.id) end end private def from_reply_to(reply_identifier, user) reply_address = self.class.from_user(reply_identifier, nil) {:from => self.class.from_user(reply_identifier, user)}.merge( reply_address.starts_with?("no-reply") ? {} : {:reply_to => reply_address} ) end def task_description(task) desc = task.comments.first.try(:body) task_description = truncate(desc ? desc : '', :length => 50) task_description.blank? ? '' : " - #{task_description}" end end Ensure daily_task_reminder preview is using a user with tasks to be shown class Emailer < ActionMailer::Base include ActionView::Helpers::TextHelper include Emailer::Incoming helper :application ANSWER_LINE = '-----------------------------==-----------------------------' class << self def emailer_defaults { :content_type => 'text/html', # :sent_on => Time.now, :from => from_address } end def send_email(template, *args) send_with_language(template, :en, *args) end def send_with_language(template, language, *args) old_locale = I18n.locale I18n.locale = language begin send(template, *args).deliver ensure I18n.locale = old_locale end end # can't use regular `receive` class method since it deals with Mail objects def receive_params(params) new.receive(params) end def from_user(reply_identifier, user) unless Teambox.config.allow_incoming_email and reply_identifier reply_identifier = "no-reply" end from_address(reply_identifier, user.try(:name)) end def from_address(recipient = "no-reply", name = "Teambox") domain = Teambox.config.smtp_settings[:domain] address = "#{recipient}@#{domain}" if name.blank? or Teambox.config.smtp_settings[:safe_from] address else %("#{name}" <#{address}>) end end end default emailer_defaults def confirm_email(user_id) @user = User.find(user_id) @login_link = confirm_email_user_url(@user, :token => @user.login_token) mail( :to => @user.email, :subject => I18n.t("emailer.confirm.subject") ) end def reset_password(user_id) @user = User.find(user_id) mail( :to => @user.email, :subject => I18n.t("emailer.reset_password.subject") ) end def forgot_password(reset_password_id) reset_password = ResetPassword.find(reset_password_id) @user = reset_password.user @url = reset_password_url(reset_password.reset_code) mail( :to => reset_password.user.email, :subject => I18n.t("emailer.forgot_password.subject") ) end def project_invitation(invitation_id) @invitation = Invitation.find(invitation_id) @referral = @invitation.user @project = @invitation.project mail( :to => @invitation.email, :from => self.class.from_user(nil, @invitation.user), :subject => I18n.t("emailer.invitation.subject", :user => @invitation.user.name, :project => @invitation.project.name) ) end def signup_invitation(invitation_id) @invitation = Invitation.find(invitation_id) @referral = @invitation.user @project = @invitation.project mail( :to => @invitation.email, :subject => I18n.t("emailer.invitation.subject", :user => @invitation.user.name, :project => @invitation.project.name) ) end def notify_export(data_id) @data = TeamboxData.find(data_id) @user = @data.user @error = !@data.exported? mail( :to => @data.user.email, :subject => @error ? I18n.t('emailer.teamboxdata.export_failed') : I18n.t('emailer.teamboxdata.exported') ) end def notify_import(data_id) @data = TeamboxData.find(data_id) @user = @data.user @error = !@data.imported? mail( :to => @data.user.email, :subject => @error ? I18n.t('emailer.teamboxdata.import_failed') : I18n.t('emailer.teamboxdata.imported') ) end def notify_conversation(user_id, project_id, conversation_id) @project = Project.find(project_id) @conversation = Conversation.find(conversation_id) @recipient = User.find(user_id) @organization = @project.organization title = @conversation.name.blank? ? truncate(@conversation.comments.first(:order => 'id ASC').body.strip) : @conversation.name mail({ :to => @recipient.email, :subject => "[#{@project.permalink}] #{title}" }.merge( from_reply_to "#{@project.permalink}+conversation+#{@conversation.id}", @conversation.comments.first.user )) end def notify_task(user_id, project_id, task_id) @project = Project.find(project_id) @task = Task.find(task_id) @task_list = @task.task_list @recipient = User.find(user_id) @organization = @task.project.organization mail({ :to => @recipient.email, :subject => "[#{@project.permalink}] #{@task.name}#{task_description(@task)}" }.merge( from_reply_to "#{@project.permalink}+task+#{@task.id}", @task.comments.first.user )) end def project_membership_notification(invitation_id) @invitation = Invitation.find_with_deleted(invitation_id) @project = @invitation.project @recipient = @invitation.invited_user mail({ :to => @invitation.invited_user.email, :subject => I18n.t("emailer.project_membership_notification.subject", :user => @invitation.user.name, :project => @invitation.project.name) }.merge( from_reply_to "#{@invitation.project.permalink}", @invitation.user )) end def daily_task_reminder(user_id) @user = User.find(user_id) @tasks = @user.tasks_for_daily_reminder_email mail( :to => @user.email, :subject => I18n.t("users.daily_task_reminder_email.daily_task_reminder") ) end def bounce_message(exception_mail, pretty_exception) info_url = 'http://help.teambox.com/faqs/advanced-features/email' mail( :to => exception_mail, :subject => I18n.t("emailer.bounce.subject"), :body => I18n.t("emailer.bounce.#{pretty_exception}") + "\n\n---\n" + I18n.t("emailer.bounce.not_delivered", :link => info_url) ) end # requires data from rake db:seed class Preview < MailView def notify_task task = Task.find_by_name "Contact area businesses for banner exchange" ::Emailer.notify_task(task.user.id, task.project.id, task.id) end def notify_conversation conversation = Conversation.find_by_name "Seth Godin's 'What matters now'" ::Emailer.notify_conversation(conversation.user.id, conversation.project.id, conversation.id) end def daily_task_reminder user = User.find_by_login 'frank' ::Emailer.daily_task_reminder(user.id) end def signup_invitation invitation = Invitation.new do |i| i.email = 'test@teambox.com' i.token = ActiveSupport::SecureRandom.hex(20) i.user = User.first i.project = Project.first end invitation.save!(false) ::Emailer.signup_invitation(invitation.id) end def reset_password user = User.first ::Emailer.reset_password(user.id) end def forgot_password password_reset = ResetPassword.create! do |passwd| passwd.email = "reset#{ActiveSupport::SecureRandom.hex(20)}@example.com" passwd.user = User.first passwd.reset_code = ActiveSupport::SecureRandom.hex(20) end ::Emailer.forgot_password(password_reset.id) end def project_membership_notification invitation = Invitation.new do |i| i.user = User.first i.invited_user = User.last i.project = Project.first end invitation.save!(false) ::Emailer.project_membership_notification(invitation.id) end def project_invitation invitation = Invitation.new do |i| i.token = ActiveSupport::SecureRandom.hex(20) i.user = User.first i.invited_user = User.last i.project = Project.first end invitation.is_silent = true invitation.save!(false) ::Emailer.project_invitation(invitation.id) end def confirm_email user = User.first ::Emailer.confirm_email(user.id) end end private def from_reply_to(reply_identifier, user) reply_address = self.class.from_user(reply_identifier, nil) {:from => self.class.from_user(reply_identifier, user)}.merge( reply_address.starts_with?("no-reply") ? {} : {:reply_to => reply_address} ) end def task_description(task) desc = task.comments.first.try(:body) task_description = truncate(desc ? desc : '', :length => 50) task_description.blank? ? '' : " - #{task_description}" end end
class Embassy extend Forwardable def initialize(world_location) @world_location = world_location end def_delegator :@world_location, :name def self.filter_offices(worldwide_organisation) worldwide_organisation.offices.select { |o| embassy_high_commission_or_consulate?(o) } end def offices @world_location.worldwide_organisations.map { |org| self.class.filter_offices(org) }.flatten end def consular_services_organisations @world_location.worldwide_organisations.select do |org| self.class.filter_offices(org).any? end end def remote_services_country offices = consular_services_organisations.map(&:offices).flatten countries = offices.map(&:country) unless countries.empty? or countries.include?(@world_location) countries.first end end private def self.embassy_high_commission_or_consulate?(office) [ "British Trade and Cultural Office", "Consulate", "Embassy", "High Commission", ].include?(office.worldwide_office_type.name) end end Rename to hide details of what constitutes an embassy office class Embassy extend Forwardable def initialize(world_location) @world_location = world_location end def_delegator :@world_location, :name def self.filter_offices(worldwide_organisation) worldwide_organisation.offices.select { |o| embassy_office?(o) } end def offices @world_location.worldwide_organisations.map { |org| self.class.filter_offices(org) }.flatten end def consular_services_organisations @world_location.worldwide_organisations.select do |org| self.class.filter_offices(org).any? end end def remote_services_country offices = consular_services_organisations.map(&:offices).flatten countries = offices.map(&:country) unless countries.empty? or countries.include?(@world_location) countries.first end end def self.embassy_office?(office) [ "British Trade and Cultural Office", "Consulate", "Embassy", "High Commission", ].include?(office.worldwide_office_type.name) end end
class Entries < ActiveRecord::Base attr_accessor :probability def self.get_words(gram_1:, gram_2: nil) other = [] scope = Entries.select('word, sum(count) as count').where(gram_1: gram_1) if gram_2.nil? other = Entries.select('gram_1 as word, sum(count) as count').where(gram_2: gram_1).group(:word).order('count DESC').to_a else scope = scope.where(gram_2: gram_2) end (scope.group(:word).order('count DESC').to_a + other).sort {|a, b| b.count <=> a.count} end end whoops class Entries < ActiveRecord::Base attr_accessor :probability def self.get_words(gram_1:, gram_2: nil) other = [] scope = Entries.select('word, sum(count) as count').where(gram_1: gram_1) if gram_2.nil? other = Entries.select('gram_1 as word, sum(count) as count').where(gram_2: gram_1).group(:gram_1).order('count DESC').to_a else scope = scope.where(gram_2: gram_2) end (scope.group(:word).order('count DESC').to_a + other).sort {|a, b| b.count <=> a.count} end end
module Gql # GQL (Graph Query Language) is to a Graph/Qernel what SQL is to a database. # # It is responsible to update the future graph with user values/assumptions # and to query the present and future graph using GQL Queries (Gquery). # class Gql extend ActiveModel::Naming include Instrumentable attr_accessor :present_graph, :future_graph, :dataset, :scenario, :calculated attr_reader :graph_model, :sandbox_mode # Initialize a Gql instance by passing a (api) scenario # # # # @example Initialize with scenario # gql = Scenario.default.gql(prepare: true) # gql.query(...) # # @example Initialize manually: # gql = Gql::Gql.new(Scenario.default) # gql.prepare # gql.query(...) # # @example Initialize with scenario and individually prepare the gql # gql = Scenario.default.gql(prepare: false) # gql.init_datasets # gql.update_present # gql.update_future # gql.present_graph.calculate # gql.future_graph.calculate # gql.calculated = true # gql.query(...) # # # @param [Graph] graph_model # @param [Dataset,String] dataset Dataset or String for country # def initialize(scenario) if scenario.is_a?(Scenario) # Assign this GQL instance the scenario, which defines the area_code, # end_year and the values of the sliders @scenario = scenario # Assign the present and future Qernel:Graph. They are both "empty" / # have no dataset assigned yet. The graphs are both permanent objects, # they stay in memory forever. So we need two different graph objects # (and nested objects) for present/future. loader = Etsource::Loader.instance @present_graph = loader.graph @future_graph = loader.graph # Assign the dataset. It is not yet assigned to the present/future # graphs yet, which will happen with #init_datasets or #prepare. This # allows for more flexibility with caching. The @dataset will hold # the present dataset, without any updates run. However some updates # also update the present graph, so it is not completely identical. @dataset = loader.dataset(@scenario.area_code) end end # @param [:console, :sandbox] mode The GQL sandbox mode. def sandbox_mode=(mode) @sandbox_mode = mode # We also have to change the sandbox_mode of the Gql::Runtime inside the # query_interfaces. @present = QueryInterface.new(self, present_graph, sandbox_mode: mode) @future = QueryInterface.new(self, future_graph, sandbox_mode: mode) end # @return [Qernel::Dataset] Dataset used for the future. Needs to be updated with user input and then calculated. # def dataset_clone instrument("gql.performance.dataset_clone") do Marshal.load(Marshal.dump(@dataset)) end end # @return [QueryInterface] # def present # Disable Caching of Gqueries until a smart solution has been found # @present ||= QueryInterface.new(self, present_graph, :cache_prefix => "#{scenario.id}-present-#{scenario.present_updated_at}") @present ||= QueryInterface.new(self, present_graph) end # @return [QueryInterface] # def future # Disable Caching of Gqueries until a smart solution has been found # QueryInterface.new(self, future_graph, :cache_prefix => "#{scenario.id}-#{scenario.updated_at}") @future ||= QueryInterface.new(self, future_graph) end # Are the graphs calculated? If true, prevent the programmers to add further # update statements. Because they won't affect the system anymore. # # When calculated changes through update statements # should no longer be allowed, as they won't have an impact on the # calculation (even though updating prices would work). # # @return [Boolean] # def calculated? @calculated == true end # Query the GQL, takes care of gql modifier strings. # # For performance reason it is suggested to pass a Gquery for 'query' # object rather than it's Gquery#query. Because parsing a gql statement # takes rather long time. # # @example Query with a Gquery instance # gql.query(Gquery.first) # @example Query with a string # gql.query("SUM(1.0, 2.0)") # => [[2010, 3.0],[2040,3.0]] # @example Query with a string that includes a query modifier (present/future) # gql.query("present:SUM(1.0, 2.0)") # => 3.0 # @example Query with a proc/lambda # gql.query(-> { SUM(1,2) }) # => 3 # # @param query [String, Gquery, Proc] A query object # @param rescue_resultset [ResultSet] A ResultSet that is return in case of errors. # @return [ResultSet] Result query, depending on its gql_modifier # def query(gquery_or_string, rescue_with = nil) if gquery_or_string.is_a?(::Gquery) modifier = gquery_or_string.gql_modifier query = gquery_or_string elsif gquery_or_string.is_a?(String) modifier = gquery_or_string.match(Gquery::GQL_MODIFIER_REGEXP).captures.first rescue nil query = gquery_or_string.sub(Gquery::GQL_MODIFIER_REGEXP, '') elsif gquery_or_string.respond_to?(:call) query, modifier = gquery_or_string, nil end query_with_modifier(query, modifier) rescue => e if rescue_with == :debug ResultSet.create([[2010, e.inspect], [2040, e.inspect]]) elsif rescue_with == :airbrake # TODO: This fails on offline setups. Convert to a notification # TODO: something's broken here with airbrake 3.0.5: # undefined method `backtrace' for #<Hash:0x007fda54900b88> ?! # https://github.com/airbrake/airbrake/issues/19 Airbrake.notify(:error_message => e.message, :backtrace => caller) unless APP_CONFIG[:standalone] ResultSet::INVALID elsif rescue_with.present? rescue_with else raise e unless rescue_with end end # Run a query with the strategy defined in the parameter def query_with_modifier(query, strategy) key = query.respond_to?(:key) ? query.key : 'custom' instrument("gql.query.#{key}.#{strategy}") do if strategy.nil? query_standard(query) elsif Gquery::GQL_MODIFIERS.include?(strategy.strip) send("query_#{strategy}", query) end end rescue Exception => e raise "Error running #{key}: #{e.inspect}" end # Connects datasets to a present and future graph. # Updates them with user inputs and calculates. # After being prepared graphs are ready to be queried. # This method can only be prepared once. # # This method is "lazy-" called from a {Gql::QueryInterface} object, # when there is no cached result for a Gquery. # # When to prepare: # - For querying # - For working/inspecting the graph (e.g. from the command line) # def prepare log = 'gql.performance.' instrument(log+'init_datasets') { init_datasets } instrument(log+'update_graphs') { update_graphs } instrument(log+'calculate_graphs') { calculate_graphs } end # Runs an array of gqueries. The gquery list might be expressed in all the formats accepted # by Gquery#get, ie key or id # # @param [Array<String>] # @return [Hash<String => ResultSet>] # def query_multiple(gquery_keys) gquery_keys = gquery_keys - ["null", "undefined"] rescue_with = Rails.env.production? ? :airbrake : :debug gquery_keys.inject({}) do |hsh, key| result = if gquery = (Gquery.get(key) rescue nil) and !gquery.converters? query(gquery, rescue_with) else # Why this? Hmm. Seems like we only really want to execute if it's a Gql query # (every gql query contains a "(" and ")"). If it represents a non-existing # gquery key, then return rescue_with (which probably used to be a 'ERROR' earlier). key.include?('(') ? query(key, rescue_with) : rescue_with end hsh.merge! key => result hsh end end def init_datasets present_graph.dataset ||= dataset_clone future_graph.dataset = dataset_clone assign_attributes_from_scenario end # Inside GQL, functions and Gqueries we had some references to # Current.scenario. The aim of this method is to assign all the needed # attributes. Ideally they will be replaced with a different way. def assign_attributes_from_scenario @present_graph.year = @scenario.start_year @future_graph.year = @scenario.end_year @present_graph.number_of_years = @scenario.years @future_graph.number_of_years = @scenario.years @present_graph.use_fce = @scenario.use_fce @future_graph.use_fce = @scenario.use_fce end def update_graphs # 2011-08-15: the present has to be prepared first. otherwise # updating the future won't work (we need the present values) update_present update_future end def calculate_graphs present_graph.calculate future_graph.calculate @calculated = true end def update_present instrument('gql.performance.present.update_present') do scenario.inputs_present.each { |input, value| update_graph(present, input, value) } end end def update_future instrument('gql.performance.future.update_future') do scenario.inputs_before.each { |input, value| update_graph(future, input, value) } scenario.inputs_future.each { |input, value| update_graph(future, input, value) } end end # @param graph a Qernel::Graph or :present, :future # def update_graph(graph, input, value) # TODO: the disabled_in_current_area check should be moved somewhere else case graph when :present then graph = present when :future then graph = future end graph.query(input, value) unless input.disabled_in_current_area?(self) end # Standard query without modifiers. Queries present and future graph. # # @param query [String, Gquery] the single query. # @return [ResultSet] Result query, depending on its gql_modifier # def query_standard(query) ResultSet.create [ [scenario.start_year, query_present(query)], [scenario.end_year, query_future(query)] ] end # @param query [String] The query # @return [Float] The result of the present graph # def query_present(query) present.query(query) end # @param query [String] The query # @return [Float] The result of the future graph # def query_future(query) future.query(query) end end end removed input check required by old scenario bulk update See #344 module Gql # GQL (Graph Query Language) is to a Graph/Qernel what SQL is to a database. # # It is responsible to update the future graph with user values/assumptions # and to query the present and future graph using GQL Queries (Gquery). # class Gql extend ActiveModel::Naming include Instrumentable attr_accessor :present_graph, :future_graph, :dataset, :scenario, :calculated attr_reader :graph_model, :sandbox_mode # Initialize a Gql instance by passing a (api) scenario # # # # @example Initialize with scenario # gql = Scenario.default.gql(prepare: true) # gql.query(...) # # @example Initialize manually: # gql = Gql::Gql.new(Scenario.default) # gql.prepare # gql.query(...) # # @example Initialize with scenario and individually prepare the gql # gql = Scenario.default.gql(prepare: false) # gql.init_datasets # gql.update_present # gql.update_future # gql.present_graph.calculate # gql.future_graph.calculate # gql.calculated = true # gql.query(...) # # # @param [Graph] graph_model # @param [Dataset,String] dataset Dataset or String for country # def initialize(scenario) if scenario.is_a?(Scenario) # Assign this GQL instance the scenario, which defines the area_code, # end_year and the values of the sliders @scenario = scenario # Assign the present and future Qernel:Graph. They are both "empty" / # have no dataset assigned yet. The graphs are both permanent objects, # they stay in memory forever. So we need two different graph objects # (and nested objects) for present/future. loader = Etsource::Loader.instance @present_graph = loader.graph @future_graph = loader.graph # Assign the dataset. It is not yet assigned to the present/future # graphs yet, which will happen with #init_datasets or #prepare. This # allows for more flexibility with caching. The @dataset will hold # the present dataset, without any updates run. However some updates # also update the present graph, so it is not completely identical. @dataset = loader.dataset(@scenario.area_code) end end # @param [:console, :sandbox] mode The GQL sandbox mode. def sandbox_mode=(mode) @sandbox_mode = mode # We also have to change the sandbox_mode of the Gql::Runtime inside the # query_interfaces. @present = QueryInterface.new(self, present_graph, sandbox_mode: mode) @future = QueryInterface.new(self, future_graph, sandbox_mode: mode) end # @return [Qernel::Dataset] Dataset used for the future. Needs to be updated with user input and then calculated. # def dataset_clone instrument("gql.performance.dataset_clone") do Marshal.load(Marshal.dump(@dataset)) end end # @return [QueryInterface] # def present # Disable Caching of Gqueries until a smart solution has been found # @present ||= QueryInterface.new(self, present_graph, :cache_prefix => "#{scenario.id}-present-#{scenario.present_updated_at}") @present ||= QueryInterface.new(self, present_graph) end # @return [QueryInterface] # def future # Disable Caching of Gqueries until a smart solution has been found # QueryInterface.new(self, future_graph, :cache_prefix => "#{scenario.id}-#{scenario.updated_at}") @future ||= QueryInterface.new(self, future_graph) end # Are the graphs calculated? If true, prevent the programmers to add further # update statements. Because they won't affect the system anymore. # # When calculated changes through update statements # should no longer be allowed, as they won't have an impact on the # calculation (even though updating prices would work). # # @return [Boolean] # def calculated? @calculated == true end # Query the GQL, takes care of gql modifier strings. # # For performance reason it is suggested to pass a Gquery for 'query' # object rather than it's Gquery#query. Because parsing a gql statement # takes rather long time. # # @example Query with a Gquery instance # gql.query(Gquery.first) # @example Query with a string # gql.query("SUM(1.0, 2.0)") # => [[2010, 3.0],[2040,3.0]] # @example Query with a string that includes a query modifier (present/future) # gql.query("present:SUM(1.0, 2.0)") # => 3.0 # @example Query with a proc/lambda # gql.query(-> { SUM(1,2) }) # => 3 # # @param query [String, Gquery, Proc] A query object # @param rescue_resultset [ResultSet] A ResultSet that is return in case of errors. # @return [ResultSet] Result query, depending on its gql_modifier # def query(gquery_or_string, rescue_with = nil) if gquery_or_string.is_a?(::Gquery) modifier = gquery_or_string.gql_modifier query = gquery_or_string elsif gquery_or_string.is_a?(String) modifier = gquery_or_string.match(Gquery::GQL_MODIFIER_REGEXP).captures.first rescue nil query = gquery_or_string.sub(Gquery::GQL_MODIFIER_REGEXP, '') elsif gquery_or_string.respond_to?(:call) query, modifier = gquery_or_string, nil end query_with_modifier(query, modifier) rescue => e if rescue_with == :debug ResultSet.create([[2010, e.inspect], [2040, e.inspect]]) elsif rescue_with == :airbrake # TODO: This fails on offline setups. Convert to a notification # TODO: something's broken here with airbrake 3.0.5: # undefined method `backtrace' for #<Hash:0x007fda54900b88> ?! # https://github.com/airbrake/airbrake/issues/19 Airbrake.notify(:error_message => e.message, :backtrace => caller) unless APP_CONFIG[:standalone] ResultSet::INVALID elsif rescue_with.present? rescue_with else raise e unless rescue_with end end # Run a query with the strategy defined in the parameter def query_with_modifier(query, strategy) key = query.respond_to?(:key) ? query.key : 'custom' instrument("gql.query.#{key}.#{strategy}") do if strategy.nil? query_standard(query) elsif Gquery::GQL_MODIFIERS.include?(strategy.strip) send("query_#{strategy}", query) end end rescue Exception => e raise "Error running #{key}: #{e.inspect}" end # Connects datasets to a present and future graph. # Updates them with user inputs and calculates. # After being prepared graphs are ready to be queried. # This method can only be prepared once. # # This method is "lazy-" called from a {Gql::QueryInterface} object, # when there is no cached result for a Gquery. # # When to prepare: # - For querying # - For working/inspecting the graph (e.g. from the command line) # def prepare log = 'gql.performance.' instrument(log+'init_datasets') { init_datasets } instrument(log+'update_graphs') { update_graphs } instrument(log+'calculate_graphs') { calculate_graphs } end # Runs an array of gqueries. The gquery list might be expressed in all the formats accepted # by Gquery#get, ie key or id # # @param [Array<String>] # @return [Hash<String => ResultSet>] # def query_multiple(gquery_keys) gquery_keys = gquery_keys - ["null", "undefined"] rescue_with = Rails.env.production? ? :airbrake : :debug gquery_keys.inject({}) do |hsh, key| result = if gquery = (Gquery.get(key) rescue nil) and !gquery.converters? query(gquery, rescue_with) else # Why this? Hmm. Seems like we only really want to execute if it's a Gql query # (every gql query contains a "(" and ")"). If it represents a non-existing # gquery key, then return rescue_with (which probably used to be a 'ERROR' earlier). key.include?('(') ? query(key, rescue_with) : rescue_with end hsh.merge! key => result hsh end end def init_datasets present_graph.dataset ||= dataset_clone future_graph.dataset = dataset_clone assign_attributes_from_scenario end # Inside GQL, functions and Gqueries we had some references to # Current.scenario. The aim of this method is to assign all the needed # attributes. Ideally they will be replaced with a different way. def assign_attributes_from_scenario @present_graph.year = @scenario.start_year @future_graph.year = @scenario.end_year @present_graph.number_of_years = @scenario.years @future_graph.number_of_years = @scenario.years @present_graph.use_fce = @scenario.use_fce @future_graph.use_fce = @scenario.use_fce end def update_graphs # 2011-08-15: the present has to be prepared first. otherwise # updating the future won't work (we need the present values) update_present update_future end def calculate_graphs present_graph.calculate future_graph.calculate @calculated = true end def update_present instrument('gql.performance.present.update_present') do scenario.inputs_present.each { |input, value| update_graph(present, input, value) } end end def update_future instrument('gql.performance.future.update_future') do scenario.inputs_before.each { |input, value| update_graph(future, input, value) } scenario.inputs_future.each { |input, value| update_graph(future, input, value) } end end # @param graph a Qernel::Graph or :present, :future # def update_graph(graph, input, value) case graph when :present then graph = present when :future then graph = future end graph.query(input, value) end # Standard query without modifiers. Queries present and future graph. # # @param query [String, Gquery] the single query. # @return [ResultSet] Result query, depending on its gql_modifier # def query_standard(query) ResultSet.create [ [scenario.start_year, query_present(query)], [scenario.end_year, query_future(query)] ] end # @param query [String] The query # @return [Float] The result of the present graph # def query_present(query) present.query(query) end # @param query [String] The query # @return [Float] The result of the future graph # def query_future(query) future.query(query) end end end