Sha256: bed6f386d49e600018885f79848cd0b8a6f0b102761be2e934d114492d311e4b

Contents?: true

Size: 1.98 KB

Versions: 9

Compression:

Stored size: 1.98 KB

Contents

require 'excon'
require 'json'

module Kontena
  module Machine
    module Upcloud
      module UpcloudCommon

        attr_reader :username
        attr_reader :password
        
        def client
          @client ||= Excon.new(
            'https://api.upcloud.com',
            omit_default_port: true,
            user: username,
            password: password,
            headers: { "Accept-Encoding" => 'application/json' }
          )
        end

        def find_template(name)
          get('storage/template')[:storages][:storage].find{|s| s[:title].downcase.start_with?(name.downcase)}
        end
        
        def find_plan(name)
          get('plan')[:plans][:plan].find{|s| s[:name].downcase.eql?(name.downcase)}
        end

        def zone_exist?(name)
          get('zone')[:zones][:zone].map{|p| p[:id]}.include?(name)
        end

        def get_server(id)
          get("server/#{id}").fetch(:server, nil)
        end

        def api_access?
          response = get('account')
          response.kind_of?(Hash) && response.has_key?(:account)
        rescue
          false
        end

        def abort_unless_api_access
          unless api_access?
            abort('Upcloud API authentication failed. Check that API access is enabled for the user.')
          end
        end

        [:get, :post, :delete].each do |http_method|
          define_method http_method do |path, opts={}|
            response = client.send(
              http_method, 
              opts.merge(
                path: File.join('/1.2', path),
                headers: {
                  'Content-Type': 'application/json'
                }
              )
            )
            if response.body && response.body.start_with?('{')
              JSON.parse(response.body, symbolize_names: true)
            elsif response.status.to_s.start_with?('2')
              {success: true}
            else
              {error: response.status}
            end
          end
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 2 rubygems

Version Path
kontena-plugin-upcloud-0.2.0.pre1 lib/kontena/machine/upcloud/upcloud_common.rb
kontena-plugin-upcloud-0.1.0 lib/kontena/machine/upcloud/upcloud_common.rb
kontena-cli-0.14.7 lib/kontena/machine/upcloud/upcloud_common.rb
kontena-cli-0.14.6 lib/kontena/machine/upcloud/upcloud_common.rb
kontena-cli-0.14.5 lib/kontena/machine/upcloud/upcloud_common.rb
kontena-cli-0.14.4 lib/kontena/machine/upcloud/upcloud_common.rb
kontena-cli-0.14.3 lib/kontena/machine/upcloud/upcloud_common.rb
kontena-cli-0.14.2 lib/kontena/machine/upcloud/upcloud_common.rb
kontena-cli-0.14.1 lib/kontena/machine/upcloud/upcloud_common.rb