module OpenShift::Runtime::ApplicationContainerExt::Environment

Constants

ALLOWED_OVERRIDES
RESERVED_VARIABLE_NAMES
USER_VARIABLE_MAX_COUNT
USER_VARIABLE_NAME_MAX_SIZE
USER_VARIABLE_VALUE_MAX_SIZE

Public Instance Methods

add_broker_auth(iv,token) click to toggle source

Public: Add broker authorization keys so gear can communicate with

broker.

iv - A String value for the IV file. token - A String value for the token file.

Examples

add_broker_auth('ivvalue', 'tokenvalue')
# => ["/var/lib/openshift/UUID/.auth/iv",
      "/var/lib/openshift/UUID/.auth/token"]

Returns An Array of Strings for the newly created auth files

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 83
def add_broker_auth(iv,token)
  broker_auth_dir=PathUtils.join(@container_dir,'.auth')
  FileUtils.mkdir_p broker_auth_dir
  File.open(PathUtils.join(broker_auth_dir, 'iv'),
            File::WRONLY|File::TRUNC|File::CREAT) do |file|
    file.write iv
  end
  File.open(PathUtils.join(broker_auth_dir, 'token'),
            File::WRONLY|File::TRUNC|File::CREAT) do |file|
    file.write token
  end

  set_rw_permission_R(broker_auth_dir)
  FileUtils.chmod(0750, broker_auth_dir)
  FileUtils.chmod(0640, Dir.glob("#{broker_auth_dir}/*"))
end
add_env_var(key, value, prefix_cloud_name = false, &blk) click to toggle source

Public: Add an environment variable to a given gear.

key - The String value of target environment variable. value - The String value to place inside the environment variable. prefix_cloud_name - The String value to append in front of key.

Examples

add_env_var('mysql-5.3')
# => 36

Returns the Integer value for how many bytes got written or raises on failure.

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 31
def add_env_var(key, value, prefix_cloud_name = false, &blk)
  env_dir = PathUtils.join(@container_dir, '.env/')
  key = "OPENSHIFT_#{key}" if prefix_cloud_name

  filename = PathUtils.join(env_dir, key)
  File.open(filename, File::WRONLY|File::TRUNC|File::CREAT) do |file|
    file.write value.to_s
  end
  set_ro_permission(filename)

  if block_given?
    blk.call(value)
  end
end
add_ssh_key(key_string, key_type=nil, comment=nil) click to toggle source

Public: Add user access by SSH to a gear

Examples

container.add_ssh_key("alongstring", "ssh-rsa", "a users key")

container.add_ssh_key("testuser@EXAMPLE.COM", "krb5-principal")

Returns: nil

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 132
def add_ssh_key(key_string, key_type=nil, comment=nil)
  if key_type == "krb5-principal"
    # create a K5login object and add it

    self.class.notify_observers(:before_add_krb5_principal, 
                                self, key_string)
    K5login.new(self).add_principal(key_string, comment)
    self.class.notify_observers(:after_add_krb5_principal,
                                self, key_string)

  else
    # create an SshAuthorizedKeys file object and add to it.
    self.class.notify_observers(:before_add_ssh_key, self, key_string)
    AuthorizedKeysFile.new(self).add_key(key_string, key_type, comment)
    self.class.notify_observers(:after_add_ssh_key, self, key_string)
  end
end
remove_broker_auth() click to toggle source

Public: Remove broker authentication keys from gear.

Examples

remove_broker_auth
# => nil

Returns nil on Success and false on Failure

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 107
def remove_broker_auth
  broker_auth_dir=PathUtils.join(@container_dir, '.auth')
  FileUtils.rm_rf broker_auth_dir
  File.exists?(broker_auth_dir) ? false : true
end
remove_env_var(key, prefix_cloud_name=false) click to toggle source

Public: Remove an environment variable from a given gear.

key - String name of the environment variable to remove. prefix_cloud_name - String prefix to append to key.

Examples

remove_env_var('OPENSHIFT_MONGODB_DB_URL')
# => nil

Returns an nil on success and false on failure.

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 57
def remove_env_var(key, prefix_cloud_name=false)
  status = false
  [".env", ".env/.uservars"].each do |path|
    env_dir = PathUtils.join(@container_dir,path)
    if prefix_cloud_name
      key = "OPENSHIFT_#{key}"
    end
    env_file_path = PathUtils.join(env_dir, key)
    FileUtils.rm_f env_file_path
    status = status ? true : (File.exists?(env_file_path) ? false : true)
  end
  status
end
remove_ssh_key(key_string, key_type=nil, comment=nil) click to toggle source

Public: remove user access by SSH to a gear

Examples

container.remove_ssh_key("alongstring", "ssh-rsa", "a users key")

container.remove_ssh_key("testuser@EXAMPLE.COM", "krb5-principal")

Returns: nil

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 159
def remove_ssh_key(key_string, key_type=nil, comment=nil)
  if key_type == "krb5-principal"
    # create a K5login object and add it

    self.class.notify_observers(:before_remove_krb5_principal, 
                                self, key_string)
    K5login.new(self).remove_principal(key_string, comment)
    self.class.notify_observers(:after_remove_krb5_principal,
                                self, key_string)

  else
    # create an SshAuthorizedKeys file object and add to it.
    self.class.notify_observers(:before_remove_ssh_key, 
                                self, 
                                key_string)
    AuthorizedKeysFile.new(self).remove_key(key_string, key_type, comment)
    self.class.notify_observers(:after_remove_ssh_key, self, key_string)
  end
end
replace_ssh_keys(ssh_keys) click to toggle source

Public: replace all user access by SSH to a gear

Examples:

Replace all of the existing keys with one SSH and one Kerberos key

a = [{'key' => 'ansshkeystring',

  'type' => 'ssh-rsa', 
  'comment' => "app-user-name" },
 {'key' => 'testuser@EXAMPLE.COM',
  'type' => 'krb5-principal',
  'comment' => 'app-user-name2"}
]

container.replace_ssh_keys(a)

Returns: nil

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 196
def replace_ssh_keys(ssh_keys)

  raise Exception.new('The provided ssh keys do not have the required attributes') unless validate_ssh_keys(ssh_keys)

  # sort the keys into 
  authorized_keys = ssh_keys.select {|k| k['type'] != 'krb5-principal'}
  krb5_principals = ssh_keys.select {|k| k['type'] == 'krb5-principal'}

  self.class.notify_observers(:before_replace_ssh_keys, self) 
  AuthorizedKeysFile.new(self).replace_keys(authorized_keys) if authorized_keys.count > 0
  K5login.new(self).replace_principals(krb5_principals) if krb5_principals.count > 0
  self.class.notify_observers(:after_replace_ssh_keys, self)
  
end
user_var_add(variables, gears = []) click to toggle source

Add user environment variable(s)

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 227
def user_var_add(variables, gears = [])
  directory = PathUtils.join(@container_dir, '.env', 'user_vars')
  FileUtils.mkpath(directory) unless File.directory?(directory)

  if (Dir.entries(directory).size - 2 + variables.size) > USER_VARIABLE_MAX_COUNT
    return 127, "CLIENT_ERROR: User Variables maximum of #{USER_VARIABLE_MAX_COUNT} exceeded"
  end

  variables.each_pair do |name, value|
    path = PathUtils.join(@container_dir, '.env', name)

    if !ALLOWED_OVERRIDES.include?(name) && (File.exists?(path) ||
        name =~ /\AOPENSHIFT_.*_IDENT\Z/ ||
        RESERVED_VARIABLE_NAMES.include?(name))
      return 127, "CLIENT_ERROR: #{name} cannot be overridden"
    end

    if name.to_s.length > USER_VARIABLE_NAME_MAX_SIZE
      return 127, "CLIENT_ERROR: name '#{name}' exceeds maximum size of #{USER_VARIABLE_NAME_MAX_SIZE}b"
    end
    if value.to_s.length > USER_VARIABLE_VALUE_MAX_SIZE
      return 127, "CLIENT_ERROR: '#{name}' value exceeds maximum size of #{USER_VARIABLE_VALUE_MAX_SIZE}b"
    end
  end

  variables.each_pair do |name, value|
    path = PathUtils.join(directory, name)
    File.open(path, 'w', 0440) do |f|
      f.write(value)
    end
    set_ro_permission(path)
  end

  return user_var_push(gears, true) unless gears.empty?
  return 0, ''
end
user_var_list(variables = []) click to toggle source

Retrieve user environment variable(s)

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 335
def user_var_list(variables = [])
  directory = PathUtils.join(@container_dir, '.env', 'user_vars')
  return {} unless File.directory?(directory)

  env = ::OpenShift::Runtime::Utils::Environ::load(directory)
  return env if !variables || variables.empty?

  variables.each_with_object({}) do |name, memo|
    memo[name] = env[name]
  end
end
user_var_push(gears, env_add=false) click to toggle source

update user environment variable(s) on other gears

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 277
def user_var_push(gears, env_add=false)
  output, gear_dns, threads = '', '', {}
  target  = PathUtils.join('.env', 'user_vars').freeze
  source  = PathUtils.join(@container_dir, target).freeze
  return 0, '' unless File.directory?(source)
  return 0, '' if env_add and (Dir.entries(source) - %w{. ..}).empty?

  begin
    gears.each do |gear|
      logger.debug("Updating #{gear} from #{source}")
      ssh_command ="ssh -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=#{@container_dir}/.openshift_ssh/known_hosts -F #{@container_dir}/.openshift_ssh/config -i #{@container_dir}/.openshift_ssh/id_rsa"
      threads[gear] = Thread.new(gear) do |fqdn|
        gear_dns = fqdn
        retries  = 2
        begin
          command = "/usr/bin/rsync -rp0 --delete -e '#{ssh_command}' #{source}/ #{fqdn}:#{target}"
          env = OpenShift::Runtime::Utils::Environ.for_gear(@container_dir)
          ::OpenShift::Runtime::Utils::oo_spawn(command, expected_exitstatus: 0, uid: @uid, env: env)
        rescue Exception => e
          NodeLogger.logger.debug { "Push #{retries} #{source} exception #{e.message}" }
          Thread.current[:exception] = e
          retries                    -= 1
          sleep(0.5)
          retry if 0 < retries
        end
      end
    end
  rescue Exception => e
    logger.warn("Failed to update #{gear_dns} from #{@container_dir}/#{source}. #{e.message}")
    return 127, "CLIENT_ERROR: #{e.message}"
  ensure
    loop do
      threads.each_pair do |id, thread|
        case thread.status
          when false
            thread.join
            if thread[:exception]
              if thread[:exception].is_a?(::OpenShift::Runtime::Utils::ShellExecutionException)
                output << "CLIENT_ERROR: Sync for #{id} user variables failed.\n"
                output << thread[:exception].stderr.split("\n").map { |l| "CLIENT_ERROR: #{l}" }.join("\n")
              else
                output << "CLIENT_ERROR: Sync for #{id} user variables failed #{thread[:exception].message}\n"
              end
            end
            threads.delete(id)
          when nil
            threads.delete(id)
        end
      end
      sleep(0.5)
      break if threads.empty?
    end
  end

  return output.empty? ? 0 : 127, output
end
user_var_remove(variables, gears = []) click to toggle source

Remove user environment variable(s)

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 265
def user_var_remove(variables, gears = [])
  directory = PathUtils.join(@container_dir, '.env', 'user_vars')
  variables.each do |name|
    path = PathUtils.join(directory, name)
    FileUtils.rm_f(path)
  end

  return user_var_push(gears) unless gears.empty?
  return 0, ''
end
validate_ssh_keys(ssh_keys) click to toggle source

validate the ssh keys to check for the required attributes

# File lib/openshift-origin-node/model/application_container_ext/environment.rb, line 212
def validate_ssh_keys(ssh_keys)
  ssh_keys.each do |key|
    begin
      if key['key'].nil? or key['type'].nil? and key['comment'].nil?
        return false
      end
    rescue Exception => ex
      return false
    end
  end
  return true
end