Class: Aspera::Cli::Plugins::Config
- Defined in:
- lib/aspera/cli/plugins/config.rb
Overview
Manage the CLI config file
Constant Summary collapse
- PRESET_GBL_ACTIONS =
Legacy actions available globally
%i[list overview lookup secure].freeze
- PRESET_EXIST_ACTIONS =
Operations requiring that preset exists
%i[show delete get unset].freeze
- PRESET_INSTANCE_ACTIONS =
require id
%i[initialize update ask set].concat(PRESET_EXIST_ACTIONS).freeze
- PRESET_ALL_ACTIONS =
(PRESET_GBL_ACTIONS + PRESET_INSTANCE_ACTIONS).freeze
- ACTIONS =
%i[ preset open documentation genkey pubkey remote_certificate gem plugins tokens echo download wizard detect coffee image ascp sync transferd email_test smtp_settings proxy_check folder file check_update initdemo vault test platform ].freeze
Constants inherited from Base
Base::ALL_OPS, Base::GLOBAL_OPS, Base::INSTANCE_OPS, Base::MAX_ITEMS, Base::MAX_PAGES, Base::REGEX_LOOKUP_ID_BY_FIELD
Instance Attribute Summary collapse
-
#gem_url ⇒ Object
readonly
$HOME/.aspera/‘program_name`.
-
#main_folder ⇒ Object
Returns the value of attribute main_folder.
-
#option_cache_tokens ⇒ Object
Returns the value of attribute option_cache_tokens.
-
#option_config_file ⇒ Object
Returns the value of attribute option_config_file.
-
#option_http_options ⇒ Object
Returns the value of attribute option_http_options.
-
#option_ignore_cert_host_port ⇒ Object
Returns the value of attribute option_ignore_cert_host_port.
-
#option_insecure ⇒ Object
Returns the value of attribute option_insecure.
-
#option_warn_insecure_cert ⇒ Object
Returns the value of attribute option_warn_insecure_cert.
-
#progress_bar ⇒ Object
readonly
Returns the value of attribute progress_bar.
Attributes inherited from Base
Class Method Summary collapse
-
.deep_clone(val) ⇒ Object
Deep clone hash so that it does not get modified in case of display and secret hide.
-
.default_app_main_folder(app_name:) ⇒ String
Product config folder (~/.aspera/<name>).
-
.gem_plugins_folder ⇒ Object
Folder containing plugins in the gem’s main folder.
-
.gem_src_root ⇒ Object
Go up as many times as englobing modules (not counting class, as it is a file).
-
.module_family_folder ⇒ Object
Product family folder (~/.aspera).
Instance Method Summary collapse
-
#add_plugin_default_preset(plugin_name_sym) ⇒ Object
Loads default parameters of plugin if no -P parameter and if there is a section defined for the plugin in the “default” section Try to find: conf[conf[plugin_str]].
-
#canonical_url(url) ⇒ Object
Version of URL without trailing “/” and removing default port.
- #check_gem_version ⇒ Object
- #config_checksum ⇒ Object
- #defaults_set(plugin_name, preset_name, preset_values, option_default, option_override) ⇒ Object
-
#email_settings ⇒ Hash
Email server setting with defaults if not defined.
-
#execute_action ⇒ Object
Main action procedure for plugin.
- #execute_action_ascp ⇒ Object
- #execute_action_transferd ⇒ Object
- #execute_connect_action ⇒ Object
- #execute_preset(action: nil, name: nil) ⇒ Object
-
#execute_test ⇒ Object
Artificially raise an exception for tests.
-
#execute_vault ⇒ Hash
Result of execution of vault command.
- #get_plugin_default_config_name(plugin_name_sym) ⇒ String
-
#global_default_preset ⇒ Object
Get the default global preset, or set default one.
- #ignore_cert?(address, port) ⇒ Boolean
-
#initialize(**_) ⇒ Config
constructor
A new instance of Config.
-
#lookup_preset(url:, username:) ⇒ Object
Look for a preset that has the corresponding URL and username.
-
#lookup_secret(url:, username:, mandatory: false) ⇒ Object
Lookup the corresponding secret for the given URL and usernames.
- #option_http_proxy ⇒ Object
- #option_http_proxy=(value) ⇒ Object
- #option_plugin_folder ⇒ Object
- #option_plugin_folder=(value) ⇒ Object
- #option_preset ⇒ Object
- #option_preset=(value) ⇒ Object
- #option_use_product ⇒ Object
- #option_use_product=(value) ⇒ Object
- #periodic_check_newer_gem_version ⇒ Object
-
#preset_by_name(config_name, include_path = []) ⇒ Object
Copy of the hash from name (also expands possible includes).
-
#read_config_file ⇒ Object
Read config file and validate format.
-
#save_config_file_if_needed ⇒ Object
Save current configuration to config file.
-
#send_email_template(email_template_default: nil, values: {}) ⇒ Object
Send email using ERB template.
-
#set_global_default(key, value) ⇒ Object
Set parameter and value in global config Creates one if none already created.
- #set_preset_key(preset, param_name, param_value) ⇒ Object
-
#trusted_cert_locations ⇒ Object
Only files.
-
#trusted_cert_locations=(path_list) ⇒ Object
Add files, folders or default locations to the certificate store.
-
#update_http_session(http_session) ⇒ Object
Called every time a new REST HTTP session is opened to set user-provided options.
-
#vault ⇒ Object
Vault, from options or cache.
-
#vault_value(name) ⇒ String
Value from vault matching <name>.<param>.
Methods inherited from Base
#add_manual_header, #config, declare_options, #do_bulk_operation, #entity_execute, #formatter, #instance_identifier, #list_entities_limit_offset_total_count, #lookup_entity_by_field, #options, #persistency, #query_read_delete, #transfer, #value_create_modify
Constructor Details
#initialize(**_) ⇒ Config
Returns a new instance of Config.
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 |
# File 'lib/aspera/cli/plugins/config.rb', line 75 def initialize(**_) # We need to defer parsing of options until we have the config file, so we can use @extend with @preset super @use_plugin_defaults = true @config_presets = nil @config_checksum_on_disk = nil @vault_instance = nil @pac_exec = nil @sdk_default_location = false @option_insecure = false @option_warn_insecure_cert = true @option_ignore_cert_host_port = [] @option_http_options = {} @ssl_warned_urls = [] @option_cache_tokens = true @main_folder = nil @option_config_file = nil # Store is used for ruby https @certificate_store = nil # Paths are used for ascp @certificate_paths = nil @progress_bar = nil # Option to set main folder .declare( :home, 'Home folder for tool', handler: {o: self, m: :main_folder}, types: String, default: self.class.default_app_main_folder(app_name: Info::CMD_NAME) ) . Log.log.debug{"#{Info::CMD_NAME} folder: #{@main_folder}"} # Data persistency manager, created by config plugin, set for global object context.persistency = PersistencyFolder.new(File.join(@main_folder, PERSISTENCY_FOLDER)) # Set folders for plugin lookup Plugins::Factory.instance.add_lookup_folder(self.class.gem_plugins_folder) Plugins::Factory.instance.add_lookup_folder(File.join(@main_folder, ASPERA_PLUGINS_FOLDERNAME)) # Option to set config file .declare( :config_file, 'Path to YAML file with preset configuration', handler: {o: self, m: :option_config_file}, default: File.join(@main_folder, DEFAULT_CONFIG_FILENAME) ) . # Read config file (set @config_presets) read_config_file # Add preset handler (needed for smtp) ExtendedValue.instance.set_handler(EXTEND_PRESET, lambda{ |v| preset_by_name(v)}) ExtendedValue.instance.set_handler(EXTEND_VAULT, lambda{ |v| vault_value(v)}) # Load defaults before it can be overridden add_plugin_default_preset(CONF_GLOBAL_SYM) # Vault options .declare(:secret, 'Secret for access keys') .declare(:vault, 'Vault for secrets', types: Hash, default: {}) .declare(:vault_password, 'Vault password') . # Declare generic plugin options only after handlers are declared Base.() # Configuration options .declare(:no_default, 'Do not load default configuration for plugin', values: :none, short: 'N'){@use_plugin_defaults = false} .declare(:preset, 'Load the named option preset from current config file', short: 'P', handler: {o: self, m: :option_preset}) .declare(:version_check_days, 'Period in days to check new version (zero to disable)', coerce: Integer, default: DEFAULT_CHECK_NEW_VERSION_DAYS) .declare(:plugin_folder, 'Folder where to find additional plugins', handler: {o: self, m: :option_plugin_folder}) # Declare wizard options @wizard = Wizard.new(self, @main_folder) # Transfer SDK options .declare(:ascp_path, 'Ascp: Path to ascp', handler: {o: Ascp::Installation.instance, m: :ascp_path}) .declare(:use_product, 'Ascp: Use ascp from specified product', handler: {o: self, m: :option_use_product}) .declare(:sdk_url, 'Ascp: URL to get Aspera Transfer Executables', default: SpecialValues::DEF) .declare(:locations_url, 'Ascp: URL to get locations of Aspera Transfer Daemon', handler: {o: Ascp::Installation.instance, m: :transferd_urls}) .declare(:sdk_folder, 'Ascp: SDK folder path', handler: {o: Products::Transferd, m: :sdk_directory}) .declare(:progress_bar, 'Display progress bar', values: :bool, default: Environment.terminal?) # Email options .declare(:smtp, 'Email: SMTP configuration', types: Hash) .declare(:notify_to, 'Email: Recipient for notification of transfers') .declare(:notify_template, 'Email: ERB template for notification of transfers') # HTTP options .declare(:insecure, 'HTTP/S: Do not validate any certificate', values: :bool, handler: {o: self, m: :option_insecure}, default: :no) .declare(:ignore_certificate, 'HTTP/S: Do not validate certificate for these URLs', types: Array, handler: {o: self, m: :option_ignore_cert_host_port}) .declare(:warn_insecure, 'HTTP/S: Issue a warning if certificate is ignored', values: :bool, handler: {o: self, m: :option_warn_insecure_cert}, default: :yes) .declare(:cert_stores, 'HTTP/S: List of folder with trusted certificates', types: [Array, String], handler: {o: self, m: :trusted_cert_locations}) .declare(:http_options, 'HTTP/S: Options for HTTP/S socket', types: Hash, handler: {o: self, m: :option_http_options}, default: {}) .declare(:http_proxy, 'HTTP/S: URL for proxy with optional credentials', types: String, handler: {o: self, m: :option_http_proxy}) .declare(:cache_tokens, 'Save and reuse OAuth tokens', values: :bool, handler: {o: self, m: :option_cache_tokens}) .declare(:fpac, 'Proxy auto configuration script') .declare(:proxy_credentials, 'HTTP proxy credentials for fpac: user, password', types: Array) . @progress_bar = TransferProgress.new if .get_option(:progress_bar) # Check SDK folder is set or not, for compatibility, we check in two places sdk_dir = Products::Transferd.sdk_directory rescue nil if sdk_dir.nil? @sdk_default_location = true Log.log.debug('SDK folder is not set, checking default') # New location sdk_dir = self.class.default_app_main_folder(app_name: TRANSFERD_APP_NAME) Log.log.debug{"Checking: #{sdk_dir}"} if !Dir.exist?(sdk_dir) Log.log.debug{"No such folder: #{sdk_dir}"} # Former location former_sdk_folder = File.join(self.class.default_app_main_folder(app_name: Info::CMD_NAME), TRANSFERD_APP_NAME) Log.log.debug{"Checking: #{former_sdk_folder}"} sdk_dir = former_sdk_folder if Dir.exist?(former_sdk_folder) end Log.log.debug{"Using: #{sdk_dir}"} Products::Transferd.sdk_directory = sdk_dir end pac_script = .get_option(:fpac) # Create PAC executor if !pac_script.nil? @pac_exec = ProxyAutoConfig.new(pac_script).register_uri_generic proxy_user_pass = .get_option(:proxy_credentials) if !proxy_user_pass.nil? Aspera.assert(proxy_user_pass.length.eql?(2), type: Cli::BadArgument){"proxy_credentials shall have two elements (#{proxy_user_pass.length})"} @pac_exec.proxy_user = proxy_user_pass[0] @pac_exec.proxy_pass = proxy_user_pass[1] end end RestParameters.instance.user_agent = Info::CMD_NAME RestParameters.instance. = @progress_bar RestParameters.instance.session_cb = lambda{ |http_session| update_http_session(http_session)} # Check http options that are global keys_to_delete = [] @option_http_options.each do |k, v| method = "#{k}=".to_sym if RestParameters.instance.respond_to?(method) keys_to_delete.push(k) RestParameters.instance.send(method, v) elsif k.eql?('ssl_options') keys_to_delete.push(k) # NOTE: here is a hack that allows setting SSLContext options Aspera.assert_type(v, Array){'ssl_options'} # Start with default options = OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:options] v.each do |opt| case opt when Integer = opt when String name = "OP_#{opt.start_with?('-') ? opt[1..] : opt}".upcase raise Cli::BadArgument, "Unknown ssl_option: #{name}, use one of: #{OpenSSL::SSL.constants.grep(/^OP_/).map{ |c| c.to_s.sub(/^OP_/, '')}.join(', ')}" if !OpenSSL::SSL.const_defined?(name) if opt.start_with?('-') &= ~OpenSSL::SSL.const_get(name) else |= OpenSSL::SSL.const_get(name) end else Aspera.error_unexpected_value(opt.class.name){'Expected String or Integer in ssl_options'} end end OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:options] = elsif OAuth::Factory.instance.parameters.key?(k.to_sym) keys_to_delete.push(k) OAuth::Factory.instance.parameters[k.to_sym] = v end end keys_to_delete.each{ |k| @option_http_options.delete(k)} OAuth::Factory.instance.persist_mgr = persistency if @option_cache_tokens OAuth::Web.additional_info = "#{Info::CMD_NAME} v#{Cli::VERSION}" Transfer::Parameters.file_list_folder = File.join(@main_folder, 'filelists') RestErrorAnalyzer.instance.log_file = File.join(@main_folder, 'rest_exceptions.log') # Register aspera REST call error handlers RestErrorsAspera.register_handlers end |
Instance Attribute Details
#gem_url ⇒ Object (readonly)
$HOME/.aspera/‘program_name`
465 466 467 |
# File 'lib/aspera/cli/plugins/config.rb', line 465 def gem_url @gem_url end |
#main_folder ⇒ Object
Returns the value of attribute main_folder.
238 239 240 |
# File 'lib/aspera/cli/plugins/config.rb', line 238 def main_folder @main_folder end |
#option_cache_tokens ⇒ Object
Returns the value of attribute option_cache_tokens.
238 239 240 |
# File 'lib/aspera/cli/plugins/config.rb', line 238 def option_cache_tokens @option_cache_tokens end |
#option_config_file ⇒ Object
Returns the value of attribute option_config_file.
466 467 468 |
# File 'lib/aspera/cli/plugins/config.rb', line 466 def option_config_file @option_config_file end |
#option_http_options ⇒ Object
Returns the value of attribute option_http_options.
238 239 240 |
# File 'lib/aspera/cli/plugins/config.rb', line 238 def @option_http_options end |
#option_ignore_cert_host_port ⇒ Object
Returns the value of attribute option_ignore_cert_host_port.
239 240 241 |
# File 'lib/aspera/cli/plugins/config.rb', line 239 def option_ignore_cert_host_port @option_ignore_cert_host_port end |
#option_insecure ⇒ Object
Returns the value of attribute option_insecure.
238 239 240 |
# File 'lib/aspera/cli/plugins/config.rb', line 238 def option_insecure @option_insecure end |
#option_warn_insecure_cert ⇒ Object
Returns the value of attribute option_warn_insecure_cert.
238 239 240 |
# File 'lib/aspera/cli/plugins/config.rb', line 238 def option_warn_insecure_cert @option_warn_insecure_cert end |
#progress_bar ⇒ Object (readonly)
Returns the value of attribute progress_bar.
239 240 241 |
# File 'lib/aspera/cli/plugins/config.rb', line 239 def @progress_bar end |
Class Method Details
.deep_clone(val) ⇒ Object
Deep clone hash so that it does not get modified in case of display and secret hide
56 57 58 |
# File 'lib/aspera/cli/plugins/config.rb', line 56 def deep_clone(val) return Marshal.load(Marshal.dump(val)) end |
.default_app_main_folder(app_name:) ⇒ String
Returns Product config folder (~/.aspera/<name>).
68 69 70 71 72 |
# File 'lib/aspera/cli/plugins/config.rb', line 68 def default_app_main_folder(app_name:) Aspera.assert_type(app_name, String) Aspera.assert(!app_name.empty?) return File.join(module_family_folder, app_name) end |
.gem_plugins_folder ⇒ Object
Folder containing plugins in the gem’s main folder
44 45 46 |
# File 'lib/aspera/cli/plugins/config.rb', line 44 def gem_plugins_folder File.dirname(File.(__FILE__)) end |
.gem_src_root ⇒ Object
Go up as many times as englobing modules (not counting class, as it is a file)
50 51 52 53 |
# File 'lib/aspera/cli/plugins/config.rb', line 50 def gem_src_root # Module.nesting[2] is Cli::Plugins File.(Module.nesting[2].to_s.gsub('::', '/').gsub(%r{[^/]+}, '..'), gem_plugins_folder) end |
.module_family_folder ⇒ Object
Returns product family folder (~/.aspera).
61 62 63 64 65 |
# File 'lib/aspera/cli/plugins/config.rb', line 61 def module_family_folder user_home_folder = Dir.home Aspera.assert(Dir.exist?(user_home_folder), type: Cli::Error){"Home folder does not exist: #{user_home_folder}. Check your user environment."} return File.join(user_home_folder, ASPERA_HOME_FOLDER_NAME) end |
Instance Method Details
#add_plugin_default_preset(plugin_name_sym) ⇒ Object
Loads default parameters of plugin if no -P parameter and if there is a section defined for the plugin in the “default” section Try to find: conf[conf[plugin_str]]
406 407 408 409 410 411 |
# File 'lib/aspera/cli/plugins/config.rb', line 406 def add_plugin_default_preset(plugin_name_sym) default_config_name = get_plugin_default_config_name(plugin_name_sym) Log.log.debug{"add_plugin_default_preset:#{plugin_name_sym}:#{default_config_name}"} .add_option_preset(preset_by_name(default_config_name), 'default_plugin', override: false) unless default_config_name.nil? return end |
#canonical_url(url) ⇒ Object
Version of URL without trailing “/” and removing default port
1167 1168 1169 |
# File 'lib/aspera/cli/plugins/config.rb', line 1167 def canonical_url(url) url.chomp('/').sub(%r{^(https://[^/]+):443$}, '\1') end |
#check_gem_version ⇒ Object
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 |
# File 'lib/aspera/cli/plugins/config.rb', line 353 def check_gem_version latest_version = begin Rest.new(base_url: 'https://rubygems.org/api/v1').read("versions/#{Info::GEM_NAME}/latest.json")['version'] rescue StandardError Log.log.warn('Could not retrieve latest gem version on rubygems.') '0' end if Gem::Version.new(Environment.ruby_version) < Gem::Version.new(Info::RUBY_FUTURE_MINIMUM_VERSION) Log.log.warn do "Note that a future version will require Ruby version #{Info::RUBY_FUTURE_MINIMUM_VERSION} at minimum, " \ "you are using #{Environment.ruby_version}" end end return { name: Info::GEM_NAME, current: Cli::VERSION, latest: latest_version, need_update: Gem::Version.new(Cli::VERSION) < Gem::Version.new(latest_version) } end |
#config_checksum ⇒ Object
517 518 519 |
# File 'lib/aspera/cli/plugins/config.rb', line 517 def config_checksum JSON.generate(@config_presets).hash end |
#defaults_set(plugin_name, preset_name, preset_values, option_default, option_override) ⇒ Object
423 424 425 426 427 428 429 430 431 432 433 434 |
# File 'lib/aspera/cli/plugins/config.rb', line 423 def defaults_set(plugin_name, preset_name, preset_values, option_default, option_override) @config_presets[CONF_PRESET_DEFAULTS] ||= {} raise Cli::Error, "A default configuration already exists for plugin '#{plugin_name}' (use --override=yes or --default=no)" \ if !option_override && option_default && @config_presets[CONF_PRESET_DEFAULTS].key?(plugin_name) raise Cli::Error, "Preset already exists: #{preset_name} (use --override=yes or provide alternate name on command line)" \ if !option_override && @config_presets.key?(preset_name) if option_default formatter.display_status("Setting config preset as default for #{plugin_name}") @config_presets[CONF_PRESET_DEFAULTS][plugin_name.to_s] = preset_name end @config_presets[preset_name] = preset_values end |
#email_settings ⇒ Hash
Returns email server setting with defaults if not defined.
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 |
# File 'lib/aspera/cli/plugins/config.rb', line 994 def email_settings smtp = .get_option(:smtp, mandatory: true) # Change keys from string into symbol smtp = smtp.symbolize_keys unsupported = smtp.keys - SMTP_CONF_PARAMS raise Cli::Error, "Unsupported SMTP parameter: #{unsupported.join(', ')}, use: #{SMTP_CONF_PARAMS.join(', ')}" unless unsupported.empty? # Defaults # smtp[:ssl] = nil (false) smtp[:tls] = !smtp[:ssl] unless smtp.key?(:tls) smtp[:port] ||= if smtp[:tls] 587 elsif smtp[:ssl] 465 else 25 end smtp[:from_email] ||= smtp[:username] if smtp.key?(:username) smtp[:from_name] ||= smtp[:from_email].sub(/@.*$/, '').gsub(/[^a-zA-Z]/, ' ').capitalize if smtp.key?(:username) smtp[:domain] ||= smtp[:from_email].sub(/^.*@/, '') if smtp.key?(:from_email) # Check minimum required %i[server port domain].each do |n| Aspera.assert(smtp.key?(n)){"Missing mandatory smtp parameter: #{n}"} end Log.log.debug{"smtp=#{smtp}"} return smtp end |
#execute_action ⇒ Object
Main action procedure for plugin
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 |
# File 'lib/aspera/cli/plugins/config.rb', line 828 def execute_action action = .get_next_command(ACTIONS) case action when :preset # Newer syntax return execute_preset when :open Environment.instance.open_editor(@option_config_file.to_s) return Main.result_nothing when :documentation section = .get_next_argument('private key file path', mandatory: false) section = "##{section}" unless section.nil? Environment.instance.open_uri("#{Info::DOC_URL}#{section}") return Main.result_nothing when :genkey # Generate new rsa key private_key_path = .get_next_argument('private key file path') private_key_length = .get_next_argument('size in bits', mandatory: false, validation: Integer, default: OAuth::Jwt::DEFAULT_PRIV_KEY_LENGTH) OAuth::Jwt.generate_rsa_private_key(path: private_key_path, length: private_key_length) return Main.result_status("Generated #{private_key_length} bit RSA key: #{private_key_path}") when :pubkey # Get pub key private_key_pem = .get_next_argument('private key PEM value') return Main.result_text(OpenSSL::PKey::RSA.new(private_key_pem).public_key.to_s) when :remote_certificate cert_action = .get_next_command(%i[chain only name]) remote_url = .get_next_argument('remote URL') remote_chain = Rest.remote_certificate_chain(remote_url, as_string: false) raise "No certificate found for #{remote_url}" unless remote_chain&.first case cert_action when :chain return Main.result_text(remote_chain.map(&:to_pem).join("\n")) when :only return Main.result_text(remote_chain.first.to_pem) when :name return Main.result_text(remote_chain.first.subject.to_a.find{ |name, _, _| name == 'CN'}[1]) end when :echo # Display the content of a value given on command line return Main.result_auto(.get_next_argument('value', validation: nil)) when :download file_url = .get_next_argument('source URL').chomp file_dest = .get_next_argument('file path', mandatory: false) file_dest = File.join(transfer.destination_folder(Transfer::Spec::DIRECTION_RECEIVE), file_url.gsub(%r{.*/}, '')) if file_dest.nil? formatter.display_status("Downloading: #{file_url}") Rest.new(base_url: file_url).call(operation: 'GET', save_to_file: file_dest) return Main.result_status("Saved to: #{file_dest}") when :tokens require 'aspera/api/node' case .get_next_command(%i{flush list show}) when :flush return Main.result_value_list(OAuth::Factory.instance.flush_tokens, name: 'file') when :list return Main.result_object_list(OAuth::Factory.instance.persisted_tokens) when :show data = OAuth::Factory.instance.get_token_info(instance_identifier) raise Cli::Error, 'Unknown identifier' if data.nil? return Main.result_single_object(data) end when :plugins case .get_next_command(%i[list create]) when :list result = [] Plugins::Factory.instance.plugin_list.each do |name| plugin_class = Plugins::Factory.instance.plugin_class(name) result.push({ plugin: name, detect: Formatter.tick(plugin_class.respond_to?(:detect)), wizard: Formatter.tick(plugin_class.instance_methods.include?(:wizard)), path: Plugins::Factory.instance.plugin_source(name) }) end return Main.result_object_list(result, fields: %w[plugin detect wizard path]) when :create plugin_name = .get_next_argument('name').downcase destination_folder = .get_next_argument('folder', mandatory: false) || File.join(@main_folder, ASPERA_PLUGINS_FOLDERNAME) plugin_file = File.join(destination_folder, "#{plugin_name}.rb") content = <<~END_OF_PLUGIN_CODE require 'aspera/cli/plugins/base' module Aspera module Cli module Plugins class #{plugin_name.snake_to_capital} < Base ACTIONS=[] def execute_action return Main.result_status('You called plugin #{plugin_name}') end end end end end END_OF_PLUGIN_CODE File.write(plugin_file, content) return Main.result_status("Created #{plugin_file}") end when :detect, :wizard # Interactive mode .ask_missing_mandatory = true # Detect plugins by url and optional query apps = @wizard.identify_plugins_for_url.freeze return Main.result_object_list(apps) if action.eql?(:detect) return @wizard.find(apps) when :coffee return Main.result_image(COFFEE_IMAGE_URL) when :image return Main.result_image(.get_next_argument('image URI or blob')) when :ascp execute_action_ascp when :sync case .get_next_command(%i[spec]) when :spec fields, data = Transfer::SpecDoc.man_table(Formatter, include_option: true, agent_columns: false, schema: Sync::Operations::CONF_SCHEMA) return Main.result_object_list(data, fields: fields.map(&:to_s)) else Aspera.error_unreachable_line end when :transferd execute_action_transferd when :gem case .get_next_command(%i[path version name]) when :path then return Main.result_text(self.class.gem_src_root) when :version then return Main.result_text(Cli::VERSION) when :name then return Main.result_text(Info::GEM_NAME) else Aspera.error_unreachable_line end when :folder return Main.result_text(@main_folder) when :file return Main.result_text(@option_config_file) when :email_test send_email_template(email_template_default: EMAIL_TEST_TEMPLATE) return Main.result_nothing when :smtp_settings return Main.result_single_object(email_settings) when :proxy_check # Ensure fpac was provided .get_option(:fpac, mandatory: true) server_url = .get_next_argument('server url') return Main.result_text(@pac_exec.get_proxies(server_url)) when :check_update return Main.result_single_object(check_gem_version) when :initdemo if @config_presets.key?(DEMO_PRESET) Log.log.warn{"Demo server preset already present: #{DEMO_PRESET}"} else Log.log.info{"Creating Demo server preset: #{DEMO_PRESET}"} @config_presets[DEMO_PRESET] = { 'url' => "ssh://#{DEMO_SERVER}.asperasoft.com:33001", 'username' => ASPERA, 'ssAP'.downcase.reverse + 'drow'.reverse => DEMO_SERVER + ASPERA # cspell:disable-line } end @config_presets[CONF_PRESET_DEFAULTS] ||= {} if @config_presets[CONF_PRESET_DEFAULTS].key?(SERVER_COMMAND) Log.log.warn{"Server default preset already set to: #{@config_presets[CONF_PRESET_DEFAULTS][SERVER_COMMAND]}"} Log.log.warn{"Use #{DEMO_PRESET} for demo: -P#{DEMO_PRESET}"} unless DEMO_PRESET.eql?(@config_presets[CONF_PRESET_DEFAULTS][SERVER_COMMAND]) else @config_presets[CONF_PRESET_DEFAULTS][SERVER_COMMAND] = DEMO_PRESET Log.log.info{"Setting server default preset to : #{DEMO_PRESET}"} end return Main.result_status('Done') when :vault then execute_vault when :test then return execute_test when :platform return Main.result_text(Environment.instance.architecture) else Aspera.error_unreachable_line end end |
#execute_action_ascp ⇒ Object
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 |
# File 'lib/aspera/cli/plugins/config.rb', line 610 def execute_action_ascp command = .get_next_command(%i[connect use show products info install spec schema errors]) case command when :connect return execute_connect_action when :use ascp_path = .get_next_argument('path to ascp') Ascp::Installation.instance.ascp_path = ascp_path formatter.display_status("ascp version: #{Ascp::Installation.instance.get_ascp_version(ascp_path)}") set_global_default(:ascp_path, ascp_path) return Main.result_nothing when :show return Main.result_text(Ascp::Installation.instance.path(:ascp)) when :info # Collect info from ascp executable data = Ascp::Installation.instance.ascp_info # Add command line transfer spec data['ts'] = transfer.option_transfer_spec # Add keys DataRepository::ELEMENTS.each_with_object(data){ |i, h| h[i.to_s] = DataRepository.instance.item(i)} # Declare those as secrets SecretHider::ADDITIONAL_KEYS_TO_HIDE.concat(DataRepository::ELEMENTS.map(&:to_s)) return Main.result_single_object(data) when :products command = .get_next_command(%i[list use]) case command when :list return Main.result_object_list(Ascp::Installation.instance.installed_products, fields: %w[name app_root]) when :use default_product = .get_next_argument('product name') Ascp::Installation.instance.use_ascp_from_product(default_product) set_global_default(:ascp_path, Ascp::Installation.instance.path(:ascp)) return Main.result_nothing end when :install # Reset to default location, if older default was used Products::Transferd.sdk_directory = self.class.default_app_main_folder(app_name: TRANSFERD_APP_NAME) if @sdk_default_location version = .get_next_argument('transferd version', mandatory: false) n, v = Ascp::Installation.instance.install_sdk(url: .get_option(:sdk_url, mandatory: true), version: version) return Main.result_status("Installed #{n} version #{v}") when :spec fields, data = Transfer::SpecDoc.man_table(Formatter, include_option: true) return Main.result_object_list(data, fields: fields.map(&:to_s)) when :schema schema = Transfer::Spec::SCHEMA.merge({'$comment'=>'DO NOT EDIT, this file was generated from the YAML.'}) agent = .get_next_argument('transfer agent name', mandatory: false) schema['properties'] = schema['properties'].select{ |_k, v| CommandLineBuilder.supported_by_agent(agent, v)} unless agent.nil? schema['properties'] = schema['properties'].sort.to_h return Main.result_single_object(schema) when :errors error_data = [] Ascp::Management::ERRORS.each_pair do |code, prop| error_data.push(code: code, mnemonic: prop[:c], retry: prop[:r], info: prop[:a]) end return Main.result_object_list(error_data) else Aspera.error_unexpected_value(command) end Aspera.error_unreachable_line end |
#execute_action_transferd ⇒ Object
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 |
# File 'lib/aspera/cli/plugins/config.rb', line 670 def execute_action_transferd command = .get_next_command(%i[list install]) case command when :install # Reset to default location, if older default was used Products::Transferd.sdk_directory = self.class.default_app_main_folder(app_name: TRANSFERD_APP_NAME) if @sdk_default_location version = .get_next_argument('transferd version', mandatory: false) n, v = Ascp::Installation.instance.install_sdk(url: .get_option(:sdk_url, mandatory: true), version: version) return Main.result_status("Installed #{n} version #{v}") when :list sdk_list = Ascp::Installation.instance.sdk_locations return Main.result_object_list( sdk_list, fields: sdk_list.first.keys - ['url'] ) else Aspera.error_unexpected_value(command) end Aspera.error_unreachable_line end |
#execute_connect_action ⇒ Object
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 |
# File 'lib/aspera/cli/plugins/config.rb', line 574 def execute_connect_action command = .get_next_command(%i[list info version]) if %i[info version].include?(command) connect_id = .get_next_argument('id or title') one_res = Products::Connect.instance.versions.find{ |i| i['id'].eql?(connect_id) || i['title'].eql?(connect_id)} raise Cli::BadIdentifier.new(:connect, connect_id) if one_res.nil? end case command when :list return Main.result_object_list(Products::Connect.instance.versions, fields: %w[id title version]) when :info one_res.delete('links') return Main.result_single_object(one_res) when :version all_links = one_res['links'] command = .get_next_command(%i[list download open]) if %i[download open].include?(command) link_title = .get_next_argument('title or rel') one_link = all_links.find{ |i| i['title'].eql?(link_title) || i['rel'].eql?(link_title)} raise "no such value: #{link_title}" if one_link.nil? end case command when :list return Main.result_object_list(all_links) when :download archive_path = one_link['href'] save_to_path = File.join(transfer.destination_folder(Transfer::Spec::DIRECTION_RECEIVE), archive_path.gsub(%r{.*/}, '')) Products::Connect.instance.cdn_api.call(operation: 'GET', subpath: archive_path, save_to_file: save_to_path) return Main.result_status("Downloaded: #{save_to_path}") when :open Environment.instance.open_uri(one_link['href']) return Main.result_status("Opened: #{one_link['href']}") end end end |
#execute_preset(action: nil, name: nil) ⇒ Object
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 |
# File 'lib/aspera/cli/plugins/config.rb', line 698 def execute_preset(action: nil, name: nil) action = .get_next_command(PRESET_ALL_ACTIONS) if action.nil? name = instance_identifier if name.nil? && PRESET_INSTANCE_ACTIONS.include?(action) name = global_default_preset if name.eql?(GLOBAL_DEFAULT_KEYWORD) # Those operations require existing option raise "no such preset: #{name}" if PRESET_EXIST_ACTIONS.include?(action) && !@config_presets.key?(name) case action when :list return Main.result_value_list(@config_presets.keys, name: 'name') when :overview # Display process modifies the value (hide secrets): we do not want to save removed secrets data = self.class.deep_clone(@config_presets) formatter.hide_secrets(data) result = [] data.each do |config, preset| preset.each do |parameter, value| result.push(CONF_OVERVIEW_KEYS.zip([config, parameter, value]).to_h) end end return Main.result_object_list(result, fields: CONF_OVERVIEW_KEYS) when :show return Main.result_single_object(self.class.deep_clone(@config_presets[name])) when :delete @config_presets.delete(name) return Main.result_status("Deleted: #{name}") when :get param_name = .get_next_argument('parameter name') value = @config_presets[name][param_name] raise "no such option in preset #{name} : #{param_name}" if value.nil? case value when Numeric, String then return Main.result_text(ExtendedValue.instance.evaluate(value.to_s)) end return Main.result_single_object(value) when :unset param_name = .get_next_argument('parameter name') @config_presets[name].delete(param_name) return Main.result_status("Removed: #{name}: #{param_name}") when :set param_name = .get_next_argument('parameter name') param_name = Manager.option_line_to_name(param_name) param_value = .get_next_argument('parameter value', validation: nil) set_preset_key(name, param_name, param_value) return Main.result_nothing when :initialize config_value = .get_next_argument('extended value', validation: Hash) Log.log.warn{"configuration already exists: #{name}, overwriting"} if @config_presets.key?(name) @config_presets[name] = config_value return Main.result_status("Modified: #{@option_config_file}") when :update # get unprocessed options = . Log.log.debug{"opts=#{}"} @config_presets[name] ||= {} @config_presets[name].merge!() return Main.result_status("Updated: #{name}") when :ask .ask_missing_mandatory = true @config_presets[name] ||= {} .get_next_argument('option names', multiple: true).each do |option_name| option_value = .get_interactive(option_name, option: true) @config_presets[name][option_name] = option_value end return Main.result_status("Updated: #{name}") when :lookup BasicAuth.() url = .get_option(:url, mandatory: true) user = .get_option(:username, mandatory: true) result = lookup_preset(url: url, username: user) raise Error, 'no such config found' if result.nil? return Main.result_single_object(result) when :secure identifier = .get_next_argument('config name', mandatory: false) preset_names = identifier.nil? ? @config_presets.keys : [identifier] secret_keywords = %w[password secret].freeze preset_names.each do |preset_name| preset = @config_presets[preset_name] next unless preset.is_a?(Hash) preset.each_key do |option_name| secret_keywords.each do |keyword| next unless option_name.end_with?(keyword) vault_label = preset_name incr = 0 until vault.get(label: vault_label, exception: false).nil? vault_label = "#{preset_name}#{incr}" incr += 1 end to_set = {label: vault_label, password: preset[option_name]} puts "need to encode #{preset_name}.#{option_name} -> #{vault_label} -> #{to_set}" # to_copy=%i[] vault.set(to_set) preset[option_name] = "@vault:#{vault_label}.password" end end end return Main.result_status('Secrets secured in vault: Make sure to save the vault password securely.') end end |
#execute_test ⇒ Object
Artificially raise an exception for tests
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 |
# File 'lib/aspera/cli/plugins/config.rb', line 1152 def execute_test case .get_next_command(%i[throw web]) when :throw # :type [String] # Options exception_class_name = .get_next_argument('exception class name', mandatory: true) exception_text = .get_next_argument('exception text', mandatory: true) type = Object.const_get(exception_class_name) Aspera.assert(type <= Exception){"#{type} is not an exception: #{type.class}"} raise type, exception_text when :web end end |
#execute_vault ⇒ Hash
Returns result of execution of vault command.
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 |
# File 'lib/aspera/cli/plugins/config.rb', line 1102 def execute_vault command = .get_next_command(%i[info list show create delete password]) case command when :info return Main.result_single_object(vault.info) when :list # , fields: %w(label url username password description) return Main.result_object_list(vault.list) when :show return Main.result_single_object(vault.get(label: .get_next_argument('label'))) when :create vault.set(.get_next_argument('info', validation: Hash).symbolize_keys) return Main.result_status('Secret added') when :delete label_to_delete = .get_next_argument('label') vault.delete(label: label_to_delete) return Main.result_status("Secret deleted: #{label_to_delete}") when :password Aspera.assert(vault.respond_to?(:change_password)){'Vault does not support password change'} vault.change_password(.get_next_argument('new_password')) return Main.result_status('Vault password updated') end end |
#get_plugin_default_config_name(plugin_name_sym) ⇒ String
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 |
# File 'lib/aspera/cli/plugins/config.rb', line 1072 def get_plugin_default_config_name(plugin_name_sym) Aspera.assert(!@config_presets.nil?){'config_presets shall be defined'} if !@use_plugin_defaults Log.log.debug('skip default config') return end if !@config_presets.key?(CONF_PRESET_DEFAULTS) Log.log.debug('No default section') return end Aspera.assert_type(@config_presets[CONF_PRESET_DEFAULTS], Hash){'default section'} if !@config_presets[CONF_PRESET_DEFAULTS].key?(plugin_name_sym.to_s) Log.log.debug("No default for #{plugin_name_sym}") return end default_config_name = @config_presets[CONF_PRESET_DEFAULTS][plugin_name_sym.to_s] if !@config_presets.key?(default_config_name) Log.log.error do "Default config name [#{default_config_name}] specified for plugin [#{plugin_name_sym}], but it does not exist in config file.\n" \ "Please fix the issue: either create preset with one parameter:\n" \ "#{Info::CMD_NAME} config id #{default_config_name} init @json:'{}'\n" \ "or remove default:\n#{Info::CMD_NAME} config id default remove #{plugin_name_sym}" end raise Cli::Error, "No such preset: #{default_config_name}" end Aspera.assert_type(@config_presets[default_config_name], Hash, type: Cli::Error){'preset type'} return default_config_name end |
#global_default_preset ⇒ Object
Get the default global preset, or set default one
414 415 416 417 418 419 420 421 |
# File 'lib/aspera/cli/plugins/config.rb', line 414 def global_default_preset result = get_plugin_default_config_name(CONF_GLOBAL_SYM) if result.nil? result = CONF_PRESET_GLOBAL set_preset_key(CONF_PRESET_DEFAULTS, CONF_GLOBAL_SYM, result) end return result end |
#ignore_cert?(address, port) ⇒ Boolean
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 |
# File 'lib/aspera/cli/plugins/config.rb', line 313 def ignore_cert?(address, port) endpoint = [address, port].freeze ignore_cert = false if @option_insecure || @option_ignore_cert_host_port.any?(endpoint) ignore_cert = true if @option_warn_insecure_cert base_url = "https://#{address}:#{port}" if !@ssl_warned_urls.include?(base_url) formatter.( :error, "#{Formatter::WARNING_FLASH} Ignoring certificate for: #{base_url}. Do not deactivate certificate verification in production." ) @ssl_warned_urls.push(base_url) end end end Log.log.debug{"ignore cert? #{endpoint} -> #{ignore_cert}"} return ignore_cert end |
#lookup_preset(url:, username:) ⇒ Object
Look for a preset that has the corresponding URL and username
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 |
# File 'lib/aspera/cli/plugins/config.rb', line 1173 def lookup_preset(url:, username:) # Remove extra info to maximize match url = canonical_url(url) Log.log.debug{"Lookup preset for #{username}@#{url}"} @config_presets.each_value do |v| next unless v.is_a?(Hash) conf_url = v['url'].is_a?(String) ? canonical_url(v['url']) : nil return self.class.deep_clone(v) if conf_url.eql?(url) && v['username'].eql?(username) end nil end |
#lookup_secret(url:, username:, mandatory: false) ⇒ Object
Lookup the corresponding secret for the given URL and usernames
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 |
# File 'lib/aspera/cli/plugins/config.rb', line 1187 def lookup_secret(url:, username:, mandatory: false) secret = .get_option(:secret) if secret.nil? conf = lookup_preset(url: url, username: username) if conf.is_a?(Hash) Log.log.debug{"Found preset #{conf} with URL and username"} secret = conf['password'] end raise "Please provide secret for #{username} using option: secret or by setting a preset for #{username}@#{url}." if secret.nil? && mandatory end return secret end |
#option_http_proxy ⇒ Object
296 297 298 |
# File 'lib/aspera/cli/plugins/config.rb', line 296 def option_http_proxy return ENV['http_proxy'] end |
#option_http_proxy=(value) ⇒ Object
300 301 302 303 |
# File 'lib/aspera/cli/plugins/config.rb', line 300 def option_http_proxy=(value) URI.parse(value) ENV['http_proxy'] = value end |
#option_plugin_folder ⇒ Object
500 501 502 |
# File 'lib/aspera/cli/plugins/config.rb', line 500 def option_plugin_folder return Plugins::Factory.instance.lookup_folders end |
#option_plugin_folder=(value) ⇒ Object
493 494 495 496 497 498 |
# File 'lib/aspera/cli/plugins/config.rb', line 493 def option_plugin_folder=(value) Aspera.assert_values(value.class, [String, Array]){'plugin folder'} value = [value] if value.is_a?(String) Aspera.assert(value.all?(String)){'plugin folder'} value.each{ |f| Plugins::Factory.instance.add_lookup_folder(f)} end |
#option_preset ⇒ Object
504 |
# File 'lib/aspera/cli/plugins/config.rb', line 504 def option_preset; 'write-only option'; end |
#option_preset=(value) ⇒ Object
506 507 508 509 510 511 512 513 514 515 |
# File 'lib/aspera/cli/plugins/config.rb', line 506 def option_preset=(value) case value when Hash .add_option_preset(value, 'set') when String .add_option_preset(preset_by_name(value), 'set_by_name') else raise BadArgument, 'Preset definition must be a String for preset name, or Hash for set of values' end end |
#option_use_product ⇒ Object
489 490 491 |
# File 'lib/aspera/cli/plugins/config.rb', line 489 def option_use_product 'write-only option, see value of ascp_path' end |
#option_use_product=(value) ⇒ Object
485 486 487 |
# File 'lib/aspera/cli/plugins/config.rb', line 485 def option_use_product=(value) Ascp::Installation.instance.use_ascp_from_product(value) end |
#periodic_check_newer_gem_version ⇒ Object
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
# File 'lib/aspera/cli/plugins/config.rb', line 375 def periodic_check_newer_gem_version # Get verification period delay_days = .get_option(:version_check_days, mandatory: true).to_i # Check only if not zero day return if delay_days.eql?(0) # Get last date from persistency last_check_array = [] check_date_persist = PersistencyActionOnce.new( manager: persistency, data: last_check_array, id: 'version_last_check' ) # Get persisted date or nil current_date = Date.today last_check_days = (current_date - Date.strptime(last_check_array.first, GEM_CHECK_DATE_FMT)) rescue nil Log.log.debug{"gem check new version: #{delay_days}, #{last_check_days}, #{current_date}, #{last_check_array}"} return if !last_check_days.nil? && last_check_days < delay_days # Generate timestamp last_check_array[0] = current_date.strftime(GEM_CHECK_DATE_FMT) check_date_persist.save # Compare this version and the one on internet check_data = check_gem_version Log.log.warn do "A new version is available: #{check_data[:latest]}. You have #{check_data[:current]}. Upgrade with: gem update #{check_data[:name]}" end if check_data[:need_update] end |
#preset_by_name(config_name, include_path = []) ⇒ Object
Returns copy of the hash from name (also expands possible includes).
471 472 473 474 475 476 477 478 479 480 481 482 483 |
# File 'lib/aspera/cli/plugins/config.rb', line 471 def preset_by_name(config_name, include_path = []) raise Cli::Error, 'loop in include' if include_path.include?(config_name) include_path = include_path.clone # Avoid messing up if there are multiple branches current = @config_presets config_name.split(PRESET_DIG_SEPARATOR).each do |name| Aspera.assert_type(current, Hash, type: Cli::Error){"sub key: #{include_path}"} include_path.push(name) current = current[name] raise Cli::Error, "Unknown config preset: #{include_path}" if current.nil? end current = self.class.deep_clone(current) unless current.is_a?(String) return ExtendedValue.instance.evaluate(current) end |
#read_config_file ⇒ Object
Read config file and validate format
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 |
# File 'lib/aspera/cli/plugins/config.rb', line 522 def read_config_file Log.log.debug{"config file is: #{@option_config_file}".red} # Files search for configuration, by default the one given by user search_files = [@option_config_file] # Find first existing file (or nil) conf_file_to_load = search_files.find{ |f| File.exist?(f)} # If no file found, create default config if conf_file_to_load.nil? Log.log.warn{"No config file found. New configuration file: #{@option_config_file}"} @config_presets = {CONF_PRESET_CONFIG => {CONF_PRESET_VERSION => 'new file'}} # @config_checksum_on_disk is nil else Log.log.debug{"loading #{@option_config_file}"} @config_presets = YAML.load_file(conf_file_to_load) @config_checksum_on_disk = config_checksum end files_to_copy = [] Log.dump(:available_presets, @config_presets, level: :trace1) Aspera.assert_type(@config_presets, Hash){'config file YAML'} # Check there is at least the config section Aspera.assert(@config_presets.key?(CONF_PRESET_CONFIG)){"Cannot find key: #{CONF_PRESET_CONFIG}"} version = @config_presets[CONF_PRESET_CONFIG][CONF_PRESET_VERSION] raise Error, 'No version found in config section.' if version.nil? Log.log.debug{"conf version: #{version}"} # VVV if there are any conversion needed, those happen here. # Fix bug in 4.4 (creating key "true" in "default" preset) @config_presets[CONF_PRESET_DEFAULTS].delete(true) if @config_presets[CONF_PRESET_DEFAULTS].is_a?(Hash) # ^^^ Place new compatibility code before this line # Set version to current @config_presets[CONF_PRESET_CONFIG][CONF_PRESET_VERSION] = Cli::VERSION unless files_to_copy.empty? Log.log.warn('Copying referenced files') files_to_copy.each do |file| FileUtils.cp(file, @main_folder) Log.log.warn{"#{file} -> #{@main_folder}"} end end rescue Psych::SyntaxError => e Log.log.error('YAML error in config file') raise e rescue StandardError => e Log.log.debug{"-> #{e.class.name} : #{e}"} if File.exist?(@option_config_file) # Then there is a problem with that file. new_name = "#{@option_config_file}.pre#{Cli::VERSION}.manual_conversion_needed" File.rename(@option_config_file, new_name) Log.log.warn{"Renamed config file to #{new_name}."} Log.log.warn('Manual Conversion is required. Next time, a new empty file will be created.') end raise Cli::Error, e.to_s end |
#save_config_file_if_needed ⇒ Object
Save current configuration to config file
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 |
# File 'lib/aspera/cli/plugins/config.rb', line 1057 def save_config_file_if_needed raise Error, 'no configuration loaded' if @config_presets.nil? current_checksum = config_checksum return false if @config_checksum_on_disk.eql?(current_checksum) FileUtils.mkdir_p(@main_folder) Environment.restrict_file_access(@main_folder) Log.log.info{"Writing #{@option_config_file}"} formatter.display_status('Saving config file.') Environment.write_file_restricted(@option_config_file, force: true){@config_presets.to_yaml} @config_checksum_on_disk = current_checksum return true end |
#send_email_template(email_template_default: nil, values: {}) ⇒ Object
Send email using ERB template
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 |
# File 'lib/aspera/cli/plugins/config.rb', line 1024 def send_email_template(email_template_default: nil, values: {}) values[:to] ||= .get_option(:notify_to, mandatory: true) notify_template = .get_option(:notify_template, mandatory: email_template_default.nil?) || email_template_default mail_conf = email_settings values[:from_name] ||= mail_conf[:from_name] values[:from_email] ||= mail_conf[:from_email] %i[to from_email].each do |n| Aspera.assert_type(values[n], String){"Missing email parameter: #{n} in config"} end = [mail_conf[:domain]] .push(mail_conf[:username], mail_conf[:password], :login) if mail_conf.key?(:username) && mail_conf.key?(:password) # Create a binding with only variables defined in values template_binding = Environment.empty_binding # Add variables to binding values.each do |k, v| Aspera.assert_type(k, Symbol) template_binding.local_variable_set(k, v) end # Execute template msg_with_headers = ERB.new(notify_template).result(template_binding) Log.dump(:msg_with_headers, msg_with_headers) require 'net/smtp' smtp = Net::SMTP.new(mail_conf[:server], mail_conf[:port]) smtp.enable_starttls if mail_conf[:tls] smtp.enable_tls if mail_conf[:ssl] smtp.start(*) do |smtp_session| smtp_session.(msg_with_headers, values[:from_email], values[:to]) end nil end |
#set_global_default(key, value) ⇒ Object
Set parameter and value in global config Creates one if none already created
460 461 462 |
# File 'lib/aspera/cli/plugins/config.rb', line 460 def set_global_default(key, value) set_preset_key(global_default_preset, key, value) end |
#set_preset_key(preset, param_name, param_value) ⇒ Object
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 |
# File 'lib/aspera/cli/plugins/config.rb', line 436 def set_preset_key(preset, param_name, param_value) Aspera.assert_values(param_name.class, [String, Symbol]){'parameter'} param_name = param_name.to_s selected_preset = @config_presets[preset] if selected_preset.nil? Log.log.debug{"Unknown preset name: #{preset}, initializing"} selected_preset = @config_presets[preset] = {} end Aspera.assert_type(selected_preset, Hash){"#{preset}.#{param_name}"} if selected_preset.key?(param_name) if selected_preset[param_name].eql?(param_value) Log.log.warn{"keeping same value for #{preset}: #{param_name}: #{param_value}"} return end Log.log.warn{"overwriting value: #{selected_preset[param_name]}"} end selected_preset[param_name] = param_value formatter.display_status("Updated: #{preset}: #{param_name} <- #{param_value}") nil end |
#trusted_cert_locations ⇒ Object
Returns only files.
284 285 286 287 288 289 290 291 292 293 294 |
# File 'lib/aspera/cli/plugins/config.rb', line 284 def trusted_cert_locations locations = @certificate_paths if locations.nil? # Compute default locations self.trusted_cert_locations = SpecialValues::DEF locations = @certificate_paths # Restore defaults @certificate_paths = @certificate_store = nil end return locations end |
#trusted_cert_locations=(path_list) ⇒ Object
Add files, folders or default locations to the certificate store
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/aspera/cli/plugins/config.rb', line 244 def trusted_cert_locations=(path_list) path_list = [path_list] unless path_list.is_a?(Array) Aspera.assert_type(path_list, Array){'cert locations'} if @certificate_store.nil? Log.log.debug('Creating SSL Cert store') @certificate_store = OpenSSL::X509::Store.new @certificate_paths = [] end path_list.each do |path| Aspera.assert_type(path, String){'Expecting a String for certificate location'} paths_to_add = [path] Log.log.debug{"Adding cert location: #{path}"} if path.eql?(SpecialValues::DEF) @certificate_store.set_default_paths paths_to_add = [OpenSSL::X509::DEFAULT_CERT_DIR] # JRuby cert file seems not to be PEM paths_to_add.push(OpenSSL::X509::DEFAULT_CERT_FILE) unless defined?(JRUBY_VERSION) paths_to_add.select!{ |f| File.exist?(f)} elsif File.file?(path) @certificate_store.add_file(path) elsif File.directory?(path) @certificate_store.add_path(path) else raise "No such file or folder: #{path}" end paths_to_add.each do |p| pp = [File.realpath(p)] if File.directory?(p) pp = Dir.entries(p) .map{ |e| File.realpath(File.join(p, e))} .select{ |entry| File.file?(entry)} end @certificate_paths.concat(pp) end end @certificate_paths.uniq! end |
#update_http_session(http_session) ⇒ Object
Called every time a new REST HTTP session is opened to set user-provided options
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
# File 'lib/aspera/cli/plugins/config.rb', line 335 def update_http_session(http_session) http_session.set_debug_output(LineLogger.new(:trace2)) if Log.instance.logger.trace2? # Rest.io_http_session(http_session).debug_output = Log.log http_session.verify_mode = SELF_SIGNED_CERT if http_session.use_ssl? && ignore_cert?(http_session.address, http_session.port) http_session.cert_store = @certificate_store if @certificate_store Log.log.debug{"Using cert store #{http_session.cert_store} (#{@certificate_store})"} unless http_session.cert_store.nil? @option_http_options.each do |k, v| method = "#{k}=".to_sym # Check if accessor is a method of Net::HTTP # continue_timeout= read_timeout= write_timeout= if http_session.respond_to?(method) http_session.send(method, v) else Log.log.error{"Unknown HTTP session attribute: #{k}"} end end end |
#vault ⇒ Object
Returns vault, from options or cache.
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 |
# File 'lib/aspera/cli/plugins/config.rb', line 1138 def vault return @vault_instance unless @vault_instance.nil? info = .get_option(:vault).symbolize_keys info[:type] ||= 'file' require 'aspera/keychain/factory' @vault_instance = Keychain::Factory.create( info, Info::CMD_NAME, @main_folder, .get_option(:vault_password) ) end |
#vault_value(name) ⇒ String
Returns value from vault matching <name>.<param>.
1127 1128 1129 1130 1131 1132 1133 1134 1135 |
# File 'lib/aspera/cli/plugins/config.rb', line 1127 def vault_value(name) m = name.split('.') raise BadArgument, 'vault name shall match <name>.<param>' unless m.length.eql?(2) # This raise exception if label not found: info = vault.get(label: m[0]) value = info[m[1].to_sym] raise "no such entry value: #{m[1]}" if value.nil? return value end |